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,500 @@
|
|
|
1
|
+
"""The contact forces in the G1 engine's contact table (an opt-in: jax_ffi.init / torch_ffi.build(contact_forces=...)),
|
|
2
|
+
and the outputs derived from them (per-substep tables, per-foot wrenches, the contact frame's tangent, the terrain
|
|
3
|
+
element). Applied to the generated text only when asked for, so the default build is unchanged
|
|
4
|
+
(scripts/identity_gate.py); the state, the tape and the gradients are bitwise those of the build without the options."""
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
CON_WORDS = 12
|
|
8
|
+
MODES = ("last", "substeps")
|
|
9
|
+
MAX_FEET = 8
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Spec:
|
|
14
|
+
"""A build's contact-force options: mode ("last" / "substeps"), feet (body ids), frame (t1 words), terrain,
|
|
15
|
+
foot_split (the foot and toe-weight words: the forest engine with foot_offset), foot_sand (the sand-fraction word:
|
|
16
|
+
foot_split with TerrainConfig.terrain_sand)."""
|
|
17
|
+
mode: str = "last"
|
|
18
|
+
feet: tuple = ()
|
|
19
|
+
frame: bool = False
|
|
20
|
+
terrain: bool = False
|
|
21
|
+
foot_split: bool = False
|
|
22
|
+
foot_sand: bool = False
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def con_words(self):
|
|
26
|
+
return (CON_WORDS + (3 if self.frame else 0) + (1 if self.terrain else 0) + (2 if self.foot_split else 0)
|
|
27
|
+
+ (1 if self.foot_sand else 0))
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def plain(self):
|
|
31
|
+
"""The original opt-in (the last substep's 12-word table only): the FFI unit keeps its MAXCON * 12 check."""
|
|
32
|
+
return (self.mode == "last" and not self.feet and not self.frame and not self.terrain
|
|
33
|
+
and not self.foot_split)
|
|
34
|
+
|
|
35
|
+
def layout(self):
|
|
36
|
+
"""{name: (offset, width)} of a contact's words."""
|
|
37
|
+
lay = dict(pair=(0, 1), dist=(1, 1), pos=(2, 3), normal=(5, 3), force=(8, 3), force_normal=(11, 1))
|
|
38
|
+
o = CON_WORDS
|
|
39
|
+
if self.frame:
|
|
40
|
+
lay["tangent1"] = (o, 3)
|
|
41
|
+
o += 3
|
|
42
|
+
if self.terrain:
|
|
43
|
+
lay["element"] = (o, 1)
|
|
44
|
+
o += 1
|
|
45
|
+
if self.foot_split:
|
|
46
|
+
lay["foot_side"] = (o, 1)
|
|
47
|
+
lay["toe_weight"] = (o + 1, 1)
|
|
48
|
+
o += 2
|
|
49
|
+
if self.foot_sand:
|
|
50
|
+
lay["sand_k"] = (o, 1)
|
|
51
|
+
return lay
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def width(spec, maxcon, nsub):
|
|
55
|
+
"""Words per world of the contact output for nsub substeps."""
|
|
56
|
+
t = (nsub if spec.mode == "substeps" else 1) * maxcon * spec.con_words
|
|
57
|
+
return t + (nsub * len(spec.feet) * 6 + len(spec.feet) if spec.feet else 0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def as_spec(contact_forces=False, foot_wrench=None, contact_frame=False, terrain=False, m=None, foot_split=False,
|
|
61
|
+
foot_sand=False):
|
|
62
|
+
"""The Spec of init()'s arguments, None for the build without the forces. contact_forces: False / None, True or
|
|
63
|
+
"last", "substeps"; foot_wrench: None / False, True (the G1's left_ankle_roll_link, right_ankle_roll_link) or body
|
|
64
|
+
names / ids (needs m for names); contact_frame: the t1 words; terrain: a terrain build; foot_split: the foot and
|
|
65
|
+
toe-weight words (the forest engine's foot_normal). foot_wrench, contact_frame and foot_split turn the forces on
|
|
66
|
+
("last") when contact_forces is off."""
|
|
67
|
+
if contact_forces is True:
|
|
68
|
+
mode = "last"
|
|
69
|
+
elif not contact_forces:
|
|
70
|
+
mode = None
|
|
71
|
+
elif contact_forces in MODES:
|
|
72
|
+
mode = contact_forces
|
|
73
|
+
else:
|
|
74
|
+
raise ValueError(f"contact_forces={contact_forces!r}: False, True, 'last' or 'substeps'")
|
|
75
|
+
feet = ()
|
|
76
|
+
if foot_wrench is not None and foot_wrench is not False:
|
|
77
|
+
names = ("left_ankle_roll_link", "right_ankle_roll_link") if foot_wrench is True else tuple(foot_wrench)
|
|
78
|
+
if not names or len(names) > MAX_FEET:
|
|
79
|
+
raise ValueError(f"foot_wrench: 1 .. {MAX_FEET} bodies")
|
|
80
|
+
ids = []
|
|
81
|
+
for b in names:
|
|
82
|
+
if isinstance(b, str):
|
|
83
|
+
import mujoco
|
|
84
|
+
assert m is not None
|
|
85
|
+
i = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, b)
|
|
86
|
+
if i < 0:
|
|
87
|
+
raise ValueError(f"foot_wrench: no body {b!r} in the model")
|
|
88
|
+
else:
|
|
89
|
+
i = int(b)
|
|
90
|
+
if m is not None and not 0 < i < m.nbody:
|
|
91
|
+
raise ValueError(f"foot_wrench: body id {i} out of range")
|
|
92
|
+
ids.append(int(i))
|
|
93
|
+
if len(set(ids)) != len(ids) or 0 in ids:
|
|
94
|
+
raise ValueError("foot_wrench: distinct bodies other than the world body")
|
|
95
|
+
feet = tuple(ids)
|
|
96
|
+
if mode is None and (feet or contact_frame or foot_split):
|
|
97
|
+
mode = "last"
|
|
98
|
+
if mode is None:
|
|
99
|
+
return None
|
|
100
|
+
if foot_sand and not (foot_split and terrain):
|
|
101
|
+
raise ValueError("foot_sand: needs foot_split (foot_normal) in a terrain build")
|
|
102
|
+
return Spec(mode, feet, bool(contact_frame), bool(terrain), bool(foot_split), bool(foot_sand))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
_STRUCT_SIM = "struct Sim {\n"
|
|
106
|
+
_STRUCT_SIMN = "struct SimNT {"
|
|
107
|
+
_HAND_BIG = " SimNfull big; // k_post's state"
|
|
108
|
+
_SOLVER = " if (niter_out && lane == 0) *niter_out = it;\n"
|
|
109
|
+
_FORCES = r""" if (s.ocf) { // contact_forces: the contacts' forces at the solution (contact_forces.py)
|
|
110
|
+
for (int r = lane; r < s.nefc; r += 32) {
|
|
111
|
+
float ds, dd, cst;
|
|
112
|
+
row_eval(s, r, s.efc_jar[r], &ds, &dd, &cst);
|
|
113
|
+
s.efc_jv[r] = -ds;
|
|
114
|
+
}
|
|
115
|
+
__syncwarp();
|
|
116
|
+
const int nc = min(s.ncon, MAXCON);
|
|
117
|
+
for (int c = lane; c < nc; c += 32) {
|
|
118
|
+
float g[4] = {0.f, 0.f, 0.f, 0.f};
|
|
119
|
+
con_force(s, s.efc_jv, c, g);
|
|
120
|
+
float* o = s.ocf + (size_t)c * CON_WORDS;
|
|
121
|
+
o[8] = g[0]; o[9] = g[1]; o[10] = g[2]; o[11] = g[3]; // frame forces, torsion (cf_finish rotates them)
|
|
122
|
+
}
|
|
123
|
+
__syncwarp();
|
|
124
|
+
}
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
_HOST_HEAD = "// tape: null, or nw * nsub records of REC_WORDS (tape.py), record w * nsub + k for world w and substep k\n"
|
|
128
|
+
_HOST_FUNCS = r"""// ---- contact_forces (contact_forces.py): the contact output of a world: CF_T tables of MAXCON * CON_WORDS words
|
|
129
|
+
// (CF_SUB: one per substep, else the last substep's), then with CF_NFOOT feet nsub * CF_NFOOT * 6 wrench words and
|
|
130
|
+
// CF_NFOOT maxima of the feet's normal force
|
|
131
|
+
#define CF_T(nsub) (CF_SUB ? (size_t)(nsub) : (size_t)1)
|
|
132
|
+
__device__ __forceinline__ size_t cf_stride(int nsub) {
|
|
133
|
+
return CF_T(nsub) * MAXCON * CON_WORDS + (CF_NFOOT ? (size_t)nsub * CF_NFOOT * 6 + CF_NFOOT : 0);
|
|
134
|
+
}
|
|
135
|
+
__device__ __forceinline__ float* cf_tab(float* ocon, int w, int k, int nsub) { // substep k's table
|
|
136
|
+
return ocon + (size_t)w * cf_stride(nsub) + (CF_SUB ? (size_t)k * MAXCON * CON_WORDS : 0);
|
|
137
|
+
}
|
|
138
|
+
__device__ __forceinline__ bool cf_on(int k, int nsub) { return CF_SUB || CF_NFOOT || k == nsub - 1; } // forces
|
|
139
|
+
__device__ __forceinline__ bool cf_wr(int k, int nsub) { return CF_SUB || k == nsub - 1; } // the other words
|
|
140
|
+
#if CF_NFOOT
|
|
141
|
+
__device__ __forceinline__ int cf_foot(int i) {
|
|
142
|
+
constexpr int fb[CF_NFOOT] = CF_FEET;
|
|
143
|
+
return fb[i];
|
|
144
|
+
}
|
|
145
|
+
#endif
|
|
146
|
+
// a substep's table words other than the forces (pair, dist, pos, normal, t1, element) from its collision; the force
|
|
147
|
+
// words of the slots past the world's contacts zero
|
|
148
|
+
template <class S>
|
|
149
|
+
__device__ __forceinline__ void cf_write(float* tab, const S& s, int ncon, int lane) {
|
|
150
|
+
for (int c = lane; c < MAXCON; c += 32) {
|
|
151
|
+
float* o = tab + (size_t)c * CON_WORDS;
|
|
152
|
+
const bool v = c < ncon;
|
|
153
|
+
o[0] = v ? (float)s.con_pair[c] : -1.f; o[1] = v ? s.con_dist[c] : 0.f;
|
|
154
|
+
for (int t = 0; t < 3; t++) { o[2 + t] = v ? s.con_pos[c][t] : 0.f; o[5 + t] = v ? s.con_frame[c][t] : 0.f; }
|
|
155
|
+
#if CF_FRAME
|
|
156
|
+
for (int t = 0; t < 3; t++) o[CF_T1 + t] = v ? s.con_frame[c][3 + t] : 0.f;
|
|
157
|
+
#endif
|
|
158
|
+
#if CF_TERRAIN
|
|
159
|
+
o[CF_ELEM] = v && s.con_pair[c] >= NPAIR ? (float)s.con_elem[c] : -1.f;
|
|
160
|
+
#endif
|
|
161
|
+
if (!v) for (int t = 8; t < 12; t++) o[t] = 0.f;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// after a substep whose forces were wanted: the frame forces (words 8 .. 10) into world coordinates, f_n into word 11,
|
|
165
|
+
// and with feet the substep's wrench of each foot (xf: the feet's body origins, CF_NFOOT * 3) about its body origin;
|
|
166
|
+
// tab: the substep's table, k: the substep
|
|
167
|
+
__device__ __forceinline__ void cf_finish(float* tab, int ncon, const int* pair, const float (*pos)[3],
|
|
168
|
+
const float (*fr)[9], const float* xf, int k, int nsub, int lane) {
|
|
169
|
+
#if CF_NFOOT
|
|
170
|
+
float acc[CF_NFOOT][7];
|
|
171
|
+
#pragma unroll
|
|
172
|
+
for (int i = 0; i < CF_NFOOT; i++)
|
|
173
|
+
#pragma unroll
|
|
174
|
+
for (int j = 0; j < 7; j++) acc[i][j] = 0.f;
|
|
175
|
+
#endif
|
|
176
|
+
for (int c = lane; c < ncon; c += 32) {
|
|
177
|
+
float* o = tab + (size_t)c * CON_WORDS;
|
|
178
|
+
const float f0 = o[8], f1 = o[9], f2 = o[10], tq = o[11];
|
|
179
|
+
float fw[3];
|
|
180
|
+
for (int j = 0; j < 3; j++) fw[j] = f0 * fr[c][j] + f1 * fr[c][3 + j] + f2 * fr[c][6 + j];
|
|
181
|
+
for (int j = 0; j < 3; j++) o[8 + j] = fw[j];
|
|
182
|
+
o[11] = f0;
|
|
183
|
+
#if CF_NFOOT
|
|
184
|
+
const int pr = pair[c], b1 = c_gbody[PG1(pr)], b2 = c_gbody[PG2(pr)];
|
|
185
|
+
#pragma unroll
|
|
186
|
+
for (int i = 0; i < CF_NFOOT; i++) {
|
|
187
|
+
const float sg = b2 == cf_foot(i) ? 1.f : (b1 == cf_foot(i) ? -1.f : 0.f); // on the foot: + on geom 2
|
|
188
|
+
if (sg == 0.f) continue;
|
|
189
|
+
float f[3], r[3];
|
|
190
|
+
for (int j = 0; j < 3; j++) { f[j] = sg * fw[j]; r[j] = pos[c][j] - xf[3 * i + j]; }
|
|
191
|
+
acc[i][0] += f[0]; acc[i][1] += f[1]; acc[i][2] += f[2];
|
|
192
|
+
acc[i][3] += r[1] * f[2] - r[2] * f[1] + sg * tq * fr[c][0];
|
|
193
|
+
acc[i][4] += r[2] * f[0] - r[0] * f[2] + sg * tq * fr[c][1];
|
|
194
|
+
acc[i][5] += r[0] * f[1] - r[1] * f[0] + sg * tq * fr[c][2];
|
|
195
|
+
acc[i][6] += f0;
|
|
196
|
+
}
|
|
197
|
+
#endif
|
|
198
|
+
}
|
|
199
|
+
#if CF_NFOOT
|
|
200
|
+
#pragma unroll
|
|
201
|
+
for (int i = 0; i < CF_NFOOT; i++)
|
|
202
|
+
#pragma unroll
|
|
203
|
+
for (int j = 0; j < 7; j++)
|
|
204
|
+
#pragma unroll
|
|
205
|
+
for (int sh = 16; sh > 0; sh >>= 1) acc[i][j] += __shfl_xor_sync(0xffffffffu, acc[i][j], sh);
|
|
206
|
+
if (lane == 0) {
|
|
207
|
+
float* wr = tab - (CF_SUB ? (size_t)k * MAXCON * CON_WORDS : 0) + CF_T(nsub) * MAXCON * CON_WORDS;
|
|
208
|
+
#pragma unroll
|
|
209
|
+
for (int i = 0; i < CF_NFOOT; i++) {
|
|
210
|
+
for (int j = 0; j < 6; j++) wr[((size_t)k * CF_NFOOT + i) * 6 + j] = acc[i][j];
|
|
211
|
+
float* mx = wr + (size_t)nsub * CF_NFOOT * 6 + i;
|
|
212
|
+
*mx = k ? fmaxf(*mx, acc[i][6]) : acc[i][6];
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
#endif
|
|
216
|
+
__syncwarp();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
"""
|
|
220
|
+
|
|
221
|
+
_KSUB_LOOP = """ for (int k = 0; k < nsub; k++)
|
|
222
|
+
substep(s, ctrl + (size_t)w * (NV - 6), iterations, lane, &nit,
|
|
223
|
+
tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);
|
|
224
|
+
"""
|
|
225
|
+
_KSUB_LOOP_NEW = """ for (int k = 0; k < nsub; k++) {
|
|
226
|
+
if (lane == 0) s.ocf = cf_on(k, nsub) ? cf_tab(ocon, w, k, nsub) : nullptr; // (contact_forces)
|
|
227
|
+
__syncwarp();
|
|
228
|
+
substep(s, ctrl + (size_t)w * (NV - 6), iterations, lane, &nit,
|
|
229
|
+
tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);
|
|
230
|
+
__syncwarp();
|
|
231
|
+
if (s.ocf) {
|
|
232
|
+
float xf[CF_NFOOT ? 3 * CF_NFOOT : 1];
|
|
233
|
+
#if CF_NFOOT
|
|
234
|
+
for (int i = 0; i < 3 * CF_NFOOT; i++) xf[i] = s.X[cf_foot(i / 3)][i % 3];
|
|
235
|
+
#endif
|
|
236
|
+
cf_finish(s.ocf, min(s.ncon, MAXCON), s.con_pair, s.con_pos, s.con_frame, xf, k, nsub, lane);
|
|
237
|
+
if (k < nsub - 1 && cf_wr(k, nsub)) cf_write(s.ocf, s, min(s.ncon, MAXCON), lane);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
"""
|
|
241
|
+
_KSUB_WRITE = """ for (int c = lane; c < MAXCON; c += 32) { // contacts of the last substep's collision: pair, dist, pos, normal
|
|
242
|
+
float* o = ocon + ((size_t)w * MAXCON + c) * 8;
|
|
243
|
+
bool v = c < min(s.ncon, MAXCON);
|
|
244
|
+
o[0] = v ? (float)s.con_pair[c] : -1.f; o[1] = v ? s.con_dist[c] : 0.f;
|
|
245
|
+
for (int k = 0; k < 3; k++) { o[2 + k] = v ? s.con_pos[c][k] : 0.f; o[5 + k] = v ? s.con_frame[c][k] : 0.f; }
|
|
246
|
+
}
|
|
247
|
+
"""
|
|
248
|
+
_KSUB_WRITE_NEW = """ cf_write(cf_tab(ocon, w, nsub - 1, nsub), s, min(s.ncon, MAXCON), lane); // (contact_forces: the forces are in)
|
|
249
|
+
"""
|
|
250
|
+
_PRE_PTR = " substep_pre(s, ctrl + (size_t)w * (NV - 6), lane, tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);\n"
|
|
251
|
+
_PRE_PTR_NEW = (" if (lane == 0) g.ocf = cf_on(k, nsub) ? cf_tab(ocon, w, k, nsub) : nullptr; // (contact_forces)\n"
|
|
252
|
+
+ _PRE_PTR
|
|
253
|
+
+ "#if CF_NFOOT\n"
|
|
254
|
+
" if (lane < 3 * CF_NFOOT) g.cf_x[lane] = s.X[cf_foot(lane / 3)][lane % 3]; // (the feet's origins)\n"
|
|
255
|
+
"#endif\n")
|
|
256
|
+
_PRE_WRITE = """ if (k == nsub - 1) // contacts of the last substep's collision: pair, dist, pos, normal
|
|
257
|
+
for (int c = lane; c < MAXCON; c += 32) {
|
|
258
|
+
float* o = ocon + ((size_t)w * MAXCON + c) * 8;
|
|
259
|
+
bool v = c < ncon;
|
|
260
|
+
o[0] = v ? (float)s.con_pair[c] : -1.f; o[1] = v ? s.con_dist[c] : 0.f;
|
|
261
|
+
for (int t = 0; t < 3; t++) { o[2 + t] = v ? s.con_pos[c][t] : 0.f; o[5 + t] = v ? s.con_frame[c][t] : 0.f; }
|
|
262
|
+
}
|
|
263
|
+
"""
|
|
264
|
+
_PRE_WRITE_NEW = """ if (cf_wr(k, nsub)) cf_write(cf_tab(ocon, w, k, nsub), s, ncon, lane); // (contact_forces: forces in k_post)
|
|
265
|
+
"""
|
|
266
|
+
_POST_PTR = " s.min_nu_bits = g.min_nu_bits;\n s.qpos = q;"
|
|
267
|
+
_POST_PTR_NEW = " s.min_nu_bits = g.min_nu_bits;\n s.ocf = g.ocf; // (contact_forces)\n s.qpos = q;"
|
|
268
|
+
_POST_WRITE = " substep_post(s, iterations, lane, &nit, tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);\n"
|
|
269
|
+
_POST_WRITE_NEW = _POST_WRITE + """ __syncwarp();
|
|
270
|
+
if (g.ocf) // (contact_forces) the forces into world coordinates, the feet's wrenches
|
|
271
|
+
#if CF_NFOOT
|
|
272
|
+
cf_finish(g.ocf, ncon, g.con_pair, g.con_pos, g.con_frame, g.cf_x, k, nsub, lane);
|
|
273
|
+
#else
|
|
274
|
+
cf_finish(g.ocf, ncon, g.con_pair, g.con_pos, g.con_frame, nullptr, k, nsub, lane);
|
|
275
|
+
#endif
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _sub(src, old, new, count, what):
|
|
280
|
+
n = src.count(old)
|
|
281
|
+
assert n == count, f"contact_forces: {what}: {n} anchors, expected {count}"
|
|
282
|
+
return src.replace(old, new)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def engine(src, spec=None):
|
|
286
|
+
"""The engine text (adjoint.cuda_source) with the contact forces: the defines, the pointers, the solver tail."""
|
|
287
|
+
spec = spec or Spec()
|
|
288
|
+
if spec.foot_split:
|
|
289
|
+
raise ValueError("foot_normal (the foot_split words): the forest engine only (this model goes to the tree "
|
|
290
|
+
"engine; engines.prefer_forest or DK_ENGINE=forest)")
|
|
291
|
+
src = _sub(src, _STRUCT_SIM, _STRUCT_SIM + " float* ocf; // contact_forces: the world's contact table of the "
|
|
292
|
+
"substep, else null\n", 1, "struct Sim")
|
|
293
|
+
src = _sub(src, _STRUCT_SIMN, _STRUCT_SIMN + "\n float* ocf; // contact_forces (Hand::ocf)\n ", 1, "struct SimNT")
|
|
294
|
+
hand = " float* ocf; // contact_forces: k_pre's table pointer for k_post (null: not wanted)\n"
|
|
295
|
+
if spec.feet:
|
|
296
|
+
hand += " float cf_x[3 * CF_NFOOT]; // contact_forces: the feet's body origins of the substep (k_pre)\n"
|
|
297
|
+
src = _sub(src, _HAND_BIG, hand + _HAND_BIG, 1, "Hand")
|
|
298
|
+
src = _sub(src, _SOLVER, _SOLVER + _FORCES, 1, "the solver's tail")
|
|
299
|
+
defs = [f"#define CON_WORDS {spec.con_words} // the contact table per contact, with the forces (contact_forces.py)",
|
|
300
|
+
f"#define CF_SUB {int(spec.mode == 'substeps')} // a table per substep",
|
|
301
|
+
f"#define CF_NFOOT {len(spec.feet)} // feet with wrenches",
|
|
302
|
+
f"#define CF_FRAME {int(spec.frame)} // the tangent t1's words",
|
|
303
|
+
f"#define CF_TERRAIN {int(spec.terrain)} // the terrain element's word"]
|
|
304
|
+
lay = spec.layout()
|
|
305
|
+
if spec.frame:
|
|
306
|
+
defs.append(f"#define CF_T1 {lay['tangent1'][0]}")
|
|
307
|
+
if spec.terrain:
|
|
308
|
+
defs.append(f"#define CF_ELEM {lay['element'][0]}")
|
|
309
|
+
if spec.feet:
|
|
310
|
+
defs.append("#define CF_FEET {" + ", ".join(str(b) for b in spec.feet) + "} // the feet's body ids")
|
|
311
|
+
return "\n".join(defs) + "\n" + src
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def host(src, spec=None):
|
|
315
|
+
"""The host kernels' text (host.KERNEL) with the contact table's forces and the options of spec."""
|
|
316
|
+
src = _sub(src, _HOST_HEAD, _HOST_FUNCS + _HOST_HEAD, 1, "the host functions")
|
|
317
|
+
src = _sub(src, _KSUB_LOOP, _KSUB_LOOP_NEW, 1, "k_substep's loop")
|
|
318
|
+
src = _sub(src, _KSUB_WRITE, _KSUB_WRITE_NEW, 1, "k_substep's table")
|
|
319
|
+
src = _sub(src, _PRE_PTR, _PRE_PTR_NEW, 1, "pre_world's pointer")
|
|
320
|
+
src = _sub(src, _PRE_WRITE, _PRE_WRITE_NEW, 1, "pre_world's table")
|
|
321
|
+
src = _sub(src, _POST_PTR, _POST_PTR_NEW, 1, "post_world_on's pointer")
|
|
322
|
+
src = _sub(src, _POST_WRITE, _POST_WRITE_NEW, 1, "post_world_on's forces")
|
|
323
|
+
return src
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def ffi(src, spec):
|
|
327
|
+
"""The FFI unit's contact output check: (B, MAXCON * W) for the plain opt-in, else (B, CF_WIDTH(substeps))."""
|
|
328
|
+
if spec.plain:
|
|
329
|
+
assert src.count("MAXCON * 8") >= 2
|
|
330
|
+
return src.replace("MAXCON * 8", f"MAXCON * {spec.con_words}")
|
|
331
|
+
nf = len(spec.feet)
|
|
332
|
+
t = "(int64_t)substeps * " if spec.mode == "substeps" else ""
|
|
333
|
+
w = f"({t}MAXCON * {spec.con_words}" + (f" + (int64_t)substeps * {6 * nf} + {nf}" if nf else "") + ")"
|
|
334
|
+
old = 'if (!dims_are(*con, {B, MAXCON * 8})) return bad("contact output must be (B, MAXCON * 8) float32");'
|
|
335
|
+
new = (f'if (!dims_are(*con, {{B, {w}}})) return bad("contact output must be (B, contact_forces width) float32 '
|
|
336
|
+
f'(g1_engine.contact_forces.width)");')
|
|
337
|
+
return _sub(src, old, new, 1, "the FFI's contact output")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def substeps_of(info, ncol):
|
|
341
|
+
"""The substep count of a contact output with ncol words per world (None where the layout does not depend on it)."""
|
|
342
|
+
cf, mc, cw = info.get("contact_forces"), int(info["maxcon"]), int(info.get("con_words", 8))
|
|
343
|
+
nf = len(cf["feet"]) if cf else 0
|
|
344
|
+
if cf and cf["mode"] == "substeps":
|
|
345
|
+
n, r = divmod(ncol - nf, mc * cw + 6 * nf)
|
|
346
|
+
elif nf:
|
|
347
|
+
n, r = divmod(ncol - mc * cw - nf, 6 * nf)
|
|
348
|
+
else:
|
|
349
|
+
return None
|
|
350
|
+
if r or n < 1:
|
|
351
|
+
raise ValueError(f"a contact output of {ncol} words per world does not fit this build's layout")
|
|
352
|
+
return n
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
SAND_EPS = 1e-3
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def decode(con, info, substeps=None, sand=None):
|
|
359
|
+
"""The contact output (B, width) as a dict of arrays (NumPy, JAX or torch: reshape and slicing only); pair stays
|
|
360
|
+
a float array (the interfaces convert it). See jax_ffi.contact_table. sand: a foot_sand build's elements' sand
|
|
361
|
+
fields (n elements, 4: k, s_max, F_y, rate; Terrain.sand_array) for foot_sand_params (None: not returned)."""
|
|
362
|
+
B, ncol = con.shape[0], con.shape[1]
|
|
363
|
+
cf, mc, cw = info.get("contact_forces"), int(info["maxcon"]), int(info.get("con_words", 8))
|
|
364
|
+
n = substeps if substeps is not None else substeps_of(info, ncol)
|
|
365
|
+
sub = bool(cf) and cf["mode"] == "substeps"
|
|
366
|
+
nt = n if sub else 1
|
|
367
|
+
if cf and n is not None and ncol != width(Spec(cf["mode"], tuple(cf["feet"]), cf["frame"], cf["terrain"],
|
|
368
|
+
bool(cf.get("foot_split", False)),
|
|
369
|
+
bool(cf.get("foot_sand", False))), mc, n):
|
|
370
|
+
raise ValueError(f"a contact output of {ncol} words per world, not this build's for {n} substeps")
|
|
371
|
+
c = con[:, :nt * mc * cw].reshape((B, nt, mc, cw) if sub else (B, mc, cw))
|
|
372
|
+
out = dict(pair=c[..., 0], dist=c[..., 1], pos=c[..., 2:5], normal=c[..., 5:8])
|
|
373
|
+
if cw >= 12:
|
|
374
|
+
out["force"], out["force_normal"] = c[..., 8:11], c[..., 11]
|
|
375
|
+
lay = (cf or {}).get("con_layout", {})
|
|
376
|
+
if "tangent1" in lay:
|
|
377
|
+
o = lay["tangent1"][0]
|
|
378
|
+
t1, nn = c[..., o:o + 3], out["normal"]
|
|
379
|
+
n0, n1, n2, a0, a1, a2 = nn[..., 0], nn[..., 1], nn[..., 2], t1[..., 0], t1[..., 1], t1[..., 2]
|
|
380
|
+
t2 = [n1 * a2 - n2 * a1, n2 * a0 - n0 * a2, n0 * a1 - n1 * a0]
|
|
381
|
+
f = out["force"]
|
|
382
|
+
out["tangent1"] = t1
|
|
383
|
+
out["tangent2"] = _stack(t2, t1)
|
|
384
|
+
out["force_t1"] = f[..., 0] * a0 + f[..., 1] * a1 + f[..., 2] * a2
|
|
385
|
+
out["force_t2"] = f[..., 0] * t2[0] + f[..., 1] * t2[1] + f[..., 2] * t2[2]
|
|
386
|
+
if "element" in lay:
|
|
387
|
+
out["element"] = c[..., lay["element"][0]]
|
|
388
|
+
if "foot_side" in lay:
|
|
389
|
+
side, w, fn = c[..., lay["foot_side"][0]], c[..., lay["toe_weight"][0]], out["force_normal"]
|
|
390
|
+
out["foot_side"], out["toe_weight"] = side, w
|
|
391
|
+
cols = []
|
|
392
|
+
for k in (0, 1):
|
|
393
|
+
on = fn * (side == k)
|
|
394
|
+
cols += [(on * (1 - w)).sum(-1), (on * w).sum(-1)]
|
|
395
|
+
out["foot_normal"] = _stack(cols, fn)
|
|
396
|
+
if "sand_k" in lay:
|
|
397
|
+
_sand_outputs(out, c, lay, (info.get("terrain") or {}).get("sand_other"), sand)
|
|
398
|
+
if cf and cf["feet"]:
|
|
399
|
+
nf = len(cf["feet"])
|
|
400
|
+
wr = con[:, nt * mc * cw:]
|
|
401
|
+
w6 = wr[:, :n * nf * 6].reshape((B, n, nf, 6))
|
|
402
|
+
out["foot_force"], out["foot_moment"] = w6[..., 0:3], w6[..., 3:6]
|
|
403
|
+
out["foot_fn_max"] = wr[:, n * nf * 6:]
|
|
404
|
+
f = out["foot_force"]
|
|
405
|
+
out["foot_fnet_max"] = _amax1((f[..., 0] ** 2 + f[..., 1] ** 2 + f[..., 2] ** 2) ** 0.5)
|
|
406
|
+
out["foot_fup_max"] = _amax1(f[..., 2])
|
|
407
|
+
return out
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _sand_outputs(out, c, lay, other, sand):
|
|
411
|
+
side, w, fn = out["foot_side"], out["toe_weight"], out["force_normal"]
|
|
412
|
+
k = c[..., lay["sand_k"][0]]
|
|
413
|
+
out["sand_k"] = k
|
|
414
|
+
sp, hp, pr, wts = [], [], [], []
|
|
415
|
+
for f in (0, 1):
|
|
416
|
+
on = side == f
|
|
417
|
+
for part in (1 - w, w):
|
|
418
|
+
a = on * part
|
|
419
|
+
sp.append((fn * k * a).sum(-1))
|
|
420
|
+
hp.append((fn * (1 - k) * a).sum(-1))
|
|
421
|
+
pr.append((k * a).sum(-1))
|
|
422
|
+
wts.append((fn * k * a, k * a))
|
|
423
|
+
sand_part, hard_part = _stack(sp, fn), _stack(hp, fn)
|
|
424
|
+
sh = _stack([sand_part, hard_part], fn)
|
|
425
|
+
out["foot_normal_split"] = sh.transpose(-1, -2) if hasattr(sh, "new_zeros") else sh.swapaxes(-1, -2)
|
|
426
|
+
out["foot_sand_presence"] = _stack(pr, fn)
|
|
427
|
+
if sand is None:
|
|
428
|
+
return
|
|
429
|
+
other = tuple(other) if other is not None else (1.0, 0.0, 0.0, 0.0)
|
|
430
|
+
torch = hasattr(fn, "new_zeros")
|
|
431
|
+
if torch:
|
|
432
|
+
import torch as _t
|
|
433
|
+
tab = _t.as_tensor(sand, dtype=fn.dtype, device=fn.device).reshape(-1, 4)
|
|
434
|
+
tab = _t.cat([tab, _t.as_tensor([other], dtype=fn.dtype, device=fn.device)], 0)
|
|
435
|
+
stop = lambda x: x.detach()
|
|
436
|
+
elif type(fn).__module__.startswith("numpy"):
|
|
437
|
+
import numpy as _np
|
|
438
|
+
tab = _np.concatenate([_np.asarray(sand, fn.dtype).reshape(-1, 4), _np.asarray([other], fn.dtype)], 0)
|
|
439
|
+
stop = lambda x: x
|
|
440
|
+
else:
|
|
441
|
+
import jax
|
|
442
|
+
import jax.numpy as jnp
|
|
443
|
+
tab = jnp.concatenate([jnp.asarray(sand, fn.dtype).reshape(-1, 4), jnp.asarray([other], fn.dtype)], 0)
|
|
444
|
+
stop = jax.lax.stop_gradient
|
|
445
|
+
n = tab.shape[0] - 1
|
|
446
|
+
e = c[..., lay["element"][0]]
|
|
447
|
+
ok = (e >= 0) & (e < n)
|
|
448
|
+
idx = ok * e + (1 - ok * 1) * n
|
|
449
|
+
idx = idx.long() if torch else idx.astype("int32")
|
|
450
|
+
par = tab[idx][..., 1:]
|
|
451
|
+
cols = []
|
|
452
|
+
for wf, wk in wts:
|
|
453
|
+
wf, wk = stop(wf), stop(wk)
|
|
454
|
+
sf, sk = wf.sum(-1), wk.sum(-1)
|
|
455
|
+
use = sf >= SAND_EPS
|
|
456
|
+
wt = use[..., None] * wf + (1 - use[..., None] * 1) * wk
|
|
457
|
+
tot = use * sf + (1 - use * 1) * sk
|
|
458
|
+
num = (wt[..., None] * par).sum(-2)
|
|
459
|
+
cols.append(num / (tot + (tot <= 0))[..., None] * (tot > 0)[..., None])
|
|
460
|
+
p = _stack(cols, fn)
|
|
461
|
+
if torch:
|
|
462
|
+
p = p.transpose(-1, -2)
|
|
463
|
+
else:
|
|
464
|
+
p = p.swapaxes(-1, -2)
|
|
465
|
+
out["foot_sand_params"] = stop(p.reshape(p.shape[:-2] + (2, 2, 3)))
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _amax1(x):
|
|
469
|
+
if hasattr(x, "new_zeros"):
|
|
470
|
+
return x.amax(1)
|
|
471
|
+
return x.max(1)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _stack(cols, like):
|
|
475
|
+
if hasattr(like, "new_zeros"):
|
|
476
|
+
import torch
|
|
477
|
+
return torch.stack(cols, -1)
|
|
478
|
+
if type(like).__module__.startswith("numpy"):
|
|
479
|
+
import numpy as np
|
|
480
|
+
return np.stack(cols, -1)
|
|
481
|
+
import jax.numpy as jnp
|
|
482
|
+
return jnp.stack(cols, -1)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def pair_geoms(m, foot_pairs=(), terrain=None):
|
|
486
|
+
"""(npair + terrain pairs, 2) model geom ids of each contact pair id of the table, in the engine's geom order (the
|
|
487
|
+
force words are the force on column 1's geom, the normal points from column 0's to column 1's): a model pair p
|
|
488
|
+
is (pair_geom1, pair_geom2) swapped where geom 1's type comes after geom 2's in MuJoCo's type order (a plane
|
|
489
|
+
first, then sphere, capsule, ..., as MuJoCo's collision table; g1_engine.step.pair_constants); a terrain build's
|
|
490
|
+
virtual pair npair + t is (-1: the terrain or an object slot, the robot geom of terrain.robot_terrain_geoms' t-th
|
|
491
|
+
entry). terrain: the build's TerrainConfig."""
|
|
492
|
+
import numpy as np
|
|
493
|
+
out = []
|
|
494
|
+
for p in range(m.npair):
|
|
495
|
+
g1, g2 = int(m.pair_geom1[p]), int(m.pair_geom2[p])
|
|
496
|
+
out.append((g2, g1) if int(m.geom_type[g1]) > int(m.geom_type[g2]) else (g1, g2))
|
|
497
|
+
if terrain is not None:
|
|
498
|
+
from nablaengine import terrain as _terrain
|
|
499
|
+
out += [(-1, int(g)) for g, _, _ in _terrain.robot_terrain_geoms(m, foot_pairs, terrain.geoms)]
|
|
500
|
+
return np.asarray(out, np.int64).reshape(-1, 2)
|