OpenGHz's picture
Add fair-comparison/extract-train-v1
d26db08 verified
Raw History Blame Contribute Delete
28.9 kB
"""Extract keypose segments from recorded demonstrations, with stages set per task.
Without a planner there are no commanded phase targets. A task names its stages in
order (STAGES): moves, gripper closings and gripper openings. Every kept
demonstration gets exactly that many segments, however it was executed; one whose
gripper events do not match the task's (count or order) is excluded and listed.
Gripper events come from what the recording holds:
- ``width`` (recorded hands, lim.umi_data): the gripper opening alone, for a task
with a single grasp. ``close_gripper`` runs from the last fully-open frame to the
first closed frame, ``open_gripper`` from the last closed frame to the first
fully-open frame, and the demonstration is cropped there: the retreat after the
release carries little of the task. A recording that stops before the gripper is
back at the open stop ends its ``open_gripper`` at its last frame. A
demonstration that leaves the open stop more than once is excluded.
- ``command`` (simulated demonstrations, lim.collect_keyposes): the recorded
actions. A closing or opening starts at the action whose gripper command changes
sign and lasts until the first later action whose commanded arm pose differs
from the previous one (or the demonstration's end).
Consecutive moves between two gripper events are split by the task's stage
configuration: a move marked ``adjacent="next"`` is the straight motion just
before the next event (a final approach), one marked ``"previous"`` the straight
motion just after the previous event (a lift); the one unmarked move of the run
takes the rest. A straight motion is the longest stretch of the reached path,
pauses removed, that stays within a distance of its chord and an angle of the
orientation interpolated along it; its boundary is the first frame at which the
path arrives at its far end. A task may set such a move's least rise above its
gripper event, so that a pause next to the gripper is not taken for that arrival.
Paths and endpoints use the poses the recording commands when it holds commands
(simulated: the pd_ee_delta_pose goal of every action, the same targets the dense
labels use), and the poses reached otherwise (recorded hands). The reached path
lags the commanded one by several millimetres and rounds its corners. Frames index observations; ``action`` t is the move from frame t to
t + 1, so the labels keep lim.keypose_data's convention: segment k covers actions
``[start, end)`` and frame ``end`` is its endpoint. The output repeats the
dataset's traj group names, holding a ``keyframes`` group in the simulated
datasets' schema and the number of frames kept; dropped demonstrations have no
group, so the keyframes file also fixes which demonstrations, and which of their
frames, both representations train on.
"""
import json
from pathlib import Path
from typing import Literal
import h5py
import numpy as np
from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveFloat, model_validator
from pydantic_settings import CliApp
from lim import keypose_data
from lim.keypose_data import AnnotationConfig, KeyposeSegment, annotation_arrays
from lim.umi_data import FORMAT, file_digest
class Stage(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
name: str
kind: Literal["move", "close", "open"]
adjacent: Literal["next", "previous"] | None = None
"""Moves only: the straight motion right before the next gripper event, or
right after the previous one; unmarked, the move takes what is left."""
min_rise_m: PositiveFloat | None = None
"""Adjacent moves only: the boundary they leave to the neighbouring move lies at
least this far above (pose z) the gripper event they are anchored on."""
STAGES = {
"umi-open-drawer": (
Stage(name="approach", kind="move"),
Stage(name="close_gripper", kind="close"),
Stage(name="transport", kind="move"),
Stage(name="open_gripper", kind="open"),
),
# The native ManiSkill StackCube expert's six primitives. The grasp holds the
# TCP at the centre of a 4 cm cube: the descent starts above its top (2 cm, and
# 5 mm to spare), and the lift carries it at least a cube height, over cube B.
"StackCube-v1": (
Stage(name="approach", kind="move"),
Stage(name="grasp_pose", kind="move", adjacent="next", min_rise_m=0.025),
Stage(name="close_gripper", kind="close"),
Stage(name="lift", kind="move", adjacent="previous", min_rise_m=0.04),
Stage(name="place_pose", kind="move"),
Stage(name="open_gripper", kind="open"),
),
}
def check_stages(stages):
"""Each run of moves between gripper events: one unmarked move at most, the
``previous`` moves before it and the ``next`` ones after it, each with an event
on that side; more than one move needs exactly one unmarked."""
if not stages or stages[0].kind == "open":
raise ValueError("A task starts with the gripper open")
events = [s.kind for s in stages if s.kind != "move"]
if any(a == b for a, b in zip(events, events[1:])) or (events and events[0] != "close"):
raise ValueError("Closings and openings must alternate, starting with a closing")
if any(s.min_rise_m is not None and s.adjacent is None for s in stages):
raise ValueError("Only a move adjacent to a gripper event has a minimum rise")
runs, run = [], []
for index, stage in enumerate(stages):
if stage.kind == "move":
run.append(index)
else:
runs.append(run)
run = []
runs.append(run)
for position, run in enumerate(runs):
marks = [stages[i].adjacent for i in run]
if any(m == "previous" for m in marks) and position == 0:
raise ValueError("A move before the first event cannot follow one")
if any(m == "next" for m in marks) and position == len(runs) - 1:
raise ValueError("A move after the last event cannot precede one")
order = {"previous": 0, None: 1, "next": 2}
if [order[m] for m in marks] != sorted(order[m] for m in marks):
raise ValueError("Moves after an event come first, moves before an event last")
if len(run) > 1 and marks.count(None) != 1:
raise ValueError("A run of several moves needs exactly one unmarked move")
return runs
class KeyposeExtractConfig(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
dataset: Path
"""Converted recordings (lim.umi_data) or simulated demonstrations (trajectory.h5)."""
output: Path
"""New keyframes H5, one traj group per kept demonstration."""
audit: Path
"""New audit JSON."""
task: str = "umi-open-drawer"
"""Stage configuration (STAGES)."""
open_above: float | None = None
"""Width events: gripper value at or above which the gripper is fully open."""
closed_below: float | None = None
"""Width events: gripper value at or below which it is closed."""
stationary_m: PositiveFloat = 0.001
"""Path points closer than this to the previous kept point are dropped (pauses)."""
straight_m: PositiveFloat = 0.003
"""Largest distance of a straight motion's points from its chord."""
straight_deg: PositiveFloat = 3.0
"""Largest angle between its orientations and the ones interpolated along it."""
motion_m: PositiveFloat = 1e-4
"""Command events: an action moves the arm when its commanded pose moves more than this,"""
motion_rad: PositiveFloat = float(np.deg2rad(0.1))
"""or turns more than this, from the previous action's."""
demos: NonNegativeInt | None = None
"""Simulated datasets: only the first this many demonstrations (training order)."""
boundary_margin: NonNegativeInt = 3
"""Frames either side of an endpoint checked for interpolated poses (audit only)."""
sheets: Path | None = None
"""New directory for contact sheets of the first camera at every endpoint."""
@model_validator(mode="after")
def check(self):
if self.task not in STAGES:
raise ValueError(f"Unknown task {self.task}; known: {sorted(STAGES)}")
check_stages(STAGES[self.task])
if (self.open_above is None) != (self.closed_below is None):
raise ValueError("Width events need both thresholds")
if self.closed_below is not None and self.closed_below >= self.open_above:
raise ValueError("The closed threshold must lie below the open one")
return self
def segment_ends(gripper, open_above, closed_below):
"""Width events: end frames of the segments of the single grasp, the last being
where the demonstration is cropped, or the number of excursions from the open
stop when there is more than one."""
gripper = np.asarray(gripper)
full = gripper >= open_above
if not full[0]:
raise ValueError("The gripper must start fully open")
leaving = np.flatnonzero(full[:-1] & ~full[1:]) + 1
returning = np.flatnonzero(~full[:-1] & full[1:]) + 1
if len(leaving) == 0:
raise ValueError("The gripper never leaves the open stop")
if len(leaving) > 1:
return len(leaving)
last = len(gripper) - 1
back = int(returning[0]) if len(returning) else None
closed = np.flatnonzero(gripper[leaving[0]:back] <= closed_below) + leaving[0]
if len(closed) == 0:
raise ValueError("The gripper never closes")
if closed[-1] == last:
raise ValueError("The recording ends before the gripper starts opening")
return [int(leaving[0] - 1), int(closed[0]), int(closed[-1]), last if back is None else back]
def width_events(gripper, open_above, closed_below):
"""[(start, end)] of the closing and the opening, or the excursion count."""
ends = segment_ends(gripper, open_above, closed_below)
if isinstance(ends, int):
return ends
return [(ends[0], ends[1]), (ends[2], ends[3])]
def command_events(actions, commanded, motion_m, motion_rad):
"""[(start, end)] of every gripper event from the recorded commands: from the
action whose gripper command changes sign to the first later action whose
commanded pose (``commanded``, per frame) moves by more than the thresholds from
the previous action's, or to the last action."""
actions = np.asarray(actions, dtype=np.float64)
closed = actions[:, -1] < 0
if closed[0]:
raise ValueError("The gripper must start open")
starts = np.flatnonzero(closed[1:] != closed[:-1]) + 1
moving = (np.linalg.norm(np.diff(commanded[:, :3], axis=0), axis=1) > motion_m) | (
_quaternion_angle(commanded[1:, 3:7], commanded[:-1, 3:7]) > motion_rad
)
events = []
for index, start in enumerate(starts):
limit = starts[index + 1] if index + 1 < len(starts) else len(actions)
later = np.flatnonzero(moving[start + 1:limit]) + start + 1
events.append((int(start), int(later[0]) if len(later) else int(limit)))
return events
CONTROLLER_ROTATION_SCALE = -0.1
"""lim.action_encoding.ROTATION_SCALE (ManiSkill 3.0.1 CPU PDEEPoseController)."""
def _wxyz_to_matrix(q):
w, x, y, z = np.moveaxis(q / np.linalg.norm(q, axis=-1, keepdims=True), -1, 0)
return np.stack([
np.stack([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], -1),
np.stack([2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], -1),
np.stack([2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], -1),
], -2)
def _matrix_to_wxyz(m):
"""Shepperd's method, w >= 0."""
trace = np.trace(m, axis1=-2, axis2=-1)
q = np.empty(m.shape[:-2] + (4,))
for index in np.ndindex(m.shape[:-2]):
r, t = m[index], trace[index]
if t > 0:
s = 2 * np.sqrt(t + 1)
v = [s / 4, (r[2, 1] - r[1, 2]) / s, (r[0, 2] - r[2, 0]) / s, (r[1, 0] - r[0, 1]) / s]
else:
i = int(np.argmax(np.diag(r)))
j, k = (i + 1) % 3, (i + 2) % 3
s = 2 * np.sqrt(1 + r[i, i] - r[j, j] - r[k, k])
v = [0.0] * 4
v[0] = (r[k, j] - r[j, k]) / s
v[1 + i], v[1 + j], v[1 + k] = s / 4, (r[j, i] + r[i, j]) / s, (r[k, i] + r[i, k]) / s
v = np.asarray(v)
q[index] = v if v[0] >= 0 else -v
return q
def _euler_xyz(e):
"""Rx(e0) @ Ry(e1) @ Rz(e2), mani_skill's euler_angles_to_matrix(..., "XYZ")."""
c, s = np.cos(e), np.sin(e)
o, i = np.zeros(e.shape[:-1]), np.ones(e.shape[:-1])
rx = np.stack([np.stack([i, o, o], -1), np.stack([o, c[..., 0], -s[..., 0]], -1),
np.stack([o, s[..., 0], c[..., 0]], -1)], -2)
ry = np.stack([np.stack([c[..., 1], o, s[..., 1]], -1), np.stack([o, i, o], -1),
np.stack([-s[..., 1], o, c[..., 1]], -1)], -2)
rz = np.stack([np.stack([c[..., 2], -s[..., 2], o], -1), np.stack([s[..., 2], c[..., 2], o], -1),
np.stack([o, o, i], -1)], -2)
return rx @ ry @ rz
def commanded_poses(actions, tcp):
"""Per frame, the pose the recording commands: frame 0 the reached start, frame
t + 1 the pd_ee_delta_pose goal of action t, as
lim.chunk_coordinates.controller_pose_targets reconstructs it (xyz,wxyz)."""
actions, tcp = np.asarray(actions, dtype=np.float64), np.asarray(tcp, dtype=np.float64)
position = tcp[:-1, :3] + np.clip(actions[:, :3], -1, 1) * 0.1
rotation = actions[:, 3:6] / np.maximum(np.linalg.norm(actions[:, 3:6], axis=1, keepdims=True), 1)
matrix = _euler_xyz(rotation * CONTROLLER_ROTATION_SCALE) @ _wxyz_to_matrix(tcp[:-1, 3:7])
goals = np.concatenate([position, _matrix_to_wxyz(matrix)], 1)
return np.concatenate([tcp[:1], goals], 0)
def _quaternion_angle(a, b):
"""Angle between wxyz unit quaternions."""
dot = np.abs(np.sum(a * b, axis=-1)).clip(max=1.0)
return 2 * np.arccos(dot)
def _slerp(a, b, alpha):
if np.dot(a, b) < 0:
b = -b
dot = float(np.clip(np.dot(a, b), -1, 1))
angle = np.arccos(dot)
if angle < 1e-8:
return np.broadcast_to(a, (len(alpha), 4))
alpha = np.asarray(alpha)[:, None]
return (np.sin((1 - alpha) * angle) * a + np.sin(alpha * angle) * b) / np.sin(angle)
def straight_boundary(pose, anchor, limit, config: KeyposeExtractConfig, min_rise=None):
"""Boundary frame of the straight motion that ends (limit < anchor) or starts
(limit > anchor) at frame ``anchor``, searched no further than ``limit``; with
``min_rise``, no rest frame lower than that above the anchor."""
step = -1 if limit < anchor else 1
frames = np.arange(anchor, limit + step, step)
position, rotation = pose[frames, :3], pose[frames, 3:7]
kept = [0]
for i in range(1, len(frames)):
if np.linalg.norm(position[i] - position[kept[-1]]) >= config.stationary_m:
kept.append(i)
kept = np.asarray(kept)
best = 0
for c in range(1, len(kept)):
points = position[kept[: c + 1]]
chord = points[-1] - points[0]
length = np.linalg.norm(chord)
offsets = points - points[0]
if length > 0:
along = offsets @ chord / length
distance = np.linalg.norm(offsets - np.outer(along / length, chord), axis=1)
else:
distance = np.linalg.norm(offsets, axis=1)
arc = np.r_[0, np.cumsum(np.linalg.norm(np.diff(points, axis=0), axis=1))]
alpha = arc / arc[-1] if arc[-1] > 0 else np.linspace(0, 1, len(points))
expected = _slerp(rotation[kept[0]], rotation[kept[c]], alpha)
angle = _quaternion_angle(rotation[kept[: c + 1]], expected)
if distance.max() > config.straight_m or np.rad2deg(angle.max()) > config.straight_deg:
break
best = c
far = kept[best]
# The stretch includes the frames still at its far end (the arrival there).
while far + 1 < len(frames) and np.linalg.norm(position[far + 1] - position[far]) < config.stationary_m:
far += 1
# Inside that stretch the boundary is where the arm comes to rest at the far
# end: the farthest group of rest frames (reached by a step no longer than
# stationary_m and no longer than the steps before and after it; groups at most
# two frames apart), and the earliest frame of that group. A pause inside the
# motion is a nearer group. Without a rest frame, the far end itself.
times = frames[: far + 1]
speed = np.linalg.norm(np.diff(pose[:, :3], axis=0), axis=1)
arrival = np.r_[np.inf, speed][times]
after = np.r_[speed, np.inf][times]
before = np.r_[np.inf, np.inf, speed][times]
rest = times[(arrival <= config.stationary_m) & (arrival <= after) & (arrival <= before)]
rest = rest[rest != anchor]
# A demonstration sped up need not slow down at the far end; a pause next to
# the gripper is then the only rest, and lies below the task's rise.
if min_rise is not None:
rest = rest[pose[rest, 2] - pose[anchor, 2] >= min_rise]
if len(rest) == 0:
return int(frames[far])
farthest_first = sorted(rest, key=lambda frame: -abs(frame - anchor))
group = [farthest_first[0]]
for frame in farthest_first[1:]:
if abs(frame - group[-1]) > 2:
break
group.append(frame)
return int(min(group))
def stage_ends(pose, events, stages, config: KeyposeExtractConfig):
"""End frame of every stage, given the gripper events [(start, end)] and the
cropped length (the last event's end, or the last frame)."""
runs = check_stages(stages)
kinds = [s.kind for s in stages if s.kind != "move"]
if len(events) != len(kinds):
return None
bounds = [0]
for start, end in events:
bounds += [start, end]
last = events[-1][1] if stages[-1].kind != "move" else len(pose) - 1
bounds.append(last)
ends = {}
for position, run in enumerate(runs):
left, right = bounds[2 * position], bounds[2 * position + 1]
if right < left:
raise ValueError("Gripper events overlap")
if not run:
continue
if len(run) == 1:
ends[run[0]] = right
continue
for i in [i for i in run if stages[i].adjacent == "previous"]:
left = ends[i] = straight_boundary(pose, left, right, config, stages[i].min_rise_m)
for i in reversed([i for i in run if stages[i].adjacent == "next"]):
ends[i] = right
right = straight_boundary(pose, right, left, config, stages[i].min_rise_m)
ends[next(i for i in run if stages[i].adjacent is None)] = right
event_index = 0
for i, stage in enumerate(stages):
if stage.kind != "move":
ends[i] = events[event_index][1]
event_index += 1
result = [ends[i] for i in range(len(stages))]
if any(b <= a for a, b in zip([0, *result], result)):
raise ValueError(f"Empty or reversed stage: ends {result}")
return result
def extract(pose, gripper, config: KeyposeExtractConfig, actions=None):
"""Keyframe arrays of the cropped demonstration, or the reason it is excluded
(an int: excursions from the open stop; a str otherwise). With ``actions``,
``pose`` is the commanded pose per frame (commanded_poses)."""
stages = STAGES[config.task]
if actions is None:
events = width_events(gripper, config.open_above, config.closed_below)
if isinstance(events, int):
return events
else:
events = command_events(actions, pose, config.motion_m, config.motion_rad)
ends = stage_ends(pose, events, stages, config)
if ends is None:
return f"{len(events)} gripper events, the task has {sum(s.kind != 'move' for s in stages)}"
starts = (0, *ends[:-1])
if actions is None:
state, commands = 1.0, []
for stage in stages:
state = {"close": -1.0, "open": 1.0}.get(stage.kind, state)
commands.append(state)
else:
commands = [float(actions[start, -1]) for start in starts]
for start, end, command in zip(starts, ends, commands):
if not np.all(actions[start:end, -1] == command):
raise ValueError("The gripper command changes inside a stage")
segments = tuple(
KeyposeSegment(name=stage.name, kind=stage.kind, start=start, end=end, gripper=command,
target_pose=tuple(float(v) for v in pose[end]))
for stage, start, end, command in zip(stages, starts, ends, commands)
)
return annotation_arrays(AnnotationConfig(
segments=segments, source_steps=ends[-1], target_to_source=tuple(range(ends[-1]))))
def contact_sheets(directory, data, kept, names, camera, columns=15, tile=112):
"""One sheet per endpoint: the camera frame there for every kept demonstration."""
from PIL import Image, ImageDraw
directory.mkdir(parents=True)
rows = -(-len(kept) // columns)
for k, name in enumerate(names):
sheet = Image.new("RGB", (columns * tile, rows * tile))
for i, (traj, ends) in enumerate(kept):
image = Image.fromarray(data[f"{traj}/obs/rgb/{camera}"][ends[k]]).resize((tile, tile))
ImageDraw.Draw(image).text((3, 2), traj.removeprefix("traj_"), fill=(255, 255, 0))
sheet.paste(image, ((i % columns) * tile, (i // columns) * tile))
sheet.save(directory / f"{k}_{name}.jpg", quality=85)
def write_keyframes(out, traj, arrays, stages, reached, frames, attrs):
keyframes = out.create_group(f"{traj}/keyframes")
keyframes.attrs.update(frames=frames, schema_version=1, **attrs,
interval="actions[start:end]; obs[end] is the achieved endpoint",
label_scope="supervision only; never policy input")
for name, values in arrays.items():
keyframes.create_dataset(name, data=values)
for name, values in (("name", [s.name for s in stages]), ("kind", [s.kind for s in stages])):
keyframes.create_dataset(name, data=list(values), dtype=h5py.string_dtype("utf-8"))
keyframes.create_dataset("achieved_pose_world", data=reached[arrays["end_action"]])
def run(config: KeyposeExtractConfig):
with h5py.File(config.dataset, "r") as data:
recorded = data.attrs.get("format") == FORMAT
result = run_recorded(config) if recorded else run_simulated(config)
with config.audit.open("x") as stream:
stream.write(json.dumps(result, indent=1) + "\n")
if config.sheets is not None and recorded:
with h5py.File(config.dataset, "r") as data:
camera = next(iter(json.loads(data.attrs["config"])["cameras"]))
kept = [(row["traj"], row["end_frames"]) for row in result["rows"]]
contact_sheets(config.sheets, data, kept, [s.name for s in STAGES[config.task]], camera)
return result
def _header(out, config):
out.attrs.update(
dataset=str(config.dataset), dataset_sha256=file_digest(config.dataset),
extractor_sha256=file_digest(__file__), keypose_data_sha256=file_digest(keypose_data.__file__),
config=config.model_dump_json(),
)
def run_recorded(config: KeyposeExtractConfig):
"""Recordings converted by lim.umi_data: width events."""
if config.open_above is None:
raise ValueError("Recorded hands need the width thresholds")
stages = STAGES[config.task]
names = [s.name for s in stages]
rows, excluded = [], []
with h5py.File(config.dataset, "r") as data, h5py.File(config.output, "x") as out:
_header(out, config)
for traj in sorted(data, key=lambda name: int(name.split("_")[-1])):
group = data[traj]
pose, gripper = group["obs/hand_pose"][:], group["obs/gripper_width"][:]
try:
arrays = extract(pose, gripper, config)
except ValueError as error:
raise ValueError(f"{traj} ({group.attrs['source']}): {error}") from error
if not isinstance(arrays, dict):
reason = f"leaves the open stop {arrays} times" if isinstance(arrays, int) else arrays
excluded.append({"traj": traj, "source": group.attrs["source"], "reason": reason})
continue
ends = arrays["end_action"]
write_keyframes(out, traj, arrays, stages, pose, ends[-1] + 1, {
"source": "extracted from gripper events; no commanded targets",
"pose_frame": "VIO world (lim.umi_data)", "pose_encoding": "xyz,wxyz"})
times = group["timestamps"][:]
flagged = group["obs/hand_pose_interpolated"][:] | group["obs/head_pose_interpolated"][:]
margin = config.boundary_margin
close, open_ = names.index("close_gripper"), names.index("open_gripper")
rows.append({
"traj": traj, "source": group.attrs["source"], "recorded_frames": len(pose),
"end_frames": ends.tolist(), "reaches_open_stop": bool(gripper[ends[-1]] >= config.open_above),
"segment_seconds": dict(zip(names, np.diff(times[np.r_[0, ends]]).round(3).tolist())),
"interpolated_endpoints": [name for name, e in zip(names, ends)
if flagged[max(0, e - margin):e + margin + 1].any()],
"grasp_min_gripper": float(gripper[ends[close - 1]:ends[open_] + 1].min()),
})
summary = {}
for name in names:
seconds = [r["segment_seconds"][name] for r in rows]
summary[name] = {
"median_s": float(np.median(seconds)),
"min_s": min(seconds), "max_s": max(seconds),
"endpoints_interpolated": sum(name in r["interpolated_endpoints"] for r in rows),
}
return {
"dataset": str(config.dataset), "output": str(config.output), "output_sha256": file_digest(config.output),
"kept": len(rows), "excluded": excluded,
"frames_kept": sum(r["end_frames"][-1] + 1 for r in rows),
"frames_cropped": sum(r["recorded_frames"] - r["end_frames"][-1] - 1 for r in rows),
"cut_before_open_stop": [[r["traj"], r["source"]] for r in rows if not r["reaches_open_stop"]],
"segments": summary,
# A grasp that closes much further than the others may have lost the object.
"lowest_grasp_gripper": [[r["traj"], r["grasp_min_gripper"]]
for r in sorted(rows, key=lambda r: r["grasp_min_gripper"])[:5]],
"config": config.model_dump(mode="json"),
"rows": rows,
}
def run_simulated(config: KeyposeExtractConfig):
"""Simulated demonstrations (lim.collect_keyposes): command events, paths and
endpoints on the commanded poses of the recorded actions. The expert's own
keyframes are never read."""
stages = STAGES[config.task]
names = [s.name for s in stages]
rows, excluded = [], []
with h5py.File(config.dataset, "r") as data, h5py.File(config.output, "x") as out:
_header(out, config)
trajs = sorted(data, key=lambda name: int(name.split("_")[-1]))
if config.demos is not None:
trajs = trajs[: config.demos]
for traj in trajs:
group = data[traj]
actions, reached = group["actions"][:], group["obs/extra/tcp_pose"][:]
pose = commanded_poses(actions, reached)
try:
arrays = extract(pose, None, config, actions=actions)
except ValueError as error:
raise ValueError(f"{traj}: {error}") from error
if not isinstance(arrays, dict):
excluded.append({"traj": traj, "reason": arrays})
continue
ends = arrays["end_action"]
write_keyframes(out, traj, arrays, stages, reached, ends[-1] + 1, {
"source": "extracted from the recorded actions' commanded poses and gripper commands; "
"no planner primitives", "pose_frame": "world", "pose_encoding": "xyz,wxyz"})
rows.append({"traj": traj, "actions": len(actions), "end_frames": ends.tolist(),
"cropped_actions": len(actions) - int(ends[-1])})
lengths = {name: [int(e - s) for r in rows for k, (s, e) in enumerate(zip([0, *r["end_frames"]], r["end_frames"]))
if names[k] == name] for name in names}
return {
"dataset": str(config.dataset), "output": str(config.output), "output_sha256": file_digest(config.output),
"kept": len(rows), "excluded": excluded,
"segments": {name: {"median_actions": float(np.median(v)), "min": min(v), "max": max(v)}
for name, v in lengths.items()} if rows else {},
"config": config.model_dump(mode="json"),
"rows": rows,
}
if __name__ == "__main__":
run(CliApp.run(KeyposeExtractConfig))