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,521 @@
|
|
|
1
|
+
"""The G1's sensors in JAX (work in progress): G1Sensors casts the D435i depth camera, the MID-360 LiDAR and the
|
|
2
|
+
height scan on a batch of states (body poses from nablaengine.jax_ffi.kinematics) against the scene (terrain, per-world
|
|
3
|
+
objects, the robot's own visual meshes), with optional noise. Under jit; no gradient by default, first-order
|
|
4
|
+
gradients w.r.t. the body poses and object poses with grad="first_order" (raygrad)."""
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import mujoco
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from nablaengine.sensors import cameras, jax_rays, raycore, raygrad, robot_mesh
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _einsum(*args):
|
|
14
|
+
import jax
|
|
15
|
+
import jax.numpy as jnp
|
|
16
|
+
return jnp.einsum(*args, precision=jax.lax.Precision.HIGHEST)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class DepthNoise:
|
|
21
|
+
"""The depth noise model (RealSense-like; parameters to be fitted to the real camera): z-proportional-squared
|
|
22
|
+
Gaussian sigma = sigma_z2 z^2, random pixel dropout, dropout at depth discontinuities (|dz| to a 4-neighbour above
|
|
23
|
+
edge_jump, kept with probability 1 - edge_drop); invalid pixels are 0."""
|
|
24
|
+
sigma_z2: float = 0.001
|
|
25
|
+
dropout: float = 0.01
|
|
26
|
+
edge_jump: float = 0.1
|
|
27
|
+
edge_drop: float = 0.5
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Shading:
|
|
32
|
+
"""The RGB camera's shading (G1Sensors(rgb=...)): each hit's colour by what it hit (the robot's visual meshes:
|
|
33
|
+
their MJCF rgba; terrain boxes, heightfields, the floor plane, object slots: these colours, or per-element arrays
|
|
34
|
+
box_rgb (nbox, 3), hf_rgb (nhf, 3), object_rgb (K, 3)), lit by a directional light (light_dir: the light's
|
|
35
|
+
travel direction, world) with Lambert's cosine plus an ambient term; sky for no hit. No shadows, no textures."""
|
|
36
|
+
light_dir: tuple = (-0.3, -0.2, -0.93)
|
|
37
|
+
ambient: float = 0.35
|
|
38
|
+
diffuse: float = 0.65
|
|
39
|
+
sky: tuple = (0.62, 0.74, 0.88)
|
|
40
|
+
box: tuple = (0.62, 0.58, 0.52)
|
|
41
|
+
hfield: tuple = (0.46, 0.50, 0.40)
|
|
42
|
+
floor: tuple = (0.55, 0.55, 0.55)
|
|
43
|
+
obj: tuple = (0.80, 0.35, 0.20)
|
|
44
|
+
box_rgb: object = None
|
|
45
|
+
hf_rgb: object = None
|
|
46
|
+
object_rgb: object = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class G1Sensors:
|
|
50
|
+
def __init__(self, model, terrain=None, robot_mjcf=None, depth=cameras.D435I_DEPTH, lidar=None,
|
|
51
|
+
height_scan=cameras.HeightScan(), housing=0.03, cell=1.0, floor_z=None, mesh_cache=None,
|
|
52
|
+
backend="software", rgb=None, shading=None, grad="none", grad_impl="fused", robot_geometry="visual",
|
|
53
|
+
mesh_simplify=0.0, rgb_seg=False):
|
|
54
|
+
"""model: the engine's MjModel (the bodies the poses refer to); robot_mjcf: an MJCF with the robot's visual
|
|
55
|
+
meshes (geom group 2) on bodies of the same names (None: the robot is not seen); housing: the clearance in
|
|
56
|
+
front of each sensor (hits nearer are ignored: its own housing). depth / lidar / height_scan: None to skip.
|
|
57
|
+
backend: the ray backend (jax_rays.setup): "software" (the CUDA kernels, the default), "optix" (the optional
|
|
58
|
+
OptiX backend: RT cores, an OptiX SDK at $OPTIX_ROOT) or "auto" (OptiX where $OPTIX_ROOT is set). rgb: a
|
|
59
|
+
pinhole camera (e.g. cameras.D435I_COLOR.with_resolution(w, h)) rendered as shaded geometry (shading: a
|
|
60
|
+
Shading, default Shading()). grad: "none" (no gradient, the default), "first_order" (the hit plane's
|
|
61
|
+
gradient w.r.t. xpos, xquat and objects: sensors/raygrad; rgb: the shading of turning surfaces) or
|
|
62
|
+
("smoothed", sigma) (depth, height scan, rgb: the gradient of the image smoothed by a Gaussian of sigma pixels /
|
|
63
|
+
grid cells, edges included; raygrad), for all sensors or per sensor as a dict {"depth": ..., "lidar": ...,
|
|
64
|
+
"height_scan": ..., "rgb": ...} (missing: "none"; the LiDAR: "none" or "first_order", a global
|
|
65
|
+
("smoothed", sigma) gives it "first_order"). The forward outputs do not depend on it. grad_impl: "fused"
|
|
66
|
+
(reverse mode by the fused CUDA backward, the default) or "xla" (custom JVPs in XLA: forward and reverse
|
|
67
|
+
mode). robot_geometry: what the rays see of the robot: "visual" (robot_mjcf's visual meshes, the default) or
|
|
68
|
+
"collision" (the model's collision geoms tessellated, robot_mesh.from_collision: cheaper, coarser; robot_mjcf
|
|
69
|
+
not needed); mesh_simplify > 0: the visual meshes simplified by vertex clustering at that cell size in metres
|
|
70
|
+
(robot_mesh.cluster; default 0: as loaded). rgb_seg: also return the RGB cast's hit ids and z-depth
|
|
71
|
+
(rgb_seg (B, H, W), rgb_depth (B, H, W) within the rgb camera's [min_depth, max_depth], 0 invalid) with
|
|
72
|
+
grad["rgb"] "none" (default False: not returned). Changing these changes the outputs; their defaults are
|
|
73
|
+
bitwise as before."""
|
|
74
|
+
import jax
|
|
75
|
+
self.m, self.depth, self.lidar, self.hs, self.housing = model, depth, lidar, height_scan, housing
|
|
76
|
+
self.rgb = rgb
|
|
77
|
+
names = ("depth", "lidar", "height_scan", "rgb")
|
|
78
|
+
if isinstance(grad, dict) and set(grad) - set(names):
|
|
79
|
+
raise ValueError(f"grad: unknown sensors {sorted(set(grad) - set(names))}")
|
|
80
|
+
self.grad = {k: grad.get(k, "none") for k in names} if isinstance(grad, dict) else dict.fromkeys(names, grad)
|
|
81
|
+
if not isinstance(grad, dict) and self.grad["lidar"] != "none":
|
|
82
|
+
self.grad["lidar"] = "first_order"
|
|
83
|
+
for k, v in self.grad.items():
|
|
84
|
+
sm = isinstance(v, tuple) and len(v) == 2 and v[0] == "smoothed" and float(v[1]) >= 0
|
|
85
|
+
if not (v in ("none", "first_order") or (sm and k != "lidar")):
|
|
86
|
+
raise ValueError(f"grad[{k!r}] = {v!r}: 'none', 'first_order' or ('smoothed', sigma) (not the LiDAR)")
|
|
87
|
+
self.grad_impl = grad_impl
|
|
88
|
+
if robot_geometry == "collision":
|
|
89
|
+
first = next((s for s in (depth, rgb, lidar) if s is not None), None)
|
|
90
|
+
rob = robot_mesh.from_collision(model, body=first.body if first is not None else None)
|
|
91
|
+
elif robot_geometry != "visual":
|
|
92
|
+
raise ValueError(f"robot_geometry {robot_geometry!r}: 'visual' or 'collision'")
|
|
93
|
+
elif robot_mjcf and mesh_simplify:
|
|
94
|
+
rob = robot_mesh.load(robot_mjcf, model, cache=mesh_cache, simplify=float(mesh_simplify))
|
|
95
|
+
else:
|
|
96
|
+
rob = robot_mesh.load(robot_mjcf, model, cache=mesh_cache) if robot_mjcf else None
|
|
97
|
+
self.rgb_seg = bool(rgb_seg)
|
|
98
|
+
if self.rgb_seg and (rgb is None or self.grad["rgb"] != "none"):
|
|
99
|
+
raise ValueError("rgb_seg: needs an rgb camera with grad['rgb'] 'none'")
|
|
100
|
+
if rgb is not None:
|
|
101
|
+
self.palette = self._palette(shading or Shading(), terrain, rob)
|
|
102
|
+
l = np.asarray((shading or Shading()).light_dir, np.float64)
|
|
103
|
+
self.light = tuple(float(x) for x in l / np.linalg.norm(l))
|
|
104
|
+
jax_rays.setup(terrain=terrain, cell=cell, floor_z=floor_z, robot=rob, nbody=model.nbody, backend=backend)
|
|
105
|
+
self.body = {}
|
|
106
|
+
self.pat = {}
|
|
107
|
+
for name, s in (("depth", depth), ("lidar", lidar), ("height_scan", height_scan), ("rgb", rgb)):
|
|
108
|
+
if s is None:
|
|
109
|
+
continue
|
|
110
|
+
b = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, s.body)
|
|
111
|
+
assert b >= 0, f"no body {s.body!r}"
|
|
112
|
+
off, dirs = s.rays()
|
|
113
|
+
if name == "lidar":
|
|
114
|
+
dirs = s.frames()
|
|
115
|
+
off = housing * dirs
|
|
116
|
+
cs = jax_rays.cone(dirs.reshape(-1, 3), off.reshape(-1, 3))
|
|
117
|
+
else:
|
|
118
|
+
if name != "height_scan":
|
|
119
|
+
off = off + housing * dirs
|
|
120
|
+
cs = jax_rays.cone(dirs, off)
|
|
121
|
+
mp, mR = s.mount() if hasattr(s, "mount") else (np.zeros(3), np.eye(3))
|
|
122
|
+
self.body[name] = b
|
|
123
|
+
self.pat[name] = (jax.numpy.asarray(off), jax.numpy.asarray(dirs), np.asarray(mp, np.float32),
|
|
124
|
+
np.asarray(mR, np.float32), cs)
|
|
125
|
+
self._dr_cone = {}
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def _palette(sh, terrain, rob):
|
|
129
|
+
import jax.numpy as jnp
|
|
130
|
+
nbox = len(terrain.boxes) if terrain is not None else 0
|
|
131
|
+
nhf = len(terrain.hf_head) if terrain is not None else 0
|
|
132
|
+
tab = lambda arr, n, c: (np.asarray(arr, np.float32).reshape(-1, 3) if arr is not None
|
|
133
|
+
else np.tile(np.float32(c), (max(n, 1), 1)))
|
|
134
|
+
robot = rob["rgba"][:, :3] if rob is not None and "rgba" in rob else np.zeros((1, 3), np.float32)
|
|
135
|
+
l = np.asarray(sh.light_dir, np.float64)
|
|
136
|
+
return dict(box=jnp.asarray(tab(sh.box_rgb, nbox, sh.box)), hf=jnp.asarray(tab(sh.hf_rgb, nhf, sh.hfield)),
|
|
137
|
+
floor=jnp.asarray(np.float32(sh.floor)), obj=jnp.asarray(tab(sh.object_rgb, 1, sh.obj)),
|
|
138
|
+
robot=jnp.asarray(np.asarray(robot, np.float32)), sky=jnp.asarray(np.float32(sh.sky)),
|
|
139
|
+
light=jnp.asarray((l / np.linalg.norm(l)).astype(np.float32)), ambient=float(sh.ambient),
|
|
140
|
+
diffuse=float(sh.diffuse))
|
|
141
|
+
|
|
142
|
+
def _shade(self, gid, nrm, vec):
|
|
143
|
+
import jax.numpy as jnp
|
|
144
|
+
P = self.palette
|
|
145
|
+
cat, idx = gid >> 24, gid & 0xFFFFFF
|
|
146
|
+
pick = lambda t: t[jnp.clip(idx, 0, t.shape[0] - 1)]
|
|
147
|
+
base = jnp.where((cat == raycore.ID_ROBOT >> 24)[..., None], pick(P["robot"]),
|
|
148
|
+
jnp.where((cat == raycore.ID_OBJECT >> 24)[..., None], pick(P["obj"]),
|
|
149
|
+
jnp.where((cat == raycore.ID_HFIELD >> 24)[..., None], pick(P["hf"]),
|
|
150
|
+
jnp.where((cat == raycore.ID_BOX >> 24)[..., None], pick(P["box"]),
|
|
151
|
+
P["floor"]))))
|
|
152
|
+
n = jnp.where((jnp.sum(nrm * vec, -1) > 0)[..., None], -nrm, nrm)
|
|
153
|
+
lam = jnp.clip(-jnp.sum(n * P["light"], -1), 0.0, 1.0)
|
|
154
|
+
c = base * (P["ambient"] + P["diffuse"] * lam)[..., None]
|
|
155
|
+
return jnp.where((gid >= 0)[..., None], jnp.clip(c, 0.0, 1.0), P["sky"])
|
|
156
|
+
|
|
157
|
+
APPEARANCE_KEYS = ("object_rgb", "floor_rgb", "robot_gain", "sky_rgb", "light_dir", "ambient", "diffuse")
|
|
158
|
+
|
|
159
|
+
def _shade_dr(self, gid, nrm, vec, app):
|
|
160
|
+
import jax.numpy as jnp
|
|
161
|
+
bad = set(app) - set(self.APPEARANCE_KEYS)
|
|
162
|
+
if bad:
|
|
163
|
+
raise ValueError(f"appearance: unknown keys {sorted(bad)} ({', '.join(self.APPEARANCE_KEYS)})")
|
|
164
|
+
P = self.palette
|
|
165
|
+
B = gid.shape[0]
|
|
166
|
+
f = lambda x: jnp.asarray(x, jnp.float32)
|
|
167
|
+
cat, idx = gid >> 24, gid & 0xFFFFFF
|
|
168
|
+
pick = lambda t: t[jnp.clip(idx, 0, t.shape[0] - 1)]
|
|
169
|
+
robot = pick(P["robot"])
|
|
170
|
+
if app.get("robot_gain") is not None:
|
|
171
|
+
robot = robot * f(app["robot_gain"]).reshape(B, 1, -1)
|
|
172
|
+
if app.get("object_rgb") is not None:
|
|
173
|
+
tab = f(app["object_rgb"]).reshape(B, -1, 3)
|
|
174
|
+
obj = jnp.take_along_axis(tab, jnp.clip(idx, 0, tab.shape[1] - 1)[..., None], axis=1)
|
|
175
|
+
else:
|
|
176
|
+
obj = pick(P["obj"])
|
|
177
|
+
floor = f(app["floor_rgb"]).reshape(B, 1, 3) if app.get("floor_rgb") is not None else P["floor"]
|
|
178
|
+
base = jnp.where((cat == raycore.ID_ROBOT >> 24)[..., None], robot,
|
|
179
|
+
jnp.where((cat == raycore.ID_OBJECT >> 24)[..., None], obj,
|
|
180
|
+
jnp.where((cat == raycore.ID_HFIELD >> 24)[..., None], pick(P["hf"]),
|
|
181
|
+
jnp.where((cat == raycore.ID_BOX >> 24)[..., None], pick(P["box"]),
|
|
182
|
+
floor))))
|
|
183
|
+
if app.get("light_dir") is not None:
|
|
184
|
+
ld = f(app["light_dir"]).reshape(B, 3)
|
|
185
|
+
light = (ld / jnp.linalg.norm(ld, axis=-1, keepdims=True))[:, None, :]
|
|
186
|
+
else:
|
|
187
|
+
light = P["light"]
|
|
188
|
+
amb = f(app["ambient"]).reshape(B, 1) if app.get("ambient") is not None else P["ambient"]
|
|
189
|
+
dif = f(app["diffuse"]).reshape(B, 1) if app.get("diffuse") is not None else P["diffuse"]
|
|
190
|
+
sky = f(app["sky_rgb"]).reshape(B, 1, 3) if app.get("sky_rgb") is not None else P["sky"]
|
|
191
|
+
n = jnp.where((jnp.sum(nrm * vec, -1) > 0)[..., None], -nrm, nrm)
|
|
192
|
+
lam = jnp.clip(-jnp.sum(n * light, -1), 0.0, 1.0)
|
|
193
|
+
c = base * (amb + dif * lam)[..., None]
|
|
194
|
+
return jnp.where((gid >= 0)[..., None], jnp.clip(c, 0.0, 1.0), sky)
|
|
195
|
+
|
|
196
|
+
def _shade_parts(self, gid, nrm, vec):
|
|
197
|
+
import jax.numpy as jnp
|
|
198
|
+
P = self.palette
|
|
199
|
+
cat, idx = gid >> 24, gid & 0xFFFFFF
|
|
200
|
+
pick = lambda t: t[jnp.clip(idx, 0, t.shape[0] - 1)]
|
|
201
|
+
base = jnp.where((cat == raycore.ID_ROBOT >> 24)[..., None], pick(P["robot"]),
|
|
202
|
+
jnp.where((cat == raycore.ID_OBJECT >> 24)[..., None], pick(P["obj"]),
|
|
203
|
+
jnp.where((cat == raycore.ID_HFIELD >> 24)[..., None], pick(P["hf"]),
|
|
204
|
+
jnp.where((cat == raycore.ID_BOX >> 24)[..., None], pick(P["box"]),
|
|
205
|
+
P["floor"]))))
|
|
206
|
+
n = jnp.where((jnp.sum(nrm * vec, -1) > 0)[..., None], -nrm, nrm)
|
|
207
|
+
lam = jnp.clip(-jnp.sum(n * P["light"], -1), 0.0, 1.0)
|
|
208
|
+
c = base * (P["ambient"] + P["diffuse"] * lam)[..., None]
|
|
209
|
+
rgb = jnp.where((gid >= 0)[..., None], jnp.clip(c, 0.0, 1.0), P["sky"])
|
|
210
|
+
lraw = -jnp.sum(n * P["light"], -1)
|
|
211
|
+
live = (gid >= 0) & (lraw > 0.0) & (lraw < 1.0)
|
|
212
|
+
kappa = jnp.where(live[..., None] & (c > 0.0) & (c < 1.0), base * P["diffuse"], 0.0)
|
|
213
|
+
return rgb, kappa, n
|
|
214
|
+
|
|
215
|
+
@staticmethod
|
|
216
|
+
def _qmat(q):
|
|
217
|
+
import jax.numpy as jnp
|
|
218
|
+
w, x, y, z = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
|
|
219
|
+
return jnp.stack([jnp.stack([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], -1),
|
|
220
|
+
jnp.stack([2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], -1),
|
|
221
|
+
jnp.stack([2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], -1)], -2)
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def _expmap(r):
|
|
225
|
+
import jax.numpy as jnp
|
|
226
|
+
t2 = jnp.sum(r * r, -1)
|
|
227
|
+
t = jnp.sqrt(jnp.maximum(t2, 1e-30))
|
|
228
|
+
small = t2 < 1e-8
|
|
229
|
+
a = jnp.where(small, 1 - t2 / 6, jnp.sin(t) / t)
|
|
230
|
+
b = jnp.where(small, 0.5 - t2 / 24, (1 - jnp.cos(t)) / jnp.maximum(t2, 1e-30))
|
|
231
|
+
z = jnp.zeros_like(r[:, 0])
|
|
232
|
+
K = jnp.stack([jnp.stack([z, -r[:, 2], r[:, 1]], -1), jnp.stack([r[:, 2], z, -r[:, 0]], -1),
|
|
233
|
+
jnp.stack([-r[:, 1], r[:, 0], z], -1)], -2)
|
|
234
|
+
return jnp.eye(3) + a[:, None, None] * K + b[:, None, None] * _einsum("bij,bjk->bik", K, K)
|
|
235
|
+
|
|
236
|
+
def _frame_dr(self, name, xpos, xquat, dr):
|
|
237
|
+
import jax.numpy as jnp
|
|
238
|
+
bad = set(dr) - {"pos", "rot", "intrinsics"}
|
|
239
|
+
if bad:
|
|
240
|
+
raise ValueError(f"camera_dr[{name!r}]: unknown keys {sorted(bad)} (pos, rot, intrinsics)")
|
|
241
|
+
b = self.body[name]
|
|
242
|
+
off, dirs, mp, mR, cs = self.pat[name]
|
|
243
|
+
R = self._qmat(xquat[:, b])
|
|
244
|
+
mpw = jnp.asarray(mp) + (jnp.asarray(dr["pos"], jnp.float32) if dr.get("pos") is not None else 0.0)
|
|
245
|
+
p = xpos[:, b] + _einsum("bij,bj->bi", R, jnp.broadcast_to(mpw, (R.shape[0], 3)))
|
|
246
|
+
Rs = _einsum("bij,jk->bik", R, mR)
|
|
247
|
+
if dr.get("rot") is not None:
|
|
248
|
+
Rs = _einsum("bij,bjk->bik", Rs, self._expmap(jnp.asarray(dr["rot"], jnp.float32)))
|
|
249
|
+
if dr.get("intrinsics") is not None:
|
|
250
|
+
cam = self.depth if name == "depth" else self.rgb
|
|
251
|
+
if name not in self._dr_cone:
|
|
252
|
+
c = cam.noisy_cone_cos()
|
|
253
|
+
self._dr_cone[name] = (c, float(np.sqrt(max(0.0, 1 - c * c))), float(cs[2]) * (1 + 1e-6))
|
|
254
|
+
dirs = cameras.pixel_dirs(jnp, cam.width, cam.height, *cam.noisy_intrinsics(dr["intrinsics"]))
|
|
255
|
+
dirs = dirs.astype(jnp.float32)
|
|
256
|
+
off = (self.housing * dirs).astype(jnp.float32)
|
|
257
|
+
cs = self._dr_cone[name]
|
|
258
|
+
return p, Rs, off, dirs, cs
|
|
259
|
+
|
|
260
|
+
def _frame(self, name, xpos, xquat, dr=None):
|
|
261
|
+
import jax.numpy as jnp
|
|
262
|
+
if dr is not None and name in ("depth", "rgb"):
|
|
263
|
+
return self._frame_dr(name, xpos, xquat, dr)
|
|
264
|
+
b = self.body[name]
|
|
265
|
+
off, dirs, mp, mR, cs = self.pat[name]
|
|
266
|
+
R = self._qmat(xquat[:, b])
|
|
267
|
+
if name == "height_scan":
|
|
268
|
+
yaw = jnp.arctan2(R[:, 1, 0], R[:, 0, 0])
|
|
269
|
+
c, s = jnp.cos(yaw), jnp.sin(yaw)
|
|
270
|
+
z, o = jnp.zeros_like(c), jnp.ones_like(c)
|
|
271
|
+
Ry = jnp.stack([jnp.stack([c, -s, z], -1), jnp.stack([s, c, z], -1), jnp.stack([z, z, o], -1)], -2)
|
|
272
|
+
return xpos[:, b], Ry, off, dirs, cs
|
|
273
|
+
return xpos[:, b] + _einsum("bij,j->bi", R, mp), _einsum("bij,jk->bik", R, mR), off, dirs, cs
|
|
274
|
+
|
|
275
|
+
def __call__(self, xpos, xquat, objects=None, lidar_frame=0, camera_dr=None, appearance=None):
|
|
276
|
+
"""dict of depth (B, H, W) z-depth in metres (0 invalid: no hit, nearer than min_depth, beyond max_depth), seg
|
|
277
|
+
(B, H, W) int32 ids (raycore.ID_*, -1 none), lidar (B, n, 3) points in the LiDAR frame (zeros for no return),
|
|
278
|
+
lidar_valid (B, n), height_scan (B, ny, nx) (body z - hit z; max_distance - offset_z for no hit), rgb (B, H, W,
|
|
279
|
+
3) in [0, 1] (with an rgb camera). lidar_frame:
|
|
280
|
+
the LiDAR pattern's frame (an int, traceable; modulo the pattern's frames: cameras.Lidar.frames), e.g. the step
|
|
281
|
+
count at the LiDAR's rate; every world sees the same frame (a per-world yaw of the mount varies the rays).
|
|
282
|
+
camera_dr (optional, per-world camera randomization of the depth and rgb cameras; None, the default: bitwise
|
|
283
|
+
as without it): a dict with any of pos (B, 3) metres added to the mount's position in its body's frame, rot
|
|
284
|
+
(B, 3) an axis-angle rotation (radians) of the camera in its own frame (x forward, y left, z up) after the
|
|
285
|
+
mount's rotation, intrinsics (B, 4) (relative change of fx, of fy, shift of cx as a fraction of the width, of
|
|
286
|
+
cy as a fraction of the height; each clipped to +-cameras.INTRINSICS_NOISE_MAX); the same for both cameras, or
|
|
287
|
+
{"depth": {...}, "rgb": {...}} per camera. Intrinsics noise casts per-world rays (software backend, grad
|
|
288
|
+
"none" for that camera). appearance (optional, per-world RGB shading; None, the default: bitwise as without
|
|
289
|
+
it): a dict with any of object_rgb (B, K, 3) the object slots' colours, floor_rgb (B, 3), robot_gain (B,) or
|
|
290
|
+
(B, 3) a multiplier of the robot meshes' colours, sky_rgb (B, 3), light_dir (B, 3) the light's travel
|
|
291
|
+
direction (normalised here), ambient (B,), diffuse (B,) (the directional light's intensity; Shading's
|
|
292
|
+
ambient 0.35 and diffuse 0.65 by default); missing keys keep Shading's values; rgb grad "none" only."""
|
|
293
|
+
import jax.numpy as jnp
|
|
294
|
+
out = {}
|
|
295
|
+
if camera_dr is not None:
|
|
296
|
+
per = set(camera_dr) <= {"depth", "rgb"} and len(camera_dr) > 0
|
|
297
|
+
cdr = {k: (camera_dr.get(k) if per else camera_dr) for k in ("depth", "rgb")}
|
|
298
|
+
else:
|
|
299
|
+
cdr = {"depth": None, "rgb": None}
|
|
300
|
+
for k in ("depth", "rgb"):
|
|
301
|
+
if cdr[k] is not None and cdr[k].get("intrinsics") is not None and self.grad[k] != "none":
|
|
302
|
+
raise ValueError(f"camera_dr intrinsics: per-world rays have no gradient (grad[{k!r}] must be 'none')")
|
|
303
|
+
if appearance is not None and self.grad["rgb"] != "none":
|
|
304
|
+
raise ValueError("appearance: per-world shading has no gradient (grad['rgb'] must be 'none')")
|
|
305
|
+
if self.depth is not None and cdr["depth"] is not None:
|
|
306
|
+
p, R, off, dirs, cs = self._frame("depth", xpos, xquat, cdr["depth"])
|
|
307
|
+
maxd = self.depth.max_depth / max(float(cs[0]) if dirs.ndim == 3 else
|
|
308
|
+
float(np.min(np.asarray(dirs)[:, 0])), 1e-3)
|
|
309
|
+
H, W = self.depth.height, self.depth.width
|
|
310
|
+
g = self.grad["depth"]
|
|
311
|
+
if isinstance(g, tuple):
|
|
312
|
+
def vdep(d, gid, nrm, pos, rot, dirs=dirs):
|
|
313
|
+
d = jnp.where(d >= 0, d + self.housing, -1.0)
|
|
314
|
+
z = d * dirs[:, 0]
|
|
315
|
+
ok = (d >= 0) & (z >= self.depth.min_depth) & (z <= self.depth.max_depth)
|
|
316
|
+
return (jnp.where(ok, z, 0.0).reshape(-1, H, W), jnp.where(d >= 0, gid, -1).reshape(-1, H, W),
|
|
317
|
+
ok.reshape(-1, H, W), None, nrm)
|
|
318
|
+
out["depth"], out["seg"] = jax_rays.cast_image(
|
|
319
|
+
raygrad.image_spec(self.depth, "depth"), vdep, float(g[1]), p, R, off, dirs, xpos, xquat, objects,
|
|
320
|
+
impl=self.grad_impl, max_distance=maxd, cone_cs=cs)
|
|
321
|
+
else:
|
|
322
|
+
d, gid, _ = jax_rays.cast(p, R, off, dirs, xpos, xquat, objects, maxd, cs, grad=g,
|
|
323
|
+
impl=self.grad_impl,
|
|
324
|
+
backend="software" if dirs.ndim == 3 else None)
|
|
325
|
+
d = jnp.where(d >= 0, d + self.housing, -1.0)
|
|
326
|
+
z = d * dirs[..., 0]
|
|
327
|
+
ok = (d >= 0) & (z >= self.depth.min_depth) & (z <= self.depth.max_depth)
|
|
328
|
+
out["depth"] = jnp.where(ok, z, 0.0).reshape(-1, H, W)
|
|
329
|
+
out["seg"] = jnp.where(d >= 0, gid, -1).reshape(-1, H, W)
|
|
330
|
+
elif self.depth is not None:
|
|
331
|
+
p, R, off, dirs, cs = self._frame("depth", xpos, xquat)
|
|
332
|
+
maxd = self.depth.max_depth / max(float(np.min(np.asarray(dirs)[:, 0])), 1e-3)
|
|
333
|
+
H, W = self.depth.height, self.depth.width
|
|
334
|
+
g = self.grad["depth"]
|
|
335
|
+
if isinstance(g, tuple):
|
|
336
|
+
def vdep(d, gid, nrm, pos, rot, dirs=dirs):
|
|
337
|
+
d = jnp.where(d >= 0, d + self.housing, -1.0)
|
|
338
|
+
z = d * dirs[:, 0]
|
|
339
|
+
ok = (d >= 0) & (z >= self.depth.min_depth) & (z <= self.depth.max_depth)
|
|
340
|
+
return (jnp.where(ok, z, 0.0).reshape(-1, H, W), jnp.where(d >= 0, gid, -1).reshape(-1, H, W),
|
|
341
|
+
ok.reshape(-1, H, W), None, nrm)
|
|
342
|
+
out["depth"], out["seg"] = jax_rays.cast_image(
|
|
343
|
+
raygrad.image_spec(self.depth, "depth"), vdep, float(g[1]), p, R, off, dirs, xpos, xquat, objects,
|
|
344
|
+
impl=self.grad_impl, max_distance=maxd, cone_cs=cs)
|
|
345
|
+
else:
|
|
346
|
+
d, gid, _ = jax_rays.cast(p, R, off, dirs, xpos, xquat, objects, maxd, cs, grad=g,
|
|
347
|
+
impl=self.grad_impl)
|
|
348
|
+
d = jnp.where(d >= 0, d + self.housing, -1.0)
|
|
349
|
+
z = d * dirs[:, 0]
|
|
350
|
+
ok = (d >= 0) & (z >= self.depth.min_depth) & (z <= self.depth.max_depth)
|
|
351
|
+
out["depth"] = jnp.where(ok, z, 0.0).reshape(-1, H, W)
|
|
352
|
+
out["seg"] = jnp.where(d >= 0, gid, -1).reshape(-1, H, W)
|
|
353
|
+
if self.lidar is not None:
|
|
354
|
+
p, R, off, dirs, cs = self._frame("lidar", xpos, xquat)
|
|
355
|
+
k = jnp.asarray(lidar_frame, jnp.int32) % dirs.shape[0]
|
|
356
|
+
off, dirs = off[k], dirs[k]
|
|
357
|
+
d, gid, _ = jax_rays.cast(p, R, off, dirs, xpos, xquat, objects, self.lidar.max_range, cs,
|
|
358
|
+
exclude_body=self.body["lidar"],
|
|
359
|
+
grad=self.grad["lidar"], impl=self.grad_impl)
|
|
360
|
+
d = jnp.where(d >= 0, d + self.housing, -1.0)
|
|
361
|
+
ok = (d >= self.lidar.min_range) & (d <= self.lidar.max_range)
|
|
362
|
+
out["lidar"] = jnp.where(ok[..., None], d[..., None] * dirs[None], 0.0)
|
|
363
|
+
out["lidar_valid"] = ok
|
|
364
|
+
out["lidar_seg"] = jnp.where(ok, gid, -1)
|
|
365
|
+
if self.rgb is not None and (cdr["rgb"] is not None or appearance is not None):
|
|
366
|
+
p, R, off, dirs, cs = self._frame("rgb", xpos, xquat, cdr["rgb"])
|
|
367
|
+
H, W = self.rgb.height, self.rgb.width
|
|
368
|
+
g = self.grad["rgb"]
|
|
369
|
+
if g != "none":
|
|
370
|
+
def vrgb(d, gid, nrm, pos, rot, dirs=dirs):
|
|
371
|
+
vec = _einsum("bij,nj->bni", rot, dirs)
|
|
372
|
+
rgb, kappa, nf = self._shade_parts(jnp.where(d >= 0, gid, -1), nrm, vec)
|
|
373
|
+
return rgb.reshape(-1, H, W, 3), gid, (d >= 0).reshape(-1, H, W), kappa, nf
|
|
374
|
+
out["rgb"], _ = jax_rays.cast_image(
|
|
375
|
+
raygrad.image_spec(self.rgb, "rgb"), vrgb, float(g[1]) if isinstance(g, tuple) else None, p, R,
|
|
376
|
+
off, dirs, xpos, xquat, objects, impl=self.grad_impl, light=self.light,
|
|
377
|
+
max_distance=self.rgb.max_depth, cone_cs=cs)
|
|
378
|
+
else:
|
|
379
|
+
d, gid, nrm = jax_rays.cast(p, R, off, dirs, xpos, xquat, objects, self.rgb.max_depth, cs,
|
|
380
|
+
backend="software" if dirs.ndim == 3 else None)
|
|
381
|
+
vec = (_einsum("bij,bnj->bni", R, dirs) if dirs.ndim == 3 else
|
|
382
|
+
_einsum("bij,nj->bni", R, dirs))
|
|
383
|
+
ids = jnp.where(d >= 0, gid, -1)
|
|
384
|
+
rgb = self._shade(ids, nrm, vec) if appearance is None else self._shade_dr(ids, nrm, vec, appearance)
|
|
385
|
+
out["rgb"] = rgb.reshape(-1, H, W, 3)
|
|
386
|
+
if self.rgb_seg:
|
|
387
|
+
self._rgb_extra(out, d, ids, dirs)
|
|
388
|
+
elif self.rgb is not None:
|
|
389
|
+
p, R, off, dirs, cs = self._frame("rgb", xpos, xquat)
|
|
390
|
+
H, W = self.rgb.height, self.rgb.width
|
|
391
|
+
g = self.grad["rgb"]
|
|
392
|
+
if g != "none":
|
|
393
|
+
def vrgb(d, gid, nrm, pos, rot, dirs=dirs):
|
|
394
|
+
vec = _einsum("bij,nj->bni", rot, dirs)
|
|
395
|
+
rgb, kappa, nf = self._shade_parts(jnp.where(d >= 0, gid, -1), nrm, vec)
|
|
396
|
+
return rgb.reshape(-1, H, W, 3), gid, (d >= 0).reshape(-1, H, W), kappa, nf
|
|
397
|
+
out["rgb"], _ = jax_rays.cast_image(
|
|
398
|
+
raygrad.image_spec(self.rgb, "rgb"), vrgb, float(g[1]) if isinstance(g, tuple) else None, p, R,
|
|
399
|
+
off, dirs, xpos, xquat, objects, impl=self.grad_impl, light=self.light,
|
|
400
|
+
max_distance=self.rgb.max_depth, cone_cs=cs)
|
|
401
|
+
else:
|
|
402
|
+
d, gid, nrm = jax_rays.cast(p, R, off, dirs, xpos, xquat, objects, self.rgb.max_depth, cs)
|
|
403
|
+
vec = _einsum("bij,nj->bni", R, dirs)
|
|
404
|
+
out["rgb"] = self._shade(jnp.where(d >= 0, gid, -1), nrm, vec).reshape(-1, H, W, 3)
|
|
405
|
+
if self.rgb_seg:
|
|
406
|
+
self._rgb_extra(out, d, jnp.where(d >= 0, gid, -1), dirs)
|
|
407
|
+
if self.hs is not None:
|
|
408
|
+
p, R, off, dirs, cs = self._frame("height_scan", xpos, xquat)
|
|
409
|
+
ny = len(np.arange(-self.hs.size[1] / 2, self.hs.size[1] / 2 + self.hs.resolution * 0.5, self.hs.resolution))
|
|
410
|
+
g = self.grad["height_scan"]
|
|
411
|
+
if isinstance(g, tuple):
|
|
412
|
+
def vhs(d, gid, nrm, pos, rot):
|
|
413
|
+
hit_z = pos[:, None, 2] + self.hs.offset_z - jnp.where(d >= 0, d, self.hs.max_distance)
|
|
414
|
+
img = (pos[:, None, 2] - hit_z).reshape(pos.shape[0], ny, -1)
|
|
415
|
+
return img, gid.reshape(img.shape), (d >= 0).reshape(img.shape), None, nrm
|
|
416
|
+
out["height_scan"], _ = jax_rays.cast_image(
|
|
417
|
+
raygrad.image_spec(self.hs, "height"), vhs, float(g[1]), p, R, off, dirs, xpos, xquat, objects,
|
|
418
|
+
impl=self.grad_impl, max_distance=self.hs.max_distance, cone_cs=cs, robot=False,
|
|
419
|
+
backend="software")
|
|
420
|
+
else:
|
|
421
|
+
d, _, _ = jax_rays.cast(p, R, off, dirs, xpos, xquat, objects, self.hs.max_distance, cs, robot=False,
|
|
422
|
+
backend="software",
|
|
423
|
+
grad=g, impl=self.grad_impl)
|
|
424
|
+
hit_z = p[:, None, 2] + self.hs.offset_z - jnp.where(d >= 0, d, self.hs.max_distance)
|
|
425
|
+
out["height_scan"] = (p[:, None, 2] - hit_z).reshape(p.shape[0], ny, -1)
|
|
426
|
+
return out
|
|
427
|
+
|
|
428
|
+
def _rgb_extra(self, out, d, ids, dirs):
|
|
429
|
+
import jax.numpy as jnp
|
|
430
|
+
H, W = self.rgb.height, self.rgb.width
|
|
431
|
+
d = jnp.where(d >= 0, d + self.housing, -1.0)
|
|
432
|
+
z = d * dirs[..., 0]
|
|
433
|
+
ok = (d >= 0) & (z >= self.rgb.min_depth) & (z <= self.rgb.max_depth)
|
|
434
|
+
out["rgb_seg"] = ids.reshape(-1, H, W)
|
|
435
|
+
out["rgb_depth"] = jnp.where(ok, z, 0.0).reshape(-1, H, W)
|
|
436
|
+
|
|
437
|
+
@staticmethod
|
|
438
|
+
def depth_noise(key, depth, noise=DepthNoise()):
|
|
439
|
+
"""depth (B, H, W) with DepthNoise applied (invalid stays 0)."""
|
|
440
|
+
import jax
|
|
441
|
+
import jax.numpy as jnp
|
|
442
|
+
k1, k2, k3 = jax.random.split(key, 3)
|
|
443
|
+
valid = depth > 0
|
|
444
|
+
z = depth + noise.sigma_z2 * depth ** 2 * jax.random.normal(k1, depth.shape)
|
|
445
|
+
drop = jax.random.uniform(k2, depth.shape) < noise.dropout
|
|
446
|
+
pad = jnp.pad(depth, ((0, 0), (1, 1), (1, 1)), mode="edge")
|
|
447
|
+
jump = jnp.maximum(jnp.maximum(jnp.abs(pad[:, 1:-1, 2:] - depth), jnp.abs(pad[:, 1:-1, :-2] - depth)),
|
|
448
|
+
jnp.maximum(jnp.abs(pad[:, 2:, 1:-1] - depth), jnp.abs(pad[:, :-2, 1:-1] - depth)))
|
|
449
|
+
edge = (jump > noise.edge_jump) & (jax.random.uniform(k3, depth.shape) < noise.edge_drop)
|
|
450
|
+
return jnp.where(valid & ~drop & ~edge, z, 0.0)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
class Delay:
|
|
454
|
+
"""A latency buffer of L frames for a sensor output (functional: init(x) -> state; push(state, x) ->
|
|
455
|
+
(state, the output L frames ago))."""
|
|
456
|
+
|
|
457
|
+
def __init__(self, frames):
|
|
458
|
+
self.L = int(frames)
|
|
459
|
+
|
|
460
|
+
def init(self, x):
|
|
461
|
+
import jax.numpy as jnp
|
|
462
|
+
return jnp.repeat(x[None], self.L + 1, 0)
|
|
463
|
+
|
|
464
|
+
def push(self, state, x):
|
|
465
|
+
import jax.numpy as jnp
|
|
466
|
+
state = jnp.concatenate([state[1:], x[None]], 0)
|
|
467
|
+
return state, state[0]
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def label_map(ids, table):
|
|
471
|
+
"""Semantic labels from ray ids: table maps (category, index) to a label: a dict {raycore.ID_*: array of labels per
|
|
472
|
+
index, or one label}; unmapped -> -1."""
|
|
473
|
+
import jax.numpy as jnp
|
|
474
|
+
cat, idx = ids >> 24, ids & raycore.ID_MASK
|
|
475
|
+
out = jnp.full(ids.shape, -1, jnp.int32)
|
|
476
|
+
for c, lab in table.items():
|
|
477
|
+
lab = jnp.asarray(lab, jnp.int32)
|
|
478
|
+
v = lab if lab.ndim == 0 else lab[jnp.clip(idx, 0, lab.shape[0] - 1)]
|
|
479
|
+
out = jnp.where((ids >= 0) & (cat == (c >> 24)), v, out)
|
|
480
|
+
return out
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class Imu:
|
|
484
|
+
"""An IMU at a site of the engine's model (the G1's imu_in_torso / imu_in_pelvis: Unitree's URDF mounts): gyro =
|
|
485
|
+
the body's angular velocity in the site frame, accelerometer = the site's linear acceleration minus gravity in the
|
|
486
|
+
site frame (the specific force; read(gravity=) takes per-world gravity), the acceleration a finite difference of the site velocity over the control step (MuJoCo's accelerometer
|
|
487
|
+
reads the instantaneous acceleration; over a 20 ms step they agree to the step's change of it). Inputs are the
|
|
488
|
+
kinematics outputs of nablaengine.jax_ffi.kinematics (xpos, xquat, cvel at the root subtree's COM, subtree_com)."""
|
|
489
|
+
|
|
490
|
+
def __init__(self, model, site="imu_in_torso", dt=None):
|
|
491
|
+
s = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, site)
|
|
492
|
+
assert s >= 0, f"no site {site!r}"
|
|
493
|
+
self.body = int(model.site_bodyid[s])
|
|
494
|
+
self.pos = np.asarray(model.site_pos[s], np.float32)
|
|
495
|
+
self.R = cameras.quat_matrix(model.site_quat[s]).astype(np.float32)
|
|
496
|
+
self.dt = float(dt) if dt is not None else None
|
|
497
|
+
self.g = np.asarray(model.opt.gravity, np.float32)
|
|
498
|
+
self.root = 0 if int(model.ntree) <= 1 else int(model.body_rootid[self.body])
|
|
499
|
+
|
|
500
|
+
def frame(self, xpos, xquat, cvel, subtree_com):
|
|
501
|
+
"""(site position (B, 3), site rotation (B, 3, 3), angular velocity (B, 3) world, site linear velocity (B, 3))."""
|
|
502
|
+
import jax.numpy as jnp
|
|
503
|
+
Rb = G1Sensors._qmat(xquat[:, self.body])
|
|
504
|
+
p = xpos[:, self.body] + _einsum("bij,j->bi", Rb, self.pos)
|
|
505
|
+
R = _einsum("bij,jk->bik", Rb, self.R)
|
|
506
|
+
w, v0 = cvel[:, self.body, :3], cvel[:, self.body, 3:]
|
|
507
|
+
v = v0 + jnp.cross(w, p - subtree_com[:, self.root])
|
|
508
|
+
return p, R, w, v
|
|
509
|
+
|
|
510
|
+
def read(self, kin_now, kin_prev, dt=None, gravity=None):
|
|
511
|
+
"""dict(gyro (B, 3), accel (B, 3)) in the site frame from the kinematics outputs (xpos, xquat, cvel,
|
|
512
|
+
subtree_com) of this step and the previous one. gravity: each world's gravity (B, 3) or (3,) (a build with
|
|
513
|
+
PhysicsParams gravity: the worlds' values, so the specific force matches each world's dynamics); None: the
|
|
514
|
+
model's opt.gravity (unchanged)."""
|
|
515
|
+
import jax.numpy as jnp
|
|
516
|
+
dt = dt or self.dt
|
|
517
|
+
_, R, w, v = self.frame(*kin_now)
|
|
518
|
+
_, _, _, vp = self.frame(*kin_prev)
|
|
519
|
+
g = self.g if gravity is None else jnp.asarray(gravity, v.dtype)
|
|
520
|
+
acc = (v - vp) / dt - g
|
|
521
|
+
return dict(gyro=_einsum("bji,bj->bi", R, w), accel=_einsum("bji,bj->bi", R, acc))
|