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.
- nablaengine/__init__.py +4 -0
- nablaengine/_fixtures/README.md +19 -0
- nablaengine/_fixtures/data/mf_s0.npz +0 -0
- nablaengine/_fixtures/mjlab/LICENSE +27 -0
- nablaengine/_fixtures/mjlab/README.md +113 -0
- nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
- nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
- nablaengine/_optional.py +30 -0
- nablaengine/_paths.py +38 -0
- nablaengine/actuators/__init__.py +169 -0
- nablaengine/actuators/bam.py +306 -0
- nablaengine/actuators/bam_params/LICENSE +202 -0
- nablaengine/actuators/bam_params/xl330/m6.json +19 -0
- nablaengine/boxbox.py +259 -0
- nablaengine/ccd.py +1122 -0
- nablaengine/checks.py +376 -0
- nablaengine/cuda.py +483 -0
- nablaengine/dist_query.py +628 -0
- nablaengine/dual.py +223 -0
- nablaengine/dyn_query.py +685 -0
- nablaengine/engines.py +114 -0
- nablaengine/envs/__init__.py +24 -0
- nablaengine/envs/brax.py +165 -0
- nablaengine/envs/convert.py +771 -0
- nablaengine/envs/dmc.py +523 -0
- nablaengine/envs/env.py +233 -0
- nablaengine/envs/kin.py +371 -0
- nablaengine/envs/ops.py +134 -0
- nablaengine/envs/rewards.py +57 -0
- nablaengine/fixtures.py +243 -0
- nablaengine/forest_engine/__init__.py +0 -0
- nablaengine/forest_engine/adjoint.py +1726 -0
- nablaengine/forest_engine/adjoint_contact.py +493 -0
- nablaengine/forest_engine/bam_hooks.py +248 -0
- nablaengine/forest_engine/body_params.py +1007 -0
- nablaengine/forest_engine/capacity_diag.py +116 -0
- nablaengine/forest_engine/ccd_coop.py +250 -0
- nablaengine/forest_engine/chol_blk.py +80 -0
- nablaengine/forest_engine/contact_forces.py +142 -0
- nablaengine/forest_engine/contact_vjp.py +462 -0
- nablaengine/forest_engine/convex.py +1331 -0
- nablaengine/forest_engine/cylinder.py +73 -0
- nablaengine/forest_engine/dist_device.py +923 -0
- nablaengine/forest_engine/dyn_device.py +696 -0
- nablaengine/forest_engine/ellipsoid.py +179 -0
- nablaengine/forest_engine/elliptic.py +272 -0
- nablaengine/forest_engine/equality.py +842 -0
- nablaengine/forest_engine/floss.py +148 -0
- nablaengine/forest_engine/foot_offset.py +368 -0
- nablaengine/forest_engine/free_gyro.py +288 -0
- nablaengine/forest_engine/host.py +530 -0
- nablaengine/forest_engine/kdof64.py +127 -0
- nablaengine/forest_engine/kinematics.py +320 -0
- nablaengine/forest_engine/margin.py +167 -0
- nablaengine/forest_engine/margin_convex.py +326 -0
- nablaengine/forest_engine/midphase.py +439 -0
- nablaengine/forest_engine/model_hooks.py +913 -0
- nablaengine/forest_engine/motor_hooks.py +50 -0
- nablaengine/forest_engine/muscle.py +485 -0
- nablaengine/forest_engine/nb128.py +118 -0
- nablaengine/forest_engine/nb64.py +163 -0
- nablaengine/forest_engine/noslip.py +1124 -0
- nablaengine/forest_engine/nv128.py +1944 -0
- nablaengine/forest_engine/object_size.py +283 -0
- nablaengine/forest_engine/replay_guard.py +40 -0
- nablaengine/forest_engine/root_spread.py +126 -0
- nablaengine/forest_engine/solref.py +74 -0
- nablaengine/forest_engine/source.py +1464 -0
- nablaengine/forest_engine/sparse_pattern.py +527 -0
- nablaengine/forest_engine/spatial.py +1045 -0
- nablaengine/forest_engine/step.py +3083 -0
- nablaengine/forest_engine/surrogate.py +498 -0
- nablaengine/forest_engine/tape.py +199 -0
- nablaengine/forest_engine/tendon.py +845 -0
- nablaengine/forest_engine/terrain.py +1059 -0
- nablaengine/forest_engine/world_forces.py +166 -0
- nablaengine/forest_engine/world_params.py +230 -0
- nablaengine/g1_engine/__init__.py +0 -0
- nablaengine/g1_engine/adjoint.py +1661 -0
- nablaengine/g1_engine/adjoint_contact.py +577 -0
- nablaengine/g1_engine/bam_hooks.py +596 -0
- nablaengine/g1_engine/condim4.py +245 -0
- nablaengine/g1_engine/contact_forces.py +500 -0
- nablaengine/g1_engine/cylccd.py +1158 -0
- nablaengine/g1_engine/cylinder.py +216 -0
- nablaengine/g1_engine/elliptic.py +565 -0
- nablaengine/g1_engine/exact_replay.py +61 -0
- nablaengine/g1_engine/host.py +358 -0
- nablaengine/g1_engine/kinematics.py +320 -0
- nablaengine/g1_engine/mesh.py +305 -0
- nablaengine/g1_engine/mesh_tables.py +79 -0
- nablaengine/g1_engine/model_hooks.py +919 -0
- nablaengine/g1_engine/motor_hooks.py +70 -0
- nablaengine/g1_engine/replay_guard.py +55 -0
- nablaengine/g1_engine/source.py +1107 -0
- nablaengine/g1_engine/sphbox.py +93 -0
- nablaengine/g1_engine/step.py +3716 -0
- nablaengine/g1_engine/tape.py +173 -0
- nablaengine/g1_engine/world_params.py +447 -0
- nablaengine/identity.py +401 -0
- nablaengine/jax_ffi.py +2536 -0
- nablaengine/model/__init__.py +1 -0
- nablaengine/model/capability.py +694 -0
- nablaengine/model/fields.py +317 -0
- nablaengine/model/gravcomp.py +64 -0
- nablaengine/model/invweight.py +145 -0
- nablaengine/motor.py +143 -0
- nablaengine/object_geometry.py +609 -0
- nablaengine/params.py +258 -0
- nablaengine/provenance.py +196 -0
- nablaengine/reference/__init__.py +0 -0
- nablaengine/reference/adjoint_groups.py +226 -0
- nablaengine/reference/jax64.py +690 -0
- nablaengine/reference/warp_physics.py +262 -0
- nablaengine/sensors/__init__.py +4 -0
- nablaengine/sensors/cameras.py +285 -0
- nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
- nablaengine/sensors/data/livox_mid360.npz +0 -0
- nablaengine/sensors/g1.py +521 -0
- nablaengine/sensors/jax_rays.py +364 -0
- nablaengine/sensors/optix_rays.py +725 -0
- nablaengine/sensors/raycore.py +630 -0
- nablaengine/sensors/raygrad.py +374 -0
- nablaengine/sensors/raygrad_cuda.py +191 -0
- nablaengine/sensors/robot_mesh.py +273 -0
- nablaengine/sensors/torch_rays.py +275 -0
- nablaengine/terrain.py +424 -0
- nablaengine/torch_ffi.py +1328 -0
- nablaengine/workdir.py +37 -0
- nablaengine-1.0.2.dist-info/METADATA +236 -0
- nablaengine-1.0.2.dist-info/RECORD +136 -0
- nablaengine-1.0.2.dist-info/WHEEL +5 -0
- nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
- nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
- nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
- nablaengine-1.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
"""JAX float64 ports of the G1 engine's forward pieces that the analytic adjoint differentiates.
|
|
2
|
+
|
|
3
|
+
Third-party code: the five primitives and make_frame mirror g1_engine/step.py's CUDA translations of MuJoCo Warp
|
|
4
|
+
(mujoco_warp/_src/collision_primitive_core.py, math.py; Copyright 2025 The Newton Developers, Apache License 2.0)."""
|
|
5
|
+
|
|
6
|
+
import dataclasses
|
|
7
|
+
import functools
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
os.environ.setdefault("JAX_PLATFORMS", "cpu")
|
|
11
|
+
|
|
12
|
+
import jax
|
|
13
|
+
import jax.numpy as jnp
|
|
14
|
+
import mujoco
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
jax.config.update("jax_enable_x64", True)
|
|
18
|
+
|
|
19
|
+
PLANE, SPHERE, CAPSULE = 0, 1, 2
|
|
20
|
+
EX, EY, EZ = np.eye(3)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclasses.dataclass(frozen=True, eq=False)
|
|
24
|
+
class Model:
|
|
25
|
+
"""Model constants of the engine (numpy, static under jit). Bodies: parent, depth, qadr, dadr, children, pos, quat,
|
|
26
|
+
axis, ipos, iquat, mass, inert, anc (hinge ancestors, nearest first), grav, armature, kp, kv, frclim, timestep, torso.
|
|
27
|
+
Collision geoms (step.collision_geoms order): gbody, gtype, gsize, gpos, gquat. Pairs (geoms ordered by type, as the
|
|
28
|
+
engine's pair table): pg1, pg2, pdim, pmu, psolref, psolimp, pfoot. Solver: binvw, dinvw, jrange, jlim, jsolref,
|
|
29
|
+
jsolimp, impratio. dofbody, ancmask as step.extra_constants."""
|
|
30
|
+
nb: int
|
|
31
|
+
nq: int
|
|
32
|
+
nv: int
|
|
33
|
+
parent: np.ndarray
|
|
34
|
+
depth: np.ndarray
|
|
35
|
+
qadr: np.ndarray
|
|
36
|
+
dadr: np.ndarray
|
|
37
|
+
children: tuple
|
|
38
|
+
pos: np.ndarray
|
|
39
|
+
quat: np.ndarray
|
|
40
|
+
axis: np.ndarray
|
|
41
|
+
ipos: np.ndarray
|
|
42
|
+
iquat: np.ndarray
|
|
43
|
+
mass: np.ndarray
|
|
44
|
+
inert: np.ndarray
|
|
45
|
+
anc: tuple
|
|
46
|
+
grav: np.ndarray
|
|
47
|
+
armature: np.ndarray
|
|
48
|
+
kp: np.ndarray
|
|
49
|
+
kv: np.ndarray
|
|
50
|
+
frclim: np.ndarray
|
|
51
|
+
timestep: float
|
|
52
|
+
torso: int
|
|
53
|
+
geoms: tuple
|
|
54
|
+
gbody: np.ndarray
|
|
55
|
+
gtype: np.ndarray
|
|
56
|
+
gsize: np.ndarray
|
|
57
|
+
gpos: np.ndarray
|
|
58
|
+
gquat: np.ndarray
|
|
59
|
+
pg1: np.ndarray
|
|
60
|
+
pg2: np.ndarray
|
|
61
|
+
pdim: np.ndarray
|
|
62
|
+
pmu: np.ndarray
|
|
63
|
+
psolref: np.ndarray
|
|
64
|
+
psolimp: np.ndarray
|
|
65
|
+
pfoot: np.ndarray
|
|
66
|
+
binvw: np.ndarray
|
|
67
|
+
dinvw: np.ndarray
|
|
68
|
+
jrange: np.ndarray
|
|
69
|
+
jlim: np.ndarray
|
|
70
|
+
jsolref: np.ndarray
|
|
71
|
+
jsolimp: np.ndarray
|
|
72
|
+
impratio: float
|
|
73
|
+
dofbody: np.ndarray
|
|
74
|
+
ancmask: np.ndarray
|
|
75
|
+
ginvw: np.ndarray = None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def model(m, foot_pairs=(), f32=False):
|
|
79
|
+
"""Model constants of MjModel m as the engine packs them (source.constants, step.pair_constants), in float64; f32=True
|
|
80
|
+
rounds every float constant to float32 first (the engine's values; for VJP references on the engine's inputs)."""
|
|
81
|
+
from nablaengine.g1_engine import step
|
|
82
|
+
|
|
83
|
+
r = (lambda x: np.array(np.asarray(x, np.float64).astype(np.float32), np.float64)) if f32 else \
|
|
84
|
+
(lambda x: np.array(x, np.float64))
|
|
85
|
+
nb = m.nbody
|
|
86
|
+
depth, children = np.zeros(nb, int), [[] for _ in range(nb)]
|
|
87
|
+
for b in range(1, nb):
|
|
88
|
+
depth[b] = depth[m.body_parentid[b]] + 1
|
|
89
|
+
children[m.body_parentid[b]].append(b)
|
|
90
|
+
assert m.jnt_type[m.body_jntadr[1]] == mujoco.mjtJoint.mjJNT_FREE and m.body_jntnum[1] == 1
|
|
91
|
+
qadr, dadr, axis = np.zeros(nb, int), np.zeros(nb, int), np.zeros((nb, 3))
|
|
92
|
+
for b in range(2, nb):
|
|
93
|
+
j = m.body_jntadr[b]
|
|
94
|
+
assert m.body_jntnum[b] == 1 and m.jnt_type[j] == mujoco.mjtJoint.mjJNT_HINGE and not m.jnt_pos[j].any()
|
|
95
|
+
qadr[b], dadr[b], axis[b] = m.jnt_qposadr[j], m.jnt_dofadr[j], m.jnt_axis[j]
|
|
96
|
+
anc = []
|
|
97
|
+
for b in range(nb):
|
|
98
|
+
k, lst = m.body_parentid[b] if b >= 2 else 0, []
|
|
99
|
+
while k >= 2:
|
|
100
|
+
lst.append(int(k))
|
|
101
|
+
k = m.body_parentid[k]
|
|
102
|
+
anc.append(tuple(lst))
|
|
103
|
+
kp, kv, frclim = np.zeros(m.nv), np.zeros(m.nv), np.full(m.nv, 1e30)
|
|
104
|
+
for a in range(m.nu):
|
|
105
|
+
j = m.actuator_trnid[a, 0]
|
|
106
|
+
assert m.actuator_biastype[a] == mujoco.mjtBias.mjBIAS_AFFINE and m.actuator_gear[a, 0] == 1.0
|
|
107
|
+
dof = m.jnt_dofadr[j]
|
|
108
|
+
kp[dof], kv[dof] = m.actuator_gainprm[a, 0], -m.actuator_biasprm[a, 2]
|
|
109
|
+
if m.jnt_actfrclimited[j]:
|
|
110
|
+
frclim[dof] = m.jnt_actfrcrange[j, 1]
|
|
111
|
+
geoms = step.collision_geoms(m)
|
|
112
|
+
gid = {g: i for i, g in enumerate(geoms)}
|
|
113
|
+
pg1, pg2 = np.zeros(m.npair, int), np.zeros(m.npair, int)
|
|
114
|
+
for i in range(m.npair):
|
|
115
|
+
g1, g2 = int(m.pair_geom1[i]), int(m.pair_geom2[i])
|
|
116
|
+
if step.GEOM_TYPE[int(m.geom_type[g1])] > step.GEOM_TYPE[int(m.geom_type[g2])]:
|
|
117
|
+
g1, g2 = g2, g1
|
|
118
|
+
pg1[i], pg2[i] = gid[g1], gid[g2]
|
|
119
|
+
jr, jlim = np.zeros((m.nv, 2)), np.zeros(m.nv, bool)
|
|
120
|
+
for j in range(1, m.njnt):
|
|
121
|
+
jr[m.jnt_dofadr[j]], jlim[m.jnt_dofadr[j]] = m.jnt_range[j], m.jnt_limited[j]
|
|
122
|
+
dofbody, mask = step.extra_constants(m)
|
|
123
|
+
torso = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, "torso_link")
|
|
124
|
+
foot = np.zeros(m.npair, bool)
|
|
125
|
+
foot[list(foot_pairs)] = True
|
|
126
|
+
from nablaengine.model import invweight
|
|
127
|
+
gi = invweight.table(m, geoms)
|
|
128
|
+
return Model(
|
|
129
|
+
nb=nb, nq=m.nq, nv=m.nv, parent=np.asarray(m.body_parentid, int), depth=depth, qadr=qadr, dadr=dadr,
|
|
130
|
+
children=tuple(tuple(c) for c in children), pos=r(m.body_pos), quat=r(m.body_quat), axis=r(axis),
|
|
131
|
+
ipos=r(m.body_ipos), iquat=r(m.body_iquat), mass=r(m.body_mass), inert=r(m.body_inertia), anc=tuple(anc),
|
|
132
|
+
grav=r(m.opt.gravity), armature=r(m.dof_armature), kp=r(kp), kv=r(kv), frclim=r(frclim),
|
|
133
|
+
timestep=float(r(m.opt.timestep)), torso=int(torso), geoms=tuple(geoms),
|
|
134
|
+
gbody=np.asarray(m.geom_bodyid[geoms], int), gtype=np.asarray([step.GEOM_TYPE[int(m.geom_type[g])] for g in geoms]),
|
|
135
|
+
gsize=r(m.geom_size[geoms]), gpos=r(m.geom_pos[geoms]), gquat=r(m.geom_quat[geoms]), pg1=pg1, pg2=pg2,
|
|
136
|
+
pdim=np.asarray(m.pair_dim, int), pmu=r(m.pair_friction[:, 0]), psolref=r(m.pair_solref),
|
|
137
|
+
psolimp=r(m.pair_solimp), pfoot=foot, binvw=r(m.body_invweight0[:, 0]), dinvw=r(m.dof_invweight0), jrange=r(jr),
|
|
138
|
+
jlim=jlim, jsolref=r(m.jnt_solref[1]), jsolimp=r(m.jnt_solimp[1]), impratio=float(r(m.opt.impratio)),
|
|
139
|
+
dofbody=np.asarray(dofbody, int), ancmask=np.asarray(mask, np.int64), ginvw=None if gi is None else r(gi))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
_I1, _I2 = np.array([1, 2, 0]), np.array([2, 0, 1])
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cross(a, b):
|
|
147
|
+
return a[_I1] * b[_I2] - a[_I2] * b[_I1]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def qmul(a, b):
|
|
151
|
+
av, bv = a[1:], b[1:]
|
|
152
|
+
return jnp.concatenate([(a[0] * b[0] - jnp.dot(av, bv))[None], a[0] * bv + b[0] * av + cross(av, bv)])
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def qrot(q, v):
|
|
156
|
+
t = 2.0 * cross(q[1:], v)
|
|
157
|
+
return v + q[0] * t + cross(q[1:], t)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def qconj(q):
|
|
161
|
+
return q * jnp.array([1.0, -1.0, -1.0, -1.0])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def qrot_inv(q, v):
|
|
165
|
+
return qrot(qconj(q), v)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _safe_norm(v):
|
|
170
|
+
s = jnp.dot(v, v)
|
|
171
|
+
pos = s > 0.0
|
|
172
|
+
return jnp.where(pos, jnp.sqrt(jnp.where(pos, s, 1.0)), 0.0)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def normalize3(v):
|
|
176
|
+
n = _safe_norm(v)
|
|
177
|
+
return jnp.where(n > 0.0, v / jnp.where(n > 0.0, n, 1.0), v)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def body_ipos(mdl, b, com):
|
|
182
|
+
"""COM offset of body b in its frame, with the per-world torso offset (domain randomization)."""
|
|
183
|
+
return mdl.ipos[b] + (com if b == mdl.torso else 0.0)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def fwd_body(mdl, b, Qp, Xp, Wp, Vp, ALp, Ap, qpos, qvel, qacc):
|
|
187
|
+
"""Pose Q, X, angular / linear velocity W, V and acceleration AL, A of body b's origin from its parent's (A is the
|
|
188
|
+
classical acceleration minus gravity: the root starts at qacc_p - g)."""
|
|
189
|
+
if b == 1:
|
|
190
|
+
q = qpos[3:7]
|
|
191
|
+
Q = q / jnp.sqrt(jnp.dot(q, q))
|
|
192
|
+
return Q, qpos[:3], qrot(Q, qvel[3:6]), qvel[:3], qrot(Q, qacc[3:6]), qacc[:3] - mdl.grav
|
|
193
|
+
q0 = qmul(Qp, mdl.quat[b])
|
|
194
|
+
X = Xp + qrot(Qp, mdl.pos[b])
|
|
195
|
+
ang, qd, qdd = qpos[mdl.qadr[b]], qvel[mdl.dadr[b]], qacc[mdl.dadr[b]]
|
|
196
|
+
ha = jnp.concatenate([jnp.cos(0.5 * ang)[None], jnp.sin(0.5 * ang) * mdl.axis[b]])
|
|
197
|
+
Q = qmul(q0, ha)
|
|
198
|
+
aw = qrot(Q, mdl.axis[b])
|
|
199
|
+
r = X - Xp
|
|
200
|
+
W = Wp + aw * qd
|
|
201
|
+
V = Vp + cross(Wp, r)
|
|
202
|
+
AL = ALp + aw * qdd + cross(Wp, aw * qd)
|
|
203
|
+
A = Ap + cross(ALp, r) + cross(Wp, cross(Wp, r))
|
|
204
|
+
return Q, X, W, V, AL, A
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def kinematics(mdl, qpos, qvel=None, qacc=None):
|
|
208
|
+
"""The fwd_body chain over the tree: dict of (NB, .) arrays Q, X, W, V, AL, A (body 0 = world, at rest)."""
|
|
209
|
+
qvel = jnp.zeros(mdl.nv) if qvel is None else qvel
|
|
210
|
+
qacc = jnp.zeros(mdl.nv) if qacc is None else qacc
|
|
211
|
+
z3 = jnp.zeros(3)
|
|
212
|
+
out = [(jnp.array([1.0, 0.0, 0.0, 0.0]), z3, z3, z3, z3, z3)]
|
|
213
|
+
for b in range(1, mdl.nb):
|
|
214
|
+
out.append(fwd_body(mdl, b, *out[mdl.parent[b]], qpos, qvel, qacc))
|
|
215
|
+
return {k: jnp.stack([o[i] for o in out]) for i, k in enumerate(("Q", "X", "W", "V", "AL", "A"))}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def body_force(mdl, b, Q, W, AL, A, ipos):
|
|
219
|
+
"""Force F and moment N about the body origin that body b alone needs (Newton-Euler at its COM)."""
|
|
220
|
+
c = qrot(Q, ipos)
|
|
221
|
+
m = mdl.mass[b]
|
|
222
|
+
F = m * (A + cross(AL, c) + cross(W, cross(W, c)))
|
|
223
|
+
qi = qmul(Q, mdl.iquat[b])
|
|
224
|
+
Iw = qrot(qi, mdl.inert[b] * qrot_inv(qi, W))
|
|
225
|
+
Ia = qrot(qi, mdl.inert[b] * qrot_inv(qi, AL))
|
|
226
|
+
return F, Ia + cross(W, Iw) + cross(c, F)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def accumulate(Xb, Xc, Fc, Nc, F, N):
|
|
230
|
+
return F + Fc, N + Nc + cross(Xc - Xb, Fc)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def torques(mdl, b, Q, F, N):
|
|
234
|
+
"""{dof: generalized force} of body b's joint from its subtree force and moment about its origin."""
|
|
235
|
+
if b == 1:
|
|
236
|
+
l = qrot_inv(Q, N)
|
|
237
|
+
return {k: (F[k] if k < 3 else l[k - 3]) for k in range(6)}
|
|
238
|
+
return {int(mdl.dadr[b]): jnp.dot(qrot(Q, mdl.axis[b]), N)}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def inverse_dynamics(mdl, qpos, qvel, qacc, com=None):
|
|
242
|
+
"""ID(q, v, a) = M_CRB(q) a + c(q, v) (gravity included, armature excluded): RNE as the engine's smooth phase (which
|
|
243
|
+
evaluates it at a = 0 for the bias force). The adjoint's channel 1 (adjoint.py A4) differentiates lambda' ID."""
|
|
244
|
+
com = jnp.zeros(3) if com is None else com
|
|
245
|
+
K = kinematics(mdl, qpos, qvel, qacc)
|
|
246
|
+
F, N = [jnp.zeros(3)] * mdl.nb, [jnp.zeros(3)] * mdl.nb
|
|
247
|
+
for b in range(1, mdl.nb):
|
|
248
|
+
F[b], N[b] = body_force(mdl, b, K["Q"][b], K["W"][b], K["AL"][b], K["A"][b], body_ipos(mdl, b, com))
|
|
249
|
+
for b in range(mdl.nb - 1, 1, -1):
|
|
250
|
+
p = mdl.parent[b]
|
|
251
|
+
F[p], N[p] = accumulate(K["X"][p], K["X"][b], F[b], N[b], F[p], N[p])
|
|
252
|
+
out = {}
|
|
253
|
+
for b in range(1, mdl.nb):
|
|
254
|
+
out.update(torques(mdl, b, K["Q"][b], F[b], N[b]))
|
|
255
|
+
return jnp.stack([out[i] for i in range(mdl.nv)])
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def bias_force(mdl, qpos, qvel, com=None):
|
|
259
|
+
"""qfrc_bias = ID(q, v, 0)."""
|
|
260
|
+
return inverse_dynamics(mdl, qpos, qvel, jnp.zeros(mdl.nv), com)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def body_inertia(mdl, b, Q, X, O, ipos):
|
|
264
|
+
"""Spatial inertia of body b about the point O, packed as J (xx yy zz xy xz yz), h = m c (3), m; c = com - O."""
|
|
265
|
+
qi = qmul(Q, mdl.iquat[b])
|
|
266
|
+
R = jnp.stack([qrot(qi, e) for e in (EX, EY, EZ)])
|
|
267
|
+
I = mdl.inert[b]
|
|
268
|
+
J = jnp.stack([I @ (R[:, 0] * R[:, 0]), I @ (R[:, 1] * R[:, 1]), I @ (R[:, 2] * R[:, 2]),
|
|
269
|
+
I @ (R[:, 0] * R[:, 1]), I @ (R[:, 0] * R[:, 2]), I @ (R[:, 1] * R[:, 2])])
|
|
270
|
+
c = X + qrot(Q, ipos) - O
|
|
271
|
+
m = mdl.mass[b]
|
|
272
|
+
cc = jnp.dot(c, c)
|
|
273
|
+
J = J + m * jnp.stack([cc - c[0] * c[0], cc - c[1] * c[1], cc - c[2] * c[2], -c[0] * c[1], -c[0] * c[2],
|
|
274
|
+
-c[1] * c[2]])
|
|
275
|
+
return jnp.concatenate([J, m * c, jnp.array([m])])
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def apply_inertia(J, w, v):
|
|
279
|
+
"""(n, f) = I (w, v) for a packed spatial inertia about O."""
|
|
280
|
+
h = J[6:9]
|
|
281
|
+
n = jnp.stack([J[0] * w[0] + J[3] * w[1] + J[4] * w[2], J[3] * w[0] + J[1] * w[1] + J[5] * w[2],
|
|
282
|
+
J[4] * w[0] + J[5] * w[1] + J[2] * w[2]]) + cross(h, v)
|
|
283
|
+
return n, J[9] * v - cross(h, w)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def dof_motion(mdl, k, t, Q, X, O):
|
|
287
|
+
"""Motion subspace (w, v) of dof t of body k about the point O (root: t = 0..5, hinge: t = 0)."""
|
|
288
|
+
if k == 1:
|
|
289
|
+
e = np.eye(3)[t % 3]
|
|
290
|
+
if t < 3:
|
|
291
|
+
return jnp.zeros(3), jnp.asarray(e)
|
|
292
|
+
return qrot(Q, e), jnp.zeros(3)
|
|
293
|
+
w = qrot(Q, mdl.axis[k])
|
|
294
|
+
return w, cross(w, O - X)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def mass_matrix(mdl, qpos, com=None):
|
|
298
|
+
"""Joint-space mass matrix by the composite-rigid-body algorithm about the root origin, with the armature (dense
|
|
299
|
+
NV x NV, the engine's packed lower triangle mirrored)."""
|
|
300
|
+
com = jnp.zeros(3) if com is None else com
|
|
301
|
+
K = kinematics(mdl, qpos)
|
|
302
|
+
O = K["X"][1]
|
|
303
|
+
J = [None] + [body_inertia(mdl, b, K["Q"][b], K["X"][b], O, body_ipos(mdl, b, com)) for b in range(1, mdl.nb)]
|
|
304
|
+
for b in range(mdl.nb - 1, 1, -1):
|
|
305
|
+
J[mdl.parent[b]] = J[mdl.parent[b]] + J[b]
|
|
306
|
+
ent = {}
|
|
307
|
+
for b in range(2, mdl.nb):
|
|
308
|
+
j = int(mdl.dadr[b])
|
|
309
|
+
sw, sv = dof_motion(mdl, b, 0, K["Q"][b], K["X"][b], O)
|
|
310
|
+
n, f = apply_inertia(J[b], sw, sv)
|
|
311
|
+
ent[j, j] = jnp.dot(sw, n) + jnp.dot(sv, f) + mdl.armature[j]
|
|
312
|
+
for k in mdl.anc[b]:
|
|
313
|
+
kw, kv = dof_motion(mdl, k, 0, K["Q"][k], K["X"][k], O)
|
|
314
|
+
ent[j, int(mdl.dadr[k])] = jnp.dot(kw, n) + jnp.dot(kv, f)
|
|
315
|
+
for t in range(6):
|
|
316
|
+
kw, kv = dof_motion(mdl, 1, t, K["Q"][1], K["X"][1], O)
|
|
317
|
+
ent[j, t] = jnp.dot(kw, n) + jnp.dot(kv, f)
|
|
318
|
+
for j in range(6):
|
|
319
|
+
sw, sv = dof_motion(mdl, 1, j, K["Q"][1], K["X"][1], O)
|
|
320
|
+
n, f = apply_inertia(J[1], sw, sv)
|
|
321
|
+
for i in range(j + 1):
|
|
322
|
+
kw, kv = dof_motion(mdl, 1, i, K["Q"][1], K["X"][1], O)
|
|
323
|
+
ent[j, i] = jnp.dot(kw, n) + jnp.dot(kv, f) + (mdl.armature[j] if i == j else 0.0)
|
|
324
|
+
rows, cols = np.array([k[0] for k in ent]), np.array([k[1] for k in ent])
|
|
325
|
+
vals = jnp.stack(list(ent.values()))
|
|
326
|
+
M = jnp.zeros((mdl.nv, mdl.nv)).at[rows, cols].set(vals)
|
|
327
|
+
return M.at[cols, rows].set(vals)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def actuator_raw(mdl, qpos, qvel, ctrl):
|
|
332
|
+
"""Unclamped PD force kp (ctrl - q) - kv qdot on the hinge dofs (zeros on the root dofs)."""
|
|
333
|
+
act = mdl.kp[6:] * (ctrl - qpos[7:]) - mdl.kv[6:] * qvel[6:]
|
|
334
|
+
return jnp.concatenate([jnp.zeros(6), act])
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def actuator_force(mdl, qpos, qvel, ctrl, clamped=None):
|
|
338
|
+
"""Clamped actuator force (the engine's qfrc_smooth part) and the clamp mask (after clamping at or beyond
|
|
339
|
+
+-frclim, the criterion of MuJoCo Warp's _actuator_lam). clamped: the mask from the forward (tape); its dofs take
|
|
340
|
+
the clamped value with a zero derivative, the others the raw PD law."""
|
|
341
|
+
raw = actuator_raw(mdl, qpos, qvel, ctrl)
|
|
342
|
+
lim = jnp.asarray(mdl.frclim)
|
|
343
|
+
cl = jnp.clip(raw, -lim, lim)
|
|
344
|
+
mask = (cl <= -lim) | (cl >= lim) if clamped is None else jnp.asarray(clamped, bool)
|
|
345
|
+
return jnp.where(mask, jax.lax.stop_gradient(cl), raw), mask
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def pow_imp(x, p):
|
|
349
|
+
return x * x if p == 2.0 else (x if p == 1.0 else jnp.power(x, p))
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def kbimp(solref, solimp, pos_imp, h):
|
|
353
|
+
"""Stiffness k, damping b and impedance imp at pos_imp (refsafe: timeconst >= 2 h), the engine's kbimp."""
|
|
354
|
+
solref, solimp = np.asarray(solref, np.float64), np.asarray(solimp, np.float64)
|
|
355
|
+
tc, dr = max(solref[0], 2.0 * h), solref[1]
|
|
356
|
+
dmin, dmax = min(max(solimp[0], 1e-4), 0.9999), min(max(solimp[1], 1e-4), 0.9999)
|
|
357
|
+
width, mid, power = max(1e-15, solimp[2]), min(max(solimp[3], 1e-4), 0.9999), max(1.0, solimp[4])
|
|
358
|
+
k = 1.0 / max(1e-15, dmax * dmax * tc * tc * dr * dr)
|
|
359
|
+
b = 2.0 / max(1e-15, dmax * tc)
|
|
360
|
+
if dmin == dmax or solimp[2] <= 1e-15:
|
|
361
|
+
return k, b, jnp.full_like(pos_imp, 0.5 * (dmin + dmax))
|
|
362
|
+
x = jnp.abs(pos_imp) / width
|
|
363
|
+
if power == 1.0:
|
|
364
|
+
mid_val = dmin + x * (dmax - dmin)
|
|
365
|
+
lo_val = hi_val = mid_val
|
|
366
|
+
else:
|
|
367
|
+
xl, xh = jnp.where(x <= mid, x, mid), jnp.where(x >= mid, jnp.minimum(x, 1.0), mid)
|
|
368
|
+
lo_val = jnp.clip(dmin + pow_imp(xl, power) / pow_imp(mid, power - 1.0) * (dmax - dmin), dmin, dmax)
|
|
369
|
+
hi_val = jnp.clip(dmin + (1.0 - pow_imp(1.0 - xh, power) / pow_imp(1.0 - mid, power - 1.0)) * (dmax - dmin),
|
|
370
|
+
dmin, dmax)
|
|
371
|
+
imp = jnp.where(x <= 0.0, dmin, jnp.where(x >= 1.0, dmax, jnp.where(x <= mid, lo_val, hi_val)))
|
|
372
|
+
return k, b, imp
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def efc_D(invw, imp):
|
|
376
|
+
"""D = 1 / R, R = invweight (1 - imp) / imp (floored at 1e-15)."""
|
|
377
|
+
return 1.0 / jnp.maximum(invw * (1.0 - imp) / imp, 1e-15)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def geom_poses(mdl, Q, X):
|
|
382
|
+
"""World positions (NG, 3) and quaternions (NG, 4) of the collision geoms from the body poses."""
|
|
383
|
+
gx = jnp.stack([X[b] + qrot(Q[b], mdl.gpos[g]) for g, b in enumerate(mdl.gbody)])
|
|
384
|
+
gq = jnp.stack([qmul(Q[b], mdl.gquat[g]) for g, b in enumerate(mdl.gbody)])
|
|
385
|
+
return gx, gq
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def make_frame(n):
|
|
389
|
+
"""MuJoCo's make_frame(n): rows n, b, c with b from e_y (|n_y| < 0.5) or e_z, made orthogonal to n."""
|
|
390
|
+
e = jnp.where((-0.5 < n[1]) & (n[1] < 0.5), EY, EZ)
|
|
391
|
+
b = normalize3(e - n * jnp.dot(n, e))
|
|
392
|
+
return jnp.stack([n, b, cross(n, b)])
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
NORMAL_EXACT, NORMAL_FROZEN, NORMAL_REG, NORMAL_CUT = 0, 1, 2, 3
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _kappa(nu, mode, eps):
|
|
399
|
+
if mode == NORMAL_EXACT:
|
|
400
|
+
return 1.0 / nu
|
|
401
|
+
if mode == NORMAL_FROZEN:
|
|
402
|
+
return jnp.zeros_like(nu)
|
|
403
|
+
if mode == NORMAL_REG:
|
|
404
|
+
return 1.0 / jnp.maximum(nu, eps)
|
|
405
|
+
return jnp.where(nu < eps, 0.0, 1.0 / nu)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
@functools.partial(jax.custom_vjp, nondiff_argnums=(1, 2))
|
|
409
|
+
def _unit_mod(v, mode, eps):
|
|
410
|
+
return v / jnp.sqrt(jnp.dot(v, v))
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _unit_mod_fwd(v, mode, eps):
|
|
414
|
+
nu = jnp.sqrt(jnp.dot(v, v))
|
|
415
|
+
return v / nu, (v / nu, nu)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _unit_mod_bwd(mode, eps, res, g):
|
|
419
|
+
n, nu = res
|
|
420
|
+
return (_kappa(nu, mode, eps) * (g - n * jnp.dot(n, g)),)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
_unit_mod.defvjp(_unit_mod_fwd, _unit_mod_bwd)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def unit_normal(v, mode=NORMAL_EXACT, eps=1e-3):
|
|
427
|
+
"""n = v / |v| (e_x when v = 0, zero derivative there); the derivative (I - n n') / |v| becomes kappa (I - n n') for
|
|
428
|
+
DK_ADJ_NORMAL = mode (the forward value is unchanged)."""
|
|
429
|
+
nu2 = jnp.dot(v, v)
|
|
430
|
+
pos = nu2 > 0.0
|
|
431
|
+
vs = jnp.where(pos, v, EX)
|
|
432
|
+
if mode == NORMAL_EXACT:
|
|
433
|
+
n = vs / jnp.sqrt(jnp.dot(vs, vs))
|
|
434
|
+
else:
|
|
435
|
+
n = _unit_mod(vs, int(mode), float(eps))
|
|
436
|
+
return jnp.where(pos, n, EX)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def sphere_sphere(p1, r1, p2, r2, mode=NORMAL_EXACT, eps=1e-3):
|
|
440
|
+
"""(dist, pos, normal) of two spheres; the core of every v / |v| normal (sphere-capsule, capsule-capsule)."""
|
|
441
|
+
d = p2 - p1
|
|
442
|
+
n = unit_normal(d, mode, eps)
|
|
443
|
+
dist = _safe_norm(d) - (r1 + r2)
|
|
444
|
+
return dist, p1 + n * (r1 + 0.5 * dist), n
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def plane_sphere(pn, pp, sp, r):
|
|
448
|
+
"""Plane (normal pn through pp) against a sphere at sp: (dist, pos, frame)."""
|
|
449
|
+
dist = jnp.dot(sp, pn) - jnp.dot(pp, pn) - r
|
|
450
|
+
return dist, sp - pn * (r + 0.5 * dist), make_frame(pn)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def plane_capsule(pn, pp, cp, cq, r, hl, slot, fallback=True):
|
|
454
|
+
"""Plane against capsule end `slot` (0: +axis, 1: -axis): (dist, pos, frame); the frame's first tangent follows the
|
|
455
|
+
capsule axis projected on the plane, or (fallback, MuJoCo Warp and the engine) make_frame's basis when that
|
|
456
|
+
projection is shorter than 0.5. fallback=False keeps the projected axis (MuJoCo C 3.17)."""
|
|
457
|
+
axis = qrot(cq, EZ)
|
|
458
|
+
b = axis - pn * jnp.dot(pn, axis)
|
|
459
|
+
bn = _safe_norm(b)
|
|
460
|
+
b = jnp.where(bn > 0.0, b / jnp.where(bn > 0.0, bn, 1.0), b)
|
|
461
|
+
basis = jnp.where((-0.5 < pn[1]) & (pn[1] < 0.5), EY, EZ)
|
|
462
|
+
b = jnp.where(bn < 0.5, basis, b) if fallback else b
|
|
463
|
+
frame = jnp.stack([pn, b, cross(pn, b)])
|
|
464
|
+
ce = cp + (1.0 if slot == 0 else -1.0) * axis * hl
|
|
465
|
+
dist = jnp.dot(ce, pn) - jnp.dot(pp, pn) - r
|
|
466
|
+
return dist, ce - pn * (r + 0.5 * dist), frame
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def sphere_capsule(sp, r1, cp, cq, r2, hl, mode=NORMAL_EXACT, eps=1e-3, reg=1e-6):
|
|
470
|
+
"""Sphere at sp against a capsule: closest point of the segment (t regularized by reg = 1e-6 as MuJoCo Warp's
|
|
471
|
+
closest_segment_point), then the sphere core. reg=0 gives the exact closest point (MuJoCo C)."""
|
|
472
|
+
axis = qrot(cq, EZ)
|
|
473
|
+
a = cp - axis * hl
|
|
474
|
+
ab = 2.0 * axis * hl
|
|
475
|
+
t = jnp.clip(jnp.dot(sp - a, ab) / (jnp.dot(ab, ab) + reg), 0.0, 1.0)
|
|
476
|
+
dist, pos, n = sphere_sphere(sp, r1, a + t * ab, r2, mode, eps)
|
|
477
|
+
return dist, pos, make_frame(n)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def capsule_params(p1, q1, hl1, p2, q2, hl2, slot=0, parallel_eps=None):
|
|
481
|
+
"""Segment parameters (x1, x2) in [-1, 1] of the capsule-capsule closest points (the engine's clamp cascade), the
|
|
482
|
+
determinant and whether the parallel branch (|det| < 1e-15, candidate `slot`) was taken. parallel_eps (the engine's
|
|
483
|
+
DK_ADJ_PARALLEL = 1 with DK_ADJ_PARALLEL_EPS; None: exact): where both parameters are free and sin^2(theta) =
|
|
484
|
+
|a1 x a2|^2 / (|a1|^2 |a2|^2) < parallel_eps, x1 and x2 are held constant in the derivative (stop_gradient; the
|
|
485
|
+
values are unchanged)."""
|
|
486
|
+
a1, a2 = qrot(q1, EZ) * hl1, qrot(q2, EZ) * hl2
|
|
487
|
+
dif = p1 - p2
|
|
488
|
+
ma, mb, mc = jnp.dot(a1, a1), -jnp.dot(a1, a2), jnp.dot(a2, a2)
|
|
489
|
+
u, v = -jnp.dot(a1, dif), jnp.dot(a2, dif)
|
|
490
|
+
det = ma * mc - mb * mb
|
|
491
|
+
par = jnp.abs(det) < 1e-15
|
|
492
|
+
dets = jnp.where(par, 1.0, det)
|
|
493
|
+
x1, x2 = (mc * u - mb * v) / dets, (ma * v - mb * u) / dets
|
|
494
|
+
w = cross(a1, a2)
|
|
495
|
+
frozen = (~par & (jnp.abs(x1) <= 1.0) & (jnp.abs(x2) <= 1.0) & (jnp.dot(w, w) < parallel_eps * ma * mc)
|
|
496
|
+
if parallel_eps is not None else None)
|
|
497
|
+
x1, x2 = (jnp.where(x1 > 1.0, 1.0, jnp.where(x1 < -1.0, -1.0, x1)),
|
|
498
|
+
jnp.where(x1 > 1.0, (v - mb) / mc, jnp.where(x1 < -1.0, (v + mb) / mc, x2)))
|
|
499
|
+
x1, x2 = (jnp.where(x2 > 1.0, jnp.clip((u - mb) / ma, -1.0, 1.0),
|
|
500
|
+
jnp.where(x2 < -1.0, jnp.clip((u + mb) / ma, -1.0, 1.0), x1)),
|
|
501
|
+
jnp.where(x2 > 1.0, 1.0, jnp.where(x2 < -1.0, -1.0, x2)))
|
|
502
|
+
cand = [(1.0, jnp.clip((v - mb) / mc, -1.0, 1.0)), (-1.0, jnp.clip((v + mb) / mc, -1.0, 1.0)),
|
|
503
|
+
(jnp.clip((u - mb) / ma, -1.0, 1.0), 1.0), (jnp.clip((u + mb) / ma, -1.0, 1.0), -1.0)][slot]
|
|
504
|
+
x1 = jnp.where(par, cand[0], x1)
|
|
505
|
+
x2 = jnp.where(par, cand[1], x2)
|
|
506
|
+
if frozen is not None:
|
|
507
|
+
x1 = jnp.where(frozen, jax.lax.stop_gradient(x1), x1)
|
|
508
|
+
x2 = jnp.where(frozen, jax.lax.stop_gradient(x2), x2)
|
|
509
|
+
return x1, x2, det, par
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def capsule_capsule(p1, q1, r1, hl1, p2, q2, r2, hl2, slot=0, mode=NORMAL_EXACT, eps=1e-3, parallel_eps=None):
|
|
513
|
+
"""Two capsules: closest points of the segments (capsule_params, parallel_eps: DK_ADJ_PARALLEL), then the sphere
|
|
514
|
+
core: (dist, pos, frame)."""
|
|
515
|
+
x1, x2, _, _ = capsule_params(p1, q1, hl1, p2, q2, hl2, slot, parallel_eps)
|
|
516
|
+
v1, v2 = p1 + qrot(q1, EZ) * hl1 * x1, p2 + qrot(q2, EZ) * hl2 * x2
|
|
517
|
+
dist, pos, n = sphere_sphere(v1, r1, v2, r2, mode, eps)
|
|
518
|
+
return dist, pos, make_frame(n)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def collide_geoms(t1, t2, x1, q1, s1, x2, q2, s2, slot=0, mode=NORMAL_EXACT, eps=1e-3, reg=1e-6, fallback=True,
|
|
522
|
+
parallel_eps=None):
|
|
523
|
+
"""(dist, pos, frame) of contact `slot` between geoms of engine types t1 <= t2 (static) at world poses (x, q) with
|
|
524
|
+
sizes s (the engine's collide_pair without the culling; the caller decides which contacts exist). reg and fallback:
|
|
525
|
+
see sphere_capsule and plane_capsule (their defaults are MuJoCo Warp's and the engine's); parallel_eps: the
|
|
526
|
+
capsule-capsule option DK_ADJ_PARALLEL (capsule_params)."""
|
|
527
|
+
if t1 == PLANE:
|
|
528
|
+
pn = qrot(q1, EZ)
|
|
529
|
+
if t2 == SPHERE:
|
|
530
|
+
return plane_sphere(pn, x1, x2, s2[0])
|
|
531
|
+
return plane_capsule(pn, x1, x2, q2, s2[0], s2[1], slot, fallback)
|
|
532
|
+
if t1 == SPHERE and t2 == SPHERE:
|
|
533
|
+
dist, pos, n = sphere_sphere(x1, s1[0], x2, s2[0], mode, eps)
|
|
534
|
+
return dist, pos, make_frame(n)
|
|
535
|
+
if t1 == SPHERE:
|
|
536
|
+
return sphere_capsule(x1, s1[0], x2, q2, s2[0], s2[1], mode, eps, reg)
|
|
537
|
+
return capsule_capsule(x1, q1, s1[0], s1[1], x2, q2, s2[0], s2[1], slot, mode, eps, parallel_eps)
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def collide(mdl, gx, gq, pair, slot=0, mode=NORMAL_EXACT, eps=1e-3):
|
|
541
|
+
"""collide_geoms for contact (pair, slot) from the collision geoms' world poses (geom_poses)."""
|
|
542
|
+
g1, g2 = int(mdl.pg1[pair]), int(mdl.pg2[pair])
|
|
543
|
+
return collide_geoms(int(mdl.gtype[g1]), int(mdl.gtype[g2]), gx[g1], gq[g1], mdl.gsize[g1], gx[g2], gq[g2],
|
|
544
|
+
mdl.gsize[g2], slot, mode, eps)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def contact_axis_distance(mdl, pair, dist):
|
|
548
|
+
"""nu = dist + r1 + r2, the centre / axis distance of a sphere or capsule contact before the radii."""
|
|
549
|
+
return dist + mdl.gsize[mdl.pg1[pair], 0] + mdl.gsize[mdl.pg2[pair], 0]
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def support(mdl, pair):
|
|
554
|
+
"""(dofs, signs) of a contact's Jacobian support: the dofs on exactly one of the two bodies' chains, +1 on body 2's."""
|
|
555
|
+
sgn = support_signs(mdl, pair)
|
|
556
|
+
dofs = np.flatnonzero(sgn)
|
|
557
|
+
return dofs, sgn[dofs]
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def support_signs(mdl, pair):
|
|
561
|
+
"""(NV,) +1 / -1 on the dofs of body 2's / body 1's chain that are not on both, 0 elsewhere (the support)."""
|
|
562
|
+
b1, b2 = int(mdl.gbody[mdl.pg1[pair]]), int(mdl.gbody[mdl.pg2[pair]])
|
|
563
|
+
sgn = np.zeros(mdl.nv)
|
|
564
|
+
for i in range(mdl.nv):
|
|
565
|
+
bi = int(mdl.dofbody[i])
|
|
566
|
+
in2, in1 = (int(mdl.ancmask[b2]) >> bi) & 1, (int(mdl.ancmask[b1]) >> bi) & 1
|
|
567
|
+
if in1 != in2:
|
|
568
|
+
sgn[i] = 1.0 if in2 else -1.0
|
|
569
|
+
return sgn
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def point_jacobian(mdl, Q, X, pos, sgn):
|
|
573
|
+
"""(3, NV) translational Jacobian of the point pos moving with body 2 relative to body 1, column i scaled by sgn[i]
|
|
574
|
+
(support_signs; may be traced): the engine's contact-Jacobian columns before the frame projection."""
|
|
575
|
+
O = X[1]
|
|
576
|
+
cols = []
|
|
577
|
+
for i in range(mdl.nv):
|
|
578
|
+
bi = int(mdl.dofbody[i])
|
|
579
|
+
w, v = dof_motion(mdl, bi, i if bi == 1 else 0, Q[bi], X[bi], O)
|
|
580
|
+
cols.append(sgn[i] * (v + cross(w, pos - O)))
|
|
581
|
+
return jnp.stack(cols, axis=1)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def contact_jacobian(mdl, Q, X, pos, frame, sgn):
|
|
585
|
+
"""(3, NV) frame rows (normal, two tangents) of J(body 2, pos) - J(body 1, pos)."""
|
|
586
|
+
return frame @ point_jacobian(mdl, Q, X, pos, sgn)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def contact_params(mdl, pair, fric):
|
|
590
|
+
"""Static and traced row parameters of a pair: dict dim, solref, solimp (tuples), mu, invweight (body_invweight0
|
|
591
|
+
translation of both bodies; condim 3 times (1 + mu^2) 2 mu^2 / impratio, the engine's formula), sgn."""
|
|
592
|
+
mu = fric if mdl.pfoot[pair] else float(mdl.pmu[pair])
|
|
593
|
+
if mdl.ginvw is None:
|
|
594
|
+
iw = mdl.binvw[mdl.gbody[mdl.pg1[pair]]] + mdl.binvw[mdl.gbody[mdl.pg2[pair]]]
|
|
595
|
+
else:
|
|
596
|
+
iw = mdl.ginvw[mdl.pg1[pair]] + mdl.ginvw[mdl.pg2[pair]]
|
|
597
|
+
dim = int(mdl.pdim[pair])
|
|
598
|
+
if dim == 3:
|
|
599
|
+
iw = (iw + mu * mu * iw) * 2.0 * mu * mu / mdl.impratio
|
|
600
|
+
return dict(dim=dim, solref=tuple(map(float, mdl.psolref[pair])), solimp=tuple(map(float, mdl.psolimp[pair])),
|
|
601
|
+
mu=mu, invweight=iw, sgn=support_signs(mdl, pair))
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def edges(dim, mu):
|
|
605
|
+
"""(nrow, 3) row directions in frame coordinates: pyramid edges n +- mu t1, n +- mu t2 (condim 3) or n (condim 1)."""
|
|
606
|
+
if dim != 3:
|
|
607
|
+
return jnp.array([[1.0, 0.0, 0.0]])
|
|
608
|
+
one, z = jnp.ones_like(mu), jnp.zeros_like(mu)
|
|
609
|
+
return jnp.stack([jnp.stack([one, mu, z]), jnp.stack([one, -mu, z]), jnp.stack([one, z, mu]),
|
|
610
|
+
jnp.stack([one, z, -mu])])
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def contact_rows(mdl, Q, X, qvel, dist, pos, frame, dim, solref, solimp, mu, invweight, sgn):
|
|
614
|
+
"""Rows of one contact (contact_params gives dim, solref, solimp (static), mu, invweight, sgn): J (nrow, NV), D, aref
|
|
615
|
+
(nrow) and the impedance (k, b, imp) at dist."""
|
|
616
|
+
J = edges(dim, mu) @ contact_jacobian(mdl, Q, X, pos, frame, sgn)
|
|
617
|
+
k, b, imp = kbimp(solref, solimp, dist, mdl.timestep)
|
|
618
|
+
D = efc_D(invweight, imp)
|
|
619
|
+
aref = -k * imp * dist - b * (J @ qvel)
|
|
620
|
+
return J, jnp.broadcast_to(D, (J.shape[0],)), aref, (k, b, imp)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def contact_psi(mdl, dist, frame, dim, solref, solimp, mu, invweight, Vv, Va, Vl, active):
|
|
624
|
+
"""Psi_c = sum over the contact's active rows of D x_e (u_e . V_lam), x_e = u_e . V_a + k imp(d) d + b u_e . V_v
|
|
625
|
+
(V_* the 3-vectors J_p v, J_p a*, J_p lam of the contact point, u_e the row direction in world coordinates;
|
|
626
|
+
active: (nrow,) the rows in the quadratic zone)."""
|
|
627
|
+
U = edges(dim, mu) @ frame
|
|
628
|
+
k, b, imp = kbimp(solref, solimp, dist, mdl.timestep)
|
|
629
|
+
D = efc_D(invweight, imp)
|
|
630
|
+
x = U @ Va + k * imp * dist + b * (U @ Vv)
|
|
631
|
+
return jnp.sum(jnp.where(jnp.asarray(active, bool), D * x * (U @ Vl), 0.0))
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def limit_rows(mdl, qpos, qvel, active=None):
|
|
635
|
+
"""Joint-limit rows of all hinge dofs (the active ones by the forward's test, or `active`): dict with dof, sign
|
|
636
|
+
(+1 lower, -1 upper), pos = min(q - lo, hi - q), D, aref, imp; inactive dofs carry the same formulas."""
|
|
637
|
+
i = np.arange(6, mdl.nv)
|
|
638
|
+
q = qpos[i + 1]
|
|
639
|
+
dmin, dmax = q - mdl.jrange[i, 0], mdl.jrange[i, 1] - q
|
|
640
|
+
sign = jnp.where(dmin < dmax, 1.0, -1.0)
|
|
641
|
+
pos = jnp.minimum(dmin, dmax)
|
|
642
|
+
act = (jnp.asarray(mdl.jlim[i]) & (pos < 0.0)) if active is None else jnp.asarray(active, bool)
|
|
643
|
+
k, b, imp = kbimp(mdl.jsolref, mdl.jsolimp, pos, mdl.timestep)
|
|
644
|
+
D = efc_D(mdl.dinvw[i], imp)
|
|
645
|
+
return dict(dof=i, sign=sign, pos=pos, active=act, D=D, aref=-k * imp * pos - b * (sign * qvel[i]), imp=imp)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def limit_psi(mdl, qpos, qvel, qacc, lam, active):
|
|
649
|
+
"""sum over the active limit rows of Psi_e = D(pos) x_e (J_e lam), x_e = J_e a + k imp pos + b J_e v."""
|
|
650
|
+
r = limit_rows(mdl, qpos, qvel, active)
|
|
651
|
+
J = r["sign"]
|
|
652
|
+
x = J * qacc[r["dof"]] - r["aref"]
|
|
653
|
+
return jnp.sum(jnp.where(active, r["D"] * x * J * lam[r["dof"]], 0.0))
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _sinc(x):
|
|
658
|
+
small = x * x < 1e-4
|
|
659
|
+
xs = jnp.where(small, 1.0, x)
|
|
660
|
+
return jnp.where(small, 1.0 - x * x / 6.0 + x ** 4 / 120.0, jnp.sin(xs) / xs)
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def quat_integrate(q, w, h):
|
|
664
|
+
"""normalize(normalize(q) (cos x, (h/2) sinc(x) w)), x = (h/2)|w| (MuJoCo Warp's smooth form; the same rotation as
|
|
665
|
+
the engine's axis-angle update, differentiable at w = 0)."""
|
|
666
|
+
x = 0.5 * h * _safe_norm(w)
|
|
667
|
+
rho = jnp.concatenate([jnp.cos(x)[None], 0.5 * h * _sinc(x) * w])
|
|
668
|
+
u = qmul(q / jnp.sqrt(jnp.dot(q, q)), rho)
|
|
669
|
+
return u / jnp.sqrt(jnp.dot(u, u))
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def integrate_pos(mdl, qpos, qvel, h=None):
|
|
673
|
+
"""q' = q (+) h v: root translation, root quaternion, hinge angles (implicitfast passes the new velocity)."""
|
|
674
|
+
h = mdl.timestep if h is None else h
|
|
675
|
+
return jnp.concatenate([qpos[:3] + h * qvel[:3], quat_integrate(qpos[3:7], qvel[3:6], h), qpos[7:] + h * qvel[6:]])
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def dof_to_qpos(g, qpos):
|
|
679
|
+
"""Lift a dof-tangent cotangent (NV) to qpos form (NQ): (g_p, 2 xi (x) (0, g_theta), g_phi), xi not normalized (MuJoCo
|
|
680
|
+
Warp's _dof_to_qpos)."""
|
|
681
|
+
gq = 2.0 * qmul(qpos[3:7], jnp.concatenate([jnp.zeros(1), g[3:6]]))
|
|
682
|
+
return jnp.concatenate([g[:3], gq, g[6:]])
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def qpos_to_dof(gq, qpos):
|
|
686
|
+
"""Tangent part of a qpos cotangent (NQ -> NV): g_theta = 1/2 Im(xi* (x) g_xi) / |xi|^2, the left inverse of
|
|
687
|
+
dof_to_qpos (for the 35-dimensional error of qpos gradients)."""
|
|
688
|
+
xi = qpos[3:7]
|
|
689
|
+
gt = 0.5 * qmul(qconj(xi), gq[3:7])[1:] / jnp.dot(xi, xi)
|
|
690
|
+
return jnp.concatenate([gq[:3], gt, gq[7:]])
|