diffneusim 1.0.0__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 (682) hide show
  1. diffneusim/__init__.py +1 -0
  2. diffneusim/_cache.py +42 -0
  3. diffneusim/_paths.py +5 -0
  4. diffneusim/bindings/rew14_ext.cu +115 -0
  5. diffneusim/bindings/soft14_capi.cpp +443 -0
  6. diffneusim/bindings/soft14_engine_ext.cu +596 -0
  7. diffneusim/bindings/soft_capi.cpp +782 -0
  8. diffneusim/bindings/soft_engine_ext.cu +495 -0
  9. diffneusim/core/cpu_engine/build.sh +40 -0
  10. diffneusim/core/cpu_engine/fiber/cuda_runtime.h +445 -0
  11. diffneusim/core/cpu_engine/x14_cpu.cpp +283 -0
  12. diffneusim/core/diff/dual.h +126 -0
  13. diffneusim/core/include/diffneusim/macros.h +35 -0
  14. diffneusim/core/kin/kinematic_tree.h +273 -0
  15. diffneusim/core/math/so3.h +182 -0
  16. diffneusim/core/soft/adj/out_adj.h +102 -0
  17. diffneusim/core/soft/adj/rnea_adj.h +425 -0
  18. diffneusim/core/soft/adj/rows_adj.h +439 -0
  19. diffneusim/core/soft/adj/rows_functor.h +89 -0
  20. diffneusim/core/soft/adj/rows_lanes.h +443 -0
  21. diffneusim/core/soft/adj/shell_adj.h +243 -0
  22. diffneusim/core/soft/adj/tree_adj.h +356 -0
  23. diffneusim/core/soft/collide.h +183 -0
  24. diffneusim/core/soft/gpu/adj14.cuh +233 -0
  25. diffneusim/core/soft/gpu/adj14_mus.cuh +98 -0
  26. diffneusim/core/soft/gpu/adj_shell.cuh +50 -0
  27. diffneusim/core/soft/gpu/adj_tab.cuh +49 -0
  28. diffneusim/core/soft/gpu/body14.cuh +47 -0
  29. diffneusim/core/soft/gpu/chol_rn.cuh +458 -0
  30. diffneusim/core/soft/gpu/chol_small.cuh +123 -0
  31. diffneusim/core/soft/gpu/chol_split.cuh +193 -0
  32. diffneusim/core/soft/gpu/engine_launch.cuh +263 -0
  33. diffneusim/core/soft/gpu/fk_rn.cuh +109 -0
  34. diffneusim/core/soft/gpu/generated/body_019e20820f86_mmfloor.cuh +28 -0
  35. diffneusim/core/soft/gpu/generated/body_62f77a4bb16b_mmfloor.cuh +52 -0
  36. diffneusim/core/soft/gpu/generated/body_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +28 -0
  37. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +28 -0
  38. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +28 -0
  39. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +28 -0
  40. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +28 -0
  41. diffneusim/core/soft/gpu/generated/body_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +52 -0
  42. diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor.cuh +25 -0
  43. diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +25 -0
  44. diffneusim/core/soft/gpu/generated/g1_soft_5db44fd45286.cuh +74 -0
  45. diffneusim/core/soft/gpu/generated/split_62f77a4bb16b_mmfloor.cuh +18 -0
  46. diffneusim/core/soft/gpu/generated/split_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +18 -0
  47. diffneusim/core/soft/gpu/generated/x14_soft_019e20820f86_mmfloor.cuh +123 -0
  48. diffneusim/core/soft/gpu/generated/x14_soft_62f77a4bb16b_mmfloor.cuh +129 -0
  49. diffneusim/core/soft/gpu/generated/x14_soft_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +123 -0
  50. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +123 -0
  51. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +123 -0
  52. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +123 -0
  53. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +123 -0
  54. diffneusim/core/soft/gpu/generated/x14_soft_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +129 -0
  55. diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor.cuh +123 -0
  56. diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +123 -0
  57. diffneusim/core/soft/gpu/k_mus.cuh +1038 -0
  58. diffneusim/core/soft/gpu/k_mus_host.cuh +377 -0
  59. diffneusim/core/soft/gpu/k_pre.cuh +52 -0
  60. diffneusim/core/soft/gpu/kernel_p.cuh +490 -0
  61. diffneusim/core/soft/gpu/kp14.cuh +465 -0
  62. diffneusim/core/soft/gpu/l2v2.cuh +367 -0
  63. diffneusim/core/soft/gpu/l2x14.cuh +319 -0
  64. diffneusim/core/soft/gpu/l3.cuh +1483 -0
  65. diffneusim/core/soft/gpu/model_view.cuh +48 -0
  66. diffneusim/core/soft/gpu/mus_case_fits.h +15 -0
  67. diffneusim/core/soft/gpu/mus_classes.h +182 -0
  68. diffneusim/core/soft/gpu/mus_row_cf.h +44 -0
  69. diffneusim/core/soft/gpu/rew14.cuh +177 -0
  70. diffneusim/core/soft/gpu/rows_ctab.cuh +44 -0
  71. diffneusim/core/soft/gpu/tree_m.cuh +247 -0
  72. diffneusim/core/soft/gpu/x14_engine_kernels.cuh +260 -0
  73. diffneusim/core/soft/gpu/x14_rowcf.h +14 -0
  74. diffneusim/core/soft/hand.h +124 -0
  75. diffneusim/core/soft/impedance.h +115 -0
  76. diffneusim/core/soft/jvp.h +202 -0
  77. diffneusim/core/soft/kin.h +250 -0
  78. diffneusim/core/soft/muscle.h +1208 -0
  79. diffneusim/core/soft/newton.h +371 -0
  80. diffneusim/core/soft/rows.h +176 -0
  81. diffneusim/core/soft/step.h +188 -0
  82. diffneusim/core/soft/tape.h +313 -0
  83. diffneusim/core/soft/x14/collide14.h +69 -0
  84. diffneusim/core/soft/x14/jvp14.h +182 -0
  85. diffneusim/core/soft/x14/law14.h +453 -0
  86. diffneusim/core/soft/x14adj/collide14_adj.h +134 -0
  87. diffneusim/core/soft/x14adj/passive14_adj.h +162 -0
  88. diffneusim/core/soft/x14adj/reward14.h +484 -0
  89. diffneusim/core/soft/x14adj/rows14_adj.h +400 -0
  90. diffneusim/core/soft/x14adj/scan14.h +349 -0
  91. diffneusim/core/soft/x14adj/shell14_adj.h +122 -0
  92. diffneusim/core/soft/x14adj/sweep14.h +255 -0
  93. diffneusim/core/soft/x14adj/tree14_adj.h +500 -0
  94. diffneusim/core/soft/x14adj/x14adj_common.h +96 -0
  95. diffneusim/data/mirror/H1622v2k_geyer_hfdeq.npz +0 -0
  96. diffneusim/data/mirror/H1622v2k_hfd.npz +0 -0
  97. diffneusim/data/mirror/H1622v2k_millard_hfdeq.npz +0 -0
  98. diffneusim/data/mirror/fullbody_contact.npz +0 -0
  99. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard.npz +0 -0
  100. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str.npz +0 -0
  101. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str_rigid.npz +0 -0
  102. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.npz +0 -0
  103. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.npz +0 -0
  104. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq.npz +0 -0
  105. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin.npz +0 -0
  106. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_calf2_pe.npz +0 -0
  107. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  108. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfix.npz +0 -0
  109. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.npz +0 -0
  110. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01.npz +0 -0
  111. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01legs.npz +0 -0
  112. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01lumbar.npz +0 -0
  113. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfix.npz +0 -0
  114. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfixlegs01.npz +0 -0
  115. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
  116. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
  117. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
  118. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
  119. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair.npz +0 -0
  120. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  121. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_hinge.npz +0 -0
  122. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
  123. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
  124. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
  125. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
  126. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_lspine_girdle_osimeq.npz +0 -0
  127. diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_millard.npz +0 -0
  128. diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_osimeq.npz +0 -0
  129. diffneusim/data/mirror/myoleg26_3d_compound_g14eq.npz +0 -0
  130. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq.npz +0 -0
  131. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose.npz +0 -0
  132. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin.npz +0 -0
  133. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30.npz +0 -0
  134. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30.npz +0 -0
  135. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_luispe.npz +0 -0
  136. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_trunk0701.npz +0 -0
  137. diffneusim/data/muscle_fit/wang_mass_volume_14t.json +91 -0
  138. diffneusim/data/muscle_fit/wang_mass_volume_14t_axfix.json +91 -0
  139. diffneusim/data/muscle_fit/wang_mass_volume_14t_axfixlegs01.json +91 -0
  140. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01.json +91 -0
  141. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01legs.json +91 -0
  142. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01lumbar.json +91 -0
  143. diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfix.json +91 -0
  144. diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfixlegs01.json +91 -0
  145. diffneusim/data/muscle_fit/wang_mass_volume_14t_n1.json +91 -0
  146. diffneusim/data/muscle_fit/wang_mass_volume_14t_n1a.json +91 -0
  147. diffneusim/data/muscle_fit/wang_mass_volume_14t_n2.json +91 -0
  148. diffneusim/data/muscle_fit/wang_mass_volume_14t_rom23.json +91 -0
  149. diffneusim/data/reference/musclemimic/myofullbody_mimic_sites.json +261 -0
  150. diffneusim/data/reference/pose3/pose3_scone.json +305 -0
  151. diffneusim/data/reference/pose3/pose3_scone.txt +3 -0
  152. diffneusim/data/reference/pose3/pose3_scone_gait.npz +0 -0
  153. diffneusim/data/reference/pose3/pose3_scone_mirror.npz +0 -0
  154. diffneusim/data/reference/pose3/pose3_scone_stand.npz +0 -0
  155. diffneusim/data/reference/x016run/MD5SUMS +241 -0
  156. diffneusim/data/reference/x016run/x016run_states.txt +240 -0
  157. diffneusim/data/reference/x016run/x016run_v3p00_s0_l0.npz +0 -0
  158. diffneusim/data/reference/x016run/x016run_v3p00_s0_l1.npz +0 -0
  159. diffneusim/data/reference/x016run/x016run_v3p00_s0_l2.npz +0 -0
  160. diffneusim/data/reference/x016run/x016run_v3p00_s0_l3.npz +0 -0
  161. diffneusim/data/reference/x016run/x016run_v3p00_s0_r0.npz +0 -0
  162. diffneusim/data/reference/x016run/x016run_v3p00_s0_r1.npz +0 -0
  163. diffneusim/data/reference/x016run/x016run_v3p00_s0_r2.npz +0 -0
  164. diffneusim/data/reference/x016run/x016run_v3p00_s0_r3.npz +0 -0
  165. diffneusim/data/reference/x016run/x016run_v3p00_s1_l0.npz +0 -0
  166. diffneusim/data/reference/x016run/x016run_v3p00_s1_l1.npz +0 -0
  167. diffneusim/data/reference/x016run/x016run_v3p00_s1_l2.npz +0 -0
  168. diffneusim/data/reference/x016run/x016run_v3p00_s1_l3.npz +0 -0
  169. diffneusim/data/reference/x016run/x016run_v3p00_s1_r0.npz +0 -0
  170. diffneusim/data/reference/x016run/x016run_v3p00_s1_r1.npz +0 -0
  171. diffneusim/data/reference/x016run/x016run_v3p00_s1_r2.npz +0 -0
  172. diffneusim/data/reference/x016run/x016run_v3p00_s1_r3.npz +0 -0
  173. diffneusim/data/reference/x016run/x016run_v3p00_s2_l0.npz +0 -0
  174. diffneusim/data/reference/x016run/x016run_v3p00_s2_l1.npz +0 -0
  175. diffneusim/data/reference/x016run/x016run_v3p00_s2_l2.npz +0 -0
  176. diffneusim/data/reference/x016run/x016run_v3p00_s2_l3.npz +0 -0
  177. diffneusim/data/reference/x016run/x016run_v3p00_s2_r0.npz +0 -0
  178. diffneusim/data/reference/x016run/x016run_v3p00_s2_r1.npz +0 -0
  179. diffneusim/data/reference/x016run/x016run_v3p00_s2_r2.npz +0 -0
  180. diffneusim/data/reference/x016run/x016run_v3p00_s2_r3.npz +0 -0
  181. diffneusim/data/reference/x016run/x016run_v3p00_s3_l0.npz +0 -0
  182. diffneusim/data/reference/x016run/x016run_v3p00_s3_l1.npz +0 -0
  183. diffneusim/data/reference/x016run/x016run_v3p00_s3_l2.npz +0 -0
  184. diffneusim/data/reference/x016run/x016run_v3p00_s3_l3.npz +0 -0
  185. diffneusim/data/reference/x016run/x016run_v3p00_s3_r0.npz +0 -0
  186. diffneusim/data/reference/x016run/x016run_v3p00_s3_r1.npz +0 -0
  187. diffneusim/data/reference/x016run/x016run_v3p00_s3_r2.npz +0 -0
  188. diffneusim/data/reference/x016run/x016run_v3p00_s3_r3.npz +0 -0
  189. diffneusim/data/reference/x016run/x016run_v3p00_s4_l0.npz +0 -0
  190. diffneusim/data/reference/x016run/x016run_v3p00_s4_l1.npz +0 -0
  191. diffneusim/data/reference/x016run/x016run_v3p00_s4_l2.npz +0 -0
  192. diffneusim/data/reference/x016run/x016run_v3p00_s4_l3.npz +0 -0
  193. diffneusim/data/reference/x016run/x016run_v3p00_s4_r0.npz +0 -0
  194. diffneusim/data/reference/x016run/x016run_v3p00_s4_r1.npz +0 -0
  195. diffneusim/data/reference/x016run/x016run_v3p00_s4_r2.npz +0 -0
  196. diffneusim/data/reference/x016run/x016run_v3p00_s4_r3.npz +0 -0
  197. diffneusim/data/reference/x016run/x016run_v3p00_s5_l0.npz +0 -0
  198. diffneusim/data/reference/x016run/x016run_v3p00_s5_l1.npz +0 -0
  199. diffneusim/data/reference/x016run/x016run_v3p00_s5_l2.npz +0 -0
  200. diffneusim/data/reference/x016run/x016run_v3p00_s5_l3.npz +0 -0
  201. diffneusim/data/reference/x016run/x016run_v3p00_s5_r0.npz +0 -0
  202. diffneusim/data/reference/x016run/x016run_v3p00_s5_r1.npz +0 -0
  203. diffneusim/data/reference/x016run/x016run_v3p00_s5_r2.npz +0 -0
  204. diffneusim/data/reference/x016run/x016run_v3p00_s5_r3.npz +0 -0
  205. diffneusim/data/reference/x016run/x016run_v3p00_s6_l0.npz +0 -0
  206. diffneusim/data/reference/x016run/x016run_v3p00_s6_l1.npz +0 -0
  207. diffneusim/data/reference/x016run/x016run_v3p00_s6_l2.npz +0 -0
  208. diffneusim/data/reference/x016run/x016run_v3p00_s6_l3.npz +0 -0
  209. diffneusim/data/reference/x016run/x016run_v3p00_s6_r0.npz +0 -0
  210. diffneusim/data/reference/x016run/x016run_v3p00_s6_r1.npz +0 -0
  211. diffneusim/data/reference/x016run/x016run_v3p00_s6_r2.npz +0 -0
  212. diffneusim/data/reference/x016run/x016run_v3p00_s6_r3.npz +0 -0
  213. diffneusim/data/reference/x016run/x016run_v3p00_s7_l0.npz +0 -0
  214. diffneusim/data/reference/x016run/x016run_v3p00_s7_l1.npz +0 -0
  215. diffneusim/data/reference/x016run/x016run_v3p00_s7_l2.npz +0 -0
  216. diffneusim/data/reference/x016run/x016run_v3p00_s7_l3.npz +0 -0
  217. diffneusim/data/reference/x016run/x016run_v3p00_s7_r0.npz +0 -0
  218. diffneusim/data/reference/x016run/x016run_v3p00_s7_r1.npz +0 -0
  219. diffneusim/data/reference/x016run/x016run_v3p00_s7_r2.npz +0 -0
  220. diffneusim/data/reference/x016run/x016run_v3p00_s7_r3.npz +0 -0
  221. diffneusim/data/reference/x016run/x016run_v3p25_s0_l0.npz +0 -0
  222. diffneusim/data/reference/x016run/x016run_v3p25_s0_l1.npz +0 -0
  223. diffneusim/data/reference/x016run/x016run_v3p25_s0_l2.npz +0 -0
  224. diffneusim/data/reference/x016run/x016run_v3p25_s0_l3.npz +0 -0
  225. diffneusim/data/reference/x016run/x016run_v3p25_s0_r0.npz +0 -0
  226. diffneusim/data/reference/x016run/x016run_v3p25_s0_r1.npz +0 -0
  227. diffneusim/data/reference/x016run/x016run_v3p25_s0_r2.npz +0 -0
  228. diffneusim/data/reference/x016run/x016run_v3p25_s0_r3.npz +0 -0
  229. diffneusim/data/reference/x016run/x016run_v3p25_s1_l0.npz +0 -0
  230. diffneusim/data/reference/x016run/x016run_v3p25_s1_l1.npz +0 -0
  231. diffneusim/data/reference/x016run/x016run_v3p25_s1_l2.npz +0 -0
  232. diffneusim/data/reference/x016run/x016run_v3p25_s1_l3.npz +0 -0
  233. diffneusim/data/reference/x016run/x016run_v3p25_s1_r0.npz +0 -0
  234. diffneusim/data/reference/x016run/x016run_v3p25_s1_r1.npz +0 -0
  235. diffneusim/data/reference/x016run/x016run_v3p25_s1_r2.npz +0 -0
  236. diffneusim/data/reference/x016run/x016run_v3p25_s1_r3.npz +0 -0
  237. diffneusim/data/reference/x016run/x016run_v3p25_s2_l0.npz +0 -0
  238. diffneusim/data/reference/x016run/x016run_v3p25_s2_l1.npz +0 -0
  239. diffneusim/data/reference/x016run/x016run_v3p25_s2_l2.npz +0 -0
  240. diffneusim/data/reference/x016run/x016run_v3p25_s2_l3.npz +0 -0
  241. diffneusim/data/reference/x016run/x016run_v3p25_s2_r0.npz +0 -0
  242. diffneusim/data/reference/x016run/x016run_v3p25_s2_r1.npz +0 -0
  243. diffneusim/data/reference/x016run/x016run_v3p25_s2_r2.npz +0 -0
  244. diffneusim/data/reference/x016run/x016run_v3p25_s2_r3.npz +0 -0
  245. diffneusim/data/reference/x016run/x016run_v3p25_s3_l0.npz +0 -0
  246. diffneusim/data/reference/x016run/x016run_v3p25_s3_l1.npz +0 -0
  247. diffneusim/data/reference/x016run/x016run_v3p25_s3_l2.npz +0 -0
  248. diffneusim/data/reference/x016run/x016run_v3p25_s3_l3.npz +0 -0
  249. diffneusim/data/reference/x016run/x016run_v3p25_s3_r0.npz +0 -0
  250. diffneusim/data/reference/x016run/x016run_v3p25_s3_r1.npz +0 -0
  251. diffneusim/data/reference/x016run/x016run_v3p25_s3_r2.npz +0 -0
  252. diffneusim/data/reference/x016run/x016run_v3p25_s3_r3.npz +0 -0
  253. diffneusim/data/reference/x016run/x016run_v3p25_s4_l0.npz +0 -0
  254. diffneusim/data/reference/x016run/x016run_v3p25_s4_l1.npz +0 -0
  255. diffneusim/data/reference/x016run/x016run_v3p25_s4_l2.npz +0 -0
  256. diffneusim/data/reference/x016run/x016run_v3p25_s4_l3.npz +0 -0
  257. diffneusim/data/reference/x016run/x016run_v3p25_s4_r0.npz +0 -0
  258. diffneusim/data/reference/x016run/x016run_v3p25_s4_r1.npz +0 -0
  259. diffneusim/data/reference/x016run/x016run_v3p25_s4_r2.npz +0 -0
  260. diffneusim/data/reference/x016run/x016run_v3p25_s4_r3.npz +0 -0
  261. diffneusim/data/reference/x016run/x016run_v3p25_s5_l0.npz +0 -0
  262. diffneusim/data/reference/x016run/x016run_v3p25_s5_l1.npz +0 -0
  263. diffneusim/data/reference/x016run/x016run_v3p25_s5_l2.npz +0 -0
  264. diffneusim/data/reference/x016run/x016run_v3p25_s5_l3.npz +0 -0
  265. diffneusim/data/reference/x016run/x016run_v3p25_s5_r0.npz +0 -0
  266. diffneusim/data/reference/x016run/x016run_v3p25_s5_r1.npz +0 -0
  267. diffneusim/data/reference/x016run/x016run_v3p25_s5_r2.npz +0 -0
  268. diffneusim/data/reference/x016run/x016run_v3p25_s5_r3.npz +0 -0
  269. diffneusim/data/reference/x016run/x016run_v3p25_s6_l0.npz +0 -0
  270. diffneusim/data/reference/x016run/x016run_v3p25_s6_l1.npz +0 -0
  271. diffneusim/data/reference/x016run/x016run_v3p25_s6_l2.npz +0 -0
  272. diffneusim/data/reference/x016run/x016run_v3p25_s6_l3.npz +0 -0
  273. diffneusim/data/reference/x016run/x016run_v3p25_s6_r0.npz +0 -0
  274. diffneusim/data/reference/x016run/x016run_v3p25_s6_r1.npz +0 -0
  275. diffneusim/data/reference/x016run/x016run_v3p25_s6_r2.npz +0 -0
  276. diffneusim/data/reference/x016run/x016run_v3p25_s6_r3.npz +0 -0
  277. diffneusim/data/reference/x016run/x016run_v3p25_s7_l0.npz +0 -0
  278. diffneusim/data/reference/x016run/x016run_v3p25_s7_l1.npz +0 -0
  279. diffneusim/data/reference/x016run/x016run_v3p25_s7_l2.npz +0 -0
  280. diffneusim/data/reference/x016run/x016run_v3p25_s7_l3.npz +0 -0
  281. diffneusim/data/reference/x016run/x016run_v3p25_s7_r0.npz +0 -0
  282. diffneusim/data/reference/x016run/x016run_v3p25_s7_r1.npz +0 -0
  283. diffneusim/data/reference/x016run/x016run_v3p25_s7_r2.npz +0 -0
  284. diffneusim/data/reference/x016run/x016run_v3p25_s7_r3.npz +0 -0
  285. diffneusim/data/reference/x016run/x016run_v3p50_s0_l0.npz +0 -0
  286. diffneusim/data/reference/x016run/x016run_v3p50_s0_l1.npz +0 -0
  287. diffneusim/data/reference/x016run/x016run_v3p50_s0_l2.npz +0 -0
  288. diffneusim/data/reference/x016run/x016run_v3p50_s0_l3.npz +0 -0
  289. diffneusim/data/reference/x016run/x016run_v3p50_s0_r0.npz +0 -0
  290. diffneusim/data/reference/x016run/x016run_v3p50_s0_r1.npz +0 -0
  291. diffneusim/data/reference/x016run/x016run_v3p50_s0_r2.npz +0 -0
  292. diffneusim/data/reference/x016run/x016run_v3p50_s0_r3.npz +0 -0
  293. diffneusim/data/reference/x016run/x016run_v3p50_s1_l0.npz +0 -0
  294. diffneusim/data/reference/x016run/x016run_v3p50_s1_l1.npz +0 -0
  295. diffneusim/data/reference/x016run/x016run_v3p50_s1_l2.npz +0 -0
  296. diffneusim/data/reference/x016run/x016run_v3p50_s1_l3.npz +0 -0
  297. diffneusim/data/reference/x016run/x016run_v3p50_s1_r0.npz +0 -0
  298. diffneusim/data/reference/x016run/x016run_v3p50_s1_r1.npz +0 -0
  299. diffneusim/data/reference/x016run/x016run_v3p50_s1_r2.npz +0 -0
  300. diffneusim/data/reference/x016run/x016run_v3p50_s1_r3.npz +0 -0
  301. diffneusim/data/reference/x016run/x016run_v3p50_s2_l0.npz +0 -0
  302. diffneusim/data/reference/x016run/x016run_v3p50_s2_l1.npz +0 -0
  303. diffneusim/data/reference/x016run/x016run_v3p50_s2_l2.npz +0 -0
  304. diffneusim/data/reference/x016run/x016run_v3p50_s2_l3.npz +0 -0
  305. diffneusim/data/reference/x016run/x016run_v3p50_s2_r0.npz +0 -0
  306. diffneusim/data/reference/x016run/x016run_v3p50_s2_r1.npz +0 -0
  307. diffneusim/data/reference/x016run/x016run_v3p50_s2_r2.npz +0 -0
  308. diffneusim/data/reference/x016run/x016run_v3p50_s2_r3.npz +0 -0
  309. diffneusim/data/reference/x016run/x016run_v3p50_s3_l0.npz +0 -0
  310. diffneusim/data/reference/x016run/x016run_v3p50_s3_l1.npz +0 -0
  311. diffneusim/data/reference/x016run/x016run_v3p50_s3_l2.npz +0 -0
  312. diffneusim/data/reference/x016run/x016run_v3p50_s3_l3.npz +0 -0
  313. diffneusim/data/reference/x016run/x016run_v3p50_s3_r0.npz +0 -0
  314. diffneusim/data/reference/x016run/x016run_v3p50_s3_r1.npz +0 -0
  315. diffneusim/data/reference/x016run/x016run_v3p50_s3_r2.npz +0 -0
  316. diffneusim/data/reference/x016run/x016run_v3p50_s3_r3.npz +0 -0
  317. diffneusim/data/reference/x016run/x016run_v3p50_s5_l0.npz +0 -0
  318. diffneusim/data/reference/x016run/x016run_v3p50_s5_l1.npz +0 -0
  319. diffneusim/data/reference/x016run/x016run_v3p50_s5_l2.npz +0 -0
  320. diffneusim/data/reference/x016run/x016run_v3p50_s5_l3.npz +0 -0
  321. diffneusim/data/reference/x016run/x016run_v3p50_s5_r0.npz +0 -0
  322. diffneusim/data/reference/x016run/x016run_v3p50_s5_r1.npz +0 -0
  323. diffneusim/data/reference/x016run/x016run_v3p50_s5_r2.npz +0 -0
  324. diffneusim/data/reference/x016run/x016run_v3p50_s5_r3.npz +0 -0
  325. diffneusim/data/reference/x016run/x016run_v3p50_s6_l0.npz +0 -0
  326. diffneusim/data/reference/x016run/x016run_v3p50_s6_l1.npz +0 -0
  327. diffneusim/data/reference/x016run/x016run_v3p50_s6_l2.npz +0 -0
  328. diffneusim/data/reference/x016run/x016run_v3p50_s6_l3.npz +0 -0
  329. diffneusim/data/reference/x016run/x016run_v3p50_s6_r0.npz +0 -0
  330. diffneusim/data/reference/x016run/x016run_v3p50_s6_r1.npz +0 -0
  331. diffneusim/data/reference/x016run/x016run_v3p50_s6_r2.npz +0 -0
  332. diffneusim/data/reference/x016run/x016run_v3p50_s6_r3.npz +0 -0
  333. diffneusim/data/reference/x016run/x016run_v3p50_s7_l0.npz +0 -0
  334. diffneusim/data/reference/x016run/x016run_v3p50_s7_l1.npz +0 -0
  335. diffneusim/data/reference/x016run/x016run_v3p50_s7_l2.npz +0 -0
  336. diffneusim/data/reference/x016run/x016run_v3p50_s7_l3.npz +0 -0
  337. diffneusim/data/reference/x016run/x016run_v3p50_s7_r0.npz +0 -0
  338. diffneusim/data/reference/x016run/x016run_v3p50_s7_r1.npz +0 -0
  339. diffneusim/data/reference/x016run/x016run_v3p50_s7_r2.npz +0 -0
  340. diffneusim/data/reference/x016run/x016run_v3p50_s7_r3.npz +0 -0
  341. diffneusim/data/reference/x016run/x016run_v3p75_s0_l0.npz +0 -0
  342. diffneusim/data/reference/x016run/x016run_v3p75_s0_l1.npz +0 -0
  343. diffneusim/data/reference/x016run/x016run_v3p75_s0_l2.npz +0 -0
  344. diffneusim/data/reference/x016run/x016run_v3p75_s0_l3.npz +0 -0
  345. diffneusim/data/reference/x016run/x016run_v3p75_s0_r0.npz +0 -0
  346. diffneusim/data/reference/x016run/x016run_v3p75_s0_r1.npz +0 -0
  347. diffneusim/data/reference/x016run/x016run_v3p75_s0_r2.npz +0 -0
  348. diffneusim/data/reference/x016run/x016run_v3p75_s0_r3.npz +0 -0
  349. diffneusim/data/reference/x016run/x016run_v3p75_s1_l0.npz +0 -0
  350. diffneusim/data/reference/x016run/x016run_v3p75_s1_l1.npz +0 -0
  351. diffneusim/data/reference/x016run/x016run_v3p75_s1_l2.npz +0 -0
  352. diffneusim/data/reference/x016run/x016run_v3p75_s1_l3.npz +0 -0
  353. diffneusim/data/reference/x016run/x016run_v3p75_s1_r0.npz +0 -0
  354. diffneusim/data/reference/x016run/x016run_v3p75_s1_r1.npz +0 -0
  355. diffneusim/data/reference/x016run/x016run_v3p75_s1_r2.npz +0 -0
  356. diffneusim/data/reference/x016run/x016run_v3p75_s1_r3.npz +0 -0
  357. diffneusim/data/reference/x016run/x016run_v3p75_s2_l0.npz +0 -0
  358. diffneusim/data/reference/x016run/x016run_v3p75_s2_l1.npz +0 -0
  359. diffneusim/data/reference/x016run/x016run_v3p75_s2_l2.npz +0 -0
  360. diffneusim/data/reference/x016run/x016run_v3p75_s2_l3.npz +0 -0
  361. diffneusim/data/reference/x016run/x016run_v3p75_s2_r0.npz +0 -0
  362. diffneusim/data/reference/x016run/x016run_v3p75_s2_r1.npz +0 -0
  363. diffneusim/data/reference/x016run/x016run_v3p75_s2_r2.npz +0 -0
  364. diffneusim/data/reference/x016run/x016run_v3p75_s2_r3.npz +0 -0
  365. diffneusim/data/reference/x016run/x016run_v3p75_s3_l0.npz +0 -0
  366. diffneusim/data/reference/x016run/x016run_v3p75_s3_l1.npz +0 -0
  367. diffneusim/data/reference/x016run/x016run_v3p75_s3_l2.npz +0 -0
  368. diffneusim/data/reference/x016run/x016run_v3p75_s3_l3.npz +0 -0
  369. diffneusim/data/reference/x016run/x016run_v3p75_s3_r0.npz +0 -0
  370. diffneusim/data/reference/x016run/x016run_v3p75_s3_r1.npz +0 -0
  371. diffneusim/data/reference/x016run/x016run_v3p75_s3_r2.npz +0 -0
  372. diffneusim/data/reference/x016run/x016run_v3p75_s3_r3.npz +0 -0
  373. diffneusim/data/reference/x016run/x016run_v3p75_s5_l0.npz +0 -0
  374. diffneusim/data/reference/x016run/x016run_v3p75_s5_l1.npz +0 -0
  375. diffneusim/data/reference/x016run/x016run_v3p75_s5_l2.npz +0 -0
  376. diffneusim/data/reference/x016run/x016run_v3p75_s5_l3.npz +0 -0
  377. diffneusim/data/reference/x016run/x016run_v3p75_s5_r0.npz +0 -0
  378. diffneusim/data/reference/x016run/x016run_v3p75_s5_r1.npz +0 -0
  379. diffneusim/data/reference/x016run/x016run_v3p75_s5_r2.npz +0 -0
  380. diffneusim/data/reference/x016run/x016run_v3p75_s5_r3.npz +0 -0
  381. diffneusim/data/reference/x016run/x016run_v3p75_s6_l0.npz +0 -0
  382. diffneusim/data/reference/x016run/x016run_v3p75_s6_l1.npz +0 -0
  383. diffneusim/data/reference/x016run/x016run_v3p75_s6_l2.npz +0 -0
  384. diffneusim/data/reference/x016run/x016run_v3p75_s6_l3.npz +0 -0
  385. diffneusim/data/reference/x016run/x016run_v3p75_s6_r0.npz +0 -0
  386. diffneusim/data/reference/x016run/x016run_v3p75_s6_r1.npz +0 -0
  387. diffneusim/data/reference/x016run/x016run_v3p75_s6_r2.npz +0 -0
  388. diffneusim/data/reference/x016run/x016run_v3p75_s6_r3.npz +0 -0
  389. diffneusim/data/reference/x016run/x016run_v3p75_s7_l0.npz +0 -0
  390. diffneusim/data/reference/x016run/x016run_v3p75_s7_l1.npz +0 -0
  391. diffneusim/data/reference/x016run/x016run_v3p75_s7_l2.npz +0 -0
  392. diffneusim/data/reference/x016run/x016run_v3p75_s7_l3.npz +0 -0
  393. diffneusim/data/reference/x016run/x016run_v3p75_s7_r0.npz +0 -0
  394. diffneusim/data/reference/x016run/x016run_v3p75_s7_r1.npz +0 -0
  395. diffneusim/data/reference/x016run/x016run_v3p75_s7_r2.npz +0 -0
  396. diffneusim/data/reference/x016run/x016run_v3p75_s7_r3.npz +0 -0
  397. diffneusim/data/state_prior/lumbar_poly_fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  398. diffneusim/engine/__init__.py +0 -0
  399. diffneusim/engine/build_tag.py +52 -0
  400. diffneusim/engine/case_tables.py +46 -0
  401. diffneusim/engine/d16_body.py +80 -0
  402. diffneusim/engine/engine14.py +367 -0
  403. diffneusim/engine/gen_split.py +159 -0
  404. diffneusim/engine/hand_format.py +69 -0
  405. diffneusim/engine/live14.py +149 -0
  406. diffneusim/engine/phase_b_tree.py +137 -0
  407. diffneusim/engine/soft14.py +130 -0
  408. diffneusim/engine/soft_capi.py +373 -0
  409. diffneusim/engine/soft_engine.py +165 -0
  410. diffneusim/engine/step14.py +132 -0
  411. diffneusim/engine/tape_format.py +89 -0
  412. diffneusim/engine/x14cpu.py +163 -0
  413. diffneusim/env/__init__.py +0 -0
  414. diffneusim/env/absent.py +20 -0
  415. diffneusim/env/cpu14.py +105 -0
  416. diffneusim/env/e0loop14.py +224 -0
  417. diffneusim/env/env14.py +568 -0
  418. diffneusim/env/kin_contact14.py +193 -0
  419. diffneusim/env/mimic_sites_x14.json +366 -0
  420. diffneusim/env/old_count.py +78 -0
  421. diffneusim/env/rew14.py +114 -0
  422. diffneusim/env/rew14_hook.py +105 -0
  423. diffneusim/g1/__init__.py +1 -0
  424. diffneusim/g1/arm_a2.py +165 -0
  425. diffneusim/g1/arm_a3.py +576 -0
  426. diffneusim/g1/read_a3.py +79 -0
  427. diffneusim/g1/rg1_read.py +89 -0
  428. diffneusim/model/__init__.py +66 -0
  429. diffneusim/model/case.py +17 -0
  430. diffneusim/model/dnmodel.py +79 -0
  431. diffneusim/model/fuse_fixed.py +281 -0
  432. diffneusim/model/monitor.py +834 -0
  433. diffneusim/models/BODIES.toml +48 -0
  434. diffneusim/models/MANIFEST.toml +979 -0
  435. diffneusim/models/cases/G290/case.bin +0 -0
  436. diffneusim/models/cases/G290/case.json +1 -0
  437. diffneusim/models/cases/G356-SRC/case.bin +0 -0
  438. diffneusim/models/cases/G356-SRC/case.json +1 -0
  439. diffneusim/models/cases/G416/case.bin +0 -0
  440. diffneusim/models/cases/G416/case.json +1 -0
  441. diffneusim/models/cases/M290C-SRC/case.bin +0 -0
  442. diffneusim/models/cases/M290C-SRC/case.json +1 -0
  443. diffneusim/models/cases/M290R-SRC/case.bin +0 -0
  444. diffneusim/models/cases/M290R-SRC/case.json +1 -0
  445. diffneusim/models/cases/M356C-SRC/case.bin +0 -0
  446. diffneusim/models/cases/M356C-SRC/case.json +1 -0
  447. diffneusim/models/cases/M356R-SRC/case.bin +0 -0
  448. diffneusim/models/cases/M356R-SRC/case.json +1 -0
  449. diffneusim/models/cases/M416C-SRC/case.bin +0 -0
  450. diffneusim/models/cases/M416C-SRC/case.json +1 -0
  451. diffneusim/models/derived/d16_expanded_62f77a4bb16b1e67_mmfloor.xml +673 -0
  452. diffneusim/models/derived/d16_expanded_a1e8b196b2cd7b3c_mmfloor.xml +673 -0
  453. diffneusim/models/derived/d16_soft_law_019e20820f8633b9_mmfloor.json +7844 -0
  454. diffneusim/models/derived/d16_soft_law_62f77a4bb16b1e67_mmfloor.json +16855 -0
  455. diffneusim/models/derived/d16_soft_law_77dbb7213f26e821_mmfloor_rampsb3l_n6t12.json +7883 -0
  456. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rampsb3l_n6t12.json +7883 -0
  457. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsd05_n6t12.json +7868 -0
  458. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsdef_n6t12.json +7868 -0
  459. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsmjd_n6t12.json +7868 -0
  460. diffneusim/models/derived/d16_soft_law_a1e8b196b2cd7b3c_mmfloor_rampsb3l_n6t12.json +16894 -0
  461. diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor.json +12655 -0
  462. diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor_rampsb3l_n6t12.json +12700 -0
  463. diffneusim/models/derived/unitree_g1_soft_law.json +15580 -0
  464. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +28913 -0
  465. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  466. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +29202 -0
  467. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
  468. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.dnmodel +1 -0
  469. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  470. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  471. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +46970 -0
  472. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  473. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  474. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  475. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +38570 -0
  476. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  477. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +38923 -0
  478. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
  479. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  480. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  481. diffneusim/models/fullbody_meshes/1mc.stl +0 -0
  482. diffneusim/models/fullbody_meshes/2distph.stl +0 -0
  483. diffneusim/models/fullbody_meshes/2mc.stl +0 -0
  484. diffneusim/models/fullbody_meshes/2midph.stl +0 -0
  485. diffneusim/models/fullbody_meshes/2proxph.stl +0 -0
  486. diffneusim/models/fullbody_meshes/3distph.stl +0 -0
  487. diffneusim/models/fullbody_meshes/3mc.stl +0 -0
  488. diffneusim/models/fullbody_meshes/3midph.stl +0 -0
  489. diffneusim/models/fullbody_meshes/3proxph.stl +0 -0
  490. diffneusim/models/fullbody_meshes/4distph.stl +0 -0
  491. diffneusim/models/fullbody_meshes/4mc.stl +0 -0
  492. diffneusim/models/fullbody_meshes/4midph.stl +0 -0
  493. diffneusim/models/fullbody_meshes/4proxph.stl +0 -0
  494. diffneusim/models/fullbody_meshes/5distph.stl +0 -0
  495. diffneusim/models/fullbody_meshes/5mc.stl +0 -0
  496. diffneusim/models/fullbody_meshes/5midph.stl +0 -0
  497. diffneusim/models/fullbody_meshes/5proxph.stl +0 -0
  498. diffneusim/models/fullbody_meshes/NOTICE +2 -0
  499. diffneusim/models/fullbody_meshes/capitate.stl +0 -0
  500. diffneusim/models/fullbody_meshes/clavicle.stl +0 -0
  501. diffneusim/models/fullbody_meshes/hamate.stl +0 -0
  502. diffneusim/models/fullbody_meshes/hat_cervical.stl +0 -0
  503. diffneusim/models/fullbody_meshes/hat_jaw.stl +0 -0
  504. diffneusim/models/fullbody_meshes/hat_skull.stl +0 -0
  505. diffneusim/models/fullbody_meshes/humerus.stl +0 -0
  506. diffneusim/models/fullbody_meshes/l_bofoot.stl +0 -0
  507. diffneusim/models/fullbody_meshes/l_femur.stl +0 -0
  508. diffneusim/models/fullbody_meshes/l_fibula.stl +0 -0
  509. diffneusim/models/fullbody_meshes/l_foot.stl +0 -0
  510. diffneusim/models/fullbody_meshes/l_patella.stl +0 -0
  511. diffneusim/models/fullbody_meshes/l_pelvis.stl +0 -0
  512. diffneusim/models/fullbody_meshes/l_talus.stl +0 -0
  513. diffneusim/models/fullbody_meshes/l_tibia.stl +0 -0
  514. diffneusim/models/fullbody_meshes/lumbar1.stl +0 -0
  515. diffneusim/models/fullbody_meshes/lumbar2.stl +0 -0
  516. diffneusim/models/fullbody_meshes/lumbar3.stl +0 -0
  517. diffneusim/models/fullbody_meshes/lumbar4.stl +0 -0
  518. diffneusim/models/fullbody_meshes/lumbar5.stl +0 -0
  519. diffneusim/models/fullbody_meshes/lunate.stl +0 -0
  520. diffneusim/models/fullbody_meshes/pisiform.stl +0 -0
  521. diffneusim/models/fullbody_meshes/r_bofoot.stl +0 -0
  522. diffneusim/models/fullbody_meshes/r_femur.stl +0 -0
  523. diffneusim/models/fullbody_meshes/r_fibula.stl +0 -0
  524. diffneusim/models/fullbody_meshes/r_foot.stl +0 -0
  525. diffneusim/models/fullbody_meshes/r_patella.stl +0 -0
  526. diffneusim/models/fullbody_meshes/r_pelvis.stl +0 -0
  527. diffneusim/models/fullbody_meshes/r_talus.stl +0 -0
  528. diffneusim/models/fullbody_meshes/r_tibia.stl +0 -0
  529. diffneusim/models/fullbody_meshes/radius.stl +0 -0
  530. diffneusim/models/fullbody_meshes/sacrum.stl +0 -0
  531. diffneusim/models/fullbody_meshes/scaphoid.stl +0 -0
  532. diffneusim/models/fullbody_meshes/scapula.stl +0 -0
  533. diffneusim/models/fullbody_meshes/thoracic10_s.stl +0 -0
  534. diffneusim/models/fullbody_meshes/thoracic11_s.stl +0 -0
  535. diffneusim/models/fullbody_meshes/thoracic12_s.stl +0 -0
  536. diffneusim/models/fullbody_meshes/thoracic1_s.stl +0 -0
  537. diffneusim/models/fullbody_meshes/thoracic2_s.stl +0 -0
  538. diffneusim/models/fullbody_meshes/thoracic3_s.stl +0 -0
  539. diffneusim/models/fullbody_meshes/thoracic4_s.stl +0 -0
  540. diffneusim/models/fullbody_meshes/thoracic5_s.stl +0 -0
  541. diffneusim/models/fullbody_meshes/thoracic6_s.stl +0 -0
  542. diffneusim/models/fullbody_meshes/thoracic7_s.stl +0 -0
  543. diffneusim/models/fullbody_meshes/thoracic8_s.stl +0 -0
  544. diffneusim/models/fullbody_meshes/thoracic9_s.stl +0 -0
  545. diffneusim/models/fullbody_meshes/thorax.stl +0 -0
  546. diffneusim/models/fullbody_meshes/thumbdist.stl +0 -0
  547. diffneusim/models/fullbody_meshes/thumbprox.stl +0 -0
  548. diffneusim/models/fullbody_meshes/trapezium.stl +0 -0
  549. diffneusim/models/fullbody_meshes/trapezoid.stl +0 -0
  550. diffneusim/models/fullbody_meshes/triquetrum.stl +0 -0
  551. diffneusim/models/fullbody_meshes/ulna.stl +0 -0
  552. diffneusim/models/source/myo_fullbody/UPSTREAM.md +91 -0
  553. diffneusim/models/source/myoleg/UPSTREAM.md +52 -0
  554. diffneusim/models/source/unitree_g1/LICENSE.mjlab +202 -0
  555. diffneusim/models/source/unitree_g1/UPSTREAM.md +38 -0
  556. diffneusim/models/source/unitree_g1/assets/head_link.STL +0 -0
  557. diffneusim/models/source/unitree_g1/assets/left_ankle_pitch_link.STL +0 -0
  558. diffneusim/models/source/unitree_g1/assets/left_ankle_roll_link.STL +0 -0
  559. diffneusim/models/source/unitree_g1/assets/left_elbow_link.STL +0 -0
  560. diffneusim/models/source/unitree_g1/assets/left_hip_pitch_link.STL +0 -0
  561. diffneusim/models/source/unitree_g1/assets/left_hip_roll_link.STL +0 -0
  562. diffneusim/models/source/unitree_g1/assets/left_hip_yaw_link.STL +0 -0
  563. diffneusim/models/source/unitree_g1/assets/left_knee_link.STL +0 -0
  564. diffneusim/models/source/unitree_g1/assets/left_rubber_hand.STL +0 -0
  565. diffneusim/models/source/unitree_g1/assets/left_shoulder_pitch_link.STL +0 -0
  566. diffneusim/models/source/unitree_g1/assets/left_shoulder_roll_link.STL +0 -0
  567. diffneusim/models/source/unitree_g1/assets/left_shoulder_yaw_link.STL +0 -0
  568. diffneusim/models/source/unitree_g1/assets/left_wrist_pitch_link.STL +0 -0
  569. diffneusim/models/source/unitree_g1/assets/left_wrist_roll_link.STL +0 -0
  570. diffneusim/models/source/unitree_g1/assets/left_wrist_yaw_link.STL +0 -0
  571. diffneusim/models/source/unitree_g1/assets/logo_link.STL +0 -0
  572. diffneusim/models/source/unitree_g1/assets/pelvis.STL +0 -0
  573. diffneusim/models/source/unitree_g1/assets/pelvis_contour_link.STL +0 -0
  574. diffneusim/models/source/unitree_g1/assets/right_ankle_pitch_link.STL +0 -0
  575. diffneusim/models/source/unitree_g1/assets/right_ankle_roll_link.STL +0 -0
  576. diffneusim/models/source/unitree_g1/assets/right_elbow_link.STL +0 -0
  577. diffneusim/models/source/unitree_g1/assets/right_hip_pitch_link.STL +0 -0
  578. diffneusim/models/source/unitree_g1/assets/right_hip_roll_link.STL +0 -0
  579. diffneusim/models/source/unitree_g1/assets/right_hip_yaw_link.STL +0 -0
  580. diffneusim/models/source/unitree_g1/assets/right_knee_link.STL +0 -0
  581. diffneusim/models/source/unitree_g1/assets/right_rubber_hand.STL +0 -0
  582. diffneusim/models/source/unitree_g1/assets/right_shoulder_pitch_link.STL +0 -0
  583. diffneusim/models/source/unitree_g1/assets/right_shoulder_roll_link.STL +0 -0
  584. diffneusim/models/source/unitree_g1/assets/right_shoulder_yaw_link.STL +0 -0
  585. diffneusim/models/source/unitree_g1/assets/right_wrist_pitch_link.STL +0 -0
  586. diffneusim/models/source/unitree_g1/assets/right_wrist_roll_link.STL +0 -0
  587. diffneusim/models/source/unitree_g1/assets/right_wrist_yaw_link.STL +0 -0
  588. diffneusim/models/source/unitree_g1/assets/torso_link_rev_1_0.STL +0 -0
  589. diffneusim/models/source/unitree_g1/assets/waist_roll_link_rev_1_0.STL +0 -0
  590. diffneusim/models/source/unitree_g1/assets/waist_yaw_link_rev_1_0.STL +0 -0
  591. diffneusim/models/source/unitree_g1/dump_mjlab_reference.py +30 -0
  592. diffneusim/models/source/unitree_g1/g1.xml +308 -0
  593. diffneusim/models/source/unitree_g1/g1_constants.py +298 -0
  594. diffneusim/models/source/unitree_g1/mjlab_compiled_reference.json +857 -0
  595. diffneusim/models/unitree_g1.dnmodel +4393 -0
  596. diffneusim/models/unitree_g1_selfcol.dnmodel +20824 -0
  597. diffneusim/rl/__init__.py +2 -0
  598. diffneusim/rl/dynsyn_layer.py +146 -0
  599. diffneusim/rl/footstep_plan.py +337 -0
  600. diffneusim/rl/g1_bm_env.py +572 -0
  601. diffneusim/rl/g1_bm_eval.py +168 -0
  602. diffneusim/rl/g1_bm_fused.py +275 -0
  603. diffneusim/rl/g1_bm_ppo.py +622 -0
  604. diffneusim/rl/g1_bm_sapo.py +551 -0
  605. diffneusim/rl/g1_ppo.py +395 -0
  606. diffneusim/rl/g1_sapo_soft.py +240 -0
  607. diffneusim/rl/g1_soft_env.py +452 -0
  608. diffneusim/rl/g1_soft_grad.py +145 -0
  609. diffneusim/rl/geyer_curves_torch.py +108 -0
  610. diffneusim/rl/gpu_fullbody_vec_env.py +1241 -0
  611. diffneusim/rl/imitation.py +2027 -0
  612. diffneusim/rl/imitation_reward_v2.py +248 -0
  613. diffneusim/rl/imitation_reward_v3.py +349 -0
  614. diffneusim/rl/latent_task.py +175 -0
  615. diffneusim/rl/llc_reward.py +316 -0
  616. diffneusim/rl/millard_curves_torch.py +154 -0
  617. diffneusim/rl/mirror_symmetry.py +212 -0
  618. diffneusim/rl/model_path.py +35 -0
  619. diffneusim/rl/mvae_recon.py +123 -0
  620. diffneusim/rl/nets_shac.py +599 -0
  621. diffneusim/rl/reset_pool.py +154 -0
  622. diffneusim/rl/sapo_capture.py +873 -0
  623. diffneusim/rl/sapo_vec.py +1051 -0
  624. diffneusim/rl/shac_vec.py +346 -0
  625. diffneusim/rl/state_prior.py +151 -0
  626. diffneusim/rl/step_library.py +105 -0
  627. diffneusim/rl/task_walk_env.py +1793 -0
  628. diffneusim/rl/task_walk_reward.py +3300 -0
  629. diffneusim/run.py +23 -0
  630. diffneusim/run_env.py +46 -0
  631. diffneusim/tasks/__init__.py +147 -0
  632. diffneusim/tasks/legacy_names.py +63 -0
  633. diffneusim/tasks/paths.py +79 -0
  634. diffneusim/tasks/settings.py +202 -0
  635. diffneusim/third_party/instantmimic_947430ee/LICENSE +202 -0
  636. diffneusim/third_party/instantmimic_947430ee/NOTICE +19 -0
  637. diffneusim/third_party/instantmimic_947430ee/README.md +31 -0
  638. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/benchmark_protocol.py +106 -0
  639. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/metrics.py +214 -0
  640. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/reference.py +513 -0
  641. diffneusim/third_party/instantmimic_947430ee/instantmimic/motion/quaternion.py +193 -0
  642. diffneusim/train/__init__.py +0 -0
  643. diffneusim/train/eval_ckpt.py +239 -0
  644. diffneusim/train/eval_mimic.py +133 -0
  645. diffneusim/train/gait_report.py +203 -0
  646. diffneusim/train/gcot_chain.py +51 -0
  647. diffneusim/train/levers.py +135 -0
  648. diffneusim/train/masked_reset.py +314 -0
  649. diffneusim/train/rl_algorithm_suite.py +917 -0
  650. diffneusim/train/train14.py +240 -0
  651. diffneusim/train/train_tw14.py +674 -0
  652. diffneusim/viz/__init__.py +5 -0
  653. diffneusim/viz/__main__.py +41 -0
  654. diffneusim/viz/camera.py +115 -0
  655. diffneusim/viz/dnrec.py +118 -0
  656. diffneusim/viz/dnrec_io.py +686 -0
  657. diffneusim/viz/hud.py +565 -0
  658. diffneusim/viz/meshes.py +458 -0
  659. diffneusim/viz/play.py +237 -0
  660. diffneusim/viz/record.py +74 -0
  661. diffneusim/viz/render.py +1402 -0
  662. diffneusim/viz/renderer.py +268 -0
  663. diffneusim/viz/rl_env_render.py +635 -0
  664. diffneusim/viz/snapshot.py +54 -0
  665. diffneusim/viz/strobe.py +124 -0
  666. diffneusim/viz/to_mp4.py +58 -0
  667. diffneusim/viz/ui.py +481 -0
  668. diffneusim/viz/viewer.py +2086 -0
  669. diffneusim-1.0.0.dist-info/METADATA +226 -0
  670. diffneusim-1.0.0.dist-info/RECORD +682 -0
  671. diffneusim-1.0.0.dist-info/WHEEL +5 -0
  672. diffneusim-1.0.0.dist-info/licenses/LICENSE +201 -0
  673. diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-ARMS-hand-wrist-4.3.txt +20 -0
  674. diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-MoBL-ARMS.txt +25 -0
  675. diffneusim-1.0.0.dist-info/licenses/LICENSES/CC-BY-3.0-OpenSim-geometry.txt +25 -0
  676. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Christophy2012-lumbarspine.txt +10 -0
  677. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lai2017-model-high-flex.txt +10 -0
  678. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lee2015-hand_muscle.txt +11 -0
  679. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Rajagopal2016-full_body.txt +11 -0
  680. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Uhlrich2022-fbmodpassivecal.txt +10 -0
  681. diffneusim-1.0.0.dist-info/licenses/NOTICE +274 -0
  682. diffneusim-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3300 @@
1
+ """Reference-free task-walking reward, after Park/Song/Kang arXiv:2603.04166.
2
+
3
+ TRANSCRIBED FROM THE AUTHORS' CODE (github.com/IlseungPark/Walk-RL, wrapper/H2190RampVelocityWrapper.py
4
+ + configs/uneven_syn.yaml), NOT from the paper's prose. Reading both is worth recording, because they
5
+ disagree in three ways that matter:
6
+
7
+ 1. The paper's eq. (3) lists SEVEN terms; both released wrappers use FOUR --
8
+ gaussian_vel, effort, rom, fall. There is no smoothness, knee-load or hip-adduction term in the
9
+ code that produced the published walking. The other three are implemented here but default to
10
+ weight 0, so the default reward is the one that demonstrably works.
11
+ 2. The paper says r_speed_track is a product of Gaussians of forward and vertical COM velocity, head
12
+ ORIENTATION and head angular velocity. The code computes the orientation Gaussian (`r_ori`) and
13
+ then does not multiply it in: the product is `r_vel_x * r_head_angvel * r_vel_z`. Followed the
14
+ code; the orientation factor is available via TASKWALK_TRUNK_UPRIGHT_USE_HEAD=1.
15
+ 3. Every Gaussian is exp(-c * e^2 / var) with a shared c = 0.06 -- not exp(-(e/sigma)^2). At c=0.06
16
+ the falloff is ~17x gentler than the bare form, which changes the reward landscape, not just its
17
+ scale.
18
+
19
+ Weights and variances below are the authors' (uneven_syn.yaml, verified against the repo: gaussian_vel 10,
20
+ effort -0.1, rom -25, fall -250, and no other terms). Two adaptations are unavoidable and are marked in
21
+ place: the KNEE ROM sign (their model flexes negative, ours positive -- measured -2.3..+81.6 deg over the
22
+ v10 corpus) and the fall test (theirs is COM height above the lower foot; ours is the same quantity
23
+ computed from our own FK).
24
+
25
+ AXIS CONVENTION -- the thing that was wrong here for a whole run of experiments. THEIR MODEL IS Y-UP:
26
+ `_is_terminated` compares `com_pos().y` against the lower calcaneus's `com_pos().y`, and
27
+ `model_velocity()` is `com_vel().x`. So in their code x is forward, y is UP and z is LATERAL. Two terms
28
+ were transcribed as if z were up:
29
+
30
+ * `r_vel_z = exp(-c vel_z^2 / 0.1^2)` penalises SIDEWAYS sway, not vertical bob. Read as vertical it
31
+ punishes the COM rise and fall that walking is made of -- on the 07_01 reference (a real human walk)
32
+ it falls to 0.128 at its worst, exactly when a foot leaves the ground, against 0.718 for the correct
33
+ lateral reading. r_speed_track is a PRODUCT, so that lands on the whole reward.
34
+ * `angvel_var = [0.6, 0.65, 1.4]^2` is indexed in their axes, i.e. ROLL 0.6, YAW 0.65, PITCH 1.4 --
35
+ and OUR head body frame is the same (x fwd, y UP, z lateral), so it is copied index-for-index.
36
+ Index-for-index onto ours (x fwd, y lateral, z up) held head PITCH 4.6x too tight, and head pitch is
37
+ what a walking gait produces.
38
+
39
+ Combined, the two cost a real human walk 17.3% of the r_speed_track product (0.7177 vs 0.8677). Both push the
40
+ same way: against the oscillations of stepping, and toward a policy that keeps its COM still.
41
+
42
+ NOT TRANSCRIBED HERE, and not reward. Two structural differences, read off the wrapper:
43
+
44
+ * MIRROR SYMMETRY. `phase_detect` is not a phase -- it is a BINARY LATCH, set to 0.0 on right
45
+ heel-strike and 0.5 on left, never advanced by time. When it reads >= 0.5 (left struck most
46
+ recently) `use_symmetry` mirrors BOTH the observation (`mirror_obs_numpy`: swaps the left/right
47
+ muscle blocks, negates the lateral components of head orientation / angular velocity / COM
48
+ velocity, permutes and sign-flips the 21 dof positions and velocities, swaps the feet) AND the
49
+ action (which output block reaches which physical leg). So the policy always sees a canonical
50
+ frame in which the most-recently-struck leg IS the right leg, and it CANNOT tell the two physical
51
+ legs apart. That halves the state-action space and makes a left/right symmetric gait the natural
52
+ solution. It does NOT forbid our failure mode: if the second foot never strikes, the latch never
53
+ flips and "keep this leg planted" stays representable. A strong prior, not a hard constraint.
54
+ * ACTION SPACE 30 for 90 muscles: `2*n_syn + 10` = 10 synergies per leg through one SHARED matrix,
55
+ plus the 10 torso muscles driven directly.
56
+ """
57
+ from __future__ import annotations
58
+
59
+ import math
60
+ import os
61
+
62
+ import torch
63
+
64
+ from diffneusim.rl.geyer_curves_torch import mtu_forces as _geyer_mtu_forces, pe_constants as _pe_constants
65
+ from diffneusim.rl import millard_curves_torch as _millard
66
+
67
+
68
+ def _mtu_forces(l_ce, v_ce, a, p):
69
+ """The reward's in-graph MTU force (F_MTU, F_CE): Millard 2013 on a Millard case's own tables when the table says so
70
+ (_millard_param_table, millard_curves_torch), else Geyer 2010 (geyer_curves_torch), the call every Geyer run makes unchanged."""
71
+ if p.get("law") == "millard2012":
72
+ return _millard.mtu_forces(l_ce, v_ce, a, p)
73
+ return _geyer_mtu_forces(l_ce, v_ce, a, p)
74
+
75
+ # Per-model q layouts, each verified against that .dnmodel's joint order and its keyframe width. Keyed by
76
+ # nq because that is the one thing the reward can check itself; `lumbar_flex=None` means the model has NO
77
+ # trunk DOF, and the r_joint_limit lumbar term is then SKIPPED rather than aimed at whatever sits at index 7.
78
+ #
79
+ # armless_ball 0-6 free, 7-9 coupled lumbar (flex/lat/axial), 10-13 hip_r ball quat, 14 knee_r,
80
+ # 15 ankle_r, 16 subtalar_r, 17 mtp_r, 18-21 hip_l ball quat, 22 knee_l, 23 ankle_l,
81
+ # 24 subtalar_l, 25 mtp_l.
82
+ # myoleg26_3d 0-6 free, 7-10 hip_r ball quat, 11 knee_r, 12 ankle_r, 13 mtp_r, 14-17 hip_l ball quat,
83
+ # 18 knee_l, 19 ankle_l, 20 mtp_l. The torso is WELDED to the pelvis -- no trunk DOF at
84
+ # all, which is why lumbar_flex is None and why head_body is the torso: on this model the
85
+ # paper's head term cannot be satisfied by counter-rotating a spine, because there is none.
86
+ # Wang 2012 supplement Table 1 -- Type I fibre fraction, "based on Anderson [1999], and Geyer and
87
+ # Herr [2010]". Keyed by our muscle names with the _r/_l side stripped. Anything absent takes SCONE's
88
+ # documented 0.5 default and is reported at construction, because a muscle defaulting silently is the
89
+ # failure this table exists to make visible.
90
+ _WANG_LAMBDA = {
91
+ "soleus": 0.81, "tibant": 0.70, "tib_ant": 0.70, "gastroc": 0.54, "vasti": 0.50,
92
+ "hamstrings": 0.44, "rectfem": 0.423, "rect_fem": 0.423,
93
+ "glutmax": 0.50, "glut_max": 0.50, "iliopsoas": 0.50,
94
+ }
95
+ # TASKWALK_WANG_LAMBDA_BY_STEM (opt-in; 11-14, found in testing, the review): the table above is keyed by Wang's group names, which the
96
+ # 290 body's muscles do not carry, so only soleus and tibant ever matched. With the opt-in, Wang 2012 supplement Table 1 is applied by GROUP
97
+ # through this explicit map of the 290 body's 40 leg stems; a stem mapped to None is not in Wang's set and takes 0.5 explicitly (SCONE's
98
+ # documented default), and every muscle that is not a leg stem must match a trunk prefix (Wang has no trunk; 0.5 explicitly). Nothing
99
+ # defaults silently: a muscle in neither list is refused.
100
+ _WANG_TABLE1 = {"SOL": 0.81, "TA": 0.70, "GAS": 0.54, "VAS": 0.50, "HAM": 0.44, "RF": 0.423, "GLU": 0.50, "HFL": 0.50}
101
+ _WANG_GROUP_BY_STEM = {
102
+ "soleus": "SOL", "tibant": "TA", "gasmed": "GAS", "gaslat": "GAS", "vasint": "VAS", "vaslat": "VAS", "vasmed": "VAS",
103
+ "semimem": "HAM", "semiten": "HAM", "bflh": "HAM", "recfem": "RF", "glmax1": "GLU", "glmax2": "GLU", "glmax3": "GLU",
104
+ "iliacus": "HFL", "psoas": "HFL",
105
+ "bfsh": None, "glmed1": None, "glmed2": None, "glmed3": None, "glmin1": None, "glmin2": None, "glmin3": None, "tfl": None, "piri": None,
106
+ "addbrev": None, "addlong": None, "addmagDist": None, "addmagIsch": None, "addmagMid": None, "addmagProx": None, "grac": None,
107
+ "sart": None, "tibpost": None, "perbrev": None, "perlong": None, "fdl": None, "fhl": None, "edl": None, "ehl": None,
108
+ }
109
+ # TASKWALK_WANG_MASS_ANATOMICAL (opt-in; 11-14, found in testing): the metabolic mass is (F_max / 0.25e6) rho l_opt, SCONE's 25 N/cm2, but the
110
+ # leg F_max were built as Rajagopal 2016's 60 N/cm2 x PCSA. The Wang volume-factor file (TASKWALK_WANG_MASS_FILE) sets each covered muscle to
111
+ # scale x (F_max l_opt)_Rajagopal / 0.25e6 x rho = scale x 2.4 x volume x rho, so dividing by 2.4 x scale gives the anatomical mass
112
+ # (Handsfield volume x 1059.7 kg/m3). Only the file's muscles (the 80 leg muscles); the trunk's specific tension is not sourced here.
113
+ _SIGMA_RAJAGOPAL2016 = 0.6e6 # N/m2 (60 N/cm2), the specific tension Rajagopal 2016 built F_max with
114
+
115
+ def _srelu(x, b):
116
+ """Smooth one-sided clamp, IDENTICAL to core/dyn/passive.h::srelu -- 0.5(x + sqrt(x^2 + b^2)).
117
+
118
+ Duplicated here on purpose rather than read back from the engine: the limit terms below have to
119
+ price the same stop the engine integrates, and a reward that reimplemented a DIFFERENT smoothing
120
+ would charge for a force that is not there. Gated by test_taskwalk_limit_terms against the C++.
121
+ """
122
+ return 0.5 * (x + torch.sqrt(x * x + b * b))
123
+
124
+
125
+ def _srelu_d(x, b):
126
+ """d/dx of _srelu -- core/dyn/passive.h::srelu_d. This is the engine's `eng` factor: 0 well inside
127
+ the range, 0.5 at the bound, 1 well past it."""
128
+ return 0.5 * (1.0 + x / torch.sqrt(x * x + b * b))
129
+
130
+
131
+ _LIMEXP_XC = 12.0 # core/dyn/passive.h::limexp_xc; e^12 = 1.6e5
132
+
133
+
134
+ def _limexp(x, a, w):
135
+ """Riener & Edrich exponential limit spring, IDENTICAL to core/dyn/passive.h::limexp --
136
+ `a exp(x/w)`, linearised above x/w = 12 so it cannot overflow. Same reason as `_srelu`: the reward
137
+ has to price the stop the engine integrates, and on a model with a `passive.exp` block that stop is
138
+ THIS law, not `k_lim * srelu`. Note it is non-zero everywhere, so a joint well inside its range
139
+ still carries a small restoring torque -- which the engine applies and the old reading called 0."""
140
+ u = x / w
141
+ return a * torch.exp(torch.clamp(u, max=_LIMEXP_XC)) * (1.0 + (u - _LIMEXP_XC).clamp_min(0.0))
142
+
143
+
144
+ _FULLBODY_NQ = (26, 40) # the full-body env's bodies: 14t (armless) and 14x (arms); the same free root, q[0:7]
145
+
146
+ _DOF_MAPS = {
147
+ # knee_sign: +1 when the model flexes POSITIVE (so hyperextension is q < 0 and the ROM term must be
148
+ # flipped), -1 when it flexes NEGATIVE like the authors' model (no flip). This is NOT shared: measured
149
+ # on each model's own retargeted human walk, armless_ball runs -2.3..+81.6 deg and myoleg26_3d runs
150
+ # -69.7..-0.7 deg, i.e. OPPOSITE. Getting it wrong does not crash -- it penalises every instant of
151
+ # knee flexion at weight 25, and the policy correctly answers by locking the knee at 0 and walking on
152
+ # stiff legs. That is exactly what ml26_sym2 did.
153
+ 26: dict(name="armless_ball", lumbar_flex=7, hip_r=10, knee_r=14, hip_l=18, knee_l=22, head_body=24,
154
+ knee_sign=+1.0),
155
+ # 14x: 14t with the fused-hand girdle arms, 14 arm DOFs (q 10-23) before the legs, so every leg address moves by +14;
156
+ # the lumbar hinges and the head body are where 14t has them (read from the dnmodel's qadr)
157
+ 40: dict(name="fusedhand_ball_girdle", lumbar_flex=7, hip_r=24, knee_r=28, hip_l=32, knee_l=36, head_body=24,
158
+ knee_sign=+1.0),
159
+ 21: dict(name="myoleg26_3d_kneeexp_g14eq", lumbar_flex=None, hip_r=7, knee_r=11, hip_l=14, knee_l=18, head_body=11,
160
+ knee_sign=-1.0),
161
+ # myoleg26_3d_compound: the SAME skeleton with each Ball hip replaced by an ordered 3-hinge stack
162
+ # (flexion z, adduction x, rotation y -- MuJoCo order), so nq drops 21 -> 19 and every index after
163
+ # the first hip shifts. Read off the model, not inferred:
164
+ # 0-6 free, 7/8/9 hip_r flexion/adduction/rotation, 10 knee_r, 11 ankle_r, 12 mtp_r,
165
+ # 13/14/15 hip_l, 16 knee_l, 17 ankle_l, 18 mtp_l.
166
+ # hip_* points at the FLEXION primitive, which is the first of the stack and is the coordinate the
167
+ # Ball map's hip_* quat start also stands in for. head_body is a BODY index and the body list is
168
+ # unchanged (11 = torso), so it does not shift. knee_sign is a property of the model's own
169
+ # convention and is likewise unchanged.
170
+ 19: dict(name="myoleg26_3d_compound_g14eq", lumbar_flex=None, hip_r=7, knee_r=10, hip_l=13, knee_l=16,
171
+ head_body=11, knee_sign=-1.0),
172
+ # H1622v2k (both the .hfd and the derived Millard variant -- identical skeletons). Read off the
173
+ # model, and NOTE the hip stack order is the OPPOSITE of myoleg26_3d_compound:
174
+ # 0-6 free, 7 hip_r ADDUCTION (axis x, -45..20), 8 hip_r FLEXION (axis -y, -30..120),
175
+ # 9 knee_r (-120..-3), 10 ankle_r, 11/12 hip_l adduction/flexion, 13 knee_l, 14 ankle_l.
176
+ # So hip_* is the SECOND primitive here and the first one there. Copying the compound map would
177
+ # have aimed the hip term at the adduction axis.
178
+ # knee_sign -1: the tibia range is -120..-3 deg, i.e. it flexes NEGATIVE, same convention as
179
+ # myoleg26_3d and opposite to armless_ball. head_body is the torso, body 7 on this 8-body tree.
180
+ # hip_ball=False: the hip is a 2-DOF HINGE STACK, so hip_* is a SCALAR flexion index and NOT the
181
+ # address of a 4-wide quaternion. TASKWALK_W_HIP_ADDUCTION's adduction term reads q[adr..adr+3] as a hip
182
+ # quaternion, so it is meaningless here and runs off the end of nq=15. Asserted at construction.
183
+ 15: dict(name="H1622v2k", lumbar_flex=None, hip_r=8, knee_r=9, hip_l=12, knee_l=13,
184
+ head_body=7, knee_sign=-1.0, hip_ball=False),
185
+ }
186
+
187
+
188
+ def _f(name: str, default: float) -> float:
189
+ return float(os.environ.get(name, default))
190
+
191
+
192
+ def _f_ever(name: str, default: float) -> float:
193
+ """The largest magnitude this weight will EVER hold: its start value or its schedule's end.
194
+
195
+ WHY IT EXISTS. `TaskWalkEnvMixin` walks any `TASKWALK_W_*` from its start value to `_END` during
196
+ training, writing the new value straight onto this object -- but two things here are BUILT ONCE in
197
+ `__init__` and only when their weight is non-zero: `_met` (the MTU parameter table) and `_lim` (the
198
+ joint-limit layout). A weight that starts at 0 and is scheduled UP therefore skips construction and
199
+ then dereferences None the moment the schedule makes its branch live.
200
+ That is not hypothetical: `ml26_sprint_curr_s1` ramps `w_limit_torque` 0 -> 3 starting at epoch 500,
201
+ and would have died there, 500 epochs into an 8-hour run. Gate CONSTRUCTION on this; the weight
202
+ itself must stay the start value or the schedule has nothing to walk from."""
203
+ v = abs(_f(name, default))
204
+ e = os.environ.get(name + "_END")
205
+ return max(v, abs(float(e))) if e is not None else v
206
+
207
+
208
+ def _b(name: str, default: int) -> bool:
209
+ """A 0/1 env FLAG, rejecting anything else instead of coercing it.
210
+
211
+ `bool(int(os.environ.get(...)))`, which this file used twice before, turns "2" into True and accepts
212
+ "-1"; and the even easier slip, `bool(os.environ.get(name, "0"))`, is True for the STRING "0". A flag
213
+ that silently means the opposite of what it reads is the kind of thing that voids a whole ladder, so
214
+ this asserts the literal instead.
215
+ """
216
+ v = str(os.environ.get(name, default))
217
+ assert v in ("0", "1"), f"{name}={v!r} must be exactly '0' or '1' (it is an enable FLAG, not a weight)"
218
+ return v == "1"
219
+
220
+
221
+ class SpeedPController:
222
+ """A PROPORTIONAL multiplier on the linear speed term: lambda = lambda0 + k_p (v_cmd - v_mean), v_mean the batch mean of the
223
+ paid forward velocity over the last `every` control steps (one SAPO epoch = its 32-step window), alive envs only.
224
+
225
+ WHY (2026-10-11, docs/training/gradient-field-ioc.md STATE 00:1x). A flat speed band + a FIXED lambda has no interior optimum in
226
+ mean speed: lambda0 balances the effort costs at ONE controller (D1: 1.47 at arm C, 1.09 at G5h ep200, 2.8-3.6 at G5h ep400), so
227
+ warm runs drifted to the band's lower edge and a cold learner to its upper edge. The speed constraint E[v_x] = v_cmd is the
228
+ predictive-simulation formulation (Ackermann & van den Bogert 2010 eq. 8b; Falisse 2019); RCPO (Tessler et al. 2019) is the RL
229
+ form (per-step guiding term, multiplier driven by the measured constraint). Plain integral (dual-ascent) control oscillates when
230
+ the objective has no curvature along the constraint, which a flat band guarantees (Platt & Barr 1988; Stooke et al. 2020 sec.
231
+ 4); the proportional term supplies that curvature. lambda_P v_x held fixed within an epoch is the per-step form of the gradient
232
+ of -(k_p / 2)(v_mean - v_cmd)^2, so it is linear in v_x per step and does not charge the within-stride speed oscillation.
233
+ The accumulation stays on the device; the host sync is once per update.
234
+
235
+ INTEGRAL PART (M1 of PAPER-SPEED-CONSTRAINT-M1-M4, 2026-11-22; TASKWALK_SPEED_I_ETA = eta > 0; 0 = OFF and update() is the
236
+ proportional form above, byte for byte). The design's multiplier update, the projected dual ascent of the constraint
237
+ E[v_x] >= v_cmd (Tessler et al. 2019 RCPO; Stooke et al. 2020 sec. 4's PI form):
238
+ lambda_I <- max(0, lambda_I + eta (v_cmd - v_mean)), lambda_I(0) = lambda0
239
+ lambda = max(0, lambda_I + k_p (v_cmd - v_mean)) (k_p >= 0; the proportional term above, on top of the design's integral)
240
+ Both projections keep lambda >= 0 (KKT dual feasibility of an inequality multiplier): an overspeeding window never pays the
241
+ policy for being slower (S2c's lambda -14 made every slow start topple, see TASKWALK_SPEED_P_LAM_MIN). The integral state
242
+ is a host float, updated once per window like the proportional read."""
243
+
244
+ def __init__(self, lam0: float, k_p: float, every: int, eta: float = 0.0, i_band: float = 0.0, eta_down: float = 0.0,
245
+ i_hold: bool = False):
246
+ assert k_p >= 0.0 and eta >= 0.0 and (k_p > 0.0 or eta > 0.0), (k_p, eta)
247
+ assert every >= 1, every
248
+ # ANTI-WINDUP (B-AW, 11-23; the review after MB 1.33's lambda_I wound up to 4.0 during the cold start's lag). Both default 0 = off,
249
+ # update() byte for byte as before:
250
+ # i_band > 0 CONDITIONAL INTEGRATION (Astrom & Hagglund, Advanced PID Control 2006, sec. 3.5): a LAG larger than i_band x the
251
+ # command (e > i_band c) leaves lambda_I as it is; the proportional term alone acts on the transient (the cold start,
252
+ # a ramp the policy has not caught), and the integral removes only the small steady-state error it exists for
253
+ # eta_down > 0 the integral's rate when the speed is OVER the command (e < 0): a slack inequality constraint's multiplier drains
254
+ # at eta_down instead of eta (it biases the equilibrium toward a small lag, measured in the B-AW test)
255
+ # i_hold integrate only at the FINAL HOLD: the caller passes update(hold=...), True when the env's command schedule is
256
+ # complete (or there is none: a fixed command). A curriculum's ramp is a moving setpoint the policy lags by 5-7 %
257
+ # (M2N65's waypoints), inside any useful band, so the integral would wind up through the whole ramp; the proportional
258
+ # term alone tracks the ramp and the initial hold, the integral acts on the final hold only. (11-23 03:3x: the first
259
+ # form compared the window's mean DRAWN command with the last window's; each world draws only at reset, so late in a
260
+ # climb, with ~1000-step episodes, windows without a reset read as constant and integrated: MB-AW 2.73's lambda_I
261
+ # 0.398 -> 0.462 while the schedule still ramped. The schedule is the setpoint; the drawn mean is not.)
262
+ assert i_band >= 0.0 and eta_down >= 0.0, (i_band, eta_down)
263
+ assert (i_band == 0.0 and eta_down == 0.0 and not i_hold) or eta > 0.0, "the anti-windup knobs act on the integral: they need eta > 0"
264
+ self.i_band, self.eta_down, self.i_hold = float(i_band), float(eta_down), bool(i_hold)
265
+ self.lam0, self.k_p, self.every = float(lam0), float(k_p), int(every)
266
+ self.eta = float(eta)
267
+ self.lam_i = float(lam0) # the integral state (the design's lambda); read only when eta > 0
268
+ self._s_v = self._s_c = self._s_n = None
269
+ self._calls = 0
270
+ self.n_updates = 0
271
+
272
+ def observe(self, v_speed, v_cmd, alive):
273
+ """v_speed, v_cmd, alive: (n_env,) tensors on one device; alive in {0, 1}."""
274
+ assert v_speed.shape == v_cmd.shape == alive.shape, (v_speed.shape, v_cmd.shape, alive.shape)
275
+ sv, sc, sn = (v_speed * alive).sum(), (v_cmd * alive).sum(), alive.sum()
276
+ if self._s_v is None:
277
+ self._s_v, self._s_c, self._s_n = sv, sc, sn
278
+ else:
279
+ self._s_v, self._s_c, self._s_n = self._s_v + sv, self._s_c + sc, self._s_n + sn
280
+ self._calls += 1
281
+
282
+ def due(self) -> bool:
283
+ return self._calls >= self.every
284
+
285
+ def update(self, hold=None):
286
+ """(lambda, v_mean, v_cmd_mean) from the accumulated window; resets the window. hold: the caller's 'the command schedule is complete'
287
+ (required with i_hold, ignored otherwise)."""
288
+ n = float(self._s_n)
289
+ assert n > 0.0, "SpeedPController: no alive env-step in the window"
290
+ v_mean, c_mean = float(self._s_v) / n, float(self._s_c) / n
291
+ self._s_v = self._s_c = self._s_n = None
292
+ self._calls = 0
293
+ self.n_updates += 1
294
+ if self.eta == 0.0:
295
+ return self.lam0 + self.k_p * (c_mean - v_mean), v_mean, c_mean
296
+ e = c_mean - v_mean
297
+ if self.i_band == 0.0 and self.eta_down == 0.0 and not self.i_hold:
298
+ self.lam_i = max(0.0, self.lam_i + self.eta * e)
299
+ else: # B-AW (see __init__)
300
+ if self.i_hold:
301
+ assert hold is not None, "TASKWALK_SPEED_I_HOLD_ONLY: update() needs hold= (the command schedule is complete)"
302
+ ramping = self.i_hold and not hold
303
+ if ramping:
304
+ step = 0.0
305
+ elif e < 0.0:
306
+ step = (self.eta_down if self.eta_down > 0.0 else self.eta) * e
307
+ elif self.i_band > 0.0 and e > self.i_band * c_mean:
308
+ step = 0.0
309
+ else:
310
+ step = self.eta * e
311
+ self.lam_i = max(0.0, self.lam_i + step)
312
+ return max(0.0, self.lam_i + self.k_p * e), v_mean, c_mean
313
+
314
+
315
+ def huber_sq(e, e0: float):
316
+ """e^2 up to e0, then the tangent line 2 e0 e - e0^2 (value and slope continuous at e0); e0 <= 0 = the plain square. For the
317
+ knee terms' excess in DEGREES (TASKWALK_*_KNEE_HUBER_DEG, 2026-10-22): the square of a degree excess makes one bent-knee
318
+ touchdown cost as much as a fall (steer1fc's 34-deg landing: 0.25 x 29^2 ~ 210 against the fall penalty 250), so the knee
319
+ terms turned steer1fc's turning steps net negative (-1.3 per step, tools/steer/turn_terms.py). Huber's tail (Huber 1964)
320
+ keeps the square, a Gaussian price, inside the tuning constant and is linear beyond it."""
321
+ if e0 <= 0.0:
322
+ return e ** 2
323
+ return torch.where(e <= e0, e ** 2, 2.0 * e0 * e - e0 * e0)
324
+
325
+
326
+ def band_excess(x, tgt: float, tol: float):
327
+ """max(|x - tgt| - tol, 0): the distance outside a free band of half-width tol around tgt (the knee terms' shape, both sides)."""
328
+ return ((x - tgt).abs() - tol).clamp_min(0.0)
329
+
330
+
331
+ def trunk_pitch_deg(hq, u, cmd_frame):
332
+ """(n,) sagittal pitch of a body's up axis u (its local up, calibrated at the standing keyframe), deg, + = the top AHEAD of the
333
+ base along the walking direction: atan2(up . forward, up . world-up) with forward = the commanded heading (`cmd_frame`, the
334
+ identity without one). The quantity fb_knob_matrix's trunk_pitch measures and tools/reference/trunk_population reports for the
335
+ human (a thorax-fixed line against the subject's own standing posture). hq (4, n) = (w, x, y, z)."""
336
+ w, x, y, z = hq[0], hq[1], hq[2], hq[3]
337
+ up_x = (1.0 - 2.0 * (y * y + z * z)) * u[0] + 2.0 * (x * y - z * w) * u[1] + 2.0 * (x * z + y * w) * u[2]
338
+ up_y = 2.0 * (x * y + z * w) * u[0] + (1.0 - 2.0 * (x * x + z * z)) * u[1] + 2.0 * (y * z - x * w) * u[2]
339
+ up_z = 2.0 * (x * z - y * w) * u[0] + 2.0 * (y * z + x * w) * u[1] + (1.0 - 2.0 * (x * x + y * y)) * u[2]
340
+ f_fwd, _ = cmd_frame(up_x, up_y)
341
+ return torch.rad2deg(torch.atan2(f_fwd, up_z))
342
+
343
+
344
+ def facing_frame(q):
345
+ """A frame function like TaskWalkReward._cmd_frame, rotated by the ROOT's yaw (the pelvis facing, detached): (x, y) -> (along the
346
+ facing, to its left). The posture bands read their axes here, not along the command: mid-turn the command points up to 180 deg
347
+ away from the body, and a command-frame width would read the fore-aft foot spacing as width (the knee gate's lesson,
348
+ docs-dev/deeploco/20261021_1630_s1k_knee/turn_cost)."""
349
+ w, x, y, z = q[3].detach(), q[4].detach(), q[5].detach(), q[6].detach()
350
+ yaw = torch.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
351
+ c, s_ = torch.cos(yaw), torch.sin(yaw)
352
+ return lambda a, b: (c * a + s_ * b, -s_ * a + c * b)
353
+
354
+
355
+ def step_width_mm(foot_pos, cmd_frame):
356
+ """(n,) lateral distance between the two calcanei across the walking direction (the commanded heading), mm."""
357
+ lat_r = cmd_frame(foot_pos[0][0], foot_pos[0][1])[1]
358
+ lat_l = cmd_frame(foot_pos[1][0], foot_pos[1][1])[1]
359
+ return 1000.0 * (lat_l - lat_r).abs()
360
+
361
+
362
+ def track_pose_error(q, q_ref, scalar_idx, quat_blocks):
363
+ """(n,) squared LOCAL pose error against a reference pose, rad^2: the scalar joint coordinates in `scalar_idx` plus each ball
364
+ joint's geodesic angle squared ((2 acos |<q, q_ref>|)^2, DeepMimic's). The caller passes the joints to track and leaves out
365
+ the root (position, height, orientation), so a commanded heading is not fought (DeepLoco re-anchors its reference to the
366
+ character's root each step for the same reason)."""
367
+ e = ((q[scalar_idx] - q_ref[scalar_idx]) ** 2).sum(0)
368
+ for s, L in quat_blocks:
369
+ dot = (q[s:s + L] * q_ref[s:s + L]).sum(0).abs().clamp(max=1.0 - 1e-6)
370
+ e = e + (2.0 * torch.acos(dot)) ** 2
371
+ return e
372
+
373
+
374
+ def stance_knee_gate(foot_grf, gate_bw: float, single: int, heel_fwd=None):
375
+ """Which leg the stance-knee term charges, (2, n) in {0, 1}, rows [right, left]. The load gate: the leg's foot carries more than
376
+ `gate_bw` bodyweights. single=1 also requires the OTHER foot to carry no more than that (single support), so the two
377
+ double-support phases, where the human knee flexes, are not charged (TASKWALK_STANCE_KNEE_SINGLE_SUPPORT). single=2 also
378
+ requires the other (swinging) heel to be AHEAD of this one along the walking axis, `heel_fwd` (2, n): the second half of
379
+ single support only, so the loading response at its start is not charged either."""
380
+ st = (foot_grf > gate_bw).to(foot_grf.dtype)
381
+ if single:
382
+ st = st * (1.0 - st.flip(0))
383
+ if single == 2:
384
+ assert heel_fwd is not None and heel_fwd.shape == foot_grf.shape, "single=2 needs the heels' forward positions (2, n)"
385
+ st = st * (heel_fwd.flip(0) > heel_fwd).to(st.dtype)
386
+ return st
387
+
388
+
389
+ class BinnedSpeedPController:
390
+ """SpeedPController with one multiplier PER COMMANDED-SPEED BIN, for a run that commands a RANGE of speeds per env
391
+ (TASKWALK_V_FIXED unset). lambda_k = lambda0 + k_p (c_mean_k - v_mean_k) over the alive env-steps whose command falls in bin k.
392
+
393
+ WHY (2026-10-17, gradient-field-ioc.md STATE 09:0x). The batch-scalar controller enforces ONE constraint, E[v_x] = E[v_cmd],
394
+ and pays every env the same lambda v_x. Under a 0.7-1.6 command range that pushes a slow-commanded env as hard as a fast one:
395
+ the mean is met while slow envs run above their command and fast ones below it. Each commanded speed is its own constraint in
396
+ the predictive-simulation formulation (Falisse 2019 solves one speed per problem), and RCPO (Tessler et al. 2019) gives each
397
+ constraint its own multiplier; binning the continuous command into K equal-width bins over [lo, hi] makes K constraints, each
398
+ the existing proportional form. A bin with no alive env-step in a window keeps its multiplier (no measurement, no update; a
399
+ fixed-speed eval fills one bin only). Commands outside [lo, hi] fall in the edge bins."""
400
+
401
+ def __init__(self, lam0: float, k_p: float, every: int, n_bins: int, lo: float, hi: float, device=None, lam_min=None):
402
+ assert k_p > 0.0, k_p
403
+ assert lam_min is None or lam_min <= lam0, (lam_min, lam0)
404
+ self.lam_min = lam_min
405
+ assert every >= 1, every
406
+ assert n_bins >= 2, n_bins
407
+ assert hi > lo, (lo, hi)
408
+ self.lam0, self.k_p, self.every, self.n_bins = float(lam0), float(k_p), int(every), int(n_bins)
409
+ self.lo, self.hi = float(lo), float(hi)
410
+ self._inner = torch.linspace(self.lo, self.hi, self.n_bins + 1, device=device)[1:-1] # (K-1,) inner edges
411
+ self.lam = torch.full((self.n_bins,), self.lam0, device=device)
412
+ self._s_v = self._s_c = self._s_n = None
413
+ self._calls = 0
414
+ self.n_updates = 0
415
+
416
+ def bin_of(self, v_cmd):
417
+ if self._inner.device != v_cmd.device:
418
+ self._inner, self.lam = self._inner.to(v_cmd.device), self.lam.to(v_cmd.device)
419
+ return torch.bucketize(v_cmd.to(self._inner.dtype).contiguous(), self._inner)
420
+
421
+ def lam_env(self, v_cmd):
422
+ """(n_env,) multiplier for each env's command. bin_of FIRST: it moves the state onto v_cmd's device."""
423
+ idx = self.bin_of(v_cmd)
424
+ return self.lam[idx].to(v_cmd.dtype)
425
+
426
+ def observe(self, v_speed, v_cmd, alive):
427
+ assert v_speed.shape == v_cmd.shape == alive.shape, (v_speed.shape, v_cmd.shape, alive.shape)
428
+ b = self.bin_of(v_cmd)
429
+ sv = torch.bincount(b, weights=(v_speed * alive).float(), minlength=self.n_bins)
430
+ sc = torch.bincount(b, weights=(v_cmd * alive).float(), minlength=self.n_bins)
431
+ sn = torch.bincount(b, weights=alive.float(), minlength=self.n_bins)
432
+ if self._s_v is None:
433
+ self._s_v, self._s_c, self._s_n = sv, sc, sn
434
+ else:
435
+ self._s_v, self._s_c, self._s_n = self._s_v + sv, self._s_c + sc, self._s_n + sn
436
+ self._calls += 1
437
+
438
+ def due(self) -> bool:
439
+ return self._calls >= self.every
440
+
441
+ def update(self):
442
+ """(lambda per bin, v_mean per bin, c_mean per bin, alive count per bin), host lists; resets the window."""
443
+ n = self._s_n
444
+ assert float(n.sum()) > 0.0, "BinnedSpeedPController: no alive env-step in the window"
445
+ has = n > 0
446
+ v_mean = torch.where(has, self._s_v / n.clamp_min(1.0), torch.zeros_like(n))
447
+ c_mean = torch.where(has, self._s_c / n.clamp_min(1.0), torch.zeros_like(n))
448
+ lam = self.lam0 + self.k_p * (c_mean - v_mean)
449
+ if self.lam_min is not None:
450
+ lam = lam.clamp_min(self.lam_min)
451
+ self.lam = torch.where(has, lam, self.lam.to(n.dtype)).to(self.lam.dtype)
452
+ self._s_v = self._s_c = self._s_n = None
453
+ self._calls = 0
454
+ self.n_updates += 1
455
+ return self.lam.tolist(), v_mean.tolist(), c_mean.tolist(), n.tolist()
456
+
457
+
458
+ def _wang_mass_factors(env, who, model=None, names=None):
459
+ """Per-muscle factors on the Wang mass, or None. TASKWALK_WANG_MASS_FILE names a json written by tools/build_wang_mass_volume.py
460
+ for ONE model: it sets the 80 Rajagopal leg muscles' mass to their measured volume (undoing the build's cos^2 pennation and Lai
461
+ 2017's l_opt edits, total leg mass held; docs-dev/analysis/20261015_0610_wang_mass_volume/RESULT.md). Unset = factor 1 everywhere, and
462
+ every earlier run is bit-identical. Applied to BOTH masses (the metabolic table and the volume weight) so they stay one quantity.
463
+ `model` / `names`: the model the masses are computed from and its muscle names, when that is not the env's own (a Millard env's
464
+ TASKWALK_MILLARD_MASS_DNMODEL, _millard_param_table); None = FULLBODY_DNMODEL and the env model's names, as every Geyer run."""
465
+ path = os.environ.get("TASKWALK_WANG_MASS_FILE", "")
466
+ if not path:
467
+ return None
468
+ import json as _json
469
+ import numpy as _np
470
+ rec = _json.load(open(path))
471
+ if model is None:
472
+ model = os.environ.get("FULLBODY_DNMODEL", "")
473
+ assert model, "TASKWALK_WANG_MASS_FILE is built per model; FULLBODY_DNMODEL must name the model it is applied to"
474
+ assert model.removesuffix(".dnmodel") == rec["model"], (f"TASKWALK_WANG_MASS_FILE was built for {rec['model']}, "
475
+ f"the env runs {model}")
476
+ if names is None:
477
+ names = [m["name"] for m in env._monitor.jm["muscles"]]
478
+ missing = sorted(set(rec["factors"]) - set(names))
479
+ assert not missing, f"TASKWALK_WANG_MASS_FILE names muscles the model lacks: {missing[:5]}"
480
+ fac = _np.array([float(rec["factors"].get(n, 1.0)) for n in names])
481
+ print(f"[taskwalk/{who}] Wang mass x volume factors from {path}: {len(rec['factors'])} muscles, "
482
+ f"range {fac.min():.3f}-{fac.max():.3f}", flush=True)
483
+ return fac
484
+
485
+
486
+ def _mtu_param_table(env):
487
+ """Per-muscle Geyer curve constants (F_max, l_opt, v_max, W, C, N, K) + Wang's mass and lambda.
488
+
489
+ Read by BOTH in-graph force consumers: the Wang 2012 metabolic rate, and the tibiofemoral-load
490
+ term, which needs the knee-spanning muscles' tendon force with a gradient to the action. Only
491
+ `mass` and `lambda` are metabolic-specific; everything else is the muscle model itself, which is
492
+ why the old name `_metabolic_table` was wrong once a second term needed it.
493
+
494
+ mass = (F_max/specific_tension)·density·l_opt -- SCONE Muscle.cpp:72, whose constants (0.25e6 Pa,
495
+ 1059.7 kg/m³) are its documented defaults and agree with Wang's stated 1060 to 0.03%.
496
+
497
+ lambda is the TYPE I FIBRE FRACTION. Wang supplement Table 1 gives it per muscle "based on
498
+ Anderson [1999], and Geyer and Herr [2010]"; muscles outside that set take SCONE's documented 0.5
499
+ default and are LISTED at construction, because a muscle silently defaulting is the failure mode
500
+ this has to make visible.
501
+ """
502
+ import numpy as _np
503
+ jm = env._monitor.jm # DnModelMonitor keeps the parsed .dnmodel (diffneusim/model/monitor.py)
504
+ if jm.get("muscle_model") == "millard2012": # a Millard 2013 model: its own table (below); this Geyer path is untouched
505
+ return _millard_param_table(env)
506
+ assert not os.environ.get("TASKWALK_MILLARD_MASS_DNMODEL", ""), (
507
+ "TASKWALK_MILLARD_MASS_DNMODEL on a Geyer model: it gives a Millard env the Geyer twin's masses; a Geyer env has its own")
508
+ jm_mass = jm # the MASS always comes from the env's own model (the compliant one in a tendon pair's both arms)
509
+ assert jm.get("muscle_model") == "geyer2010", (
510
+ f"the metabolic term needs the passive curve to split F_CE out of F_MTU, and only geyer2010's "
511
+ f"f_p0 is implemented; model is {jm.get('muscle_model')}")
512
+ fmax, lopt, wpe, cc, nn, kk, vmax, lam, defaulted = [], [], [], [], [], [], [], [], []
513
+ lam_seen, lam_trunk = set(), 0
514
+ pe_rest, pe_eps, beta = [], [], []
515
+ for m in jm["muscles"]:
516
+ gain, named = "gainprm" in m, "max_isometric_force" in m
517
+ assert gain != named, f"{m['name']}: EITHER gainprm OR named params (core/io/dnmodel.h:121)"
518
+ assert gain, ("the in-graph force path reads the geyer curve constants from gainprm "
519
+ "[F_max, l_opt, l_slack, v_max, W, C, N, K, E_REF] (core/io/dnmodel.h:93); "
520
+ f"{m['name']} uses the named form, which does not carry C/N/K")
521
+ g = m["gainprm"]
522
+ fmax.append(float(g[0])); lopt.append(float(g[1])); vmax.append(float(g[3]))
523
+ wpe.append(float(g[4])); cc.append(float(g[5])); nn.append(float(g[6])); kk.append(float(g[7]))
524
+ r_, e_ = _pe_constants(m)
525
+ pe_rest.append(r_); pe_eps.append(e_)
526
+ # PARALLEL-FIBRE VISCOSITY, read as the loader reads it (core/io/dnmodel.h: `fiber_damping`, alias
527
+ # `beta_damp`, absent = 0). geyer_curves_torch.mtu_forces carries it as beta*v0, the engine's Geyer
528
+ # residual term (core/mtu/solve.h `f_v (f_pe + A f_l) + beta_damp v0`); every full-body model has 0.1.
529
+ assert not ("fiber_damping" in m and "beta_damp" in m), f"{m['name']}: fiber_damping OR beta_damp"
530
+ beta.append(float(m.get("fiber_damping", m.get("beta_damp", 0.0))))
531
+ key = m["name"].rsplit("_", 1)[0] if m["name"].rsplit("_", 1)[-1] in ("r", "l") else m["name"]
532
+ if key in _WANG_LAMBDA:
533
+ lam.append(_WANG_LAMBDA[key])
534
+ else:
535
+ lam.append(0.5); defaulted.append(key)
536
+ fmax = _np.array(fmax); lopt = _np.array(lopt)
537
+ mass = _np.array([(float(m["gainprm"][0]) / 0.25e6) * 1059.7 * float(m["gainprm"][1]) for m in jm_mass["muscles"]]) # the env's own model
538
+ _fac = _wang_mass_factors(env, "metabolic")
539
+ if _fac is not None:
540
+ mass = mass * _fac
541
+ _ms = _mass_scale(env, "metabolic")
542
+ if _ms is not None:
543
+ mass = mass * _np.array(_ms)
544
+ if defaulted:
545
+ print(f"[taskwalk/metabolic] lambda: {len(set(defaulted))} muscle groups fall back to SCONE's "
546
+ f"0.5 default -> {sorted(set(defaulted))}", flush=True)
547
+ # TaskWalkReward is constructed inside _tw_setup, BEFORE q is allocated, so take the device from
548
+ # the env itself rather than from a state tensor that does not exist yet.
549
+ dev = env.device
550
+ t = lambda x: torch.as_tensor(x, dtype=torch.float32, device=dev)[:, None]
551
+ return dict(mass=t(mass), lam=t(lam), fmax=t(fmax), lopt=t(lopt), wpe=t(wpe),
552
+ curve=dict(F_max=t(fmax), l_opt=t(lopt), v_max=t(vmax), W=t(wpe),
553
+ C=t(cc), N=t(nn), K=t(kk), beta=t(beta), pe_rest=t(pe_rest), pe_eps=t(pe_eps)),
554
+ body_mass=float(sum(float(b.get("mass", 0.0)) for b in jm["bodies"])))
555
+
556
+
557
+ # Knobs the Millard table refuses, each defined on Geyer quantities (2026-11-17, M0). Set on a Millard model they would either crash on
558
+ # the missing gainprm or silently mean something else.
559
+ _MILLARD_REFUSED = {
560
+ "TASKWALK_MUSCLE_CURVE_DNMODEL": "the force reads the muscle case's own tables (E0_MUSCLE_CASE); a curve dnmodel is the Geyer probes' "
561
+ "way to give the reward a case's gainprm, and the env model is the Millard case's own model",
562
+ "TASKWALK_MUSCLE_CURVE_FMAX_SCALED": "a curve-dnmodel switch (see TASKWALK_MUSCLE_CURVE_DNMODEL)",
563
+ "TASKWALK_MUSCLE_CURVE_LOPT_SCALED": "a curve-dnmodel switch (see TASKWALK_MUSCLE_CURVE_DNMODEL)",
564
+ "TASKWALK_MUSCLE_CURVE_PE_ABSOLUTE": "a curve-dnmodel switch on Geyer's own PE (L_PE0 / E_REF_PE), which a Millard muscle does not have",
565
+ "TASKWALK_MUSCLE_MASS_SCALED": "reads the curve dnmodel's gainprm F_max",
566
+ "TASKWALK_EFFORT_N1_EQUIV": "reads the curve dnmodel's gainprm F_max",
567
+ "TASKWALK_WANG_MASS_FILE": "its factors are built for a Geyer model's PROJECTED F_max x l_opt (tools/build_wang_mass_volume.py premise "
568
+ "(i): model = source x cos(pennation) each) and checked against that model's name; on a Millard model's "
569
+ "unprojected values they would put the pennated legs' 1 / cos^2 in a second time (allowed with "
570
+ "TASKWALK_MILLARD_MASS_DNMODEL, which applies it to that Geyer model's masses)",
571
+ "TASKWALK_WANG_MASS_ANATOMICAL": "needs TASKWALK_WANG_MASS_FILE (refused above)",
572
+ }
573
+
574
+
575
+ def _wang_lambda(jm):
576
+ """Wang's type I fibre fraction per muscle, by name: the rule of _mtu_param_table's loop (TASKWALK_WANG_LAMBDA_BY_STEM or
577
+ _WANG_LAMBDA, SCONE's 0.5 elsewhere, listed), for the Millard table, whose muscles carry no gainprm for that loop to read."""
578
+ lam, defaulted = [], []
579
+ lam_seen, lam_trunk = set(), 0
580
+ for m in jm["muscles"]:
581
+ key = m["name"].rsplit("_", 1)[0] if m["name"].rsplit("_", 1)[-1] in ("r", "l") else m["name"]
582
+ if key in _WANG_LAMBDA:
583
+ lam.append(_WANG_LAMBDA[key])
584
+ else:
585
+ lam.append(0.5); defaulted.append(key)
586
+ if defaulted:
587
+ print(f"[taskwalk/metabolic] lambda: {len(set(defaulted))} muscle groups fall back to SCONE's 0.5 default -> {sorted(set(defaulted))}",
588
+ flush=True)
589
+ return lam
590
+
591
+
592
+ def _millard_param_table(env):
593
+ """_mtu_param_table on a Millard 2013 model (2026-11-17; the review item M0, the predictive results on Millard).
594
+
595
+ FORCE: the muscle case's own arrays (millard_curves_torch.case_table; E0_MUSCLE_CASE, the case env14 hands the engine), so the
596
+ reward's F_MTU / F_CE are the engine's law on the engine's tables (gated by tools/d16_x14adj/millard_reward_gate.py). The case's
597
+ scalars are asserted equal to the env model's named ones, in order, as env14 asserts l_opt.
598
+
599
+ MASS, default: (F_max / 0.25 MPa) x 1059.7 x l_opt with the model's NAMED values, each muscle's own source F_max and l_opt, which
600
+ carry no pennation projection (a Geyer body's are source x cos(pennation) each, hence the cos^2 its Wang factor file undoes). So no
601
+ factor file applies (TASKWALK_WANG_MASS_FILE is refused). Differences from a Geyer twin's masses: the legs' Lai 2017 l_opt
602
+ redistribution of that file is not applied; every pennated muscle is 1 / cos^2 heavier than the Geyer projection; a scaled F_max
603
+ (P2-STR's knee extensors) scales its mass with it, where the Geyer P2-STR cells kept N1's masses (their env model was N1's).
604
+ MASS, TASKWALK_MILLARD_MASS_DNMODEL=<a Geyer dnmodel: a name under models/, or a path> (the review 11-17: the Millard twins take
605
+ the Geyer cells' masses EXACTLY): the masses are the Geyer path's, computed from that model's gainprm by the same expression and
606
+ times TASKWALK_WANG_MASS_FILE's factors exactly as the Geyer path applies them (the file allowed again, checked against that
607
+ model's name). Its muscles must be the env model's, by name, in order and count. The mass vector's md5 (float64, muscle order) is
608
+ printed, so a cell's log carries it. The other mass knobs stay refused.
609
+
610
+ LAMBDA: as the Geyer table (_wang_lambda). Refused knobs: _MILLARD_REFUSED, each with its reason."""
611
+ import hashlib as _hashlib
612
+ import json as _json
613
+ import pathlib as _pathlib
614
+ import numpy as _np
615
+ jm = env._monitor.jm
616
+ assert jm.get("muscle_model") == "millard2012", jm.get("muscle_model")
617
+ mass_key = os.environ.get("TASKWALK_MILLARD_MASS_DNMODEL", "")
618
+ for k, why in _MILLARD_REFUSED.items():
619
+ if k == "TASKWALK_WANG_MASS_FILE" and mass_key:
620
+ continue # allowed with the Geyer mass model: applied to ITS masses, as the Geyer path does
621
+ assert not os.environ.get(k, ""), f"{k} on a Millard model: {why}"
622
+ case_dir = os.environ.get("E0_MUSCLE_CASE", "")
623
+ assert case_dir, "a Millard model's in-graph force reads the muscle case's tables: E0_MUSCLE_CASE must name the case the engine runs"
624
+ names = [m["name"] for m in jm["muscles"]]
625
+ for m in jm["muscles"]:
626
+ assert "gainprm" not in m, f"{m['name']}: a Millard model's muscles carry the named OpenSim scalars, not gainprm"
627
+ curve = _millard.case_table(case_dir, names, env.device, torch.float32)
628
+ named = {k: _np.array([float(m[f]) for m in jm["muscles"]]) for k, f in
629
+ (("fmax", "max_isometric_force"), ("lopt", "optimal_fiber_length"), ("lslack", "tendon_slack_length"),
630
+ ("vmax", "max_contraction_velocity"), ("beta", "fiber_damping"))}
631
+ for k, v in named.items():
632
+ d = float(_np.abs(curve["_np"][k] - v).max() / max(1e-300, float(_np.abs(v).max())))
633
+ assert d < 1e-12, f"the case's {k} is not the env model's (max relative difference {d:.3e}): {case_dir} is another model's case"
634
+ pen = _np.array([float(m["pennation_angle_at_optimal"]) for m in jm["muscles"]])
635
+ dh = float(_np.abs(curve["_np"]["pen_h"] - named["lopt"] * _np.sin(pen)).max() / float(named["lopt"].max()))
636
+ assert dh < 1e-12, f"the case's pen_h is not the model's l_opt sin(pennation) (max {dh:.3e} of the largest l_opt)"
637
+ rig_model = _np.array([bool(m.get("rigid_tendon", False)) for m in jm["muscles"]])
638
+ rig_case = curve["_np"]["rigid"].astype(bool)
639
+ assert not (rig_model & ~rig_case).any(), "a muscle the model declares rigid is compliant in the case"
640
+ if mass_key:
641
+ mpath = _pathlib.Path(mass_key) if os.path.isabs(mass_key) else _pathlib.Path(__file__).resolve().parents[1] / "models" / mass_key
642
+ assert mpath.is_file(), f"TASKWALK_MILLARD_MASS_DNMODEL={mass_key}: no such model ({mpath})"
643
+ jm_mass = _json.loads(mpath.read_text())
644
+ assert jm_mass.get("muscle_model") == "geyer2010", (
645
+ f"TASKWALK_MILLARD_MASS_DNMODEL={mass_key} is {jm_mass.get('muscle_model')}: the twin's masses come from a Geyer model")
646
+ mnames = [m["name"] for m in jm_mass["muscles"]]
647
+ assert mnames == names, (f"TASKWALK_MILLARD_MASS_DNMODEL={mass_key}: its muscles are not the env model's in order and count "
648
+ f"({len(mnames)} vs {len(names)}; first difference "
649
+ f"{next(((i, a, b) for i, (a, b) in enumerate(zip(mnames, names)) if a != b), 'in the count')})")
650
+ # the Geyer path's mass, the same expression on the same model (_mtu_param_table: jm_mass = the env's own model there)
651
+ mass = _np.array([(float(m["gainprm"][0]) / 0.25e6) * 1059.7 * float(m["gainprm"][1]) for m in jm_mass["muscles"]])
652
+ _fac = _wang_mass_factors(env, "metabolic", model=mpath.name, names=mnames)
653
+ if _fac is not None:
654
+ mass = mass * _fac
655
+ mass_src = f"{mpath.name} + {os.environ.get('TASKWALK_WANG_MASS_FILE', '') or 'no Wang file'}"
656
+ else:
657
+ mass = (named["fmax"] / 0.25e6) * 1059.7 * named["lopt"]
658
+ mass_src = f"{os.environ.get('FULLBODY_DNMODEL', '') or 'the env model'} (named source F_max x l_opt) + no Wang file"
659
+ md5 = _hashlib.md5(_np.ascontiguousarray(mass, dtype="<f8").tobytes()).hexdigest()
660
+ print(f"[taskwalk/metabolic] masses from {mass_src}: md5 {md5}", flush=True)
661
+ lam = _wang_lambda(jm)
662
+ dev = env.device
663
+ t = lambda x: torch.as_tensor(x, dtype=torch.float32, device=dev)[:, None] # noqa: E731
664
+ print(f"[taskwalk/metabolic] Millard 2013 force from the case {case_dir}: {len(names)} muscles in the model's order, "
665
+ f"{int(rig_case.sum())} rigid, {int((curve['_np']['pen_h'] > 0).sum())} pennated; scalars = the model's named ones", flush=True)
666
+ return dict(mass=t(mass), lam=t(lam), fmax=curve["F_max"], lopt=curve["l_opt"], curve=curve,
667
+ body_mass=float(sum(float(b.get("mass", 0.0)) for b in jm["bodies"])))
668
+
669
+
670
+ def _mass_scale(env, who):
671
+ """Per-muscle factors on the muscle mass, or None. TASKWALK_MUSCLE_MASS_SCALED (opt-in; 11-14, the strength probe's STR-M control):
672
+ comma-separated STEMS whose mass is computed from the curve dnmodel's F_max (TASKWALK_MUSCLE_CURVE_DNMODEL; the stems must be
673
+ TASKWALK_MUSCLE_CURVE_FMAX_SCALED's, asserted), so mass x (F_max_curve / F_max_env): with F_max x s the mass is x s too, and the metabolic
674
+ heat per newton of force equals N1's (STR keeps N1's mass, so its price per newton is ~1 / s). Applied to BOTH masses (the metabolic table
675
+ and the volume weight) so they stay one quantity, as the Wang factors are. Unset = None, bit-identical."""
676
+ stems = ()
677
+ return None
678
+ fs = ()
679
+ path = ""
680
+ assert '', (f"TASKWALK_MUSCLE_MASS_SCALED={stems} needs TASKWALK_MUSCLE_CURVE_DNMODEL and "
681
+ f"TASKWALK_MUSCLE_CURVE_FMAX_SCALED on the same stems ({fs})")
682
+ import json as _json
683
+ byname = {m["name"]: m for m in _json.load(open(path))["muscles"]}
684
+ every = stems == ("all",) # "all": every muscle's mass from the curve dnmodel's F_max (factor 1 where equal)
685
+ out, hit = [], []
686
+ for m in env._monitor.jm["muscles"]:
687
+ n = m["name"]
688
+ stem = n.rsplit("_", 1)[0] if n.rsplit("_", 1)[-1] in ("r", "l") else n
689
+ f = float(byname[n]["gainprm"][0]) / float(m["gainprm"][0]) if (stem in stems) else 1.0
690
+ out.append(f)
691
+ if (stem in stems):
692
+ hit.append((n, f))
693
+ assert hit and ({h[0].rsplit("_", 1)[0] for h in hit} == set(stems)), (stems, hit)
694
+ _shown = hit if len(hit) <= 16 else hit[:8] + [("...", float("nan"))] + hit[-4:]
695
+ print(f"[taskwalk/{who}] muscle mass from the curve dnmodel's F_max on {len(hit)} muscles ({', '.join(f'{n} x{f:.4f}' for n, f in _shown)})",
696
+ flush=True)
697
+ return out
698
+
699
+
700
+ def _wang_anatomical_divisor(env):
701
+ """Per-muscle divisor on the METABOLIC mass for TASKWALK_WANG_MASS_ANATOMICAL (see _SIGMA_RAJAGOPAL2016): 2.4 x the volume-factor file's
702
+ scale on the file's muscles, 1 elsewhere. Requires TASKWALK_WANG_MASS_FILE built by the Rajagopal 2016 rule (asserted from the file).
703
+ Combinations, asserted not defaulted: with TASKWALK_MUSCLE_MASS_SCALED the two factors multiply (allowed); with
704
+ TASKWALK_EFFORT_N1_EQUIV=all the N1-equivalent heats read this anatomical mass (allowed). The activation term's volume weights are not
705
+ touched (the trunk's mass is unsourced)."""
706
+ import json as _json
707
+ import numpy as _np
708
+ path = os.environ.get("TASKWALK_WANG_MASS_FILE", "")
709
+ assert path, "TASKWALK_WANG_MASS_ANATOMICAL needs TASKWALK_WANG_MASS_FILE (its Rajagopal 2016 F_max l_opt rule defines the volume)"
710
+ rec = _json.load(open(path))
711
+ assert "Rajagopal 2016" in rec.get("rule", "") and any("Rajagopal2016" in s for s in rec.get("sources", [])), (
712
+ f"{path}: the anatomical divisor assumes the file's rule scale x (F_max l_opt)[Rajagopal 2016] / (F_max l_opt)[model]; got {rec.get('rule')!r}")
713
+ k = (_SIGMA_RAJAGOPAL2016 / 0.25e6) * float(rec["scale"])
714
+ names = [m["name"] for m in env._monitor.jm["muscles"]]
715
+ div = _np.array([k if n in rec["factors"] else 1.0 for n in names])
716
+ combo = []
717
+ print(f"[taskwalk/metabolic] anatomical Wang mass ON: the METABOLIC table's mass / {k:.4f} (Rajagopal 2016's 60 N/cm2 / the reward's "
718
+ f"25 N/cm2 x the volume file's scale {float(rec['scale']):.5f}) on its {int((div != 1.0).sum())} muscles = Handsfield volume x rho; "
719
+ f"the other {int((div == 1.0).sum())} unchanged; the activation term's volume weights unchanged"
720
+ + ("; " + "; ".join(combo) if combo else ""), flush=True)
721
+ return div
722
+
723
+
724
+ def _n1_equiv_scale(env):
725
+ """Per-muscle s = F_max(curve dnmodel) / F_max(env model), (n_mus, 1), or None. TASKWALK_EFFORT_N1_EQUIV (opt-in; 11-14 for the design's
726
+ "since we weakened the muscles, we also have to reduce the activation and metabolic penalties", the review): every effort term reads
727
+ the N1-EQUIVALENT activation s a (and excitation s u). A muscle at F_max x s needs a / s for the force N1 makes at a, so the price of a
728
+ given force equals N1's exactly in the activation term (w (s a')^p = w a^p, any exponent, either weighting, N1's normaliser) and in
729
+ Wang's activation and maintenance heats (mass f_A(s u'), mass f_M(s a'), N1's masses). The shortening heat and the mechanical work read
730
+ the REAL force (a', F_max'), so they match where that force is N1's. Caveat: "the same force at a / s" is exact for the active fibre
731
+ force only; the PE, the damper and (unless absolute) the tendon scale with F_max too, so on a plain F_max probe the fibre does not sit at
732
+ N1's length (closer on the passive-preserving bodies). "all" only (the curve dnmodel carries the factors); TASKWALK_MUSCLE_MASS_SCALED is
733
+ refused (a second price correction). Unset = None, bit-identical."""
734
+ v = ""
735
+ return None
736
+ assert v == "all", f"TASKWALK_EFFORT_N1_EQUIV={v!r}: only 'all' (the curve dnmodel's F_max ratio per muscle)"
737
+ path = ""
738
+ assert '', "TASKWALK_EFFORT_N1_EQUIV needs TASKWALK_MUSCLE_CURVE_DNMODEL and TASKWALK_MUSCLE_CURVE_FMAX_SCALED (the probe's F_max)"
739
+ import json as _json
740
+ byname = {m["name"]: m for m in _json.load(open(path))["muscles"]}
741
+ s = [float(byname[m["name"]]["gainprm"][0]) / float(m["gainprm"][0]) for m in env._monitor.jm["muscles"]]
742
+ assert all(0.0 < x <= 2.0 for x in s), (min(s), max(s))
743
+ hit = sum(x != 1.0 for x in s)
744
+ assert hit, f"TASKWALK_EFFORT_N1_EQUIV: no muscle's F_max differs in {path}"
745
+ print(f"[taskwalk/effort] N1-equivalent activation ON: the activation term and the activation / maintenance heats read s a (s u) with "
746
+ f"s = F_max' / F_max on {hit} muscles ({min(s):.3f}-{max(s):.3f}); masses N1's; the force terms read the real force", flush=True)
747
+ return torch.as_tensor(s, dtype=torch.float32, device=env.device)[:, None]
748
+
749
+
750
+ def _muscle_mass(env):
751
+ """Per-muscle mass (n_mus, 1), the volume weight of TASKWALK_ACTIVATION_WEIGHTING=volume: the same
752
+ (F_max/specific_tension)·density·l_opt, with the same constants, as `_mtu_param_table`'s `mass`.
753
+
754
+ Separate because the volume weight needs NOTHING else from that table, and the table asserts what only
755
+ its in-graph FORCE path needs -- no fibre damping, geyer2010 curves. The full body carries beta_damp 0.1
756
+ on all 290 muscles, so routing the weight through the table made the option crash at construction
757
+ there (2026-09-27, before its first run)."""
758
+ jm = env._monitor.jm
759
+ assert jm.get("muscle_model") != "millard2012", (
760
+ "TASKWALK_ACTIVATION_WEIGHTING=volume on a Millard model: not ported (it reads gainprm and the Geyer-projection Wang factors; "
761
+ "the paper cells run unit weighting)")
762
+ assert not os.environ.get("TASKWALK_MILLARD_MASS_DNMODEL", ""), (
763
+ "TASKWALK_MILLARD_MASS_DNMODEL on a Geyer model: it gives a Millard env the Geyer twin's masses; a Geyer env has its own")
764
+ g = [m["gainprm"] for m in jm["muscles"]]
765
+ assert all(len(x) >= 2 for x in g), "gainprm must carry [F_max, l_opt, ...] (core/io/dnmodel.h:93)"
766
+ mass = [(float(x[0]) / 0.25e6) * 1059.7 * float(x[1]) for x in g]
767
+ _fac = _wang_mass_factors(env, "volume weight")
768
+ if _fac is not None:
769
+ mass = [m_ * f_ for m_, f_ in zip(mass, _fac)]
770
+ _ms = _mass_scale(env, "volume weight")
771
+ if _ms is not None:
772
+ mass = [m_ * f_ for m_, f_ in zip(mass, _ms)]
773
+ return torch.as_tensor(mass, dtype=torch.float32, device=env.device)[:, None]
774
+
775
+
776
+ def metabolic_rate(u, a, lce, lce_dot, M, terms="all", *, mech_scale=1.0, per_muscle=False, onset_phi=None, heat_scale=None):
777
+ """Wang et al. 2012 Ė per env, in WATTS (per muscle, (n_mus, n_env), with `per_muscle`). `u`/`a`/`lce`/`lce_dot` are (n_mus, n_env).
778
+
779
+ Shared by the reward and by `tools/taskwalk_metabolic_grad_gate.py`, deliberately: a gate that
780
+ re-implements the arithmetic tests a copy. Isolated here so the gate can differentiate it WITHOUT
781
+ the env, which is required rather than tidy -- [[training-not-reproducible-same-seed]] records that
782
+ the same binary at the same seed does not reproduce, so a finite difference taken through the env
783
+ is comparing two different functions and cannot certify a gradient.
784
+
785
+ Ȧ = mass·f_A(u) f_A = 40λ·sin(π/2·u) + 133(1−λ)(1 − cos(π/2·u)) supp. Eq (15)
786
+ Ṁ = mass·g(l̃)·f_M(a) f_M = 74λ·sin(π/2·a) + 111(1−λ)(1 − cos(π/2·a)) supp. Eq (16)
787
+ Ṡ = 0.25·F_MTU·{−v_CE}₊ main §5.1
788
+ Ẇ = F_CE·{−v_CE}₊ main §5.1
789
+
790
+ `mech_scale` multiplies the MECHANICAL PAIR (Ṡ + Ẇ) only, and is a DEVIATION FROM WANG at any
791
+ value but 1.0 -- his four terms carry no relative weight. It exists because the uniform weight
792
+ sweep cannot separate two different failures: `Ṡ` and `Ẇ` are both ∝ {−v_CE}₊, i.e. proportional
793
+ to the very shortening that locomotion requires, so scaling all four terms down to rescue them
794
+ also weakens the Ȧ+Ṁ barrier that `ml26_romoff_s5` showed is what prevents a stilt. Holding the
795
+ heat terms at their measured optimum and moving only this asks whether the mechanical pair needs a
796
+ smaller coefficient (recoverable) or suppresses locomotion at every coefficient (not).
797
+ 1.0 leaves the arithmetic bit-identical, so every existing cell is unaffected.
798
+
799
+ ONSET FACTOR (TASKWALK_METABOLIC_ONSET, `onset_phi`): Bhargava, Pandy & Anderson 2004's decay function phi multiplies the
800
+ ACTIVATION heat only (their Eq. 3; the maintenance heat, Eq. 7, carries none). `onset_phi` is (n_mus, n_env), built by
801
+ TaskWalkReward._onset_phi; None = phi 1, Wang's form and bit-identical.
802
+
803
+ SHORT-LENGTH MULTIPLIER (TASKWALK_METABOLIC_SHORT_K, not Wang): when `M` carries `short_k`, the masked muscles'
804
+ four-term rate is multiplied by 1 + k * max(0, l_ref - l_ce / l_opt). Wang's rate FALLS when the soleus works
805
+ short (g(l) above), where humans pay MORE: Beck et al. 2022 measured +189% / +228% net metabolic power at the
806
+ same plantarflexion moment with the soleus fascicles 17% shorter (4.85 / 6.58 N.m). k and l_ref are both
807
+ pinned by those two levels on the calibrated calf (docs-dev/task-rl-warmstart/20261012_0025_kneepair_warm/e2_lref_pin.py,
808
+ RESULT.md section 8: l_ref 0.844, k 23.2 on ..._calf2_pe). An M without `short_k` is bit-identical.
809
+
810
+ N1-EQUIVALENT HEATS (TASKWALK_EFFORT_N1_EQUIV, `heat_scale`, (n_mus, 1)): the activation and maintenance heats read s u and s a, the
811
+ activation a muscle of N1's strength would need for the same force (see _n1_equiv_scale); the shortening heat and the mechanical work
812
+ keep the real `a` and M's F_max (the actual force). None = bit-identical.
813
+ """
814
+ hp = math.pi / 2
815
+ lam, mass = M["lam"], M["mass"]
816
+ l_til = lce / M["lopt"]
817
+ u_h, a_h = (u, a) if heat_scale is None else (heat_scale * u, heat_scale * a)
818
+ f_a = 40 * lam * torch.sin(hp * u_h) + 133 * (1 - lam) * (1 - torch.cos(hp * u_h))
819
+ if onset_phi is not None: # TASKWALK_METABOLIC_ONSET (opt-in; None = bit-identical)
820
+ f_a = onset_phi * f_a
821
+ f_m = 74 * lam * torch.sin(hp * a_h) + 111 * (1 - lam) * (1 - torch.cos(hp * a_h))
822
+ g = torch.where(l_til < 0.5, torch.full_like(l_til, 0.5),
823
+ torch.where(l_til < 1.0, l_til,
824
+ torch.where(l_til < 1.5, 3.0 - 2.0 * l_til, torch.zeros_like(l_til)))) # supp. Eq (14)
825
+ e_dot = mass * f_a + mass * g * f_m
826
+ if terms == "all" and mech_scale != 0.0:
827
+ f_mtu, f_ce = _mtu_forces(lce, lce_dot, a, M["curve"])
828
+ if M.get("force_floor", False): # TASKWALK_METABOLIC_FORCE_FLOOR (opt-in; absent = bit-identical)
829
+ f_mtu, f_ce = f_mtu.clamp_min(0.0), f_ce.clamp_min(0.0)
830
+ short = (-lce_dot).clamp_min(0.0) # v_ce>0 is LENGTHENING (curves.h:12)
831
+ e_dot = e_dot + mech_scale * (0.25 * f_mtu * short + f_ce * short)
832
+ if M.get("short_k", 0.0) != 0.0:
833
+ e_dot = e_dot * (1.0 + M["short_k"] * M["short_mask"] * (M["short_lref"] - l_til).clamp_min(0.0))
834
+ if "effort_keep" in M: # TASKWALK_EFFORT_EXCLUDE_MUSCLES (a probe knob); absent = bit-identical
835
+ e_dot = e_dot * M["effort_keep"]
836
+ return e_dot if per_muscle else e_dot.sum(dim=0)
837
+
838
+
839
+ def metabolic_per_distance(r_met, v, v0, s):
840
+ """TASKWALK_METABOLIC_PER_DIST's charge (TaskWalkReward.__init__ says why): the step's metabolic rate over a floored forward speed,
841
+ r_met / v_eff with v_eff = v0 + s ln(1 + exp((v - v0) / s)) >= v0 > 0. Above v0 + several s it is r_met / v; well below v0 it is
842
+ r_met / v0; smooth at v0 (d v_eff / d v = sigmoid((v - v0) / s)); no sign flip at v < 0. Differentiable through r_met and v.
843
+ Shared by the reward and python/tests/test_metabolic_per_dist.py, so the test checks the arithmetic the reward runs."""
844
+ return r_met / (v0 + s * torch.nn.functional.softplus((v - v0) / s))
845
+
846
+
847
+ def effort_speed_gate(r_total, effort, w_track, r_track, k):
848
+ """M2 (TASKWALK_EFFORT_SPEED_GATE_K, TaskWalkReward.__init__ says why): a total that ADDED w_track r_track and SUBTRACTED effort,
849
+ rewritten to pay w_track r_track exp(-k effort) instead (the effort gated by the speed reward the step earns). Shared by the reward and
850
+ python/tests/test_speed_constraint_m1_m4.py."""
851
+ return r_total + effort - w_track * r_track * (1.0 - torch.exp(-k * effort))
852
+
853
+
854
+ def effort_per_distance(r_total, effort, v, v_cmd, f0, fs):
855
+ """M3 (TASKWALK_EFFORT_PER_DIST, TaskWalkReward.__init__ says why): a total that SUBTRACTED effort, rewritten to subtract
856
+ effort v_cmd / v_eff (metabolic_per_distance's floored speed with v0 = f0 v_cmd, s = fs v_cmd). Shared with the test."""
857
+ return r_total + effort - metabolic_per_distance(effort * v_cmd, v, f0 * v_cmd, fs * v_cmd)
858
+
859
+
860
+ def lane_heading_reward(f, l, valid_prev, k, v_min):
861
+ """TASKWALK_MID_LANE_FORM=heading's term (TaskWalkReward.__init__ says why): exp(-k psi^2), psi = atan2(l, f) of the low-passed COM
862
+ velocity in the command frame, where the heading exists (a valid rate and f^2 + l^2 >= v_min^2); exactly 1 elsewhere, with the INPUTS
863
+ substituted so atan2 is never evaluated at (0, 0). torch.where only (no host reads): capturable. Shared with its test."""
864
+ ok = f * f + l * l >= v_min * v_min
865
+ if valid_prev is not None:
866
+ ok = ok & valid_prev
867
+ else:
868
+ ok = torch.zeros_like(ok)
869
+ psi = torch.atan2(torch.where(ok, l, torch.zeros_like(l)), torch.where(ok, f, torch.ones_like(f)))
870
+ return torch.exp(-k * psi * psi)
871
+ # Bhargava, Pandy & Anderson 2004 Eq. 6 (TASKWALK_METABOLIC_ONSET): tau_phi 45 ms, the 6 % floor, the 10 % excitation threshold
872
+ _ONSET_TAU, _ONSET_FLOOR, _ONSET_THR = 0.045, 0.06, 0.10
873
+
874
+ class TaskWalkReward:
875
+ """Stateful because three terms are rate terms (COM velocity, head angular velocity, excitation
876
+ smoothness): they need the previous control step. `reset(env_ids)` clears those for restarted envs so
877
+ a reset never manufactures a huge finite difference."""
878
+ _n1eq_s = None # TASKWALK_EFFORT_N1_EQUIV's per-muscle s, set in the env setup; the class default keeps it off everywhere else
879
+ keep_parts = False # TASKWALK_LOG_TERMINALS: the env sets it True to read the step's speed parts (detached); default off
880
+
881
+ def _stop_table(self, dev, dtype):
882
+ """TASKWALK_LIMIT_TORQUE_STOP's per-joint constants, in self._lim's row order: each row's law limit row, found by the dnmodel
883
+ link's (body name, joint name) (a name alone lands on a same-named chain's phantom link), with its solref / solimp and the law's
884
+ diagA; the ranges asserted equal (the reward's q and the law's coordinate are the same hinge)."""
885
+ import json as _json, pathlib as _pathlib, re as _re
886
+ law_p = getattr(self.env, "_tw_law_path", None)
887
+ assert law_p is not None, "TASKWALK_LIMIT_TORQUE_STOP reads the D16 law's limit rows: env14 sets env._tw_law_path (E0_ENGINE14)"
888
+ law = _json.loads(_pathlib.Path(law_p).read_text())
889
+ jm = _json.loads(_re.sub(r"^\s*//.*$", "", _pathlib.Path(str(self.env.model)).read_text(), flags=_re.M))
890
+ jname = {int(b["qadr"]): b.get("joint_name") for b in jm["bodies"]
891
+ if b.get("joint") in ("revolute", "slide") and "coupled" not in b and "qadr" in b}
892
+ LB = law["bodies"]
893
+ rows = {(LB[e["body"]]["name"], LB[e["body"]]["joint_name"]): e for e in law["limits"] if not e.get("coupled")}
894
+ cols = []
895
+ for qa, lo, hi, nm in zip(self._lim["q"], self._lim["lo"], self._lim["hi"], self._lim["names"]):
896
+ if not any(nm.startswith(pfx) for pfx in self.limit_torque_stop_joints):
897
+ cols.append((1.0, 1.0, 0.9, 0.95, 1e-3, 0.5, 2.0, 1.0, 0.0)) # not selected: a neutral row, priced 0 (sel 0)
898
+ continue
899
+ e = rows.get((nm, jname[int(qa)]))
900
+ assert e is not None, f"TASKWALK_LIMIT_TORQUE_STOP: no law limit row for {nm} ({jname[int(qa)]})"
901
+ assert abs(e["range"][0] - lo) < 1e-6 and abs(e["range"][1] - hi) < 1e-6, (nm, e["range"], lo, hi)
902
+ (tc, dr), (dmin, dmax, width, mid, power) = e["solref"], e["solimp"]
903
+ cols.append((tc, dr, dmin, dmax, width, mid, power, float(e["diagA"]), 1.0))
904
+ assert any(c[-1] for c in cols), f"TASKWALK_LIMIT_TORQUE_STOP_JOINTS={self.limit_torque_stop_joints} matches no limited joint {self._lim['names']}"
905
+ t = torch.tensor(cols, dtype=dtype, device=dev).t().unsqueeze(-1) # (9, nlim, 1)
906
+ return dict(zip(("tc", "dr", "dmin", "dmax", "width", "mid", "power", "diagA", "sel"), t))
907
+
908
+ def _stop_torque(self, qk, vk, dlo, dhi):
909
+ """(nlim, n): the solver's stop, unilateral, + past the lower bound and - past the upper, MuJoCo's soft-limit law at the row's
910
+ impedance with the law's diagA, gated HARD past the bound as the solver activates its row (see __init__); 0 on unselected joints"""
911
+ if self._stop_t is None:
912
+ self._stop_t = self._stop_table(qk.device, qk.dtype)
913
+ S = self._stop_t
914
+
915
+ def one(pen, v_in): # pen: penetration (bound - q or q - bound), v_in: velocity into the stop
916
+ r = pen.clamp_min(0.0) # the row exists only past the bound (margin 0)
917
+ x = (r / S["width"]).clamp(max=1.0)
918
+ y = torch.where(x <= S["mid"], x ** S["power"] / S["mid"] ** (S["power"] - 1),
919
+ 1.0 - (1.0 - x) ** S["power"] / (1.0 - S["mid"]) ** (S["power"] - 1))
920
+ d = S["dmin"] + y * (S["dmax"] - S["dmin"])
921
+ K = d * d / (S["dmax"] ** 2 * S["tc"] ** 2 * S["dr"] ** 2 * (1.0 - d) * S["diagA"])
922
+ B = 2.0 * d / (S["dmax"] * S["tc"] * (1.0 - d) * S["diagA"])
923
+ return (K * r + B * v_in * (pen > 0.0).to(pen.dtype)).clamp_min(0.0)
924
+ return (one(dlo, -vk) - one(dhi, vk)) * S["sel"]
925
+
926
+ @staticmethod
927
+ def _limit_layout(env):
928
+ """(qadr, vadr, lo, hi) for every LIMITED 1-DOF joint, and (k_lim, beta, d_lim) as the ENGINE
929
+ sees them. Returns None when the model carries no passive block.
930
+
931
+ THE OVERRIDES ARE APPLIED HERE TOO. core/io/dnmodel.h:551 lets DN_PASSIVE_K_LIM / _BETA /
932
+ _D_LIM replace the artifact's values at load, so a reward that read only the file would price a
933
+ stop the engine is not integrating. Read the file, then apply the same three overrides.
934
+
935
+ 1-DOF ONLY, and that is a real limitation, not an oversight: a Ball joint's range of motion goes
936
+ through core/dyn/ball_limit.h on an Euler chart, not through passive_force's `limited[]` mask,
937
+ so the Ball hips are absent from this and the limit terms do not price them. On myoleg26 that
938
+ leaves the knees, ankles and MTPs -- which is where this line's stop problem lives.
939
+ """
940
+ import json as _json, os as _os, pathlib as _pathlib, re as _re
941
+ raw = _pathlib.Path(str(env.model)).read_text()
942
+ jm = _json.loads(_re.sub(r"^\s*//.*$", "", raw, flags=_re.M))
943
+ if "passive" not in jm:
944
+ return None
945
+ k_lim, beta, d_lim = (float(x) for x in jm["passive"]["params"])
946
+ for var, i in (("DN_PASSIVE_K_LIM", 0), ("DN_PASSIVE_BETA", 1),
947
+ ("DN_PASSIVE_D_LIM", 2)):
948
+ e = _os.environ.get(var)
949
+ if e is not None:
950
+ k_lim, beta, d_lim = [float(e) if j == i else v
951
+ for j, v in enumerate((k_lim, beta, d_lim))]
952
+ # The engine's quintic-gated "opensim" law (passive.h limit_smoothstep) is not reproduced here.
953
+ assert jm["passive"].get("limit_law", "srelu") == "srelu", (
954
+ f"passive.limit_law {jm['passive'].get('limit_law')!r}: the limit terms implement only the srelu / exponential law")
955
+ nq = {"free": 7, "ball": 4, "revolute": 1, "slide": 1, "fixed": 0}
956
+ nv = {"free": 6, "ball": 3, "revolute": 1, "slide": 1, "fixed": 0}
957
+ # THE ENGINE'S RULE (core/io/dnmodel.h passive layer): a fixed body and a COUPLED ("mimic") body own no DOF --
958
+ # the loader skips both, and the file gives a coupled body the ALIASED address of the next owned DOF -- and a
959
+ # limit applies only where `limited` is set. The old walk summed every revolute's width and took any `range`,
960
+ # which is the same thing on an uncoupled model (every myoLeg26 file) but on the spine-coupled full body counted
961
+ # 15 lumbar mimics as their own DOFs: the knee came out at q 29 of 26 and the reward's gather faulted on the GPU
962
+ # (fb_bolt_sprint_s1's knob check, 2026-09-28). The walk is also wrong on a COMPOUND body (several hinges in one
963
+ # body own several DOFs), so the addresses come from the file's own qadr/vadr, which are the loader's.
964
+ out = []
965
+ for b in jm["bodies"]:
966
+ j = b.get("joint", "fixed")
967
+ own = j != "fixed" and "coupled" not in b
968
+ if own and j in ("revolute", "slide") and b.get("limited") and b.get("range") is not None:
969
+ assert "qadr" in b and "vadr" in b, f"{b.get('name')}: a limited joint without qadr/vadr in the file"
970
+ lo, hi = (float(x) for x in b["range"])
971
+ # PER-DOF limit damper and stiffness, resolved in the loader's order (core/io/dnmodel.h): the
972
+ # body's `d_lim`, then its `limit` block (read after it, so it wins), else the scalar; a
973
+ # DN_PASSIVE_D_LIM override replaces the whole array. The committed models carry
974
+ # tools/limit_damping.py's per-joint values (toes 0.23, ankle 1.7, knee 13.7 N.m.s/rad); pricing
975
+ # the scalar 327.7 instead charged the toe damper ~1400x (v25, 2026-10-05).
976
+ d_i, k_i = d_lim, k_lim
977
+ if "d_lim" in b:
978
+ d_i = float(b["d_lim"])
979
+ if "limit" in b:
980
+ Lb = b["limit"]
981
+ assert float(Lb["k_up"]) == float(Lb["k_lo"]), f"{b['name']}: asymmetric limit stiffness"
982
+ k_i, d_i = float(Lb["k_up"]), float(Lb["damping"])
983
+ if _os.environ.get("DN_PASSIVE_D_LIM") is not None:
984
+ d_i = d_lim
985
+ out.append((int(b["qadr"]), int(b["vadr"]), lo, hi, d_i, k_i, str(b.get("name", ""))))
986
+ if not out:
987
+ return None
988
+ # THE EXPONENTIAL BRANCH, because that is the law the ENGINE runs on this model family.
989
+ # `core/dyn/passive.h:167` is an either/or: `spring = exp_a > 0 ? limexp(dlo)-limexp(dhi)
990
+ # : k_lim*(srelu(dlo)-srelu(dhi))`, so on any model carrying a `passive.exp` block the
991
+ # `k_lim` branch is DEAD CODE and pricing it prices a torque nothing applies. Measured on
992
+ # `myoleg26_3d_kneeexp_pub` (exp = [6.72, 0.06023], k_lim = 2000) at the knee:
993
+ # q = -10 deg (inside) engine -0.37 N.m k_lim law 0.00 <- term blind
994
+ # q = 0 deg (the stop) engine -6.72 k_lim law -1.39 <- 4.8x UNDER
995
+ # q = +2 deg (past) engine -12.0 k_lim law -69.8 <- 5.8x OVER
996
+ # i.e. the old reading was not merely mis-scaled, it had the wrong SHAPE and no single weight
997
+ # could fix it. Models with no `exp` block keep the `k_lim` law and are bit-identical.
998
+ exp_a = exp_w = 0.0
999
+ if isinstance(jm["passive"].get("exp"), (list, tuple)):
1000
+ exp_a, exp_w = (float(x) for x in jm["passive"]["exp"])
1001
+ # the loader applies these two overrides as well, with or without an `exp` block in the file
1002
+ if _os.environ.get("DN_PASSIVE_EXP_A") is not None:
1003
+ exp_a = float(_os.environ["DN_PASSIVE_EXP_A"])
1004
+ if "exp" not in jm["passive"]:
1005
+ exp_w = 1.0 # PassiveParams' default width
1006
+ if _os.environ.get("DN_PASSIVE_EXP_W") is not None:
1007
+ exp_w = float(_os.environ["DN_PASSIVE_EXP_W"])
1008
+ assert exp_a == 0.0 or exp_w > 0.0, f"passive.exp width must be positive, got {exp_w}"
1009
+ # The model's COORDINATE SPRINGS on these joints (jm["coord_springs"], the engine's SpringGeneralizedForce
1010
+ # tau = -k (q - rest); the Falisse 2022 toe on the mtp60k25 bodies), per limited joint, 0 where there is none.
1011
+ # Read for TASKWALK_LIMIT_TORQUE_SPRINGS only; carried always so the layout says what the body has.
1012
+ spr = {int(c["qadr"]): (float(c["stiffness"]), float(c["rest"])) for c in jm.get("coord_springs", [])}
1013
+ return dict(q=[o[0] for o in out], v=[o[1] for o in out],
1014
+ lo=[o[2] for o in out], hi=[o[3] for o in out],
1015
+ d_lim_v=[o[4] for o in out], k_lim_v=[o[5] for o in out], names=[o[6] for o in out],
1016
+ spring_k=[spr.get(o[0], (0.0, 0.0))[0] for o in out], spring_rest=[spr.get(o[0], (0.0, 0.0))[1] for o in out],
1017
+ k_lim=k_lim, beta=beta, d_lim=d_lim, exp_a=exp_a, exp_w=exp_w)
1018
+
1019
+ @staticmethod
1020
+ def _model_knee_bound(env):
1021
+ """The knee's EXTENSION-side range bound, in radians, read from the .dnmodel the env integrates.
1022
+
1023
+ Which side is "extension" is per-model: myoleg26 flexes negative (range [-145, 0] -> the bound is
1024
+ the UPPER end), armless_ball flexes positive (range [0, +120] -> the LOWER end). knee_sign already
1025
+ encodes that, so pick the end r_joint_limit is written against. Falls back to 0.0 when the model carries no
1026
+ range for that dof, which is the historical default.
1027
+ """
1028
+ import json as _json, pathlib as _pathlib, re as _re
1029
+ try:
1030
+ raw = _pathlib.Path(str(env.model)).read_text()
1031
+ jm = _json.loads(_re.sub(r"^\s*//.*$", "", raw, flags=_re.M))
1032
+ except Exception:
1033
+ return 0.0
1034
+ m = _DOF_MAPS.get(env.nq)
1035
+ if m is None:
1036
+ return 0.0
1037
+ want, sign = int(m["knee_r"]), float(m["knee_sign"])
1038
+ for b in jm.get("bodies", []):
1039
+ if b.get("coupled") is not None or "qadr" not in b or "range" not in b:
1040
+ continue
1041
+ if int(b["qadr"]) != want:
1042
+ continue
1043
+ lo, hi = float(b["range"][0]), float(b["range"][1])
1044
+ # knee_sign -1: flexes negative, extension is the HIGH end. +1: flexes positive, extension is LOW.
1045
+ return hi if sign < 0 else lo
1046
+ return 0.0
1047
+
1048
+ def __init__(self, env):
1049
+ self.env = env
1050
+ m = _DOF_MAPS.get(env.nq)
1051
+ assert m is not None, (
1052
+ f"TaskWalkReward has no dof map for nq={env.nq} (known: "
1053
+ f"{ {k: v['name'] for k, v in _DOF_MAPS.items()} }). Add one rather than letting the indices "
1054
+ "silently point at other joints.")
1055
+ _lum = m["lumbar_flex"]
1056
+ self.i_lumbar = None if _lum is None else int(_lum)
1057
+ self.i_hip_r = int(m["hip_r"])
1058
+ self.i_hip_l = int(m["hip_l"])
1059
+ self.i_knee_r = int(m["knee_r"])
1060
+ self.i_knee_l = int(m["knee_l"])
1061
+ self.i_head = int(m["head_body"])
1062
+ self.knee_sign = float(m["knee_sign"])
1063
+
1064
+ # --- REWARD MODE -------------------------------------------------------------------------------
1065
+ # "taskwalk" (default) is everything below. "shac_snu" REPLACES the whole reward and its fall test
1066
+ # with SHAC's Humanoid MTU task (Xu et al., ICLR 2022, arXiv:2204.07137, appendix A.3.6: Lee et
1067
+ # al. 2019's lower body, 152 MTUs), eq. 23-25:
1068
+ # R = v_x + 0.1 R_up + R_heading + R_height - 0.001 ||a||^2
1069
+ # R_height = -200 dh^2 (dh < 0), 4 dh (dh >= 0), dh = clip(h - 0.51, -1, 0.05)
1070
+ # terminate when the pelvis height h < 0.46 m
1071
+ # The PAPER, not the DiffRL code (envs/snu_humanoid.py), which differs in two places: it charges
1072
+ # the L1 norm (the L2 line is commented out) and computes R_height but never adds it.
1073
+ # `h` is SNU metres. SNU's model stands at 0.9686 m and ours at a different height with the pelvis
1074
+ # origin at a different place, so the env supplies h_snu = H_SCALE * q_z + H_OFFSET. Both are
1075
+ # REQUIRED: a default would be a constant nobody measured.
1076
+ self.reward_mode = "taskwalk"
1077
+
1078
+ # --- weights: configs/uneven_syn.yaml `w:` ------------------------------------------------
1079
+ self.w_speed_track = _f("TASKWALK_W_SPEED_TRACK", 10.0) # gaussian_vel: 10
1080
+ # The authors' 0.1 is on a SUM over 90 muscles; our formula is the MEAN, so the equivalent
1081
+ # weight is 0.1*90 = 9.0. Default 10 (the run's value, a deliberate round-up) so the code is
1082
+ # self-consistent without an env var -- leaving 0.1 here would make the term inert by default.
1083
+ self.w_activation = _f("TASKWALK_W_ACTIVATION", 10.0)
1084
+ self.activation_exp = _f("TASKWALK_ACTIVATION_EXP", 2.0) # see the effort term; 2.0 keeps every cell bit-identical
1085
+ self.activation_aref = 0.2 # normaliser for the exponent ladder, see below
1086
+ # ACKERMANN'S OTHER AXIS. Ackermann & van den Bogert 2010 (J Biomech 43:1055) Table 1 is a 2x4
1087
+ # grid: the exponent p above, CROSSED with a per-muscle weight omega_i in {1, muscle volume}.
1088
+ # `TASKWALK_ACTIVATION_EXP` walks the p row; this walks the omega column (run on myoLeg26 as
1089
+ # ml26_fxfhsc_volw_s1/_s2: knee_hs -11.6 / -18.7, knee_dip 0.00 -- straight-legged, as the paper
1090
+ # says; first full-body run 2026-09-27). Their finding is that the two columns disagree at p <= 3 -- unit weights flex the
1091
+ # stance knee, volume weights go straight-legged -- because "the use of muscle volume-based
1092
+ # weighting factors favors activation of smaller muscles such as the Gastrocnemius and inhibits
1093
+ # the activation of larger muscle groups as the Vasti", and the vasti is what a loading response
1094
+ # needs. Volume is proportional to Wang's per-muscle MASS and the normaliser divides the constant
1095
+ # density out, so this reuses that table rather than inventing a density.
1096
+ # "unit" is the shipped behaviour and is bit-identical.
1097
+ self.activation_weighting = os.environ.get("TASKWALK_ACTIVATION_WEIGHTING", "unit")
1098
+ assert self.activation_weighting in ("unit", "volume"), (
1099
+ f"TASKWALK_ACTIVATION_WEIGHTING must be 'unit' or 'volume', got {self.activation_weighting!r}")
1100
+ self.w_joint_limit = _f("TASKWALK_W_JOINT_LIMIT", 25.0) # rom: -25
1101
+ # STEP FORM OF THE SAME BOUND, added 2026-09-10 on request. `W_JOINT_LIMIT` charges
1102
+ # the violation in RADIANS and is linear in it; this charges a flat 1 PER LEG that is past
1103
+ # `knee_min` and nothing otherwise, so a small violation costs exactly what a large one does.
1104
+ # The two share `knee_min` and are independent weights, so a cell can run either or both.
1105
+ # WHAT IT COSTS: a step has ZERO derivative away from the threshold, so this term contributes
1106
+ # NOTHING to the pathwise gradient that SAPO/SHAC differentiates through the simulator -- it
1107
+ # reaches the policy only through the critic. The linear form's constant dkr/dq = +-1 inside
1108
+ # the violated region is very likely how W_JOINT_LIMIT moves a converged knee 49 deg while
1109
+ # reading exactly 0.0000 at the optimum. Measure with tools/gait/reward_grad_probe.py before
1110
+ # reading any result from this term as evidence about the BOUND rather than about gradients.
1111
+ self.w_joint_limit_step = 0.0
1112
+ # THE EXPONENT ON THE KNEE VIOLATION, added 2026-09-13. 1.0 is the linear form above and every
1113
+ # existing cell is bit-identical at the default.
1114
+ #
1115
+ # WHY IT IS NEEDED, measured rather than argued. With the knee's passive curve set to published
1116
+ # stiffness (k_lim 184, beta 0.0576), W_JOINT_LIMIT was bisected across [0, 5]:
1117
+ #
1118
+ # W_ROM 0 0.25 0.5 1 5
1119
+ # knee_hs +13.25 +14.18 +11.70 -61.89 -62.59
1120
+ # past 14.38 14.46 13.63 0.00 0.00
1121
+ #
1122
+ # Three weights spanning a factor of two leave the knee within a degree of the same
1123
+ # hyperextension, and the next step flips it seventy-three degrees into a crouch. That is what a
1124
+ # CONSTANT-GRADIENT penalty does against a SATURATING support: `srelu`'s stiffness rises to
1125
+ # k_lim and stops, so beyond the knee of the curve the marginal benefit of leaning further is
1126
+ # fixed, and so is the marginal cost. Either the cost is below the benefit everywhere -- lean in
1127
+ # until the geometry stops you -- or above it everywhere -- never approach the bound at all.
1128
+ # No weight makes them balance at an intermediate angle, so no weight produces an interior.
1129
+ # The note at `w_joint_limit_step` above already suspected this: "the linear form's constant
1130
+ # dkr/dq = +-1 inside the violated region is very likely how W_JOINT_LIMIT moves a converged
1131
+ # knee 49 deg while reading exactly 0.0000 at the optimum."
1132
+ #
1133
+ # An exponent above 1 makes the marginal cost GROW with the violation, so it crosses the fixed
1134
+ # marginal benefit at a finite penetration and an interior equilibrium exists. 2.0 is the
1135
+ # ordinary quadratic and matches the form used for passive joint moments in the musculoskeletal
1136
+ # literature, where resistance past a bound rises faster than linearly rather than at a fixed
1137
+ # rate. The STEP form is the opposite extreme -- zero gradient -- and neither of the two shapes
1138
+ # this reward already had has a gradient that grows.
1139
+ #
1140
+ # UNITS MOVE WITH THE EXPONENT. The violation is in RADIANS, so at 14 deg (0.244 rad) the linear
1141
+ # term reads 0.244 and the square reads 0.0596. A weight carried over unchanged is a 4x cut in
1142
+ # magnitude and a much larger cut in gradient near the bound; scale it deliberately.
1143
+ # SMOOTHING, and it is the one property that separates the terms that WORK on this line from
1144
+ # the ones that do not. `clamp_min(0)` makes this penalty identically ZERO at the bound and
1145
+ # everywhere inside it, so a knee resting exactly on its stop sits at a global minimum of the
1146
+ # term with no gradient pushing it inward -- and once a large weight does push it past the
1147
+ # bound, the flat interior gives no signal about where to stop, so it falls to a crouch. That
1148
+ # is exactly the measured behaviour: six angle-based forms all landed either ON the stop or in
1149
+ # a collapsed crouch, with no interior.
1150
+ #
1151
+ # `TASKWALK_W_LIMIT_TORQUE` and `_POWER` do not have that shape. Both are built on `_srelu`,
1152
+ # whose value and derivative stay nonzero several degrees INSIDE the bound (at beta = 0.0576
1153
+ # rad = 3.30 deg the spring still reads 2.20 N.m at 3.3 deg inside and 0.85 at 10 deg), so
1154
+ # their minimum is strictly interior and there is a gradient that positions the joint rather
1155
+ # than only forbidding the boundary. Both produced a knee off the stop with a human-sized
1156
+ # loading response where every clamp-based form failed.
1157
+ #
1158
+ # This knob puts the SAME smoothing on the angle term so the two can be compared as shapes at
1159
+ # matched magnitude, instead of the comparison being confounded with torque-vs-angle. 0.0
1160
+ # keeps the hard clamp and leaves every cell on record bit-identical; a positive value is the
1161
+ # beta in radians, and passing the model's own passive beta makes the angle term reach as far
1162
+ # inside the bound as the limit terms do.
1163
+ self.joint_limit_beta = _f("TASKWALK_JOINT_LIMIT_BETA", 0.0)
1164
+ assert self.joint_limit_beta >= 0.0, (
1165
+ f"TASKWALK_JOINT_LIMIT_BETA={self.joint_limit_beta} must be >= 0; it is a smoothing WIDTH "
1166
+ f"in radians, and 0 means the hard clamp this reward has always used")
1167
+ # --- METABOLIC EFFORT, Wang et al. 2012 (docs/training/concepts/metabolic-effort-term.md) -----
1168
+ # Ė = Ȧ + Ṁ + Ṡ + Ẇ, the same four terms SCONE's EffortMeasure::GetWang2012 computes, verified
1169
+ # against the paper AND its supplement. Charged PER STEP because Wang's objective is a trial
1170
+ # AVERAGE RATE (main paper §5.1, J_M = Ḃ + (1/T)ΣΣĖ) -- it is NOT a cost of transport; that is
1171
+ # SCONE's addition and does not transfer to a per-step reward.
1172
+ # NORMALISED BY BODY MASS so the weight is scale-free, following Wang's own w_e = 0.004/mass.
1173
+ # 0 => off and every earlier run is bit-identical.
1174
+ self.w_metabolic_rate = _f("TASKWALK_W_METABOLIC_RATE", 0.0)
1175
+ # WHICH TERMS. "heat" = Ȧ + Ṁ only; "all" additionally charges Ṡ + Ẇ.
1176
+ # DEFAULT IS "all" AGAIN, since 2026-08-31. It was briefly "heat" because Ṡ and Ẇ took F_MTU
1177
+ # from the coupling stage's side channel, which detaches on purpose (gpu_bridge.py:190), and a
1178
+ # stop-gradient force made the gradient point the WRONG WAY (analytic -2.54 against FD +5.16).
1179
+ # The force is now computed IN-GRAPH from l_ce, v_ce and A via the residual rearrangement in
1180
+ # geyer_curves_torch (checked against the engine kernel by test_geyer_curves_torch), so no
1181
+ # engine change and no detached tensor. "heat" is kept because it is what the 0.03-1.0 weight
1182
+ # sweep was run on, and those cells are only reproducible with it.
1183
+ self.metabolic_terms = os.environ.get("TASKWALK_METABOLIC_RATE_TERMS", "all")
1184
+ assert self.metabolic_terms in ("heat", "all"), self.metabolic_terms
1185
+ # A SEPARATE SCALE ON Ṡ + Ẇ, which Wang does not have -- see metabolic_rate's docstring for why
1186
+ # it is needed to tell "the mechanical pair needs a smaller coefficient" apart from "the
1187
+ # mechanical pair suppresses locomotion at every coefficient". 1.0 = Wang, and bit-identical.
1188
+ self.metabolic_mech = 1.0
1189
+ # SQUARED PER-MUSCLE METABOLIC RATE, added 2026-10-02: Falisse et al. 2019 (J R Soc Interface 16:20190402,
1190
+ # eq. 2.1) minimise (1/d) int [w1 ||Edot||^2 + w2 ||a||^2 + ...], Edot the per-muscle metabolic rate (their
1191
+ # smooth Bhargava model; here Wang 2012, `metabolic_rate(per_muscle=True)`), w1 = 500/92/body mass on the
1192
+ # squared 2-norm over muscles. Their sensitivity analysis: NOT squaring or removing this term increased
1193
+ # stance knee flexion (and trunk sway, step width); the nominal criterion gave an extended mid-stance knee.
1194
+ # Squaring prices CONCENTRATION: one muscle carrying a large sustained rate costs far more than the same
1195
+ # energy spread. Measured 2026-10-02 on the taskwalk control's mid-stance: soleus_r is 69% of this sum
1196
+ # (26% of the linear one), the imitation's is spread (soleus 16, gastrocnemius 16, vasti 15%).
1197
+ # Value: sum_i Edot_i^2 / (n_mus * body mass), Falisse's own normalisation (the muscle count, body mass), in
1198
+ # W^2/kg. Needs the fibre velocity; run it with TASKWALK_LCE_DOT_COUPLED=1 (value-free) or the mechanical
1199
+ # pair's gradient is the one-sided 1/dt artefact recorded at TASKWALK_LCE_DOT_COUPLED. 0 = OFF.
1200
+ self.w_metabolic_sq = _f("TASKWALK_W_METABOLIC_SQ", 0.0)
1201
+ assert self.w_metabolic_sq >= 0.0, "TASKWALK_W_METABOLIC_SQ is a cost weight, >= 0"
1202
+ self.w_fall_penalty = _f("TASKWALK_W_FALL_PENALTY", 250.0) # fall: -250
1203
+ # ALIVE BONUS, per step, while not fallen. 0 = OFF and every earlier run is bit-identical.
1204
+ #
1205
+ # WHY IT MAY BE NEEDED. Every term in this reward except r_speed_track is a PENALTY. At a commanded
1206
+ # speed the policy cannot reach, g_fwd = exp(-c e^2/var) is ~3e-14 (measured: |v_fwd - v_tgt| =
1207
+ # 1.594 m/s for an untrained policy at V_HI=2.5), and since r_speed_track = g_fwd*g_lat*g_hw is a
1208
+ # PRODUCT the whole w=10 positive term is off. The per-step reward is then purely negative --
1209
+ # measured -2.6 to -4.9 -- so **every step alive costs return**, and the only way to improve is
1210
+ # to shed effort and rom, i.e. to stop moving. That is exactly the stilt this campaign keeps
1211
+ # producing at 0.7-2.5.
1212
+ #
1213
+ # WHAT IT DOES NOT DO, stated so the result is not over-read: a stilt survives too (4-5/8), so a
1214
+ # flat alive bonus pays it as well. This removes the "living is negative" pathology; it does not
1215
+ # by itself make walking fast pay better than locking up.
1216
+ self.w_alive_bonus = _f("TASKWALK_W_ALIVE_BONUS", 0.0)
1217
+ # --- SPRINT: maximise forward speed instead of tracking a commanded one --------------------
1218
+ # + w_speed_max * v_com,x [monotone, uncapped, signed]
1219
+ # This is the sprint task, and it is a DIFFERENT SHAPE from r_speed_track, not a retuning of
1220
+ # it. Both sprint papers maximise: Bolt (arXiv:2609.11083) pays `1e-2 * v_x(pelvis)` and
1221
+ # lambda-hold (arXiv:2608.17030) pays `exp(v_x)`; neither tracks a target. Linear rather than
1222
+ # lambda-hold's exponential so the marginal value of a m/s stays constant and a critic can fit
1223
+ # it. See docs/design/sprint-myoleg26.md.
1224
+ #
1225
+ # WHY A TARGET SPEED WOULD NOT WORK HERE, which is the whole reason this term exists. A
1226
+ # gaussian tracking gate's gradient is dead outside roughly [0.05, 0.5] m/s of error (peak at
1227
+ # e* = sigma/sqrt(2c) = 0.20); measured on an untrained policy at V_HI=2.5 the error is
1228
+ # 1.594 m/s and g_fwd ~ 3e-14, and r_speed_track is a PRODUCT so the whole velocity term
1229
+ # switches off. A sprint target would have to be set at a speed nobody has measured this model
1230
+ # can reach, i.e. exactly where the gate is dead. `w * v` has gradient `w` everywhere.
1231
+ #
1232
+ # ADDITIVE, NOT A FACTOR. It is deliberately not multiplied into the gate product: v_fwd is
1233
+ # SIGNED, so inside a product a tighter lateral gate would make a backwards rollout score less
1234
+ # negative and sway would be rewarded. Bolt is additive for the same reason; lambda-hold can
1235
+ # multiply only because exp(v_x) > 0.
1236
+ #
1237
+ # The term is UNBOUNDED above by construction. What bounds the return is the fall termination
1238
+ # and the episode length, which is also Bolt's arrangement (their `velocity_reward_max`, a
1239
+ # tent capped at a target speed, exists in reward_lib and no environment calls it).
1240
+ self.w_speed_max = _f("TASKWALK_W_SPEED_MAX", 0.0)
1241
+ # WHICH VELOCITY the speed term pays. "com" (default, every earlier run) = v_com[0], the COM's
1242
+ # finite difference below. "root" = the root origin's world-x velocity read off the STATE, R v_body,
1243
+ # which is what Bolt pays (`velocity_reward` on the pelvis, docs/design/sprint-myoleg26.md sec. 2)
1244
+ # and what SHAC pays (`_shac_snu`).
1245
+ # WHY IT IS NOT A DETAIL under a pathwise learner. `_rate` detaches the stored previous sample, so
1246
+ # the in-graph derivative of a window's sum of w * v_com,x is (w/dt) * sum_t dcom_t/dtheta, not the
1247
+ # telescoped (w/dt) * dcom_H/dtheta of the quantity it computes: every step re-pays the position it
1248
+ # inherited. For a sustained push that over-weights the speed gradient by ~H/2 (16x at H 32) and
1249
+ # loads it onto the window's EARLY actions. qd is state, so the root signal's derivative is exact.
1250
+ # Full body only: it reads the root as (x, y, z, w, x, y, z) with qd[3:6] body-frame linear, the
1251
+ # layout `_shac_snu` asserts; myoleg26 orders its free joint differently.
1252
+ self.speed_max_signal = os.environ.get("TASKWALK_SPEED_MAX_SIGNAL", "com")
1253
+ assert self.speed_max_signal in ("com", "root"), (
1254
+ f"TASKWALK_SPEED_MAX_SIGNAL={self.speed_max_signal!r}; known: 'com', 'root'")
1255
+ if self.speed_max_signal == "root":
1256
+ assert env.nq in _FULLBODY_NQ, f"TASKWALK_SPEED_MAX_SIGNAL=root reads the full body's root layout; nq={env.nq}"
1257
+ assert self.w_speed_max != 0.0, "TASKWALK_SPEED_MAX_SIGNAL=root with TASKWALK_W_SPEED_MAX=0 does nothing"
1258
+ # PROPORTIONAL SPEED MULTIPLIER (SpeedPController above). TASKWALK_W_SPEED_MAX becomes lambda0 (the D1 value of the cell's
1259
+ # cost set at its parent), TASKWALK_SPEED_P_GAIN the gain in reward per step per (m/s)^2, TASKWALK_SPEED_P_EVERY the window
1260
+ # in control steps (SAPO's epoch, 32). 0 = OFF and every earlier run is bit-identical. The multiplier moves the reward, so a
1261
+ # MEASUREMENT tool (CRN fields, reward replay) must run with it off and the weight set to the value it is measuring at.
1262
+ self.speed_p_gain = _f("TASKWALK_SPEED_P_GAIN", 0.0)
1263
+ assert self.speed_p_gain >= 0.0, self.speed_p_gain
1264
+ # M1 (PAPER-SPEED-CONSTRAINT-M1-M4, 11-22): TASKWALK_SPEED_I_ETA = eta > 0 adds SpeedPController's integral part (the design's
1265
+ # lambda <- max(0, lambda + eta (v_cmd - v_mean)), see the class); 0 (default) = OFF, every earlier run bit-identical. With it on
1266
+ # the controller exists even at TASKWALK_SPEED_P_GAIN = 0 (a pure integral); the batch-scalar form only.
1267
+ self.speed_i_eta = 0.0
1268
+ self._speed_p = None
1269
+ # TW1 S2a (11-10, TW1_S2_DESIGN.md): the two capture hazards, both OFF by default (the eager path is unchanged).
1270
+ # _wt: the weights that change between windows, as 0-d device tensors for the ARITHMETIC (the Python floats stay for the
1271
+ # control flow and the asserts); enable_tensor_weights() turns it on, set_weight() writes a float and its tensor together.
1272
+ # _speed_p_defer: the speed P update runs at the window boundary (speed_p_window_end) instead of inside the step.
1273
+ self._wt = None
1274
+ self._wt_frozen = False # inside a captured window: set_weight writes the float only (the slot reads its block row)
1275
+ self._speed_p_defer = False
1276
+ # TASKWALK_SPEED_P_CENTERED=1 (default 0, every earlier run bit-identical): pay the P correction on the speed ERROR,
1277
+ # lambda0 v + (lambda - lambda0)(v - v_cmd), instead of lambda v. Same derivative in v, so the same gradient field; what
1278
+ # changes is the per-step VALUE. lambda v drops the constraint's own constant -(lambda - lambda0) v_cmd, which is what the
1279
+ # controller's docstring form -(k_p / 2)(v_mean - v_cmd)^2 keeps: an overspeeding bin (lambda < lambda0) then pays every
1280
+ # alive step lambda v ~ -14 x 1.2 m/s, a negative per-step reward that makes the fall (penalty 250, once) pay
1281
+ # (S2c / S2d: every slow start topples within ~1 s; docs-dev/deeploco/20261021_0340_s2c_run38), while an underspeeding
1282
+ # fast bin gets an implicit alive bonus (lambda - lambda0) v_cmd, ~+50 per step at 3.4 m/s. Centred, the correction is
1283
+ # ~ -k_p (v_mean - v_cmd)(v - v_cmd): small near the command in every bin, no termination incentive and no hidden bonus.
1284
+ # =2: centre ONLY the overspeeding side, lambda v - min(lambda - lambda0, 0) v_cmd. MEASURED with =1 (S2g, killed at ep408,
1285
+ # docs-dev/deeploco/20261021_0740_s2g_cen): the slow bins tracked their commands (0.85 -> 0.79 m/s) but the fast bins never
1286
+ # ran: centred, an UNDERspeeding fast bin pays (lambda - lambda0)(v - v_cmd) ~ 96 x (1.4 - 3.7) = -220 per step, the same
1287
+ # termination incentive moved to the other end (eplen 62 at ep168), and its multiplier ran away to 96. A negative per-step
1288
+ # level makes the fall pay; a positive one only favours survival. So keep the uncentred lambda v where lambda >= lambda0 (its
1289
+ # level is a survival bonus, which S2c / S2d ran under) and centre where lambda < lambda0 (the level that made S2c's slow
1290
+ # starts fall). The derivative in v is lambda everywhere, as in every form.
1291
+ _spc = "0"
1292
+ self.speed_p_centered = int(_spc)
1293
+ for _k in ("TASKWALK_SPEED_I_BAND", "TASKWALK_SPEED_I_ETA_DOWN", "TASKWALK_SPEED_I_HOLD_ONLY"): # B-AW: never silently unused
1294
+ assert _f(_k, 0.0) == 0.0, (
1295
+ f"{_k} is the M1 integral's anti-windup: it needs TASKWALK_SPEED_I_ETA > 0 and one batch-scalar controller")
1296
+ if self.speed_p_gain > 0.0:
1297
+ assert self.w_speed_max != 0.0, "TASKWALK_SPEED_P_GAIN needs TASKWALK_W_SPEED_MAX = lambda0 (the D1 value), not 0"
1298
+ # TASKWALK_SPEED_I_BAND / TASKWALK_SPEED_I_ETA_DOWN (B-AW, 11-23; SpeedPController.__init__ says what): default 0 = off
1299
+ self._speed_p = SpeedPController(self.w_speed_max, self.speed_p_gain, 32,
1300
+ eta=self.speed_i_eta, i_band=0.0,
1301
+ eta_down=0.0,
1302
+ i_hold=False)
1303
+ if self._speed_p.i_band > 0.0 or self._speed_p.eta_down > 0.0 or self._speed_p.i_hold:
1304
+ print(f"[taskwalk] speed P anti-windup (B-AW): integrate a lag only within {self._speed_p.i_band:g} x the command; "
1305
+ f"the integral's rate over the command {self._speed_p.eta_down or self.speed_i_eta:g}; "
1306
+ f"integrate only on a constant command: {self._speed_p.i_hold}", flush=True)
1307
+ print(f"[taskwalk] speed P multiplier: lambda0 {self.w_speed_max} gain {self.speed_p_gain} "
1308
+ f"every {self._speed_p.every} control steps", flush=True)
1309
+ # COUPLED COM RATE. `_rate` detaches the previous COM, so under BPTT a window's derivative of any term in v_com
1310
+ # re-pays every inherited position: sum_t dcom_t/dtheta instead of the telescoped dcom_H/dtheta, H(H+1)/2
1311
+ # against H for a held velocity (16.5x at H 32; docs/logs/bug-grad-audits.md 2026-09-28). 1 keeps the
1312
+ # previous COM IN THE GRAPH and subtracts the value-free `(c_prev - sg(c_prev)) / dt`, the correction
1313
+ # TASKWALK_LCE_DOT_COUPLED applies to the fibre rate: v_com's VALUE is bit-identical, only its derivative
1314
+ # changes (to the finite difference's own). The attached sample is dropped at every window boundary and
1315
+ # per-env cut (`detach_history`, called by the env) and masked for envs reset since the last step.
1316
+ # Full body only: GpuFullBodyVecEnv is the env that calls `detach_history`. 0 = OFF, every cell on record.
1317
+ self.com_rate_coupled = _b("TASKWALK_COM_RATE_COUPLED", 0)
1318
+ if self.com_rate_coupled:
1319
+ assert env.nq in _FULLBODY_NQ, f"TASKWALK_COM_RATE_COUPLED is wired into the full-body env only; nq={env.nq}"
1320
+ self._com_graph = None
1321
+ # COUPLED SECOND / THIRD DIFFERENCES (2026-10-09). `_accel` and `_jerk` detach their stored samples, so under
1322
+ # BPTT the derivative of sum_t c(a_t) keeps only the CURRENT sample's coefficient: dC/dx_s = c'(a_s) / dt^2
1323
+ # instead of (c'(a_s) - 2 c'(a_{s+1}) + c'(a_{s+2})) / dt^2. For a difference stencil the detached and true
1324
+ # gradients satisfy <g_det, g_true> ~ integral |U(w)|^2 Re[(1 - e^{iw})^k] dw, which for k = 2 (and 3) is
1325
+ # NEGATIVE wherever the content is below a quarter of the sampling rate: gait-frequency head motion. So the
1326
+ # detached gradient of the head-acceleration cost points UP that cost. Measured on a synthetic gait (eight
1327
+ # stride harmonics, H 32 windows): cos(detached, true) -0.84 to -0.88, 7-8x the norm, and a step along it
1328
+ # RAISES the cost; the coupled one is at cos +0.98. In training (fb_tw_PROBE_armCwarm_w6_flat13_s1, head
1329
+ # acceleration weighted 15.4): the per-step head cost rose 0.69 -> 3.04 over ep104-152 while the policy
1330
+ # stayed up in 128 / 128 starts. 1 keeps the two (three) previous samples IN THE GRAPH inside a window and
1331
+ # adds the value-free `(x - sg(x))` corrections, the route TASKWALK_COM_RATE_COUPLED takes for `_rate`: the
1332
+ # VALUES are unchanged, the derivative becomes the stencil's own. Cut by `detach_history` at every window
1333
+ # boundary and per-env cut; envs reset since are already zeroed by the stencil's own n_valid counter.
1334
+ # Full body only (the env that calls `detach_history`). 0 = OFF, every cell on record.
1335
+ self.accel_coupled = _b("TASKWALK_ACCEL_COUPLED", 0)
1336
+ if self.accel_coupled:
1337
+ assert env.nq in _FULLBODY_NQ, f"TASKWALK_ACCEL_COUPLED is wired into the full-body env only; nq={env.nq}"
1338
+ self._acc_graph = {}
1339
+ self._ema_graph = None
1340
+ # --- ROOT ORIENTATION, SHAC's two posture terms (arXiv:2204.07137 eq. 23; `_shac_snu` below), as DEFICITS:
1341
+ # + w_root_up * (R[2,2] - 1) + w_root_heading * (R[0,0] - 1) [root frame from the STATE, exact]
1342
+ # R[2,2] is the world-up component of the root's up axis, R[0,0] the forward component of its forward axis
1343
+ # (pitch and yaw both lower it). SHAC's weights are 0.1 and 1 against a v_x coefficient of 1.
1344
+ # MINUS ONE, unlike SHAC: the derivative is SHAC's, the constant is not. Upright, SHAC's pair pays +1.1 per
1345
+ # step, which is an alive bonus, and this reward already carries one (mid_lane); an A/B that added both
1346
+ # would not say whether the posture GRADIENT or the larger alive constant did the work.
1347
+ # WHY A PATHWISE LEARNER MAY NEED THEM WHERE BOLT'S PPO DOES NOT. Bolt prices posture only through
1348
+ # termination (root height, a 30 deg heading cone); PPO sees a termination in its returns. SAPO's actor
1349
+ # sees the reward's in-graph derivative plus the critic's at the window end, and a termination only
1350
+ # through the critic. Bolt's reward has no in-graph posture term at all (mid_lane is a LATERAL position).
1351
+ # Full body only, the root layout `_shac_snu` asserts. 0 = OFF, not computed, bit-identical.
1352
+ self.w_root_up = _f("TASKWALK_W_ROOT_UP", 0.0)
1353
+ self.w_root_heading = _f("TASKWALK_W_ROOT_HEADING", 0.0)
1354
+ if self.w_root_up != 0.0 or self.w_root_heading != 0.0:
1355
+ assert env.nq in _FULLBODY_NQ, f"TASKWALK_W_ROOT_UP / _HEADING read the full body's root layout; nq={env.nq}"
1356
+ # TASKWALK_UP_BODY (the design brief, 11-11 23:1x: "change it from pelvis upright to TRUNK upright"): the body whose up
1357
+ # axis the w_root_up term reads.
1358
+ # root (default) the root quaternion q[3:7] exactly as before: R[2,2] - 1, bit-identical
1359
+ # thorax the THORAX body's up axis, calibrated in the STANDING KEYFRAME (the thorax frame is not world-aligned
1360
+ # standing): u_local = R0^T e_z (calibrate_up_body, the env's _tw_calibrate), and the term is
1361
+ # (R_thorax(q) u_local)_z - 1 = (R_thorax R0^T)[2,2] - 1 = cos(the thorax's tilt from its standing attitude) - 1,
1362
+ # 0 at the standing attitude; yaw about world z costs nothing. From the reward's own FK (the env adds the
1363
+ # thorax to its FK body set, so no new FK call), in the graph, no host read.
1364
+ # The heading term stays on the root.
1365
+ self.up_body = os.environ.get("TASKWALK_UP_BODY", "root")
1366
+ assert self.up_body in ("root", "thorax"), f"TASKWALK_UP_BODY={self.up_body!r}: root | thorax"
1367
+ self.i_up_body = None
1368
+ self.up_body_local = None
1369
+ if self.up_body == "thorax":
1370
+ assert self.w_root_up != 0.0, "TASKWALK_UP_BODY=thorax selects the body of the w_root_up term; set TASKWALK_W_ROOT_UP"
1371
+ assert getattr(env, "_monitor", None) is not None, "TASKWALK_UP_BODY=thorax needs the env's FK monitor at reward construction"
1372
+ names = [b["name"] for b in env._monitor.bodies]
1373
+ assert "thorax" in names, f"TASKWALK_UP_BODY=thorax: the model has no body named 'thorax' ({env.nq} qpos)"
1374
+ self.i_up_body = max(i for i, nm in enumerate(names) if nm == "thorax")
1375
+ print(f"[taskwalk] the up term reads {'the root quaternion q[3:7]' if self.up_body == 'root' else f'the thorax (body {self.i_up_body}), standing-calibrated'}"
1376
+ f"; w_root_up {self.w_root_up}, w_root_heading {self.w_root_heading} (the heading on the root)", flush=True)
1377
+ # --- SPRINT: Bolt's mid-lane term, which is also the only thing that makes his gait SYMMETRIC.
1378
+ # + w_mid_lane * exp(-k * (z_com - z_com_at_reset)^2) [lateral POSITION, metres]
1379
+ # `mid_lane_reward` in msk_envs/utils/reward_lib.py:29, weight `lambda_mid_lane = 1e-2` = the
1380
+ # same 1e-2 his speed term carries, and it doubles as his `r_alive` (there is no separate alive
1381
+ # term in his sprint path). k = 2.5 is his, giving half value at 0.53 m.
1382
+ #
1383
+ # WHY IT IS BACK after being dropped from the first design. The argument for dropping it was
1384
+ # that a forward-only velocity reward already prices diagonal running at v*cos(theta) and we
1385
+ # have no lane to stay in. MEASURED on ml26_sprint_v0_s1: the trained gait veers 3.42 m sideways
1386
+ # in 10 s at a net heading of 5.9 deg, where cos = 0.995 -- the "price" is 0.5% of the speed
1387
+ # term, i.e. free. Bolt's lane would have terminated that episode inside 1.5 s. The lopsided
1388
+ # gait it produced has the right hip never flexing past -6.3 deg while the left reaches +48.4.
1389
+ #
1390
+ # RELATIVE TO THE RESET, not to world zero: RSI drops the body at the clip's own lateral
1391
+ # offset, so an absolute |z| would charge a constant bias that has nothing to do with veering.
1392
+ self.w_mid_lane = _f("TASKWALK_W_MID_LANE", 0.0)
1393
+ self.mid_lane_k = _f("TASKWALK_MID_LANE_K", 2.5)
1394
+ assert self.mid_lane_k > 0.0, "TASKWALK_MID_LANE_K must be positive"
1395
+ # THE LANE ON THE STRIDE-FILTERED HEADING (TASKWALK_MID_LANE_FORM=heading, opt-in). The offset form prices the COM's lateral OFFSET from the reset, the integral of past heading errors, so it
1396
+ # charges a state for its history (1-3 deg of heading compounds to 0.9-2.3 m over 10 s). The heading form prices the heading of the
1397
+ # COM velocity low-passed at tau ~ one running stride (_velocity_ema, the speed gates' helper; it passes ~0.16 of the stride's
1398
+ # lateral sway and the heading whole): r = exp(-k_psi psi^2), psi = atan2(lateral, forward) in the command frame (_cmd_frame).
1399
+ # Below v_min the heading is undefined (a stopped or falling body; atan2's gradient grows as 1 / |v|): there r = 1, the inputs
1400
+ # substituted so atan2 is never evaluated at (0, 0). A SINGULARITY GUARD, not a lever: every running record stays above 3 m/s.
1401
+ # The alive role is kept (a straight body earns 1 per step). K / TAU / VMIN have no default (the values: k_psi = ln 2 / (5.9 deg)^2
1402
+ # = 65.4 / rad^2, the quoted ml26 veer paying half the alive level; tau 0.56 s, one running stride; v_min 0.5 m/s). The average
1403
+ # is carried through the window like the force-rate filter (_lane_graph, cut in detach_history, re-seeded per env after a reset
1404
+ # through _prev["lane_ema_valid"]). Unset = "offset", today's term, bit-identical (the heading state never exists).
1405
+ self.mid_lane_form = os.environ.get("TASKWALK_MID_LANE_FORM", "offset")
1406
+ # TASKWALK_MID_LANE_FORM=root (2026-11-23, R17: Bolt's term as his code has it, msk_envs envs/lanes.py + envs/utils/rewards.py):
1407
+ # exp(-k z^2) with z = the ROOT (pelvis) world lateral position, the lane centre FIXED at the world's lateral 0 (his SIDE_IDX
1408
+ # coordinate), not the COM's offset from its reset. Opt-in; unset = "offset", bit-identical.
1409
+ assert self.mid_lane_form in ("offset", "heading", "root"), f"TASKWALK_MID_LANE_FORM={self.mid_lane_form!r}: offset | heading | root"
1410
+ _lane_knobs = ("TASKWALK_MID_LANE_HEADING_K", "TASKWALK_MID_LANE_HEADING_TAU", "TASKWALK_MID_LANE_HEADING_VMIN")
1411
+ if self.mid_lane_form == "heading":
1412
+ assert _f_ever("TASKWALK_W_MID_LANE", 0.0) != 0.0, "TASKWALK_MID_LANE_FORM=heading with TASKWALK_W_MID_LANE=0 does nothing"
1413
+ for _k in _lane_knobs:
1414
+ assert os.environ.get(_k) is not None, f"TASKWALK_MID_LANE_FORM=heading needs {_k} (no default: the cell sets 38's value)"
1415
+ self.lane_k, self.lane_tau, self.lane_vmin = (float(os.environ[_k]) for _k in _lane_knobs)
1416
+ assert self.lane_k > 0.0 and self.lane_tau > 0.0 and self.lane_vmin > 0.0, (self.lane_k, self.lane_tau, self.lane_vmin)
1417
+ print(f"[taskwalk] mid lane on the heading: exp(-{self.lane_k:g} psi^2), psi of the COM velocity low-passed at tau "
1418
+ f"{self.lane_tau:g} s, r = 1 below {self.lane_vmin:g} m/s", flush=True)
1419
+ else:
1420
+ assert all(os.environ.get(_k) is None for _k in _lane_knobs), f"{_lane_knobs} without TASKWALK_MID_LANE_FORM=heading"
1421
+ self._lane_graph = None
1422
+ # In the paper's eq. (3) but NOT in either released wrapper -> 0 by default. Turning one on is a
1423
+ # deviation from the configuration that produced the published result, so it should be deliberate.
1424
+ self.w_action_rate = _f("TASKWALK_W_ACTION_RATE", 0.0)
1425
+ # EXCITATION-RISE COST (the force-rate cost), added 2026-10-02. The human pays for QUICK steps:
1426
+ # at 1.3 m/s net metabolic power is ~+21% at +20% stride rate (Umberger & Martin 2007, J Exp Biol
1427
+ # 210:3255, Fig. 4A), and the isolated swing's cost rises with frequency at CONSTANT work (Doke &
1428
+ # Kuo 2007, J Exp Biol 210:2390: Edot = 0.433 f^2.5 + 0.459). van der Zee & Kuo 2021 (J Exp Biol
1429
+ # 224: jeb233965) isolate it as a cost per contraction proportional to the rate of force development,
1430
+ # explained by a first-order excitation-contraction delay: to raise force faster, more Ca2+ must be
1431
+ # released (and pumped back), so the cost is paid per unit of activation RISE. Neither the effort
1432
+ # term (activation LEVEL) nor Wang 2012 (level + work) contains it, and on eight taskwalk gaits at
1433
+ # 102-153 steps/min every cost we compute is flat per metre (docs-dev/analysis/20261002_0530_cadence_cost).
1434
+ # FORM: sum_i m_i (u_i,t - u_i,t-1)+ / sum_i m_i, the mass-weighted positive excitation change per
1435
+ # control step. Mass because Ca2+ transport scales with muscle volume (Wang's heat terms are per kg
1436
+ # as well); the positive part because the cost is per release, which over a cycle equals the fall.
1437
+ # NOT `w_action_rate`: that is the paper's (du)^2 smoothness penalty on two exoskeleton commands,
1438
+ # unit-weighted, through `_rate`'s detached previous sample. This one keeps the previous excitation
1439
+ # IN THE GRAPH (the value-free correction TASKWALK_COM_RATE_COUPLED uses), so a window's derivative
1440
+ # is the finite difference's own; the attached sample is cut by `detach_history`. 0 = OFF.
1441
+ self.w_exc_rise = 0.0
1442
+ # ACTIVE-MUSCLE SATURATION COST (TASKWALK_W_ACTIVE_SAT, opt-in; 11-13 for the review's separation study, ruling (a): separate
1443
+ # the long-stride walk from the quick-walk basins, with a slope across the plateau). THE QUANTITY has a source: Schumacher et al.
1444
+ # 2025 (arXiv 2309.02976, read in the primary text by the review) price "the number of active muscles above 15 % activity"
1445
+ # (c_effort = alpha(t) a^3 + w1 (u - u_prev)^2 + w2 N_active, w2 = 1.579) in a reference-free muscle walker. THE FORM IS OURS:
1446
+ # their indicator has no gradient, so the smooth saturating relative r = sum_m V_m a_m / (a_m + a0) / sum_m V_m, with V_m the
1447
+ # volume weight (_muscle_mass, the activation term's), a the step's mean activation (a_mean, the activation and metabolic terms'),
1448
+ # a0 = TASKWALK_ACTIVE_SAT_A0 (default 0.05); per step, no state. Their weight 1.579 does NOT transfer (task reward in [0, 1],
1449
+ # 80-90 muscles, unnormalised count). Measured on records (tools38 m60 / m52): rises along the 10-02 quick-step escape and falls
1450
+ # along a burst-free longer step, at the plateau and at the long-stride walk; known bias: it charges RECRUITMENT, not level, so it
1451
+ # favours few muscles near saturation and load on passive structures. 0 = OFF and bit-identical.
1452
+ self.w_active_sat = 0.0
1453
+ self.active_sat_a0 = 0.05
1454
+ # STANCE KNEE BY FOOT PROXIMITY (TASKWALK_W_STANCE_KNEE_PROX, opt-in; 11-13 for the review's task B, the design brief: "find the good
1455
+ # reward that can clearly separate good gait" and "its not differentiable"). Per leg, per step:
1456
+ # exp(-relu(h) / H) relu(knee - K) / 10, summed over both legs,
1457
+ # h the LOWEST bottom of that foot's contact spheres (calcaneus and toes) above the floor, from the FK of q (the env's
1458
+ # TASKWALK_FALL_FOOT_GEOM tables), knee = knee_sign rad2deg(q_knee) (flexion +). A smooth load proxy: no contact force (the
1459
+ # engine's is non-smooth at contact), so it is in the window's graph through q_t with a gradient before and after touchdown.
1460
+ # H and K are DERIVED from GOOD's own records (tools38 m86: H = GOOD's median foot height over terminal swing, 15.4 mm; K = GOOD's
1461
+ # single-support knee median, 6.8 deg) and have NO default: a cell states them. Measured (m86 / m52 --cand, rbase/probe6):
1462
+ # separates the class medians (GOOD 1.42 per step at unit weight, bent 2.55, crouch 4.18, quick classes 2.7-3.3); at w ~1 it
1463
+ # turns the window gradient toward a straighter stance knee at 4 of the 5 bent / quick endings; it charges the loading-response
1464
+ # walks (stance flexion 12-16 deg) too. Flat ground only (h is a world z). It RAMPS like every TASKWALK_W_* (_END / _STEPS /
1465
+ # _AFTER, control steps; the env computes h while the weight is non-zero anywhere on the ramp) and the total reads it through _w()
1466
+ # (TENSOR_WEIGHTS) so a captured window carries the ramp. The form is continuous with two kinds of kink, both inherited from the
1467
+ # priced form: relu(h) at h = 0 (a stance foot sits there or below: d/dh = 0 in penetration) and the min over a foot's spheres at a
1468
+ # tie (a flat foot). 0 = OFF and bit-identical.
1469
+ self.w_stance_knee_prox = 0.0
1470
+ self._u_graph = None
1471
+ # NOT the paper's term. The paper penalizes the tibiofemoral joint reaction above 3 bodyweights;
1472
+ # this penalizes the summed tension of the knee-spanning muscles above a threshold calibrated to
1473
+ # that estimator. It captures CO-CONTRACTION, which is what the paper's term is for and what a
1474
+ # ground-reaction proxy cannot see, but it is not the same quantity and its threshold is not 3 BW.
1475
+ # The faithful version needs the RNE joint reaction readout; tracked separately.
1476
+ self.w_knee_load = _f("TASKWALK_W_KNEE_LOAD", 0.0)
1477
+ # Either in-graph force consumer needs the table; building it for only one of them is how
1478
+ # the knee-load term ended up unable to leave the detached side channel.
1479
+ self._met = (_mtu_param_table(env)
1480
+ if (_f_ever("TASKWALK_W_METABOLIC_RATE", 0.0) != 0.0
1481
+ or _f_ever("TASKWALK_W_METABOLIC_SQ", 0.0) != 0.0
1482
+ or _f_ever("TASKWALK_W_KNEE_LOAD", 0.0) != 0.0) else None)
1483
+ # SHORT-LENGTH MULTIPLIER on the metabolic rate (metabolic_rate's docstring: Beck 2022, k and l_ref pinned on
1484
+ # the calibrated calf). 0 = OFF and bit-identical. The constants were pinned on ..._calf2_pe's soleus; on the
1485
+ # lane body the same procedure pins l_ref only loosely (0.81-0.93) and fails the out-of-sample check.
1486
+ short_k = _f("TASKWALK_METABOLIC_SHORT_K", 0.0)
1487
+ if short_k != 0.0:
1488
+ assert short_k > 0.0 and self._met is not None, "TASKWALK_METABOLIC_SHORT_K needs a metabolic term on"
1489
+ assert self._met["curve"].get("law") != "millard2012", (
1490
+ "TASKWALK_METABOLIC_SHORT_K on a Millard model: its l_ref was pinned on the Geyer calf2_pe soleus's PROJECTED fibre "
1491
+ "length (l_ce / l_opt is unprojected on Millard), so the constant does not carry")
1492
+ assert self.w_metabolic_rate != 0.0 or self.w_metabolic_sq != 0.0, "TASKWALK_METABOLIC_SHORT_K multiplies the metabolic rate"
1493
+ short_lref = float(os.environ["TASKWALK_METABOLIC_SHORT_LREF"])
1494
+ assert 0.5 < short_lref < 1.5, short_lref
1495
+ import re as _re
1496
+ pat = _re.compile(os.environ.get("TASKWALK_METABOLIC_SHORT_MUSCLES", r"^(soleus|gasmed|gaslat)_[lr]$"))
1497
+ names = [m["name"] for m in env._monitor.jm["muscles"]]
1498
+ hit = [n for n in names if pat.match(n)]
1499
+ assert hit, f"TASKWALK_METABOLIC_SHORT_MUSCLES {pat.pattern!r} matches no muscle"
1500
+ self._met["short_k"], self._met["short_lref"] = short_k, short_lref
1501
+ self._met["short_mask"] = torch.as_tensor([1.0 if pat.match(n) else 0.0 for n in names],
1502
+ dtype=torch.float32, device=env.device)[:, None]
1503
+ print(f"[taskwalk/metabolic] short-length multiplier k {short_k:g}, l_ref {short_lref:g} on {hit}", flush=True)
1504
+ # FORCE FLOOR on the metabolic term's forces (TASKWALK_METABOLIC_FORCE_FLOOR=1, opt-in; 11-12 for PREREG_TENDON, the review):
1505
+ # mtu_forces is the residual's tendon-side expression and is NOT floored: below (1 - W) l_opt the buffer element drives F_MTU
1506
+ # negative and the concentric f_v is negative beyond -v_max, while the engine's force is never negative (rigid = 2: floored at 0).
1507
+ # Wang's S-dot and W-dot are non-negative by construction; with a negative force they become a CREDIT, and the Beck short-length
1508
+ # multiplier (x up to 1 + k l_ref) amplifies it. The 356 rigid walking arm's crouch earned that credit (its gastrocnemii below
1509
+ # slack in 14-19 % of frames). Floors F_MTU and F_CE at 0 inside metabolic_rate only (the knee-load term is untouched).
1510
+ if os.environ.get("TASKWALK_METABOLIC_FORCE_FLOOR", "0") == "1":
1511
+ assert self._met is not None, "TASKWALK_METABOLIC_FORCE_FLOOR needs a metabolic term on"
1512
+ self._met["force_floor"] = True
1513
+ print("[taskwalk/metabolic] force floor: F_MTU and F_CE clamped at 0 inside the metabolic rate", flush=True)
1514
+ # FORCE-RATE COST (TASKWALK_METABOLIC_FORCE_RATE = k_F in J per (N/s), 0 / absent = OFF and bit-identical; the low-pass cutoff
1515
+ # TASKWALK_METABOLIC_FORCE_RATE_HZ, default 3; 11-12, the design's 15:42 request and the review's ruling on FORCE_RATE_NOTE.md).
1516
+ # van der Zee & Kuo 2021 (J Exp Biol 224:jeb233965) price each contraction in proportion to its peak force rate; Wong, Cluff & Kuo
1517
+ # 2021 (eLife 10:e68013) Eq. 13 write such a cost per time as the rectified second derivative, and over one smooth one-sided
1518
+ # contraction int |F''|_+ dt = 2 F'_peak (a sinusoidal cycle), so the per-step form here is
1519
+ # P_FR = (k_F / 2) sum over muscles |y''|_+ (W, added to the metabolic rate before its weight; no new weight),
1520
+ # y = each muscle's force F (the reward's own MTU force, _mtu_forces, floored as the metabolic term floors it) through a CAUSAL
1521
+ # 2nd-order Butterworth low-pass at the cutoff (bilinear transform, unity DC gain), y'' its second difference over control steps.
1522
+ # ASSUMPTIONS OF OURS, each to be labelled in a cell: k_F = 2.35e-3 is van der Zee & Kuo's isometric knee-extension value (0.047 J
1523
+ # per (N.m/s), both legs' torque, the cost linear in it) through their 5.0 cm quadriceps moment arm, UNVERIFIED in the primary
1524
+ # (equations read through a summary), and taken equal per newton for every muscle; the cutoff 3 Hz is the first round number above
1525
+ # the experiments' top frequency 2.5 Hz (a raw 100 Hz difference reads exploration noise and contact transients instead).
1526
+ # STATE: the filter's last two inputs and outputs per muscle and env (_fr_x1, _fr_x2, _fr_y1, _fr_y2), ATTACHED to the graph inside a
1527
+ # BPTT window so the actor's gradient reaches the past forces the term is about, and cut by detach_history at window starts and
1528
+ # per-env cuts (the VALUE carries across a cut, the graph does not). An env restarted since the last step (`valid` false) re-seeds
1529
+ # its state at the current force (the filter's steady state: y = F and y'' = 0 on that step, no charge for the reset itself).
1530
+ self.fr_k = 0.0
1531
+ self.fr_hz = 3.0
1532
+ self._fr_x1 = self._fr_x2 = self._fr_y1 = self._fr_y2 = None
1533
+ self._fr_c = None
1534
+ self.last_force_rate = None
1535
+ self._vol_mass = _muscle_mass(env) if self.activation_weighting == "volume" else None
1536
+ self._n1eq_s = _n1_equiv_scale(env) # TASKWALK_EFFORT_N1_EQUIV (see _n1_equiv_scale); None = bit-identical
1537
+ if self._n1eq_s is not None: # the effort terms it covers: activation + the metabolic rate's heats; refuse the rest
1538
+ for _k in ("TASKWALK_W_ACTIVE_SAT", "TASKWALK_W_EXC_RISE", "TASKWALK_W_ACTION_RATE", "TASKWALK_W_METABOLIC_SQ"):
1539
+ assert _f_ever(_k, 0.0) == 0.0, f"TASKWALK_EFFORT_N1_EQUIV covers the activation and metabolic-rate terms only: {_k} must be 0"
1540
+ # EFFORT EXCLUSION, a DIAGNOSTIC probe knob and not a model of anything (gradient-field-ioc.md STATE 2026-10-13 22:1x: every gait
1541
+ # on the lumbar-spine body holds its trunk at activation 0.22-0.36, and that tonic cost carries most of the reward's ranking of
1542
+ # the stance gaits). TASKWALK_EFFORT_EXCLUDE_MUSCLES is a regex; the matched muscles are dropped from the activation term and
1543
+ # from the metabolic terms, and every normaliser is kept, so each remaining muscle is priced exactly as before. Unset = OFF and
1544
+ # bit-identical.
1545
+ self._effort_keep = None
1546
+ # RAMP (11-13, the review after the from-epoch-0 draw did not learn to walk): TASKWALK_W_ACTIVE_SAT is the START weight and
1547
+ # _END / _STEPS / _AFTER walk it like every TASKWALK_W_* schedule (task_walk_env._tw_parse_w_sched, control steps); the weights
1548
+ # are built when the weight is non-zero ANYWHERE on the ramp (_f_ever), the term is computed while the current weight is
1549
+ # non-zero, and the total reads it through _w() (TENSOR_WEIGHTS) so a captured window carries the ramp. No _END = no ramp,
1550
+ # bitwise the fixed-weight term of 3d8604fa2.
1551
+ # PERFORMANCE GATE (TASKWALK_ACTIVE_SAT_GATE=1, opt-in; 11-13 for the review): the epoch-keyed ramp above arrives at epoch 1000
1552
+ # whatever the run is doing, and a late learner is not walking yet then (R3-H64-HEADQ_mc_s2's eplen first stays above the threshold
1553
+ # below at about epoch 1100, hq_s2's at about 1260; tools38 m67 on the logs). Schumacher et al. 2025 (arXiv 2309.02976, Section II-A,
1554
+ # Algorithm 1 "Effort weight adaptation", read in the primary text) raise their effort weight only while a smoothed task return
1555
+ # stays above a threshold and lower it below (Table IV(d): delta-alpha 9e-4, theta 1000, beta 0.8, lambda 0.9). As printed their box
1556
+ # never raises it (s_mean is tested and never updated; c_mean is): we read s_mean as c_mean (OURS). Here the weight starts at 0 and
1557
+ # the ENV (task_walk_env._asat_gate_update, once per window at initialize_trajectory, outside any captured graph) walks it: the
1558
+ # signal is the trainer's eplen column (the mean over worlds of the episode age) with STANDING worlds zeroed (survived the window,
1559
+ # root speed under V_MIN over it: a standing policy cannot open it), smoothed r <- beta r + (1 - beta) s; with c the smoothed [r > theta]: r > theta
1560
+ # and c > 0.5 -> w + DW (to WMAX); r > theta and c <= 0.5 -> unchanged; r <= theta -> w - DW (to 0). lambda is not used (= 1).
1561
+ # THETA, DW, WMAX, V_MIN have no default (DERIVED per recipe); BETA defaults to the paper's 0.8, read per window instead of per
1562
+ # episode. The R-3 recipe's (11-13, tools38): THETA 153.1 = the middle of the largest gap in 969 logged eplen rows of 19 N1 runs
1563
+ # (137.8 -> 168.4, m67); DW 0.03 = 6 over 200 epochs, the ramp's rate (12800 control steps at H64); WMAX 6 = the separation
1564
+ # study's weight; V_MIN 0.441 = the middle of (0, 0.882): every 64-step window of every N1 walking record moves >= 0.882 m/s,
1565
+ # fallers move as fast until they fall, none stands (m68). The weight runs through the TW1 tensor route (train_tw14.install_tw1
1566
+ # adds it), constant inside a window; a window boundary is the only place it changes (the capture key flips at 0 <-> non-0).
1567
+ # TARGET (11-13, the review: the stance-knee-proximity cost's young-policy price ruled out a weight fixed from epoch 0):
1568
+ # TASKWALK_ACTIVE_SAT_GATE_TARGET names the weight the gate walks, default w_active_sat (bitwise the gate above); w_stance_knee_prox
1569
+ # is the other routed cost it may carry (its H / K required as for the fixed term). The gate's rule and signal are unchanged.
1570
+ self.active_sat_gate = False
1571
+ self.asat_gate_target = "w_active_sat"
1572
+ if self.active_sat_gate:
1573
+ _tg = self.asat_gate_target
1574
+ assert getattr(self, _tg) == 0.0 and os.environ.get(f"TASKWALK_{_tg.upper()}_END") is None, f"the gate owns {_tg}: start 0, no _END"
1575
+
1576
+ def _req(n):
1577
+ v = os.environ.get(n)
1578
+ assert v is not None, f"{n} has no default (TASKWALK_ACTIVE_SAT_GATE: a DERIVED value per recipe)"
1579
+ return float(v)
1580
+ self.asat_gate_par = dict(theta=_req("TASKWALK_ACTIVE_SAT_GATE_THETA"), dw=_req("TASKWALK_ACTIVE_SAT_GATE_DW"),
1581
+ wmax=_req("TASKWALK_ACTIVE_SAT_GATE_WMAX"), vmin=_req("TASKWALK_ACTIVE_SAT_GATE_VMIN"),
1582
+ beta=0.8)
1583
+ P = self.asat_gate_par
1584
+ assert P["dw"] > 0.0 and P["wmax"] > 0.0 and P["theta"] > 0.0 and P["vmin"] >= 0.0 and 0.0 <= P["beta"] < 1.0, P
1585
+ if self.active_sat_gate: # the volume weights (see above)
1586
+ _mass = _muscle_mass(env)
1587
+ self._asat_mass = _mass / _mass.sum() # (n_mus, 1), sums to 1
1588
+ print(f"[taskwalk/effort] active-muscle saturation cost ON: w {self.w_active_sat:g}"
1589
+ + (f" (PERFORMANCE-GATED: {self.asat_gate_par})" if self.active_sat_gate else "")
1590
+ + f", a0 {self.active_sat_a0:g}, volume-weighted", flush=True)
1591
+ else:
1592
+ self._asat_mass = None
1593
+ # filled by TaskWalkEnvMixin._tw_setup, which is the only place the model's muscle order and
1594
+ # body masses are resolved. None here and a non-zero weight is a wiring error, not a config one.
1595
+ self.knee_mus = None # (right, left) index tensors into the muscle axis
1596
+ self.bw_n = None # bodyweight in newtons
1597
+ self.w_hip_adduction = _f("TASKWALK_W_HIP_ADDUCTION", 0.0)
1598
+ # HIP ROTATION, the same shape as the adduction term one axis over. `hip_rot_p2p` became a
1599
+ # SCORED column at SCORE_VERSION 10 (human 15.81 deg, tol 8.0) and the corrected-model
1600
+ # baseline reads 58.40 -- 5.32 tolerance units, its worst column by 1.8x. Nothing in this
1601
+ # reward was a function of hip rotation before now, so the variable has been free for the
1602
+ # whole campaign, and the two implemented terms that could have reached it are both spent:
1603
+ # W_JOINT_LIMIT DQd the gait at 1 (heel_pct 13.89) and W_HIP_ADDUCTION is already satisfied
1604
+ # (measured mean adduction -0.91 / -0.01 deg, i.e. at its target).
1605
+ self.w_hip_rotation = _f("TASKWALK_W_HIP_ROTATION", 0.0)
1606
+ # The learned STATE PRIOR (branch feat/state-prior; docs/AGENDA.md 2026-10-17 02:3x): the cost NLL(x) - c, x the prior's features
1607
+ # (diffneusim/rl/state_prior.py FullbodyPriorMap) of (q, qd, the per-foot 3-D GRF in the graph) and NLL the per-dim
1608
+ # mean Gaussian NLL of a trained StatePriorVAE (TASKWALK_STATE_PRIOR_FILE, tools/state_prior/train_prior.py). The centre c
1609
+ # (TASKWALK_STATE_PRIOR_CENTER) has NO default: a raw NLL is negative for human states and would be a hidden alive bonus
1610
+ # (docs-dev/20261016_1707_state_prior_review/README.md). Default weight 0 = bit-identical; a training run with it is the
1611
+ # user's decision (P1).
1612
+ self.w_state_prior = 0.0
1613
+ # TASKWALK_STATE_PRIOR_HEADING_GATE_DEG (default 0 = off, every earlier run bit-identical): apply the prior only while the
1614
+ # pelvis faces the commanded heading within the gate. MEASURED (docs-dev/deeploco/20261021_0950_s1v_vae_walk): both trained
1615
+ # priors charge TURNING frames ~+0.23-0.26 NLL per frame over straight ones (the turn's sideways ground reaction, hip
1616
+ # adduction / rotation, lumbar rotation), since AddBiomechanics holds almost no turning gait; S1v lost the squares and the
1617
+ # zigzag to it. The gate keeps the prior on the states its data covers. Value by measurement: 30 deg is above every straight
1618
+ # frame of S1f at 0.7-1.6 m/s (max 29.0, p99 24.0) and below 70% of its left-turn frames. Needs the heading task.
1619
+ self.state_prior_gate_rad = math.radians(0.0)
1620
+ assert self.state_prior_gate_rad >= 0.0, self.state_prior_gate_rad
1621
+ # The PER-PHASE Gaussian state prior (feat/state-prior; docs-dev/20261017_0705_phase_tests/RESULT.md): the per-dim mean Gaussian
1622
+ # NLL of the prior's features (hip rotation dropped) under a Gaussian per 10% of the right foot's cycle, minus the held-out
1623
+ # humans' median (tools/state_prior/fit_phase_gauss.py). The phase is the time since the right foot's last strike over its
1624
+ # last stride, from the per-foot vertical force, DETACHED: a strike is a rise above 0.03 BW (the 20 N rule at ~70 kg) at
1625
+ # least 0.4 s after the last, a stride counts when it lasts 0.7-1.8 s (the human data's own rule), and until an env has one
1626
+ # the term is 0 for it. Default weight 0 = bit-identical; a training run with it is a separate decision (P1).
1627
+ self.w_phase_prior = 0.0
1628
+ self._pp = None
1629
+ # DEAD BAND (rad, symmetric): only |rot| beyond it is charged. WHY (docs/training/gradient-field-ioc.md STATE 2026-10-10
1630
+ # 15:1x-15:2x): unbanded, this term charged the imitation's subject (Rajagopal S11, -8.7 / -1.1 deg) exactly what it charged
1631
+ # the imitation (0.3595 vs 0.3588 / step at w 13.572) and every human clip 0.28-2.14, and the competitors won by holding the
1632
+ # rotation at ~0, which no human does. Humans at ~1.3 m/s: 99% of samples in [-21.0, +8.2] deg (Fukuchi 2018, 39 subjects);
1633
+ # a symmetric band needs no left / right sign convention. 0 = unbanded, bit-identical to every cell on record.
1634
+ self.hip_rotation_band = _f("TASKWALK_HIP_ROTATION_BAND", 0.0)
1635
+ assert self.hip_rotation_band >= 0.0, "TASKWALK_HIP_ROTATION_BAND is a half-width in rad, >= 0"
1636
+
1637
+ # =============================================================================================
1638
+ # MECHANICS COSTS -- all default 0, i.e. the shipped reward is bit-identical with none of them.
1639
+ # Every one is a cost a real body pays, none prescribes a trajectory, and none is a function of
1640
+ # a SCORED column, so they satisfy the predictive rule (see the module docstring). Where a term
1641
+ # comes from a paper the formula is that paper's, verbatim, with any deviation named.
1642
+ # =============================================================================================
1643
+
1644
+ # --- GRF RATE = Veerkamp et al. 2021's FGImpact (J Biomech 123:110530) ------------------------
1645
+ # FGImpact = (1/distance) * integral [ |dGRFx_l/dt| + |dGRFy_l/dt| + |dGRFx_r/dt| + |dGRFy_r/dt| ] dt
1646
+ # L1, not squared. BOTH the fore-aft and the vertical component. BOTH legs, summed. It prices
1647
+ # how FAST the ground reaction changes, not how big it gets: a rigid landing and a compliant one
1648
+ # reach the same peak, and only the rate separates them. Their justification is cutaneous: the
1649
+ # foot's mechanoreceptors sense yank (Kavounoudias & Roll 1998; Kennedy & Inglis 2002) and a high
1650
+ # loading rate is implicated in tissue injury (Mundermann et al. 2005; Nigg 1985).
1651
+ # It was their BEST single criterion by agreement with experiment (mean R^2 0.56 over four).
1652
+ # MEASURED HERE 2026-09-08, and it is the largest anomaly on this line: max dGRF/dt is 108 BW/s
1653
+ # against 13.5 for the human at the same 1.30 m/s (data/reference/human/fukuchi2018_grf_moments_1p3.npz),
1654
+ # a factor of 8.0, where the PEAK is only 2.0x off.
1655
+ # DEVIATION: theirs divides by distance travelled over a 10 s trial; a per-step reward cannot,
1656
+ # because integral(f)/integral(v) is not integral(f/v). Speed here is tracked to a fixed target,
1657
+ # so distance per episode is near-constant and the two differ by a constant. Named, not hidden.
1658
+ # WAS UNRUNNABLE UNTIL 2026-09-09: this read the detached `foot_grf`, so it was
1659
+ # `requires_grad=False` at any weight. It now reads a COM-derived ground reaction that is in the
1660
+ # graph -- see the block in __call__ for the identity, its validation against the engine, and
1661
+ # the per-leg -> total departure from the paper.
1662
+ self.w_grf_rate = 0.0
1663
+
1664
+ # --- HEAD ACCELERATION = Veerkamp's HeadStab ---------------------------------------------------
1665
+ # Fore-aft and vertical linear acceleration of the head body. Theirs weights the two almost
1666
+ # equally (normalisers 0.63 / 0.62) and it was 18.4% of their optimal combined cost and their
1667
+ # BEST single criterion for the knee MOMENT (R^2 0.54) -- and they name it, with the joint-limit
1668
+ # term, as what mattered for "obtaining knee flexion in early stance".
1669
+ # WHY IT IS NOT THE SAME AS A GRF PENALTY, which is the trap this term looks like. For the WHOLE
1670
+ # BODY a_com = sum(GRF)/M - g is an IDENTITY, so charging COM acceleration IS charging the ground
1671
+ # reaction. The HEAD is not the COM. Measured here 2026-09-08 the two currently agree to 97%
1672
+ # (r = 0.98 frame by frame) -- but that agreement is the DEFECT, not a licence to substitute one
1673
+ # for the other: it says the legs transmit everything because nothing is absorbing. A gait that
1674
+ # absorbed with the knee would drive them apart, which is exactly the behaviour being bought.
1675
+ # So this MUST read the head body, never `com`.
1676
+ self.w_head_accel = _f("TASKWALK_W_HEAD_ACCEL", 0.0)
1677
+ self.head_accel_ref = 9.80665 # m/s^2; 1 g -> the term reads ~1
1678
+ # CAP, in units of REF, applied per component BEFORE the square. Default huge = inert, so every
1679
+ # cell on record is bit-identical.
1680
+ #
1681
+ # WHY IT IS NEEDED, and it took three cells to stop arguing about the weight instead. A square on
1682
+ # an unbounded quantity is dominated by whatever the state does WORST, and early in training the
1683
+ # head accelerates far harder than in any gait:
1684
+ # ml26_fxfhsc_head_s1 w = 2.0 flat never walked (eplen flat 21-27 for 260 epochs, ret < 0)
1685
+ # ml26_fxfhsc_head02_s1 w = 0.2 flat trained to eplen 228 and then DQ'd, 0/8 survivors
1686
+ # ml26_fxfhsc_headsched_s1 0 -> 2.0 ramp tracked the parent while the weight was 0, then
1687
+ # COLLAPSED as it rose: eplen 83.5 (ep240, w 0.4) ->
1688
+ # 30.7 (ep300, w 1.0) -> 27.9 (ep360)
1689
+ # The ramp shows the fault is not the scale and not the timing: the term destroys a gait that is
1690
+ # already forming. `TASKWALK_W_KNEE_LOAD` carries the same diagnosis and the same fix in its own
1691
+ # comment -- "a bare square makes one frame 4600 against a velocity reward near 9 ... the cap is
1692
+ # the one deviation from Eq (2) kept on purpose" -- and it clamps at 15 BW.
1693
+ #
1694
+ # WHERE TO SET IT. Measured in a WALKING gait, |a_head,vert| peaks at 13.1 m/s^2 = 1.34 REF and
1695
+ # the fore-aft at 5.8 = 0.59, so a cap at 2 REF clips nothing a gait does and everything a
1696
+ # flailing model does. That asymmetry is the point: inert once walking, bounded before.
1697
+ self.head_accel_cap = _f("TASKWALK_HEAD_ACCEL_CAP", 1e9)
1698
+ # The COM FLOOR is walking-sized too: COM_FLOOR_H is the human WALK's own floor (0.8818 on 07_01), and human runs at 3.2-3.8
1699
+ # m/s spend 52-58% of the stride below it, 9-11 per step at w 10000 (docs-dev/deeploco/20261021_0020_s2_run_prior). Gated with
1700
+ # the other two only when TASKWALK_WALK_TERMS_COM_FLOOR=1 (default 0, so the S2 / S2b cells keep their meaning); the fall
1701
+ # TERMINATION is not gated (its 0.767 floor sits below a run's ~0.81 minimum).
1702
+ _wcf = "0"
1703
+ self.walk_terms_com_floor = _wcf == "1"
1704
+ assert self.head_accel_cap > 0.0, "TASKWALK_HEAD_ACCEL_CAP must be positive"
1705
+ # DEAD BAND, in units of REF, per component (fore-aft x, vertical z): only the excess is charged. Ong, Geijtenbeek, Hicks
1706
+ # & Delp 2019 (PLoS Comput Biol, eq. 12) leave +-0.25 g fore-aft and +-0.5 g vertical free, "approximated from experimental
1707
+ # data of human walking" (Menz 2003). WHY (docs/training/gradient-field-ioc.md STATE 2026-10-10 09:0x): unbanded, this term
1708
+ # charges the human's own pendular head motion (vertical RMS ~0.18 g at 1.3 m/s, Mazza 2008) and was 57% of the learner's
1709
+ # field at the imitation expert, pushing it to a flat COM that humans pay ~2x for (Ortega & Farley 2005). 0 = unbanded,
1710
+ # bit-identical to every cell on record.
1711
+ self.head_accel_band = (_f("TASKWALK_HEAD_ACCEL_BAND_X", 0.0), _f("TASKWALK_HEAD_ACCEL_BAND_Z", 0.0))
1712
+ assert min(self.head_accel_band) >= 0.0, "TASKWALK_HEAD_ACCEL_BAND_* is a half-width in units of REF, >= 0"
1713
+
1714
+ # --- JOINT-LIMIT TORQUE = Veerkamp's KneeExt, faithfully ---------------------------------------
1715
+ # KneeExt = integral [ F_limit,left + F_limit,right ] dt
1716
+ # "a penalty to the use of the knee limit torque, representing ligaments". Ours sums the WHOLE
1717
+ # limit torque -- spring AND damper -- over every limited 1-DOF joint, which is what the engine
1718
+ # actually applies.
1719
+ # HOW THIS DIFFERS FROM `TASKWALK_W_JOINT_LIMIT`, which is the same idea in the wrong variable:
1720
+ # that term is `clamp(bound - q, 0)`, the ANGLE past the stop. The stop's spring torque is
1721
+ # k_lim * srelu(that angle), so at a FIXED k_lim the two are the same function times a constant
1722
+ # and this buys nothing over it. It buys two things anyway: (1) the damper, which the angle
1723
+ # cannot see at all, and (2) comparability across k_lim, since a cell that changes the stop's
1724
+ # stiffness changes the price of a given penetration automatically instead of silently.
1725
+ # ENCODING WARNING: the spring part is monotone in `past_bound`, a SCORED column. Read
1726
+ # `w_limit_power` below if you want the part that is not.
1727
+ self.w_limit_torque = _f("TASKWALK_W_LIMIT_TORQUE", 0.0)
1728
+ self.limit_torque_ref = _f("TASKWALK_LIMIT_TORQUE_REF", 10.0) # N.m; k_lim*beta/2 at the bound
1729
+ assert self.limit_torque_ref > 0.0, "TASKWALK_LIMIT_TORQUE_REF must be positive"
1730
+ # PHYSIOLOGICAL FLOOR, in N.m, below which passive limit load is FREE. Default 0.0 charges every
1731
+ # newton-metre and leaves every cell on record bit-identical.
1732
+ #
1733
+ # WHY A FLOOR AND NOT JUST A WEIGHT. A healthy knee reaches its end of range and loads its
1734
+ # passive restraints in normal use; that is not a defect and a reward should not price it. What
1735
+ # is a defect is going PAST it. The clinical literature puts a number on where "past" starts:
1736
+ # passive hyperextension in healthy adults averages about 6 deg (women 6.7 deg, whole-group
1737
+ # range 0-17), and beyond 10 deg is classified genu recurvatum. On this model's own passive
1738
+ # curve 6 deg costs 20.6 N.m, which is also where Riener & Edrich's capsule term sits (22.7 N.m)
1739
+ # and is comfortably inside the 25-27 N.m that Deardurff 2026 and Noyes 2023 apply to INTACT
1740
+ # cadaver knees on a 6-DOF robot. So a floor at ~20 N.m says: load the stop as a human does,
1741
+ # free; drive it past where a human's range ends, and pay.
1742
+ #
1743
+ # THIS IS WHAT THE PARAMETER WORK BOUGHT. k_lim 184 was checked against three sources it was not
1744
+ # fitted to and stands, so the stop is not the defect -- the policy driving 47 N.m into it is,
1745
+ # against the 20.6 N.m that defines the healthy end of range. The floor turns that measured gap
1746
+ # into the term instead of a tuned weight.
1747
+ # WHICH JOINTS the limit-torque term charges: a comma list of body-name prefixes (e.g. "toes"); unset = every
1748
+ # limited 1-DOF joint, bit-identical. WHY (2026-10-07, column generation over the physics feature library,
1749
+ # tools/gait/fb_physics_features.py): the heel-down expert loads the KNEE extension stop more than the failure gaits
1750
+ # (1.5 vs 0.1 N.m: its stance knee straightens) and the MTP stop far less (2.4 vs 6-9 N.m; the human retarget 0.16),
1751
+ # so the all-joint sum charged the expert for straightening its knee -- the LP-reward probe crouched to knee_mid
1752
+ # 28-33 deg. The MTP-only sum separates the expert from every recorded failure gait with the human's sign.
1753
+ _lj = os.environ.get("TASKWALK_LIMIT_TORQUE_JOINTS", "").strip()
1754
+ self.limit_torque_joints = tuple(x.strip() for x in _lj.split(",") if x.strip()) if _lj else None
1755
+ # THE TOE'S WHOLE PASSIVE MOMENT (2026-10-07). 0 = the stop torque only, bit-identical. 1: each charged joint's
1756
+ # coordinate spring (the model's coord_springs) is added to its stop torque before |.|, so the term prices the
1757
+ # passive moment the joint's tissue carries. WHY: on the lane body the toe-stop torque separated the forefoot
1758
+ # gaits from the heel-down expert (AL iteration 1-2), but that 30 deg stop also blocks the human push-off (human
1759
+ # barefoot MTP extension 40-45 deg; the Falisse-toe probe moved the soleus earlier and removed the late knee load).
1760
+ # On the Falisse toe (stop -60.2 deg + 25 N.m/rad) the stop never engages and the cold learner chose the forefoot
1761
+ # (cell 102); its whole passive toe moment separates them instead (fb_physics_features mtp_passive: forefoot 15.2
1762
+ # N.m vs the heel-down probe 4.1-5.2; a human push-off reaches ~22 N.m on this spring over ~25% of the cycle).
1763
+ self.limit_torque_springs = _b("TASKWALK_LIMIT_TORQUE_SPRINGS", 0)
1764
+ # THE TOE SPRING AS ITS OWN WEIGHT (2026-10-11). The same passive moment the flag above folds into the stop term, priced by a
1765
+ # SEPARATE weight so a schedule can switch it off once the gait has formed: sum over the selected joints that carry a coordinate
1766
+ # spring of (|k (q - rest)| / REF)^pow, with the term's own exponent and REF. WHY (docs/training/gradient-field-ioc.md STATE
1767
+ # 2026-10-11 11:1x-15:4x): PredSim's own w4 keeps the stiffness moment OUT of the cost (createCasadi_PassiveMoments.m, tau_J =
1768
+ # tau_lim), and with it out from the start the cold learner selects a forefoot-leaning stance (the fourth cold screen); inside the
1769
+ # heel-down basin, with it out, the push-off deepens 5-7 deg and that gait scores highest under the cost-off reward (D2e). So it
1770
+ # selects the basin and then holds the push-off down. With the toe's stop torque ~0 in walking (stop at -60 deg), the split
1771
+ # (SPRINGS 0 + this weight) equals SPRINGS 1 at the same weight up to the stop x spring cross term. Default 0 = bit-identical.
1772
+ self.w_toe_spring = 0.0
1773
+ self.limit_torque_floor = _f("TASKWALK_LIMIT_TORQUE_FLOOR", 0.0)
1774
+ assert self.limit_torque_floor >= 0.0, (
1775
+ f"TASKWALK_LIMIT_TORQUE_FLOOR={self.limit_torque_floor} must be >= 0; it is a N.m threshold "
1776
+ f"below which passive limit load costs nothing")
1777
+ # THE EXPONENT (2026-10-09). 1 = sum |tau| / REF, bit-identical. 2 = sum (|tau| / REF)^2 per joint: the passive-torque
1778
+ # term of the PredSim objective, w4 ||T_passive||^2 over every joint (Falisse et al. 2019 J R Soc Interface, "limited
1779
+ # knee overextension"; with toes, Falisse 2022 and Afschrift 2025). Admitted by the IOC outer loop's column generation on
1780
+ # the protocol-M records (docs/training/ioc-outer-loop.md): fb_physics_features passive_sq_all, which this reproduces
1781
+ # with TASKWALK_LIMIT_TORQUE_JOINTS covering every stop, TASKWALK_LIMIT_TORQUE_SPRINGS=1 and REF 10.
1782
+ # THE SOLVER'S STOP in the same term (TASKWALK_LIMIT_TORQUE_STOP=1; 11-14, the review after the m120 / m121): past a
1783
+ # joint's range the D16 law's constraint row (MuJoCo's soft limit with the law's reduced inverse weight) carries most of the stop
1784
+ # load; on MET05's crouch it averaged ~147 N m at the ankle against <= 31 N m from the exp spring this term prices. With the knob
1785
+ # the per-joint torque adds that row's quasi-static force, f = max(0, K r + B v_in), K = d^2 / (dmax^2 tc^2 dr^2 (1 - d) diagA)
1786
+ # and B = 2 d / (dmax tc (1 - d) diagA) from the row's solref / solimp and the LAW's diagA (MuJoCo's own invweight0 would read
1787
+ # 0.09x). The gate is HARD, as the solver activates a row: r = max(0, penetration), the velocity part only past the bound (a
1788
+ # smooth _srelu tail times K ~ 1e6 on lumbar5 charged hundreds of N m inside the range: the catch, 11-14). A MONOTONE PRICE of the
1789
+ # stop, not the solver's N m: it over-reads (MET05's ankle median 1.14x when the row pushes, ~1.4x summed with the frames the row
1790
+ # releases; MET025's ankle 1.66-1.75x; coupled-chain rows far more, hence the selector). tools/d16_taskwalk/limit_law/.
1791
+ # TASKWALK_LIMIT_TORQUE_STOP_JOINTS (required with the knob): body-name prefixes of the joints whose stop is priced, separate
1792
+ # from TASKWALK_LIMIT_TORQUE_JOINTS (which also picks the springs). Same POW / REF / weight; 0 = off, bit-identical. Needs env14
1793
+ # (the law: env._tw_law_path).
1794
+ self.limit_torque_stop = _b("TASKWALK_LIMIT_TORQUE_STOP", 0)
1795
+ self.limit_torque_stop_joints = [p.strip() for p in os.environ.get("TASKWALK_LIMIT_TORQUE_STOP_JOINTS", "").split(",") if p.strip()]
1796
+ assert not self.limit_torque_stop or self.limit_torque_stop_joints, \
1797
+ "TASKWALK_LIMIT_TORQUE_STOP=1 needs TASKWALK_LIMIT_TORQUE_STOP_JOINTS (e.g. talus_ for the ankles): coupled-chain stops over-read"
1798
+ assert self.limit_torque_stop or not self.limit_torque_stop_joints, "TASKWALK_LIMIT_TORQUE_STOP_JOINTS without TASKWALK_LIMIT_TORQUE_STOP=1"
1799
+ self._stop_t = None
1800
+ self.limit_torque_pow = _f("TASKWALK_LIMIT_TORQUE_POW", 1.0)
1801
+ assert self.limit_torque_pow in (1.0, 2.0), f"TASKWALK_LIMIT_TORQUE_POW={self.limit_torque_pow}: 1 or 2"
1802
+ assert not (self.limit_torque_pow == 2.0 and self.limit_torque_floor > 0.0), "the floor is a TASKWALK_LIMIT_TORQUE_POW=1 form"
1803
+
1804
+ # --- JOINT-LIMIT POWER: the part `past_bound` cannot see ---------------------------------------
1805
+ # sum over limited dofs of d_lim * qvel^2 * eng [W, dissipated in the stop]
1806
+ # The engine's limit is a spring AND a dashpot (core/dyn/passive.h:48). Two strides with the SAME
1807
+ # penetration can arrive at the stop at ten times different speed and burn ten times the energy
1808
+ # in the ligament, and today they score identically. Measured 2026-09-08 on ml26_fxfhsc_s1: the
1809
+ # peak damper torque is 113% of the peak spring torque (144% on jl10) and, decisively,
1810
+ # r(past_bound, |damper|) = +0.04 -- so this is very nearly ORTHOGONAL to the column the existing
1811
+ # joint-limit term and the board both measure. tau*omega rather than |tau| because the physical
1812
+ # quantity being charged is dissipated POWER, not force.
1813
+ self.w_limit_power = 0.0
1814
+ self.limit_power_ref = 10.0 # W
1815
+
1816
+ # --- PEAK VERTICAL GRF: the CONTROL for the head-acceleration term -----------------------------
1817
+ # One-sided, above a threshold, squared, per leg. This exists so the claim in `w_head_accel`
1818
+ # above -- that a head term is strictly better than a ground-reaction term because it also
1819
+ # admits absorbing with the legs -- can be TESTED instead of asserted. Run one cell each.
1820
+ # The default threshold is the human first peak at this line's own 1.30 m/s, 1.06 BW, measured
1821
+ # from data/reference/human/fukuchi2018_grf_moments_1p3.npz (Fukuchi et al. 2018, 43 trials /
1822
+ # 39 subjects). Ours is 2.14 BW. A THRESHOLD is a one-sided bound, not a trajectory.
1823
+ # Also moved onto the COM-derived ground reaction (2026-09-09), for the same reason. This one
1824
+ # needs only TWO time derivatives of q where the rate term needs three, so it is the better
1825
+ # conditioned of the two and the one to try first.
1826
+ self.w_grf_peak = 0.0
1827
+ # --- PER-FOOT BRAKING: each foot's fore-aft ground reaction AGAINST the walking direction (+x) ----------
1828
+ # Design note, 2026-09-28, on RL walks that brake 0.4-0.9 BW per step: "how about penalising only the GRF
1829
+ # opposite to the velocity, with the human's 0.2 BW as the threshold", and then: "using the human's is
1830
+ # fine, but we have the imitation data, so compromise with it -- the human value may be unreachable in
1831
+ # our engine." Cost per env = sum over feet of relu(-F_x / BW - THR), in bodyweights.
1832
+ # PER FOOT, which is why it needs the engine's contact force in the graph (foot_grf_x comes from
1833
+ # gpu_bridge.contact_force_gpu, FD-gated by tools/contact_force_vjp_gate.py) and cannot be derived from
1834
+ # the COM like the GRF terms above: the COM identity gives the NET force, and the net braking of these
1835
+ # walks is imitation-like -- the excess is two feet pushing against each other in double support.
1836
+ # THE THRESHOLD, measured (fullbody-walk-investigation-log 2026-09-29): the human per-foot braking peak
1837
+ # at 1.30 m/s is 0.171 / 0.166 BW (R / L; fukuchi2018_grf_moments_1p3.npz, the mean curve of 43
1838
+ # treadmill trials), but on THIS engine both post-fix full-body imitations exceed it -- per-step peak
1839
+ # p90 0.329 (MyoAssist ep1000) and 0.373 (CMU 07_01 ep1000), with one foot at 0.30-0.37 in each. The
1840
+ # default 0.35 sits between those two p90s: what a gait with human kinematics produces here, so the
1841
+ # term charges only the braking the imitation does not do (the RL walks: per-step medians 0.57-0.92).
1842
+ # LINEAR, not squared: the squared GRF-peak term above never walked because a falling policy spikes
1843
+ # to several BW; a hinge's gradient is W per BW however hard the fall.
1844
+ self.w_brake = _f("TASKWALK_W_BRAKE", 0.0)
1845
+ # --- POSITIVE COM WORK PER LIMB (individual-limbs method; Donelan, Kram & Kuo 2002): sum_feet {F_foot . v_COM}+ / m,
1846
+ # W/kg, the step-to-step transition work. 2026-10-09: with the force-human expert (the RRA-consistent imitation, arm A2)
1847
+ # no weighting of the shipped terms beats the 17 recorded same-body failures (t* -0.34 / step: the flat, bent-knee
1848
+ # gaits are CHEAPER on this model's activation / metabolic costs, where humans pay ~2x for flat walking, Ortega &
1849
+ # Farley 2005); this column alone makes it feasible (t* +0.11 / step; the expert 0.56 W/kg, the failures 0.62-0.90).
1850
+ # Work minimisation is what produces the inverted-pendulum walk in Srinivasan & Ruina 2006 ("the exceptionally
1851
+ # smooth, flat walk is never optimal"). Same definition as tools/gait/fb_physics_features.py's com_pos_w; per-foot
1852
+ # force IN the graph (`foot_grf3`), v_COM the reward's own (coupled) COM rate. Default 0 = bit-identical.
1853
+ self.w_com_pos_work = _f("TASKWALK_W_COM_POS_WORK", 0.0)
1854
+ assert self.w_com_pos_work >= 0.0, "TASKWALK_W_COM_POS_WORK is a cost weight, >= 0"
1855
+ # --- TOUCHDOWN HEEL SPEED: the calcaneus's forward (+x) speed at the control step each foot first loads --
1856
+ # Design note, 2026-09-29 ("so should the landing speed be the penalty?" -> "a"). Measured first (pushoff_friction,
1857
+ # per step median, ep1000): heel at touchdown +3.45 m/s on the RL walks (brk10; 3.42-3.70 in every braking /
1858
+ # effort cell) against +1.16 (MyoAssist imitation) and -0.19 (CMU 07_01 imitation, a human clip tracked). The
1859
+ # braking price flattened the braking PEAK but never slowed the heel, and the braking IMPULSE was already
1860
+ # human-level (0.024 BW.s per step against Fukuchi 2018's ~0.028 and the 07_01 imitation's 0.027) -- so the
1861
+ # defect left is the collision itself. Cost per env = sum over feet of td * relu(v_x - V_MAX), td = 1 on the
1862
+ # step the foot's vertical GRF first exceeds GATE_BW (the same 0.05 BW stance gate pushoff_friction uses),
1863
+ # v_x the finite-difference heel velocity with the value-free coupled correction (the exact BPTT derivative,
1864
+ # as TASKWALK_COM_RATE_COUPLED does for the COM). V_MAX 1.2 = the faster of the two imitations: reachable on
1865
+ # this engine with human kinematics. The gate is a detached sensor reading; the gradient runs through v_x.
1866
+ self.w_touchdown = 0.0
1867
+ self.touchdown_v_max = 1.2
1868
+ self.touchdown_gate_bw = 0.05
1869
+ self._heel_graph = None
1870
+ self.brake_thr_bw = _f("TASKWALK_BRAKE_THR_BW", 0.35)
1871
+ assert self.brake_thr_bw >= 0.0, "TASKWALK_BRAKE_THR_BW must be non-negative"
1872
+ # Read once; the tensors are built on the first call, when the device is known.
1873
+ _toe_ever = _f_ever("TASKWALK_W_TOE_SPRING", 0.0) != 0.0
1874
+ _lim_ever = (_f_ever("TASKWALK_W_LIMIT_TORQUE", 0.0) != 0.0
1875
+ or _f_ever("TASKWALK_W_LIMIT_POWER", 0.0) != 0.0 or _toe_ever)
1876
+ self._lim = self._limit_layout(env) if _lim_ever else None
1877
+ if self.limit_torque_joints is not None:
1878
+ assert self._lim is not None, "TASKWALK_LIMIT_TORQUE_JOINTS needs TASKWALK_W_LIMIT_TORQUE (or _POWER) and a passive block"
1879
+ sel = [any(nm.startswith(pfx) for pfx in self.limit_torque_joints) for nm in self._lim["names"]]
1880
+ assert any(sel), (f"TASKWALK_LIMIT_TORQUE_JOINTS={self.limit_torque_joints} matches none of the limited joints "
1881
+ f"{self._lim['names']}")
1882
+ self._lim["tau_sel"] = [1.0 if x else 0.0 for x in sel]
1883
+ if self.limit_torque_stop: # logging only: the joints whose solver stop is priced (_stop_table builds lazily)
1884
+ _ss = [nm for nm in self._lim["names"] if any(nm.startswith(p) for p in self.limit_torque_stop_joints)] if self._lim is not None else None
1885
+ print(f"[taskwalk/limit] solver-stop price (TASKWALK_LIMIT_TORQUE_STOP) on "
1886
+ + (f"{len(_ss)} of {len(self._lim['names'])} limited joints, prefixes {self.limit_torque_stop_joints}: {_ss}"
1887
+ if _ss is not None else f"prefixes {self.limit_torque_stop_joints}, but no limit layout (W_LIMIT_TORQUE / _POWER 0)"), flush=True)
1888
+ if self.limit_torque_springs:
1889
+ assert self._lim is not None and self.limit_torque_joints is not None, (
1890
+ "TASKWALK_LIMIT_TORQUE_SPRINGS adds the springs of the joints TASKWALK_LIMIT_TORQUE_JOINTS selects")
1891
+ assert any(k > 0.0 and t > 0.0 for k, t in zip(self._lim["spring_k"], self._lim["tau_sel"])), (
1892
+ f"TASKWALK_LIMIT_TORQUE_SPRINGS=1 but none of the selected joints {self.limit_torque_joints} carries a coordinate "
1893
+ f"spring in this model (springs {dict(zip(self._lim['names'], self._lim['spring_k']))})")
1894
+ if _toe_ever:
1895
+ assert not self.limit_torque_springs, (
1896
+ "TASKWALK_W_TOE_SPRING prices the spring the TASKWALK_LIMIT_TORQUE_SPRINGS flag already folds into limit_torque: "
1897
+ "set the flag to 0 or the spring is charged twice")
1898
+ assert self._lim is not None and self.limit_torque_joints is not None, (
1899
+ "TASKWALK_W_TOE_SPRING charges the springs of the joints TASKWALK_LIMIT_TORQUE_JOINTS selects")
1900
+ assert any(k > 0.0 and t > 0.0 for k, t in zip(self._lim["spring_k"], self._lim["tau_sel"])), (
1901
+ f"TASKWALK_W_TOE_SPRING set but none of the selected joints {self.limit_torque_joints} carries a coordinate spring "
1902
+ f"(springs {dict(zip(self._lim['names'], self._lim['spring_k']))})")
1903
+ assert self.limit_torque_floor == 0.0, "TASKWALK_W_TOE_SPRING has no floor form"
1904
+ assert not (_lim_ever and self._lim is None), (
1905
+ "TASKWALK_W_LIMIT_TORQUE / _POWER need a model with a `passive` block and at least one "
1906
+ "limited 1-DOF joint")
1907
+ self._lim_t = None # device tensors, filled lazily
1908
+ # The adduction term builds the femur's long axis from a hip ROTATION MATRIX, so it needs a Ball
1909
+ # hip. On a hinge-stack hip (H1622v2k) `hip_*` is a scalar flexion index, and reading 4 entries
1910
+ # from it silently mixes two joints -- or, on nq=15, walks off the end of q with a bare
1911
+ # IndexError 4 seconds into training. Fail here instead, with the reason.
1912
+ assert not (self.w_hip_adduction != 0.0 and not m.get("hip_ball", True)), (
1913
+ f"TASKWALK_W_HIP_ADDUCTION={self.w_hip_adduction} needs a BALL hip; {m['name']} (nq={env.nq}) has a hinge-stack "
1914
+ f"hip, so its hip_r/hip_l are scalar FLEXION indices and the adduction term cannot be "
1915
+ f"computed from them. Set TASKWALK_W_HIP_ADDUCTION=0 for this model.")
1916
+ assert not (self.w_hip_rotation != 0.0 and not m.get("hip_ball", True)), (
1917
+ f"TASKWALK_W_HIP_ROTATION={self.w_hip_rotation} needs a BALL hip; {m['name']} (nq={env.nq}) has a hinge-stack "
1918
+ f"hip, so its hip_r/hip_l are scalar FLEXION indices and the rotation term cannot be "
1919
+ f"computed from them. Set TASKWALK_W_HIP_ROTATION=0 for this model.")
1920
+
1921
+ # --- r_speed_track: exp(-c e^2 / var), the authors' constants -----------------------------------------
1922
+ #
1923
+ # EVERY `*_VAR` KNOB IS A DIVISOR, SO A LARGER VALUE IS A **WEAKER** PENALTY. The five are
1924
+ # `V_VAR_X`, `V_VAR_LAT`, `ANGVEL_VAR_{ROLL,PITCH,YAW}`, `ORI_VAR` and `H_VAR`, and each is
1925
+ # SQUARED here before use, so the penalty exponent scales as 1/value^2. Raising one RELAXES the
1926
+ # term; lowering one TIGHTENS it. This is the opposite of every `W_*` weight in this file.
1927
+ #
1928
+ # This sign was reported backwards for a whole session on 2026-08-26. `ml26_angvel15` is named for
1929
+ # 1.5x the DEFAULTS below, but the baseline it is compared against (`ml26_squeeze`) sits at 2.0x --
1930
+ # so the "1.5x" cell has the SMALLER var and a (2.0/1.5)^2 = 1.78x LARGER penalty than its own
1931
+ # baseline. **A cell name is a multiple of the DEFAULT and says nothing about the direction of the
1932
+ # comparison**; read both env files before describing which way a var knob moved.
1933
+ self.c = 0.06
1934
+ self.v_tol = _f("TASKWALK_SPEED_TOL", 0.05) # flat band half-width (m/s)
1935
+ self.v_var_x = 0.07 ** 2
1936
+ # TWO-STAGE (sharp + wide) FORWARD-SPEED GAUSSIAN. 0 = OFF and the term is bit-identical.
1937
+ #
1938
+ # WHY. A single Gaussian's gradient is 2c*e/var * g, which vanishes at BOTH ends: linearly as
1939
+ # e -> 0, and exponentially as e grows because g decays faster than e rises. With sigma=0.07 and
1940
+ # c=0.06 the gradient peaks at e* = sigma/sqrt(2c) = 0.20 m/s and is DEAD outside roughly
1941
+ # [0.05, 0.5]. Measured 2026-09-04 on an untrained policy at V_HI=2.5: |v_fwd - v_tgt| is 1.594
1942
+ # m/s, i.e. 8x past the peak, where g_fwd ~ 3e-14 -- and since r_speed_track = g_fwd*g_lat*g_hw is a
1943
+ # PRODUCT, the whole w=10 velocity term is switched off exactly where training starts.
1944
+ #
1945
+ # A wider Gaussian alone would fix the far field and blunt the near field (its peak moves out to
1946
+ # 1.15 m/s at sigma=0.40). The mixture keeps both: the sharp component supplies precision near
1947
+ # the target, the wide one supplies a live gradient at the errors an untrained policy actually
1948
+ # has. Both are normalised to 1 at e=0, so the mixture is still in (0, 1] and composes with the
1949
+ # product unchanged.
1950
+ #
1951
+ # THE COST, stated: at large error the term no longer reads ~0 but ~mix*exp(-c e^2/var_wide), so
1952
+ # a policy that does not track is scored less harshly. That is the trade -- gradient where the
1953
+ # policy is, against a weaker penalty for being there.
1954
+ self.v_var_x2 = 0.0 ** 2 # wide sigma; 0 disables
1955
+ # LATERAL, not vertical. THEIR MODEL IS Y-UP: _is_terminated compares `com_pos().y` against the
1956
+ # lower foot's `com_pos().y`, and model_velocity() is `com_vel().x`. So their `vel_z` is the
1957
+ # SIDE-TO-SIDE COM velocity and the term penalises SWAY. Reading it as vertical -- which this did
1958
+ # -- penalises the COM rise and fall that walking is made of: measured on the 07_01 reference (a
1959
+ # real human walk) the vertical reading drops this factor to 0.128 at its worst, exactly at the
1960
+ # moments the foot leaves the ground, against 0.718 for the lateral one. r_speed_track is a PRODUCT, so
1961
+ # that lands on the whole reward.
1962
+ self.v_var_lat = 0.1 ** 2
1963
+ # VERTICAL, the third axis of the same product, added 2026-09-15 on request.
1964
+ # DEFAULT 0 = DISABLED, so every cell on record is bit-identical.
1965
+ #
1966
+ # WHY IT IS NOT THE BUG ABOVE. The paragraph above records that reading the authors' `vel_z`
1967
+ # as vertical crushed a REAL HUMAN WALK to 0.128, and that is why it became `v_lat`. That is a
1968
+ # verdict on the VARIANCE, not on the axis: `v_var_lat` = 0.10 m/s is the SWAY scale, and human
1969
+ # vertical COM velocity is three times larger. Measured on the reference this reward is scored
1970
+ # against (`myoassist_segmented_gait.npz`, `dq_pelvis_ty`): rms 0.262, p95 0.373, peak 0.409 m/s.
1971
+ #
1972
+ # WHY THE VARIANCE IS 0.45 AND NOT A GUESS. The sizing criterion is that the gate must be
1973
+ # ~FREE for a real human walk, so it charges only EXCESS: require g >= 0.95 at the human's PEAK,
1974
+ # sigma^2 >= C * 0.409^2 / ln(1/0.95) = 0.06 * 0.167 / 0.0513 = 0.195 -> sigma >= 0.442.
1975
+ # At 0.45 the human's worst frame scores 0.952 (the old bug's 0.10 gives 0.366) and the mean
1976
+ # gate is human 0.980 / ml26_romslack_s1 0.990 / ml26_spin_s1 0.942 -- i.e. it is inert on both
1977
+ # the human and the flat-bobbing cell and charges the one that bobs 111 mm against the human's
1978
+ # 70.7. Set it from the reference again if the reference changes; do not tune it against a score.
1979
+ #
1980
+ # READ THE RESULT WITH THIS IN MIND: 62% of this model's vertical excursion is arithmetically
1981
+ # the knee yield (knee_dip 23.5 deg -> 68.6 mm of hip drop on this leg), so the term is
1982
+ # PARTLY a knee_dip penalty. The human's own 70.7 mm bob is only 15% yield, so driving v_vert
1983
+ # down is right in direction but will find the STRUT if it overshoots. Watch knee_dip -> 0 and
1984
+ # past_bound rising, not the score.
1985
+ self.v_var_vert = 0.0 ** 2
1986
+ self.trunk_upright_var = 0.06 ** 2
1987
+ # Their angvel_var = [0.6, 0.65, 1.4]^2 is indexed in THEIR axes (x fwd, y UP, z lateral), i.e.
1988
+ # ROLL 0.6, YAW 0.65, PITCH 1.4.
1989
+ #
1990
+ # THE INDEX-FOR-INDEX COPY IS CORRECT AND WAS BROKEN BY a1fb2488, RESTORED 2026-09-17.
1991
+ # `w_head` is `2*vec(q_prev^-1 (x) q_t)/dt` expressed in the HEAD's OWN BODY FRAME, not in world.
1992
+ # On myoleg26 the torso is welded to the pelvis with identity quat and
1993
+ # `pelvis.quat = [0.7071, 0.7071, 0, 0]`, a 90 deg rotation about world x, so the body axes are
1994
+ # (x fwd, y UP, z lateral) -- THE SAME CONVENTION AS THE PAPER. a1fb2488 ("their model is Y-UP, so
1995
+ # two reward terms were aimed at the wrong axes") remapped indices 1 and 2 on the reasoning that
1996
+ # our WORLD is z-up. The world is; this quantity is not in it.
1997
+ #
1998
+ # MEASURED on five cells' rollouts, body axis against the world component it correlates with:
1999
+ # w_head[0] ROLL r +0.87..+0.99 rms 0.12-0.28 rad/s
2000
+ # w_head[1] YAW r +0.99..+1.00 rms 0.24-0.46 <- the LARGEST of the three
2001
+ # w_head[2] PITCH r -0.95..-0.99 rms 0.11-0.19
2002
+ # So from 2026-08-07 to 2026-09-17 the YAW rate was gated at sigma 1.40 and PITCH at 0.65 --
2003
+ # exactly the "pitch held 4.6x too tight" state that commit set out to remove.
2004
+ #
2005
+ # THIS IS NOT BIT-IDENTICAL and it is not meant to be: it is a transcription bug with a known
2006
+ # correct value, so it is restored rather than swept. Cells that set the three names by hand
2007
+ # (e.g. `bdampnd`: ROLL 1.20 / PITCH 2.80 / YAW 1.30, all 2x the then-defaults) now get those
2008
+ # values on the axes their names say, which is also 2x the CORRECTED defaults.
2009
+ # `test_head_angvel_axis_mapping_*` pins both the premise and the mapping.
2010
+ self.angvel_var = [_f("TASKWALK_HEAD_ANGVEL_VAR_ROLL", 0.60) ** 2,
2011
+ _f("TASKWALK_HEAD_ANGVEL_VAR_YAW", 0.65) ** 2,
2012
+ _f("TASKWALK_HEAD_ANGVEL_VAR_PITCH", 1.40) ** 2]
2013
+ self.use_head_ori = _b("TASKWALK_TRUNK_UPRIGHT_USE_HEAD", 0) # code drops it; ALREADY a flag
2014
+ self.v_lat_tol = _f("TASKWALK_SPEED_LAT_TOL", 0.0)
2015
+ self.angvel_tol = [0.0, # SAME ORDER as angvel_var: ROLL, YAW, PITCH
2016
+ 0.0,
2017
+ 0.0]
2018
+ assert self.v_lat_tol >= 0.0 and min(self.angvel_tol) >= 0.0, "a flat band is a half-width, >= 0"
2019
+ # SAME ORDER AS angvel_var, which is [ROLL, YAW, PITCH] -- see the mapping note there. A flag
2020
+ # named for one axis while gating another is precisely what `_b`'s docstring is about.
2021
+ self.gate_hw = [True,
2022
+ True,
2023
+ True]
2024
+ self.mean_var_x = 0.07 ** 2
2025
+ self.mean_var_lat = 0.1 ** 2
2026
+ self._mean_graph = None
2027
+
2028
+ # --- r_joint_limit: knee above 0, lumbar outside [-20, +10] deg (subtalar is commented out upstream) ---
2029
+ # SIGN: they penalize `knee - 0` when POSITIVE because their knee flexes negative. Whether OUR
2030
+ # knee does too is per-model (see knee_sign in _DOF_MAPS), so the violation is
2031
+ # `knee_sign * (knee_min - q)` clamped at 0.
2032
+ # DEFAULT = THE MODEL'S OWN KNEE BOUND, not a constant. The authors hardcode 0 and their H2190's
2033
+ # joint limit is also 0, so theirs agree by coincidence of value, not by linkage. Ours used to
2034
+ # default to 0 regardless of the model, which silently kills the term on any variant whose knee
2035
+ # stops short of 0: with the bound at -3 deg the knee cannot reach 0 (3 deg past it is ~105 N.m at
2036
+ # beta 0.001), so `clamp(knee_sign*(0 - q), 0)` is identically zero and the reward stops policing
2037
+ # anything. Read the bound off the model so physics and reward guard the SAME line; the env var
2038
+ # still overrides for a deliberate mismatch.
2039
+ self.knee_min = math.radians(_f("TASKWALK_KNEE_MIN_DEG", math.degrees(self._model_knee_bound(env))))
2040
+ self.lumbar_lo = math.radians(-20.0)
2041
+ self.lumbar_hi = math.radians(10.0)
2042
+
2043
+ # fall: COM height ABOVE THE LOWER FOOT below this (m). Theirs is 0.5 on a 1.8 m model; a
2044
+ # relative test, so it survives the slope curriculum where absolute height is meaningless.
2045
+ self.fall_h = _f("TASKWALK_FALL_H", 0.50)
2046
+ # ROOT-HEIGHT fall test, replacing the COM-above-foot one when set: Bolt's `env_lanes._get_terminated`
2047
+ # ends the episode at root height < 0.6 m on his model, whose standing pelvis is 1.038 m above the ground
2048
+ # (models/bolt_sprinter.dnmodel, all joints 0, lowest contact point) -- 57.8% of it. ABSOLUTE height, so it
2049
+ # needs flat ground, and it reads q[2] as world z, which is the full body's root layout (myoLeg26 orders its
2050
+ # free joint differently). 0 = off: every earlier run is bit-identical.
2051
+ self.fall_root_h = _f("TASKWALK_FALL_ROOT_H", 0.0)
2052
+ if self.fall_root_h > 0.0:
2053
+ assert env.nq in _FULLBODY_NQ, f"TASKWALK_FALL_ROOT_H reads q[2] as the root height (the full body); nq={env.nq}"
2054
+ assert (os.environ.get("TASKWALK_SLOPE_LO_DEG") == "0" and os.environ.get("TASKWALK_SLOPE_HI_DEG") == "0"), \
2055
+ "TASKWALK_FALL_ROOT_H is an absolute height: export TASKWALK_SLOPE_LO_DEG=0 and _HI_DEG=0 (flat ground)"
2056
+ # NON-FOOT FLOOR CONTACT as a fall (TASKWALK_FALL_NONFOOT=1; 11-13, the review): the m118 found the running line ending on
2057
+ # its knees, shins flat, the root 7-34 mm above FALL_ROOT_H, so it never terminated. With the switch any NON-foot floor pair of
2058
+ # the D16 law within its margin (env14's contact read, env._tw_nonfoot_term; E0_ENV14_KINLATCH) is OR-ed into the fall test
2059
+ # below: the same termination as the root height (done, not a timeout, bootstrap 0; r_fall at W_FALL_PENALTY), no new reward
2060
+ # term. It reads the control step's END pose, as the latch does. 0 = off, bit-identical.
2061
+ self.fall_nonfoot = os.environ.get("TASKWALK_FALL_NONFOOT", "0") == "1"
2062
+ assert os.environ.get("TASKWALK_FALL_NONFOOT", "0") in ("0", "1"), os.environ.get("TASKWALK_FALL_NONFOOT")
2063
+ # Knee-load threshold in bodyweights. The paper's number is 3, against a true tibiofemoral
2064
+ # reaction. Our estimate is the summed knee-spanning muscle tension, which does NOT project onto
2065
+ # the tibia axis and so runs high: measured on this model, 10.3 BW mean standing with the muscles
2066
+ # essentially off (max 108), rising to 21.9 under heavy co-contraction. At a threshold of 3 it
2067
+ # would fire every step and swamp every other term. 15 is calibrated to THIS estimator -- quiet at
2068
+ # rest, active under co-contraction, which is the behaviour the term is for. It is therefore a
2069
+ # co-contraction penalty calibrated to the model, NOT the paper's 3-bodyweight physiological
2070
+ # threshold; the honest version needs the RNE joint reaction (deferred).
2071
+ self.knee_load_min_bw = 15.0
2072
+ self.knee_load_cap_bw = 10.0 # bounds the heavy tail; see r_knee_load
2073
+ # THE SHAPE ABOVE THE THRESHOLD. 2.0 is Eq (2)'s square and the default, so every existing cell
2074
+ # is bit-identical; 1.0 is the ordinary engineering form, a hinge that charges the excess
2075
+ # linearly. Which one is right depends on what the term is FOR: the paper minimises total knee
2076
+ # load as the objective, where a square is correct because it is the thing being optimised,
2077
+ # while here it is a constraint on a gait that must load the knee to walk at all, and a square
2078
+ # on the excess punishes one bad frame far more than many mediocre ones.
2079
+ self.knee_load_exp = 2.0
2080
+
2081
+ # Head up axis in the HEAD's own body frame, calibrated from the standing keyframe by the env
2082
+ # (calibrate_head_up). Defaults to local +z so a caller that forgets is at least well-defined,
2083
+ # but the env always calibrates -- see _head_upright_and_rate for why the default is wrong.
2084
+ self.head_up_local = (0.0, 0.0, 1.0)
2085
+ self.log_terms = _b("TASKWALK_LOG_TERMS", 0) # off = no host syncs
2086
+ self.last_terms = None
2087
+ self.v_tgt = None # per-env target speed, set by the speed curriculum
2088
+ # COMMANDED HEADING (TASKWALK_HEADING, task_walk_env.py), (n,) world yaw in rad, DETACHED; None = off and every term below
2089
+ # reads world +x exactly as before (bit-identical). When set, the terms that assumed travel along world +x read the COMMAND
2090
+ # frame instead: the forward / lateral speed gates (and their EMA / stride-mean forms), the speed term's velocity, the
2091
+ # root-heading term and the head acceleration's fore-aft axis. The brake's fore-aft GRF is rotated by the env, which
2092
+ # computes it. The frame is the command, not the body: a turn is then progress along the new direction from its first
2093
+ # step, and nothing rewards the body for yawing toward a measurement axis.
2094
+ self.heading_cmd = None
2095
+ # TARGET COM HEIGHT above the lower foot, per env, drawn and observed exactly like v_tgt. Default
2096
+ # weight 0, which leaves the reward bit-identical to every earlier run.
2097
+ #
2098
+ # WHY IT EXISTS. The threshold `fall_h` was measured to set the maximum walkable speed on its own:
2099
+ # grouped over the corpus, cells with fall_h >= 0.86 are 0/8 at BOTH 1.3 and 1.6 m/s, cells at 0.80
2100
+ # are 5/8 at 1.3 and 0/8 at 1.6, and cells at <= 0.775 reach 1.6 at 3/8. The same knob also sets the
2101
+ # landing knee -- 0.90 gives knee_hs -11.7 against the human's -10.5 while 0.775 pins the knee to the
2102
+ # extension limit at -0.2. One scalar was deciding both, so a single run could have the posture or the
2103
+ # speed and not both. Making the height a COMMANDED, OBSERVED quantity turns that into a family the
2104
+ # policy learns across, which is what the commanded speed already is.
2105
+ #
2106
+ # RANGE, from the measured COM-above-lower-foot of every cell that actually walks: the reachable span
2107
+ # is 0.867 (fh80mk4 at 1.3) to 0.989 (fxfh), with per-cell medians 0.905-0.959. So 0.87-0.96 covers
2108
+ # crouch through upright with every target attainable; a target of 0.70 is a deep squat no walking
2109
+ # cell ever visits and 1.00 is above the leg's reach (femur 0.395 + shank 0.400).
2110
+ self.h_lo = 0.87
2111
+ self.h_hi = 0.96
2112
+ self.h_var = 0.05 ** 2
2113
+ # FLAT BAND, the same shape the speed term uses (v_tol), and it is needed for a recorded reason: the
2114
+ # COM rise and fall is what walking IS. The measured within-episode swing (max - min, per-cell median)
2115
+ # is 0.058-0.102 m, so an instantaneous height cost with no dead band charges normal gait. Sizing it
2116
+ # against those numbers, with c = 0.06 and h_var = 0.05^2:
2117
+ # height error tol 0 tol 0.02 tol 0.03 tol 0.05 situation
2118
+ # 0.03 0.021 0.002 0.000 0.000 half the within-stride swing
2119
+ # 0.05 0.058 0.021 0.010 0.000 half the largest swing
2120
+ # 0.09 0.177 0.111 0.083 0.038 target 0.96 while sitting at 0.87
2121
+ # 0.03 charges nothing for the swing and 0.083 for a full crouch, which at w_pelvis_height 10 is 0.83 reward
2122
+ # units -- 5.5x the 0.152 gap between the two gait attractors this line has been unable to select
2123
+ # between. 0.05 would both halve that and exceed the 0.09-wide target range, making every target
2124
+ # satisfiable from any height.
2125
+ self.h_tol = 0.03
2126
+ self.w_pelvis_height = 0.0
2127
+ # COM FLOOR: the fall condition made differentiable. Weight 0 by default (bit-identical).
2128
+ # r = relu(COM_FLOOR_H - h)^2, h = COM over the lowest foot contact sphere (the foot-sphere fall gate's own
2129
+ # quantity), charged at -W_COM_FLOOR per step.
2130
+ # WHY (2026-09-26, tools/grad_anatomy.py on the full body): the fall is a non-differentiable termination,
2131
+ # and on consistent ground the pathwise gradient of the rest of this reward points AWAY from staying up at
2132
+ # the start (per-env cos with d(sum COM height)/da -0.150) -- locally, falling forward buys speed. Nothing
2133
+ # differentiable here said "stay up". This says it with the SAME criterion the -250 already enforces.
2134
+ # PREDICTIVE: a task condition (do not fall), not a trajectory and not a scored column; zero on every frame
2135
+ # of human walking when COM_FLOOR_H is the human clip's own floor of h (0.8818 on 07_01 for the lane model).
2136
+ # COM_FLOOR_H has NO default: it is a measured property of a model and a clip.
2137
+ self.w_com_floor = _f("TASKWALK_W_COM_FLOOR", 0.0)
2138
+ assert self.w_com_floor >= 0.0, "TASKWALK_W_COM_FLOOR is a cost weight, >= 0"
2139
+ self.com_floor_h = float(os.environ["TASKWALK_COM_FLOOR_H"]) if self.w_com_floor != 0.0 else None
2140
+ # STANCE KNEE EXTENSION. Weight 0 by default, so the reward stays bit-identical to all ~300 cells.
2141
+ #
2142
+ # WHY IT IS BEING ADDED NOW, after being deliberately NOT added for months. Measured 2026-09-05:
2143
+ # no term in this reward is a function of an ABSOLUTE joint angle -- W_ROM is a one-sided bound
2144
+ # penalty and W_KNEE is a tibiofemoral LOAD penalty that is 0 in all 294 cells. And the
2145
+ # three-muscle-model cross-check just came back with knee_mid at -18.8 (myoleg26), -20.8 (hyfydy)
2146
+ # and -20.6 (millard) against the human's -1.2. The excess flexion is the same on three different
2147
+ # muscle models under this reward, so it is not the model -- it is the task, and the task has
2148
+ # never asked for the knee to extend.
2149
+ #
2150
+ # DELIBERATELY A DIAGNOSTIC. Rewarding the variable the cell is scored on proves nothing about
2151
+ # the physics; what it decides is whether the knee CAN extend at midstance in a gait that already
2152
+ # walks 6/8 with a human-scale range. If a direct term cannot do it, the barrier is optimisation
2153
+ # or stability and that is a much stronger result than another weight sweep.
2154
+ #
2155
+ # STANCE-GATED by the measured GRF rather than by phase, because the target is midstance and the
2156
+ # swing knee is already close to human (peak -69.5 against -56.9). The gate is the same `foot_grf`
2157
+ # the W_KNEE term uses. Flat band first: `TASKWALK_STANCE_KNEE_TOL_DEG` degrees of free play around the
2158
+ # target, on the same reasoning as v_tol and h_tol -- an instantaneous quadratic with no dead band
2159
+ # charges the loading wave that walking is made of.
2160
+ self.w_stance_knee_angle = 0.0
2161
+ # TOUCHDOWN KNEE (2026-10-19, gradient-field-ioc.md STATE 03:2x; the design brief, 03:2x: "if a reward pulled the heel-strike knee to 0
2162
+ # it would be perfect"). NOT PREDICTIVE, like the stance-knee term. Charged once per step per leg, at the control step whose foot
2163
+ # load first passes TASKWALK_STANCE_KNEE_GATE_BW (the load-onset transition touchdown_cost uses), on the flexion past
2164
+ # TGT + TOL, squared in degrees. The target is the human's strike knee, not 0 (Fukuchi 2018 at 1.3 m/s: 1.9 +- 4.6 deg), with
2165
+ # TOL of free play so the human pays nothing. Measured motive: the late-gate run (..._sknrls_s1) lands at 12.1 and its loading
2166
+ # flexes 17.2 from there (human 16.0), so 10.2 of its 11.5-deg loading overshoot is the landing offset. 0 = off, bit-identical.
2167
+ self.w_touchdown_knee = 0.0
2168
+ # POSTURE BANDS (2026-10-22, the steering line; NOT PREDICTIVE, the knee terms' form). Design note: "it keeps leaning
2169
+ # the torso back and walking with the feet wide." MEASURED: every steering cell with the knee terms leans back 12-13 deg
2170
+ # (steer1fc 0.2) and walks 221-411 mm wide (steer1fc 75); nothing in the reward prices either (w_root_up 0; the head
2171
+ # gate is centred on vertical and costs a 13-deg lean ~1% of the speed term). Centres and bands from human populations:
2172
+ # trunk pitch 4.4 +- 3.6 deg (412 trials, 3 labs, against the subject's standing posture: data/reference/human/
2173
+ # trunk_pitch_pop.npz), step width 157 +- 21 mm (Fukuchi 2018, 61 trials at 1.1-1.5 m/s, the opposite-strike calcaneus
2174
+ # offset: gdi_h_fukuchi2018_pop_v4.npz). TRUNK: per step, w x huber_sq(band_excess(pitch) in deg, HUBER_DEG). WIDTH: per
2175
+ # touchdown (the touchdown knee's load-onset), w x huber_sq(band_excess(width) in cm, HUBER_CM). Both read their axes in the
2176
+ # PELVIS FACING frame (facing_frame), not the command's. 0 = off, bit-identical.
2177
+ # MOTION TRACKING (2026-10-22, the DeepLoco-lite arm; NOT PREDICTIVE, an imitation term). Design note: "maybe use
2178
+ # imitation like DeepLoco; keep the results with and without." A COST w (1 - exp(-a e)) on the local pose error e (rad^2,
2179
+ # track_pose_error: the joints below the root, never the root's position, height or yaw) against a reference clip at the
2180
+ # env's phase (the env computes e: TASKWALK_TRACK_POSE=1). Bounded at w per step, so a turn can trade pose for the task;
2181
+ # written as a cost, so it adds no alive bonus. a: arm the pose scale (DN_IM_AP 2.0). 0 = off, bit-identical.
2182
+ self.w_track_pose = 0.0
2183
+ # The same error in DeepLoco's REWARD form, + w_r exp(-a e) (its terms are all positive kernels, so its per-step level never
2184
+ # goes negative). Same gradient as the cost form; the price is a level of up to w_r per step, i.e. an alive bonus of that
2185
+ # size. Chosen where the cost form could push turning steps below zero (2026-10-22: a negative level makes the fall pay).
2186
+ self.w_track_pose_r = 0.0
2187
+ self.w_trunk_pitch = 0.0
2188
+ self.w_step_width = 0.0
2189
+ # STANCE ANKLE (2026-10-20, gradient-field-ioc.md STATE 12:3x). NOT PREDICTIVE (stage A, like the two knee terms). The stance
2190
+ # knee follows the shank: over the eight touchdown-line records the knee at 40% tracks the ankle at 40% (r 0.79), which sits at
2191
+ # 15-21 deg of dorsiflexion against the human's 11.5 (Fukuchi 2018 at 1.3), and the model's soleus is silent until 38-44% of the
2192
+ # cycle where the human's (Schreiber 2019, 1.2-1.4 m/s) is at 33-40% of its peak from strike and reaches half of it by 31%: nothing
2193
+ # brakes the tibia in mid-stance. Charged per step on each leg in single support (stance_knee_gate, TASKWALK_STANCE_ANKLE_SINGLE
2194
+ # _SUPPORT, 1 by default) on the dorsiflexion past TGT + TOL, squared in degrees; TGT = the human's stance maximum (12.1 at 45%),
2195
+ # so the human pays nothing. The ankle coordinate is the one after the knee (the convention the reward's own "ankle" record uses),
2196
+ # checked by joint name on first use. 0 = off, bit-identical.
2197
+ self.w_stance_ankle = 0.0
2198
+ self.stance_ankle_single = 1
2199
+ # SIZING, because the raw term is large and this line has twice shipped a term whose weight was
2200
+ # read off the wrong scale. It is degrees SQUARED past the band, summed over two legs: at the
2201
+ # current baseline's 18.8 deg of midstance flexion that is 2*(18.8-1.2-8.0)^2 = 184.3 per stance
2202
+ # step at w=1, against a velocity reward whose MAXIMUM is W_VEL*1 = 10. So w=1 would be 18x the
2203
+ # entire task. w=0.01 puts it at 1.84, about 18% of the velocity term, and being quadratic it
2204
+ # falls to 0.16 by the time the knee reaches 12 deg -- a pull that fades as it succeeds.
2205
+ # fall_h TRACKS the target when the margin is set: fall_h = h_tgt - margin. The margin must exceed
2206
+ # the within-episode COM swing or a policy sitting exactly on its target still dies every stride --
2207
+ # measured swing (max - min per episode, median) is 0.058-0.102 m, so 0.05 is too tight and 0.09 is
2208
+ # the smallest value above the whole measured range. 0.0 disables the coupling and keeps fall_h fixed.
2209
+ self.fall_margin = 0.0
2210
+ self.h_tgt = None
2211
+ self._prev = {}
2212
+ self._h0 = None
2213
+
2214
+ def calibrate_head_up(self, head_quat_rest):
2215
+ """Set the head's up axis from its orientation in the standing keyframe: u_local = R0^T e_z, so
2216
+ (R(q) u_local)_z == 1 exactly at rest and falls off as the head tips, whatever the body frame is."""
2217
+ w, x, y, z = (float(v) for v in head_quat_rest[:, 0])
2218
+ self.head_up_local = (2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y))
2219
+
2220
+ def calibrate_up_body(self, body_quat_rest):
2221
+ """TASKWALK_UP_BODY=thorax: the up term's body axis from its standing-keyframe orientation, u_local = R0^T e_z (as
2222
+ calibrate_head_up), so the term (R(q) u_local)_z - 1 is exactly 0 at the standing attitude."""
2223
+ assert self.i_up_body is not None, "calibrate_up_body is for TASKWALK_UP_BODY=thorax"
2224
+ w, x, y, z = (float(v) for v in body_quat_rest[:, 0])
2225
+ self.up_body_local = (2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y))
2226
+
2227
+ def up_term(self, q, quat):
2228
+ """(n,) the w_root_up term's deficit before its weight: R[2,2] - 1 of the root quaternion (root, today's arithmetic) or
2229
+ (R_thorax(q) u_local)_z - 1 of the standing-calibrated thorax (TASKWALK_UP_BODY=thorax)"""
2230
+ if self.up_body == "root":
2231
+ x, y = q[4], q[5]
2232
+ return -2.0 * (x * x + y * y) # R[2, 2] - 1, 0 upright
2233
+ assert self.up_body_local is not None, "TASKWALK_UP_BODY=thorax: the env calibrates the thorax's axis (_tw_calibrate) first"
2234
+ bq = quat[self.i_up_body] # (4, n)
2235
+ u = self.up_body_local
2236
+ w, x, y, z = bq[0], bq[1], bq[2], bq[3]
2237
+ return ((2.0 * (x * z - y * w)) * u[0] + (2.0 * (y * z + x * w)) * u[1] + (1.0 - 2.0 * (x * x + y * y)) * u[2]) - 1.0
2238
+
2239
+ # ---------------------------------------------------------------------------------------------
2240
+ def reset(self, env_ids=None):
2241
+ """Drop the rate-term history for restarted envs (all of them when env_ids is None)."""
2242
+ if self._pp is not None: # the phase prior's per-env strike state
2243
+ if env_ids is None:
2244
+ self._pp = None
2245
+ else:
2246
+ self._pp[0][env_ids] = False
2247
+ self._pp[1][env_ids] = 0.0
2248
+ self._pp[2][env_ids] = 0.0
2249
+ self._pp[3][env_ids] = 0.0
2250
+ if env_ids is None:
2251
+ self._prev = {}
2252
+ self._fr_x1 = self._fr_x2 = self._fr_y1 = self._fr_y2 = None # TASKWALK_METABOLIC_FORCE_RATE re-seeds at the next force
2253
+ self._com_graph = None
2254
+ self._heel_graph = None
2255
+ self._u_graph = None
2256
+ self._ema_graph = None
2257
+ self._mean_graph = None
2258
+ self._lane_graph = None
2259
+ self._acc_graph = {}
2260
+ return
2261
+ # `_acc_graph` (TASKWALK_ACCEL_COUPLED) is not touched either: the stencils' n_valid counters, zeroed below,
2262
+ # mask the restarted envs until their history is post-reset.
2263
+ # `_com_graph` (TASKWALK_COM_RATE_COUPLED) is NOT zeroed here: it is attached, an in-place write would break
2264
+ # the backward, and the envs reset now are masked out of its correction by `valid` on the next step.
2265
+ for k, v in self._prev.items():
2266
+ if k.startswith("_acc_"):
2267
+ # `_accel` history is [p1, p2, n_valid], not a tensor: zero both samples AND the counter
2268
+ # so the restarted envs need two fresh steps again before the second difference is used.
2269
+ p1, p2, nv = v
2270
+ if p1 is not None:
2271
+ p1[..., env_ids] = 0.0
2272
+ p2[..., env_ids] = 0.0
2273
+ nv[env_ids] = 0
2274
+ elif k.startswith("_jrk_"):
2275
+ # `_jerk` history is [p1, p2, p3, n_valid] -- also a LIST, so it must be handled here and
2276
+ # not fall through to the tensor branch below, which would raise on a list.
2277
+ p1, p2, p3, nv = v
2278
+ if p1 is not None:
2279
+ p1[..., env_ids] = 0.0
2280
+ p2[..., env_ids] = 0.0
2281
+ p3[..., env_ids] = 0.0
2282
+ nv[env_ids] = 0
2283
+ elif k in ("ema_valid", "mean_valid"):
2284
+ pass # replaced below, never mutated (consumed by torch.where)
2285
+ elif k != "valid" and v is not None:
2286
+ v[..., env_ids] = 0.0 # detached history: in-place is safe
2287
+ if "valid" in self._prev: # absent before the first reward call: nothing to clear
2288
+ # REPLACE, never mutate: `valid` is consumed by torch.where inside the reward, so it is saved
2289
+ # for the backward pass. Editing it in place bumps its version and BPTT dies with
2290
+ # "a variable needed for gradient computation has been modified by an inplace operation".
2291
+ v = self._prev["valid"].clone()
2292
+ v[env_ids] = False
2293
+ self._prev["valid"] = v
2294
+ for k in ("ema_valid", "mean_valid"): # TASKWALK_SPEED_EMA_TAU / _MEAN_TAU: the restarted envs re-seed
2295
+ if k in self._prev:
2296
+ v = self._prev[k].clone()
2297
+ v[env_ids] = False
2298
+ self._prev[k] = v
2299
+
2300
+ def _velocity_ema(self, key, graph, v_h, dt, tau, valid_prev):
2301
+ """One step of the attached exponential average of the horizontal COM velocity `v_h` (2,n) with time constant
2302
+ `tau`: `graph` is the previous average (None after a full reset), `self._prev[key]` says which envs have one."""
2303
+ beta = dt / tau
2304
+ assert 0.0 < beta <= 1.0, (dt, tau)
2305
+ ema_valid = self._prev.get(key)
2306
+ if ema_valid is None or ema_valid.shape[-1] != v_h.shape[-1] or graph is None or graph.shape != v_h.shape:
2307
+ ema_valid = torch.zeros(v_h.shape[-1], dtype=torch.bool, device=v_h.device)
2308
+ prev = torch.zeros_like(v_h)
2309
+ else:
2310
+ prev = graph
2311
+ ema = torch.where(ema_valid[None, :], (1.0 - beta) * prev + beta * v_h, v_h)
2312
+ # a rate is real once `_rate` had a previous sample: seed on that step, blend from the next
2313
+ self._prev[key] = valid_prev.clone() if valid_prev is not None else torch.zeros_like(ema_valid)
2314
+ return ema
2315
+
2316
+ def detach_history(self, mask=None):
2317
+ """Cut the attached COM sample (TASKWALK_COM_RATE_COUPLED) at a BPTT boundary: all envs at a window start
2318
+ (the env's `initialize_trajectory`), the `mask` envs at a per-env cut (`detach_envs`). The previous window's
2319
+ graph is freed, so holding a reference into it is a "backward through the graph a second time"."""
2320
+ if self._heel_graph is not None:
2321
+ self._heel_graph = (self._heel_graph.detach() if mask is None
2322
+ else torch.where(mask, self._heel_graph.detach(), self._heel_graph))
2323
+ if self._fr_x1 is not None: # TASKWALK_METABOLIC_FORCE_RATE's attached filter state (the value carries)
2324
+ self._fr_x1, self._fr_x2, self._fr_y1, self._fr_y2 = (
2325
+ g.detach() if mask is None else torch.where(mask[None, :], g.detach(), g)
2326
+ for g in (self._fr_x1, self._fr_x2, self._fr_y1, self._fr_y2))
2327
+ if self._u_graph is not None: # TASKWALK_W_EXC_RISE's attached excitation
2328
+ self._u_graph = (self._u_graph.detach() if mask is None
2329
+ else torch.where(mask[None, :], self._u_graph.detach(), self._u_graph))
2330
+ if self._ema_graph is not None: # TASKWALK_SPEED_EMA_TAU's attached average
2331
+ self._ema_graph = (self._ema_graph.detach() if mask is None
2332
+ else torch.where(mask[None, :], self._ema_graph.detach(), self._ema_graph))
2333
+ if self._mean_graph is not None: # TASKWALK_SPEED_MEAN_TAU's attached average
2334
+ self._mean_graph = (self._mean_graph.detach() if mask is None
2335
+ else torch.where(mask[None, :], self._mean_graph.detach(), self._mean_graph))
2336
+ if self._lane_graph is not None: # TASKWALK_MID_LANE_FORM=heading's attached average
2337
+ self._lane_graph = (self._lane_graph.detach() if mask is None
2338
+ else torch.where(mask[None, :], self._lane_graph.detach(), self._lane_graph))
2339
+ for k, gs in self._acc_graph.items(): # TASKWALK_ACCEL_COUPLED's attached samples
2340
+ self._acc_graph[k] = [g.detach() if mask is None else torch.where(mask[None, :], g.detach(), g) for g in gs]
2341
+ if self._com_graph is None:
2342
+ return
2343
+ if mask is None:
2344
+ self._com_graph = self._com_graph.detach()
2345
+ else:
2346
+ self._com_graph = torch.where(mask[None, :], self._com_graph.detach(), self._com_graph)
2347
+
2348
+ def _origin(self, key, value):
2349
+ """`value` latched per-env at the first reward step after that env's reset, and held.
2350
+
2351
+ The lane term needs lateral displacement from where the EPISODE started; `_prev` is already
2352
+ cleared per-env by `reset`, so a companion bool in the same dict gets cleared with it and the
2353
+ next step re-latches. Detached throughout -- it is a constant the term measures against, and
2354
+ putting the reset pose in the graph would backprop into a teleport."""
2355
+ flag, org = self._prev.get(key + "_set"), self._prev.get(key)
2356
+ if flag is None:
2357
+ flag = torch.zeros(value.shape[-1], dtype=torch.bool, device=value.device)
2358
+ org = torch.zeros_like(value.detach())
2359
+ self._prev[key + "_set"], self._prev[key] = flag, org
2360
+ with torch.no_grad():
2361
+ # in-graph, no host read (11-11, the review): the captured window cannot carry `if bool(fresh.any())` and an indexed
2362
+ # write (S290B's first capture: cudaErrorStreamCaptureUnsupported); the same values: the fresh envs take the current value,
2363
+ # the latched ones keep theirs, and every flag is then set (flag | ~flag); in place, so the tensors keep their identity for
2364
+ # the reset pool, which finds the reset's in-place clears of these two tensors by identity / version counter
2365
+ fresh = ~flag
2366
+ org.copy_(torch.where(fresh, value.detach(), org))
2367
+ flag.fill_(True)
2368
+ return org
2369
+
2370
+ def _fr_coef(self, dt):
2371
+ """The causal 2nd-order Butterworth low-pass at `fr_hz` for sample time dt (bilinear transform with prewarping, scipy.signal.butter's
2372
+ design): (b0, b1, b2, a1, a2), unity DC gain."""
2373
+ if self._fr_c is not None:
2374
+ assert self._fr_c[0] == dt, ("the control step changed after construction", self._fr_c[0], dt)
2375
+ else:
2376
+ assert isinstance(dt, float) and 0.0 < self.fr_hz < 0.5 / dt, (dt, self.fr_hz)
2377
+ K = math.tan(math.pi * self.fr_hz * dt); n_ = 1.0 / (1.0 + math.sqrt(2.0) * K + K * K)
2378
+ b0 = K * K * n_
2379
+ self._fr_c = (dt, (b0, 2.0 * b0, b0, 2.0 * (K * K - 1.0) * n_, (1.0 - math.sqrt(2.0) * K + K * K) * n_))
2380
+ return self._fr_c[1]
2381
+
2382
+ def _force_rate(self, x, dt, valid_prev):
2383
+ """TASKWALK_METABOLIC_FORCE_RATE's power (W, per env) from the muscle forces x (n_mus, n_env) of this step; see __init__. The filter
2384
+ state is attached (cut by detach_history); envs with `valid_prev` false (restarted) re-seed at x."""
2385
+ b0, b1, b2, a1, a2 = self._fr_coef(dt)
2386
+ xd = x.detach()
2387
+ st = (self._fr_x1, self._fr_x2, self._fr_y1, self._fr_y2)
2388
+ if st[0] is None or st[0].shape != x.shape or valid_prev is None:
2389
+ x1 = x2 = y1 = y2 = xd
2390
+ fresh = None # every env seeds on this call
2391
+ else:
2392
+ fresh = ~valid_prev[None, :]
2393
+ x1, x2, y1, y2 = (torch.where(fresh, xd, s_) for s_ in st)
2394
+ y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2
2395
+ ydd = (y - 2.0 * y1 + y2) / (dt * dt)
2396
+ # THE SEED STEP (11-12, the reward-compile finding): with the state seeded at x the filter's output equals x only up to rounding
2397
+ # (unity DC gain in exact arithmetic), so y'' there is rounding amplified by 1 / dt^2 and its sign, hence which muscles carry the
2398
+ # |.|_+ gradient, is decided by the last bit (forcerate_conditioning.py: the window gradient's whole f32 / f64 gap sat on that
2399
+ # step). The intended value is 0 on a seed step; it is now exactly 0, value and gradient.
2400
+ ydd = torch.zeros_like(ydd) if fresh is None else torch.where(fresh, torch.zeros_like(ydd), ydd)
2401
+ p = (0.5 * self.fr_k) * ydd.clamp_min(0.0).sum(dim=0)
2402
+ self._fr_x1, self._fr_x2, self._fr_y1, self._fr_y2 = x, x1, y, y1
2403
+ if self.log_terms:
2404
+ self.last_force_rate = p.detach() # diagnostic (W per env), read by the replay gates only
2405
+ return p
2406
+
2407
+ def _onset_phi(self, u, dt):
2408
+ """Bhargava 2004's phi (Eq. 6) per muscle and env, averaged over this control step with u held (TASKWALK_METABOLIC_ONSET; see
2409
+ __init__). The counter t_stim lives in `_prev["onset_t"]` (detached; zeroed by reset(), dropped with a full reset) and is
2410
+ advanced here: + dt while u > 0.1, 0 otherwise. The gradient reaches u through the exponent only."""
2411
+ t0 = self._prev.get("onset_t")
2412
+ if t0 is None or t0.shape != u.shape:
2413
+ t0 = torch.zeros_like(u.detach())
2414
+ on = u.detach() > _ONSET_THR
2415
+ k = torch.where(on, u, torch.ones_like(u)) / _ONSET_TAU # 1 / s; the safe divisor never reaches the u <= 0.1 branch
2416
+ avg = _ONSET_FLOOR + (torch.exp(-t0 * k) - torch.exp(-(t0 + dt) * k)) / (k * dt)
2417
+ phi = torch.where(on, avg, torch.full_like(avg, _ONSET_FLOOR + 1.0))
2418
+ self._prev["onset_t"] = torch.where(on, t0 + dt, torch.zeros_like(t0)).detach()
2419
+ return phi
2420
+
2421
+ def _rate(self, key, value, dt):
2422
+ """(value - previous)/dt, zero on the first step after a reset. `value` stays in the graph; the
2423
+ stored previous is detached, which is the correct pathwise derivative for the CURRENT step."""
2424
+ prev = self._prev.get(key)
2425
+ valid = self._prev.get("valid")
2426
+ if valid is None:
2427
+ valid = torch.zeros(value.shape[-1], dtype=torch.bool, device=value.device)
2428
+ self._prev["valid"] = valid
2429
+ elif valid.shape[-1] != value.shape[-1]:
2430
+ valid = torch.zeros(value.shape[-1], dtype=torch.bool, device=value.device)
2431
+ self._prev["valid"] = valid
2432
+ if prev is None or prev.shape != value.shape:
2433
+ prev = torch.zeros_like(value)
2434
+ self._prev[key] = prev
2435
+ out = (value - prev) / dt
2436
+ out = torch.where(valid, out, torch.zeros_like(out))
2437
+ self._prev[key] = value.detach().clone()
2438
+ self._prev["valid"] = torch.ones_like(valid) # replaced, not mutated (see reset)
2439
+ return out
2440
+
2441
+ def _accel(self, key, value, dt):
2442
+ """Second central difference (v_t - 2 v_{t-1} + v_{t-2}) / dt^2, zero until TWO steps of history
2443
+ exist. Its own history, separate from `_rate`'s: `_rate` has a single shared `valid` flag, which
2444
+ would call the second difference usable one step too early and report a large bogus acceleration
2445
+ on the step after every reset.
2446
+
2447
+ Only `value` (the current sample) stays in the graph; both stored samples are detached, which is
2448
+ the same pathwise convention `_rate` uses -- the derivative of the CURRENT step's contribution.
2449
+ """
2450
+ h = self._prev.setdefault("_acc_" + key, [None, None, None]) # [p1, p2, n_valid]
2451
+ p1, p2, nv = h
2452
+ if p1 is None or p1.shape != value.shape:
2453
+ p1 = torch.zeros_like(value); p2 = torch.zeros_like(value)
2454
+ nv = torch.zeros(value.shape[-1], dtype=torch.uint8, device=value.device)
2455
+ if nv.shape[-1] != value.shape[-1]:
2456
+ nv = torch.zeros(value.shape[-1], dtype=torch.uint8, device=value.device)
2457
+ out = (value - 2.0 * p1 + p2) / (dt * dt)
2458
+ if self.accel_coupled: # TASKWALK_ACCEL_COUPLED: the stencil's own derivative
2459
+ g = self._acc_graph.get("_acc_" + key)
2460
+ if g is not None and g[0].shape == value.shape:
2461
+ out = out + (-2.0 * (g[0] - g[0].detach()) + (g[1] - g[1].detach())) / (dt * dt) # exactly 0 in value
2462
+ self._acc_graph["_acc_" + key] = [value, g[0]]
2463
+ else:
2464
+ self._acc_graph["_acc_" + key] = [value, value.detach()]
2465
+ out = torch.where(nv >= 2, out, torch.zeros_like(out))
2466
+ self._prev["_acc_" + key] = [value.detach().clone(), p1, torch.clamp(nv + 1, max=2)]
2467
+ return out
2468
+
2469
+ def head_accel_cost(self, a_head):
2470
+ """(n,) the head-acceleration cost from the (3,n) world head acceleration: fore-aft (x) and vertical (z) in units of
2471
+ REF, minus the dead band (TASKWALK_HEAD_ACCEL_BAND_*; 0 = unbanded), each capped before the square."""
2472
+ # TW1 (11-10, the GPU gate 3 under a CUDA graph capture): rows x and z as a strided view (the list index built a host index
2473
+ # tensor, an H2D copy each step) and the band cached on the device; the same values bit for bit (abs of the same elements;
2474
+ # each row's gradient one contribution either way)
2475
+ ah = a_head[0::2].abs() / self.head_accel_ref
2476
+ if max(self.head_accel_band) > 0.0:
2477
+ key = (ah.dtype, ah.device)
2478
+ band = getattr(self, "_head_accel_band_t", {}).get(key)
2479
+ if band is None:
2480
+ band = torch.tensor(self.head_accel_band, dtype=ah.dtype, device=ah.device)[:, None]
2481
+ self._head_accel_band_t = {**getattr(self, "_head_accel_band_t", {}), key: band}
2482
+ ah = (ah - band).clamp_min(0.0) # only the excess over the human band
2483
+ ah = ah.clamp(max=self.head_accel_cap)
2484
+ return (ah ** 2).sum(dim=0)
2485
+
2486
+ def touchdown_cost(self, foot_pos, foot_grf, valid_prev, dt):
2487
+ """(n,) sum over feet of td * relu(v_heel_x - V_MAX); see w_touchdown. `foot_pos` [right, left] (3,n) world
2488
+ calcaneus positions in the graph, `foot_grf` (2,n) vertical GRF in BW (detached), `valid_prev` the rate
2489
+ history's validity BEFORE this step's `_rate` calls (False on the first step after a reset)."""
2490
+ heel = torch.stack([foot_pos[0], foot_pos[1]]) # (2,3,n)
2491
+ n = heel.shape[-1]
2492
+ ok = (valid_prev if valid_prev is not None and valid_prev.shape[-1] == n
2493
+ else torch.zeros(n, dtype=torch.bool, device=heel.device))
2494
+ prev = self._prev.get("heel_td")
2495
+ if prev is None or prev.shape != heel.shape:
2496
+ prev = heel.detach().clone()
2497
+ v = (heel - prev) / dt
2498
+ if self._heel_graph is not None and self._heel_graph.shape == heel.shape:
2499
+ v = v - (self._heel_graph - self._heel_graph.detach()) / dt # exactly 0 in value; the prev sample's grad
2500
+ v = torch.where(ok, v, torch.zeros_like(v))
2501
+ self._heel_graph = heel
2502
+ self._prev["heel_td"] = heel.detach().clone()
2503
+ loaded = (foot_grf.detach() > self.touchdown_gate_bw).to(heel.dtype) # (2,n)
2504
+ was = self._prev.get("td_loaded")
2505
+ if was is None or was.shape != loaded.shape:
2506
+ was = torch.ones_like(loaded) # no touchdown on the first call
2507
+ td = loaded * (1.0 - was) * ok.to(heel.dtype)
2508
+ self._prev["td_loaded"] = loaded.clone()
2509
+ self.last_touchdown = td.detach()
2510
+ return (td * (v[:, 0, :] - self.touchdown_v_max).clamp_min(0.0)).sum(dim=0)
2511
+
2512
+ @staticmethod
2513
+ def brake_cost(foot_grf_x, thr):
2514
+ """(n,) per-env braking cost: sum over feet of relu(-F_x/BW - thr). `foot_grf_x` (2,n) in bodyweights,
2515
+ + = forward (+x, the walking direction); braking is the NEGATIVE part."""
2516
+ return (-foot_grf_x - thr).clamp_min(0.0).sum(dim=0)
2517
+
2518
+ def _jerk(self, key, value, dt):
2519
+ """Third backward difference (v_t - 3 v_{t-1} + 3 v_{t-2} - v_{t-3}) / dt^3, zero until THREE
2520
+ steps of history exist. Its own counter, like `_accel`'s.
2521
+
2522
+ WHY NOT `_rate(_accel(...))`. Composing them is the same stencil but takes its validity from
2523
+ `_rate`'s SINGLE SHARED `valid` flag, which is already true by the time `_accel` first returns a
2524
+ real number. The step after `_accel` becomes valid would then difference a real acceleration
2525
+ against the ZERO it emitted while warming up, and report a jerk of a_com/dt -- a spike about
2526
+ 100x the true value, once per reset, on exactly the term that is meant to price impact. This is
2527
+ the same failure `_accel`'s own docstring describes one level down.
2528
+
2529
+ Only `value` stays in the graph; the three stored samples are detached, matching `_rate` and
2530
+ `_accel` -- the derivative of the CURRENT step's contribution.
2531
+ """
2532
+ h = self._prev.setdefault("_jrk_" + key, [None, None, None, None]) # [p1, p2, p3, n_valid]
2533
+ p1, p2, p3, nv = h
2534
+ if p1 is None or p1.shape != value.shape:
2535
+ p1 = torch.zeros_like(value); p2 = torch.zeros_like(value); p3 = torch.zeros_like(value)
2536
+ nv = torch.zeros(value.shape[-1], dtype=torch.uint8, device=value.device)
2537
+ if nv.shape[-1] != value.shape[-1]:
2538
+ nv = torch.zeros(value.shape[-1], dtype=torch.uint8, device=value.device)
2539
+ out = (value - 3.0 * p1 + 3.0 * p2 - p3) / (dt * dt * dt)
2540
+ if self.accel_coupled: # TASKWALK_ACCEL_COUPLED: the stencil's own derivative
2541
+ g = self._acc_graph.get("_jrk_" + key)
2542
+ if g is not None and g[0].shape == value.shape:
2543
+ out = out + (-3.0 * (g[0] - g[0].detach()) + 3.0 * (g[1] - g[1].detach())
2544
+ - (g[2] - g[2].detach())) / (dt * dt * dt) # exactly 0 in value
2545
+ self._acc_graph["_jrk_" + key] = [value, g[0], g[1]]
2546
+ else:
2547
+ self._acc_graph["_jrk_" + key] = [value, value.detach(), value.detach()]
2548
+ out = torch.where(nv >= 3, out, torch.zeros_like(out))
2549
+ self._prev["_jrk_" + key] = [value.detach().clone(), p1, p2, torch.clamp(nv + 1, max=3)]
2550
+ return out
2551
+
2552
+ # ---------------------------------------------------------------------------------------------
2553
+ def _hip_adduction(self, q):
2554
+ """Frontal-plane hip angle per side, from the BALL hip quaternion.
2555
+
2556
+ Geometric rather than Euler: the femur's long axis in the pelvis frame is d = R_hip @ (0,0,-1),
2557
+ and its component along the body's lateral axis is the sine of the ab/adduction angle. Positive =
2558
+ ADducted (thigh toward the midline) on BOTH sides, which is why the left side takes -y: the model
2559
+ faces +x with +y to the left (issue #29), so medial is +y on the right and -y on the left. An Euler
2560
+ decomposition would need a convention and would gimbal near the pole; this does not.
2561
+ """
2562
+ out = []
2563
+ for adr, medial in ((self.i_hip_r, +1.0), (self.i_hip_l, -1.0)):
2564
+ w, x, y, z = q[adr], q[adr + 1], q[adr + 2], q[adr + 3]
2565
+ # third column of R(q), negated: d = R @ (0,0,-1)
2566
+ dx = -(2.0 * (x * z + y * w))
2567
+ dy = -(2.0 * (y * z - x * w))
2568
+ dz = -(1.0 - 2.0 * (x * x + y * y))
2569
+ n = torch.sqrt(dx * dx + dy * dy + dz * dz).clamp_min(1e-9)
2570
+ out.append(torch.asin((medial * dy / n).clamp(-1.0 + 1e-7, 1.0 - 1e-7)))
2571
+ return out[0], out[1]
2572
+
2573
+ def _hip_rotation(self, q):
2574
+ """Internal/external hip rotation per side, radians, from the BALL hip quaternion.
2575
+
2576
+ THE SAME ANGLE THE BOARD SCORES. `tools/gait/score.py:hip_rot_deg` reads it as the Y component of
2577
+ the ZXY intrinsic Euler chart -- the chart `core/dyn/ball_limit.h` constrains, in which Z is
2578
+ flexion, X is ad/abduction and Y is rotation with a symmetric +-40 deg range on both sides:
2579
+ rot = atan2(-R20, R22), R20 = 2(xz - wy), R22 = 1 - 2(xx + yy)
2580
+ so the reward and the score cannot drift apart on a convention.
2581
+
2582
+ NO MEDIAL SIGN, unlike `_hip_adduction`. The term is the SQUARE, which is sign-blind, and the
2583
+ chart already reads 0 at the anatomical neutral pose on both sides (identity quaternion ->
2584
+ atan2(0, 1) = 0). Mirroring would be a no-op that could only introduce a bug.
2585
+ """
2586
+ out = []
2587
+ for adr in (self.i_hip_r, self.i_hip_l):
2588
+ w, x, y, z = q[adr], q[adr + 1], q[adr + 2], q[adr + 3]
2589
+ out.append(torch.atan2(-(2.0 * (x * z - w * y)), 1.0 - 2.0 * (x * x + y * y)))
2590
+ return out[0], out[1]
2591
+
2592
+ def _head_upright_and_rate(self, quat, dt):
2593
+ """(head up-axis world-z component, head angular velocity as a 3-vector).
2594
+
2595
+ The authors weight the head's angular velocity PER AXIS (var = [0.6, 0.65, 1.4]^2), so this returns
2596
+ the vector, not a speed: collapsing it to a magnitude would apply the tightest tolerance to every
2597
+ axis and over-penalise the yaw the gait legitimately produces.
2598
+
2599
+ The up axis is the head's OWN rest axis, not local +z. The head body frame comes from the model and
2600
+ its local z is NOT vertical -- measured on armless_ball the up axis is local +y, and assuming +z made
2601
+ `1 - 2(x^2+y^2)` read 0.0000 in the standing keyframe.
2602
+ """
2603
+ hq = quat[self.i_head] # (4, n)
2604
+ u = self.head_up_local
2605
+ w, x, y, z = hq[0], hq[1], hq[2], hq[3]
2606
+ up_z = ((2.0 * (x * z - y * w)) * u[0] + (2.0 * (y * z + x * w)) * u[1]
2607
+ + (1.0 - 2.0 * (x * x + y * y)) * u[2]) # (R(q) u)_z
2608
+ # angular velocity from the frame-to-frame rotation: 2 * vec(q_prev^-1 (x) q_t) / dt (small-angle
2609
+ # exact to second order), expressed in the head frame like the authors' head_body.ang_vel().
2610
+ prev = self._prev.get("head_q")
2611
+ valid = self._prev.get("valid")
2612
+ if prev is None or prev.shape != hq.shape:
2613
+ prev = hq.detach().clone()
2614
+ self._prev["head_q"] = prev
2615
+ pw, px, py, pz = prev[0], prev[1], prev[2], prev[3]
2616
+ sgn = torch.sign((hq * prev).sum(0)).clamp_min(-1.0) # shortest arc
2617
+ rw = sgn * (pw * w + px * x + py * y + pz * z)
2618
+ rx = sgn * (pw * x - px * w - py * z + pz * y)
2619
+ ry = sgn * (pw * y + px * z - py * w - pz * x)
2620
+ rz = sgn * (pw * z - px * y + py * x - pz * w)
2621
+ _ = rw
2622
+ w_head = torch.stack([2.0 * rx / dt, 2.0 * ry / dt, 2.0 * rz / dt], 0)
2623
+ if valid is not None:
2624
+ w_head = torch.where(valid[None, :], w_head, torch.zeros_like(w_head))
2625
+ self._prev["head_q"] = hq.detach().clone()
2626
+ return up_z, w_head
2627
+
2628
+ # ---------------------------------------------------------------------------------------------
2629
+ def _shac_snu(self, q, qd, excitation):
2630
+ """SHAC Humanoid MTU reward, eq. 23-25 (see `reward_mode` in __init__). Frame definitions follow
2631
+ DiffRL envs/snu_humanoid.py, which the paper's prose ("projection") leaves open:
2632
+ v_x world-x velocity of the ROOT origin (their obs[5], `lin_vel - cross(torso_pos,
2633
+ ang_vel)`: the twist moved to the pelvis origin, not the COM its comment names). Our
2634
+ free joint is qd = [w_body; v_body], so v_world = R v_body.
2635
+ R_up world-up component of the root's up axis (obs[51], `up_vec[:, 1]` in their y-up world).
2636
+ R_heading the root's forward axis projected on the forward direction. Their code points it at a
2637
+ target 10 km down +x, which is +x to within 1e-4 rad over a 10 s episode; the paper's
2638
+ "forward direction" is +x exactly, and that is what this uses.
2639
+ ||a||^2 over the policy's commanded excitation in [0, 1]. Their `self.actions` is the action
2640
+ AFTER the [-1, 1] -> [0, 1] map, which dflex applies directly as the activation; ours is
2641
+ `u`, before the activation filter.
2642
+ Our root frame is x-anterior, z-up at the identity quaternion, as SNU's root is at its start
2643
+ rotation, so no calibration rotation is needed."""
2644
+ w, x, y, z = q[3], q[4], q[5], q[6]
2645
+ r00 = 1.0 - 2.0 * (y * y + z * z)
2646
+ r01 = 2.0 * (x * y - w * z)
2647
+ r02 = 2.0 * (x * z + w * y)
2648
+ v_x = r00 * qd[3] + r01 * qd[4] + r02 * qd[5]
2649
+ r_up = 1.0 - 2.0 * (x * x + y * y) # R[2, 2]
2650
+ r_heading = r00 # (R e_x) . e_x
2651
+ h = self.shac_h_scale * q[2] + self.shac_h_offset # SNU metres
2652
+ dh = (h - 0.51).clamp(-1.0, 0.05)
2653
+ r_height = torch.where(dh < 0.0, -200.0 * dh * dh, 4.0 * dh)
2654
+ r_act = (excitation ** 2).sum(dim=0)
2655
+ self.last_fall = (h < 0.46).to(q.dtype)
2656
+ if self.log_terms:
2657
+ with torch.no_grad():
2658
+ self.last_terms = {"v_x": float(v_x.mean()), "up": 0.1 * float(r_up.mean()),
2659
+ "heading": float(r_heading.mean()), "height": float(r_height.mean()),
2660
+ "act": -0.001 * float(r_act.mean())}
2661
+ return v_x + 0.1 * r_up + r_heading + r_height - 0.001 * r_act
2662
+
2663
+ def _activation_term(self, a_mean):
2664
+ """The effort term per env (moved out of __call__ verbatim on 2026-10-13 so the probe knob
2665
+ TASKWALK_EFFORT_EXCLUDE_MUSCLES can be tested; the arithmetic is unchanged)."""
2666
+ if self._n1eq_s is not None: # TASKWALK_EFFORT_N1_EQUIV: the N1-equivalent activation s a
2667
+ a_mean = self._n1eq_s.to(a_mean.dtype) * a_mean
2668
+ if self.activation_weighting == "volume":
2669
+ # `_muscle_mass` returns (n_mus, 1) (as `_mtu_param_table` did, whose `t` lambda ends in
2670
+ # `[:, None]`). An extra unsqueeze here made it (n_mus, 1, 1), which broadcast against
2671
+ # a_mean's (n_mus, n_env) to (n_mus, n_mus, n_env) and left r_activation as (26, 1024)
2672
+ # instead of (1024,). That crashed ml26_fxfhsc_volw_s1 at the first reward call.
2673
+ w_mus = self._vol_mass.to(a_mean.dtype) # (n_mus, 1), prop. to volume
2674
+ if self._effort_keep is None:
2675
+ wmean = lambda x: (w_mus * x).sum(dim=0) / w_mus.sum()
2676
+ else: # excluded muscles priced 0, the normaliser kept
2677
+ k_mus = self._effort_keep.to(a_mean.dtype)
2678
+ wmean = lambda x: (w_mus * k_mus * x).sum(dim=0) / w_mus.sum()
2679
+ elif self._effort_keep is None:
2680
+ wmean = lambda x: x.mean(dim=0)
2681
+ else:
2682
+ k_mus = self._effort_keep.to(a_mean.dtype)
2683
+ wmean = lambda x: (k_mus * x).sum(dim=0) / x.shape[0]
2684
+ if self.activation_exp == 2.0 and self.activation_weighting == "unit" and self._effort_keep is None:
2685
+ r_activation = (a_mean ** 2).mean(dim=0) # bit-identical to every cell on record
2686
+ else:
2687
+ r_activation = wmean(a_mean ** self.activation_exp) / (self.activation_aref ** (self.activation_exp - 2.0))
2688
+ return r_activation
2689
+
2690
+ def _cmd_frame(self, x, y):
2691
+ """A horizontal world vector (x, y) in the COMMAND frame: (along the commanded heading, to its left). The identity, with no
2692
+ arithmetic, when no heading is commanded, so every earlier cell is bit-identical."""
2693
+ if self.heading_cmd is None:
2694
+ return x, y
2695
+ h = self.heading_cmd.detach().to(x.dtype)
2696
+ assert h.shape == x.shape, (h.shape, x.shape)
2697
+ c, s = torch.cos(h), torch.sin(h)
2698
+ return c * x + s * y, -s * x + c * y
2699
+
2700
+ def __call__(self, q, qd, a_mean, excitation, com, quat, dt, foot_pos, fall_z=None,
2701
+ lce=None, lce_dot=None, foot_grf=None, head_pos=None, foot_grf_x=None, foot_grf3=None, track_err=None, foot_h2=None):
2702
+ """One scalar reward per env. `com` (3,n) world COM, `quat` (nb,4,n) body orientations,
2703
+ `foot_grf` (2,n) per-foot VERTICAL ground reaction in bodyweights, [right, left].
2704
+
2705
+ `foot_grf` is a DETACHED sensor reading and is now used ONLY as a per-leg stance gate
2706
+ (`w_knee_load`, `w_stance_knee_angle`). The ground-reaction TERMS derive it from `com`
2707
+ instead, which is in the graph -- the fore-aft component argument that used to be here is
2708
+ gone with them.
2709
+ `foot_grf_x` (2,n) per-foot FORE-AFT (+x) ground reaction in bodyweights, [right, left], IN THE GRAPH
2710
+ (the engine contact force's VJP), for `w_brake`.
2711
+ `head_pos` (3,n) is the head body's WORLD position, for the head-acceleration term. It must be
2712
+ the head body and not `com`: see `w_head_accel` for why substituting the COM turns that term
2713
+ into a ground-reaction penalty by Newton's third law.
2714
+
2715
+ There used to be a `grf_v` here carrying a finished tibiofemoral load off the step's DETACHED
2716
+ MTU side channel. Both consumers now derive what they need in-graph, so it is gone rather than
2717
+ left as an argument nobody reads."""
2718
+ n = q.shape[1]
2719
+ if self.v_tgt is None:
2720
+ self.v_tgt = torch.full((n,), 1.2, device=q.device, dtype=q.dtype)
2721
+
2722
+ # --- r_speed_track = r_vel_x * r_head_angvel * r_vel_z (the authors' product; see the module docstring
2723
+ # for why head ORIENTATION is computed but not multiplied in) ---------------------------------
2724
+ valid_prev = self._prev.get("valid") # before `_rate` marks every env valid
2725
+ v_com = self._rate("com", com, dt) # (3,n) world COM velocity
2726
+ if self.com_rate_coupled:
2727
+ if self._com_graph is not None and valid_prev is not None and self._com_graph.shape == com.shape:
2728
+ corr = (self._com_graph - self._com_graph.detach()) / dt # exactly 0 in value
2729
+ v_com = v_com - torch.where(valid_prev, corr, torch.zeros_like(corr))
2730
+ self._com_graph = com
2731
+ # kept for the env's DeepLoco reward (TASKWALK_LLC, llc_reward.py): the same in-graph COM rate, and where it is valid
2732
+ self.last_v_com = v_com
2733
+ self.last_v_com_valid = (valid_prev if valid_prev is not None
2734
+ else torch.zeros(v_com.shape[-1], dtype=torch.bool, device=v_com.device))
2735
+ v_fwd, v_lat = self._cmd_frame(v_com[0], v_com[1]) # world is z-up on BOTH our models
2736
+ v_fwd_g, v_lat_g = v_fwd, v_lat # what the forward / lateral GATES read
2737
+ # A DISABLED GATE IS NOT MULTIPLIED IN AT ALL -- see the flag block in __init__ for why that is
2738
+ # not the same as giving it a huge variance. BIT-PARITY, by construction: with every flag set the
2739
+ # factor list is [g_fwd, g_lat, g_hw] and the left-associative reduce at the bottom is exactly
2740
+ # `g_fwd * g_lat * g_hw`, with `g_hw` exactly `(e_roll * e_pitch) * e_yaw` -- the old
2741
+ # `ones_like(g_fwd) * e0 * e1 * e2` opens with an exact `1.0 * e0`, so dropping the `ones` does
2742
+ # not move a bit. Float multiply is NOT associative, which is why the GROUPING is preserved here
2743
+ # rather than flattening everything into one running product.
2744
+ gates = []
2745
+ e_v = (v_fwd_g - self.v_tgt).abs().sub(self.v_tol).clamp_min(0.0) # 0 inside the flat band
2746
+ g_fwd = torch.exp(-self.c * e_v ** 2 / self.v_var_x)
2747
+ gates.append(g_fwd)
2748
+ g_lat = None
2749
+ e_lat = v_lat_g if self.v_lat_tol == 0.0 else v_lat_g.abs().sub(self.v_lat_tol).clamp_min(0.0)
2750
+ g_lat = torch.exp(-self.c * e_lat ** 2 / self.v_var_lat) # SWAY (see v_var_lat; band v_lat_tol)
2751
+ if g_lat is not None:
2752
+ gates.append(g_lat)
2753
+ g_mean = None
2754
+ # UNCONDITIONAL: this call advances self._prev["head_q"], so skipping it when the head gates are
2755
+ # off would leave a stale previous quaternion and make the flags change more than they name.
2756
+ up_z, w_head = self._head_upright_and_rate(quat, dt)
2757
+ g_hw = None
2758
+ for i_ax in range(3):
2759
+ if self.gate_hw[i_ax]:
2760
+ w_ax = (w_head[i_ax] if self.angvel_tol[i_ax] == 0.0
2761
+ else w_head[i_ax].abs().sub(self.angvel_tol[i_ax]).clamp_min(0.0))
2762
+ e_hw = torch.exp(-self.c * w_ax ** 2 / self.angvel_var[i_ax])
2763
+ g_hw = e_hw if g_hw is None else g_hw * e_hw
2764
+ if g_hw is not None:
2765
+ gates.append(g_hw)
2766
+ if self.use_head_ori:
2767
+ gates.append(torch.exp(-self.c * (1.0 - up_z) ** 2 / self.trunk_upright_var))
2768
+ if self.log_terms:
2769
+ # DIAGNOSTIC ONLY: the product's factors, so a probe can say WHICH gate a posture pays into
2770
+ # (tools/gait/taskwalk_term_rollout.py). The per-axis head gates are re-derived there from
2771
+ # w_head with this object's own c and angvel_var. up_x (world forward component of the same up axis)
2772
+ # SIGNS the tilt that up_z alone cannot: atan2(up_x, up_z) > 0 leans toward +x, the walking direction.
2773
+ hq, u = quat[self.i_head], self.head_up_local
2774
+ w_, x_, y_, z_ = hq[0], hq[1], hq[2], hq[3]
2775
+ up_x = ((1.0 - 2.0 * (y_ * y_ + z_ * z_)) * u[0] + (2.0 * (x_ * y_ - z_ * w_)) * u[1]
2776
+ + (2.0 * (x_ * z_ + y_ * w_)) * u[2]) # (R(q) u)_x
2777
+ self.last_gates_t = {"fwd": g_fwd.detach(),
2778
+ "lat": g_lat.detach() if g_lat is not None else None,
2779
+ "mean": g_mean.detach() if g_mean is not None else None,
2780
+ "w_head": w_head.detach(), "up_z": up_z.detach(), "up_x": up_x.detach(),
2781
+ "v_com": v_com.detach(), # the raw (3, n) velocity the gates read
2782
+ "knee": q[[self.i_knee_r, self.i_knee_l]].detach(),
2783
+ # the ankle sits right after the knee in every layout of _DOF_MAPS (armless_ball 15 / 23)
2784
+ "ankle": q[[self.i_knee_r + 1, self.i_knee_l + 1]].detach(),
2785
+ "foot_grf": foot_grf.detach() if foot_grf is not None else None}
2786
+ r_speed_track = gates[0]
2787
+ for g in gates[1:]:
2788
+ r_speed_track = r_speed_track * g
2789
+
2790
+ # --- the velocity the sprint term pays (see `speed_max_signal` in __init__) --------------------
2791
+ if self.speed_max_signal == "root":
2792
+ w, x, y, z = q[3], q[4], q[5], q[6] # the same R row `_shac_snu` reads
2793
+ v_speed = ((1.0 - 2.0 * (y * y + z * z)) * qd[3] + 2.0 * (x * y - w * z) * qd[4]
2794
+ + 2.0 * (x * z + w * y) * qd[5])
2795
+ if self.heading_cmd is not None: # R row 1: the root's world-y velocity
2796
+ v_y = (2.0 * (x * y + w * z) * qd[3] + (1.0 - 2.0 * (x * x + z * z)) * qd[4]
2797
+ + 2.0 * (y * z - w * x) * qd[5])
2798
+ v_speed, _ = self._cmd_frame(v_speed, v_y)
2799
+ else:
2800
+ v_speed = v_fwd
2801
+
2802
+ # --- root orientation (see `w_root_up` in __init__) --------------------------------------------
2803
+ if self.w_root_up != 0.0 or self.w_root_heading != 0.0:
2804
+ w, x, y, z = q[3], q[4], q[5], q[6] # the same R entries `_shac_snu` reads
2805
+ r_root_up = (-2.0 * (x * x + y * y) if self.up_body == "root" # R[2, 2] - 1, 0 upright (the default, as before)
2806
+ else self.up_term(q, quat)) # TASKWALK_UP_BODY=thorax: the standing-calibrated trunk
2807
+ r_root_heading = -2.0 * (y * y + z * z) # R[0, 0] - 1, 0 facing +x
2808
+ if self.heading_cmd is not None:
2809
+ # (R e_x) . (cos h, sin h, 0) - 1 = cos(yaw - h) - 1 for an upright root: 0 facing the command
2810
+ f_fwd, f_lat = self._cmd_frame(1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + w * z))
2811
+ r_root_heading = f_fwd - 1.0 # cos(e) - 1
2812
+ else:
2813
+ r_root_up = r_root_heading = torch.zeros_like(v_fwd)
2814
+
2815
+ # --- mid-lane: stay on the line you started on (Bolt's mid_lane_reward) --------------------
2816
+ if self.w_mid_lane != 0.0 and self.mid_lane_form == "heading": # TASKWALK_MID_LANE_FORM=heading (see __init__)
2817
+ vf = self._lane_graph = self._velocity_ema("lane_ema_valid", self._lane_graph, v_com[:2], dt, self.lane_tau, valid_prev)
2818
+ f_l, l_l = self._cmd_frame(vf[0], vf[1])
2819
+ r_mid_lane = lane_heading_reward(f_l, l_l, valid_prev, self.lane_k, self.lane_vmin)
2820
+ elif self.w_mid_lane != 0.0 and self.mid_lane_form == "root": # R17: Bolt's z = the pelvis's world lateral position, centre 0
2821
+ r_mid_lane = torch.exp(-self.mid_lane_k * q[1] ** 2)
2822
+ elif self.w_mid_lane != 0.0:
2823
+ dz = com[1] - self._origin("lane0", com[1]) # lateral displacement since reset, m
2824
+ r_mid_lane = torch.exp(-self.mid_lane_k * dz ** 2)
2825
+ else:
2826
+ r_mid_lane = torch.zeros_like(r_speed_track)
2827
+
2828
+ # --- effort: MEAN squared activation ------------------------------------------------------------
2829
+ # The authors SUM over their 90 muscles at weight 0.1. We have 290, so the same formula prices
2830
+ # effort 3.22x higher against an unchanged velocity reward -- and with w=10 (intended for the mean)
2831
+ # it measured 836 against a velocity term of 1.6, i.e. 500x, which trains the policy to go limp.
2832
+ # mean * 10 reproduces their balance exactly: 10 * mean(a^2) == 0.1 * 90 * mean(a^2).
2833
+ # EXPONENT, default 2.0 = the authors' form, bit-identical to every cell on record.
2834
+ # WHY IT IS A KNOB. A power n charges the PEAK relative to a persistent FLOOR by (peak/floor)^n,
2835
+ # so on the measured iliopsoas profile (floor 0.209, peak 0.545) n=1 gives 2.6x, n=2 gives 6.8x
2836
+ # and n=3 gives 17.7x. A quadratic therefore shaves peaks and leaves a floor standing, which is
2837
+ # the one activation pattern in this gait that is outside the human range. n=1 is not a sparsity
2838
+ # prior either -- it is the small-u limit of Wang's slow-twitch recruitment term
2839
+ # (40*lam*sin(pi/2 u), metabolic_rate above), i.e. the half that mean(a^2) drops.
2840
+ # n=3 is Crowninshield & Brand 1981's redundancy criterion, aimed at load SHARING rather than at
2841
+ # a floor, and it moves the floor the WRONG way -- which is exactly why it belongs in the ladder
2842
+ # as the control: if n=3 also helps, the floor mechanism is wrong.
2843
+ # NORMALISED so the ladder varies SHAPE ONLY. A bare a^n also rescales the term (a uniform 0.2
2844
+ # activation costs 0.20 / 0.040 / 0.0080 at n = 1 / 2 / 3), so an unnormalised n=1 cell would
2845
+ # carry 5x the effort weight of its n=2 parent and the comparison would confound curvature with
2846
+ # magnitude. Dividing by A_REF^(n-2) makes all three arms agree exactly when every activation
2847
+ # equals A_REF and differ only in how they price deviations from it. A_REF is the measured mean
2848
+ # activation on this line (per-muscle cycle means run 0.073-0.398, overall 0.18 on
2849
+ # ml26_bdamp01_nd at v=1.3); it sets where the arms cross, not the physics.
2850
+ # OMEGA: Ackermann's other axis. "unit" is a plain mean over muscles -- their omega_i = 1, and
2851
+ # the shipped behaviour. "volume" weights each muscle by its VOLUME and divides by the weight
2852
+ # sum, which is their omega_i = V_i. Volume = mass / density with ONE density for every muscle,
2853
+ # so the density cancels in the normalised sum and Wang's per-muscle mass is used directly
2854
+ # rather than inventing a constant.
2855
+ r_activation = self._activation_term(a_mean)
2856
+ r_active_sat = torch.zeros_like(r_activation)
2857
+
2858
+ # --- metabolic: Wang et al. 2012 Ė = Ȧ + Ṁ + Ṡ + Ẇ, per step, W/kg of body mass -------------
2859
+ r_met = torch.zeros_like(r_speed_track)
2860
+ if self.w_metabolic_rate != 0.0:
2861
+ assert lce is not None, "TASKWALK_W_METABOLIC_RATE needs the fibre length"
2862
+ assert self.metabolic_terms == "heat" or lce_dot is not None, (
2863
+ 'TASKWALK_METABOLIC_RATE_TERMS="all" needs the fibre velocity')
2864
+ # GRADIENT REACH. Every input here is in-graph: u and a from the policy, lce from the
2865
+ # state, lce_dot from lce against a detached previous value. The force is derived from
2866
+ # those (geyer_curves_torch), NOT taken from the coupling stage's detached side channel --
2867
+ # that is what made the four-term gradient point the wrong way.
2868
+ # the keyword only when on: the off call is today's call, unchanged (wrappers of metabolic_rate keep working)
2869
+ kw_on = {}
2870
+ if self._n1eq_s is not None: # TASKWALK_EFFORT_N1_EQUIV: the heats at s u, s a (see _n1_equiv_scale)
2871
+ kw_on["heat_scale"] = self._n1eq_s.to(a_mean.dtype)
2872
+ r_met = metabolic_rate(excitation, a_mean, lce, lce_dot, self._met,
2873
+ self.metabolic_terms,
2874
+ mech_scale=self.metabolic_mech, **kw_on) / self._met["body_mass"]
2875
+ r_met_sq = torch.zeros_like(r_speed_track)
2876
+ if self.w_metabolic_sq != 0.0:
2877
+ assert lce is not None and lce_dot is not None, "TASKWALK_W_METABOLIC_SQ needs the fibre length and velocity"
2878
+ e_mus = metabolic_rate(excitation, a_mean, lce, lce_dot, self._met, "all",
2879
+ mech_scale=self.metabolic_mech, per_muscle=True) # (n_mus, n_env), W
2880
+ r_met_sq = (e_mus ** 2).sum(dim=0) / (e_mus.shape[0] * self._met["body_mass"])
2881
+ if self.log_terms:
2882
+ # DIAGNOSTIC ONLY: the effort terms' per-muscle parts (tools/gait/fb_crn_fields.py --record-muscles), so a field can
2883
+ # be resolved to the muscle it acts through. Detached; nothing reads it inside the reward.
2884
+ self.last_muscle_t = {"a": a_mean.detach(),
2885
+ "e": e_mus.detach() if self.w_metabolic_sq != 0.0 else None}
2886
+
2887
+ # --- MECHANICS COSTS (all inert at weight 0; see their declarations for sources) --------------
2888
+ zero = torch.zeros_like(r_speed_track)
2889
+
2890
+ # GRF RATE -- Veerkamp's FGImpact, L1 over {fore-aft, vertical} of the TOTAL ground reaction.
2891
+ # d(GRF/Mg)/dt = d3(com)/dt3 / g: the +1 vertical offset differentiates away and the mass has
2892
+ # already cancelled. Taken as ONE third-difference rather than `_rate(_accel(...))` -- see
2893
+ # `_jerk` for the once-per-reset spike that composition produces. This is the noisiest term in
2894
+ # the reward by construction: three time derivatives of a 100 Hz signal.
2895
+ r_grf_rate = zero
2896
+
2897
+ r_touchdown = zero
2898
+
2899
+ if self.w_brake != 0.0:
2900
+ assert foot_grf_x is not None, "w_brake needs foot_grf_x, the per-foot fore-aft GRF in the graph"
2901
+ r_brake = self.brake_cost(foot_grf_x, self.brake_thr_bw)
2902
+ else:
2903
+ r_brake = zero
2904
+
2905
+ if self.w_com_pos_work != 0.0:
2906
+ assert foot_grf3 is not None and foot_grf3.shape[:2] == (3, 2), (
2907
+ "w_com_pos_work needs foot_grf3, the per-foot 3-D GRF in bodyweights (3, 2, n), in the graph")
2908
+ p_feet = (foot_grf3 * v_com[:, None, :].to(foot_grf3.dtype)).sum(0) # (2, n), BW * m/s
2909
+ r_com_pos_work = (9.81 * p_feet.clamp_min(0.0).sum(0)).to(r_speed_track.dtype) # W/kg
2910
+ else:
2911
+ r_com_pos_work = zero
2912
+
2913
+ r_state_prior = zero
2914
+
2915
+ r_phase_prior = zero
2916
+
2917
+ # PEAK VERTICAL GRF -- one-sided above the human's first peak, squared. Two derivatives only,
2918
+ # so this is the better-conditioned of the pair and the one to run first.
2919
+ r_grf_peak = zero
2920
+
2921
+ # HEAD ACCELERATION -- Veerkamp's HeadStab: fore-aft (world x) and vertical (world z).
2922
+ if self.w_head_accel != 0.0:
2923
+ assert head_pos is not None, "TASKWALK_W_HEAD_ACCEL needs the head body's world position"
2924
+ a_head = self._accel("head", head_pos, dt) # (3,n) m/s^2
2925
+ if self.heading_cmd is not None: # fore-aft = along the command
2926
+ a_f, a_l = self._cmd_frame(a_head[0], a_head[1])
2927
+ a_head = torch.stack([a_f, a_l, a_head[2]], 0)
2928
+ # fore-aft (world x) and vertical (world z), each in units of REF, each CAPPED before the
2929
+ # square so one violent frame cannot outweigh a whole episode.
2930
+ r_head_accel = self.head_accel_cost(a_head)
2931
+ if self.log_terms:
2932
+ self.last_head_acc_t = a_head[[0, 2]].detach() # DIAGNOSTIC ONLY (fb_crn_fields --record-gates)
2933
+ else:
2934
+ r_head_accel = zero
2935
+
2936
+ # JOINT-LIMIT TORQUE and POWER -- the stop the engine actually applies, same srelu law.
2937
+ if self.w_limit_torque != 0.0:
2938
+ if self._lim_t is None:
2939
+ L, dev = self._lim, q.device
2940
+ self._lim_t = dict(
2941
+ q=torch.tensor(L["q"], dtype=torch.long, device=dev),
2942
+ v=torch.tensor(L["v"], dtype=torch.long, device=dev),
2943
+ lo=torch.tensor(L["lo"], dtype=q.dtype, device=dev).unsqueeze(-1),
2944
+ hi=torch.tensor(L["hi"], dtype=q.dtype, device=dev).unsqueeze(-1),
2945
+ d=torch.tensor(L["d_lim_v"], dtype=q.dtype, device=dev).unsqueeze(-1),
2946
+ k=torch.tensor(L["k_lim_v"], dtype=q.dtype, device=dev).unsqueeze(-1),
2947
+ sel=(torch.tensor(L["tau_sel"], dtype=q.dtype, device=dev).unsqueeze(-1) if "tau_sel" in L else None),
2948
+ sk=torch.tensor(L["spring_k"], dtype=q.dtype, device=dev).unsqueeze(-1),
2949
+ sr=torch.tensor(L["spring_rest"], dtype=q.dtype, device=dev).unsqueeze(-1))
2950
+ T, beta = self._lim_t, self._lim["beta"]
2951
+ qk, vk = q[T["q"]], qd[T["v"]] # (nlim, n)
2952
+ dlo, dhi = T["lo"] - qk, qk - T["hi"]
2953
+ eng = _srelu_d(dlo, beta) + _srelu_d(dhi, beta)
2954
+ # SAME BRANCH THE ENGINE TAKES (core/dyn/passive.h:167). exp_a > 0 -> the exponential
2955
+ # ligament spring; otherwise the k_lim linear law, which keeps every model without a
2956
+ # `passive.exp` block bit-identical.
2957
+ _a, _w = self._lim["exp_a"], self._lim["exp_w"]
2958
+ spring = (_limexp(dlo, _a, _w) - _limexp(dhi, _a, _w)) if _a > 0.0 else \
2959
+ T["k"] * (_srelu(dlo, beta) - _srelu(dhi, beta))
2960
+ tau_lim = spring - T["d"] * vk * eng
2961
+ if self.limit_torque_stop: # + the solver's stop (TASKWALK_LIMIT_TORQUE_STOP, see __init__)
2962
+ tau_lim = tau_lim + self._stop_torque(qk, vk, dlo, dhi)
2963
+ if self.limit_torque_springs: # + the joint's coordinate spring, signed (see __init__)
2964
+ tau_lim = tau_lim - T["sk"] * (qk - T["sr"])
2965
+ _tl = tau_lim.abs()
2966
+ if self.limit_torque_floor > 0.0: # free up to the healthy end of range
2967
+ _tl = (_tl - self.limit_torque_floor).clamp_min(0.0)
2968
+ if T["sel"] is not None: # TASKWALK_LIMIT_TORQUE_JOINTS: only the selected stops
2969
+ _tl = _tl * T["sel"]
2970
+ if self.limit_torque_pow == 2.0: # the PredSim form, per joint (see __init__)
2971
+ r_limit_torque = ((_tl / self.limit_torque_ref) ** 2).sum(dim=0)
2972
+ else:
2973
+ r_limit_torque = _tl.sum(dim=0) / self.limit_torque_ref
2974
+ # dissipated POWER, always >= 0: the dashpot can only take energy out.
2975
+ r_limit_power = (T["d"] * vk * vk * eng).sum(dim=0) / self.limit_power_ref
2976
+ if self.w_limit_torque == 0.0:
2977
+ r_limit_torque = zero
2978
+ r_limit_power = zero
2979
+ r_toe_spring = zero
2980
+ else:
2981
+ r_limit_torque = r_limit_power = r_toe_spring = zero
2982
+
2983
+ # --- rom: knee past neutral + lumbar outside the band (subtalar commented out upstream) --------
2984
+ _vr = self.knee_sign * (self.knee_min - q[self.i_knee_r])
2985
+ _vl = self.knee_sign * (self.knee_min - q[self.i_knee_l])
2986
+ if self.joint_limit_beta > 0.0: # smooth hinge; see the declaration
2987
+ kr, kl = _srelu(_vr, self.joint_limit_beta), _srelu(_vl, self.joint_limit_beta)
2988
+ else:
2989
+ kr, kl = _vr.clamp_min(0.0), _vl.clamp_min(0.0) # bit-identical to every cell on record
2990
+ # `kr`/`kl` stay LINEAR below -- the step form and the gradient probe both read them as the raw
2991
+ # violation, and only the summed penalty takes the exponent.
2992
+ r_joint_limit = kr + kl
2993
+ # The step form: 1 per leg past the bound, 0 otherwise. Deliberately NOT differentiable; see
2994
+ # the note at `w_joint_limit_step`. Knee only -- the lumbar band below has no step counterpart
2995
+ # and myoleg26 has no lumbar coordinate at all.
2996
+ r_joint_limit_step = zero
2997
+ if self.i_lumbar is not None:
2998
+ # A model with a welded trunk (myoleg26) has no lumbar coordinate to hold in a band; the term
2999
+ # DROPS rather than aiming at whatever index 7 happens to be on that model.
3000
+ lum = q[self.i_lumbar]
3001
+ r_joint_limit = r_joint_limit + (self.lumbar_lo - lum).clamp_min(0.0) + (lum - self.lumbar_hi).clamp_min(0.0)
3002
+
3003
+ # --- fall: COM height above the LOWER foot, a relative test that survives a sloped ground ------
3004
+ # `fall_z`, when the env supplies it (TASKWALK_FALL_FOOT_GEOM), is the lowest point of the foot's
3005
+ # CONTACT SPHERES -- calcanei and toes alike. Without it this falls back to the calcaneus body
3006
+ # ORIGINS, which sit 25-39 mm above the true contact and ignore the toes entirely; see the note in
3007
+ # task_walk_env._tw_setup. Default is the fallback, so every earlier run is bit-identical.
3008
+ foot_z = fall_z if fall_z is not None else torch.minimum(foot_pos[0][2], foot_pos[1][2])
3009
+ h_com = com[2] - foot_z
3010
+ # per-env threshold when the margin couples it to the target; the comparison broadcasts either way
3011
+ thr = self.fall_h
3012
+ fell = (q[2] < self.fall_root_h) if self.fall_root_h > 0.0 else (h_com < thr)
3013
+ if self.fall_nonfoot: # TASKWALK_FALL_NONFOOT: a non-foot body on the floor (the D16 law's pairs, env14)
3014
+ nf = getattr(self.env, "_tw_nonfoot_term", None)
3015
+ assert nf is not None, "TASKWALK_FALL_NONFOOT: env14's contact read is not installed (E0_ENV14_KINLATCH, env14.install_from_env)"
3016
+ fell = fell | nf()
3017
+ self.last_fall = fell.to(q.dtype) # the env terminates on this, making the penalty one-time
3018
+ r_fall = self.last_fall
3019
+
3020
+ # --- target COM height: a cost, zero when the body sits on its commanded height -----------------
3021
+ r_pelvis_height = torch.zeros_like(r_speed_track)
3022
+
3023
+ # --- COM floor (see __init__): the fall condition with a gradient ------------------------------
3024
+ if self.w_com_floor != 0.0:
3025
+ assert fall_z is not None, ("TASKWALK_W_COM_FLOOR needs TASKWALK_FALL_FOOT_GEOM=1: the calcaneus-origin "
3026
+ "proxy reads a body on its toes as fallen")
3027
+ r_com_floor = (self.com_floor_h - h_com).clamp_min(0.0) ** 2
3028
+ else:
3029
+ r_com_floor = torch.zeros_like(r_speed_track)
3030
+
3031
+ # --- eq.(3) terms absent from the released code (weight 0 unless asked for) --------------------
3032
+ if self.w_hip_adduction != 0.0:
3033
+ add_r, add_l = self._hip_adduction(q)
3034
+ r_hip_adduction = add_r ** 2 + add_l ** 2
3035
+ else:
3036
+ r_hip_adduction = torch.zeros_like(r_speed_track)
3037
+ if self.w_hip_rotation != 0.0:
3038
+ rot_r, rot_l = self._hip_rotation(q)
3039
+ if self.hip_rotation_band > 0.0:
3040
+ rot_r = (rot_r.abs() - self.hip_rotation_band).clamp_min(0.0)
3041
+ rot_l = (rot_l.abs() - self.hip_rotation_band).clamp_min(0.0)
3042
+ r_hip_rotation = rot_r ** 2 + rot_l ** 2
3043
+ else:
3044
+ r_hip_rotation = torch.zeros_like(r_speed_track)
3045
+ if self.w_action_rate != 0.0:
3046
+ # MEAN, not sum: the authors smooth two exoskeleton torque commands, and carrying their weight
3047
+ # onto a sum over 290 muscle excitations made this term 41.7 -- four times the maximum velocity
3048
+ # reward. Exactly the mistake the effort term already had.
3049
+ d_u = self._rate("u", excitation, dt) * dt
3050
+ r_action_rate = (d_u ** 2).mean(dim=0)
3051
+ else:
3052
+ r_action_rate = torch.zeros_like(r_speed_track)
3053
+ r_exc_rise = torch.zeros_like(r_speed_track)
3054
+ if self.w_knee_load != 0.0:
3055
+ assert foot_grf is not None and lce is not None and lce_dot is not None, (
3056
+ "TASKWALK_W_KNEE_LOAD needs the foot GRF and the fibre length/velocity")
3057
+ # TIBIOFEMORAL COMPRESSION: the tendon force of the muscles that SPAN the knee, plus the
3058
+ # ipsilateral ground reaction, in bodyweights. Choi/Ton/Gill/Song 2026 Eq (2) penalises
3059
+ # (F_knee/(m*g))^2, F_knee being "the compressive component of the tibiofemoral joint contact
3060
+ # force aligned with the tibial axis, arising from intersegmental dynamics and muscle forces".
3061
+ #
3062
+ # THE FORCE IS RECOMPUTED IN-GRAPH, not read from the coupling stage's side channel. The side
3063
+ # channel is `.detach()`ed by construction, so a term built on it has NO path to the action
3064
+ # and contributes exactly zero to a pathwise learner at any weight -- measured, this term read
3065
+ # requires_grad=False for its whole existence. The metabolic term hit the same wall and was
3066
+ # fixed the same way; this reuses that route (geyer_curves_torch, gated against the engine
3067
+ # kernel by test_geyer_curves_torch) rather than adding an engine readout.
3068
+ #
3069
+ # THE GROUND REACTION STAYS DETACHED, deliberately. A gradient path through it would teach
3070
+ # the policy to cut knee load by UNLOADING THE FOOT -- shorter stance, shorter steps, which is
3071
+ # the pathology Choi et al. and Miller 2013 already report from this term. Inside the square
3072
+ # it still scales the gradient correctly: d/dx (F_m + F_g)^2 = 2(F_m + F_g) dF_m/dx. It is
3073
+ # not posture-free, though: measured over 785 strides, a straighter landing knee raises the
3074
+ # peak GRF 16% and its rise rate 48%, so this closes a real route and is a trade, not a free
3075
+ # choice.
3076
+ #
3077
+ # WHAT IS STILL A PROXY. The tensions are summed unprojected (the exact version needs the RNE
3078
+ # joint reaction, an engine readout, still deferred); the ground reaction is the VERTICAL
3079
+ # component rather than the tibial-axis one; shank and foot inertia are absent; and muscles
3080
+ # that do not span the knee are omitted, which Sasaki & Neptune 2010 show contribute through
3081
+ # the ground reaction. Measured against Kutzner et al. 2010's in-vivo 2.61 BW walking peak,
3082
+ # this proxy reads ~2-4x high, part of which is real: our F_max are Handsfield/Rajagopal and
3083
+ # run 1.51x the Geyer model's over these five muscles (docs/logs/model-registry.md).
3084
+ #
3085
+ # NO STANCE GATE, matching Eq (2), which has none. It therefore also charges swing, where
3086
+ # there is no tibiofemoral contact and the measured muscle sum is still 2.58 BW over half the
3087
+ # leg-frames; that is a known and accepted departure from the physics, taken to keep the
3088
+ # published form intact.
3089
+ f_mtu, _ = _mtu_forces(lce, lce_dot, a_mean, self._met["curve"])
3090
+ musc = torch.stack([f_mtu[self.knee_mus[0]].sum(0),
3091
+ f_mtu[self.knee_mus[1]].sum(0)]) / self.bw_n
3092
+ load = musc.to(foot_grf.dtype) + foot_grf
3093
+ # CAPPED: the estimate is heavy-tailed (measured in stance p95 10.1 BW, max 68.5). A bare
3094
+ # square makes one frame 4600 against a velocity reward near 9; the paper's trial-level
3095
+ # CMA-ES cost never feels that and a per-step pathwise gradient does. The cap is the one
3096
+ # deviation from Eq (2) kept on purpose, and at 15 BW it clips under 5% of stance frames.
3097
+ if self.log_terms:
3098
+ self.last_knee_load = load.detach() # (2,n) BW, for the probes
3099
+ # the exact inputs the in-graph force used, so a probe can re-derive it and
3100
+ # compare against the engine on the state the policy is really in
3101
+ self.last_force_in = (lce.detach(), lce_dot.detach(), a_mean.detach(), f_mtu.detach())
3102
+ over = (load - self.knee_load_min_bw).clamp(min=0.0, max=self.knee_load_cap_bw)
3103
+ # `** self.knee_load_exp` rather than `** 2`: exp = 2.0 is the shipped default and gives the
3104
+ # identical expression. A NON-INTEGER exponent on an exactly-zero `over` has an infinite
3105
+ # derivative, which is most frames -- the clamp puts the whole sub-threshold gait at 0 --
3106
+ # so offset the base by a tiny epsilon under the power and subtract it back. At exp = 2 the
3107
+ # epsilon changes the value by 1e-24 and the gradient not at all.
3108
+ eps = 1e-12
3109
+ per_leg = (over + eps) ** self.knee_load_exp - eps ** self.knee_load_exp
3110
+ r_knee_load = per_leg.sum(dim=0)
3111
+ else:
3112
+ r_knee_load = torch.zeros_like(r_speed_track)
3113
+
3114
+ r_stance_knee_angle = torch.zeros_like(r_speed_track)
3115
+
3116
+ if foot_h2 is not None: # TASKWALK_W_STANCE_KNEE_PROX (see __init__); the env passes h when the weight is live
3117
+ _kr = self.knee_sign * torch.rad2deg(q[self.i_knee_r]); _kl = self.knee_sign * torch.rad2deg(q[self.i_knee_l])
3118
+ _px = torch.exp(-foot_h2.clamp_min(0.0) / self.skp_h) # (2, n): 1 on the floor, e^-1 at H
3119
+ r_stance_knee_prox = (_px[0] * (_kr - self.skp_k).clamp_min(0.0) + _px[1] * (_kl - self.skp_k).clamp_min(0.0)) / 10.0
3120
+ else:
3121
+ r_stance_knee_prox = torch.zeros_like(r_speed_track)
3122
+
3123
+ r_stance_ankle = torch.zeros_like(r_speed_track)
3124
+
3125
+ r_touchdown_knee = torch.zeros_like(r_speed_track)
3126
+
3127
+ r_track_pose = r_track_pose_r = torch.zeros_like(r_speed_track)
3128
+
3129
+ r_trunk_pitch = torch.zeros_like(r_speed_track)
3130
+
3131
+ r_step_width = torch.zeros_like(r_speed_track)
3132
+
3133
+ # the speed multiplier: the scalar w_speed_max, or with command bins each env's own bin's multiplier, (n_env,)
3134
+ w_sm = self._speed_p.lam_env(torch.broadcast_to(self.v_tgt, v_speed.shape)) if isinstance(self._speed_p, BinnedSpeedPController) \
3135
+ else self._w("w_speed_max")
3136
+ r_sm = w_sm * v_speed
3137
+ if self.keep_parts:
3138
+ # TASKWALK_LOG_TERMINALS (task_walk_env's terminal census, 11-23): the step's speed parts, DETACHED references (no kernel,
3139
+ # no host sync); the census sums them in its own device buffers
3140
+ self._last_rst = (self.w_speed_track * r_speed_track).detach()
3141
+ self._last_rsm = r_sm.detach()
3142
+ if self.log_terms:
3143
+ # DIAGNOSTIC ONLY: seven host syncs per step. Detached so it neither warns nor pins the graph.
3144
+ # Leave it OFF in a run whose throughput matters -- it exists to read the term BALANCE, which
3145
+ # is how the effort bug (836 against a velocity term of 1.6) was found.
3146
+ # The WEIGHTED term tensors, still attached, so a probe can autograd.grad each one against
3147
+ # the action and report a GRADIENT per term instead of a value. Reporting only the value is
3148
+ # what let a constant-dominated term look healthy: a large mean says nothing about what the
3149
+ # pathwise learner can move, and this repo has twice recorded that a term measuring ~0 at the
3150
+ # optimum was load-bearing. Cheap -- these are references, not copies.
3151
+ self.last_terms_t = {
3152
+ "speed_max": r_sm, "mid_lane": self.w_mid_lane * r_mid_lane,
3153
+ "root_up": self.w_root_up * r_root_up, "root_heading": self.w_root_heading * r_root_heading,
3154
+ "speed_track": self.w_speed_track * r_speed_track, "activation": self.w_activation * r_activation, "joint_limit": self.w_joint_limit * r_joint_limit, "joint_limit_step": self.w_joint_limit_step * r_joint_limit_step,
3155
+ "metabolic_rate": self.w_metabolic_rate * r_met, "metabolic_sq": self.w_metabolic_sq * r_met_sq, "fall_penalty": self.w_fall_penalty * r_fall,
3156
+ "hip_adduction": self.w_hip_adduction * r_hip_adduction, "hip_rotation": self.w_hip_rotation * r_hip_rotation, "action_rate": self.w_action_rate * r_action_rate, "exc_rise": self.w_exc_rise * r_exc_rise, "active_sat": self.w_active_sat * r_active_sat, "stance_knee_prox": self.w_stance_knee_prox * r_stance_knee_prox, "pelvis_height": self.w_pelvis_height * r_pelvis_height,
3157
+ "knee_load": self.w_knee_load * r_knee_load, "stance_knee_angle": self.w_stance_knee_angle * r_stance_knee_angle, "touchdown_knee": self.w_touchdown_knee * r_touchdown_knee, "stance_ankle": self.w_stance_ankle * r_stance_ankle,
3158
+ "trunk_pitch": self.w_trunk_pitch * r_trunk_pitch, "step_width": self.w_step_width * r_step_width,
3159
+ "track_pose": self.w_track_pose * r_track_pose, "track_pose_r": self.w_track_pose_r * r_track_pose_r,
3160
+ "grf_rate": self.w_grf_rate * r_grf_rate, "grf_peak": self.w_grf_peak * r_grf_peak,
3161
+ "brake": self.w_brake * r_brake, "touchdown": self.w_touchdown * r_touchdown,
3162
+ "com_pos_work": self.w_com_pos_work * r_com_pos_work,
3163
+ "head_accel": self.w_head_accel * r_head_accel, "com_floor": self.w_com_floor * r_com_floor,
3164
+ "limit_torque": self.w_limit_torque * r_limit_torque, "limit_power": self.w_limit_power * r_limit_power,
3165
+ "toe_spring": self.w_toe_spring * r_toe_spring, "state_prior": self.w_state_prior * r_state_prior,
3166
+ "phase_prior": self.w_phase_prior * r_phase_prior}
3167
+ with torch.no_grad():
3168
+ self.last_terms = {
3169
+ "speed_max": float(r_sm.mean()),
3170
+ "mid_lane": float(r_mid_lane.mean()) * self.w_mid_lane,
3171
+ "root_up": float(r_root_up.mean()) * self.w_root_up,
3172
+ "root_heading": float(r_root_heading.mean()) * self.w_root_heading,
3173
+ "speed_track": float(r_speed_track.mean()) * self.w_speed_track, "activation": float(r_activation.mean()) * self.w_activation,
3174
+ "metabolic_rate": float(r_met.mean()) * self.w_metabolic_rate,
3175
+ "metabolic_sq": float(r_met_sq.mean()) * self.w_metabolic_sq,
3176
+ "joint_limit": float(r_joint_limit.mean()) * self.w_joint_limit, "joint_limit_step": float(r_joint_limit_step.mean()) * self.w_joint_limit_step, "fall_penalty": float(r_fall.mean()) * self.w_fall_penalty,
3177
+ "hip_adduction": float(r_hip_adduction.mean()) * self.w_hip_adduction, "hip_rotation": float(r_hip_rotation.mean()) * self.w_hip_rotation, "action_rate": float(r_action_rate.mean()) * self.w_action_rate,
3178
+ "exc_rise": float(r_exc_rise.mean()) * self.w_exc_rise, "active_sat": float(r_active_sat.mean()) * self.w_active_sat, "stance_knee_prox": float(r_stance_knee_prox.mean()) * self.w_stance_knee_prox,
3179
+ "knee_load": float(r_knee_load.mean()) * self.w_knee_load, "knee_load_max": float(r_knee_load.max()) * self.w_knee_load,
3180
+ "pelvis_height": float(r_pelvis_height.mean()) * self.w_pelvis_height,
3181
+ "stance_knee_angle": float(r_stance_knee_angle.mean()) * self.w_stance_knee_angle,
3182
+ "touchdown_knee": float(r_touchdown_knee.mean()) * self.w_touchdown_knee,
3183
+ "trunk_pitch": float(r_trunk_pitch.mean()) * self.w_trunk_pitch, "step_width": float(r_step_width.mean()) * self.w_step_width,
3184
+ "track_pose": float(r_track_pose.mean()) * self.w_track_pose,
3185
+ "track_pose_r": float(r_track_pose_r.mean()) * self.w_track_pose_r,
3186
+ "stance_ankle": float(r_stance_ankle.mean()) * self.w_stance_ankle,
3187
+ "grf_rate": float(r_grf_rate.mean()) * self.w_grf_rate,
3188
+ "grf_peak": float(r_grf_peak.mean()) * self.w_grf_peak,
3189
+ "brake": float(r_brake.mean()) * self.w_brake,
3190
+ "com_pos_work": float(r_com_pos_work.mean()) * self.w_com_pos_work,
3191
+ "touchdown": float(r_touchdown.mean()) * self.w_touchdown,
3192
+ "head_accel": float(r_head_accel.mean()) * self.w_head_accel,
3193
+ "com_floor": float(r_com_floor.mean()) * self.w_com_floor,
3194
+ "limit_torque": float(r_limit_torque.mean()) * self.w_limit_torque,
3195
+ "limit_power": float(r_limit_power.mean()) * self.w_limit_power,
3196
+ "toe_spring": float(r_toe_spring.mean()) * self.w_toe_spring,
3197
+ "state_prior": float(r_state_prior.mean()) * self.w_state_prior,
3198
+ "phase_prior": float(r_phase_prior.mean()) * self.w_phase_prior}
3199
+ # the muscle price alone, IN THE GRAPH, for TASKWALK_LLC_EFFORT (task_walk_env): DeepLoco's reward replaces r_total below
3200
+ # but keeps this part of it (docs-dev/deeploco/20261026_1000_llc_effort)
3201
+ self.last_effort_t = (self.w_activation * r_activation + self._w("w_metabolic_rate") * r_met + self.w_metabolic_sq * r_met_sq)
3202
+ # every non-velocity term is a COST here, so they subtract (the authors' yaml carries the
3203
+ # minus in the weight; keeping the sign at the sum makes the weights readable as magnitudes)
3204
+ r_total = (self.w_alive_bonus * (~self.last_fall.bool()).to(r_speed_track.dtype)
3205
+ + r_sm
3206
+ + self.w_mid_lane * r_mid_lane
3207
+ + self.w_root_up * r_root_up + self.w_root_heading * r_root_heading + self.w_track_pose_r * r_track_pose_r
3208
+ + self.w_speed_track * r_speed_track - self.w_activation * r_activation - self._w("w_joint_limit") * r_joint_limit - self.w_joint_limit_step * r_joint_limit_step - self.w_action_rate * r_action_rate
3209
+ - self.w_exc_rise * r_exc_rise - self._w("w_active_sat") * r_active_sat - self._w("w_stance_knee_prox") * r_stance_knee_prox
3210
+ - self._w("w_metabolic_rate") * r_met - self.w_metabolic_sq * r_met_sq
3211
+ - self.w_fall_penalty * r_fall - self.w_knee_load * r_knee_load - self.w_hip_adduction * r_hip_adduction - self._w("w_hip_rotation") * r_hip_rotation
3212
+ - self.w_pelvis_height * r_pelvis_height - self.w_stance_knee_angle * r_stance_knee_angle - self.w_touchdown_knee * r_touchdown_knee - self.w_stance_ankle * r_stance_ankle
3213
+ - self.w_trunk_pitch * r_trunk_pitch - self.w_step_width * r_step_width - self.w_track_pose * r_track_pose
3214
+ - self.w_com_floor * r_com_floor
3215
+ - self.w_grf_rate * r_grf_rate - self.w_grf_peak * r_grf_peak - self._w("w_head_accel") * r_head_accel
3216
+ - self.w_brake * r_brake - self.w_touchdown * r_touchdown - self.w_com_pos_work * r_com_pos_work
3217
+ - self._w("w_limit_torque") * r_limit_torque - self.w_limit_power * r_limit_power
3218
+ - self.w_toe_spring * r_toe_spring - self.w_state_prior * r_state_prior
3219
+ - self.w_phase_prior * r_phase_prior)
3220
+ if self._speed_p is not None:
3221
+ # AFTER the total: this step was paid with the window's lambda; the new one applies from the next step
3222
+ with torch.no_grad():
3223
+ # Under a commanded heading the controller regulates SPEED, the horizontal COM speed, and the reward still pays
3224
+ # progress ALONG the command at its rate. Fed the command-frame speed it read every turn's lag as a speed deficit:
3225
+ # the frozen walker (straight ahead under a wandering command) averaged 0.04-0.2 m/s in the command frame, the
3226
+ # multipliers went to 35-60 against the walker's ~5, and the sprint term took over the reward (steering S1,
3227
+ # docs-dev/deeploco/20261020_2000_s1_heading).
3228
+ v_obs = torch.hypot(v_com[0], v_com[1]) if self.heading_cmd is not None else v_speed
3229
+ self._speed_p.observe(v_obs.detach(), torch.broadcast_to(self.v_tgt, v_speed.shape).to(v_speed.dtype),
3230
+ (1.0 - self.last_fall).to(v_speed.dtype))
3231
+ if self._speed_p.due() and isinstance(self._speed_p, BinnedSpeedPController):
3232
+ lam, v_mean, c_mean, n_alive = self._speed_p.update()
3233
+ if self._speed_p.n_updates % 10 == 1:
3234
+ print(f"[taskwalk] speed P: update {self._speed_p.n_updates} per bin (cmd v_mean -> multiplier): " + "; ".join(
3235
+ f"{c:.2f} {v:.3f} -> {l:.3f}" if n > 0 else "empty" for l, v, c, n in zip(lam, v_mean, c_mean, n_alive)),
3236
+ flush=True)
3237
+ elif self._speed_p.due() and not self._speed_p_defer:
3238
+ self._speed_p_apply()
3239
+ return r_total
3240
+
3241
+ # ------------------------------------------------------------------ TW1 S2a: the capture hazards (off by default)
3242
+ # w_metabolic_rate (11-14, for TASKWALK_METABOLIC_PER_DIST's ramped cell): a scheduled metabolic weight under --tw1-capture was
3243
+ # refused here (no tensor route). It is routed only when scheduled; unscheduled, _w() returns the float (bit-identical).
3244
+ TENSOR_WEIGHTS = ("w_speed_max", "w_head_accel", "w_hip_rotation", "w_joint_limit", "w_limit_torque", "w_active_sat", "w_stance_knee_prox",
3245
+ "w_metabolic_rate")
3246
+
3247
+ def _w(self, name):
3248
+ """a weight for the reward's ARITHMETIC: its 0-d device tensor when enable_tensor_weights() named it, else the Python float"""
3249
+ return self._wt[name] if self._wt is not None and name in self._wt else getattr(self, name)
3250
+
3251
+ def enable_tensor_weights(self, names, device):
3252
+ """the named weights' arithmetic through 0-d float32 device tensors (set_weight writes them). A float32 0-d tensor holding a
3253
+ Python float's float32 rounding multiplies a float32 tensor exactly as the Python scalar does (the kernels cast the scalar to
3254
+ float), so the reward is bitwise the same. Only the names TENSOR_WEIGHTS routes through _w() are allowed."""
3255
+ assert set(names) <= set(self.TENSOR_WEIGHTS), f"no tensor route for {sorted(set(names) - set(self.TENSOR_WEIGHTS))}"
3256
+ assert not isinstance(self._speed_p, BinnedSpeedPController), "the binned controller's multipliers are not routed"
3257
+ # the metabolic rate is COMPUTED only while its weight is non-zero (the step's `if self.w_metabolic_rate != 0.0`), and a captured
3258
+ # window bakes that branch: a routed schedule that starts at 0 would replay the skipped branch whatever the ramp does
3259
+ assert "w_metabolic_rate" not in names or self.w_metabolic_rate != 0.0, \
3260
+ "a scheduled TASKWALK_W_METABOLIC_RATE under capture must start non-zero (the term's branch is baked into the window)"
3261
+ self._wt = {n: torch.tensor(float(getattr(self, n)), dtype=torch.float32, device=device) for n in names}
3262
+
3263
+ def set_weight(self, name, value):
3264
+ """a weight's new value: the Python float, and its tensor in place when it has one"""
3265
+ setattr(self, name, value)
3266
+ if self._wt is not None and name in self._wt and not self._wt_frozen:
3267
+ # a NEW tensor, not fill_: the previous step's w * r saved the old one for the backward (an in-place write breaks it)
3268
+ self._wt[name] = torch.tensor(float(value), dtype=torch.float32, device=self._wt[name].device)
3269
+
3270
+ def defer_speed_p(self):
3271
+ """the speed P update leaves the step: speed_p_window_end() runs it at the window boundary. It already applies from the next
3272
+ step, so with the update every H steps and the calls counted from construction it is the same update at the same step."""
3273
+ assert isinstance(self._speed_p, SpeedPController) and not isinstance(self._speed_p, BinnedSpeedPController)
3274
+ self._speed_p_defer = True
3275
+
3276
+ def speed_p_window_end(self):
3277
+ """the deferred speed P update (a no-op when it is not due), with the in-step update's print"""
3278
+ assert self._speed_p_defer
3279
+ if self._speed_p.due():
3280
+ with torch.no_grad():
3281
+ self._speed_p_apply()
3282
+
3283
+ def _cmd_schedule_done(self):
3284
+ """the env's commanded-speed schedule is COMPLETE (or there is none, a fixed command): TASKWALK_V_LO / _HI_END reached, read from the
3285
+ schedule itself (env._train_steps against each schedule's AFTER + STEPS), the same host integers the schedule advances by; B-AW's
3286
+ hold-only test (SpeedPController.update(hold=))"""
3287
+ e = self.env
3288
+ done = True
3289
+ for k in ("lo", "hi"):
3290
+ if getattr(e, f"_tw_v_{k}_end", None) is not None:
3291
+ done = done and int(e._train_steps) >= int(getattr(e, f"_tw_v_{k}_after")) + int(getattr(e, f"_tw_v_{k}_steps"))
3292
+ return done
3293
+
3294
+ def _speed_p_apply(self):
3295
+ lam, v_mean, c_mean = (self._speed_p.update(hold=self._cmd_schedule_done()) if getattr(self._speed_p, "i_hold", False)
3296
+ else self._speed_p.update())
3297
+ self.set_weight("w_speed_max", lam)
3298
+ if self._speed_p.n_updates % 10 == 1:
3299
+ print(f"[taskwalk] speed P: update {self._speed_p.n_updates} v_mean {v_mean:.3f} cmd {c_mean:.3f} "
3300
+ f"-> w_speed_max {lam:.3f}" + (f" (integral lambda_I {self._speed_p.lam_i:.3f})" if self._speed_p.eta > 0.0 else ""), flush=True)