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,320 @@
1
+ """CUDA source of the G1 engine's kinematics outputs and their VJP: body poses, COM velocities and subtree COMs of a
2
+ state (qpos, qvel) with the per-world torso COM offset com, as MuJoCo MJX's mjx.kinematics + smooth.com_pos +
3
+ smooth.com_vel (mujoco 3.17.0, mujoco/mjx/_src/smooth.py) compute them (qpos, xpos, xquat, cvel, subtree_com), and the
4
+ VJP of that map. nablaengine.jax_ffi runs it after the step's last
5
+ substep (step(..., kinematics=True): the output state's) and on its own (jax_ffi.kinematics)."""
6
+
7
+ import mujoco
8
+ import numpy as np
9
+
10
+ KIN_WPB = 4
11
+ OUTPUTS = ("qpos_n", "xpos", "xquat", "cvel", "subtree_com")
12
+
13
+
14
+ def shapes(m, B):
15
+ """{output: shape} of one call for batch size B."""
16
+ nb = m.nbody
17
+ return dict(qpos_n=(B, m.nq), xpos=(B, nb, 3), xquat=(B, nb, 4), cvel=(B, nb, 6), subtree_com=(B, nb, 3))
18
+
19
+
20
+ def check_model(m):
21
+ """Assert what the kernels assume of the model (beyond source.constants: free root body 1, hinges at the body
22
+ origins): MJX's world body at the origin, massless, with body 1 its only child; one hinge per body after the root,
23
+ with qpos0 = 0 (MJX's angle is qpos - qpos0, the engine's qpos); no mocap bodies; every subtree mass >= mjMINVAL
24
+ (MJX's fallback to xipos unused); one kinematic tree (body_rootid 1 for b >= 1). The capability checker's
25
+ kinematics scope (nablaengine.model.capability: H1, H6, H7, H8, H25, H31) runs first and raises its UnsupportedModel
26
+ (an AssertionError) with the codes; the asserts below are the same conditions. A jointless (welded) body has
27
+ body_jntadr -1 (which would index the last joint): body_jntnum is checked first."""
28
+ from nablaengine.model import capability
29
+ capability.require(m, None, None, "kinematics", "kinematics outputs")
30
+ assert m.nbody <= 64 and m.nmocap == 0
31
+ assert not np.any(m.body_pos[0]) and np.array_equal(m.body_quat[0], [1.0, 0.0, 0.0, 0.0]) and m.body_mass[0] == 0
32
+ assert [b for b in range(1, m.nbody) if m.body_parentid[b] == 0] == [1]
33
+ assert all(int(m.body_rootid[b]) == 1 for b in range(1, m.nbody)) and int(m.body_rootid[0]) == 0
34
+ for b in range(2, m.nbody):
35
+ assert m.body_jntnum[b] == 1 and m.body_jntadr[b] >= 0, f"body {b}: one joint (a jointless body has none)"
36
+ j = m.body_jntadr[b]
37
+ assert m.jnt_type[j] == mujoco.mjtJoint.mjJNT_HINGE and m.qpos0[m.jnt_qposadr[j]] == 0.0
38
+ sub = np.array(m.body_mass, np.float64)
39
+ for b in range(m.nbody - 1, 0, -1):
40
+ sub[m.body_parentid[b]] += sub[b]
41
+ assert sub.min() >= mujoco.mjMINVAL, "a subtree mass below mjMINVAL (MJX would use xipos)"
42
+
43
+
44
+ KIN_DEVICE = r"""
45
+ // ---- kinematics outputs (nablaengine.g1_engine.kinematics; MJX kinematics + com_pos + com_vel) and their VJP.
46
+ // One warp per world (lane b = body b, the tree one depth level at a time, as substep_pre), KIN_WPB worlds per block,
47
+ // each world's state in its own slice of static shared memory (kept small: the kernels are latency bound, so the
48
+ // worlds per SM count). Inputs and outputs whole per world, lane-strided (coalesced); k_kin_vjp reads its cotangents
49
+ // by body rows (lane b: body b's few floats; the warp's loads cover one contiguous segment, cached)
50
+ #ifndef KIN_WPB
51
+ #define KIN_WPB 4
52
+ #endif
53
+ #define KIN_QOUT (NB * 3) // floats per world of xpos and subtree_com; xquat NB * 4, cvel NB * 6, qpos_n NQ
54
+
55
+ struct KinF { // the forward's per-world state (2.4 KB)
56
+ float Q[NB][4], X[NB][3]; // fwd_body's poses
57
+ union {
58
+ struct { float W[NB][3], V[NB][3]; }; // fwd_body's twists (W angular, V the velocity of the body origin)
59
+ float cv[NB][6]; // then cvel (staged for the copy-out)
60
+ };
61
+ float C[NB][3], Mt[NB]; // the subtree sums of m xipos, then the subtree COMs; the subtree masses
62
+ float qpos[NQ], qvel[NV], com[3];
63
+ };
64
+ struct KinB { // the VJP's per-world state (4.5 KB): the forward's, the sweeps' cotangents, the gradients
65
+ float Q[NB][4], X[NB][3], W[NB][3], V[NB][3], Mt[NB];
66
+ union {
67
+ float C[NB][3]; // the forward's subtree sums / COMs (C_1 is kept in registers before G overwrites them)
68
+ float G[NB][3]; // sum over the path root .. b of the subtree sums' cotangents (the down sweep)
69
+ };
70
+ float qpos[NQ], qvel[NV], com[3];
71
+ float bW[NB][3], bV[NB][3], F[NB][3], N[NB][3], rb[NB][3]; // twists' cotangents, pose sweep F_b, N_b, r bar_b
72
+ float gq[NQ], gv[NV];
73
+ };
74
+
75
+ __device__ __forceinline__ void kin_copy(float* dst, const float* src, int n, int lane) {
76
+ for (int i = lane; i < n; i += 32) dst[i] = src[i];
77
+ }
78
+
79
+ // body b's children (at most 3: source.constants) into registers before a sweep: their count
80
+ __device__ __forceinline__ int kin_children(int b, int* ch) {
81
+ const int n = b >= 1 && b < NB ? c_nchild[b] : 0;
82
+ #pragma unroll
83
+ for (int i = 0; i < 3; i++) ch[i] = i < n ? c_child[3 * b + i] : 0;
84
+ return n;
85
+ }
86
+
87
+ // one world's state from (qpos, qvel, com) already in s: poses and twists by the forward's fwd_body steps (the root:
88
+ // fwd_body itself; a hinge body: fwd_hinge_rot for every body before the sweep, off the levels' chain, then
89
+ // fwd_hinge_pos and fwd_hinge_rest at its level: the bits of fwd_body, whose acceleration channel is dead code here),
90
+ // then the subtree COMs C and masses Mt (MJX com_pos: leaf to root, own m xipos plus the children's sums in child
91
+ // order; C_0 = C_1, body 0 being massless with body 1 its only child, at depth 1)
92
+ template <class S>
93
+ __device__ __forceinline__ void kin_state(S& s, int lane) {
94
+ const int b = lane, d = b < NB ? c_depth[b] : -1, p = b < NB ? c_parent[b] : 0;
95
+ float qb[4] = {1.f, 0.f, 0.f, 0.f}, pb[3] = {0.f, 0.f, 0.f}, ax[3] = {0.f, 0.f, 1.f}, ha[4] = {1.f, 0.f, 0.f, 0.f};
96
+ float qd = 0.f;
97
+ if (b >= 2 && b < NB) {
98
+ for (int k = 0; k < 4; k++) qb[k] = c_quat[4 * b + k];
99
+ for (int k = 0; k < 3; k++) { pb[k] = c_pos[3 * b + k]; ax[k] = c_axis[3 * b + k]; }
100
+ qd = s.qvel[c_dadr[b]];
101
+ fwd_hinge_rot(s.qpos[c_qadr[b]], ax, ha);
102
+ }
103
+ if (lane == 0) {
104
+ s.Q[0][0] = 1.f; s.Q[0][1] = s.Q[0][2] = s.Q[0][3] = 0.f;
105
+ for (int k = 0; k < 3; k++) s.X[0][k] = s.W[0][k] = s.V[0][k] = 0.f;
106
+ }
107
+ __syncwarp();
108
+ for (int L = 1; L <= MAXD; L++) {
109
+ if (d == L) {
110
+ float Qp[4], Xp[3], Wp[3], Vp[3], Qb[4], Xb[3], Wb[3], Vb[3], ALb[3], Ab[3], q0[4];
111
+ const float z3[3] = {0.f, 0.f, 0.f};
112
+ for (int k = 0; k < 4; k++) Qp[k] = s.Q[p][k];
113
+ for (int k = 0; k < 3; k++) { Xp[k] = s.X[p][k]; Wp[k] = s.W[p][k]; Vp[k] = s.V[p][k]; }
114
+ if (L == 1) { // body 1, the free root
115
+ fwd_body(1, Qp, Xp, Wp, Vp, z3, z3, s.qpos, s.qvel, s.qvel, Qb, Xb, Wb, Vb, ALb, Ab);
116
+ } else {
117
+ fwd_hinge_pos(Qp, Xp, qb, pb, q0, Xb);
118
+ fwd_hinge_rest(q0, ha, ax, qd, 0.f, Xp, Wp, Vp, z3, z3, Qb, Xb, Wb, Vb, ALb, Ab);
119
+ }
120
+ for (int k = 0; k < 4; k++) s.Q[b][k] = Qb[k];
121
+ for (int k = 0; k < 3; k++) { s.X[b][k] = Xb[k]; s.W[b][k] = Wb[k]; s.V[b][k] = Vb[k]; }
122
+ }
123
+ __syncwarp();
124
+ }
125
+ float S3[3] = {0.f, 0.f, 0.f}, Mb = 0.f;
126
+ int ch[3];
127
+ const int nch = kin_children(b, ch);
128
+ if (b >= 1 && b < NB) {
129
+ float ip[3], c[3];
130
+ body_ipos(b, s.com, ip);
131
+ qrot(s.Q[b], ip, c);
132
+ Mb = c_mass[b];
133
+ for (int k = 0; k < 3; k++) { S3[k] = (s.X[b][k] + c[k]) * Mb; s.C[b][k] = S3[k]; }
134
+ s.Mt[b] = Mb;
135
+ }
136
+ __syncwarp();
137
+ for (int L = MAXD - 1; L >= 1; L--) {
138
+ if (d == L && nch > 0) {
139
+ #pragma unroll
140
+ for (int i = 0; i < 3; i++)
141
+ if (i < nch) {
142
+ for (int k = 0; k < 3; k++) S3[k] += s.C[ch[i]][k];
143
+ Mb += s.Mt[ch[i]];
144
+ }
145
+ for (int k = 0; k < 3; k++) s.C[b][k] = S3[k];
146
+ s.Mt[b] = Mb;
147
+ }
148
+ __syncwarp();
149
+ }
150
+ if (b >= 1 && b < NB)
151
+ for (int k = 0; k < 3; k++) s.C[b][k] = S3[k] / Mb;
152
+ __syncwarp();
153
+ if (lane == 0) {
154
+ for (int k = 0; k < 3; k++) s.C[0][k] = s.C[1][k];
155
+ s.Mt[0] = s.Mt[1];
156
+ }
157
+ __syncwarp();
158
+ }
159
+
160
+ template <class S>
161
+ __device__ __forceinline__ void kin_load(S& s, int w, const float* qpos, const float* qvel, const float* com,
162
+ int lane) {
163
+ kin_copy(s.qpos, qpos + (size_t)w * NQ, NQ, lane);
164
+ kin_copy(s.qvel, qvel + (size_t)w * NV, NV, lane);
165
+ if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane]; // (fixtures: not in the kinematics outputs)
166
+ __syncwarp();
167
+ }
168
+
169
+ // the kinematics outputs of nw worlds: qn (nw, NQ), xpos (nw, NB, 3), xquat (nw, NB, 4), cvel (nw, NB, 6), sc (nw, NB,
170
+ // 3); block of KIN_WPB warps, warp = world
171
+ __global__ void __launch_bounds__(32 * KIN_WPB) k_kin(int nw, const float* qpos, const float* qvel, const float* com,
172
+ float* qn, float* xpos, float* xquat, float* cvel, float* sc) {
173
+ __shared__ KinF sm[KIN_WPB];
174
+ const int lane = threadIdx.x & 31, w = blockIdx.x * KIN_WPB + (threadIdx.x >> 5);
175
+ if (w >= nw) return; // a whole warp
176
+ KinF& s = sm[threadIdx.x >> 5];
177
+ kin_load(s, w, qpos, qvel, com, lane);
178
+ kin_state(s, lane);
179
+ const int b = lane;
180
+ float o[6] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; // cvel_b = [W_b; V_b + W_b x (C_1 - X_b)], body 0: zeros
181
+ if (b >= 1 && b < NB) {
182
+ float r[3], u[3];
183
+ for (int k = 0; k < 3; k++) r[k] = s.C[1][k] - s.X[b][k];
184
+ cross(s.W[b], r, u);
185
+ for (int k = 0; k < 3; k++) { o[k] = s.W[b][k]; o[3 + k] = s.V[b][k] + u[k]; }
186
+ }
187
+ __syncwarp(); // (cv aliases W, V)
188
+ if (b < NB)
189
+ for (int k = 0; k < 6; k++) s.cv[b][k] = o[k];
190
+ __syncwarp();
191
+ float* oq = qn + (size_t)w * NQ;
192
+ for (int i = lane; i < NQ; i += 32) oq[i] = i >= 3 && i < 7 ? s.Q[1][i - 3] : s.qpos[i];
193
+ kin_copy(xpos + (size_t)w * KIN_QOUT, &s.X[0][0], KIN_QOUT, lane);
194
+ kin_copy(xquat + (size_t)w * NB * 4, &s.Q[0][0], NB * 4, lane);
195
+ kin_copy(cvel + (size_t)w * NB * 6, &s.cv[0][0], NB * 6, lane);
196
+ kin_copy(sc + (size_t)w * KIN_QOUT, &s.C[0][0], KIN_QOUT, lane);
197
+ }
198
+
199
+ // the VJP: cotangents of k_kin's outputs (gqn, gxpos, gxquat, gcvel, gsc, same layouts) -> gq (nw, NQ), gv (nw, NV)
200
+ // of (qpos, qvel); gq_in / gv_in (may be null: zero) are added last (the step's combined backward: its outputs'
201
+ // direct cotangents)
202
+ __global__ void __launch_bounds__(32 * KIN_WPB) k_kin_vjp(int nw, const float* qpos, const float* qvel,
203
+ const float* com, const float* gqn, const float* gxpos,
204
+ const float* gxquat, const float* gcvel, const float* gsc,
205
+ const float* gq_in, const float* gv_in, float* gq,
206
+ float* gv) {
207
+ __shared__ KinB sm[KIN_WPB];
208
+ const int lane = threadIdx.x & 31, w = blockIdx.x * KIN_WPB + (threadIdx.x >> 5);
209
+ if (w >= nw) return;
210
+ KinB& s = sm[threadIdx.x >> 5];
211
+ kin_load(s, w, qpos, qvel, com, lane);
212
+ kin_state(s, lane);
213
+ const int b = lane, d = b < NB ? c_depth[b] : -1, p = b < NB ? c_parent[b] : 0;
214
+ const bool body = b >= 1 && b < NB;
215
+ const size_t row = (size_t)w * NB + (body ? b : 0); // this lane's body row of the cotangents
216
+ const float C1[3] = {s.C[1][0], s.C[1][1], s.C[1][2]};
217
+ // cvel_b = [W_b; V_b + W_b x r_b], r_b = C_1 - X_b: W bar, V bar; r bar = nu bar x W_b -> C_1 bar, -X_b bar.
218
+ // xquat (b >= 2; the root's goes into its quaternion directly): tau bar = 1/2 vec(g_Q Q*)
219
+ float fb[3] = {0.f, 0.f, 0.f}, tb[3] = {0.f, 0.f, 0.f}, gr[3] = {0.f, 0.f, 0.f}, gS[3] = {0.f, 0.f, 0.f};
220
+ if (body) {
221
+ float wb[3], vb[3], r[3], t[3];
222
+ for (int k = 0; k < 3; k++) { wb[k] = gcvel[row * 6 + k]; vb[k] = gcvel[row * 6 + 3 + k]; r[k] = C1[k] - s.X[b][k]; }
223
+ cross(r, vb, t);
224
+ for (int k = 0; k < 3; k++) { s.bW[b][k] = wb[k] + t[k]; s.bV[b][k] = vb[k]; }
225
+ cross(vb, s.W[b], gr);
226
+ for (int k = 0; k < 3; k++) { fb[k] = gxpos[row * 3 + k] - gr[k]; gS[k] = gsc[row * 3 + k]; }
227
+ if (b >= 2) {
228
+ const float* q = s.Q[b]; // vec(g q*)
229
+ const float g0 = gxquat[row * 4], g1 = gxquat[row * 4 + 1], g2 = gxquat[row * 4 + 2], g3 = gxquat[row * 4 + 3];
230
+ tb[0] = 0.5f * (-g0 * q[1] + g1 * q[0] - g2 * q[3] + g3 * q[2]);
231
+ tb[1] = 0.5f * (-g0 * q[2] + g1 * q[3] + g2 * q[0] - g3 * q[1]);
232
+ tb[2] = 0.5f * (-g0 * q[3] - g1 * q[2] + g2 * q[1] + g3 * q[0]);
233
+ }
234
+ }
235
+ float gc1[3]; // C_1 bar from the cvel reference point (every lane: the same sum)
236
+ for (int k = 0; k < 3; k++) gc1[k] = warp_sum(gr[k]);
237
+ // subtree_com: C_b = S_b / M_b (C_0 = C_1): S bar_b = C bar_b / M_b; xipos_j bar = m_j sum over the path root .. j
238
+ if (body)
239
+ for (int k = 0; k < 3; k++)
240
+ gS[k] = (b == 1 ? gS[k] + gsc[(size_t)w * NB * 3 + k] + gc1[k] : gS[k]) / s.Mt[b];
241
+ __syncwarp(); // (every lane has read C_1: G overwrites C)
242
+ for (int L = 1; L <= MAXD; L++) {
243
+ if (d == L)
244
+ for (int k = 0; k < 3; k++) { gS[k] += b >= 2 ? s.G[p][k] : 0.f; s.G[b][k] = gS[k]; }
245
+ __syncwarp();
246
+ }
247
+ if (body) { // xipos_b = X_b + c_b, c_b = R_b ipos_b: f bar += g, tau bar += c x g
248
+ float ip[3], c[3], g[3], t[3];
249
+ body_ipos(b, s.com, ip);
250
+ qrot(s.Q[b], ip, c);
251
+ const float m = c_mass[b];
252
+ for (int k = 0; k < 3; k++) { g[k] = m * gS[k]; fb[k] += g[k]; }
253
+ cross(c, g, t);
254
+ for (int k = 0; k < 3; k++) { s.F[b][k] = fb[k]; s.N[b][k] = tb[k] + t[k]; }
255
+ }
256
+ __syncwarp();
257
+ // leaf to root: the twists' recursion reversed with the pose sweep (adjoint.py adj_tree_up's pattern: a parent pulls
258
+ // its children's finished cotangents, deterministic). Off the levels' chain, before: the children, the hinge axis z_b
259
+ // = R_b axis_b (W_b = W_p + z qd), its rate and addresses
260
+ int ch[3];
261
+ const int nch = kin_children(b, ch), iv = b >= 2 && b < NB ? c_dadr[b] : 0, iq = b >= 2 && b < NB ? c_qadr[b] : 0;
262
+ float z[3] = {0.f, 0.f, 0.f};
263
+ if (b >= 2 && b < NB) qrot(s.Q[b], c_axis + 3 * b, z);
264
+ const float qd = s.qvel[iv];
265
+ for (int L = MAXD; L >= 1; L--) {
266
+ if (d == L) {
267
+ float bW[3], bV[3], F[3], N[3], t[3], u[3];
268
+ for (int k = 0; k < 3; k++) { bW[k] = s.bW[b][k]; bV[k] = s.bV[b][k]; F[k] = s.F[b][k]; N[k] = s.N[b][k]; }
269
+ #pragma unroll
270
+ for (int i = 0; i < 3; i++) {
271
+ if (i >= nch) break;
272
+ const int c = ch[i];
273
+ float r[3];
274
+ for (int k = 0; k < 3; k++) r[k] = s.X[c][k] - s.X[b][k];
275
+ cross(r, s.bV[c], t); // V_c = V_b + W_b x r_c
276
+ cross(r, s.F[c], u);
277
+ for (int k = 0; k < 3; k++) {
278
+ bW[k] += s.bW[c][k] + t[k]; bV[k] += s.bV[c][k];
279
+ F[k] += s.F[c][k] - s.rb[c][k]; N[k] += s.N[c][k] + u[k];
280
+ }
281
+ }
282
+ if (b >= 2) {
283
+ const int i = iv;
284
+ float rb[3];
285
+ s.gv[i] = dot3(z, bW);
286
+ for (int k = 0; k < 3; k++) u[k] = qd * bW[k];
287
+ cross(z, u, t); // z = R_b axis rotates with the body
288
+ cross(bV, s.W[p], rb); // V_b = V_p + W_p x r_b
289
+ for (int k = 0; k < 3; k++) { N[k] += t[k]; F[k] += rb[k]; s.rb[b][k] = rb[k]; }
290
+ s.gq[iq] = dot3(z, N);
291
+ } else { // the root: V_1 = qvel[0:3], W_1 = R_1 qvel[3:6]; X_1 = qpos[0:3], Q_1 = normalize(qpos[3:7])
292
+ float l[3];
293
+ qrot_inv(s.Q[1], bW, l);
294
+ for (int k = 0; k < 3; k++) { s.gv[k] = bV[k]; s.gv[3 + k] = l[k]; s.gq[k] = F[k]; }
295
+ cross(s.W[1], bW, t);
296
+ for (int k = 0; k < 3; k++) N[k] += t[k];
297
+ const float n0[4] = {0.f, N[0], N[1], N[2]}, *u4 = s.Q[1], *q = s.qpos + 3;
298
+ float a[4];
299
+ qmul(n0, u4, a); // dL/dQ_1 (tangential) = 2 [0; N] Q_1, plus the direct cotangents of Q_1
300
+ for (int k = 0; k < 4; k++) a[k] = 2.f * a[k] + gxquat[row * 4 + k] + gqn[(size_t)w * NQ + 3 + k];
301
+ const float nq = sqrtf(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);
302
+ const float ua = u4[0] * a[0] + u4[1] * a[1] + u4[2] * a[2] + u4[3] * a[3];
303
+ for (int k = 0; k < 4; k++) s.gq[3 + k] = (a[k] - u4[k] * ua) / nq; // normalize's VJP
304
+ }
305
+ for (int k = 0; k < 3; k++) { s.bW[b][k] = bW[k]; s.bV[b][k] = bV[k]; s.F[b][k] = F[k]; s.N[b][k] = N[k]; }
306
+ }
307
+ __syncwarp();
308
+ }
309
+ const float* cq = gqn + (size_t)w * NQ;
310
+ float* oq = gq + (size_t)w * NQ;
311
+ float* ov = gv + (size_t)w * NV;
312
+ for (int i = lane; i < NQ; i += 32) {
313
+ const float g = i >= 3 && i < 7 ? s.gq[i] : s.gq[i] + cq[i]; // qpos_n passes the other entries through
314
+ oq[i] = gq_in ? gq_in[(size_t)w * NQ + i] + g : g;
315
+ }
316
+ for (int i = lane; i < NV; i += 32) ov[i] = gv_in ? gv_in[(size_t)w * NV + i] + s.gv[i] : s.gv[i];
317
+ }
318
+
319
+ static inline unsigned kin_grid(int nw) { return (unsigned)((nw + KIN_WPB - 1) / KIN_WPB); }
320
+ """
@@ -0,0 +1,167 @@
1
+ """Contact margins on the forest engine (MuJoCo's pair margin / gap)."""
2
+ import re
3
+
4
+ import mujoco
5
+ import numpy as np
6
+
7
+ G = mujoco.mjtGeom
8
+ SUPPORTED = {tuple(sorted((int(a), int(b)))) for a, b in (
9
+ (G.mjGEOM_PLANE, G.mjGEOM_SPHERE), (G.mjGEOM_PLANE, G.mjGEOM_CAPSULE), (G.mjGEOM_PLANE, G.mjGEOM_ELLIPSOID),
10
+ (G.mjGEOM_PLANE, G.mjGEOM_CYLINDER), (G.mjGEOM_PLANE, G.mjGEOM_BOX), (G.mjGEOM_SPHERE, G.mjGEOM_SPHERE),
11
+ (G.mjGEOM_SPHERE, G.mjGEOM_CAPSULE), (G.mjGEOM_CAPSULE, G.mjGEOM_CAPSULE), (G.mjGEOM_SPHERE, G.mjGEOM_CYLINDER))}
12
+ CONVEX = {tuple(sorted((int(a), int(b)))) for a, b in (
13
+ (G.mjGEOM_SPHERE, G.mjGEOM_BOX), (G.mjGEOM_CAPSULE, G.mjGEOM_BOX), (G.mjGEOM_BOX, G.mjGEOM_BOX),
14
+ (G.mjGEOM_PLANE, G.mjGEOM_MESH), (G.mjGEOM_CAPSULE, G.mjGEOM_CYLINDER), (G.mjGEOM_CYLINDER, G.mjGEOM_CYLINDER),
15
+ (G.mjGEOM_CYLINDER, G.mjGEOM_BOX), (G.mjGEOM_SPHERE, G.mjGEOM_ELLIPSOID), (G.mjGEOM_CAPSULE, G.mjGEOM_ELLIPSOID),
16
+ (G.mjGEOM_ELLIPSOID, G.mjGEOM_ELLIPSOID), (G.mjGEOM_ELLIPSOID, G.mjGEOM_CYLINDER),
17
+ (G.mjGEOM_ELLIPSOID, G.mjGEOM_BOX))} | {tuple(sorted((int(t), int(G.mjGEOM_MESH)))) for t in (
18
+ G.mjGEOM_SPHERE, G.mjGEOM_CAPSULE, G.mjGEOM_ELLIPSOID, G.mjGEOM_CYLINDER, G.mjGEOM_BOX, G.mjGEOM_MESH)}
19
+
20
+
21
+ def _tname(t):
22
+ return G(int(t)).name[7:].lower()
23
+
24
+
25
+ def pair_types(m, p):
26
+ """Pair p's MuJoCo geom types, sorted."""
27
+ return tuple(sorted((int(m.geom_type[m.pair_geom1[p]]), int(m.geom_type[m.pair_geom2[p]]))))
28
+
29
+
30
+ def supported_pair(m, p):
31
+ """Whether pair p's geom types take a margin on the forest engine (SUPPORTED)."""
32
+ return pair_types(m, p) in SUPPORTED or pair_types(m, p) in CONVEX
33
+
34
+
35
+ def convex_active(m):
36
+ """Whether model m has a convex pair (CONVEX) with a nonzero margin (forest_engine.margin_convex's edits)."""
37
+ return any(float(m.pair_margin[p]) != 0 and pair_types(m, p) in CONVEX for p in range(m.npair))
38
+
39
+
40
+ def supported_types(t1, t2):
41
+ """Whether a pair of MuJoCo geom types takes a margin on the forest engine (the converter's rule)."""
42
+ t = tuple(sorted((int(t1), int(t2))))
43
+ return t in SUPPORTED or t in CONVEX
44
+
45
+
46
+ def active(m):
47
+ """Whether model m has a pair with a nonzero margin (the margin build)."""
48
+ return bool(m.npair) and bool(np.any(np.asarray(m.pair_margin) != 0))
49
+
50
+
51
+ def problems(m):
52
+ """[(pair name, reason)] of the margins the forest engine does not take (empty: none, or all supported). The
53
+ build options that refuse margins are checked by check()."""
54
+ out = []
55
+ for p in range(m.npair):
56
+ mg, gap = float(m.pair_margin[p]), float(m.pair_gap[p])
57
+ name = mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_PAIR, p) or str(p)
58
+ if hasattr(m, "pair_adhesion") and float(m.pair_adhesion[p]) != 0:
59
+ out.append((name, f"adhesion {float(m.pair_adhesion[p])} (the engine has no contact adhesion)"))
60
+ elif mg < 0 or gap < 0:
61
+ out.append((name, f"negative margin / gap ({mg}, {gap})"))
62
+ elif (mg != 0 or gap != 0) and not supported_pair(m, p):
63
+ out.append((name, f"margin {mg} / gap {gap} on a {'-'.join(map(_tname, pair_types(m, p)))} pair (no "
64
+ "margin on this pair type)"))
65
+ from nablaengine.forest_engine import margin_convex
66
+ return out + margin_convex.problems(m)
67
+
68
+
69
+ def check(m, terrain=None, surrogate=False, noslip=False, midphase=False):
70
+ """ValueError where the margins of model m do not fit the forest build (no margins: nothing)."""
71
+ if not active(m) and not problems(m):
72
+ return
73
+ bad = problems(m)
74
+ if bad:
75
+ raise ValueError(f"contact margins the forest engine does not take: {bad[:6]}{' ...' if len(bad) > 6 else ''}")
76
+ from nablaengine.forest_engine import step
77
+ opts = [k for k, v in (("a terrain build", terrain is not None), ("contact_surrogate", surrogate),
78
+ ("noslip (opt.noslip_iterations > 0)", noslip), ("the collision mid-phase", midphase),
79
+ (f"more than {step.GROUP_PAIRS} pairs (the two-level broad phase)",
80
+ m.npair > step.GROUP_PAIRS)) if v]
81
+ if opts:
82
+ raise ValueError(f"contact margins (pair_margin != 0): not with {', '.join(opts)} (forest_engine.margin)")
83
+
84
+
85
+ def constants(m):
86
+ """([c_pmarg as float32, then forest_engine.margin_convex's arrays], their layout entries) for
87
+ adjoint.engine_constants; None without margins."""
88
+ if not active(m):
89
+ return None
90
+ from nablaengine.forest_engine import margin_convex
91
+ arrs, lays = [np.asarray(m.pair_margin, np.float64).astype(np.float32)], [("c_pmarg", "f", int(m.npair), 1)]
92
+ cv = margin_convex.constants(m)
93
+ if cv is not None:
94
+ arrs, lays = arrs + cv[0], lays + cv[1]
95
+ return np.concatenate(arrs), lays
96
+
97
+
98
+ DECL = ("DKC float c_pmarg[NPAIR]; // the pairs' contact margins (forest_engine.margin)\n"
99
+ "#define PMARGIN(pr) (c_pmarg[pr])\n")
100
+ _DECL_AT = "DKC int c_gbody["
101
+ _ADD_HEAD = ("__device__ __forceinline__ bool add_contact(S& s, int pair, int slot, float dist, const float* pos,\n"
102
+ " const float* frame) {\n")
103
+ _ADD_OLD = " s.con_dist[c] = dist;\n"
104
+ _ADD_NEW = " s.con_dist[c] = RSUB(dist, PMARGIN(pair)); // (forest_engine.margin: d - includemargin)\n"
105
+ _BOUND = ((" return dot3(dif, n) <= RFMA(c_grbound[g2], 1.f + 1e-5f, 1e-6f);\n",
106
+ " return dot3(dif, n) <= RFMA(RADD(c_grbound[g2], PMARGIN(pr)), 1.f + 1e-5f, 1e-6f); // (margin)\n"),
107
+ (" float rb = RADD(c_grbound[g1], c_grbound[g2]);\n return dot3(dif, dif) <=",
108
+ " float rb = RADD(RADD(c_grbound[g1], c_grbound[g2]), PMARGIN(pr)); // (margin)\n"
109
+ " return dot3(dif, dif) <="))
110
+ _CP_HEAD = "__device__ DK_INL_COLLIDE void collide_pair(S& s, int pair) {\n"
111
+ _CP_EDITS = ((" if (dot3_rn(dif, n) > c_grbound[g2]) return;",
112
+ " if (dot3_rn(dif, n) > RADD(c_grbound[g2], PMARGIN(pair))) return; // (margin)"),
113
+ ("rb = RADD(c_grbound[g1], c_grbound[g2]);\n if (dot3_rn(dif, dif) > RMUL(rb, rb)) return;",
114
+ "rb = RADD(RADD(c_grbound[g1], c_grbound[g2]), PMARGIN(pair)); // (margin)\n"
115
+ " if (dot3_rn(dif, dif) > RMUL(rb, rb)) return;"))
116
+ _THRESH = re.compile(r"if \((dist|d4\[i\]) < 0\.f\) (add_contact|add_sphere_contact)\(s, pair, ")
117
+ _PARALLEL = " if (dist <= 0.f) {\n"
118
+ _REPLAY = re.compile(r"\n( *)const int br = adj_pair_geom(_aux)?\(pair, slot, (s\.taux\[c\], )?s\.gx, s\.gq, &d, p, "
119
+ r"fr, &nu, nullptr, nullptr[^\n]*\);\n")
120
+
121
+
122
+ def _sub1(src, a, b, what):
123
+ k = src.count(a)
124
+ if k != 1:
125
+ raise RuntimeError(f"forest_engine.margin: {what}: anchor found {k} times: {a[:80]!r}")
126
+ return src.replace(a, b)
127
+
128
+
129
+ def engine(src, m):
130
+ """The final engine text (adjoint.cuda_source, last) with the margins; unchanged without them."""
131
+ if not active(m):
132
+ return src
133
+ src = _sub1(src, _DECL_AT, DECL + _DECL_AT, "declaration")
134
+ i = src.index(_ADD_HEAD) if src.count(_ADD_HEAD) == 1 else -1
135
+ if i < 0:
136
+ raise RuntimeError("forest_engine.margin: add_contact's head")
137
+ j = src.index("\n}\n", i)
138
+ body = _sub1(src[i:j], _ADD_OLD, _ADD_NEW, "add_contact's distance")
139
+ src = src[:i] + body + src[j:]
140
+ for a, b in _BOUND:
141
+ src = _sub1(src, a, b, "pair_bound")
142
+ i = src.index(_CP_HEAD) if src.count(_CP_HEAD) == 1 else -1
143
+ if i < 0:
144
+ raise RuntimeError("forest_engine.margin: collide_pair's head")
145
+ j = src.index("\n}\n", i)
146
+ fn = src[i:j]
147
+ for a, b in _CP_EDITS:
148
+ fn = _sub1(fn, a, b, "collide_pair's culls")
149
+ n = len(_THRESH.findall(fn))
150
+ if n < 1:
151
+ raise RuntimeError("forest_engine.margin: collide_pair's contact tests")
152
+ fn = _THRESH.sub(lambda mt: f"if ({mt.group(1)} < PMARGIN(pair)) {mt.group(2)}(s, pair, ", fn)
153
+ if fn.count(_PARALLEL) > 1:
154
+ raise RuntimeError("forest_engine.margin: capsule-capsule's parallel candidates")
155
+ fn = fn.replace(_PARALLEL, " if (dist <= PMARGIN(pair)) { // (margin: MuJoCo Warp's capsule_capsule)\n")
156
+ left = re.findall(r"[^\n]*(?:< 0\.f|<= 0\.f)\)[^\n]*add_(?:sphere_)?contact\(s, pair[^\n]*", fn)
157
+ if left:
158
+ raise RuntimeError(f"forest_engine.margin: collide_pair's contact tests without the margin: {left[:3]}")
159
+ src = src[:i] + fn + src[j:]
160
+ hits = _REPLAY.findall(src)
161
+ if "adj_contact_one(" in src:
162
+ if len(hits) != 1:
163
+ raise RuntimeError(f"forest_engine.margin: adj_contact_one's replay found {len(hits)} times")
164
+ src = _REPLAY.sub(lambda mt: mt.group(0) + f"{mt.group(1)}d = RSUB(d, PMARGIN(pair)); // (forest_engine."
165
+ "margin: the forward's d - includemargin)\n", src)
166
+ from nablaengine.forest_engine import margin_convex
167
+ return margin_convex.engine(src, m)