nablaengine 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,306 @@
1
+ """BAM, Rhoban's servo model (Better Actuator Models, model M6), for the XL330 servo: the engine-independent part."""
2
+
3
+ import copy
4
+ import warnings
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ PARAMS_DIR = Path(__file__).resolve().parent / "bam_params"
12
+ M6_KEYS = ("kt", "R", "armature", "friction_base", "friction_stribeck", "load_friction_motor",
13
+ "load_friction_external", "load_friction_motor_stribeck", "load_friction_external_stribeck",
14
+ "load_friction_motor_quad", "load_friction_external_quad", "dtheta_stribeck", "alpha", "friction_viscous")
15
+ ERROR_GAIN = {"xl330": (4096 / (2 * math.pi)) / (256 * 885)}
16
+ FIRMWARE_MAX_CURRENT = {"xl330": 1.75}
17
+ FRICTION_SOLREF = (0.01, 1.0)
18
+ FRICTION_SOLIMP = (0.99, 0.9999, 0.001, 0.5, 2.0)
19
+
20
+
21
+ def load_params(params="xl330/m6"):
22
+ """The M6 parameter dict of a BAM parameter set: "xl330/m6" (bundled) or a path to a BAM json (an XL330 M6 set:
23
+ "actuator": "xl330", "model": "m6"). ValueError for another servo or model."""
24
+ p = Path(params)
25
+ path = PARAMS_DIR / f"{params}.json" if not p.suffix and (PARAMS_DIR / f"{params}.json").exists() else p
26
+ if not path.exists():
27
+ raise ValueError(f"BAM parameters {params!r}: not a bundled set ('xl330/m6') or an existing json file")
28
+ d = json.loads(path.read_text())
29
+ if d.get("model") != "m6" or d.get("actuator") != "xl330":
30
+ raise ValueError(f"BAM parameters {params!r}: an XL330 M6 set is supported (actuator 'xl330', model 'm6'), "
31
+ f"not actuator {d.get('actuator')!r} model {d.get('model')!r}")
32
+ miss = [k for k in M6_KEYS if k not in d]
33
+ if miss:
34
+ raise ValueError(f"BAM parameters {params!r}: missing {miss}")
35
+ out = {k: float(d[k]) for k in M6_KEYS}
36
+ out["actuator"] = d["actuator"]
37
+ return out
38
+
39
+
40
+ def max_current(bam, p=None):
41
+ """The firmware current limit of bam (a nablaengine.actuators.Bam) in A, None when switched off."""
42
+ mc = bam.max_current
43
+ if mc is None:
44
+ return None
45
+ if mc == "firmware":
46
+ p = p or load_params(bam.params)
47
+ return FIRMWARE_MAX_CURRENT[p["actuator"]]
48
+ mc = float(mc)
49
+ if not (mc > 0 and math.isfinite(mc)):
50
+ raise ValueError(f"Bam(max_current={bam.max_current!r}): a positive current in A, 'firmware' or None")
51
+ return mc
52
+
53
+
54
+ def servo(bam, p=None):
55
+ """The engine model's servo values of bam at its nominal voltage: kp, frclim (the force limit at duty 1), damping
56
+ (KD + friction_viscous), kd (KD = kt^2 / R), armature, frictionloss (friction_base), ilim (kt I_max, the current
57
+ limit's torque; None when off), vin_nom, vin_min."""
58
+ p = p or load_params(bam.params)
59
+ vn = float(bam.vin_nom)
60
+ imax = max_current(bam, p)
61
+ return dict(kp=p["kt"] * vn * ERROR_GAIN[p["actuator"]] * float(bam.kp_fw) / p["R"], frclim=p["kt"] * vn / p["R"],
62
+ damping=p["kt"] ** 2 / p["R"] + p["friction_viscous"], kd=p["kt"] ** 2 / p["R"],
63
+ armature=p["armature"], frictionloss=p["friction_base"],
64
+ ilim=None if imax is None else p["kt"] * imax, vin_nom=vn, vin_min=float(bam.vin_min))
65
+
66
+
67
+ def act_words(nv):
68
+ """Floats of a world's BAM state row: tau (nv), ext (nv), vin0, drop."""
69
+ return 2 * int(nv) + 2
70
+
71
+
72
+ def layout(nv):
73
+ """{name: (offset, width)} of a world's BAM state row."""
74
+ nv = int(nv)
75
+ return {"tau": (0, nv), "ext": (nv, nv), "vin0": (2 * nv, 1), "drop": (2 * nv + 1, 1)}
76
+
77
+
78
+ def initial_state(nv, batch, vin0=7.4, drop=0.0, tau=None, ext=None):
79
+ """A (batch, act_words(nv)) float32 NumPy array of BAM state rows: zero torques (or tau / ext, (batch, nv) or
80
+ (nv,)), the supply voltage vin0 (V) and the drop gain drop (V per N m of summed |tau|), scalars or (batch,)."""
81
+ nv, B = int(nv), int(batch)
82
+ a = np.zeros((B, act_words(nv)), np.float32)
83
+ if tau is not None:
84
+ a[:, :nv] = tau
85
+ if ext is not None:
86
+ a[:, nv:2 * nv] = ext
87
+ a[:, 2 * nv] = vin0
88
+ a[:, 2 * nv + 1] = drop
89
+ return a
90
+
91
+
92
+ def _servo_ids(m):
93
+ import mujoco
94
+ act = np.arange(m.nu)
95
+ if m.nu and (m.actuator_trntype != mujoco.mjtTrn.mjTRN_JOINT).any():
96
+ raise ValueError("BAM: every actuator must drive a joint (joint transmission)")
97
+ jnt = m.actuator_trnid[:, 0].copy()
98
+ return act, jnt, m.jnt_dofadr[jnt].copy(), m.jnt_qposadr[jnt].copy()
99
+
100
+
101
+ def check_model(m, bam):
102
+ """Raise ValueError unless the MjModel m fits BAM's engine form (prepare's output): one position servo per hinge
103
+ after a free root (in dof order) without kv, the servo values of bam (kp, the joints' force limit, damping,
104
+ armature), a positive frictionloss on every servo dof, the friction rows' impedance, no joint stiffness, the
105
+ pyramidal cone, no condim-4 pairs."""
106
+ import mujoco
107
+ sv, bad = servo(bam), []
108
+ if m.njnt < 1 or m.jnt_type[0] != mujoco.mjtJoint.mjJNT_FREE or m.nu != m.nv - 6:
109
+ bad.append(f"a free root and one servo per hinge (nu = {m.nu}, nv - 6 = {m.nv - 6})")
110
+ else:
111
+ _, jnt, dof, _ = _servo_ids(m)
112
+ if not (dof == np.arange(6, m.nv)).all() or (m.jnt_type[jnt] != mujoco.mjtJoint.mjJNT_HINGE).any():
113
+ bad.append("the actuators must drive the hinges in dof order")
114
+ else:
115
+ close = lambda a, b: np.allclose(a, b, rtol=1e-6, atol=0)
116
+ if not close(m.actuator_gainprm[:, 0], sv["kp"]) or not close(-m.actuator_biasprm[:, 1], sv["kp"]):
117
+ bad.append(f"actuator kp is not BAM's {sv['kp']:.6g} (gainprm[0] = -biasprm[1])")
118
+ if (m.actuator_biasprm[:, 2] != 0).any():
119
+ bad.append("actuator kv != 0: the back-EMF belongs to dof_damping")
120
+ if (m.actuator_forcelimited != 0).any():
121
+ bad.append("actuator forcerange: BAM's limit is the joints' jnt_actfrcrange")
122
+ if not (m.jnt_actfrclimited[jnt] != 0).all() or not close(m.jnt_actfrcrange[jnt, 1], sv["frclim"]) \
123
+ or not close(-m.jnt_actfrcrange[jnt, 0], sv["frclim"]):
124
+ bad.append(f"jnt_actfrcrange is not +-{sv['frclim']:.6g} (kt vin_nom / R)")
125
+ if not close(m.dof_damping[6:], sv["damping"]):
126
+ bad.append(f"dof_damping[6:] is not KD + friction_viscous = {sv['damping']:.6g}")
127
+ if not close(m.dof_armature[6:], sv["armature"]):
128
+ bad.append(f"dof_armature[6:] is not the servo's {sv['armature']:.6g}")
129
+ if not (m.dof_frictionloss[6:] > 0).all():
130
+ bad.append("dof_frictionloss[6:] has zeros: every servo dof needs its friction row")
131
+ if (m.jnt_stiffness != 0).any():
132
+ bad.append("joint stiffness")
133
+ if m.nv and (not np.allclose(m.dof_solref, FRICTION_SOLREF) or not np.allclose(m.dof_solimp, FRICTION_SOLIMP)):
134
+ bad.append(f"the friction rows' impedance (dof_solref {FRICTION_SOLREF}, dof_solimp {FRICTION_SOLIMP})")
135
+ if m.opt.cone != mujoco.mjtCone.mjCONE_PYRAMIDAL:
136
+ bad.append("the elliptic friction cone (not with BAM yet)")
137
+ if m.npair and (m.pair_dim > 3).any():
138
+ bad.append("condim-4 contact pairs (not with BAM yet)")
139
+ if bad:
140
+ raise ValueError("BAM: the model does not fit the servo model's engine form (actuators.bam.prepare makes one "
141
+ "that does): " + "; ".join(bad))
142
+
143
+
144
+ def prepare(m, bam):
145
+ """A copy of the MjModel m with every actuator made an XL330 under bam (a nablaengine.actuators.Bam) in the
146
+ engine's form (the module docstring): position servos kp without kv or actuator force limit, the joints' force
147
+ limit +-frclim, BAM's damping, armature, frictionloss and friction-row impedance; mj_setConst then recomputes the
148
+ derived constants (the inverse weights). Idempotent. ValueError for a model whose actuators are not one per hinge
149
+ after a free root."""
150
+ import mujoco
151
+ sv = servo(bam)
152
+ m = copy.deepcopy(m)
153
+ if m.njnt < 1 or m.jnt_type[0] != mujoco.mjtJoint.mjJNT_FREE or m.nu != m.nv - 6:
154
+ raise ValueError(f"BAM: a free root and one actuator per hinge are needed (nu = {m.nu}, nv - 6 = {m.nv - 6})")
155
+ act, jnt, dof, _ = _servo_ids(m)
156
+ if not (dof == np.arange(6, m.nv)).all() or (m.jnt_type[jnt] != mujoco.mjtJoint.mjJNT_HINGE).any():
157
+ raise ValueError("BAM: the actuators must drive the hinges in dof order")
158
+ g, bp = m.actuator_gainprm[act, 0], m.actuator_biasprm[act]
159
+ other = (m.actuator_biastype[act] != mujoco.mjtBias.mjBIAS_AFFINE) | (bp[:, 1] != -g) | (g <= 0)
160
+ if other.any():
161
+ names = [mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_ACTUATOR, int(a)) or str(int(a)) for a in act[other]]
162
+ warnings.warn(f"BAM replaces {len(names)} actuator(s) that are not position servos (e.g. velocity servos or "
163
+ f"motors) with XL330 position servos: {', '.join(names[:8])}" + (" ..." if len(names) > 8 else ""),
164
+ RuntimeWarning, stacklevel=2)
165
+ m.actuator_gaintype[act] = mujoco.mjtGain.mjGAIN_FIXED
166
+ m.actuator_biastype[act] = mujoco.mjtBias.mjBIAS_AFFINE
167
+ m.actuator_gainprm[act] = 0.0
168
+ m.actuator_biasprm[act] = 0.0
169
+ m.actuator_gainprm[act, 0] = sv["kp"]
170
+ m.actuator_biasprm[act, 1] = -sv["kp"]
171
+ m.actuator_dyntype[act] = mujoco.mjtDyn.mjDYN_NONE
172
+ m.actuator_gear[act] = 0.0
173
+ m.actuator_gear[act, 0] = 1.0
174
+ m.actuator_forcelimited[act] = 0
175
+ m.jnt_actfrclimited[jnt] = 1
176
+ m.jnt_actfrcrange[jnt] = (-sv["frclim"], sv["frclim"])
177
+ m.dof_damping[dof] = sv["damping"]
178
+ m.dof_armature[dof] = sv["armature"]
179
+ m.dof_frictionloss[dof] = sv["frictionloss"]
180
+ m.dof_solref[:] = FRICTION_SOLREF
181
+ m.dof_solimp[:] = FRICTION_SOLIMP
182
+ mujoco.mj_setConst(m, mujoco.MjData(m))
183
+ return m
184
+
185
+
186
+
187
+ def budget(tm, te, v, p):
188
+ """The M6 friction budget from the previous solve's motor torque tm, external torque te and the velocity v
189
+ (bam.mjlab.BamActuator._compute_friction_budget)."""
190
+ sb = np.exp(-np.abs(v / p["dtheta_stribeck"]) ** p["alpha"])
191
+ am, ae = np.abs(tm), np.abs(te)
192
+ return (p["friction_base"] + sb * p["friction_stribeck"]
193
+ + np.abs(te * p["load_friction_external"] - tm * p["load_friction_motor"])
194
+ + sb * np.abs(te * p["load_friction_external_stribeck"] - tm * p["load_friction_motor_stribeck"])
195
+ + sb * np.where(am > ae, p["load_friction_external_quad"] * ae ** 2, p["load_friction_motor_quad"] * am ** 2))
196
+
197
+
198
+ def force_window(sc, v, sv):
199
+ """(lo, hi) of the servo force after the current limit and the PWM limit, as one window (clamp(clamp(x, a, b),
200
+ c, d) = clamp(x, lo, hi)): the current window KD v +- ilim, then the voltage window +-sc frclim (applied last)."""
201
+ c = sc * sv["frclim"]
202
+ if sv["ilim"] is None:
203
+ return -c * np.ones_like(v), c * np.ones_like(v)
204
+ a, b = sv["kd"] * v - sv["ilim"], sv["kd"] * v + sv["ilim"]
205
+ lo, hi = np.maximum(a, -c), np.minimum(b, c)
206
+ lo = np.where(a > c, c, np.where(b < -c, -c, lo))
207
+ hi = np.where(a > c, c, np.where(b < -c, -c, hi))
208
+ return lo, hi
209
+
210
+
211
+ class Reference:
212
+ """The engine-form BAM servo model on MuJoCo C in float64, one world: the prepared model (prepare), every substep
213
+ the voltage scale on kp, the current and voltage windows in jnt_actfrcrange, the friction budget in
214
+ dof_frictionloss (from the previous solve's tau, ext), then mj_step; tau, ext from the solve. step(qpos, qvel,
215
+ warm, ctrl, act, substeps) runs one control step from a state and returns (qpos', qvel', warm', act')."""
216
+
217
+ def __init__(self, m, bam):
218
+ import mujoco
219
+ self.m = prepare(m, bam)
220
+ check_model(self.m, bam)
221
+ self.d = mujoco.MjData(self.m)
222
+ self.p, self.sv = load_params(bam.params), servo(bam)
223
+ self.act, self.jnt, self.dof, self.qadr = _servo_ids(self.m)
224
+ self.kp = self.m.actuator_gainprm[self.act, 0].copy()
225
+
226
+ def substep(self, ctrl, tau, ext, vin0, drop):
227
+ import mujoco
228
+ m, d, sv = self.m, self.d, self.sv
229
+ v = d.qvel[self.dof].copy()
230
+ sc = max(vin0 - drop * np.abs(tau).sum(), sv["vin_min"]) / sv["vin_nom"]
231
+ m.actuator_gainprm[self.act, 0] = self.kp * sc
232
+ m.actuator_biasprm[self.act, 1] = -self.kp * sc
233
+ lo, hi = force_window(sc, v, sv)
234
+ m.jnt_actfrcrange[self.jnt, 0], m.jnt_actfrcrange[self.jnt, 1] = lo, hi
235
+ m.dof_frictionloss[self.dof] = budget(tau, ext, v, self.p)
236
+ d.ctrl[:] = ctrl
237
+ mujoco.mj_step(m, d)
238
+ fr = np.zeros(m.nv)
239
+ for i in range(d.nefc):
240
+ if d.efc_type[i] == mujoco.mjtConstraint.mjCNSTR_FRICTION_DOF:
241
+ fr[d.efc_id[i]] += d.efc_force[i]
242
+ ext = (-d.qfrc_bias + d.qfrc_constraint - fr)[self.dof]
243
+ tau = d.qfrc_actuator[self.dof] - sv["kd"] * v
244
+ return tau, ext
245
+
246
+ def step(self, qpos, qvel, warm, ctrl, act, substeps):
247
+ """One control step of `substeps` substeps from (qpos, qvel, warm (qacc_warmstart), ctrl, act (a state row,
248
+ act_words(nv))): (qpos', qvel', warm', act') in float64."""
249
+ import mujoco
250
+ m, d, nv = self.m, self.d, self.m.nv
251
+ mujoco.mj_resetData(m, d)
252
+ d.qpos[:], d.qvel[:], d.qacc_warmstart[:] = qpos, qvel, warm
253
+ act = np.asarray(act, np.float64)
254
+ tau, ext = act[6:nv].copy(), act[nv + 6:2 * nv].copy()
255
+ vin0, drop = float(act[2 * nv]), float(act[2 * nv + 1])
256
+ for _ in range(int(substeps)):
257
+ tau, ext = self.substep(ctrl, tau, ext, vin0, drop)
258
+ out = np.zeros(act_words(nv))
259
+ out[6:nv], out[nv + 6:2 * nv], out[2 * nv], out[2 * nv + 1] = tau, ext, vin0, drop
260
+ return d.qpos.copy(), d.qvel.copy(), d.qacc_warmstart.copy(), out
261
+
262
+
263
+
264
+ def _f(x):
265
+ return repr(float(np.float32(x))) + "f"
266
+
267
+
268
+ def device_header(bam):
269
+ """The #defines and the friction budget's device functions of a BAM build (the M6 constants of bam's parameter
270
+ set, its nominal and minimum voltage, the current limit)."""
271
+ p, sv = load_params(bam.params), servo(bam)
272
+ ilim = sv["ilim"]
273
+ return f"""#define DK_BAM 1 // the BAM servo model in the kernels (nablaengine.actuators.bam)
274
+ #define BAM_STRIDE (2 * NV + 2) // a world's BAM state row: tau[NV], ext[NV], vin0, drop
275
+ #define BAM_VIN_NOM {_f(sv["vin_nom"])}
276
+ #define BAM_VIN_MIN {_f(sv["vin_min"])}
277
+ #define BAM_KD {_f(sv["kd"])} // back-EMF damping kt^2 / R
278
+ #define BAM_CURRENT_LIMIT {0 if ilim is None else 1} // the firmware current limit (window KD v +- BAM_ILIM)
279
+ #define BAM_ILIM {_f(0.0 if ilim is None else ilim)} // kt I_max
280
+ #define BAM_F_BASE {_f(p["friction_base"])}
281
+ #define BAM_F_STRIB {_f(p["friction_stribeck"])}
282
+ #define BAM_LF_MOT {_f(p["load_friction_motor"])}
283
+ #define BAM_LF_EXT {_f(p["load_friction_external"])}
284
+ #define BAM_LFS_MOT {_f(p["load_friction_motor_stribeck"])}
285
+ #define BAM_LFS_EXT {_f(p["load_friction_external_stribeck"])}
286
+ #define BAM_Q_MOT {_f(p["load_friction_motor_quad"])}
287
+ #define BAM_Q_EXT {_f(p["load_friction_external_quad"])}
288
+ #define BAM_RDTHETA {_f(1.0 / p["dtheta_stribeck"])}
289
+ #define BAM_ALPHA {_f(p["alpha"])}
290
+ #define BAM_SCALE(x) (bsc * (x))
291
+ #define BAM_FLOSS(s, i) (s).bfl[i]
292
+ // the M6 friction budget of a servo dof from the previous solve's motor torque tm and external torque te and the
293
+ // dof's velocity v (bam.mjlab.BamActuator._compute_friction_budget)
294
+ __device__ __forceinline__ float bam_budget(float tm, float te, float v) {{
295
+ const float sb = expf(-powf(fabsf(v) * BAM_RDTHETA, BAM_ALPHA));
296
+ const float am = fabsf(tm), ae = fabsf(te);
297
+ return BAM_F_BASE + sb * BAM_F_STRIB + fabsf(te * BAM_LF_EXT - tm * BAM_LF_MOT)
298
+ + sb * fabsf(te * BAM_LFS_EXT - tm * BAM_LFS_MOT) + sb * (am > ae ? BAM_Q_EXT * ae * ae : BAM_Q_MOT * am * am);
299
+ }}
300
+ """
301
+
302
+
303
+ def tape_words(nv):
304
+ """Words a BAM build adds to a substep's tape record: the scale, tau[NV], ext[NV], the servo forces[NV], the
305
+ current-limit flags[NV], to a multiple of 32."""
306
+ return -(-(1 + 4 * int(nv)) // 32) * 32
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,19 @@
1
+ {
2
+ "kt": 0.36601349688984386,
3
+ "R": 2.8113923539223227,
4
+ "armature": 0.0018077432831600838,
5
+ "q_offset": 0.0271132870444849,
6
+ "friction_base": 0.004771183165566,
7
+ "friction_stribeck": 0.004676345799486616,
8
+ "load_friction_motor": 0.2667860954283698,
9
+ "load_friction_external": 8.515871897059342e-06,
10
+ "load_friction_motor_stribeck": 1.0722918395099123e-05,
11
+ "load_friction_external_stribeck": 0.08077928978935671,
12
+ "load_friction_motor_quad": 0.009972471242139415,
13
+ "load_friction_external_quad": 0.004902565732332559,
14
+ "dtheta_stribeck": 2.890372094130307,
15
+ "alpha": 8.683259907618984,
16
+ "friction_viscous": 0.005359668274599504,
17
+ "model": "m6",
18
+ "actuator": "xl330"
19
+ }