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,845 @@
1
+ """Fixed tendons in the forest engine: tendon equality rows, tendon limit rows, tendon passive forces (stiffness with
2
+ its deadband, damping, implicit in implicitfast) and tendon armature, forward and adjoint."""
3
+ import mujoco
4
+ import numpy as np
5
+
6
+ from nablaengine.forest_engine import equality as EQ
7
+
8
+ TL_KIND, ET_KIND = 7, 8
9
+ MAX_LIMITED = 16
10
+
11
+
12
+ def _is_fixed(m, t):
13
+ if t >= m.ntendon:
14
+ return True
15
+ adr, n = int(m.tendon_adr[t]), int(m.tendon_num[t])
16
+ return all(int(m.wrap_type[w]) == int(mujoco.mjtWrap.mjWRAP_JOINT) for w in range(adr, adr + n))
17
+
18
+
19
+ def support_list(m, t):
20
+ """[(dof, coef)] of tendon t's support, ascending: a fixed tendon's coefficients, a spatial tendon's support
21
+ (forest_engine.spatial.support) with coefficient 0 (its J is per world)."""
22
+ from nablaengine.forest_engine import spatial
23
+ if not _is_fixed(m, t):
24
+ return [(d, 0.0) for d in spatial.support(m, t)]
25
+ return sorted(coefs(m, t).items())
26
+
27
+
28
+ def spatial_build(m):
29
+ """Whether the build takes forest_engine.spatial's text: a used tendon is spatial, or a general actuator
30
+ (forest_engine.muscle)."""
31
+ from nablaengine.forest_engine import muscle
32
+ return muscle.applies(m) or any(not _is_fixed(m, t) for t in used(m))
33
+
34
+
35
+ def coefs(m, t):
36
+ """{dof: coef} of fixed tendon t (a joint listed twice: summed)."""
37
+ if t >= m.ntendon:
38
+ from nablaengine.forest_engine import muscle
39
+ return {muscle.virtual_dof(m, t): 1.0}
40
+ out = {}
41
+ for w in range(int(m.tendon_adr[t]), int(m.tendon_adr[t]) + int(m.tendon_num[t])):
42
+ d = int(m.jnt_dofadr[int(m.wrap_objid[w])])
43
+ out[d] = out.get(d, 0.0) + float(m.wrap_prm[w])
44
+ return out
45
+
46
+
47
+ def _eq_on(m):
48
+ return m.neq > 0 and not EQ.disabled(m)
49
+
50
+
51
+ def tendon_eqs(m):
52
+ """The active tendon equalities that get rows, in equality order: [dict(e, t1, t2 (-1: none), poly (5,), solref,
53
+ solimp, invw, dofs (the union support, ascending))]."""
54
+ if not _eq_on(m):
55
+ return []
56
+ out = []
57
+ for e in range(m.neq):
58
+ if not m.eq_active0[e] or int(m.eq_type[e]) != int(mujoco.mjtEq.mjEQ_TENDON):
59
+ continue
60
+ t1, t2 = int(m.eq_obj1id[e]), int(m.eq_obj2id[e])
61
+ if not _is_fixed(m, t1) or (t2 >= 0 and not _is_fixed(m, t2)):
62
+ continue
63
+ dofs = sorted(set(coefs(m, t1)) | (set(coefs(m, t2)) if t2 >= 0 else set()))
64
+ invw = float(m.tendon_invweight0[t1]) + (float(m.tendon_invweight0[t2]) if t2 >= 0 else 0.0)
65
+ out.append(dict(e=e, t1=t1, t2=t2, poly=np.array(m.eq_data[e, :5], float), solref=np.array(m.eq_solref[e]),
66
+ solimp=np.array(m.eq_solimp[e]), invw=invw, dofs=dofs))
67
+ return out
68
+
69
+
70
+ def _limit_off(m):
71
+ D = mujoco.mjtDisableBit
72
+ return bool(int(m.opt.disableflags) & (int(D.mjDSBL_LIMIT) | int(D.mjDSBL_CONSTRAINT)))
73
+
74
+
75
+ def limited(m):
76
+ """The limited tendons, in tendon order (none when the flags disable limits)."""
77
+ if _limit_off(m):
78
+ return []
79
+ return [t for t in range(m.ntendon) if m.tendon_limited[t]]
80
+
81
+
82
+ def _flag(m, bit):
83
+ return bool(int(m.opt.disableflags) & int(bit))
84
+
85
+
86
+ def passive(m):
87
+ """The tendons with stiffness or damping (the flags' SPRING / DAMPER respected)."""
88
+ D = mujoco.mjtDisableBit
89
+ k = not _flag(m, D.mjDSBL_SPRING)
90
+ d = not _flag(m, D.mjDSBL_DAMPER)
91
+ return [t for t in range(m.ntendon) if (k and m.tendon_stiffness[t] > 0) or (d and m.tendon_damping[t] > 0)]
92
+
93
+
94
+ def stiffness(m, t):
95
+ return 0.0 if _flag(m, mujoco.mjtDisableBit.mjDSBL_SPRING) else float(m.tendon_stiffness[t])
96
+
97
+
98
+ def damping(m, t):
99
+ return 0.0 if _flag(m, mujoco.mjtDisableBit.mjDSBL_DAMPER) else float(m.tendon_damping[t])
100
+
101
+
102
+ def armature(m):
103
+ """The tendons with armature."""
104
+ return [t for t in range(m.ntendon) if m.tendon_armature[t] > 0]
105
+
106
+
107
+ def actuators(m):
108
+ """The actuators on tendons (fixed, and spatial ones: forest_engine.spatial): [(actuator, tendon)]; with the general
109
+ joint actuators on their virtual tendons (forest_engine.muscle), in actuator order."""
110
+ from nablaengine.forest_engine import muscle
111
+ vj = set(muscle.joint_general(m)) if muscle.applies(m) else set()
112
+ return [(a, int(m.actuator_trnid[a, 0]) if a not in vj else muscle.virtual_tendon(m, a)) for a in range(m.nu)
113
+ if int(m.actuator_trntype[a]) == int(mujoco.mjtTrn.mjTRN_TENDON) or a in vj]
114
+
115
+
116
+ def carriers(m):
117
+ """{actuator: carrier dof} for the tendon actuators: the first support dof without a joint actuator and not another
118
+ tendon actuator's (None where there is none: check_actuators refuses it)."""
119
+ taken = {int(m.jnt_dofadr[m.actuator_trnid[a, 0]]) for a in range(m.nu)
120
+ if int(m.actuator_trntype[a]) == int(mujoco.mjtTrn.mjTRN_JOINT)}
121
+ if spatial_build(m):
122
+ return {a: None for a, _ in actuators(m)}
123
+ out = {}
124
+ for a, t in actuators(m):
125
+ if not _is_fixed(m, t):
126
+ out[a] = None
127
+ continue
128
+ d = next((d for d in sorted(coefs(m, t)) if d not in taken), None)
129
+ out[a] = d
130
+ if d is not None:
131
+ taken.add(d)
132
+ return out
133
+
134
+
135
+ def check_actuators(m):
136
+ """[(actuator name, reason)] of the tendon actuators the forest engine does not support."""
137
+ bad = []
138
+ car = carriers(m)
139
+ sb = any(not _is_fixed(m, int(m.actuator_trnid[a, 0])) for a in range(m.nu)
140
+ if int(m.actuator_trntype[a]) == int(mujoco.mjtTrn.mjTRN_TENDON)) or spatial_build(m)
141
+ for a in range(m.nu):
142
+ if int(m.actuator_trntype[a]) != int(mujoco.mjtTrn.mjTRN_TENDON):
143
+ continue
144
+ nm = mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, a) or str(a)
145
+ t = int(m.actuator_trnid[a, 0])
146
+ affine = int(m.actuator_biastype[a]) == int(mujoco.mjtBias.mjBIAS_AFFINE)
147
+ from nablaengine.forest_engine import muscle
148
+ if muscle.is_general(m, a):
149
+ pass
150
+ elif not (m.actuator_dyntype[a] == mujoco.mjtDyn.mjDYN_NONE and m.actuator_gaintype[a] == mujoco.mjtGain.mjGAIN_FIXED
151
+ and (affine or int(m.actuator_biastype[a]) == int(mujoco.mjtBias.mjBIAS_NONE))
152
+ and (not affine or m.actuator_biasprm[a, 0] == 0.0) and m.actuator_gear[a, 0] == 1.0
153
+ and not np.any(m.actuator_gear[a, 1:])
154
+ and (not m.actuator_forcelimited[a] or m.actuator_forcerange[a, 0] == -m.actuator_forcerange[a, 1])):
155
+ bad.append((nm, "tendon actuator: not fixed gain / affine bias / gear 1 / symmetric forcerange"))
156
+ if m.tendon_actfrclimited[t]:
157
+ bad.append((nm, "tendon actfrcrange"))
158
+ if any(m.jnt_actfrclimited[int(m.dof_jntid[d])] for d, _ in support_list(m, t)):
159
+ bad.append((nm, "tendon actuator through a joint with actuatorfrcrange"))
160
+ if not sb and car.get(a) is None:
161
+ bad.append((nm, "no support dof without a joint actuator (the tape's carrier)"))
162
+ return bad
163
+
164
+
165
+ def used(m):
166
+ """The tendons the engine reads (equality objects, limited, passive, armature, actuators), ascending."""
167
+ s = set(limited(m)) | set(passive(m)) | set(armature(m)) | {t for _, t in actuators(m)}
168
+ for r in tendon_eqs(m):
169
+ s |= {r["t1"]} | ({r["t2"]} if r["t2"] >= 0 else set())
170
+ return sorted(s)
171
+
172
+
173
+ def applies(m):
174
+ """Whether the model has tendons the engine simulates, or general actuators (forest_engine.muscle: then the build
175
+ takes this module's text)."""
176
+ from nablaengine.forest_engine import muscle
177
+ return (m.ntendon > 0 and bool(used(m))) or muscle.applies(m)
178
+
179
+
180
+ def trees(m, t):
181
+ """The kinematic trees tendon t spans."""
182
+ return sorted({int(m.dof_treeid[d]) for d, _ in support_list(m, t)})
183
+
184
+
185
+ def spans_trees(m):
186
+ """The tendons the engine reads that span several kinematic trees."""
187
+ return [t for t in used(m) if len(trees(m, t)) > 1]
188
+
189
+
190
+ def _ancestor(m, i, j):
191
+ while i >= 0:
192
+ if i == j:
193
+ return True
194
+ i = int(m.dof_parentid[i])
195
+ return False
196
+
197
+
198
+ def check(m):
199
+ """[(tendon or equality name, reason)] of the tendon uses the forest engine does not support (empty: all)."""
200
+ bad = []
201
+ J = mujoco.mjtJoint
202
+ name = lambda t: mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_TENDON, t) or str(t)
203
+ from nablaengine.forest_engine import spatial
204
+ for t in range(m.ntendon):
205
+ if not _is_fixed(m, t):
206
+ bad += [(name(t), why) for why in spatial.check_tendon(m, t)]
207
+ else:
208
+ for w in range(int(m.tendon_adr[t]), int(m.tendon_adr[t]) + int(m.tendon_num[t])):
209
+ j = int(m.wrap_objid[w])
210
+ if int(m.jnt_type[j]) not in (int(J.mjJNT_HINGE), int(J.mjJNT_SLIDE)):
211
+ bad.append((name(t), "a joint other than hinge / slide"))
212
+ if m.tendon_frictionloss[t] > 0 and not _flag(m, mujoco.mjtDisableBit.mjDSBL_FRICTIONLOSS) \
213
+ and not _flag(m, mujoco.mjtDisableBit.mjDSBL_CONSTRAINT):
214
+ bad.append((name(t), "tendon frictionloss (no frictionloss rows in the forest adjoint)"))
215
+ if _is_fixed(m, t) and m.tendon_length0[t] != 0:
216
+ bad.append((name(t), "tendon_length0 != 0 (joint refs: the converter folds them)"))
217
+ if t in limited(m):
218
+ if m.tendon_margin[t] < 0:
219
+ bad.append((name(t), "negative limit margin"))
220
+ if t in armature(m) and len(support_list(m, t)) > 32:
221
+ bad.append((name(t), "armature on more than 32 dofs"))
222
+ if spatial_build(m):
223
+ from nablaengine.forest_engine import spatial
224
+ words = spatial.words(m)
225
+ if words > spatial.MAX_TS_WORDS:
226
+ bad.append(("tendons", f"spatial tendons: per-world tendon storage of {words} words (at most "
227
+ f"{spatial.MAX_TS_WORDS}: the adjoint's shared memory; fewer used tendons or actuators)"))
228
+ if len(limited(m)) > MAX_LIMITED:
229
+ bad.append(("tendons", f"{len(limited(m))} limited tendons (at most {MAX_LIMITED})"))
230
+ for r in tendon_eqs(m):
231
+ nm = mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_EQUALITY, r["e"]) or str(r["e"])
232
+ if r["t1"] == r["t2"]:
233
+ bad.append((nm, "tendon1 == tendon2"))
234
+ if len(r["dofs"]) > 32:
235
+ bad.append((nm, "a tendon equality over more than 32 dofs"))
236
+ return bad
237
+
238
+
239
+ def check_eq(m, e):
240
+ """The reasons tendon equality e is not supported (forest_engine.equality.check)."""
241
+ why = []
242
+ t1, t2 = int(m.eq_obj1id[e]), int(m.eq_obj2id[e])
243
+ for t in (t1, t2):
244
+ if t >= 0 and not _is_fixed(m, t):
245
+ why.append("a tendon equality on a spatial tendon")
246
+ if not m.eq_active0[e]:
247
+ why.append("tendon equality inactive at build (eq_active0 = 0)")
248
+ return why
249
+
250
+
251
+
252
+ def _f32(x):
253
+ return EQ._f32(x)
254
+
255
+
256
+ def header(m):
257
+ """The tendon tables (compile-time constants, at least one entry each)."""
258
+ ts = used(m)
259
+ tix = {t: k for k, t in enumerate(ts)}
260
+ nt = len(ts)
261
+ sup = [support_list(m, t) for t in ts]
262
+ kt = max(len(x) for x in sup)
263
+ es, ls, ps, ar = tendon_eqs(m), limited(m), passive(m), armature(m)
264
+ acts, car = actuators(m), carriers(m)
265
+ sb = spatial_build(m)
266
+ if sb:
267
+ car = {a: 0 for a, _ in acts}
268
+ bias = lambda a: (m.actuator_biasprm[a] if int(m.actuator_biastype[a]) == int(mujoco.mjtBias.mjBIAS_AFFINE)
269
+ else np.zeros(10))
270
+ from nablaengine.forest_engine import muscle
271
+ gen = {a: muscle.plain_constants(m, a) for a, _ in acts if muscle.is_general(m, a)}
272
+ ke = max([len(r["dofs"]) for r in es], default=1)
273
+ n1 = lambda n: max(n, 1)
274
+ tab = lambda typ, nm, n, vals, note="": (f"__device__ const {typ} {nm}[{n}] = {{{vals}}};"
275
+ + (f" // {note}" if note else "") + "\n")
276
+ I, F = EQ._ints, EQ._floats
277
+ dense = []
278
+ for s_ in sup:
279
+ c = dict(s_)
280
+ dense += [c.get(i, 0.0) for i in range(m.nv)]
281
+ tdof = [x for s in sup for x in [d for d, _ in s] + [0] * (kt - len(s))]
282
+ tco = [x for s in sup for x in [c for _, c in s] + [0.0] * (kt - len(s))]
283
+ pat = []
284
+ for s in sup:
285
+ ds = [d for d, _ in s]
286
+ pat += [sum(1 << b for b in range(a + 1) if _ancestor(m, ds[a], ds[b])) for a in range(len(ds))]
287
+ pat += [0] * (kt - len(ds))
288
+ lsp = [x for t in ts for x in (m.tendon_lengthspring[t] if t < m.ntendon else (0.0, 0.0))]
289
+ etd = [x for r in es for x in r["dofs"] + [0] * (ke - len(r["dofs"]))]
290
+ from nablaengine.forest_engine import model_hooks
291
+ implicit = model_hooks.integrator(m) == "implicitfast"
292
+ nd = sum(1 for t in ps if damping(m, t) > 0)
293
+ return (f"#define NTEN {nt} // fixed tendons the engine reads (forest_engine.tendon)\n"
294
+ f"#define KTEN {kt} // the largest tendon support (dofs)\n"
295
+ f"#define NEQT {len(es)} // tendon equality rows (kind 8), the last equality rows\n"
296
+ f"#define KET {ke} // the largest tendon equality support\n"
297
+ f"#define NTL {len(ls)} // limited tendons (kind 7 rows after the equality rows: at most 2 NTL)\n"
298
+ f"#define NTP {len(ps)} // tendons with stiffness or damping\n"
299
+ f"#define NTA {len(ar)} // tendons with armature\n"
300
+ f"#define TEN_IMPLICIT {int(implicit and nd > 0)} // tendon damping in implicitfast's matrix\n"
301
+ + tab("int", "c_tnd", nt, I(len(s) for s in sup), "tendon: support size")
302
+ + tab("unsigned char", "c_tdof", nt * kt, I(tdof), "its dofs, ascending")
303
+ + tab("float", "c_tco", nt * kt, F(tco), "their coefficients")
304
+ + tab("unsigned", "c_tpat", nt * kt, ", ".join(f"{x}u" for x in pat),
305
+ "support entry a: the entries b <= a on M's sparsity pattern (bits)")
306
+ + tab("float", "c_tcd", nt * m.nv, F(dense), "the coefficient of every dof (0: none)")
307
+ + tab("float", "c_tstiff", nt, F(stiffness(m, t) if t in ps else 0.0 for t in ts))
308
+ + tab("float", "c_tdamp", nt, F(damping(m, t) if t in ps else 0.0 for t in ts))
309
+ + tab("float", "c_tlsp", 2 * nt, F(lsp), "the spring's deadband (tendon_lengthspring)")
310
+ + tab("int", "c_tpas", n1(len(ps)), I(tix[t] for t in ps), "the tendons with a passive force")
311
+ + tab("float", "c_tdampp", n1(len(ps)), F(damping(m, t) for t in ps), "their damping")
312
+ + tab("int", "c_tarmt", n1(len(ar)), I(tix[t] for t in ar), "the tendons with armature")
313
+ + tab("float", "c_tarm", n1(len(ar)), F(m.tendon_armature[t] for t in ar))
314
+ + tab("int", "c_ett", 2 * n1(len(es)), I(x for r in es for x in (tix[r["t1"]], tix[r["t2"]] if r["t2"] >= 0
315
+ else -1)),
316
+ "tendon equality: tendons 1, 2 (-1: none)")
317
+ + tab("int", "c_etnd", n1(len(es)), I(len(r["dofs"]) for r in es), "its union support size")
318
+ + tab("unsigned char", "c_etdof", n1(len(es)) * ke, I(etd), "its dofs, ascending")
319
+ + tab("float", "c_etpoly", 5 * n1(len(es)), F(x for r in es for x in r["poly"]), "polycoef")
320
+ + tab("float", "c_etsolref", 2 * n1(len(es)), F(x for r in es for x in r["solref"]))
321
+ + tab("float", "c_etsolimp", 5 * n1(len(es)), F(x for r in es for x in r["solimp"]))
322
+ + tab("float", "c_etinvw", n1(len(es)), F(r["invw"] for r in es))
323
+ + tab("int", "c_tlt", n1(len(ls)), I(tix[t] for t in ls), "limited tendon: the tendon")
324
+ + tab("float", "c_tlr", 2 * n1(len(ls)), F(x for t in ls for x in m.tendon_range[t]), "its range")
325
+ + tab("float", "c_tlmargin", n1(len(ls)), F(m.tendon_margin[t] for t in ls))
326
+ + tab("float", "c_tlsolref", 2 * n1(len(ls)), F(x for t in ls for x in m.tendon_solref_lim[t]))
327
+ + tab("float", "c_tlsolimp", 5 * n1(len(ls)), F(x for t in ls for x in m.tendon_solimp_lim[t]))
328
+ + tab("float", "c_tlinvw", n1(len(ls)), F(m.tendon_invweight0[t] for t in ls))
329
+ + f"#define NTACT {len(acts)} // actuators on fixed tendons\n"
330
+ + tab("int", "c_tat", n1(len(acts)), I(tix[t] for _, t in acts), "tendon actuator: the tendon")
331
+ + tab("int", "c_taa", n1(len(acts)), I(a for a, _ in acts), "its actuator (ctrl index)")
332
+ + tab("int", "c_tacar", n1(len(acts)), I(car[a] for a, _ in acts), "its carrier dof (the tape's bits)")
333
+ + tab("float", "c_takp", n1(len(acts)), F(gen[a][0] if a in gen else m.actuator_gainprm[a, 0] for a, _ in acts))
334
+ + tab("float", "c_takq", n1(len(acts)), F(gen[a][1] if a in gen else -bias(a)[1] for a, _ in acts))
335
+ + tab("float", "c_takv", n1(len(acts)), F(gen[a][2] if a in gen else -bias(a)[2] for a, _ in acts))
336
+ + tab("float", "c_tafrc", n1(len(acts)), F(gen[a][3] if a in gen else (
337
+ m.actuator_forcerange[a, 1] if m.actuator_forcelimited[a] else 1e30) for a, _ in acts),
338
+ "forcerange (symmetric)")
339
+ + tab("float", "c_tactr", 2 * n1(len(acts)), F(x for a, _ in acts for x in (
340
+ gen[a][4] if a in gen else m.actuator_ctrlrange[a] if m.actuator_ctrllimited[a] else (-1e30, 1e30))),
341
+ "ctrlrange")
342
+ + (_spatial_header(m, ts, kt, acts, implicit) if sb else "")
343
+ + (_muscle_header(m, acts) if sb and _muscle_on(m) else "")
344
+ )
345
+
346
+
347
+ def _muscle_on(m):
348
+ from nablaengine.forest_engine import muscle
349
+ return muscle.applies(m)
350
+
351
+
352
+ def _muscle_header(m, acts):
353
+ from nablaengine.forest_engine import muscle
354
+ return muscle.tables(m, acts)
355
+
356
+
357
+ def _spatial_header(m, ts, kt, acts, implicit):
358
+ from nablaengine.forest_engine import spatial
359
+ return (f"#define SP_IMPLICIT {int(implicit)} // tendon actuators' kv in implicitfast's matrix (forest_engine.spatial)\n"
360
+ + spatial.tables(m, ts, kt, acts))
361
+
362
+
363
+ DEVICE = r"""// fixed tendons (forest_engine.tendon): L = sum c_i q_i over the support, explicitly rounded (the adjoint replays the
364
+ // limit rows' test and the equality rows' pos bitwise)
365
+ __device__ __forceinline__ float ten_len(const float* qpos, int t) {
366
+ const unsigned char* d = c_tdof + KTEN * t;
367
+ const float* c = c_tco + KTEN * t;
368
+ float L = RMUL(c[0], qpos[c_dqadr[d[0]]]);
369
+ for (int k = 1; k < c_tnd[t]; k++) L = RFMA(c[k], qpos[c_dqadr[d[k]]], L);
370
+ return L;
371
+ }
372
+ // c . v of tendon t (v an NV vector)
373
+ __device__ __forceinline__ float ten_jv(const float* v, int t) {
374
+ const unsigned char* d = c_tdof + KTEN * t;
375
+ const float* c = c_tco + KTEN * t;
376
+ float acc = 0.f;
377
+ for (int k = 0; k < c_tnd[t]; k++) acc += c[k] * v[d[k]];
378
+ return acc;
379
+ }
380
+ // the part of c . v on M's sparsity pattern relative to dof i (its ancestors and descendants on the support,
381
+ // c_tpat): the implicit damping's row i, (h d c c' restricted) y = h d c_i ten_jv_pat(y, t, i)
382
+ __device__ __forceinline__ float ten_jv_pat(const float* v, int t, int i) {
383
+ const unsigned char* d = c_tdof + KTEN * t;
384
+ const float* c = c_tco + KTEN * t;
385
+ int a = 0;
386
+ while (d[a] != i) a++;
387
+ float acc = 0.f;
388
+ for (int k = 0; k < c_tnd[t]; k++) {
389
+ const bool on = k <= a ? (c_tpat[KTEN * t + a] >> k) & 1u : (c_tpat[KTEN * t + k] >> a) & 1u;
390
+ if (on) acc += c[k] * v[d[k]];
391
+ }
392
+ return acc;
393
+ }
394
+ // tendon equality e: J_2 = -P'(L2) (0 without tendon 2), its derivative -P''(L2), pos = L1 - P(L2)
395
+ __device__ __forceinline__ float et_j2(const float* qpos, int e) {
396
+ const int t2 = c_ett[2 * e + 1];
397
+ if (t2 < 0) return 0.f;
398
+ const float* c = c_etpoly + 5 * e;
399
+ const float x = ten_len(qpos, t2);
400
+ return -RFMA(x, RFMA(x, RFMA(x, RMUL(4.f, c[4]), RMUL(3.f, c[3])), RMUL(2.f, c[2])), c[1]);
401
+ }
402
+ __device__ __forceinline__ float et_j2d(const float* qpos, int e) {
403
+ const int t2 = c_ett[2 * e + 1];
404
+ if (t2 < 0) return 0.f;
405
+ const float* c = c_etpoly + 5 * e;
406
+ const float x = ten_len(qpos, t2);
407
+ return -RFMA(x, RFMA(x, RMUL(12.f, c[4]), RMUL(6.f, c[3])), RMUL(2.f, c[2]));
408
+ }
409
+ __device__ __forceinline__ float et_pos(const float* qpos, int e) {
410
+ const float* c = c_etpoly + 5 * e;
411
+ const float L1 = ten_len(qpos, c_ett[2 * e]);
412
+ const int t2 = c_ett[2 * e + 1];
413
+ if (t2 < 0) return RSUB(L1, c[0]);
414
+ const float x = ten_len(qpos, t2);
415
+ return RSUB(L1, RFMA(x, RFMA(x, RFMA(x, RFMA(x, c[4], c[3]), c[2]), c[1]), c[0]));
416
+ }
417
+ // its J at dof i (J_2 = et_j2)
418
+ __device__ __forceinline__ float et_J(int e, int i, float j2) {
419
+ const int t2 = c_ett[2 * e + 1];
420
+ const float c1 = c_tcd[NV * c_ett[2 * e] + i];
421
+ return t2 < 0 ? c1 : c1 + j2 * c_tcd[NV * t2 + i];
422
+ }
423
+ __device__ __forceinline__ float et_jv(const float* qpos, int e, const float* v) {
424
+ const float j2 = et_j2(qpos, e);
425
+ const unsigned char* d = c_etdof + KET * e;
426
+ float acc = 0.f;
427
+ for (int k = 0; k < c_etnd[e]; k++) acc += et_J(e, d[k], j2) * v[d[k]];
428
+ return acc;
429
+ }
430
+ // limited tendon l, side 0 (lower: dist = L - range[0], J = +c) or 1 (upper: dist = range[1] - L, J = -c)
431
+ __device__ __forceinline__ float tl_dist(const float* qpos, int l, int side) {
432
+ const float L = ten_len(qpos, c_tlt[l]);
433
+ return side ? RSUB(c_tlr[2 * l + 1], L) : RSUB(L, c_tlr[2 * l]);
434
+ }
435
+ // the number of active tendon limit rows at qpos (the forward's test)
436
+ __device__ __forceinline__ int tl_rows(const float* qpos) {
437
+ int n = 0;
438
+ for (int l = 0; l < NTL; l++)
439
+ for (int side = 0; side < 2; side++) n += tl_dist(qpos, l, side) < c_tlmargin[l] ? 1 : 0;
440
+ return n;
441
+ }
442
+ // the passive force of tendon t (index into the tendon table): -k (L - s) - d (c . v), s the deadband's nearer end
443
+ // (L inside: no spring force); keff: its dF/dL (k outside the deadband, else 0)
444
+ __device__ __forceinline__ float ten_passive_f(const float* qpos, const float* v, int t, float* keff) {
445
+ const float L = ten_len(qpos, t), lo = c_tlsp[2 * t], hi = c_tlsp[2 * t + 1], k = c_tstiff[t];
446
+ const float sp = L > hi ? -k * (L - hi) : L < lo ? -k * (L - lo) : 0.f;
447
+ *keff = L > hi || L < lo ? k : 0.f;
448
+ return sp - c_tdamp[t] * ten_jv(v, t);
449
+ }
450
+ // the tendons' passive force on dof i
451
+ __device__ __forceinline__ float ten_qfrc(const float* qpos, const float* v, int i) {
452
+ float acc = 0.f, ke;
453
+ for (int p = 0; p < NTP; p++) {
454
+ const int t = c_tpas[p];
455
+ const float c = c_tcd[NV * t + i];
456
+ if (c != 0.f) acc += c * ten_passive_f(qpos, v, t, &ke);
457
+ }
458
+ return acc;
459
+ }
460
+ // A += w_t c_t c_t' over the tendons in list[0 .. n) (w = scale * wt[p]) on M's sparsity pattern (c_tpat: MuJoCo's
461
+ // sparse qM); lane a: the entries (a, b <= a) of the support, tendons one after another (fenced)
462
+ __device__ __forceinline__ void ten_outer(float* A, const int* list, const float* wt, int n, float scale, int lane) {
463
+ for (int p = 0; p < n; p++) {
464
+ const int t = list[p], nd = c_tnd[t];
465
+ const unsigned char* d = c_tdof + KTEN * t;
466
+ const float* c = c_tco + KTEN * t;
467
+ if (lane < nd) {
468
+ const float g = scale * wt[p] * c[lane];
469
+ const unsigned pm = c_tpat[KTEN * t + lane];
470
+ for (int b = 0; b <= lane; b++)
471
+ if ((pm >> b) & 1u) A[TRI(d[lane], d[b])] += g * c[b];
472
+ }
473
+ __syncwarp();
474
+ }
475
+ }
476
+ // the tendon actuators' force on dof i: f = kp u - kq L - kv (c . v), u = ctrl clamped to ctrlrange, f clamped to
477
+ // the forcerange; on the carrier dof also the flags (ctrl clamped, force at its forcerange) for the tape's bits
478
+ __device__ __forceinline__ float tact_qfrc(const float* qpos, const float* v, const float* ctrl, int i, bool* aclamp,
479
+ bool* uclamp, bool* clamp) {
480
+ float acc = 0.f;
481
+ for (int k = 0; k < NTACT; k++) {
482
+ const int t = c_tat[k], a = c_taa[k];
483
+ const float c = c_tcd[NV * t + i];
484
+ const bool car = c_tacar[k] == i;
485
+ if (c == 0.f && !car) continue;
486
+ const float u = fminf(fmaxf(ctrl[a], c_tactr[2 * k]), c_tactr[2 * k + 1]);
487
+ float f = c_takp[k] * u - c_takq[k] * ten_len(qpos, t) - c_takv[k] * ten_jv(v, t);
488
+ const bool fc = f <= -c_tafrc[k] || f >= c_tafrc[k];
489
+ f = fminf(fmaxf(f, -c_tafrc[k]), c_tafrc[k]);
490
+ if (car) { *uclamp = *uclamp || u != ctrl[a]; *aclamp = *aclamp || fc; *clamp = *clamp || fc; }
491
+ acc += c * f;
492
+ }
493
+ return acc;
494
+ }
495
+ // L += h kv c c' of the tendon actuators whose kv is on (the carrier dof's kvoff bit), on M's sparsity pattern
496
+ template <class S>
497
+ __device__ void tact_implicit(S& s, float h, int lane) {
498
+ for (int k = 0; k < NTACT; k++) {
499
+ const int t = c_tat[k], cr = c_tacar[k], nd = c_tnd[t];
500
+ if ((s.kvoff[cr >> 5] >> (cr & 31)) & 1u) continue;
501
+ const unsigned char* d = c_tdof + KTEN * t;
502
+ const float* c = c_tco + KTEN * t;
503
+ if (lane < nd) {
504
+ const float g = h * c_takv[k] * c[lane];
505
+ const unsigned pm = c_tpat[KTEN * t + lane];
506
+ for (int b = 0; b <= lane; b++)
507
+ if ((pm >> b) & 1u) s.L[TRI(d[lane], d[b])] += g * c[b];
508
+ }
509
+ __syncwarp();
510
+ }
511
+ }
512
+ // J' f of the tendon rows on dof i, added to acc: the tendon equality rows (after the connect rows), then the tendon
513
+ // limit rows (kind 7, after the equality rows)
514
+ template <class S>
515
+ __device__ __forceinline__ void ten_jtf(const S& s, const float* f, int i, float& acc) {
516
+ for (int e = 0; e < NEQT; e++) {
517
+ const float fe = f[s.nefc_dof + NEQJ + 3 * NEQC + e];
518
+ const float J = et_J(e, i, et_j2(s.qpos, e));
519
+ if (J != 0.f) acc += J * fe;
520
+ }
521
+ for (int r = s.nefc_dof + NEQR; r < s.nefc && s.efc_kind[r] == 7; r++) {
522
+ const float c = c_tcd[NV * c_tlt[s.efc_a[r]] + i];
523
+ if (c != 0.f) acc += s.efc_b[r] * c * f[r];
524
+ }
525
+ }
526
+ // H += J' D J of the tendon rows (lane a: the entries (a, b <= a) of the row's support; rows one after another):
527
+ // the equality rows always, the limit rows on their quadratic piece
528
+ template <class S>
529
+ __device__ void ten_hessian(S& s, int lane) {
530
+ for (int e = 0; e < NEQT; e++) {
531
+ const int r = s.nefc_dof + NEQJ + 3 * NEQC + e, nd = c_etnd[e];
532
+ const unsigned char* d = c_etdof + KET * e;
533
+ const float j2 = et_j2(s.qpos, e), D = s.efc_D[r];
534
+ if (lane < nd) {
535
+ const float g = D * et_J(e, d[lane], j2);
536
+ for (int b = 0; b <= lane; b++) s.L[TRI(d[lane], d[b])] += g * et_J(e, d[b], j2);
537
+ }
538
+ __syncwarp();
539
+ }
540
+ for (int r = s.nefc_dof + NEQR; r < s.nefc && s.efc_kind[r] == 7; r++) {
541
+ float ds, dd, cost;
542
+ row_eval(s, r, s.efc_jar[r], &ds, &dd, &cost);
543
+ if (dd != 0.f) {
544
+ const int t = c_tlt[s.efc_a[r]], nd = c_tnd[t];
545
+ const unsigned char* d = c_tdof + KTEN * t;
546
+ const float* c = c_tco + KTEN * t;
547
+ if (lane < nd) {
548
+ const float g = dd * c[lane];
549
+ for (int b = 0; b <= lane; b++) s.L[TRI(d[lane], d[b])] += g * c[b];
550
+ }
551
+ }
552
+ __syncwarp();
553
+ }
554
+ }
555
+
556
+ """
557
+
558
+ ADJ_DEVICE = r"""
559
+ // A5 / A6, tendon rows (forest_engine.tendon), lane 0 in row order (deterministic): the tendon equality rows (always on
560
+ // their quadratic piece) as the joint rows with J = c_1 + J_2 c_2 (dJ/dq_m = -P''(L2) c2_m c2), then the tendon limit
561
+ // rows replayed with the forward's test (tl_dist), the tape's zone bits, limit_row_vjp in the tendon coordinate times
562
+ // c. jtf (debug build): the rows' J' f into s.jtf
563
+ __device__ __noinline__ void adj_tendon(Adj& s, int lane, bool jtf) {
564
+ if (lane == 0) {
565
+ for (int e = 0; e < NEQT; e++) {
566
+ const int t2 = c_ett[2 * e + 1], nd = c_etnd[e];
567
+ const unsigned char* d = c_etdof + KET * e;
568
+ const float pos = et_pos(s.q, e), j2 = et_j2(s.q, e), j2d = et_j2d(s.q, e);
569
+ float ri[6];
570
+ adj_row_impedance(c_etsolref + 2 * e, c_etsolimp + 5 * e, pos, c_etinvw[e], ri);
571
+ const float k = ri[0], b = ri[1], imp = ri[2], dimp = ri[3], D = ri[4], dD = ri[5];
572
+ float ja = 0.f, jv = 0.f, jl = 0.f, c2a = 0.f, c2v = 0.f, c2l = 0.f;
573
+ for (int q = 0; q < nd; q++) {
574
+ const int i = d[q];
575
+ const float J = et_J(e, i, j2);
576
+ ja += J * s.a[i]; jv += J * s.v[i]; jl += J * s.lam[i];
577
+ if (t2 >= 0) {
578
+ const float c2 = c_tcd[NV * t2 + i];
579
+ c2a += c2 * s.a[i]; c2v += c2 * s.v[i]; c2l += c2 * s.lam[i];
580
+ }
581
+ }
582
+ const float x = ja + k * imp * pos + b * jv;
583
+ const float sp = jl * (dD * x + D * (k * (imp + dimp * pos))), pv = D * b * jl;
584
+ const float sn = t2 >= 0 ? j2d * (D * ((c2a + b * c2v) * jl + x * c2l)) : 0.f;
585
+ for (int q = 0; q < nd; q++) {
586
+ const int i = d[q];
587
+ const float J = et_J(e, i, j2);
588
+ s.Pq[i] += sp * J + (t2 >= 0 ? sn * c_tcd[NV * t2 + i] : 0.f);
589
+ s.Pv[i] += pv * J;
590
+ #ifdef DK_ADJ_DEBUG
591
+ if (jtf) s.jtf[i] += -D * x * J;
592
+ #endif
593
+ }
594
+ }
595
+ int r = NFLOSS + (((unsigned)s.hdr >> 18) & 63u) + NEQR; // the first tendon limit row
596
+ for (int l = 0; l < NTL; l++)
597
+ for (int side = 0; side < 2; side++) {
598
+ const float dist = tl_dist(s.q, l, side);
599
+ if (!(dist < c_tlmargin[l])) continue;
600
+ const bool act = (s.zone[r >> 5] >> (r & 31)) & 1u;
601
+ r++;
602
+ if (!act) continue;
603
+ const int t = c_tlt[l], nd = c_tnd[t];
604
+ const unsigned char* d = c_tdof + KTEN * t;
605
+ const float* c = c_tco + KTEN * t;
606
+ const float pos = RSUB(dist, c_tlmargin[l]), sg = side ? -1.f : 1.f;
607
+ float ri[6], pq, pv, ca = 0.f, cv = 0.f, cl = 0.f;
608
+ adj_row_impedance(c_tlsolref + 2 * l, c_tlsolimp + 5 * l, pos, c_tlinvw[l], ri);
609
+ for (int q = 0; q < nd; q++) { ca += c[q] * s.a[d[q]]; cv += c[q] * s.v[d[q]]; cl += c[q] * s.lam[d[q]]; }
610
+ limit_row_vjp(sg, pos, ca, cv, cl, ri[0], ri[1], ri[2], ri[3], ri[4], ri[5], &pq, &pv);
611
+ for (int q = 0; q < nd; q++) { s.Pq[d[q]] += pq * c[q]; s.Pv[d[q]] += pv * c[q]; }
612
+ #ifdef DK_ADJ_DEBUG
613
+ if (jtf) {
614
+ const float x = sg * ca + ri[0] * ri[2] * pos + ri[1] * (sg * cv);
615
+ for (int q = 0; q < nd; q++) s.jtf[d[q]] += -ri[4] * x * sg * c[q];
616
+ }
617
+ #endif
618
+ }
619
+ }
620
+ (void)jtf;
621
+ __syncwarp();
622
+ }
623
+ """
624
+
625
+
626
+ def _sub(text, a, b, count=1):
627
+ assert text.count(a) == count, f"forest tendon: {text.count(a)} x {a[:80]!r}"
628
+ return text.replace(a, b)
629
+
630
+
631
+ TL_ROWS = """ int ntl = 0; // the tendon limit rows (kind 7) after the equality rows (forest_engine.tendon): candidate (tendon
632
+ { // lane >> 1, side lane & 1), in (tendon, side) order
633
+ const int l = min(lane >> 1, NTL > 0 ? NTL - 1 : 0), side = lane & 1;
634
+ const bool on = lane < 2 * NTL && tl_dist(s.qpos, l, side) < c_tlmargin[l];
635
+ const unsigned bal = __ballot_sync(0xffffffffu, on);
636
+ if (on) {
637
+ const int r = ndof + __popc(bal & below);
638
+ s.efc_kind[r] = 7; s.efc_a[r] = l; s.efc_b[r] = side ? -1 : 1;
639
+ }
640
+ ntl = __popc(bal);
641
+ ndof += ntl;
642
+ }
643
+ """
644
+
645
+ JOB_TL = """ const bool tlr = !con && j >= ndof - ntl; // a tendon limit row (forest_engine.tendon)
646
+ const bool eqr = !con && j >= ndof - ntl - NEQR; // an equality row (forest_engine.equality) or a tendon limit
647
+ float eqvel = 0.f, eqpos = 0.f, eqjd = 0.f;
648
+ if (tlr) {
649
+ const int l = s.efc_a[j], side = s.efc_b[j] < 0;
650
+ pos = RSUB(tl_dist(s.qpos, l, side), c_tlmargin[l]); eqpos = pos;
651
+ eqvel = s.efc_b[j] * ten_jv(s.qvel, c_tlt[l]);
652
+ iw = c_tlinvw[l];
653
+ sref = c_tlsolref + 2 * l; simp = c_tlsolimp + 5 * l;
654
+ } else if (eqr) {
655
+ const int e = j - (ndof - ntl - NEQR);
656
+ if (e >= NEQJ + 3 * NEQC) { // tendon equality
657
+ const int et = e - NEQJ - 3 * NEQC;
658
+ pos = et_pos(s.qpos, et); eqpos = pos;
659
+ eqvel = et_jv(s.qpos, et, s.qvel);
660
+ iw = c_etinvw[et];
661
+ sref = c_etsolref + 2 * et; simp = c_etsolimp + 5 * et;
662
+ } else if (e < NEQJ) { // joint
663
+ """
664
+
665
+
666
+ def hooks(m):
667
+ """The forward's edits for a tendon build: forest_engine.equality's connect-build hooks (NEQC possibly 0) with the
668
+ tendon rows, then the passive force, the armature and the implicit damping."""
669
+ base = list(EQ.hooks_connect(m, extra_rows=len(tendon_eqs(m))))
670
+ out = []
671
+ for a, b in base:
672
+ if a == "#define NFLOSS ":
673
+ b = b.replace("#define NFLOSS ", header(m) + "#define NFLOSS ")
674
+ elif a.startswith("template <class T> struct dk_is_ptr"):
675
+ b = b.replace("template <class T> struct dk_is_ptr", DEVICE + "template <class T> struct dk_is_ptr", 1)
676
+ elif "eq_jtf(s, f, lane + 32 * t, acc[t]);" in b:
677
+ b = _sub(b, "eq_jtf(s, f, lane + 32 * t, acc[t]);",
678
+ "{ eq_jtf(s, f, lane + 32 * t, acc[t]); ten_jtf(s, f, lane + 32 * t, acc[t]); }")
679
+ elif " eq_jtf(s, f, i, acc);\n" in b:
680
+ b = _sub(b, " eq_jtf(s, f, i, acc);\n", " eq_jtf(s, f, i, acc);\n ten_jtf(s, f, i, acc);\n")
681
+ elif "eq_hessian(s, lane);" in b:
682
+ b = _sub(b, " __syncwarp();\n SUBPROF(28);\n",
683
+ " __syncwarp();\n ten_hessian(s, lane); // the tendon rows (forest_engine.tendon)\n"
684
+ " SUBPROF(28);\n")
685
+ elif "s.nefc_dof = ndof - NEQR;" in b:
686
+ b = _sub(b, "s.nefc_dof = ndof - NEQR;", "s.nefc_dof = ndof - NEQR - ntl;")
687
+ elif a == " if (kind == 0) val = v[a];\n":
688
+ b = (" if (kind == 7) val = b * ten_jv(v, c_tlt[a]); // tendon limit row (forest_engine.tendon)\n"
689
+ " else if (kind == 8) val = et_jv(s.qpos, a, v); // tendon equality row\n else " + b.lstrip())
690
+ elif a == EQ.ROWS_INSERT_AT:
691
+ b = _sub(b, " else { s.efc_kind[r] = 6; s.efc_a[r] = c; s.efc_b[r] = e - NEQJ - 3 * c; }\n",
692
+ " else if (e < NEQJ + 3 * NEQC) { s.efc_kind[r] = 6; s.efc_a[r] = c; s.efc_b[r] = e - NEQJ - 3 * c; }\n"
693
+ " else { s.efc_kind[r] = 8; s.efc_a[r] = e - NEQJ - 3 * NEQC; s.efc_b[r] = 0; } // tendon\n")
694
+ i = b.index(EQ.ROWS_INSERT_AT)
695
+ b = b[:i] + TL_ROWS + b[i:]
696
+ elif a == EQ.JOB_OLD:
697
+ head = (" const bool eqr = !con && j >= ndof - NEQR; // an equality row (forest_engine.equality)\n"
698
+ " float eqvel = 0.f, eqpos = 0.f, eqjd = 0.f;\n if (eqr) {\n"
699
+ " const int e = j - (ndof - NEQR);\n if (e < NEQJ) { // joint\n")
700
+ b = _sub(b, head, JOB_TL)
701
+ out.append((a, b))
702
+ from nablaengine.forest_engine import model_hooks
703
+ implicit = model_hooks.integrator(m) == "implicitfast"
704
+ if actuators(m):
705
+ out.append((" s.qsm[i] = act - c_damp[i] * s.qvel[i]",
706
+ " act += tact_qfrc(s.qpos, s.qvel, ctrl, i, &aclamp, &uclamp, &clamp); // the tendon actuators "
707
+ "(forest_engine.tendon)\n s.qsm[i] = act - c_damp[i] * s.qvel[i]"))
708
+ if passive(m):
709
+ out.append((" s.qsm[i] = act - c_damp[i] * s.qvel[i]",
710
+ " act += ten_qfrc(s.qpos, s.qvel, i); // the tendons' passive force (forest_engine.tendon)\n"
711
+ " s.qsm[i] = act - c_damp[i] * s.qvel[i]"))
712
+ if armature(m):
713
+ out.append((" __syncwarp();\n SUBPROF(17);\n",
714
+ " __syncwarp();\n ten_outer(s.M, c_tarmt, c_tarm, NTA, 1.f, lane); // tendon armature: M += a c c' "
715
+ "(forest_engine.tendon)\n SUBPROF(17);\n"))
716
+ damp = implicit and any(damping(m, t) > 0 for t in passive(m))
717
+ if damp or (implicit and actuators(m)):
718
+ add = ""
719
+ if damp:
720
+ add += (" ten_outer(s.L, c_tpas, c_tdampp, NTP, h, lane); // + h d c c' of the tendons' damping "
721
+ "(forest_engine.tendon)\n")
722
+ if implicit and actuators(m):
723
+ add += (" tact_implicit(s, h, lane); // + h kv c c' of the tendon actuators (kv off at the forcerange; "
724
+ "forest_engine.tendon)\n")
725
+ out.append((" __syncwarp();\n CHOL_M_SOLVE(s.L, s.L, s.tmp, lane, s.cbuf);\n",
726
+ " __syncwarp();\n" + add + " CHOL_M_SOLVE(s.L, s.L, s.tmp, lane, s.cbuf);\n"))
727
+ return out
728
+
729
+
730
+ def adj_hooks(m, src):
731
+ """The adjoint's edits: equality's (with adj_tendon after adj_connect, the contacts' first row after the tendon limit
732
+ rows), the implicit tendon damping and actuator kv in A1, the passive force and the tendon actuators in
733
+ adj_compose."""
734
+ out = []
735
+ for a, b in EQ.adj_hooks_connect(m, src):
736
+ if a.startswith("template <bool DBG>\n__device__ __noinline__ void adj_limits("):
737
+ b = _sub(b, " adj_connect(s, lane, jtf);\n}\n", " adj_connect(s, lane, jtf);\n adj_tendon(s, lane, jtf);\n}\n")
738
+ b = ADJ_DEVICE + b
739
+ elif "nlim + NEQR + c + " in b:
740
+ b = _sub(b, "nlim + NEQR + c + ", "nlim + NEQR + tl_rows(s.q) + c + ")
741
+ out.append((a, b))
742
+ from nablaengine.forest_engine import model_hooks
743
+ implicit = model_hooks.integrator(m) == "implicitfast"
744
+ damp = implicit and any(damping(m, t) > 0 for t in passive(m))
745
+ if damp or (implicit and actuators(m)):
746
+ out.append((" s.ny[i] = -s.y[i];\n }\n __syncwarp();\n APROF(APROF_SOLVE_Q);\n",
747
+ " s.ny[i] = -s.y[i];\n }\n"
748
+ " for (int i = lane; i < NV; i += 32) { // - h (d_t c (c . y) + kv c (c . y)) on M's pattern: the "
749
+ "tendons'\n"
750
+ " float acc = 0.f; // implicit damping and actuator kv (forest_engine.tendon)\n"
751
+ + (" for (int p = 0; p < NTP; p++) {\n"
752
+ " const int t = c_tpas[p];\n"
753
+ " const float c = c_tcd[NV * t + i];\n"
754
+ " if (c != 0.f) acc += c_tdamp[t] * c * ten_jv_pat(s.y, t, i);\n"
755
+ " }\n" if damp else "")
756
+ + (" for (int k = 0; k < NTACT; k++) {\n"
757
+ " const int t = c_tat[k], cr = c_tacar[k];\n"
758
+ " const float c = c_tcd[NV * t + i];\n"
759
+ " if (c != 0.f && !((s.kvoff[cr >> 5] >> (cr & 31)) & 1u)) acc += c_takv[k] * c * "
760
+ "ten_jv_pat(s.y, t, i);\n"
761
+ " }\n" if implicit and actuators(m) else "")
762
+ + " s.abar[i] -= h * acc;\n"
763
+ " }\n __syncwarp();\n APROF(APROF_SOLVE_Q);\n"))
764
+ if passive(m) or actuators(m):
765
+ body = ""
766
+ if passive(m):
767
+ body += (" for (int p = 0; p < NTP; p++) { // the passive force: P_q += k_eff c (c . lam), P_v += d c (c . lam)\n"
768
+ " const int t = c_tpas[p];\n"
769
+ " const float c = c_tcd[NV * t + i];\n"
770
+ " if (c == 0.f) continue;\n"
771
+ " float ke;\n"
772
+ " (void)ten_passive_f(s.q, s.v, t, &ke);\n"
773
+ " const float cl = c * ten_jv(s.lam, t);\n"
774
+ " s.Pq[i] += ke * cl;\n"
775
+ " s.Pv[i] += c_tdamp[t] * cl;\n"
776
+ " }\n")
777
+ if actuators(m):
778
+ body += (" for (int k = 0; k < NTACT; k++) { // the tendon actuators: f = kp u - kq L - kv (c . v), lam~ = "
779
+ "c . lam\n"
780
+ " const int t = c_tat[k], cr = c_tacar[k]; // (0 where f is at its forcerange: the carrier dof's "
781
+ "clamp bit)\n"
782
+ " const float c = c_tcd[NV * t + i];\n"
783
+ " if (c == 0.f) continue;\n"
784
+ " const float cl = ten_jv(s.lam, t), lt = ((s.clamp[cr >> 5] >> (cr & 31)) & 1u) ? 0.f : cl;\n"
785
+ " s.Pq[i] += c_takq[k] * c * lt;\n"
786
+ " s.Pv[i] += c_takv[k] * c * (DK_ADJ_CLAMP_KV ? lt : cl);\n"
787
+ " }\n")
788
+ ub = ""
789
+ if actuators(m):
790
+ ub = (" if (lane == 0) // u bar += kp lam~ (ctrl at its ctrlrange: none; the carrier dof's uclamp bit)\n"
791
+ " for (int k = 0; k < NTACT; k++) {\n"
792
+ " const int t = c_tat[k], cr = c_tacar[k];\n"
793
+ " if (((s.clamp[cr >> 5] >> (cr & 31)) & 1u) || ((s.uclamp[cr >> 5] >> (cr & 31)) & 1u)) continue;\n"
794
+ " s.ubar[c_taa[k]] += c_takp[k] * ten_jv(s.lam, t);\n"
795
+ " }\n")
796
+ out.append((" for (int i = lane; i < NV; i += 32) s.vbar[i] -= s.Pv[i];\n",
797
+ " for (int i = lane; i < NV; i += 32) { // the tendons (forest_engine.tendon)\n" + body + " }\n"
798
+ + ub + " __syncwarp();\n"
799
+ " for (int i = lane; i < NV; i += 32) s.vbar[i] -= s.Pv[i];\n"))
800
+ return out
801
+
802
+
803
+ def nrows_max(m):
804
+ """The tendon rows at most: the equality rows and 2 per limited tendon."""
805
+ return len(tendon_eqs(m)) + 2 * len(limited(m))
806
+
807
+
808
+ def solimp_powers(m):
809
+ return ([float(np.float32(r["solimp"][4])) for r in tendon_eqs(m)]
810
+ + [float(np.float32(m.tendon_solimp_lim[t, 4])) for t in limited(m)])
811
+
812
+
813
+ DEV_AT = "template <class T> struct dk_is_ptr { static constexpr bool value = false; };\n"
814
+ SP_CONJ = (" float ts_store[TS_WORDS]; // the tendons' L, J and actuator forces (forest_engine.spatial ts_base: right "
815
+ "after ec_Jrows)\n")
816
+
817
+
818
+ def apply(src, m, nefc_rows):
819
+ """src (adjoint.cuda_source's unit, after model_hooks and elliptic) with the tendon edits (and the equality edits
820
+ of the model's joint / connect equalities) for a model with fixed tendons the engine uses."""
821
+ bad = check(m) + check_actuators(m) + EQ.check(m)
822
+ if bad:
823
+ raise ValueError(f"tendons / equality constraints the forest engine does not support: {bad[:4]}")
824
+ EQ.check_rows(m, nefc_rows, extra=nrows_max(m))
825
+ has_adj = "__device__ __noinline__ void adj_limits(" in src
826
+ pairs = hooks(m) + (adj_hooks(m, src) if has_adj else [])
827
+ if spatial_build(m):
828
+ from nablaengine.forest_engine import spatial
829
+ pairs = spatial.transform(m, pairs, EQ.EC_CONJ, SP_CONJ, DEV_AT) + (spatial.adj_extra() if has_adj else [])
830
+ for a, b in pairs:
831
+ k = src.count(a)
832
+ if a == EQ.EC_CONJ and k == 2:
833
+ src = src.replace(a, b)
834
+ continue
835
+ if k != 1:
836
+ raise RuntimeError(f"forest tendon: anchor found {k} times, expected 1: {a[:100]!r}")
837
+ src = src.replace(a, b)
838
+ from nablaengine.forest_engine import muscle
839
+ if muscle.applies(m):
840
+ src = muscle.apply(src, m)
841
+ if spatial_build(m):
842
+ from nablaengine.forest_engine import spatial
843
+ if spatial.compact_on(m):
844
+ src = spatial.compact(src, m)
845
+ return src