EMR-Demo / visualize.py
seu-zuxing's picture
Demo video scene: seamless loops (blend 15 over windows whose end matches their start; ping-pong rows), no hidden frames (part 3)
27c3885 verified
Raw History Blame Contribute Delete
20.9 kB
"""Visualize the EMR demo motions.
Needs numpy and mujoco (pip install numpy mujoco); writing mp4 also needs imageio-ffmpeg. Offscreen rendering on a
machine without a display: set MUJOCO_GL=egl.
python visualize.py list [--task locomotion|dexterous|hoi]
python visualize.py play hoi_demo_0003 # interactive MuJoCo viewer, loops
python visualize.py play hoi_demo_0003 --video hoi_3.mp4 # offscreen, camera follows the robot
python visualize.py scene demo_video --video demo.mp4 # the project page's demo video
python visualize.py scene cover --image cover.png # the project page's cover
python visualize.py scene sections # lists which motions each page section shows
Paths are relative to this file's folder (the dataset root); --root picks another.
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
import mujoco
import numpy as np
FLOOR = np.array([0.13, 0.13, 0.14])
OBJECT_COLORS = [(0.88, 0.55, 0.24), (0.73, 0.55, 0.36), (0.31, 0.64, 0.65), (0.50, 0.75, 0.50),
(0.80, 0.36, 0.28), (0.90, 0.75, 0.30), (0.45, 0.55, 0.80)]
TABLE_COLOR = (0.72, 0.52, 0.33)
# --------------------------------------------------------------------------------------------------- math
def quat_to_mat(q: np.ndarray) -> np.ndarray:
q = q / np.linalg.norm(q, axis=-1, keepdims=True)
w, x, y, z = np.moveaxis(q, -1, 0)
return np.stack([np.stack([1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], -1),
np.stack([2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], -1),
np.stack([2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)], -1)], -2)
def nlerp(q0, q1, w):
w = np.asarray(w)[..., None]
q1 = np.where((q0 * q1).sum(-1, keepdims=True) < 0, -q1, q1)
q = (1 - w) * q0 + w * q1
return q / np.linalg.norm(q, axis=-1, keepdims=True)
def yaw_rot(a: float) -> np.ndarray:
c, s = np.cos(a), np.sin(a)
return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1.0]])
def pchip(t: np.ndarray, y: np.ndarray, ts: np.ndarray) -> np.ndarray:
"""Shape-preserving piecewise cubic interpolation along axis 0 (same rule as scipy's PchipInterpolator)."""
t, y, ts = np.asarray(t, float), np.asarray(y, float), np.asarray(ts, float)
h = np.diff(t)
d = np.diff(y, axis=0) / h[:, None]
m = np.zeros_like(y)
with np.errstate(divide="ignore", invalid="ignore"):
for k in range(1, len(t) - 1):
a, b = d[k - 1], d[k]
w1, w2 = 2 * h[k] + h[k - 1], h[k] + 2 * h[k - 1]
m[k] = np.where(a * b > 0, (w1 + w2) / (w1 / a + w2 / b), 0.0)
def edge(h0, h1, d0, d1):
e = ((2 * h0 + h1) * d0 - h0 * d1) / (h0 + h1)
e = np.where(np.sign(e) != np.sign(d0), 0.0, e)
return np.where((np.sign(d0) != np.sign(d1)) & (np.abs(e) > 3 * np.abs(d0)), 3 * d0, e)
m[0] = edge(h[0], h[1], d[0], d[1])
m[-1] = edge(h[-1], h[-2], d[-1], d[-2])
i = np.clip(np.searchsorted(t, ts, side="right") - 1, 0, len(t) - 2)
s = ((ts - t[i]) / h[i])[:, None]
hh = h[i][:, None]
return ((2 * s**3 - 3 * s**2 + 1) * y[i] + (s**3 - 2 * s**2 + s) * hh * m[i] +
(-2 * s**3 + 3 * s**2) * y[i + 1] + (s**3 - s**2) * hh * m[i + 1])
# ------------------------------------------------------------------------------------------------- motions
class Motion:
"""One motion file. Its per-frame state is a dict of arrays; pieces() turns a state frame into mesh poses."""
LIN = ("root_pos", "dof_pos", "object_pos", "link_pos", "table_pos")
QUAT = ("root_quat_wxyz", "object_quat_wxyz", "link_quat_wxyz", "table_quat_wxyz")
def __init__(self, root: Path, mid: str, robots: dict, table: bool = True, color=OBJECT_COLORS[0]) -> None:
task = mid.split("_demo_")[0]
self.id, self.task, self.root = mid, task, root
z = np.load(root / task / f"{mid}.npz", allow_pickle=False)
self.z = {k: z[k] for k in z.files}
self.fps = float(self.z["fps"])
self.n = len(self.z["source_frames"])
if not table:
self.z = {k: v for k, v in self.z.items() if not k.startswith("table_")}
self.state = {k: self.z[k].astype(np.float64) for k in self.LIN + self.QUAT if k in self.z}
self.assets: list[tuple[str, tuple]] = [] # (mesh path relative to root, rgba)
self.n_robot = 0
if task in ("locomotion", "hoi"):
self.robot = robots.setdefault(str(self.z["robot"]), Robot(root, str(self.z["robot"])))
self.adr = self.robot.adr(list(self.z["joint_names"]))
self.assets += self.robot.assets
self.n_robot = len(self.robot.assets)
if task == "dexterous":
self.assets += [(f"hands/meshes/{f}", tuple(c)) for f, c in zip(self.z["link_meshes"], self.z["link_rgba"])]
if "object_meshes" in self.z:
col = (*color, 1.0)
self.assets += [(f"objects/{f}", col) for f in self.z["object_meshes"]]
if "table_mesh" in self.z:
self.assets.append((f"objects/{self.z['table_mesh']}", (*TABLE_COLOR, 1.0)))
def loop(self, start: int, L: int, B: int, pingpong: bool = False) -> dict:
"""State for loop frames [0, L): the window [start, start + L + B), its last B frames faded into its first.
With pingpong: the window [start, start + L) forward, then backward (2 L - 2 frames, no blend)."""
if pingpong:
idx = np.concatenate([np.arange(start, start + L), np.arange(start + L - 2, start, -1)])
return {k: x[idx] for k, x in self.state.items()}
u = np.arange(L)
w = np.clip(u / B, 0, 1) if B else np.ones(L)
w = w * w * (3 - 2 * w)
a = np.where(u < B, start + L + u, start + u)
b = start + u
out = {}
for k, x in self.state.items():
ww = w.reshape((-1,) + (1,) * (x.ndim - 1))
out[k] = nlerp(x[a], x[b], ww[..., 0]) if k in self.QUAT else (1 - ww) * x[a] + ww * x[b]
return out
def pieces(self, st: dict, k: int):
"""Poses of every asset at state frame k: positions (n, 3), rotations (n, 3, 3), and whether each pose is
already the pose of MuJoCo's processed mesh frame (robot geoms) or of the mesh file's own frame."""
P, R, mesh_frame = [], [], []
if self.n_robot:
p, r = self.robot.fk(st["root_pos"][k], st["root_quat_wxyz"][k], st["dof_pos"][k], self.adr)
P.append(p)
R.append(r)
mesh_frame += [True] * len(p)
if "link_pos" in st:
P.append(st["link_pos"][k])
R.append(quat_to_mat(st["link_quat_wxyz"][k]))
mesh_frame += [False] * len(st["link_pos"][k])
if "object_pos" in st:
P.append(st["object_pos"][k])
R.append(quat_to_mat(st["object_quat_wxyz"][k]))
mesh_frame += [False] * len(st["object_pos"][k])
if "table_pos" in st:
P.append(st["table_pos"][k][None])
R.append(quat_to_mat(st["table_quat_wxyz"][k])[None])
mesh_frame.append(False)
return np.concatenate(P), np.concatenate(R), np.array(mesh_frame)
class Robot:
def __init__(self, root: Path, name: str) -> None:
self.model = mujoco.MjModel.from_xml_path(str(root / "robots" / f"{name}.xml"))
self.data = mujoco.MjData(self.model)
m = self.model
self.assets = [(f"robots/meshes/{m.mesh(m.geom_dataid[g]).name}.stl", tuple(m.geom_rgba[g]))
for g in range(m.ngeom)]
def adr(self, names: list[str]) -> np.ndarray:
return np.array([self.model.jnt_qposadr[self.model.joint(str(n)).id] for n in names])
def fk(self, root, quat, dof, adr):
d = self.data
d.qpos[:3], d.qpos[3:7], d.qpos[adr] = root, quat, dof
mujoco.mj_kinematics(self.model, d)
return d.geom_xpos.copy(), d.geom_xmat.reshape(-1, 3, 3).copy()
# --------------------------------------------------------------------------------------------------- scene
class Scene:
"""Instances of motions on one floor; every mesh is a world geom whose pose is written per frame."""
def __init__(self, root: Path, width: int, height: int, fovy: float = 42.0) -> None:
self.root, self.width, self.height, self.fovy = root, width, height, fovy
self.inst: list[dict] = []
def add(self, motion: Motion, place=None, dim: float = 1.0) -> None:
self.inst.append({"m": motion, "place": place, "dim": dim})
def compile(self) -> None:
spec = mujoco.MjSpec()
spec.compiler.degree = False
spec.visual.global_.offwidth, spec.visual.global_.offheight = self.width, self.height
spec.visual.quality.shadowsize = 8192
spec.visual.quality.offsamples = 8
spec.visual.map.znear, spec.visual.map.zfar = 0.02, 120.0
spec.visual.headlight.ambient = [0.28, 0.28, 0.30]
spec.visual.headlight.diffuse = [0.30, 0.30, 0.30]
spec.visual.headlight.specular = [0.05, 0.05, 0.05]
spec.visual.rgba.haze = [0.09, 0.09, 0.10, 1.0]
spec.add_texture(name="grid", type=mujoco.mjtTexture.mjTEXTURE_2D,
builtin=mujoco.mjtBuiltin.mjBUILTIN_CHECKER, width=512, height=512,
rgb1=FLOOR.tolist(), rgb2=FLOOR.tolist(), mark=mujoco.mjtMark.mjMARK_EDGE,
markrgb=[0.24, 0.24, 0.26])
mat = spec.add_material(name="floor", texrepeat=[1, 1], texuniform=True, reflectance=0.0)
mat.textures[mujoco.mjtTextureRole.mjTEXROLE_RGB] = "grid"
spec.add_texture(name="sky", type=mujoco.mjtTexture.mjTEXTURE_SKYBOX,
builtin=mujoco.mjtBuiltin.mjBUILTIN_GRADIENT, width=256, height=256,
rgb1=[0.10, 0.10, 0.11], rgb2=[0.04, 0.04, 0.045])
wb = spec.worldbody
wb.add_geom(type=mujoco.mjtGeom.mjGEOM_PLANE, size=[90, 90, 0.1], material="floor", contype=0, conaffinity=0)
for pos, dirn, diff, shadow in (([-6, -10, 14], [0.35, 0.55, -1.0], 0.62, True),
([8, -6, 10], [-0.5, 0.4, -1.0], 0.22, False),
([0, 12, 8], [0.0, -0.6, -1.0], 0.18, False)):
wb.add_light(pos=pos, dir=dirn, diffuse=[diff] * 3, specular=[0.15] * 3, castshadow=shadow,
type=mujoco.mjtLightType.mjLIGHT_DIRECTIONAL)
meshes = sorted({a for it in self.inst for a, _ in it["m"].assets})
mname = {a: f"m{i}" for i, a in enumerate(meshes)}
for a in meshes:
spec.add_mesh(name=mname[a], file=str(self.root / a), inertia=mujoco.mjtMeshInertia.mjMESH_INERTIA_SHELL)
names = []
for i, it in enumerate(self.inst):
for j, (a, c) in enumerate(it["m"].assets):
c = np.asarray(c, float)
rgb = FLOOR + (c[:3] - FLOOR) * it["dim"]
nm = f"i{i}_{j}"
wb.add_geom(name=nm, type=mujoco.mjtGeom.mjGEOM_MESH, meshname=mname[a], rgba=[*rgb, 1.0],
contype=0, conaffinity=0)
names.append(nm)
self.model = spec.compile()
self.model.vis.global_.fovy = self.fovy
self.idx = np.array([self.model.geom(n).id for n in names])
self.off_p = self.model.geom_pos[self.idx].copy() # mesh processing offsets (geoms were added at identity)
self.off_R = quat_to_mat(self.model.geom_quat[self.idx].copy())
self.data = mujoco.MjData(self.model)
mujoco.mj_forward(self.model, self.data)
def write(self, frames: list[tuple]) -> None:
"""frames: per instance (state, k) or (state, k, hidden): pose all its meshes at state frame k and write them
into the scene; a hidden instance is moved far below the floor."""
xp, xr, k0 = [], [], 0
for it, (st, k, *hid) in zip(self.inst, frames):
P, R, mesh_frame = it["m"].pieces(st, k)
n = len(P)
op, oR = self.off_p[k0:k0 + n], self.off_R[k0:k0 + n]
Pw = np.where(mesh_frame[:, None], P, P + np.einsum("nij,nj->ni", R, op))
Rw = np.where(mesh_frame[:, None, None], R, np.einsum("nij,njk->nik", R, oR))
pl = it["place"]
if pl is not None:
(rx, ry, ryaw), (sx, sy, syaw), dz = pl
Rz = yaw_rot(syaw - ryaw)
Pw = (Pw + np.array([0, 0, dz]) - np.array([rx, ry, 0.0])) @ Rz.T + np.array([sx, sy, 0.0])
Rw = np.einsum("ij,njk->nik", Rz, Rw)
if hid and hid[0]:
Pw = Pw - np.array([0.0, 0.0, 1000.0])
xp.append(Pw)
xr.append(Rw.reshape(n, 9))
k0 += n
self.data.geom_xpos[self.idx] = np.concatenate(xp)
self.data.geom_xmat[self.idx] = np.concatenate(xr)
def set_cam(cam, eye, tgt) -> None:
f = np.asarray(tgt, float) - np.asarray(eye, float)
dist = float(np.linalg.norm(f))
f /= dist
cam.lookat[:] = tgt
cam.distance, cam.azimuth = dist, float(np.degrees(np.arctan2(f[1], f[0])))
cam.elevation = float(np.degrees(np.arcsin(f[2])))
def renderer(scene: Scene):
r = mujoco.Renderer(scene.model, scene.height, scene.width, max_geom=scene.model.ngeom + 100)
r.scene.flags[mujoco.mjtRndFlag.mjRND_SHADOW] = True
r.scene.flags[mujoco.mjtRndFlag.mjRND_REFLECTION] = False
return r
def video_writer(path: str, w: int, h: int, fps: float):
import imageio_ffmpeg
wr = imageio_ffmpeg.write_frames(path, (w, h), fps=fps, codec="libx264", macro_block_size=2, quality=None,
output_params=["-crf", "20", "-preset", "medium", "-movflags", "+faststart"])
wr.send(None)
return wr
# ------------------------------------------------------------------------------------------------ commands
def cmd_list(root: Path, args) -> None:
for row in json.loads((root / "index.json").read_text()):
if args.task and row["task"] != args.task:
continue
print(f"{row['id']:22s} {row['robot']:24s} {row['source_dataset']:10s} {row['source_clip']:48s} "
f"{row['frames']:5d} frames shown in: {', '.join(row['shown_in'])}")
def cmd_play(root: Path, args) -> None:
robots: dict = {}
m = Motion(root, args.id, robots)
sc = Scene(root, args.width, args.height, args.fovy)
sc.add(m)
sc.compile()
st = m.state
center = lambda k: (st["root_pos"][k] if "root_pos" in st else # noqa: E731
(st["link_pos"][k].mean(0) if "link_pos" in st else st["object_pos"][k].mean(0)))
dist = 3.2 if m.task != "dexterous" else 0.8
cam = mujoco.MjvCamera()
cam.type = mujoco.mjtCamera.mjCAMERA_FREE
cam.azimuth, cam.elevation, cam.distance = 120.0, -15.0, dist
if args.video:
wr = video_writer(args.video, args.width, args.height, m.fps)
with renderer(sc) as r:
for k in range(m.n):
sc.write([(st, k)])
c = center(k)
cam.lookat[:] = [c[0], c[1], c[2] if m.task == "dexterous" else 0.85]
r.update_scene(sc.data, camera=cam)
wr.send(np.ascontiguousarray(r.render()))
wr.close()
print("saved", args.video)
return
from mujoco import viewer as mj_viewer
with mj_viewer.launch_passive(sc.model, sc.data) as v:
c = center(0)
v.cam.lookat[:] = [c[0], c[1], c[2] if m.task == "dexterous" else 0.85]
v.cam.distance, v.cam.azimuth, v.cam.elevation = dist, 120.0, -15.0
k = 0
while v.is_running():
t0 = time.time()
sc.write([(st, k)])
v.sync()
k = (k + 1) % m.n
time.sleep(max(0.0, 1.0 / m.fps - (time.time() - t0)))
def place_of(row) -> tuple:
return (tuple(row["root"]), tuple(row["spot"]), float(row.get("lift_dz", 0.0)))
def cmd_scene(root: Path, args) -> None:
if args.name == "sections":
for row in json.loads((root / "scenes" / "sections.json").read_text()):
print(json.dumps(row))
return
conf = json.loads((root / "scenes" / f"{args.name}.json").read_text())
robots: dict = {}
motions: dict = {}
def get(row, i):
key = (row["id"], bool(row.get("table", False)), i % len(OBJECT_COLORS))
if key not in motions:
motions[key] = Motion(root, row["id"], robots, table=key[1], color=OBJECT_COLORS[key[2]])
return motions[key]
if args.name == "cover":
W, H = args.width or conf["width"], args.height or conf["height"]
sc = Scene(root, W * args.ss, H * args.ss, conf["camera"]["fovy"])
frames = []
for i, row in enumerate(conf["instances"]):
m = get(row, i)
sc.add(m, place_of(row), conf["background_keep"] if row["role"] == "background" else 1.0)
frames.append((m.state, row["frame"]))
sc.compile()
sc.write(frames)
cam = mujoco.MjvCamera()
cam.type = mujoco.mjtCamera.mjCAMERA_FREE
c = conf["camera"]
cam.lookat[:], cam.distance, cam.azimuth, cam.elevation = c["lookat"], c["distance"], c["azimuth"], \
c["elevation"]
with renderer(sc) as r:
r.update_scene(sc.data, camera=cam)
img = r.render()
out = args.image or "cover.png"
if args.ss > 1:
img = img.reshape(H, args.ss, W, args.ss, 3).mean((1, 3)).astype(np.uint8)
_save_png(out, img)
print("saved", out)
return
# demo_video
W, H = args.width or conf["width"], args.height or conf["height"]
fps, B, hide = conf["fps"], conf["blend"], conf.get("hide", 0) # hide: frames hidden as each loop restarts
sc = Scene(root, W, H, conf["fovy"])
loops = []
for i, row in enumerate(conf["instances"]):
m = get(row, i)
sc.add(m, place_of(row))
pp = bool(row.get("pingpong", False))
loops.append((m.loop(row["start"], row["loop"], B, pp), 2 * row["loop"] - 2 if pp else row["loop"],
row["phase"]))
sc.compile()
keys = conf["camera_keys"]
n = int(round(conf["seconds"] * fps)) if not args.seconds else int(round(args.seconds * fps))
ts = np.arange(n) / fps
kt = np.array([k[0] for k in keys])
eyes = pchip(kt, np.array([k[1] for k in keys]), ts)
tgts = pchip(kt, np.array([k[2] for k in keys]), ts)
cam = mujoco.MjvCamera()
cam.type = mujoco.mjtCamera.mjCAMERA_FREE
out = args.video or "demo_video.mp4"
wr = video_writer(out, W, H, fps)
with renderer(sc) as r:
for f in range(n):
sc.write([(st, (f + ph) % L, (f + ph) % L < hide) for st, L, ph in loops])
set_cam(cam, eyes[f], tgts[f])
r.update_scene(sc.data, camera=cam)
wr.send(np.ascontiguousarray(r.render()))
if f % 150 == 0:
print(f"frame {f}/{n}", flush=True)
wr.close()
print("saved", out)
def _save_png(path: str, img: np.ndarray) -> None:
import struct
import zlib
h, w, _ = img.shape
raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))
chunk = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF) # noqa
with open(path, "wb") as fh:
fh.write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) +
chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", default=str(Path(__file__).resolve().parent))
sub = ap.add_subparsers(dest="cmd", required=True)
a = sub.add_parser("list")
a.add_argument("--task", default="")
a = sub.add_parser("play")
a.add_argument("id")
a.add_argument("--video", default="")
a.add_argument("--width", type=int, default=1280)
a.add_argument("--height", type=int, default=720)
a.add_argument("--fovy", type=float, default=40.0)
a = sub.add_parser("scene")
a.add_argument("name", choices=["demo_video", "cover", "sections"])
a.add_argument("--video", default="")
a.add_argument("--image", default="")
a.add_argument("--width", type=int, default=0)
a.add_argument("--height", type=int, default=0)
a.add_argument("--seconds", type=float, default=0.0, help="demo_video: render only the first seconds")
a.add_argument("--ss", type=int, default=1, help="cover: supersampling factor")
args = ap.parse_args()
root = Path(args.root)
{"list": cmd_list, "play": cmd_play, "scene": cmd_scene}[args.cmd](root, args)
if __name__ == "__main__":
main()