diff --git a/.dockerignore b/.dockerignore index 71171c1..8c92a49 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,5 @@ /datasets/ +/agentic_design/ /src/ /docs/ diff --git a/autodata_core/__init__.py b/autodata_core/__init__.py index 4e3dc92..2d5bcae 100644 --- a/autodata_core/__init__.py +++ b/autodata_core/__init__.py @@ -5,7 +5,7 @@ Public entrypoints: -* :class:`DataGenerator` — orchestrates a single async generation job. +* :class:`DataGenerator` — runs one asynchronous generation job. * :class:`DataGenInfoPool` — source-demo container; built via :meth:`DataGenInfoPool.from_hdf5`. * :class:`GenerationAlgorithm` and concrete subclasses — pluggable algorithm surface. * :func:`get_algorithm`, :func:`iter_algorithms` — algorithm registry lookup. @@ -23,6 +23,7 @@ from autodata_core.data_generator import DataGenerator, GenerationResult from autodata_core.datagen_info import DatagenInfo from autodata_core.pool import DataGenInfoPool +from autodata_core.schedulegen import ScheduleGen from autodata_core.waypoint import MultiWaypoint, Waypoint, WaypointSequence, WaypointTrajectory __all__ = [ @@ -35,6 +36,7 @@ "MimicGen", "MultiWaypoint", "SoftMimicGen", + "ScheduleGen", "SkillGen", "Waypoint", "WaypointSequence", diff --git a/autodata_core/algorithms.py b/autodata_core/algorithms.py index 994b132..0354ef0 100644 --- a/autodata_core/algorithms.py +++ b/autodata_core/algorithms.py @@ -7,10 +7,10 @@ behavior diverges between Mimic, DexMimicGen, SkillGen, etc. Subclasses self-register at import time via :class:`_AlgorithmMeta`. -The main behavioral hook is :meth:`GenerationAlgorithm.plan_subtask_trajectory`, called by -``DataGenerator`` every time an EEF needs a new executable trajectory. Object-state adaptation is -routed through :meth:`GenerationAlgorithm.transform_source_eef_poses`. Rigid algorithms use the -default object-pose transform while SoftMimicGen overrides it with nodal TPS registration. +Per-subtask algorithms customize :meth:`GenerationAlgorithm.plan_subtask_trajectory`. +SkillGen adds planned transits, while SoftMimicGen adapts source poses using nodal registration. +ScheduleGen implements :meth:`GenerationAlgorithm.generate_and_execute_episode` because all +paths must be built before scheduling. Both hooks use the shared episode lifecycle. """ from __future__ import annotations @@ -18,16 +18,40 @@ import time import torch from collections.abc import Iterable, Iterator +from dataclasses import dataclass from typing import TYPE_CHECKING, Any from autodata_core.selection_strategy import make_selection_strategy if TYPE_CHECKING: + from isaaclab.managers import TerminationTermCfg + from autodata_core.data_generator import DataGenerator, _EEFGenerationState from autodata_core.waypoint import Waypoint from autodata_interfaces.datastream.datastream import Datastream from autodata_interfaces.tasks.subtask_spec import Subtask + +@dataclass(frozen=True) +class AlgorithmEpisodeResult: + """Result returned by an episode-level generation algorithm. + + Args: + success: Whether the executed episode satisfied the task success term. + diagnostics: Stable scalar diagnostics suitable for generation sidecars. + """ + + success: bool + diagnostics: tuple[tuple[str, str], ...] = () + + def __post_init__(self) -> None: + """Require a boolean outcome and uniquely named diagnostic entries.""" + assert isinstance(self.success, bool), "success must be a bool" + assert isinstance(self.diagnostics, tuple), "diagnostics must be a tuple" + names = tuple(name for name, _ in self.diagnostics) + assert len(names) == len(set(names)), "diagnostic names must be unique" + + REGISTERED_ALGORITHMS: dict[str, type[GenerationAlgorithm]] = {} @@ -35,6 +59,7 @@ def get_algorithm(name: str, **kwargs: Any) -> GenerationAlgorithm: """Construct the algorithm registered under ``name``, forwarding ``kwargs`` to its ``__init__``. Mimic and DexMimicGen take no kwargs. SkillGen requires ``motion_planners=`` (per-env dict). + ScheduleGen requires ``planning_contexts=`` (per-env arm and full-state planners). """ if name not in REGISTERED_ALGORITHMS: raise KeyError(f"Unknown algorithm {name!r}. Registered: {sorted(REGISTERED_ALGORITHMS)}") @@ -64,10 +89,41 @@ class GenerationAlgorithm(metaclass=_AlgorithmMeta): """ name: str = "" - expected_eef_count: int | tuple[int, ...] = 1 + expected_eef_count: int | tuple[int, ...] | None = 1 requires_motion_planner: bool = False uses_subtask_start_signals: bool = False supports_coordination: bool = False + plans_complete_episode: bool = False + + async def generate_and_execute_episode( + self, + *, + data_generator: DataGenerator, + env_id: int, + success_term: TerminationTermCfg, + env_action_queue: Any, + pause_subtask: bool, + ) -> AlgorithmEpisodeResult: + """Execute an episode-level algorithm after shared reset. + + Per-subtask algorithms leave :attr:`plans_complete_episode` false and never enter this + method. + + Args: + data_generator: Generator providing source data and environment interfaces. + env_id: Environment used for the attempt. + success_term: Task success condition. + env_action_queue: Queue consumed by the shared environment stepping loop. + pause_subtask: Whether the algorithm should pause at subtask boundaries. + + Returns: + Attempt outcome and algorithm diagnostics. + + Raises: + NotImplementedError: The algorithm does not plan complete episodes. + """ + + raise NotImplementedError(f"algorithm {self.name!r} does not plan complete episodes") def validate_setup(self, datastream: Datastream) -> None: """Validate source annotations against the composed datastream. diff --git a/autodata_core/data_generator.py b/autodata_core/data_generator.py index 2a5b797..bfe4ab1 100644 --- a/autodata_core/data_generator.py +++ b/autodata_core/data_generator.py @@ -12,6 +12,7 @@ import asyncio import contextlib import numpy as np +import time import torch from copy import deepcopy from dataclasses import dataclass, field @@ -30,9 +31,11 @@ from autodata_core.waypoint import MultiWaypoint, Waypoint, WaypointSequence, WaypointTrajectory from autodata_interfaces.env.reset_request import EnvResetRequest from autodata_interfaces.tasks.subtask_constraint_spec import SubTaskConstraintCoordinationScheme, SubTaskConstraintType +from autodata_utils.generation_result import record_generation_attempt if TYPE_CHECKING: from autodata_interfaces.datastream.datastream import Datastream + from autodata_utils.generation_result import AttemptLog @contextlib.asynccontextmanager @@ -55,11 +58,13 @@ class GenerationResult: success: Whether the task succeeded at any step of the attempt. extras: Algorithm-specific facts about the attempt, from :meth:`~autodata_core.algorithms.GenerationAlgorithm.attempt_extras`. + diagnostics: Scalar algorithm details recorded in the generation result. """ initial_state: dict success: bool extras: dict[str, Any] = field(default_factory=dict) + diagnostics: tuple[tuple[str, str], ...] = () @dataclass @@ -117,7 +122,23 @@ def __init__( self.datastream = datastream self.algorithm = algorithm self.src_demo_datagen_info_pool = datastream.source_pool - self.demo_keys = demo_keys + assert demo_keys is None or isinstance(demo_keys, list), "demo_keys must be a list or None" + self.demo_keys = None if demo_keys is None else tuple(demo_keys) + self._source_demo_indices: tuple[int, ...] | None = None + if self.demo_keys is not None: + assert self.demo_keys, "demo_keys must be non-empty or None" + assert all( + isinstance(key, str) and key for key in self.demo_keys + ), "demo_keys must contain non-empty strings" + assert len(self.demo_keys) == len(set(self.demo_keys)), "demo_keys must be unique" + pool_demo_keys = tuple(self.src_demo_datagen_info_pool.demo_keys) + assert len(pool_demo_keys) == len( + self.src_demo_datagen_info_pool.datagen_infos + ), "source demo keys and episodes are misaligned" + pool_indices = {key: index for index, key in enumerate(pool_demo_keys)} + unknown_keys = tuple(key for key in self.demo_keys if key not in pool_indices) + assert not unknown_keys, f"unknown source demo keys: {unknown_keys}" + self._source_demo_indices = tuple(pool_indices[key] for key in self.demo_keys) self._validate_eef_count_for_algorithm() self._validate_coordination_for_algorithm() @@ -132,9 +153,13 @@ def __repr__(self) -> str: # ------------------------------------------------------------------ def _validate_eef_count_for_algorithm(self) -> None: + """Check that the task's end-effector count is supported by the algorithm.""" num_eefs = len(self.datastream.get_eef_names()) expected = self.algorithm.expected_eef_count - ok = num_eefs == expected if isinstance(expected, int) else num_eefs in expected + if expected is None: + ok = num_eefs > 0 + else: + ok = num_eefs == expected if isinstance(expected, int) else num_eefs in expected if not ok: raise ValueError( f"Algorithm {self.algorithm.name!r} expects {expected} EEF(s), task descriptor defines {num_eefs}" @@ -228,15 +253,85 @@ def select_source_demo( object_nodal_positions: torch.Tensor | None = None, subtask_object_soft: bool = False, ) -> int: - """Pick a source demonstration index for a subtask via the configured strategy.""" + """Pick one source demonstration for a subtask. + + Args: + eef_name: End effector performing the subtask. + eef_pose: Current end-effector transform with shape ``(4, 4)`` [m]. + object_pose: Current reference-object transform [m], or None for object-free subtasks. + src_demo_current_subtask_boundaries: Start/end sample indices for each source demonstration. + subtask_object_name: Reference-object name, or None for object-free subtasks. + selection_strategy_name: Registered source-selection strategy. + selection_strategy_kwargs: Optional strategy settings. + object_nodal_positions: Current deformable-object nodes [m], or None. + subtask_object_soft: Whether the reference object uses nodal state. + + Returns: + Selected index in the source demonstration pool. + """ + + return self.select_source_demo_candidates( + eef_name=eef_name, + eef_pose=eef_pose, + object_pose=object_pose, + src_demo_current_subtask_boundaries=src_demo_current_subtask_boundaries, + subtask_object_name=subtask_object_name, + selection_strategy_name=selection_strategy_name, + selection_strategy_kwargs=selection_strategy_kwargs, + max_candidates=1, + object_nodal_positions=object_nodal_positions, + subtask_object_soft=subtask_object_soft, + )[0] + + def select_source_demo_candidates( + self, + eef_name: str, + eef_pose: torch.Tensor, + object_pose: torch.Tensor | None, + src_demo_current_subtask_boundaries: np.ndarray, + subtask_object_name: str | None, + selection_strategy_name: str, + selection_strategy_kwargs: dict | None = None, + max_candidates: int | None = None, + *, + object_nodal_positions: torch.Tensor | None = None, + subtask_object_soft: bool = False, + ) -> tuple[int, ...]: + """Select ordered source demonstrations without replacement for one subtask. + + Args: + eef_name: End effector performing the subtask. + eef_pose: Current end-effector transform with shape ``(4, 4)`` [m]. + object_pose: Current reference-object transform [m], or None for object-free subtasks. + src_demo_current_subtask_boundaries: Start/end sample indices for each source demonstration. + subtask_object_name: Reference-object name, or None for object-free subtasks. + selection_strategy_name: Registered source-selection strategy. + selection_strategy_kwargs: Optional strategy settings. + max_candidates: Maximum number of candidates; None keeps all eligible candidates. + object_nodal_positions: Current deformable-object nodes [m], or None. + subtask_object_soft: Whether the reference object uses nodal state. + + Returns: + Candidate indices in the source demonstration pool, in selection order. + """ + + assert max_candidates is None or ( + type(max_candidates) is int and max_candidates >= 1 + ), "max_candidates must be a positive integer or None" if subtask_object_name is None: assert selection_strategy_name == "random", selection_strategy_name + source_demo_indices: range | tuple[int, ...] + if self._source_demo_indices is None: + source_demo_indices = range(len(self.src_demo_datagen_info_pool.datagen_infos)) + else: + source_demo_indices = self._source_demo_indices + src_subtask_datagen_infos: list[DatagenInfo] = [] - for i in range(len(self.src_demo_datagen_info_pool.datagen_infos)): - src_ep = self.src_demo_datagen_info_pool.datagen_infos[i] - start_ind = src_demo_current_subtask_boundaries[i][0] - end_ind = src_demo_current_subtask_boundaries[i][1] + for source_demo_index in source_demo_indices: + src_ep = self.src_demo_datagen_info_pool.datagen_infos[source_demo_index] + start_ind = src_demo_current_subtask_boundaries[source_demo_index][0] + end_ind = src_demo_current_subtask_boundaries[source_demo_index][1] src_subtask_datagen_infos.append( DatagenInfo( eef_pose=src_ep.eef_pose[eef_name][start_ind:end_ind], @@ -258,13 +353,58 @@ def select_source_demo( strategy = make_selection_strategy(selection_strategy_name) kwargs = selection_strategy_kwargs or {} - return strategy.select_source_demo( + strategy_args = dict( eef_pose=eef_pose, object_pose=object_pose, src_subtask_datagen_infos=src_subtask_datagen_infos, - object_nodal_positions=object_nodal_positions, **kwargs, ) + if subtask_object_soft: + strategy_args["object_nodal_positions"] = object_nodal_positions + if max_candidates == 1: + selected = strategy.select_source_demo(**strategy_args) + return (source_demo_indices[selected],) + local_candidates = strategy.source_demo_candidates(**strategy_args) + candidates = tuple(source_demo_indices[index] for index in local_candidates) + return candidates if max_candidates is None else candidates[:max_candidates] + + def select_episode_source_candidates( + self, + env_id: int, + all_randomized_subtask_boundaries: dict[str, np.ndarray], + ) -> tuple[int, ...]: + """Select shared source demonstrations using the policy's anchor subtask. + + Args: + env_id: Environment whose current robot and object poses guide selection. + all_randomized_subtask_boundaries: Source start/end sample indices per end effector. + + Returns: + Ordered source-pool indices, or an empty tuple when no anchor is configured. + """ + + policy = self.datastream.get_generation_policy() + if policy.source_selection_anchor is None: + return () + eef_name, subtask_name = policy.source_selection_anchor.split(".", maxsplit=1) + subtasks = self.datastream.get_subtasks(eef_name) + subtask_index = next(index for index, subtask in enumerate(subtasks) if subtask.name == subtask_name) + subtask = subtasks[subtask_index] + object_name = subtask.object_ref or None + object_pose = ( + self.datastream.get_object_poses(env_ids=[env_id])[object_name][0] if object_name is not None else None + ) + candidates = self.select_source_demo_candidates( + eef_name=eef_name, + eef_pose=self.datastream.get_robot_eef_pose(env_ids=[env_id], eef_name=eef_name)[0], + object_pose=object_pose, + src_demo_current_subtask_boundaries=all_randomized_subtask_boundaries[eef_name][:, subtask_index], + subtask_object_name=object_name, + selection_strategy_name=subtask.selection_strategy, + selection_strategy_kwargs=subtask.selection_strategy_kwargs, + max_candidates=policy.source_candidate_count, + ) + return candidates # ------------------------------------------------------------------ # Subtask trajectory generation @@ -556,6 +696,81 @@ def merge_eef_subtask_trajectory( # Generation loop # ------------------------------------------------------------------ + async def generate_loop( + self, + env_id: int, + success_term: TerminationTermCfg, + env_reset_queue: asyncio.Queue, + env_action_queue: asyncio.Queue, + pause_subtask: bool, + stats: dict[str, int], + attempts: list[dict[str, Any]], + pending_env_ids: set[int], + attempt_log: AttemptLog | None = None, + ) -> None: + """Generate within a shared trial budget and hold slots while other episodes finish. + + Reservation and completion updates do not yield, so the simulator's event loop owns + the counters without a lock. The caller cancels this coroutine after reaching its target. + + Args: + env_id: Environment used by this generation coroutine. + success_term: Task success predicate. + env_reset_queue: Reset requests serviced by the synchronous simulator loop. + env_action_queue: Actions consumed by the synchronous simulator loop. + pause_subtask: Whether to pause at subtask boundaries. + stats: Shared completed-episode counters. + attempts: Shared completion-ordered episode results. + pending_env_ids: Environment slots with a reserved, unfinished episode. + attempt_log: Optional native metrics log receiving each completed attempt. + """ + + policy = self.datastream.get_generation_policy() + hold = None + while True: + if not policy.remaining_attempts(stats["num_attempts"], stats["num_success"], len(pending_env_ids)): + if hold is None: + hold = self._hold_current_pose(env_id) + await hold.execute(self.datastream, success_term, env_id, env_action_queue) + continue + assert env_id not in pending_env_ids + pending_env_ids.add(env_id) + hold = None + attempt_started = time.monotonic() + try: + result = await self.generate( + env_id=env_id, + success_term=success_term, + env_reset_queue=env_reset_queue, + env_action_queue=env_action_queue, + pause_subtask=pause_subtask, + ) + finally: + pending_env_ids.remove(env_id) + record_generation_attempt( + result, env_id, stats, attempts, attempt_log=attempt_log, start_time_s=attempt_started + ) + + def _hold_current_pose(self, env_id: int) -> MultiWaypoint: + """Capture fixed EEF targets and current passthrough commands for an idle slot. + + Args: + env_id: Environment whose targets should be held. + + Returns: + Waypoints encoded through the embodiment for each step, including relative controllers. + """ + + passthrough = self.datastream.get_passthrough_actions([env_id]) + if passthrough is None: + actions = self.datastream.get_env().action_manager.action[env_id : env_id + 1] + passthrough = self.datastream.actions_to_passthrough_actions(actions) + commands = {name: values[0].detach().clone() for name, values in passthrough.items()} + return MultiWaypoint({ + name: Waypoint(self.datastream.get_robot_eef_pose([env_id], name)[0].detach().clone(), commands, noise=0.0) + for name in self.datastream.get_eef_names() + }) + async def generate( self, env_id: int, @@ -571,6 +786,25 @@ async def generate( env_id=env_id, env_reset_queue=env_reset_queue ) + if self.algorithm.plans_complete_episode: + episode_result = await self.algorithm.generate_and_execute_episode( + data_generator=self, + env_id=env_id, + success_term=success_term, + env_action_queue=env_action_queue, + pause_subtask=pause_subtask, + ) + self._finalize_episode_recording( + env_id_tensor=env_id_tensor, + success=episode_result.success, + export_demo=export_demo, + ) + return GenerationResult( + initial_state=initial_state, + success=episode_result.success, + diagnostics=episode_result.diagnostics, + ) + runtime_constraints = self._build_runtime_subtask_constraints() eef_states = self._initialize_eef_states() selected_src_demo_inds: dict[str, int | None] = {name: None for name in self.datastream.get_eef_names()} @@ -651,13 +885,11 @@ async def generate( # Recorder lifecycle stays on env by design: the Datastream is # a read interface; controller-side mutation is reached through the get_env() escape hatch. - env = self.datastream.get_env() - env.recorder_manager.set_success_to_episodes( - env_id_tensor, - torch.tensor([[buffers.success]], dtype=torch.bool, device=self.datastream.device), + self._finalize_episode_recording( + env_id_tensor=env_id_tensor, + success=buffers.success, + export_demo=export_demo, ) - if export_demo: - env.recorder_manager.export_episodes(env_id_tensor) return GenerationResult( initial_state=initial_state, @@ -701,6 +933,15 @@ async def _reset_environment_for_generation( env_id: int, env_reset_queue: asyncio.Queue, ) -> tuple[torch.Tensor, dict]: + """Reset recording and the selected environment before capturing its state. + + Args: + env_id: Environment to reset. + env_reset_queue: Queue serviced by the synchronous simulator loop. + + Returns: + Environment index tensor and a copied, single-environment reset state. + """ env_id_tensor = torch.tensor([env_id], dtype=torch.int64, device=self.datastream.device) # Recorder + reset queue stay on env. The initial scene state # snapshot is read through the Datastream interface. @@ -708,7 +949,36 @@ async def _reset_environment_for_generation( completion = asyncio.get_running_loop().create_future() await env_reset_queue.put(EnvResetRequest(env_id=env_id, completion=completion)) await completion - return env_id_tensor, self.datastream.get_scene_state(is_relative=True) + return env_id_tensor, self.datastream.get_scene_state(is_relative=True, env_ids=[env_id]) + + def _finalize_episode_recording( + self, + *, + env_id_tensor: torch.Tensor, + success: bool, + export_demo: bool, + ) -> None: + """Set recorder success and export nonempty episodes after either algorithm path. + + Args: + env_id_tensor: Environment indices whose episodes have finished. + success: Whether the episode satisfies the task success condition. + export_demo: Whether to export the recorded episode. + """ + + env = self.datastream.get_env() + env.recorder_manager.set_success_to_episodes( + env_id_tensor, + torch.tensor([[success]], dtype=torch.bool, device=self.datastream.device), + ) + if export_demo: + env_ids = [ + env_id + for env_id in env_id_tensor.tolist() + if any(key != "initial_state" for key in env.recorder_manager.get_episode(env_id).data) + ] + if env_ids: + env.recorder_manager.export_episodes(env_ids) def _build_runtime_subtask_constraints(self) -> dict: runtime_constraints: dict = {} diff --git a/autodata_core/datagen_info.py b/autodata_core/datagen_info.py index ff8af39..fe42979 100644 --- a/autodata_core/datagen_info.py +++ b/autodata_core/datagen_info.py @@ -1,10 +1,7 @@ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Per-episode datagen schema consumed by :class:`DataGenerator`. - -This is the generator-internal stand-in for the eventual ``Datastream`` abstraction. -""" +"""Recorded source poses, annotation signals and action channels used during generation.""" from __future__ import annotations @@ -25,7 +22,9 @@ class DatagenInfo: object_nodal_positions: ``{object_name: [T, N, 3]}`` recorded deformable-object nodal positions [m]. subtask_term_signals: ``{subtask_name: [T]}`` binary completion flag per step. - subtask_start_signals: ``{subtask_name: [T]}`` binary start flag per step; required by SkillGen. + subtask_start_signals: ``{subtask_name: [T]}`` binary skill-start flags for SkillGen and ScheduleGen. + object_event_signals: ``{event_name: [T]}`` grasp/release flags used by ScheduleGen's + object ownership tracking, separate from the shared skill-boundary signals. target_eef_pose: ``{eef_name: [T, 4, 4]}`` controller target poses [m, rad]. passthrough_action: ``{channel_name: [T, D]}`` non-pose actions copied verbatim from the source demo, keyed by channel (eef grippers/hands plus any non-eef channel such as a @@ -41,7 +40,9 @@ def __init__( subtask_start_signals: dict[str, Any] | None = None, target_eef_pose: dict[str, torch.Tensor] | None = None, passthrough_action: dict[str, torch.Tensor] | None = None, + object_event_signals: dict[str, torch.Tensor] | None = None, ) -> None: + """Store source tensors and annotation mappings.""" self.eef_pose = eef_pose self.object_poses = dict(object_poses) if object_poses is not None else None self.object_nodal_positions = dict(object_nodal_positions) if object_nodal_positions is not None else None @@ -49,6 +50,7 @@ def __init__( self.subtask_start_signals = dict(subtask_start_signals) if subtask_start_signals is not None else None self.target_eef_pose = target_eef_pose self.passthrough_action = passthrough_action + self.object_event_signals = dict(object_event_signals) if object_event_signals is not None else None @classmethod def from_episode(cls, ep_grp: dict, eef_name_map: dict[str, str] | None = None) -> DatagenInfo: @@ -86,11 +88,12 @@ def _rename(poses: dict[str, torch.Tensor] | None) -> dict[str, torch.Tensor] | object_nodal_positions=datagen_info.get("object_nodal_position"), subtask_term_signals=datagen_info.get("subtask_term_signals"), subtask_start_signals=datagen_info.get("subtask_start_signals"), + object_event_signals=datagen_info.get("object_event_signals"), target_eef_pose=_rename(datagen_info.get("target_eef_pose")), ) def to_dict(self) -> dict[str, Any]: - """Materialize a dict with only the populated fields.""" + """Return a dictionary containing only populated fields.""" out: dict[str, Any] = {} if self.eef_pose is not None: out["eef_pose"] = self.eef_pose @@ -106,4 +109,6 @@ def to_dict(self) -> dict[str, Any]: out["target_eef_pose"] = self.target_eef_pose if self.passthrough_action is not None: out["passthrough_action"] = self.passthrough_action + if self.object_event_signals is not None: + out["object_event_signals"] = deepcopy(self.object_event_signals) return out diff --git a/autodata_core/pool.py b/autodata_core/pool.py index 949468e..440923b 100644 --- a/autodata_core/pool.py +++ b/autodata_core/pool.py @@ -11,6 +11,7 @@ from __future__ import annotations import asyncio +import torch from typing import TYPE_CHECKING from isaaclab.utils.datasets import EpisodeData, HDF5DatasetFileHandler @@ -23,7 +24,11 @@ class DataGenInfoPool: - """Container of source :class:`DatagenInfo` records keyed by EEF subtask boundary.""" + """Source records and skill boundaries shared by all generation algorithms. + + Stable demo keys support source selection. ScheduleGen additionally reads object-event + annotations through :meth:`get_object_event_index`; ordinary skill slicing does not use them. + """ def __init__( self, @@ -40,12 +45,13 @@ def __init__( grippers plus any non-eef channels) via ``actions_to_passthrough_actions``. device: Target torch device for episode tensors. uses_start_signals: Whether the algorithm reads subtask start signals - (SkillGen-only). Selects how subtask boundaries are parsed and validated. + (SkillGen and ScheduleGen). Selects how subtask boundaries are parsed and validated. asyncio_lock: Optional lock guarding concurrent ``add_episode`` calls when a single pool feeds multiple async generators. """ self._datagen_infos: list[DatagenInfo] = [] self._subtask_boundaries: dict[str, list[list[tuple[int, int]]]] = {} + self._demo_keys: list[str] = [] self.task_descriptor = task_descriptor self.embodiment_adapter = embodiment_adapter @@ -54,12 +60,16 @@ def __init__( self._asyncio_lock = asyncio_lock self.subtask_term_signal_names: dict[str, list[str]] = {} + self.subtask_start_signal_names: dict[str, list[str]] = {} self.subtask_term_offset_ranges: dict[str, list[tuple[int, int]]] = {} self.subtask_start_offset_ranges: dict[str, list[tuple[int, int]]] = {} for eef_name in task_descriptor.get_eef_names(): subtasks = task_descriptor.get_subtasks(eef_name) self.subtask_term_signal_names[eef_name] = [st.subtask_term_signal for st in subtasks] + self.subtask_start_signal_names[eef_name] = [ + st.subtask_start_signal or st.subtask_term_signal for st in subtasks + ] self.subtask_term_offset_ranges[eef_name] = [st.subtask_term_offset_range for st in subtasks] self.subtask_start_offset_ranges[eef_name] = [ getattr(st.algo_params, "subtask_start_offset_range", (0, 0)) for st in subtasks @@ -90,7 +100,7 @@ def from_hdf5( for episode_name in episode_names: if select_demo_keys is not None and episode_name not in select_demo_keys: continue - pool._add_episode(handler.load_episode(episode_name, device)) + pool._add_episode(handler.load_episode(episode_name, device), demo_key=episode_name) return pool @property @@ -101,6 +111,32 @@ def datagen_infos(self) -> list[DatagenInfo]: def subtask_boundaries(self) -> dict[str, list[list[tuple[int, int]]]]: return self._subtask_boundaries + @property + def demo_keys(self) -> tuple[str, ...]: + """Source episode keys ordered exactly like :attr:`datagen_infos`.""" + + return tuple(self._demo_keys) + + def get_object_event_index(self, demo_index: int, annotation_key: str) -> int: + """Return a ScheduleGen attachment/release annotation without skill-boundary offsets. + + Args: + demo_index: Index of the selected source demonstration in this pool. + annotation_key: Event signal named in the task descriptor. + + Returns: + First active source-state sample, with no subtask-end offset. + + Raises: + AssertionError: The selected source has no mark with this name. + ValueError: The signal is empty, nonbinary, or has no active sample. + """ + signals = self._datagen_infos[demo_index].object_event_signals + assert ( + signals is not None and annotation_key in signals + ), f"source demo {self._demo_keys[demo_index]!r} is missing object event {annotation_key!r}" + return self._find_first_rising_edge(signals[annotation_key], signal_name=annotation_key) + @property def asyncio_lock(self) -> asyncio.Lock | None: return self._asyncio_lock @@ -117,10 +153,20 @@ async def add_episode(self, episode: EpisodeData) -> None: else: self._add_episode(episode) - def _add_episode(self, episode: EpisodeData) -> None: + def _add_episode(self, episode: EpisodeData, *, demo_key: str | None = None) -> None: + """Parse source annotations and append an episode with its subtask boundaries. + + Args: + episode: Recorded actions, poses and annotation signals. + demo_key: Source episode name; generated from the pool index when omitted. + """ ep_grp = episode.data ep_datagen_info = DatagenInfo.from_episode(ep_grp) + if ep_datagen_info.subtask_term_signals is None and all( + len(self.task_descriptor.get_subtasks(eef_name)) == 1 for eef_name in self.task_descriptor.get_eef_names() + ): + ep_datagen_info.subtask_term_signals = {} missing = [ name for name in ("eef_pose", "target_eef_pose", "subtask_term_signals") @@ -151,7 +197,32 @@ def _add_episode(self, episode: EpisodeData) -> None: ep_datagen_info.target_eef_pose = {configured_eef: target_eef_pose[source_eef]} ep_datagen_info.passthrough_action = self.embodiment_adapter.actions_to_passthrough_actions(ep_grp["actions"]) + + object_event_signals = ep_grp["obs"]["datagen_info"].get("object_event_signals", {}) + required_events = { + event.annotation_key + for eef_name in self.task_descriptor.get_eef_names() + for subtask in self.task_descriptor.get_subtasks(eef_name) + for segment in subtask.segments + for event in segment.events + if event.annotation_key + } + assert required_events <= object_event_signals.keys(), ( + f"source demo {demo_key!r} is missing object_event_signals: " + f"{sorted(required_events - object_event_signals.keys())}" + ) + for name, signal in object_event_signals.items(): + assert signal.ndim in (1, 2) and signal.shape[0] == signal.numel() == len( + ep_grp["actions"] + ), f"object event {name!r} must contain one scalar per source action" + self._find_first_rising_edge(signal, signal_name=name) + if demo_key is None: + index = len(self._datagen_infos) + while (demo_key := f"demo_{index}") in self._demo_keys: + index += 1 + assert demo_key not in self._demo_keys, f"duplicate source demo key {demo_key!r}" self._datagen_infos.append(ep_datagen_info) + self._demo_keys.append(demo_key) for eef_name in self.subtask_term_signal_names.keys(): self._subtask_boundaries.setdefault(eef_name, []) @@ -165,35 +236,77 @@ def _parse_subtask_boundaries( ) -> list[tuple[int, int]]: """Compute ``[(start, end), ...]`` indices for each subtask of ``eef_name`` in this episode.""" use_skillgen = self.uses_start_signals - signal_names = self.subtask_term_signal_names[eef_name] + term_signal_names = self.subtask_term_signal_names[eef_name] + start_signal_names = self.subtask_start_signal_names[eef_name] boundaries: list[tuple[int, int]] = [] prev_end = 0 - for subtask_index, signal_name in enumerate(signal_names): + for subtask_index, term_signal_name in enumerate(term_signal_names): if use_skillgen: if ep.subtask_start_signals is None: raise ValueError( - f"subtask_start_signals missing for subtask {signal_name!r} but use_skillgen is enabled" + f"subtask_start_signals missing for subtask {term_signal_name!r} but use_skillgen is enabled" ) - start_indicators = ep.subtask_start_signals[signal_name].flatten().int() - start_index = int((start_indicators[1:] - start_indicators[:-1]).nonzero()[0][0]) + 1 + start_signal_name = start_signal_names[subtask_index] + if not start_signal_name: + raise ValueError(f"subtask {eef_name}[{subtask_index}] has no start signal") + if start_signal_name not in ep.subtask_start_signals: + raise ValueError(f"subtask start signal {start_signal_name!r} is missing from the episode") + start_index = self._find_first_rising_edge( + ep.subtask_start_signals[start_signal_name], + signal_name=start_signal_name, + ) else: start_index = prev_end - if subtask_index == len(signal_names) - 1: + if subtask_index == len(term_signal_names) - 1: end_index = ep_grp["actions"].shape[0] else: - term_indicators = ep.subtask_term_signals[signal_name].flatten().int() - end_index = int((term_indicators[1:] - term_indicators[:-1]).nonzero()[0][0]) + 2 + if not term_signal_name: + raise ValueError(f"non-final subtask {eef_name}[{subtask_index}] has no termination signal") + if ep.subtask_term_signals is None or term_signal_name not in ep.subtask_term_signals: + raise ValueError(f"subtask termination signal {term_signal_name!r} is missing from the episode") + end_index = ( + self._find_first_rising_edge( + ep.subtask_term_signals[term_signal_name], + signal_name=term_signal_name, + ) + + 1 + ) if end_index <= start_index: - raise ValueError(f"subtask {signal_name!r} has non-increasing boundary: {start_index} -> {end_index}") + raise ValueError( + f"subtask {eef_name}[{subtask_index}] has non-increasing boundary: {start_index} -> {end_index}" + ) boundaries.append((start_index, end_index)) prev_end = end_index self._validate_subtask_offsets(eef_name, boundaries) return boundaries + @staticmethod + def _find_first_rising_edge(signal, *, signal_name: str) -> int: + """Return the first ``0 -> 1`` index, or zero for an initially true signal. + + Later signal changes do not move a boundary that has already been reached. + """ + + values = torch.as_tensor(signal).flatten() + if values.numel() == 0: + raise ValueError(f"annotation signal {signal_name!r} is empty") + if not torch.all((values == 0) | (values == 1)): + raise ValueError(f"annotation signal {signal_name!r} must be binary") + values = values.to(dtype=torch.int8) + differences = values[1:] - values[:-1] + rising_edges = (differences == 1).nonzero().flatten() + 1 + if values[0] == 1: + rising_edges = torch.cat( + [torch.zeros(1, dtype=rising_edges.dtype, device=rising_edges.device), rising_edges] + ) + if rising_edges.numel() == 0: + raise ValueError(f"annotation signal {signal_name!r} has no rising edge") + return int(rising_edges[0].item()) + def _validate_subtask_offsets(self, eef_name: str, boundaries: list[tuple[int, int]]) -> None: """Sanity-check that the worst-case randomized boundaries stay non-empty and non-overlapping.""" start_offsets = self.subtask_start_offset_ranges[eef_name] diff --git a/autodata_core/schedulegen/__init__.py b/autodata_core/schedulegen/__init__.py new file mode 100644 index 0000000..e3dbd7a --- /dev/null +++ b/autodata_core/schedulegen/__init__.py @@ -0,0 +1,26 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Complete-path generation, collision checks, scheduling and replay for ScheduleGen.""" + +from autodata_core.schedulegen.algorithm import ScheduleGen +from autodata_core.schedulegen.types import ( + ArmPath, + ArmWaypointConflict, + ObjectStateSample, + PathObjectEvent, + PathObjectPose, + ScheduledObjectEvent, + ScheduledObjectPose, +) + +__all__ = [ + "ArmPath", + "ArmWaypointConflict", + "ObjectStateSample", + "PathObjectEvent", + "PathObjectPose", + "ScheduledObjectEvent", + "ScheduledObjectPose", + "ScheduleGen", +] diff --git a/autodata_core/schedulegen/algorithm.py b/autodata_core/schedulegen/algorithm.py new file mode 100644 index 0000000..2b38177 --- /dev/null +++ b/autodata_core/schedulegen/algorithm.py @@ -0,0 +1,1234 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build, schedule, validate and replay complete episodes with ScheduleGen.""" + +from __future__ import annotations + +import math +import time +import torch +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from itertools import combinations +from typing import TYPE_CHECKING, Any + +from autodata_core.algorithms import AlgorithmEpisodeResult, GenerationAlgorithm +from autodata_core.schedulegen.types import ( + ArmPath, + ArmWaypointConflict, + EpisodeGenerationError, + EpisodePaths, + ObjectStateSample, + ScheduledObjectEvent, + ScheduledObjectPose, + ScheduledRobotContact, + ScheduledWorldContact, +) +from autodata_core.waypoint import MultiWaypoint, Waypoint +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory +from autodata_utils import pose_math + +if TYPE_CHECKING: + from isaaclab.managers import TerminationTermCfg + + from autodata_core.data_generator import DataGenerator + from autodata_core.scheduling import Schedule + from autodata_interfaces.datastream.datastream import Datastream + from autodata_interfaces.motion_planners.curobo.collision_spheres import ObjectCollisionSpheres + from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner + from autodata_interfaces.motion_planners.curobo.planner_factory import CuroboPlanningContext + from autodata_interfaces.tasks.schedule_constraint_spec import ScheduleSpec, SegmentId + + +@dataclass(frozen=True) +class _ValidatedEpisode: + """Paths and a schedule that passed the configured checks before replay.""" + + arm_paths: Mapping[str, ArmPath] + schedule: Schedule + replay_joint_trajectory: NamedJointTrajectory | None + diagnostics_before_success: tuple[tuple[str, str], ...] + diagnostics_after_success: tuple[tuple[str, str], ...] + + +@dataclass +class _PreparedEpisode: + """One reset scene and its paths, independent of the selected replay environment.""" + + planning_env_id: int + initial_state: dict + initial_object_poses: Mapping[str, torch.Tensor] + initial_joint_positions: torch.Tensor + selected_source: dict[str, int | None] + source_candidate_diagnostics: tuple[tuple[str, str], ...] = () + paths: EpisodePaths | None = None + conflicts: tuple[ArmWaypointConflict, ...] = () + validated: _ValidatedEpisode | None = None + result: AlgorithmEpisodeResult | None = None + start_time_s: float = field(default_factory=time.monotonic) + + +class ScheduleGen(GenerationAlgorithm): + """Build complete paths, schedule them and replay collision-checked episodes. + + Planning contexts and path-builder caches are isolated per environment. Scene reset, + recording and dataset export remain owned by :class:`DataGenerator`. + """ + + name = "schedulegen" + expected_eef_count = None + requires_motion_planner = True + uses_subtask_start_signals = True + supports_coordination = False + plans_complete_episode = True + + def __init__( + self, + planning_contexts: Mapping[int, CuroboPlanningContext], + *, + collision_densify_factor: int = 1, + attempt_diagnostics: Callable[[Datastream, int, TerminationTermCfg], tuple[tuple[str, str], ...]] | None = None, + ) -> None: + """Create the algorithm with one planning context per environment. + + Args: + planning_contexts: Arm planners and a full-state collision model per environment. + collision_densify_factor: Linear collision samples per waypoint interval. + attempt_diagnostics: Optional task-owned terminal diagnostics callback. + """ + + from autodata_core.schedulegen.path_builder import PathBuilder + + assert planning_contexts, "ScheduleGen requires at least one planning context" + assert all( + type(env_id) is int and env_id >= 0 for env_id in planning_contexts + ), "planning context keys must be non-negative environment indices" + assert attempt_diagnostics is None or callable(attempt_diagnostics) + assert type(collision_densify_factor) is int and collision_densify_factor >= 1 + self.planning_contexts = dict(planning_contexts) + self.collision_densify_factor = collision_densify_factor + self.attempt_diagnostics = attempt_diagnostics + self._path_builders: dict[int, PathBuilder] = {} + for env_id, context in self.planning_contexts.items(): + assert context.group_planners, "planners must not be empty" + if context.full_state is not None: + assert not context.full_state.config.planning_enabled, "full-state context must disable planning" + self._path_builders[env_id] = PathBuilder(context.group_planners) + + def validate_setup(self, datastream: Datastream) -> None: + """Check that the task defines named segments and a schedule. + + Args: + datastream: Composed task, embodiment and environment interfaces. + + Raises: + AssertionError: A required segment or schedule setting is missing. + """ + + schedule_spec = datastream.get_schedule_spec() + assert schedule_spec is not None, "ScheduleGen requires a task schedule specification" + assert datastream.get_eef_names(), "ScheduleGen requires at least one end effector" + for eef_name in datastream.get_eef_names(): + for subtask_index, subtask in enumerate(datastream.get_subtasks(eef_name)): + assert ( + subtask.name and subtask.segments + ), f"ScheduleGen subtask {eef_name}[{subtask_index}] requires a stable name and segments" + + async def generate_and_execute_episode( + self, + *, + data_generator: DataGenerator, + env_id: int, + success_term: TerminationTermCfg, + env_action_queue: Any, + pause_subtask: bool, + ) -> AlgorithmEpisodeResult: + """Build all paths, schedule them, restore the scene and replay one attempt. + + Path-building, scheduling and validation failures are returned as failed attempts. + Scene reset, recording and dataset export remain owned by :class:`DataGenerator`. + + Args: + data_generator: Generator providing the source data and environment interfaces. + env_id: Environment used for this attempt. + success_term: Task success condition evaluated during and after replay. + env_action_queue: Queue consumed by the shared environment stepping loop. + pause_subtask: Common algorithm option; unused for complete-episode scheduling. + + Returns: + Attempt outcome with source choices, failure stage and schedule diagnostics. + """ + + del pause_subtask + assert env_id in self.planning_contexts, f"no ScheduleGen planning context configured for env {env_id}" + prepared = self._episode_prepare(data_generator, env_id, success_term) + if prepared.result is not None: + return prepared.result + try: + prepared.validated = self._episode_validate( + data_generator=data_generator, + episode_paths=prepared.paths, + initial_object_poses=prepared.initial_object_poses, + initial_joint_positions=prepared.initial_joint_positions, + schedule_spec=data_generator.datastream.get_schedule_spec(), + env_id=env_id, + ) + except EpisodeGenerationError as failure: + self._state_restore(data_generator.datastream, prepared.initial_state, env_id) + return self._failure_result( + data_generator=data_generator, + env_id=env_id, + success_term=success_term, + selected_source=prepared.selected_source, + source_candidate_diagnostics=prepared.source_candidate_diagnostics, + failure=failure, + ) + self._state_restore(data_generator.datastream, prepared.initial_state, env_id) + return await self._episode_execute(data_generator, prepared, env_id, success_term, env_action_queue) + + def _episode_prepare( + self, data_generator: DataGenerator, env_id: int, success_term: TerminationTermCfg + ) -> _PreparedEpisode: + """Capture the selected reset scene and build complete unscheduled paths. + + Args: + data_generator: Generator providing source selection and the datastream. + env_id: Environment whose reset scene is used for planning. + success_term: Task success predicate used in failure diagnostics. + + Returns: + Reset state and complete paths, or a recorded preparation failure. + """ + + planners = self.planning_contexts[env_id].group_planners + datastream = data_generator.datastream + eef_names = tuple(datastream.get_eef_names()) + assert set(planners) == set(eef_names), "planner keys must match task EEF names" + schedule_spec = datastream.get_schedule_spec() + assert schedule_spec is not None, "ScheduleGen requires a schedule specification" + + prepared = _PreparedEpisode( + planning_env_id=env_id, + initial_state=datastream.get_scene_state(is_relative=True, env_ids=[env_id]), + initial_object_poses={ + object_ref: poses[0].detach().clone() + for object_ref, poses in datastream.get_object_poses(env_ids=[env_id]).items() + }, + initial_joint_positions=datastream.get_robot_joint_positions(env_ids=[env_id])[0].detach().clone(), + selected_source={name: None for name in eef_names}, + ) + boundaries = data_generator.randomize_subtask_boundaries() + try: + prepared.paths, prepared.source_candidate_diagnostics = self._path_builders[env_id].build( + data_generator, + env_id, + eef_names, + prepared.selected_source, + boundaries=boundaries, + ) + except EpisodeGenerationError as failure: + self._state_restore(datastream, prepared.initial_state, env_id) + prepared.result = self._failure_result( + data_generator=data_generator, + env_id=env_id, + success_term=success_term, + selected_source=prepared.selected_source, + source_candidate_diagnostics=prepared.source_candidate_diagnostics, + failure=failure, + ) + + return prepared + + async def _episode_execute( + self, + data_generator: DataGenerator, + prepared: _PreparedEpisode, + env_id: int, + success_term: TerminationTermCfg, + env_action_queue: Any, + ) -> AlgorithmEpisodeResult: + """Replay a validated episode using the target environment's controller. + + Args: + data_generator: Generator providing the live datastream. + prepared: Validated paths and the planning context used to build them. + env_id: Replay environment, which may differ from the planning environment. + success_term: Task success predicate evaluated during replay. + env_action_queue: Queue consumed by the shared simulator stepping loop. + + Returns: + Replay outcome with task, schedule and tracking diagnostics. + """ + + validated_episode = prepared.validated + assert validated_episode is not None + datastream = data_generator.datastream + planners = self.planning_contexts[prepared.planning_env_id].group_planners + try: + success, first_success_tick = await self._schedule_replay( + data_generator=data_generator, + env_id=env_id, + success_term=success_term, + env_action_queue=env_action_queue, + arm_paths=dict(validated_episode.arm_paths), + schedule=validated_episode.schedule, + joint_trajectory=validated_episode.replay_joint_trajectory, + planning_env_id=prepared.planning_env_id, + ) + except EpisodeGenerationError as failure: + return self._failure_result( + data_generator=data_generator, + env_id=env_id, + success_term=success_term, + selected_source=prepared.selected_source, + source_candidate_diagnostics=prepared.source_candidate_diagnostics, + failure=failure, + validated_episode=validated_episode, + tracking_paths=validated_episode.arm_paths, + planning_env_id=prepared.planning_env_id, + ) + finally: + if validated_episode.replay_joint_trajectory is not None: + datastream.reset_robot_joint_posture_target(env_id) + + return AlgorithmEpisodeResult( + success=success, + diagnostics=( + ("stage", "complete" if success else "task_evaluation"), + ("replayed", "true"), + *_source_demo_diagnostics(data_generator, prepared.selected_source), + *prepared.source_candidate_diagnostics, + *_validated_episode_diagnostics(validated_episode, first_success_tick), + *_terminal_tracking_diagnostics( + datastream, + planners, + validated_episode.arm_paths, + env_id, + ), + *self._attempt_diagnostics_collect(data_generator, env_id, success_term), + ), + ) + + def _failure_result( + self, + *, + data_generator: DataGenerator, + env_id: int, + success_term: TerminationTermCfg, + selected_source: Mapping[str, int | None], + source_candidate_diagnostics: tuple[tuple[str, str], ...], + failure: EpisodeGenerationError, + validated_episode: _ValidatedEpisode | None = None, + tracking_paths: Mapping[str, ArmPath] | None = None, + planning_env_id: int | None = None, + ) -> AlgorithmEpisodeResult: + """Collect failure diagnostics without resetting an attempted replay. + + Args: + data_generator: Generator providing the live scene and source pool. + env_id: Environment whose terminal state is inspected. + success_term: Task predicate used by task-specific diagnostics. + selected_source: Selected source indices keyed by end effector. + source_candidate_diagnostics: Candidate choices and earlier source rejections. + failure: Expected preparation, validation or replay error. + validated_episode: Validated schedule when replay was attempted, or None. + tracking_paths: Paths used to compare final actual and target poses. + planning_env_id: Planning context to reuse, or None for the replay environment. + + Returns: + Failed attempt with stage, source, motion and task diagnostics. + """ + + planners = self.planning_contexts[env_id if planning_env_id is None else planning_env_id].group_planners + validation_diagnostics = ( + _validated_episode_diagnostics(validated_episode, None) if validated_episode is not None else () + ) + tracking_diagnostics = ( + _terminal_tracking_diagnostics(data_generator.datastream, planners, tracking_paths, env_id) + if tracking_paths is not None + else () + ) + return AlgorithmEpisodeResult( + success=False, + diagnostics=( + ("stage", failure.stage), + ("replayed", "true" if validated_episode is not None else "false"), + ("message", str(failure)), + *_source_demo_diagnostics(data_generator, selected_source), + *source_candidate_diagnostics, + *validation_diagnostics, + *failure.diagnostics, + *tracking_diagnostics, + *self._attempt_diagnostics_collect(data_generator, env_id, success_term), + ), + ) + + def _episode_validate( + self, + *, + data_generator: DataGenerator, + episode_paths: EpisodePaths, + initial_object_poses: Mapping[str, torch.Tensor], + initial_joint_positions: torch.Tensor, + schedule_spec: ScheduleSpec, + env_id: int = 0, + ) -> _ValidatedEpisode: + """Find conflicts, solve a schedule and check the combined paths. + + Args: + data_generator: Generator providing task and embodiment interfaces. + episode_paths: Complete paths and carried-object geometry. + initial_object_poses: Object transforms at reset [m]. + initial_joint_positions: Reset joint positions in articulation order [rad, m]. + schedule_spec: Collision margin, timing strategy and task constraints. + env_id: Planning context used for collision checks. + + Returns: + Checked paths, schedule and optional shared-joint trajectory. + """ + + conflicts = self._conflicts_find(dict(episode_paths.arm_paths), schedule_spec.collision_margin_m, env_id) + schedule = self._episode_schedule_solve( + data_generator=data_generator, + episode_paths=episode_paths, + conflicts=conflicts, + schedule_spec=schedule_spec, + ) + return self._episode_validate_scheduled( + data_generator=data_generator, + episode_paths=episode_paths, + initial_object_poses=initial_object_poses, + initial_joint_positions=initial_joint_positions, + schedule_spec=schedule_spec, + conflicts=conflicts, + schedule=schedule, + env_id=env_id, + ) + + def _episode_schedule_solve( + self, + *, + data_generator: DataGenerator, + episode_paths: EpisodePaths, + conflicts: tuple[ArmWaypointConflict, ...], + schedule_spec: ScheduleSpec, + ) -> Schedule: + """Solve a CPU schedule after collision checks identify conflicting waypoints. + + Args: + data_generator: Generator providing segment resource requirements. + episode_paths: Complete unscheduled paths. + conflicts: Cross-arm waypoint pairs that cannot overlap. + schedule_spec: Timing strategy and task constraints. + + Returns: + Schedule satisfying collision and task constraints. + + Raises: + EpisodeGenerationError: No valid schedule is returned by the solver. + """ + + from autodata_core.schedulegen.scheduling import schedule_arm_paths + from autodata_core.scheduling import ScheduleFailure + + arm_paths = episode_paths.arm_paths + schedule = schedule_arm_paths( + arm_paths, + conflicts, + schedule_spec, + segment_resource_ids=data_generator.datastream.get_segment_resource_ids(), + ) + if isinstance(schedule, ScheduleFailure): + raise EpisodeGenerationError( + "scheduling", + schedule.message, + ( + ( + "object_collision_spheres", + _object_collision_spheres_format(episode_paths.object_collision_spheres), + ), + ("collision_conflicts", str(len(conflicts))), + ("path_layout", _path_layout_format(arm_paths)), + ("initial_conflicts", _endpoint_conflicts_format(arm_paths, conflicts, terminal=False)), + ("terminal_conflicts", _endpoint_conflicts_format(arm_paths, conflicts, terminal=True)), + ("deepest_conflicts", _deepest_conflicts_format(conflicts)), + ), + ) + return schedule + + def _episode_validate_scheduled( + self, + *, + data_generator: DataGenerator, + episode_paths: EpisodePaths, + initial_object_poses: Mapping[str, torch.Tensor], + initial_joint_positions: torch.Tensor, + schedule_spec: ScheduleSpec, + conflicts: tuple[ArmWaypointConflict, ...], + schedule: Schedule, + env_id: int = 0, + ) -> _ValidatedEpisode: + """Check a solved schedule without repeating collision discovery or optimization. + + Project object attachments and contact permissions onto execution ticks, then validate + synchronized robot/object states. Return replay targets and diagnostics only after all + configured geometric checks pass; expected failures raise :class:`EpisodeGenerationError`. + + Args: + data_generator: Generator providing task and embodiment interfaces. + episode_paths: Complete paths and carried-object geometry. + initial_object_poses: Object transforms at reset [m]. + initial_joint_positions: Reset joint positions in articulation order [rad, m]. + schedule_spec: Collision margin and timing requirements. + conflicts: Cross-arm waypoint pairs used by the scheduler. + schedule: Solved execution ticks for all segments. + env_id: Planning context used for collision checks. + + Returns: + Checked paths, schedule, replay targets and diagnostics. + """ + + from autodata_core.schedulegen.collision import ( + scheduled_object_spheres, + scheduled_robot_object_validate, + scheduled_robot_validate, + scheduled_world_validate, + ) + from autodata_core.schedulegen.scheduling import ( + project_object_states, + schedule_object_events, + schedule_object_poses, + schedule_robot_contacts, + schedule_world_contacts, + ) + from autodata_interfaces.tasks.segment_spec import SegmentEventType + + context = self.planning_contexts[env_id] + planners = context.group_planners + full_state_planner = context.full_state + datastream = data_generator.datastream + arm_paths = episode_paths.arm_paths + diagnostics_before_success = [ + ("object_collision_spheres", _object_collision_spheres_format(episode_paths.object_collision_spheres)), + ("collision_conflicts", str(len(conflicts))), + ("makespan_ticks", str(schedule.makespan_ticks)), + ("schedule_segments", _schedule_segments_format(schedule)), + ] + present_segments = {segment_id for path in arm_paths.values() for segment_id in path.segment_bounds} + full_state_diagnostics: tuple[tuple[str, str], ...] = () + object_state_diagnostics: tuple[tuple[str, str], ...] = () + try: + # Retain stage identifiers used by saved reports; these operations map paths to ticks. + try: + schedule_stage = "object_event_lowering" + scheduled_object_events = schedule_object_events(arm_paths, schedule) + diagnostics_before_success.append( + ("scheduled_object_events", _scheduled_object_events_format(scheduled_object_events)) + ) + schedule_stage = "object_pose_lowering" + scheduled_object_poses = schedule_object_poses(arm_paths, schedule) + diagnostics_before_success.append( + ("scheduled_object_poses", _scheduled_object_poses_format(scheduled_object_poses)) + ) + schedule_stage = "world_contact_lowering" + scheduled_world_contacts = schedule_world_contacts( + arm_paths, + schedule, + { + segment_id: contacts + for segment_id, contacts in datastream.get_segment_world_contacts().items() + if segment_id in present_segments + }, + ) + diagnostics_before_success.append( + ("scheduled_world_contacts", _scheduled_world_contacts_format(scheduled_world_contacts)) + ) + schedule_stage = "robot_contact_lowering" + scheduled_robot_contacts = schedule_robot_contacts( + arm_paths, + schedule, + { + segment_id: contacts + for segment_id, contacts in datastream.get_segment_robot_contacts().items() + if segment_id in present_segments + }, + scheduled_object_events, + attachment_link_names={ + name: tuple(planners[name].config.hand_link_names) + for name in { + event.path_event.segment_id.eef_name + for event in scheduled_object_events + if event.path_event.spec.event_type == SegmentEventType.ATTACH + } + }, + ) + diagnostics_before_success.append( + ("scheduled_robot_contacts", _scheduled_robot_contacts_format(scheduled_robot_contacts)) + ) + except AssertionError as error: + raise EpisodeGenerationError(schedule_stage, str(error)) from error + + tool_poses_by_eef: Mapping[str, torch.Tensor] | None = None + full_state_visualization_index: int | None = None + scheduled_robot = None + joint_trajectory: NamedJointTrajectory | None = None + if full_state_planner is not None: + joint_trajectory = _scheduled_joint_trajectory_solve( + datastream, + planners, + full_state_planner, + arm_paths, + schedule, + initial_joint_positions, + collision_margin_m=schedule_spec.collision_margin_m, + env_id=env_id, + ) + scheduled_robot = scheduled_robot_validate( + datastream, + planners, + full_state_planner, + arm_paths, + schedule, + initial_joint_positions, + joint_trajectory=joint_trajectory, + collision_margin_m=schedule_spec.collision_margin_m, + densify_factor=self.collision_densify_factor, + ) + tool_poses_by_eef = scheduled_robot.tool_poses_by_eef + full_state_visualization_index = scheduled_robot.visualization_index + full_state_diagnostics = ( + ("full_state_self_collision_samples", str(scheduled_robot.self_collision_sample_count)), + ) + if joint_trajectory is not None: + full_state_diagnostics += (("whole_body_realized_joints", ",".join(joint_trajectory.joint_names)),) + elif scheduled_world_contacts or scheduled_robot_contacts: + raise EpisodeGenerationError( + "full_state_contact_resolution", + "task contact policy requires the designated full-state collision context", + ) + + object_spheres: Mapping[str, torch.Tensor] = {} + if episode_paths.object_collision_spheres: + if tool_poses_by_eef is None or scheduled_robot is None: + raise EpisodeGenerationError( + "object_state_projection", + "scheduled object state requires the designated full-state kinematic context", + ) + try: + object_states = project_object_states( + initial_object_poses, + tool_poses_by_eef, + tuple(episode_paths.object_collision_spheres), + scheduled_object_events, + scheduled_object_poses, + makespan_ticks=schedule.makespan_ticks, + ) + except AssertionError as error: + raise EpisodeGenerationError("object_state_projection", str(error)) from error + object_state_diagnostics = (("scheduled_object_states", _object_states_format(object_states)),) + object_spheres = scheduled_object_spheres( + object_states, + episode_paths.object_collision_spheres, + makespan_ticks=schedule.makespan_ticks, + ) + if full_state_visualization_index is not None: + assert full_state_planner is not None + _scheduled_object_spheres_animate( + object_spheres, + full_state_planner.plan_visualizer, + full_state_visualization_index, + ) + + if scheduled_robot is not None: + assert full_state_planner is not None + object_manipulation_starts = { + object_ref: min( + ( + schedule.ticks_for(event.path_event.segment_id)[0] + for event in scheduled_object_events + if event.path_event.spec.event_type == SegmentEventType.ATTACH + and event.path_event.spec.object_ref == object_ref + ), + default=schedule.makespan_ticks + 1, + ) + for object_ref in object_spheres + } + robot_object_samples, waived_robot_contact_samples = scheduled_robot_object_validate( + full_state_planner, + scheduled_robot, + object_spheres, + collision_margin_m=schedule_spec.collision_margin_m, + object_manipulation_starts=object_manipulation_starts, + robot_contacts=scheduled_robot_contacts, + ) + robot_world_samples, object_world_samples, waived_world_contact_samples = scheduled_world_validate( + full_state_planner, + scheduled_robot, + object_spheres, + episode_paths.object_collision_spheres, + collision_margin_m=schedule_spec.collision_margin_m, + object_manipulation_starts=object_manipulation_starts, + world_contacts=scheduled_world_contacts, + ) + full_state_diagnostics += ( + ("full_state_robot_world_collision_samples", str(robot_world_samples)), + ("full_state_robot_object_collision_samples", str(robot_object_samples)), + ("full_state_robot_object_contact_samples", str(waived_robot_contact_samples)), + ("full_state_object_world_collision_samples", str(object_world_samples)), + ("full_state_object_world_contact_samples", str(waived_world_contact_samples)), + ) + except EpisodeGenerationError as failure: + raise EpisodeGenerationError( + failure.stage, + str(failure), + ( + *diagnostics_before_success, + *full_state_diagnostics, + *object_state_diagnostics, + *failure.diagnostics, + ), + ) from failure + + return _ValidatedEpisode( + arm_paths=arm_paths, + schedule=schedule, + replay_joint_trajectory=( + NamedJointTrajectory(tuple(full_state_planner.active_joint_names), scheduled_robot.joint_positions) + if scheduled_robot is not None and joint_trajectory is not None + else None + ), + diagnostics_before_success=tuple(diagnostics_before_success), + diagnostics_after_success=(*full_state_diagnostics, *object_state_diagnostics), + ) + + def _attempt_diagnostics_collect( + self, + data_generator: DataGenerator, + env_id: int, + success_term: TerminationTermCfg, + ) -> tuple[tuple[str, str], ...]: + """Collect task diagnostics without hiding the attempt outcome.""" + + if self.attempt_diagnostics is None: + return () + try: + diagnostics = self.attempt_diagnostics(data_generator.datastream, env_id, success_term) + assert isinstance(diagnostics, tuple), "attempt diagnostics callback must return a tuple" + assert all( + isinstance(item, tuple) and len(item) == 2 and isinstance(item[0], str) and isinstance(item[1], str) + for item in diagnostics + ), "attempt diagnostics must contain string name/value pairs" + names = tuple(name for name, _ in diagnostics) + assert len(names) == len(set(names)), "attempt diagnostic names must be unique" + assert all(name.startswith("final_") for name in names), "attempt diagnostic names must start with final_" + return diagnostics + except Exception as error: + return (("attempt_diagnostics_error", f"{type(error).__name__}: {error}"),) + + def _conflicts_find( + self, arm_paths: dict[str, ArmPath], margin_m: float, env_id: int + ) -> tuple[ArmWaypointConflict, ...]: + """Find cross-arm conflicts using this environment's planning models.""" + + from autodata_core.schedulegen.collision import find_waypoint_conflicts + + planners = self.planning_contexts[env_id].group_planners + conflicts: list[ArmWaypointConflict] = [] + for first_name, second_name in combinations(sorted(arm_paths), 2): + conflicts.extend( + find_waypoint_conflicts( + arm_paths[first_name], + arm_paths[second_name], + planners[first_name], + planners[second_name], + collision_margin_m=margin_m, + densify_factor=self.collision_densify_factor, + ) + ) + return tuple(conflicts) + + async def _schedule_replay( + self, + *, + data_generator: DataGenerator, + env_id: int, + success_term: TerminationTermCfg, + env_action_queue: Any, + arm_paths: dict[str, ArmPath], + schedule: Schedule, + joint_trajectory: NamedJointTrajectory | None = None, + planning_env_id: int | None = None, + ) -> tuple[bool, int | None]: + """Replay scheduled commands and accept only terminal task success. + + Args: + data_generator: Owner of the datastream and shared waypoint execution. + env_id: Environment to execute in. + success_term: Task success predicate evaluated after each command. + env_action_queue: Optional queue used by asynchronous environment stepping. + arm_paths: Complete unscheduled paths keyed by end-effector name. + schedule: Execution ticks, including waits and terminal holds on each lane. + joint_trajectory: Optional coupled posture targets in named joint order. + planning_env_id: Kinematic context to reuse, or None for the replay environment's context. + + Returns: + Terminal task success and the first successful tick, if any. A transient success + alone is not accepted; configured final holds and convergence commands still run. + + Raises: + EpisodeGenerationError: Terminal tool targets do not converge within the step limit. + AssertionError: Replay produces non-finite robot joint positions. + """ + + planners = self.planning_contexts[env_id if planning_env_id is None else planning_env_id].group_planners + timelines = {name: _scheduled_waypoints_build(path, schedule) for name, path in arm_paths.items()} + datastream = data_generator.datastream + policy = datastream.get_generation_policy() + final_hold = policy.final_hold_steps + terminal_success = False + first_success_tick = None + for tick in range(schedule.makespan_ticks + final_hold): + if joint_trajectory is not None: + posture_index = min(tick, schedule.makespan_ticks - 1) + datastream.set_robot_joint_posture_target( + joint_trajectory.joint_names, + joint_trajectory.positions[posture_index], + env_id, + ) + waypoints = {name: timeline[min(tick, schedule.makespan_ticks - 1)] for name, timeline in timelines.items()} + tick_success = await MultiWaypoint(waypoints).execute( + datastream=datastream, + success_term=success_term, + env_id=env_id, + env_action_queue=env_action_queue, + ) + assert bool( + torch.isfinite(datastream.get_robot_joint_positions(env_ids=[env_id])).all() + ), f"Physics produced non-finite robot joints at replay tick {tick}." + if tick_success and first_success_tick is None: + first_success_tick = tick + terminal_success = tick_success + + # Export only a task state that survives the complete scheduled/post-hold replay. A + # transient success remains observable through first_success_tick but is not accepted. + if terminal_success or policy.terminal_convergence_steps == 0: + return terminal_success, first_success_tick + terminal_waypoints = {name: timeline[-1] for name, timeline in timelines.items()} + for correction_step in range(policy.terminal_convergence_steps + 1): + errors = { + name: _terminal_pose_error(datastream, planners[name], env_id, waypoint.pose) + for name, waypoint in terminal_waypoints.items() + } + converged = all( + position_error <= planners[name].config.position_threshold + and rotation_error <= planners[name].config.rotation_threshold + for name, (position_error, rotation_error) in errors.items() + ) + if converged: + return terminal_success, first_success_tick + if correction_step == policy.terminal_convergence_steps: + error_text = ", ".join( + f"{name}=({position_error:.6f}m,{rotation_error:.6f}rad)" + for name, (position_error, rotation_error) in sorted(errors.items()) + ) + raise EpisodeGenerationError( + "terminal_convergence", + f"terminal targets did not converge after {policy.terminal_convergence_steps} steps: {error_text}", + ) + if joint_trajectory is not None: + datastream.set_robot_joint_posture_target( + joint_trajectory.joint_names, + joint_trajectory.positions[-1], + env_id, + ) + tick_success = await MultiWaypoint(terminal_waypoints).execute( + datastream=datastream, + success_term=success_term, + env_id=env_id, + env_action_queue=env_action_queue, + ) + if tick_success and first_success_tick is None: + first_success_tick = schedule.makespan_ticks + final_hold + correction_step + terminal_success = tick_success + return terminal_success, first_success_tick + + @staticmethod + def _state_restore(datastream: Any, initial_state: dict, env_id: int) -> None: + """Restore scene state and actuator targets before replay or a planning failure.""" + + env_ids = torch.tensor([env_id], dtype=torch.int64, device=datastream.device) + env = datastream.get_env() + env.scene.reset_to(initial_state, env_ids=env_ids, is_relative=True) + + +def _validated_episode_diagnostics( + episode: _ValidatedEpisode, + first_success_tick: int | None, +) -> tuple[tuple[str, str], ...]: + """Combine path-check and replay diagnostics for the attempt result.""" + + return ( + *episode.diagnostics_before_success, + ("first_success_tick", "none" if first_success_tick is None else str(first_success_tick)), + *episode.diagnostics_after_success, + ) + + +def _path_layout_format(arm_paths: Mapping[str, ArmPath]) -> str: + """Summarize path lengths and half-open segment waypoint bounds.""" + + return "; ".join( + f"{eef_name}[{len(path.waypoints)}]:" + + ",".join(f"{segment_id}={start}:{end}" for segment_id, (start, end) in path.segment_bounds.items()) + for eef_name, path in sorted(arm_paths.items()) + ) + + +def _object_collision_spheres_format(geometries: Mapping[str, ObjectCollisionSpheres]) -> str: + """Summarize each object's sphere count and geometry checksum.""" + + return ";".join( + f"{name}:{len(geometry.spheres)}:{geometry.geometry_digest}" for name, geometry in sorted(geometries.items()) + ) + + +def _source_demo_diagnostics( + data_generator: DataGenerator, + selected_source: Mapping[str, int | None], +) -> tuple[tuple[str, str], ...]: + """Report the selected demonstration key, or unselected status, for each arm.""" + + demo_keys = data_generator.src_demo_datagen_info_pool.demo_keys + return tuple( + ( + f"source_demo.{eef_name}", + "unselected" if source_index is None else demo_keys[source_index], + ) + for eef_name, source_index in sorted(selected_source.items()) + ) + + +def _schedule_segments_format(schedule: Schedule) -> str: + """Format the first and last command tick of each scheduled segment.""" + + return ";".join( + f"{segment_id}={ticks[0]}:{ticks[-1]}" + for segment_id, ticks in sorted(schedule.waypoint_ticks.items(), key=lambda item: str(item[0])) + ) + + +def _scheduled_world_contacts_format(contacts: tuple[ScheduledWorldContact, ...]) -> str: + """Format exact logical pairs and half-open boundary intervals for diagnostics.""" + + return ( + ";".join( + f"{contact.segment_id}:{contact.spec.object_ref}->{contact.spec.fixture_ref}" + f"@{contact.start_tick}:{contact.stop_tick}" + for contact in contacts + ) + or "none" + ) + + +def _scheduled_robot_contacts_format(contacts: tuple[ScheduledRobotContact, ...]) -> str: + """Format exact robot/object permissions and half-open boundary intervals.""" + + return ( + ";".join( + f"{contact.segment_id}:{contact.spec.object_ref}<-{','.join(contact.spec.robot_link_names)}" + f"@{contact.start_tick}:{contact.stop_tick}" + for contact in contacts + ) + or "none" + ) + + +def _scheduled_object_events_format(events: tuple[ScheduledObjectEvent, ...]) -> str: + """Format attachment transitions with their boundary ticks and source annotations.""" + + if not events: + return "none" + formatted = [] + for scheduled in events: + event = scheduled.path_event + source = event.spec.annotation_key or event.spec.point.value + formatted.append( + f"{scheduled.tick}:{event.segment_id}[{event.local_boundary_index}]:" + f"{event.spec.event_type.value}:{event.spec.object_ref}@{source}" + ) + return ";".join(formatted) + + +def _scheduled_object_poses_format(poses: tuple[ScheduledObjectPose, ...]) -> str: + """Summarize object-pose sample counts and tick ranges by segment.""" + + if not poses: + return "none" + grouped: dict[tuple[SegmentId, str], list[int]] = {} + for scheduled in poses: + path_pose = scheduled.path_pose + grouped.setdefault((path_pose.segment_id, path_pose.object_ref), []).append(scheduled.sample_tick) + return ";".join( + f"{segment_id}:{object_ref}:{len(ticks)}@{ticks[0]}:{ticks[-1]}" + for (segment_id, object_ref), ticks in grouped.items() + ) + + +def _object_states_format(states: tuple[ObjectStateSample, ...]) -> str: + """Summarize attachment intervals and pose jumps at consecutive object boundaries.""" + + if not states: + return "none" + by_object: dict[str, list[ObjectStateSample]] = {} + for state in states: + by_object.setdefault(state.object_ref, []).append(state) + formatted = [] + for object_ref, samples in sorted(by_object.items()): + assert tuple(sample.boundary_tick for sample in samples) == tuple(range(len(samples))) + spans: list[str] = [] + jumps: list[str] = [] + start = 0 + owner = samples[0].owner_eef_name + for sample in samples: + if sample.attachment_pose_jump is not None: + position_jump, rotation_jump = sample.attachment_pose_jump + jumps.append(f"{sample.boundary_tick}={position_jump:.6f}m/{rotation_jump:.6f}rad") + for index, sample in enumerate((*samples[1:], None), start=1): + next_owner = None if sample is None else sample.owner_eef_name + if next_owner != owner: + if owner is not None: + spans.append(f"{owner}@{start}:{index}") + start = index + owner = next_owner + formatted.append( + f"{object_ref}:{len(samples)}:{','.join(spans) or 'world'}:attach_jump@{','.join(jumps) or 'none'}" + ) + return ";".join(formatted) + + +def _terminal_tracking_diagnostics( + datastream: Any, + planners: Mapping[str, CuroboPlanner], + arm_paths: Mapping[str, ArmPath], + env_id: int, +) -> tuple[tuple[str, str], ...]: + """Report final tool errors [m, rad] from measured joints and planner FK.""" + + diagnostics: list[tuple[str, str]] = [] + for eef_name, path in sorted(arm_paths.items()): + position_error, rotation_error = _terminal_pose_error( + datastream, + planners[eef_name], + env_id, + path.waypoints[-1].pose, + ) + diagnostics.extend(( + (f"final_tracking.{eef_name}.position_error_m", f"{position_error:.6f}"), + (f"final_tracking.{eef_name}.rotation_error_rad", f"{rotation_error:.6f}"), + )) + return tuple(diagnostics) + + +def _conflict_format(conflict: ArmWaypointConflict) -> str: + """Format a conflicting arm-waypoint pair and its sphere clearance [m].""" + + return ( + f"{conflict.first_eef_name}[{conflict.first_waypoint_index}]<->" + f"{conflict.second_eef_name}[{conflict.second_waypoint_index}]={conflict.clearance_m:.4f}m" + ) + + +def _endpoint_conflicts_format( + arm_paths: Mapping[str, ArmPath], + conflicts: tuple[ArmWaypointConflict, ...], + *, + terminal: bool, +) -> str: + """Count endpoint conflicts and format at most twelve representative pairs.""" + + endpoints = {eef_name: len(path.waypoints) - 1 if terminal else 0 for eef_name, path in arm_paths.items()} + endpoint_conflicts = [ + conflict + for conflict in conflicts + if conflict.first_waypoint_index == endpoints[conflict.first_eef_name] + or conflict.second_waypoint_index == endpoints[conflict.second_eef_name] + ] + samples = "; ".join(_conflict_format(conflict) for conflict in endpoint_conflicts[:12]) + return f"{len(endpoint_conflicts)}: {samples}" if endpoint_conflicts else "0" + + +def _deepest_conflicts_format(conflicts: tuple[ArmWaypointConflict, ...]) -> str: + """Format up to eight waypoint conflicts with the smallest sphere clearances.""" + + return "; ".join( + _conflict_format(conflict) for conflict in sorted(conflicts, key=lambda item: item.clearance_m)[:8] + ) + + +def _terminal_pose_error( + datastream: Any, + planner: CuroboPlanner, + env_id: int, + target_pose: torch.Tensor, +) -> tuple[float, float]: + """Compare the target tool pose with FK of measured planner joints. + + Args: + datastream: Source of measured, named robot joint positions. + planner: Arm model defining joint order and environment-relative tool poses. + env_id: Environment whose joint state is queried. + target_pose: Environment-relative tool transform with shape ``(4, 4)`` [m]. + + Returns: + Position and rotation error [m, rad], both infinite if either pose is non-finite. + """ + + selected = datastream.get_robot_joint_positions(env_ids=[env_id], joint_names=planner.active_joint_names) + actual_pose = planner.joint_positions_to_ee_poses(selected)[0] + target_pose = target_pose.to(device=actual_pose.device, dtype=actual_pose.dtype) + if not bool(torch.isfinite(actual_pose).all()) or not bool(torch.isfinite(target_pose).all()): + return math.inf, math.inf + position_error, rotation_error = pose_math.pose_errors(actual_pose, target_pose) + return float(position_error.item()), float(rotation_error.item()) + + +def _scheduled_waypoints_build(path: ArmPath, schedule: Schedule) -> tuple[Waypoint, ...]: + """Expand a path to one command per tick, holding its initial and final waypoints. + + Args: + path: Unscheduled waypoints and segment bounds. + schedule: Execution ticks, including waits between waypoints. + + Returns: + One waypoint for each execution tick. + """ + + from autodata_core.schedulegen.scheduling import get_scheduled_path_indices + + return tuple(path.waypoints[index] for index in get_scheduled_path_indices(path, schedule)) + + +def _scheduled_object_spheres_animate( + object_spheres: Mapping[str, torch.Tensor], + visualizer: Any, + schedule_index: int, +) -> None: + """Add exact projected object spheres to an existing full-state Rerun timeline.""" + + timelines = tuple(object_spheres[name][:-1] for name in sorted(object_spheres)) + assert timelines and len({len(timeline) for timeline in timelines}) == 1 + visualizer.animate_object_collision_spheres(torch.cat(timelines, dim=1), schedule_index=schedule_index) + + +def _scheduled_joint_trajectory_solve( + datastream: Any, + planners: Mapping[str, CuroboPlanner], + full_state_planner: CuroboPlanner, + arm_paths: Mapping[str, ArmPath], + schedule: Schedule, + initial_joint_positions: torch.Tensor, + *, + collision_margin_m: float, + env_id: int, +) -> NamedJointTrajectory | None: + """Use the embodiment controller to solve paths that share active joints. + + Args: + datastream: Embodiment interface owning coupled trajectory solving. + planners: Arm planners keyed by end-effector name. + full_state_planner: Combined robot model used to check self-collision. + arm_paths: Unscheduled paths containing tool targets and joint seeds. + schedule: Execution ticks used to align each arm's targets and seeds. + initial_joint_positions: Initial robot state in live articulation order [rad, m]. + collision_margin_m: Minimum self-collision clearance required by the validity callback [m]. + env_id: Environment whose controller solves the trajectory. + + Returns: + One named joint configuration per schedule tick, or ``None`` for disjoint planning groups. + + Raises: + EpisodeGenerationError: Coupled solving fails, is unsupported, or returns incomplete targets. + """ + + from autodata_core.schedulegen.scheduling import get_scheduled_path_indices + + owners: dict[str, list[str]] = {} + for eef_name, planner in planners.items(): + for joint_name in getattr(planner, "active_joint_names", ()): + owners.setdefault(joint_name, []).append(eef_name) + shared_joint_names = {name for name, eef_names in owners.items() if len(eef_names) > 1} + if not shared_joint_names: + return None + + live_names = tuple(datastream.get_robot_joint_names()) + full_names = tuple(full_state_planner.active_joint_names) + live_index = {name: index for index, name in enumerate(live_names)} + full_index = {name: index for index, name in enumerate(full_names)} + assert not set(full_names) - set(live_names), "full-state joints must exist in the live articulation" + state_templates = initial_joint_positions[[live_index[name] for name in full_names]].repeat( + schedule.makespan_ticks, 1 + ) + target_eef_poses: dict[str, torch.Tensor] = {} + joint_seed_trajectories: dict[str, NamedJointTrajectory] = {} + for eef_name, path in arm_paths.items(): + indices = get_scheduled_path_indices(path, schedule) + source_indices = torch.tensor(indices, device=path.joint_positions.device) + lane_positions = path.joint_positions.index_select(0, source_indices).to( + device=state_templates.device, + dtype=state_templates.dtype, + ) + target_eef_poses[eef_name] = torch.stack([path.waypoints[index].pose for index in indices]) + joint_seed_trajectories[eef_name] = NamedJointTrajectory( + tuple(planners[eef_name].active_joint_names), + path.joint_positions.index_select(0, source_indices), + ) + for lane_index, joint_name in enumerate(planners[eef_name].active_joint_names): + state_templates[:, full_index[joint_name]] = lane_positions[:, lane_index] + + def joint_state_is_valid(joint_names: tuple[str, ...], positions: torch.Tensor, sample: int) -> bool: + """Check a coupled candidate in the full robot state for its scheduled sample.""" + + missing = set(joint_names) - set(full_names) + assert not missing, f"coupled trajectory contains joints outside the full-state context: {sorted(missing)}" + state = state_templates[sample].clone() + values = positions.to(device=state.device, dtype=state.dtype) + state[[full_index[name] for name in joint_names]] = values + return bool(full_state_planner.joint_positions_self_collision_free(state.unsqueeze(0), collision_margin_m)[0]) + + try: + trajectory = datastream.solve_robot_joint_trajectory( + target_eef_poses, + joint_seed_trajectories, + initial_joint_positions, + min(planner.config.position_threshold for planner in planners.values()), + min(planner.config.rotation_threshold for planner in planners.values()), + joint_state_is_valid, + env_id, + ) + except Exception as error: + # Keep the stage name used by saved generation reports. + raise EpisodeGenerationError( + "whole_body_realization", + f"{type(error).__name__}: {error}", + ) from error + if trajectory is None: + raise EpisodeGenerationError( + "whole_body_realization", + f"planning groups share joints {sorted(shared_joint_names)}, but the embodiment has no shared-joint solver", + ) + if len(trajectory.positions) != schedule.makespan_ticks: + raise EpisodeGenerationError( + "whole_body_realization", + f"coupled trajectory has {len(trajectory.positions)} samples for a {schedule.makespan_ticks}-tick schedule", + ) + missing = shared_joint_names - set(trajectory.joint_names) + if missing: + raise EpisodeGenerationError( + "whole_body_realization", + f"coupled trajectory does not own shared joints: {sorted(missing)}", + ) + return trajectory + + +__all__ = ["ScheduleGen"] diff --git a/autodata_core/schedulegen/batching.py b/autodata_core/schedulegen/batching.py new file mode 100644 index 0000000..4bc5b7d --- /dev/null +++ b/autodata_core/schedulegen/batching.py @@ -0,0 +1,301 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Buffered preparation and scheduling with the ordinary asynchronous episode replay.""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +import torch +from concurrent.futures import ThreadPoolExecutor +from typing import TYPE_CHECKING, Any + +from autodata_core.data_generator import GenerationResult +from autodata_core.schedulegen.types import EpisodeGenerationError +from autodata_core.waypoint import MultiWaypoint +from autodata_interfaces.env.isaaclab_env_interface import env_loop +from autodata_utils.generation_result import record_generation_attempt + +if TYPE_CHECKING: + from isaaclab.managers import TerminationTermCfg + + from autodata_core.data_generator import DataGenerator + from autodata_core.schedulegen.algorithm import ScheduleGen, _PreparedEpisode + from autodata_utils.generation_result import AttemptLog + + +def generate_buffered( + env: Any, + data_generator: DataGenerator, + algorithm: ScheduleGen, + success_term: TerminationTermCfg, + schedule_workers: int, + *, + attempt_log: AttemptLog | None = None, +) -> dict: + """Prepare waves on environment zero, schedule independently and replay in vectorized environments. + + Only CPU scheduling uses worker threads. Scene resets, GPU planning, validation and + simulation stay on the calling thread. Geometry, dynamics and robot base poses must match + across replay environments; each episode supplies its own environment-relative reset state. + Resets finish outside the event loop before replay coroutines start. + + Args: + env: Environment to step, including an optional recording wrapper. + data_generator: Owner of source selection, recording and episode export. + algorithm: ScheduleGen with one shared planning context bound to environment zero. + success_term: Task success predicate evaluated by the ordinary replay coroutine. + schedule_workers: Maximum number of simultaneous CPU schedule solves. + attempt_log: Optional native metrics log receiving each completed attempt. + + Returns: + Counters, completion-ordered attempts, timing totals [s] and target-reached status. + """ + + assert set(algorithm.planning_contexts) == {0}, "buffered generation requires one environment-zero context" + assert type(schedule_workers) is int and schedule_workers > 0 + datastream = data_generator.datastream + base_env = datastream.get_env() + policy = datastream.get_generation_policy() + assert policy.reset_settling_steps == 0, "buffered generation does not support reset_settling_steps" + schedule_spec = datastream.get_schedule_spec() + assert schedule_spec is not None + loop = asyncio.get_event_loop() + stats = {"num_success": 0, "num_failures": 0, "num_attempts": 0} + attempts: list[dict[str, object]] = [] + # Keep the saved timing keys stable; certify_s measures validation. + timings = {name: 0.0 for name in ("prepare_s", "conflicts_s", "schedule_wall_s", "certify_s", "replay_s")} + workers = min(schedule_workers, base_env.num_envs) + planning_ids = torch.tensor([0], dtype=torch.int64, device=datastream.device) + with ThreadPoolExecutor(max_workers=workers) as executor: + while True: + count = min(base_env.num_envs, policy.remaining_attempts(stats["num_attempts"], stats["num_success"])) + if count <= 0: + break + print(f"Preparing buffered batch of {count} candidates.", flush=True) + candidates = [] + for _ in range(count): + attempt_started = time.monotonic() + started = time.perf_counter() + base_env.recorder_manager.reset(env_ids=planning_ids) + base_env.reset(env_ids=planning_ids) + prepared = algorithm._episode_prepare(data_generator, 0, success_term) + prepared.start_time_s = attempt_started + timings["prepare_s"] += time.perf_counter() - started + candidates.append(prepared) + if prepared.result is None: + assert prepared.paths is not None + started = time.perf_counter() + try: + prepared.conflicts = algorithm._conflicts_find( + dict(prepared.paths.arm_paths), schedule_spec.collision_margin_m, 0 + ) + except EpisodeGenerationError as failure: + _failed(data_generator, algorithm, prepared, success_term, failure) + timings["conflicts_s"] += time.perf_counter() - started + + started = time.perf_counter() + futures = [ + ( + prepared, + executor.submit( + algorithm._episode_schedule_solve, + data_generator=data_generator, + episode_paths=prepared.paths, + conflicts=prepared.conflicts, + schedule_spec=schedule_spec, + ), + ) + for prepared in candidates + if prepared.result is None + ] + solved = [] + for prepared, future in futures: + try: + solved.append((prepared, future.result())) + except EpisodeGenerationError as failure: + _failed(data_generator, algorithm, prepared, success_term, failure) + timings["schedule_wall_s"] += time.perf_counter() - started + started = time.perf_counter() + for prepared, schedule in solved: + algorithm._state_restore(datastream, prepared.initial_state, 0) + try: + prepared.validated = algorithm._episode_validate_scheduled( + data_generator=data_generator, + episode_paths=prepared.paths, + initial_object_poses=prepared.initial_object_poses, + initial_joint_positions=prepared.initial_joint_positions, + schedule_spec=schedule_spec, + conflicts=prepared.conflicts, + schedule=schedule, + env_id=0, + ) + except EpisodeGenerationError as failure: + _failed(data_generator, algorithm, prepared, success_term, failure) + timings["certify_s"] += time.perf_counter() - started + for prepared in candidates: + if prepared.result is not None: + record_generation_attempt( + GenerationResult(prepared.initial_state, False, diagnostics=prepared.result.diagnostics), + 0, + stats, + attempts, + attempt_log=attempt_log, + start_time_s=prepared.start_time_s, + ) + ready = [prepared for prepared in candidates if prepared.validated is not None] + started = time.perf_counter() + if ready: + _replay_wave( + env, data_generator, algorithm, success_term, ready, loop, stats, attempts, attempt_log=attempt_log + ) + timings["replay_s"] += time.perf_counter() - started + env_ids = torch.arange(base_env.num_envs, device=datastream.device) + base_env.recorder_manager.reset(env_ids=env_ids) + completed = stats["num_success"] if policy.guarantee_success else stats["num_attempts"] + return { + "stats": stats, + "attempts": attempts, + "completed": completed >= policy.num_trials, + "execution": {"schedule_workers": workers, "timings_s": timings}, + } + + +def _failed( + data_generator: DataGenerator, + algorithm: ScheduleGen, + prepared: _PreparedEpisode, + success_term: TerminationTermCfg, + failure: EpisodeGenerationError, +) -> None: + """Retain a pre-replay failure on the candidate's original state. + + Args: + data_generator: Generator owning the live datastream. + algorithm: Algorithm providing state restoration and failure diagnostics. + prepared: Candidate whose preparation or scheduling failed. + success_term: Task success predicate used by failure diagnostics. + failure: Expected generation failure reported on the calling thread. + """ + + algorithm._state_restore(data_generator.datastream, prepared.initial_state, 0) + prepared.result = algorithm._failure_result( + data_generator=data_generator, + env_id=0, + success_term=success_term, + selected_source=prepared.selected_source, + source_candidate_diagnostics=prepared.source_candidate_diagnostics, + failure=failure, + ) + + +def _states_stack(states: list[dict]) -> dict: + """Stack matching single-environment scene states without modifying the copies. + + Args: + states: Environment-relative states, each containing one tensor row per scene field. + + Returns: + A scene state with one row per replay slot. + """ + + assert states and all(set(state) == set(states[0]) for state in states) + stacked = {} + for name, value in states[0].items(): + values = [state[name] for state in states] + if isinstance(value, dict): + stacked[name] = _states_stack(values) + else: + assert all(isinstance(item, torch.Tensor) and item.shape == value.shape for item in values) + assert value.shape[0] == 1, "buffered states must contain exactly one environment" + stacked[name] = torch.cat(values, dim=0) + return stacked + + +def _replay_wave( + env: Any, + data_generator: DataGenerator, + algorithm: ScheduleGen, + success_term: TerminationTermCfg, + ready: list[_PreparedEpisode], + loop: asyncio.AbstractEventLoop, + stats: dict[str, int], + attempts: list[dict[str, object]], + *, + attempt_log: AttemptLog | None = None, +) -> None: + """Replay a wave and hold finished slots without exporting their tails. + + Unassigned slots hold their initial validated target without executing another episode. + + Args: + env: Environment to step, including an optional recording wrapper. + data_generator: Owner of recording and episode export. + algorithm: Algorithm providing the shared episode replay coroutine. + success_term: Task success predicate evaluated during replay. + ready: Validated candidates assigned to the first available replay slots. + attempt_log: Optional native metrics log receiving each completed attempt. + loop: Event loop driven by the synchronous simulator step loop. + stats: Mutable counters for the complete generation run. + attempts: Mutable completion-ordered attempt records. + """ + + datastream = data_generator.datastream + base_env = datastream.get_env() + assert 0 < len(ready) <= base_env.num_envs + slots = [*ready, *([ready[0]] * (base_env.num_envs - len(ready)))] + env_ids = torch.arange(base_env.num_envs, device=datastream.device) + base_env.recorder_manager.reset(env_ids=env_ids) + base_env.reset_to(_states_stack([prepared.initial_state for prepared in slots]), env_ids=env_ids, is_relative=True) + action_queue = asyncio.Queue() + attempts_before = stats["num_attempts"] + + async def replay(env_id: int, prepared: _PreparedEpisode) -> None: + """Export a real slot at its exact endpoint, then emit valid terminal holds until the wave ends.""" + + if env_id < len(ready): + result = await algorithm._episode_execute(data_generator, prepared, env_id, success_term, action_queue) + data_generator._finalize_episode_recording( + env_id_tensor=env_ids[env_id : env_id + 1], success=result.success, export_demo=True + ) + record_generation_attempt( + GenerationResult(prepared.initial_state, result.success, diagnostics=result.diagnostics), + env_id, + stats, + attempts, + attempt_log=attempt_log, + start_time_s=prepared.start_time_s, + ) + hold_index = -1 if env_id < len(ready) else 0 + waypoints = {name: path.waypoints[hold_index] for name, path in prepared.validated.arm_paths.items()} + while True: + trajectory = prepared.validated.replay_joint_trajectory + if trajectory is not None: + datastream.set_robot_joint_posture_target( + trajectory.joint_names, trajectory.positions[hold_index], env_id + ) + await MultiWaypoint(waypoints).execute(datastream, success_term, env_id, action_queue) + + tasks = asyncio.gather(*(replay(env_id, prepared) for env_id, prepared in enumerate(slots))) + try: + env_loop( + env, + asyncio.Queue(), + action_queue, + loop, + generation_policy_params=datastream.get_generation_policy(), + stats=stats, + data_gen_tasks=tasks, + stop_after_attempts=len(ready), + ) + assert stats["num_attempts"] - attempts_before == len( + ready + ), "buffered replay stopped before all episodes completed" + finally: + tasks.cancel() + with contextlib.suppress(asyncio.CancelledError): + loop.run_until_complete(tasks) + for env_id in range(base_env.num_envs): + datastream.reset_robot_joint_posture_target(env_id) diff --git a/autodata_core/schedulegen/collision.py b/autodata_core/schedulegen/collision.py new file mode 100644 index 0000000..c833a52 --- /dev/null +++ b/autodata_core/schedulegen/collision.py @@ -0,0 +1,887 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Collision discovery and composed-trajectory checks for ScheduleGen.""" + +from __future__ import annotations + +import math +import torch +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from itertools import combinations +from typing import TYPE_CHECKING, Any + +from autodata_core.schedulegen.scheduling import get_scheduled_path_indices +from autodata_core.schedulegen.types import ( + ArmPath, + ArmWaypointConflict, + EpisodeGenerationError, + ObjectStateSample, + ScheduledRobotContact, + ScheduledWorldContact, +) +from autodata_core.scheduling import Schedule +from autodata_core.waypoint import Waypoint +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory +from autodata_interfaces.motion_planners.curobo.collision_spheres import ObjectCollisionSpheres +from autodata_interfaces.tasks.schedule_constraint_spec import SegmentId +from autodata_utils import pose_math + +if TYPE_CHECKING: + from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner + + +def find_waypoint_conflicts( + first_path: ArmPath, + second_path: ArmPath, + first_planner: CuroboPlanner, + second_planner: CuroboPlanner, + *, + collision_margin_m: float = 0.0, + densify_factor: int = 1, + pair_batch_size: int = 256, + sphere_batch_size: int = 64, +) -> tuple[ArmWaypointConflict, ...]: + """Return sampled original-waypoint conflicts between two arm paths. + + Joint paths are optionally linearly densified. Each colliding evaluated interior sample is + mapped to both original waypoints that bound its interpolation interval, so the scheduler + conservatively blocks that sampled interval. This is a finite-sampling check, not a continuous + swept-volume guarantee. + + Both planners must express their arm-local spheres in the same planning-root frame. Shared + ancestry stays in each planner so cuRobo can avoid arm-body collisions, but is removed from the + cross-arm distance query. Shared-joint proposals are averaged per candidate pair before FK so + both sides describe one physically consistent robot state; the embodiment's shared-joint solver + remains authoritative. + + Args: + first_path: Complete first-arm path. + second_path: Complete second-arm path. + first_planner: Initialized ordinary cuRobo planner for ``first_path``. + second_planner: Initialized ordinary cuRobo planner for ``second_path``. + collision_margin_m: Additional required sphere-surface separation [m]. + densify_factor: Linear samples per original path interval. + pair_batch_size: Maximum dense waypoint pairs evaluated together. + sphere_batch_size: Maximum spheres per arm-side distance chunk. + + Returns: + Deduplicated conflicts ordered by the two original waypoint indices. + """ + + assert isinstance(first_path, ArmPath) and isinstance(second_path, ArmPath) + assert first_path.eef_name != second_path.eef_name, "collision paths must belong to different lanes" + assert math.isfinite(collision_margin_m) and collision_margin_m >= 0.0 + assert type(densify_factor) is int and densify_factor >= 1 + assert type(pair_batch_size) is int and pair_batch_size >= 1 + assert type(sphere_batch_size) is int and sphere_batch_size >= 1 + _planning_roots_match(first_planner, second_planner) + + first_dense, first_support = _path_densify(first_path.joint_positions, densify_factor) + second_dense, second_support = _path_densify(second_path.joint_positions, densify_factor) + first_joint_names = tuple(getattr(first_planner, "active_joint_names", ())) + second_joint_names = tuple(getattr(second_planner, "active_joint_names", ())) + if first_joint_names or second_joint_names: + assert len(first_joint_names) == first_dense.shape[1] + assert len(second_joint_names) == second_dense.shape[1] + second_joint_index = {name: index for index, name in enumerate(second_joint_names)} + shared_joint_indices = tuple( + (index, second_joint_index[name]) for index, name in enumerate(first_joint_names) if name in second_joint_index + ) + second_count = second_dense.shape[0] + pair_count = first_dense.shape[0] * second_count + conflicts: dict[tuple[int, int], float] = {} + + for pair_start in range(0, pair_count, pair_batch_size): + pair_end = min(pair_start + pair_batch_size, pair_count) + flat_indices = torch.arange(pair_start, pair_end, dtype=torch.long) + first_dense_indices = torch.div(flat_indices, second_count, rounding_mode="floor") + second_dense_indices = torch.remainder(flat_indices, second_count) + first_positions = first_dense.index_select(0, first_dense_indices.to(first_dense.device)) + second_positions = second_dense.index_select(0, second_dense_indices.to(second_dense.device)) + for first_index, second_index in shared_joint_indices: + shared = 0.5 * ( + first_positions[:, first_index] + + second_positions[:, second_index].to(first_positions.device, first_positions.dtype) + ) + first_positions[:, first_index] = shared + second_positions[:, second_index] = shared.to(second_positions.device, second_positions.dtype) + first_spheres = first_planner.joint_positions_to_collision_spheres(first_positions) + second_spheres = second_planner.joint_positions_to_collision_spheres(second_positions).to( + device=first_spheres.device, + dtype=first_spheres.dtype, + ) + first_links = first_planner.collision_sphere_link_names(first_spheres.shape[1]) + second_links = second_planner.collision_sphere_link_names(second_spheres.shape[1]) + shared_links = set(first_links) & set(second_links) + first_spheres = first_spheres[:, [name not in shared_links for name in first_links]] + second_spheres = second_spheres[:, [name not in shared_links for name in second_links]] + assert first_spheres.shape[1] and second_spheres.shape[1], "each lane must own collision spheres" + minimum_clearance = _minimum_clearance(first_spheres, second_spheres, sphere_batch_size) + colliding = torch.nonzero(minimum_clearance <= collision_margin_m, as_tuple=False).flatten().cpu() + + for local_index in colliding.tolist(): + first_dense_index = int(first_dense_indices[local_index]) + second_dense_index = int(second_dense_indices[local_index]) + clearance = float(minimum_clearance[local_index].item()) + for first_index in first_support[first_dense_index]: + for second_index in second_support[second_dense_index]: + key = (first_index, second_index) + conflicts[key] = min(conflicts.get(key, math.inf), clearance) + + return tuple( + ArmWaypointConflict( + first_eef_name=first_path.eef_name, + first_waypoint_index=first_index, + second_eef_name=second_path.eef_name, + second_waypoint_index=second_index, + clearance_m=clearance, + ) + for (first_index, second_index), clearance in sorted(conflicts.items()) + ) + + +def _path_densify(path: torch.Tensor, factor: int) -> tuple[torch.Tensor, tuple[tuple[int, ...], ...]]: + """Interpolate joint samples and map each sample to its supporting original waypoints.""" + + dense, ticks = _joint_timeline_densify(path, factor) + supports = tuple((int(tick),) if tick.is_integer() else (math.floor(tick), math.ceil(tick)) for tick in ticks) + return dense, supports + + +def _minimum_clearance(first: torch.Tensor, second: torch.Tensor, sphere_batch_size: int) -> torch.Tensor: + """Compute the minimum active sphere-surface clearance for each paired sample. + + Args: + first: First sphere batch with shape ``(T, S1, 4)`` [m], storing XYZ and radius. + second: Second sphere batch with shape ``(T, S2, 4)`` [m], in the same frame. + sphere_batch_size: Maximum spheres per chunk in each pairwise distance calculation. + + Returns: + Signed minimum clearances with shape ``(T,)`` [m]; negative values indicate penetration. + Spheres with nonpositive radii are ignored. + + Raises: + AssertionError: Any paired sample has no finite active-sphere clearance. + """ + + batch_size = first.shape[0] + minimum = torch.full((batch_size,), math.inf, device=first.device, dtype=first.dtype) + for first_start in range(0, first.shape[1], sphere_batch_size): + first_chunk = first[:, first_start : first_start + sphere_batch_size] + for second_start in range(0, second.shape[1], sphere_batch_size): + second_chunk = second[:, second_start : second_start + sphere_batch_size] + distances = torch.linalg.vector_norm( + first_chunk[:, :, None, :3] - second_chunk[:, None, :, :3], + dim=-1, + ) + clearance = distances - first_chunk[:, :, None, 3] - second_chunk[:, None, :, 3] + valid = (first_chunk[:, :, None, 3] > 0.0) & (second_chunk[:, None, :, 3] > 0.0) + clearance = torch.where(valid, clearance, math.inf) + minimum = torch.minimum(minimum, clearance.flatten(1).amin(dim=1)) + assert bool(torch.isfinite(minimum).all()), "each arm path sample must contain an active collision sphere" + return minimum + + +def _planning_roots_match(first_planner: Any, second_planner: Any) -> None: + """Require matching planning-root names when both planners expose them.""" + + first_root = getattr(first_planner, "planning_root_frame_name", None) + second_root = getattr(second_planner, "planning_root_frame_name", None) + if first_root is not None and second_root is not None: + assert first_root == second_root, f"arm planners use different planning roots: {first_root!r}, {second_root!r}" + + +@dataclass(frozen=True) +class _ScheduledRobotState: + """Combined joint states and tool poses used by scheduled collision checks.""" + + joint_positions: torch.Tensor + initial_joint_positions: torch.Tensor + collision_joint_positions: torch.Tensor + collision_sample_ticks: tuple[float, ...] + tool_poses_by_eef: Mapping[str, torch.Tensor] + self_collision_sample_count: int + visualization_index: int | None + + +def arm_path_fk_validate( + eef_name: str, + waypoints: Sequence[Waypoint], + joint_positions: torch.Tensor, + planner: CuroboPlanner, + segment_bounds: Mapping[SegmentId, tuple[int, int]] | None = None, +) -> None: + """Check that path joint states reproduce their waypoint tool poses. + + Args: + eef_name: End-effector name included in failure diagnostics. + waypoints: Tool-pose targets in path order; translation is in [m]. + joint_positions: Planner-ordered joint states with shape (T, J) [rad, m]. + planner: Arm planner providing FK and pose tolerances. + segment_bounds: Optional half-open path bounds used to label failures. + + Raises: + EpisodeGenerationError: A joint state is invalid or FK exceeds a pose tolerance. + """ + + assert waypoints and len(waypoints) == len(joint_positions), "path poses and joint states must align" + if not bool(torch.isfinite(joint_positions).all()): + raise EpisodeGenerationError("forward_kinematics", f"{eef_name} path contains non-finite joint positions") + try: + actual_poses = planner.joint_positions_to_ee_poses(joint_positions) + except Exception as error: + raise EpisodeGenerationError("forward_kinematics", f"{eef_name} path FK failed: {error}") from error + + target_poses = torch.stack([waypoint.pose for waypoint in waypoints]).to( + device=actual_poses.device, + dtype=actual_poses.dtype, + ) + assert actual_poses.shape == target_poses.shape, "path FK must return one 4x4 pose per joint state" + finite = torch.isfinite(actual_poses).all(dim=(-2, -1)) & torch.isfinite(target_poses).all(dim=(-2, -1)) + position_error, rotation_error = pose_math.pose_errors(actual_poses, target_poses) + rejected = ( + ~finite + | (position_error > planner.config.position_threshold) + | (rotation_error > planner.config.rotation_threshold) + ) + if not bool(rejected.any()): + return + + first = int(torch.nonzero(rejected, as_tuple=False)[0, 0].item()) + position_error = torch.nan_to_num(position_error, nan=math.inf, posinf=math.inf, neginf=math.inf) + rotation_error = torch.nan_to_num(rotation_error, nan=math.inf, posinf=math.inf, neginf=math.inf) + location = f"path waypoint {first}/{len(waypoints)}" + for segment_id, (start, end) in (segment_bounds or {}).items(): + if start <= first < end: + location = f"{segment_id} waypoint {first - start}/{end - start} (path index {first})" + break + + raise EpisodeGenerationError( + "forward_kinematics", + f"{eef_name} path FK rejected {location}: " + f"position_error={float(position_error[first]):.6f} m, " + f"rotation_error={float(rotation_error[first]):.6f} rad", + ) + + +def scheduled_object_spheres( + object_states: tuple[ObjectStateSample, ...], + object_geometry: Mapping[str, ObjectCollisionSpheres], + *, + makespan_ticks: int, +) -> dict[str, torch.Tensor]: + """Transform fitted object spheres along the predicted object trajectory. + + Args: + object_states: Object poses at each execution boundary. + object_geometry: Fitted object-frame collision spheres keyed by object name. + makespan_ticks: Exclusive terminal execution tick. + + Returns: + Object name to sphere tensor with shape (makespan_ticks + 1, S, 4). + Each sphere stores its environment-frame center and radius [m]. + """ + + sphere_timelines = {} + for object_ref, geometry in sorted(object_geometry.items()): + samples = tuple(state for state in object_states if state.object_ref == object_ref) + assert tuple(sample.boundary_tick for sample in samples) == tuple(range(makespan_ticks + 1)) + poses = torch.tensor(tuple(sample.env_from_object for sample in samples), dtype=torch.float32) + centers = poses.new_tensor(tuple((*sphere.center, 1.0) for sphere in geometry.spheres)) + positions = torch.matmul(poses, centers.transpose(0, 1)).transpose(1, 2)[..., :3] + radii = poses.new_tensor(tuple(sphere.radius for sphere in geometry.spheres)).expand(len(samples), -1) + sphere_timelines[object_ref] = torch.cat((positions, radii.unsqueeze(-1)), dim=-1) + assert sphere_timelines, "object sphere projection requires at least one sphere geometry" + return sphere_timelines + + +def scheduled_robot_object_validate( + full_state_planner: CuroboPlanner, + scheduled_robot: _ScheduledRobotState, + object_spheres: Mapping[str, torch.Tensor], + *, + collision_margin_m: float, + object_manipulation_starts: Mapping[str, int], + robot_contacts: tuple[ScheduledRobotContact, ...], + batch_size: int = 256, +) -> tuple[int, int]: + """Check projected objects against the robot using grasp, carry and release permissions. + + Args: + full_state_planner: Collision model for the combined robot. + scheduled_robot: Scheduled joint states and tool poses. + object_spheres: Predicted environment-frame sphere centers and radii [m]. + collision_margin_m: Additional required surface separation [m]. + object_manipulation_starts: Boundary where each projected object replaces its original world mesh. + Robot/world checks cover the original mesh before this boundary. + robot_contacts: Object/link pairs and intervals where contact is permitted. + batch_size: Maximum number of states per collision query. + + Returns: + Number of checked object-state samples and samples with permitted contacts. + + Raises: + EpisodeGenerationError: Geometry is missing or an unpermitted collision is found. + """ + + assert type(batch_size) is int and batch_size > 0 + assert set(object_manipulation_starts) == set(object_spheres) + robot_states = torch.cat( + (scheduled_robot.initial_joint_positions.unsqueeze(0), scheduled_robot.joint_positions), + dim=0, + ) + sample_count = 0 + waived_contact_sample_count = 0 + contacts_by_object: dict[str, list[ScheduledRobotContact]] = {} + for contact in robot_contacts: + contacts_by_object.setdefault(contact.spec.object_ref, []).append(contact) + + missing = set(contacts_by_object) - set(object_spheres) + if missing: + raise EpisodeGenerationError( + "full_state_robot_contact_resolution", f"missing object geometry: {sorted(missing)}" + ) + for object_ref, spheres in sorted(object_spheres.items()): + contacts = contacts_by_object.get(object_ref, []) + assert len(spheres) == len(robot_states), "robot and object boundary timelines must align" + if any(contact.stop_tick > len(spheres) for contact in contacts): + raise EpisodeGenerationError( + "full_state_robot_contact_resolution", + f"robot-contact interval for {object_ref!r} exceeds its projected timeline", + ) + start_tick = object_manipulation_starts[object_ref] + assert type(start_tick) is int and 0 <= start_tick <= len(spheres) + allowed_links_by_tick = tuple( + tuple( + sorted({ + link_name + for contact in contacts + if contact.start_tick <= tick < contact.stop_tick + for link_name in contact.spec.robot_link_names + }) + ) + for tick in range(start_tick, len(spheres)) + ) + start = start_tick + while start < len(spheres): + allowed_links = allowed_links_by_tick[start - start_tick] + stop = start + 1 + while ( + stop < len(spheres) + and stop - start < batch_size + and allowed_links_by_tick[stop - start_tick] == allowed_links + ): + stop += 1 + try: + strict_collision_free = full_state_planner.joint_positions_environment_spheres_collision_free( + robot_states[start:stop], + spheres[start:stop], + collision_margin_m, + ) + if allowed_links: + collision_free = full_state_planner.joint_positions_environment_spheres_collision_free( + robot_states[start:stop], + spheres[start:stop], + collision_margin_m, + allowed_robot_link_names=allowed_links, + ) + waived_contact_sample_count += int( + torch.count_nonzero(~strict_collision_free & collision_free).item() + ) + else: + collision_free = strict_collision_free + except Exception as error: + raise EpisodeGenerationError( + "full_state_robot_object_collision", + f"cuRobo robot/object query failed for {object_ref!r} at boundary tick {start}: " + f"{type(error).__name__}: {error}", + ) from error + sample_count += stop - start + rejected = torch.nonzero(~collision_free, as_tuple=False) + if len(rejected): + tick = start + int(rejected[0, 0].item()) + witness_message = "" + try: + witness = full_state_planner.joint_positions_environment_spheres_collision_witness( + robot_states[tick : tick + 1], + spheres[tick : tick + 1], + collision_margin_m, + allowed_robot_link_names=allowed_links, + ) + if witness is not None: + link_name, robot_sphere_index, object_sphere_index = witness + witness_message = ( + f"; {link_name}[{robot_sphere_index}] versus {object_ref}[{object_sphere_index}]" + ) + except Exception as error: + witness_message = f"; witness unavailable: {type(error).__name__}: {error}" + raise EpisodeGenerationError( + "full_state_robot_object_collision", + f"full robot intersects projected object {object_ref!r} outside reviewed contact at " + f"boundary tick {tick}/{len(spheres) - 1}{witness_message}", + ) + start = stop + return sample_count, waived_contact_sample_count + + +def scheduled_world_validate( + full_state_planner: CuroboPlanner, + scheduled_robot: _ScheduledRobotState, + object_spheres: Mapping[str, torch.Tensor], + object_geometry: Mapping[str, ObjectCollisionSpheres], + *, + collision_margin_m: float, + object_manipulation_starts: Mapping[str, int], + world_contacts: tuple[ScheduledWorldContact, ...] = (), + batch_size: int = 256, +) -> tuple[int, int, int]: + """Check the robot and predicted object poses against the planning world. + + Args: + full_state_planner: Collision model for the combined robot. + scheduled_robot: Scheduled joint states and tool poses. + object_spheres: Predicted environment-frame sphere centers and radii [m]. + object_geometry: Fitted object geometry and corresponding world obstacle names. + collision_margin_m: Additional required surface separation [m]. + object_manipulation_starts: First manipulation-segment tick per projected object. + Its original mesh remains an obstacle before that tick. + world_contacts: Object/fixture pairs and intervals where contact is permitted. + batch_size: Maximum number of states per collision query. + + Returns: + Robot/world, object/world and permitted-contact sample counts. + + Raises: + EpisodeGenerationError: World synchronization fails or an unpermitted collision is found. + """ + + assert type(batch_size) is int and batch_size > 0 + assert set(object_spheres) == set(object_geometry), "projected object geometry must be complete" + assert set(object_manipulation_starts) == set(object_geometry) + assert all( + type(tick) is int and 0 <= tick <= len(scheduled_robot.joint_positions) + 1 + for tick in object_manipulation_starts.values() + ) + excluded_paths = tuple(sorted(geometry.obstacle_path for geometry in object_geometry.values())) + assert len(excluded_paths) == len(set(excluded_paths)), "projected objects must resolve to unique obstacle paths" + try: + full_state_planner.update_world() + except Exception as error: + raise EpisodeGenerationError( + "full_state_world_sync", + f"cuRobo world synchronization failed: {type(error).__name__}: {error}", + ) from error + + robot_states = scheduled_robot.collision_joint_positions + robot_sample_ticks = scheduled_robot.collision_sample_ticks + + def exclusions_at(tick: float) -> tuple[str, ...]: + """Exclude each original mesh only after manipulation begins at this boundary.""" + return tuple( + sorted( + geometry.obstacle_path + for name, geometry in object_geometry.items() + if object_manipulation_starts[name] <= tick + ) + ) + + exclusions_by_tick = tuple(exclusions_at(tick) for tick in robot_sample_ticks) + exclusions_by_boundary = tuple(exclusions_at(tick) for tick in range(len(scheduled_robot.joint_positions) + 1)) + start = 0 + while start < len(robot_states): + stop = start + 1 + while ( + stop < len(robot_states) + and stop - start < batch_size + and exclusions_by_tick[stop] == exclusions_by_tick[start] + ): + stop += 1 + try: + collision_free = full_state_planner.joint_positions_world_collision_free( + robot_states[start:stop], + collision_margin_m, + excluded_obstacle_paths=exclusions_by_tick[start], + ) + except Exception as error: + raise EpisodeGenerationError( + "full_state_robot_world_collision", + f"cuRobo robot/world query failed at schedule tick {start}: {type(error).__name__}: {error}", + ) from error + rejected = torch.nonzero(~collision_free, as_tuple=False) + if len(rejected): + sample = start + int(rejected[0, 0].item()) + tick = robot_sample_ticks[sample] + witness_message = "" + try: + witness = full_state_planner.joint_positions_world_collision_witness( + robot_states[sample : sample + 1], + collision_margin_m, + excluded_obstacle_paths=exclusions_by_tick[start], + ) + if witness is not None: + link_name, sphere_index, obstacle_path = witness + witness_message = f"; {link_name}[{sphere_index}] versus {obstacle_path}" + except Exception as error: + witness_message = f"; witness unavailable: {type(error).__name__}: {error}" + raise EpisodeGenerationError( + "full_state_robot_world_collision", + "full robot intersects the configured world at schedule tick " + f"{tick:g}/{len(scheduled_robot.joint_positions)}{witness_message}", + ) + start = stop + + resolved_contacts: list[tuple[ScheduledWorldContact, tuple[str, ...]]] = [] + for contact in world_contacts: + object_ref = contact.spec.object_ref + if object_ref not in object_spheres: + raise EpisodeGenerationError( + "full_state_world_contact_resolution", + f"world-contact object {object_ref!r} has no projected sphere geometry", + ) + if contact.stop_tick > len(object_spheres[object_ref]): + raise EpisodeGenerationError( + "full_state_world_contact_resolution", + f"world-contact interval for {object_ref!r} exceeds its projected timeline", + ) + try: + fixture_paths = full_state_planner.world_object_obstacle_paths(contact.spec.fixture_ref) + except Exception as error: + raise EpisodeGenerationError( + "full_state_world_contact_resolution", + f"fixture {contact.spec.fixture_ref!r} could not be resolved: {type(error).__name__}: {error}", + ) from error + overlap = set(fixture_paths) & set(excluded_paths) + if overlap: + raise EpisodeGenerationError( + "full_state_world_contact_resolution", + f"fixture {contact.spec.fixture_ref!r} overlaps projected objects: {sorted(overlap)}", + ) + resolved_contacts.append((contact, fixture_paths)) + + object_sample_count = 0 + waived_contact_sample_count = 0 + for object_ref, spheres in sorted(object_spheres.items()): + object_sample_count += len(spheres) + allowed_paths_by_tick = tuple( + tuple( + sorted({ + path + for contact, fixture_paths in resolved_contacts + if contact.spec.object_ref == object_ref and contact.start_tick <= tick < contact.stop_tick + for path in fixture_paths + }) + ) + for tick in range(len(spheres)) + ) + start = 0 + while start < len(spheres): + allowed_paths = allowed_paths_by_tick[start] + stop = start + 1 + while ( + stop < len(spheres) + and stop - start < batch_size + and allowed_paths_by_tick[stop] == allowed_paths + and exclusions_by_boundary[stop] == exclusions_by_boundary[start] + ): + stop += 1 + strict_exclusions = tuple( + sorted({object_geometry[object_ref].obstacle_path, *exclusions_by_boundary[start]}) + ) + query_exclusions = tuple(sorted(set(strict_exclusions) | set(allowed_paths))) + try: + strict_collision_free = full_state_planner.environment_spheres_world_collision_free( + spheres[start:stop], + collision_margin_m, + excluded_obstacle_paths=strict_exclusions, + ) + if allowed_paths: + collision_free = full_state_planner.environment_spheres_world_collision_free( + spheres[start:stop], + collision_margin_m, + excluded_obstacle_paths=query_exclusions, + ) + waived_contact_sample_count += int( + torch.count_nonzero(~strict_collision_free & collision_free).item() + ) + else: + collision_free = strict_collision_free + except Exception as error: + raise EpisodeGenerationError( + "full_state_object_world_collision", + f"cuRobo object/world query failed for {object_ref!r} at boundary tick {start}: " + f"{type(error).__name__}: {error}", + ) from error + rejected = torch.nonzero(~collision_free, as_tuple=False) + if len(rejected): + tick = start + int(rejected[0, 0].item()) + witness_message = "" + try: + witness = full_state_planner.environment_spheres_world_collision_witness( + spheres[tick : tick + 1], + collision_margin_m, + excluded_obstacle_paths=query_exclusions, + ) + if witness is not None: + sphere_index, obstacle_path = witness + witness_message = f"; {object_ref}[{sphere_index}] versus {obstacle_path}" + except Exception as error: + witness_message = f"; witness unavailable: {type(error).__name__}: {error}" + raise EpisodeGenerationError( + "full_state_object_world_collision", + f"projected object {object_ref!r} intersects the configured world at " + f"boundary tick {tick}/{len(spheres) - 1}{witness_message}", + ) + start = stop + _object_pairs_validate(object_spheres, object_manipulation_starts, collision_margin_m, batch_size) + return len(robot_states), object_sample_count, waived_contact_sample_count + + +def _object_pairs_validate( + object_spheres: Mapping[str, torch.Tensor], + object_manipulation_starts: Mapping[str, int], + collision_margin_m: float, + batch_size: int, +) -> None: + """Reject collisions between projected object timelines. + + Args: + object_spheres: Environment-frame spheres with shape ``(T, N, 4)`` per object [m]. + object_manipulation_starts: Boundary where each projected object replaces its original world mesh. + collision_margin_m: Additional required surface separation [m]. + batch_size: Maximum number of states per collision query. + """ + + for first_name, second_name in combinations(sorted(object_spheres), 2): + first, second = object_spheres[first_name], object_spheres[second_name] + assert len(first) == len(second), "projected object timelines must align" + # Until both original meshes are excluded, the native object/world queries above + # cover this pair without substituting another surface-sphere approximation. + pair_start = max(object_manipulation_starts[first_name], object_manipulation_starts[second_name]) + for start in range(pair_start, len(first), batch_size): + clearances = _minimum_clearance(first[start : start + batch_size], second[start : start + batch_size], 64) + rejected = torch.nonzero(clearances <= collision_margin_m, as_tuple=False) + if len(rejected): + tick = start + int(rejected[0, 0]) + raise EpisodeGenerationError( + "full_state_object_object_collision", + f"projected objects {first_name!r} and {second_name!r} collide at boundary tick {tick}", + ) + + +def scheduled_robot_validate( + datastream: Any, + planners: Mapping[str, CuroboPlanner], + full_state_planner: CuroboPlanner, + arm_paths: Mapping[str, ArmPath], + schedule: Schedule, + initial_joint_positions: torch.Tensor, + *, + joint_trajectory: NamedJointTrajectory | None = None, + collision_margin_m: float, + densify_factor: int, + batch_size: int = 256, +) -> _ScheduledRobotState: + """Combine arm paths and check tool FK and robot self-collision. + + Args: + datastream: Interface providing the robot joint names and controller frames. + planners: Arm planners keyed by end-effector name. + full_state_planner: Collision model containing the combined robot joints. + arm_paths: Complete unscheduled arm paths. + schedule: Execution ticks for every segment waypoint. + initial_joint_positions: Initial articulation state in live joint order [rad, m]. + joint_trajectory: Optional coupled-controller trajectory in named joint order. + collision_margin_m: Additional required surface separation [m]. + densify_factor: Linear samples per waypoint interval for collision checks. + batch_size: Maximum number of states per collision query. + + Returns: + Combined joint states, tool poses and collision-check details. + + Raises: + EpisodeGenerationError: Joint states, tool poses or sampled self-collisions are invalid. + """ + + live_names = tuple(datastream.get_robot_joint_names()) + assert initial_joint_positions.shape == (len(live_names),) + full_names = full_state_planner.active_joint_names + live_index = {name: index for index, name in enumerate(live_names)} + missing = set(full_names) - set(live_names) + assert not missing, f"full-state joints are absent from the live articulation: {sorted(missing)}" + for joint_name, compiled_position in full_state_planner.locked_joint_positions.items(): + if joint_name not in live_index: + raise EpisodeGenerationError( + "full_state_locked_joint_state", + f"locked joint {joint_name!r} is absent from the live articulation", + ) + live_position = float(initial_joint_positions[live_index[joint_name]].item()) + if not math.isfinite(live_position) or not math.isclose( + live_position, + compiled_position, + abs_tol=1.0e-6, + rel_tol=0.0, + ): + raise EpisodeGenerationError( + "full_state_locked_joint_state", + f"locked joint {joint_name!r} changed from compiled {compiled_position:.8f} " + f"to live {live_position:.8f}", + ) + initial_full_state = initial_joint_positions[[live_index[name] for name in full_names]] + states = initial_full_state.repeat(schedule.makespan_ticks, 1) + full_index = {name: index for index, name in enumerate(full_names)} + written: dict[str, str] = {} + timeline_indices: dict[str, tuple[int, ...]] = {} + + if joint_trajectory is not None: + assert joint_trajectory.positions.shape[0] == schedule.makespan_ticks + missing = set(joint_trajectory.joint_names) - set(full_names) + assert not missing, f"coupled trajectory contains joints outside the full-state context: {sorted(missing)}" + trajectory = joint_trajectory.positions.to(device=states.device, dtype=states.dtype) + for trajectory_index, joint_name in enumerate(joint_trajectory.joint_names): + states[:, full_index[joint_name]] = trajectory[:, trajectory_index] + written[joint_name] = "whole_body" + + for eef_name, path in arm_paths.items(): + planner = planners[eef_name] + indices = get_scheduled_path_indices(path, schedule) + timeline_indices[eef_name] = indices + source_indices = torch.tensor(indices, device=path.joint_positions.device) + lane_states = path.joint_positions.index_select(0, source_indices).to(device=states.device, dtype=states.dtype) + assert lane_states.shape == (schedule.makespan_ticks, len(planner.active_joint_names)) + for lane_index, joint_name in enumerate(planner.active_joint_names): + assert joint_name in full_index, f"group joint {joint_name!r} is absent from the full-state context" + if written.get(joint_name) == "whole_body": + continue + column = full_index[joint_name] + if joint_name in written and not torch.allclose( + states[:, column], lane_states[:, lane_index], atol=1.0e-6, rtol=0.0 + ): + raise EpisodeGenerationError( + "full_state_composition", + f"groups {written[joint_name]!r} and {eef_name!r} disagree on shared joint {joint_name!r}", + ) + states[:, column] = lane_states[:, lane_index] + written[joint_name] = eef_name + unwritten = set(full_names) - set(written) + assert not unwritten, f"full-state active joints have no trajectory owner: {sorted(unwritten)}" + + tool_links = tuple(planners[name].config.ee_link_name for name in arm_paths) + assert all(tool_links), "every planning group must declare its physical tool link" + boundary_states = torch.cat((initial_full_state.unsqueeze(0), states), dim=0) + try: + full_state_planner.planning_root_pose_refresh() + full_tool_poses = full_state_planner.joint_positions_to_link_poses( + boundary_states, + tool_links, + ) + except Exception as error: + raise EpisodeGenerationError( + "full_state_forward_kinematics", + f"{type(error).__name__}: {error}", + ) from error + for eef_name, tool_link in zip(arm_paths, tool_links, strict=True): + path = arm_paths[eef_name] + target_poses = torch.stack([path.waypoints[index].pose for index in timeline_indices[eef_name]]) + actual_poses = full_tool_poses[tool_link][1:] + target_poses = target_poses.to(device=actual_poses.device, dtype=actual_poses.dtype) + position_error, rotation_error = pose_math.pose_errors(actual_poses, target_poses) + rejected = ( + ~torch.isfinite(actual_poses).all(dim=(-2, -1)) + | ~torch.isfinite(target_poses).all(dim=(-2, -1)) + | (position_error > planners[eef_name].config.position_threshold) + | (rotation_error > planners[eef_name].config.rotation_threshold) + ) + if bool(rejected.any()): + tick = int(torch.nonzero(rejected, as_tuple=False)[0, 0].item()) + raise EpisodeGenerationError( + "full_state_forward_kinematics", + f"{eef_name} full-state FK rejected schedule tick {tick}: " + f"position_error={float(position_error[tick]):.6f} m, " + f"rotation_error={float(rotation_error[tick]):.6f} rad", + ) + + visualization_index = None + if full_state_planner.plan_visualizer is not None: + full_state_planner.world_visualization_refresh() + spheres = full_state_planner.joint_positions_to_collision_spheres(boundary_states) + visualization_index = full_state_planner.plan_visualizer.animate_collision_spheres(spheres) + + dense_states, sample_ticks = _joint_timeline_densify(boundary_states, densify_factor) + for start in range(0, len(dense_states), batch_size): + try: + collision_free = full_state_planner.joint_positions_self_collision_free( + dense_states[start : start + batch_size], + collision_margin_m, + ) + except Exception as error: + raise EpisodeGenerationError( + "full_state_self_collision", + f"cuRobo query failed at validation sample {start}: {type(error).__name__}: {error}", + ) from error + rejected = torch.nonzero(~collision_free, as_tuple=False) + if len(rejected): + sample = start + int(rejected[0, 0].item()) + witness_message = "" + try: + witness = full_state_planner.joint_positions_self_collision_witness( + dense_states[sample : sample + 1], + collision_margin_m, + ) + if witness is not None: + first_link, first_sphere, second_link, second_sphere, clearance = witness + witness_message = ( + f"; {first_link}[{first_sphere}] versus {second_link}[{second_sphere}], " + f"clearance={clearance:.6f} m" + ) + except Exception as error: + witness_message = f"; witness unavailable: {type(error).__name__}: {error}" + raise EpisodeGenerationError( + "full_state_self_collision", + f"full robot self collision at validation sample {sample}/{len(dense_states)} " + f"near schedule tick {sample_ticks[sample]:.3f}{witness_message}", + ) + return _ScheduledRobotState( + joint_positions=states, + initial_joint_positions=initial_full_state, + collision_joint_positions=dense_states, + collision_sample_ticks=sample_ticks, + tool_poses_by_eef={ + eef_name: full_tool_poses[tool_link].detach().clone() + for eef_name, tool_link in zip(arm_paths, tool_links, strict=True) + }, + self_collision_sample_count=len(dense_states), + visualization_index=visualization_index, + ) + + +def _joint_timeline_densify(states: torch.Tensor, factor: int) -> tuple[torch.Tensor, tuple[float, ...]]: + """Subdivide joint-space intervals while retaining all original samples. + + Args: + states: Joint positions with shape ``(T, J)`` in consistent joint order [rad, m]. + factor: Equal subdivisions per adjacent pair; one leaves the timeline unchanged. + + Returns: + Interpolated joint positions and their fractional ticks on the original timeline. + The final original sample is included exactly once. + """ + + assert states.ndim == 2 and len(states) > 0 + assert type(factor) is int and factor >= 1 + if factor == 1 or len(states) == 1: + return states, tuple(float(index) for index in range(len(states))) + samples: list[torch.Tensor] = [] + ticks: list[float] = [] + for index in range(len(states) - 1): + for subdivision in range(factor): + alpha = subdivision / factor + samples.append(torch.lerp(states[index], states[index + 1], alpha)) + ticks.append(index + alpha) + samples.append(states[-1]) + ticks.append(float(len(states) - 1)) + return torch.stack(samples), tuple(ticks) + + +__all__ = ["find_waypoint_conflicts"] diff --git a/autodata_core/schedulegen/path_builder.py b/autodata_core/schedulegen/path_builder.py new file mode 100644 index 0000000..e5f5539 --- /dev/null +++ b/autodata_core/schedulegen/path_builder.py @@ -0,0 +1,1431 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build complete unscheduled paths using AutoData trajectory and planner interfaces.""" + +from __future__ import annotations + +import math +import torch +from collections.abc import Mapping, Sequence +from copy import deepcopy +from dataclasses import dataclass, field, replace +from types import MappingProxyType +from typing import TYPE_CHECKING + +from autodata_core.schedulegen.collision import arm_path_fk_validate +from autodata_core.schedulegen.types import ( + ArmPath, + EpisodeGenerationError, + EpisodePaths, + PathObjectEvent, + PathObjectPose, +) +from autodata_core.waypoint import Waypoint, WaypointSequence, WaypointTrajectory +from autodata_interfaces.motion_planners.curobo.collision_spheres import ObjectCollisionSpheres +from autodata_interfaces.tasks.schedule_constraint_spec import SegmentId +from autodata_interfaces.tasks.segment_spec import ( + DemonstrationSourceWindowSpec, + SegmentEventPoint, + SegmentEventSpec, + SegmentEventType, + SegmentKind, + SegmentProvider, + SegmentSpec, +) +from autodata_utils import pose_math + +if TYPE_CHECKING: + from autodata_core.data_generator import DataGenerator + from autodata_interfaces.datastream.datastream import Datastream + from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner + + +@dataclass(frozen=True) +class _CarriedObject: + """Rigid object pose relative to the planner/controller tool frame.""" + + object_name: str + tool_from_object: torch.Tensor + + def pose_at_tool(self, tool_pose: torch.Tensor) -> torch.Tensor: + """Compose the tool-relative object transform with an environment-relative tool pose.""" + + return tool_pose @ self.tool_from_object + + +@dataclass(frozen=True) +class _PreparedSegmentGoal: + """Resolved tool target consumed by a motion-planned segment.""" + + segment_id: SegmentId | None + entry_waypoint: Waypoint + object_pose_overrides: Mapping[str, torch.Tensor] = field(default_factory=dict) + + +@dataclass(frozen=True) +class _SegmentBuildRequest: + """Inputs for building one segment on an end-effector path.""" + + data_generator: DataGenerator + planner: CuroboPlanner + env_id: int + eef_name: str + subtask_index: int + segment_id: SegmentId + segment_spec: SegmentSpec + current_joints: torch.Tensor + passthrough: dict[str, torch.Tensor] + previous_waypoints: tuple[Waypoint, ...] + goal: _PreparedSegmentGoal | None + carried_object: _CarriedObject | None + object_collision_spheres: dict[str, ObjectCollisionSpheres] + source_skill: WaypointTrajectory | None + source_boundary: tuple[int, int] | None + source_demo_index: int | None + + +@dataclass(frozen=True) +class _SegmentPath: + """Waypoints, joint states and object events produced by one segment.""" + + waypoints: tuple[Waypoint, ...] + joint_positions: tuple[torch.Tensor, ...] + carried_object: _CarriedObject | None + object_events: tuple[PathObjectEvent, ...] = () + object_pose_keyframes: tuple[PathObjectPose, ...] = () + + def __post_init__(self) -> None: + """Require a nonempty segment with one joint configuration per waypoint.""" + + assert self.waypoints, "a segment must contain at least one waypoint" + assert len(self.waypoints) == len(self.joint_positions), "segment waypoints and joint positions must align" + + +@dataclass(frozen=True) +class PathBuilder: + """Build complete arm paths before scheduling or simulator execution. + + Reuse :class:`DataGenerator` for source selection, transforms and trajectory merging. + Add planner joint paths, object events and collision geometry needed by the scheduler. + Object geometry is cached across attempts; path and attachment state are per attempt. + + Args: + planners: Arm planners keyed by end-effector name. + """ + + planners: Mapping[str, CuroboPlanner] + _object_geometry_cache: dict[str, ObjectCollisionSpheres] = field( + default_factory=dict, init=False, repr=False, compare=False + ) + + def build( + self, + data_generator: DataGenerator, + env_id: int, + eef_names: tuple[str, ...], + selected_source: dict[str, int | None], + *, + boundaries: dict | None = None, + ) -> tuple[EpisodePaths, tuple[tuple[str, str], ...]]: + """Build all arm paths, trying source candidates in their selected order. + + Args: + data_generator: Owner of source selection, transformation and trajectory merging. + env_id: Environment whose initial state defines the paths. + eef_names: End effectors whose paths must be built. + selected_source: Source-demo index per end effector, updated in place. + boundaries: Optional source subtask boundaries already randomized for this attempt. + + Returns: + Complete unscheduled paths and source-selection diagnostics. + + Raises: + EpisodeGenerationError: No selected source can produce valid paths. + """ + if boundaries is None: + boundaries = data_generator.randomize_subtask_boundaries() + candidates = data_generator.select_episode_source_candidates(env_id, boundaries) + if not candidates: + return ( + self._arm_paths_build( + data_generator, + env_id, + eef_names, + selected_source, + boundaries, + ), + (), + ) + + attempted: list[int] = [] + rejections: list[tuple[int, EpisodeGenerationError]] = [] + for candidate_index, candidate in enumerate(candidates): + attempted.append(candidate) + selected_source.update(dict.fromkeys(eef_names, candidate)) + try: + episode = self._arm_paths_build( + data_generator, + env_id, + eef_names, + selected_source, + boundaries, + ) + except EpisodeGenerationError as failure: + rejections.append((candidate, failure)) + diagnostics = _source_candidate_diagnostics(data_generator, attempted, rejections) + if candidate_index == len(candidates) - 1: + raise EpisodeGenerationError(failure.stage, str(failure), diagnostics) from failure + continue + return episode, _source_candidate_diagnostics(data_generator, attempted, rejections) + + raise AssertionError("source candidate loop must return or raise") + + def _arm_paths_build( + self, + data_generator: DataGenerator, + env_id: int, + eef_names: tuple[str, ...], + selected_source: dict[str, int | None], + boundaries: dict, + ) -> EpisodePaths: + """Build every arm path and clear temporary planner attachments afterward.""" + + planners = tuple(self.planners.values()) + for planner in planners: + planner.object_collision_spheres_reset() + try: + object_collision_spheres: dict[str, ObjectCollisionSpheres] = {} + object_effect_poses: dict[tuple[SegmentId, str], torch.Tensor] = {} + arm_paths = {} + path_eef_names = data_generator.datastream.get_path_build_order() + assert set(path_eef_names) == set(eef_names), "path construction order must cover every EEF" + for eef_name in path_eef_names: + arm_paths[eef_name] = self._arm_path_build( + data_generator, + env_id, + eef_name, + boundaries, + selected_source, + object_collision_spheres, + object_effect_poses, + ) + episode_paths = EpisodePaths(arm_paths, object_collision_spheres) + finally: + for planner in planners: + planner.object_collision_spheres_reset() + return episode_paths + + def _arm_path_build( + self, + data_generator: DataGenerator, + env_id: int, + eef_name: str, + boundaries: dict, + selected_source: dict[str, int | None], + object_collision_spheres: dict[str, ObjectCollisionSpheres], + object_effect_poses: dict[tuple[SegmentId, str], torch.Tensor] | None = None, + ) -> ArmPath: + """Join planned, demonstrated and scripted segments for one arm. + + Args: + data_generator: Owner of source selection and trajectory transformation. + env_id: Environment supplying the initial joint and object state. + eef_name: End effector whose ordered segments are built. + boundaries: Randomized source subtask boundaries for this attempt. + selected_source: Source-demo indices, updated during demonstration selection. + object_collision_spheres: Shared object geometry populated by attachment events. + object_effect_poses: Object poses produced by earlier segments, updated in place. + + Returns: + Complete arm path with aligned joint states, segment bounds and object events. + """ + + if object_effect_poses is None: + object_effect_poses = {} + datastream = data_generator.datastream + planner = self.planners[eef_name] + planner.planning_root_pose_refresh() + subtasks = datastream.get_subtasks(eef_name) + assert subtasks, f"ScheduleGen requires at least one subtask for {eef_name}" + first_segments = subtasks[0].segments + assert first_segments, f"ScheduleGen subtask {eef_name}.{subtasks[0].name} has no segments" + policy = datastream.get_generation_policy() + current_joints = datastream.get_robot_joint_positions(env_ids=[env_id], joint_names=planner.active_joint_names)[ + 0 + ].clone() + if first_segments[0].provider == SegmentProvider.MOTION_PLANNER: + current_joints = _initial_auxiliary_joint_positions_apply(planner, current_joints) + initial_joint_positions = planner.joint_positions_to_named_positions(current_joints) + waypoints: list[Waypoint] = [] + joint_positions: list[torch.Tensor] = [] + segment_bounds: dict[SegmentId, tuple[int, int]] = {} + object_events: list[PathObjectEvent] = [] + object_pose_keyframes: list[PathObjectPose] = [] + previous_passthrough: dict[str, torch.Tensor] | None = None + carried_object: _CarriedObject | None = None + passthrough_smoothed = False + previous_segment_waypoints: tuple[Waypoint, ...] = () + + for subtask_index, subtask in enumerate(subtasks): + assert subtask.segments, f"ScheduleGen subtask {eef_name}.{subtask.name} has no segments" + demonstration_segments = tuple( + (index, segment) + for index, segment in enumerate(subtask.segments) + if segment.provider == SegmentProvider.DEMONSTRATION + ) + assert ( + len(demonstration_segments) <= 1 + ), f"ScheduleGen subtask {eef_name}.{subtask.name} supports at most one demonstration segment" + source_skill = None + source_boundary = None + selected_source_index = None + prepared_goals: dict[SegmentId, _PreparedSegmentGoal] = {} + if demonstration_segments: + skill_index, skill_spec = demonstration_segments[0] + assert skill_spec.kind == SegmentKind.SKILL + source_skill, source_boundary, selected_source_index = self._demonstration_prepare( + data_generator=data_generator, + env_id=env_id, + eef_name=eef_name, + subtask_index=subtask_index, + segment_index=skill_index, + boundaries=boundaries, + selected_source=selected_source, + ) + skill_id = SegmentId(eef_name, subtask.name, skill_spec.name) + prepared_goals[skill_id] = _PreparedSegmentGoal(skill_id, deepcopy(source_skill[0])) + if previous_passthrough is None: + previous_passthrough = datastream.joint_positions_to_passthrough_actions( + initial_joint_positions, + prepared_goals[skill_id].entry_waypoint.passthrough_action, + ) + else: + if previous_passthrough is None: + live_passthrough = datastream.get_passthrough_actions(env_ids=[env_id]) + if live_passthrough is None: + raise EpisodeGenerationError( + "passthrough_state", + f"embodiment cannot recover live passthrough actions for first motion-only lane {eef_name}", + ) + assert all( + isinstance(values, torch.Tensor) and values.ndim == 2 and len(values) == 1 + for values in live_passthrough.values() + ), "live passthrough actions must contain one batched row per channel" + passthrough_template = { + name: values[0].detach().clone() for name, values in live_passthrough.items() + } + previous_passthrough = datastream.joint_positions_to_passthrough_actions( + initial_joint_positions, + passthrough_template, + ) + else: + assert ( + previous_segment_waypoints + ), f"motion-only subtask {eef_name}.{subtask.name} requires a preceding segment path" + + for segment_spec in subtask.segments: + if segment_spec.provider == SegmentProvider.SCRIPTED and not passthrough_smoothed: + _passthrough_transitions_smooth( + waypoints, + eef_name, + delay_steps=policy.skill_passthrough_delay_steps, + interpolation_steps=policy.skill_passthrough_interpolation_steps, + ) + passthrough_smoothed = True + previous_passthrough = deepcopy(waypoints[-1].passthrough_action) + + segment_id = SegmentId(eef_name, subtask.name, segment_spec.name) + goal = prepared_goals.get(segment_spec.goal_segment_id) + if segment_spec.motion_goal is not None: + assert previous_passthrough is not None + pose_template = ( + previous_segment_waypoints[-1].pose + if previous_segment_waypoints + else planner.joint_positions_to_ee_poses(current_joints.unsqueeze(0))[0] + ) + goal = self._motion_goal_prepare( + data_generator=data_generator, + env_id=env_id, + segment_id=segment_id, + segment_spec=segment_spec, + pose_template=pose_template, + passthrough=previous_passthrough, + object_effect_poses=object_effect_poses, + ) + segment_path = self._segment_build( + _SegmentBuildRequest( + data_generator=data_generator, + planner=planner, + env_id=env_id, + eef_name=eef_name, + subtask_index=subtask_index, + segment_id=segment_id, + segment_spec=segment_spec, + current_joints=current_joints, + passthrough=previous_passthrough, + previous_waypoints=previous_segment_waypoints, + goal=goal, + carried_object=carried_object, + object_collision_spheres=object_collision_spheres, + source_skill=source_skill, + source_boundary=source_boundary, + source_demo_index=selected_source_index, + ) + ) + segment_start = len(waypoints) + waypoints.extend(segment_path.waypoints) + joint_positions.extend(segment_path.joint_positions) + segment_bounds[segment_id] = segment_start, len(waypoints) + object_events.extend(segment_path.object_events) + object_pose_keyframes.extend(segment_path.object_pose_keyframes) + for keyframe in segment_path.object_pose_keyframes: + object_effect_poses[(segment_id, keyframe.object_ref)] = keyframe.env_from_object + current_joints = segment_path.joint_positions[-1] + carried_object = segment_path.carried_object + previous_passthrough = deepcopy(segment_path.waypoints[-1].passthrough_action) + previous_segment_waypoints = segment_path.waypoints + + if not passthrough_smoothed: + _passthrough_transitions_smooth( + waypoints, + eef_name, + delay_steps=policy.skill_passthrough_delay_steps, + interpolation_steps=policy.skill_passthrough_interpolation_steps, + ) + joint_positions = [ + self._joint_positions_match_passthrough( + datastream, + planner, + positions, + waypoint.passthrough_action, + ) + for waypoint, positions in zip(waypoints, joint_positions, strict=True) + ] + joint_position_path = torch.stack(joint_positions) + arm_path_fk_validate(eef_name, waypoints, joint_position_path, planner, segment_bounds) + path = ArmPath( + eef_name=eef_name, + waypoints=tuple(waypoints), + joint_positions=joint_position_path, + segment_bounds=segment_bounds, + object_events=tuple(object_events), + object_pose_keyframes=tuple(object_pose_keyframes), + ) + if policy.max_joint_step_rad is None: + return path + return _arm_path_refine( + path, + planner=planner, + datastream=datastream, + max_joint_step_rad=policy.max_joint_step_rad, + ) + + def _demonstration_prepare( + self, + *, + data_generator: DataGenerator, + env_id: int, + eef_name: str, + subtask_index: int, + segment_index: int, + boundaries: dict, + selected_source: dict[str, int | None], + ) -> tuple[WaypointTrajectory, tuple[int, int], int]: + """Select, transform and trim the demonstration for one skill segment. + + Args: + data_generator: Owner of source selection and trajectory transformation. + env_id: Environment whose object poses define the transformed skill. + eef_name: End effector executing the skill. + subtask_index: Subtask containing the demonstrated segment. + segment_index: Position of the demonstration within the subtask. + boundaries: Randomized source subtask boundaries for this attempt. + selected_source: Source indices updated by the generator during selection. + + Returns: + Transformed trajectory, retained source boundaries and selected demo index. + """ + + datastream = data_generator.datastream + subtask = datastream.get_subtasks(eef_name)[subtask_index] + skill_spec = subtask.segments[segment_index] + source_skill = data_generator.generate_eef_subtask_trajectory( + env_id=env_id, + eef_name=eef_name, + subtask_ind=subtask_index, + all_randomized_subtask_boundaries=boundaries, + runtime_subtask_constraints_dict={}, + selected_src_demo_inds=selected_source, + ) + assert len(source_skill), f"source skill {eef_name}.{subtask.name} is empty" + has_observation_prefix = subtask_index == 0 or datastream.get_generation_policy().transform_first_robot_pose + if has_observation_prefix and segment_index: + # A preceding segment replaces the observed-EEF approach seed, not a demonstrated command. + assert len(source_skill) > 1, f"source skill {eef_name}.{subtask.name} has no target commands" + source_skill.pop_first() + source_demo_index = selected_source[eef_name] + assert source_demo_index is not None + selected_boundary = boundaries[eef_name][source_demo_index, subtask_index] + source_skill, source_boundary = self._demonstration_source_window_apply( + data_generator=data_generator, + eef_name=eef_name, + subtask_index=subtask_index, + events=skill_spec.events, + source_demo_index=source_demo_index, + source_boundary=(int(selected_boundary[0]), int(selected_boundary[1])), + source_skill=source_skill, + source_window=skill_spec.demonstration_source_window, + ) + return source_skill, source_boundary, source_demo_index + + @staticmethod + def _motion_goal_prepare( + *, + data_generator: DataGenerator, + env_id: int, + segment_id: SegmentId, + segment_spec: SegmentSpec, + pose_template: torch.Tensor, + passthrough: dict[str, torch.Tensor], + object_effect_poses: Mapping[tuple[SegmentId, str], torch.Tensor] | None = None, + ) -> _PreparedSegmentGoal: + """Resolve a configured tool target in the environment or object frame. + + Args: + data_generator: Generator providing current object poses. + env_id: Environment whose object frames define the target. + segment_id: Segment receiving the target. + segment_spec: Segment declaring the motion goal. + pose_template: Pose tensor supplying the device and numeric type. + passthrough: Hand and other non-pose commands retained at the target. + object_effect_poses: Object poses predicted after earlier segments [m]. + + Returns: + Resolved tool target and any predicted object-pose overrides. + """ + + goal = segment_spec.motion_goal + assert goal is not None and segment_spec.goal_segment_id is None + position = pose_template.new_tensor(goal.position_m) + quaternion = pose_template.new_tensor(goal.rotation_xyzw) + reference_from_tool = pose_math.make_pose(position, pose_math.matrix_from_quat(quaternion)) + env_from_tool = reference_from_tool + object_pose_overrides = {} + if goal.object_ref: + if goal.object_pose_after_segment_id is None: + object_poses = data_generator.datastream.get_object_poses(env_ids=[env_id]) + if goal.object_ref not in object_poses: + raise EpisodeGenerationError( + "motion_goal", + f"motion goal for {segment_id} references unknown object {goal.object_ref!r}", + ) + env_from_object = object_poses[goal.object_ref][0] + else: + effect_key = goal.object_pose_after_segment_id, goal.object_ref + if object_effect_poses is None or effect_key not in object_effect_poses: + raise EpisodeGenerationError( + "task_effect", + f"motion goal for {segment_id} has no terminal object pose from " + f"{goal.object_pose_after_segment_id}", + ) + env_from_object = object_effect_poses[effect_key] + object_pose_overrides[goal.object_ref] = env_from_object + env_from_tool = env_from_object.to(pose_template) @ reference_from_tool + return _PreparedSegmentGoal( + None, + Waypoint(env_from_tool, deepcopy(passthrough)), + MappingProxyType(object_pose_overrides), + ) + + def _segment_build( + self, + request: _SegmentBuildRequest, + ) -> _SegmentPath: + """Build a segment using its configured trajectory source.""" + + builder_by_provider = { + SegmentProvider.MOTION_PLANNER: self._motion_segment_build, + SegmentProvider.DEMONSTRATION: self._demonstration_segment_build, + SegmentProvider.SCRIPTED: self._scripted_segment_build, + } + builder = builder_by_provider.get(request.segment_spec.provider) + if builder is None: + raise EpisodeGenerationError( + "segment_provider", + f"segment provider {request.segment_spec.provider.value!r} is not integrated for {request.segment_id}", + ) + return builder(request) + + def _motion_segment_build( + self, + request: _SegmentBuildRequest, + ) -> _SegmentPath: + """Plan a transit to the configured segment goal.""" + + assert request.goal is not None, f"unresolved segment goal for {request.segment_id}" + assert request.segment_spec.goal_segment_id == request.goal.segment_id + carried_object_pose = None + if request.carried_object is not None: + assert request.previous_waypoints, "a carried-object transit requires a preceding segment" + carried_object_pose = request.carried_object.pose_at_tool(request.previous_waypoints[-1].pose) + waypoints, joint_positions = self._transit_plan( + request.data_generator, + request.planner, + request.env_id, + request.goal.entry_waypoint.pose, + request.passthrough, + request.current_joints, + request.carried_object.object_name if request.carried_object is not None else None, + carried_object_pose, + request.goal.object_pose_overrides, + ) + return _SegmentPath( + waypoints=tuple(waypoints), + joint_positions=tuple(joint_positions), + carried_object=request.carried_object, + ) + + def _demonstration_segment_build( + self, + request: _SegmentBuildRequest, + ) -> _SegmentPath: + """Merge a transformed demonstration and map its object events to path samples. + + Args: + request: Prepared source skill, entry state and attachment geometry. + + Returns: + Skill waypoints, IK joint samples and resolved object events. + """ + + assert request.source_skill is not None + assert request.source_boundary is not None + assert request.source_demo_index is not None + has_execution_predecessor = bool(request.previous_waypoints) + source_length = len(request.source_skill) + merged_skill = request.data_generator.merge_eef_subtask_trajectory( + env_id=request.env_id, + eef_name=request.eef_name, + subtask_index=request.subtask_index, + prev_executed_traj=list(request.previous_waypoints) if has_execution_predecessor else None, + subtask_trajectory=request.source_skill, + force_use_prev_traj=has_execution_predecessor, + ) + if not has_execution_predecessor: + initial_joints = request.current_joints.clone() + initial_pose = request.planner.joint_positions_to_ee_poses(initial_joints.unsqueeze(0))[0] + merged_skill.insert( + 0, + Waypoint( + pose=initial_pose, + passthrough_action=deepcopy(request.passthrough), + noise=0.0, + joint_seed=initial_joints.clone(), + ), + ) + skill_events, object_pose_keyframes = self._skill_events_resolve( + data_generator=request.data_generator, + planner=request.planner, + segment_id=request.segment_id, + events=request.segment_spec.events, + source_demo_index=request.source_demo_index, + source_boundary=request.source_boundary, + source_length=source_length, + merged_skill=merged_skill, + ) + current_joints = request.current_joints + carried_object = request.carried_object + joint_positions: list[torch.Tensor] = [] + for skill_index, waypoint in enumerate(merged_skill): + for event in skill_events.get(skill_index, ()): + carried_object = self._object_event_apply( + request.planner, + request.env_id, + current_joints, + event, + carried_object, + request.object_collision_spheres, + ) + solution = current_joints + if has_execution_predecessor or skill_index: + solution = request.planner.solve_ik_kinematic(waypoint.pose, current_joints) + if solution is None: + raise EpisodeGenerationError( + "inverse_kinematics", + f"IK failed for {request.segment_id} at waypoint {skill_index}/{len(merged_skill)}", + ) + solution = self._joint_positions_match_passthrough( + request.data_generator.datastream, + request.planner, + solution, + waypoint.passthrough_action, + ) + current_joints = solution + joint_positions.append(solution) + for event in skill_events.get(len(merged_skill), ()): + carried_object = self._object_event_apply( + request.planner, + request.env_id, + current_joints, + event, + carried_object, + request.object_collision_spheres, + ) + return _SegmentPath( + waypoints=tuple(merged_skill), + joint_positions=tuple(joint_positions), + carried_object=carried_object, + object_events=tuple(event for slot in sorted(skill_events) for event in skill_events[slot]), + object_pose_keyframes=object_pose_keyframes, + ) + + def _scripted_segment_build(self, request: _SegmentBuildRequest) -> _SegmentPath: + """Build a hold or Cartesian retreat while preserving attachment state. + + Args: + request: Scripted segment, entry state and current hand commands. + + Returns: + Scripted waypoints and joint samples with the existing attachment state. + """ + data_generator, planner = request.data_generator, request.planner + eef_name, segment_spec = request.eef_name, request.segment_spec + current_joints, passthrough = request.current_joints, request.passthrough + + assert segment_spec.provider == SegmentProvider.SCRIPTED + assert segment_spec.kind in {SegmentKind.HOLD, SegmentKind.TRANSIT} + assert segment_spec.duration_steps > 0 + topology_links = set(planner.config.hand_link_names) + task_links = {link_name for contact in segment_spec.robot_contacts for link_name in contact.robot_link_names} + missing_links = task_links - topology_links + assert not missing_links, f"task contact links are outside the planner hand topology: {sorted(missing_links)}" + + assert eef_name in passthrough, f"passthrough actions are missing the {eef_name!r} channel" + target_passthrough = deepcopy(passthrough) + if segment_spec.passthrough_preset: + preset_values = data_generator.datastream.get_eef_passthrough_preset( + eef_name, + segment_spec.passthrough_preset, + ) + preset_joint_names = data_generator.datastream.get_robot_eef_joint_names(eef_name) + assert len(preset_values) == len(preset_joint_names) + configured_auxiliary = planner.config.initial_auxiliary_joint_positions + assert set(configured_auxiliary) <= set(preset_joint_names) + assert set(preset_joint_names) <= set( + planner.joint_positions_to_named_positions(current_joints) + ), "passthrough preset joints must be active planner joints or their mimic followers" + target_passthrough[eef_name] = passthrough[eef_name].new_tensor(preset_values) + assert ( + target_passthrough[eef_name].shape == passthrough[eef_name].shape + ), "release preset must match the incoming passthrough shape" + seed_passthrough = passthrough if segment_spec.kind == SegmentKind.TRANSIT else target_passthrough + seed_joints = self._joint_positions_match_passthrough( + data_generator.datastream, + planner, + current_joints, + seed_passthrough, + ) + start_pose = planner.joint_positions_to_ee_poses(seed_joints.unsqueeze(0))[0] + offset = start_pose.new_tensor(segment_spec.cartesian_offset_m or (0.0, 0.0, 0.0)) + waypoints: list[Waypoint] = [] + joint_positions: list[torch.Tensor] = [] + for step in range(1, segment_spec.duration_steps + 1): + progress = step / segment_spec.duration_steps + step_passthrough = target_passthrough + if segment_spec.kind == SegmentKind.TRANSIT and segment_spec.passthrough_preset: + step_passthrough = deepcopy(target_passthrough) + step_passthrough[eef_name] = torch.lerp( + passthrough[eef_name], + target_passthrough[eef_name], + progress, + ) + target_pose = start_pose.clone() + target_pose[:3, 3] += offset * progress + solution = seed_joints + if segment_spec.kind == SegmentKind.TRANSIT: + ik_seed = self._joint_positions_match_passthrough( + data_generator.datastream, + planner, + seed_joints, + step_passthrough, + ) + solution = planner.solve_ik_kinematic(target_pose, ik_seed) + if solution is None: + raise EpisodeGenerationError( + "inverse_kinematics", + f"IK failed for scripted segment {segment_spec.name!r} at " + f"waypoint {step - 1}/{segment_spec.duration_steps}", + ) + solution = self._joint_positions_match_passthrough( + data_generator.datastream, + planner, + solution, + step_passthrough, + ) + seed_joints = solution + waypoints.append( + Waypoint( + pose=target_pose, + passthrough_action=deepcopy(step_passthrough), + noise=0.0, + joint_seed=solution.clone(), + ) + ) + joint_positions.append(solution.clone()) + return _SegmentPath(tuple(waypoints), tuple(joint_positions), request.carried_object) + + def _demonstration_source_window_apply( + self, + *, + data_generator: DataGenerator, + eef_name: str, + subtask_index: int, + events: tuple[SegmentEventSpec, ...], + source_demo_index: int, + source_boundary: tuple[int, int], + source_skill: WaypointTrajectory, + source_window: DemonstrationSourceWindowSpec | None, + ) -> tuple[WaypointTrajectory, tuple[int, int]]: + """Trim a demonstration after its annotated event and configured trailing samples. + + Args: + data_generator: Generator providing source annotations. + eef_name: End effector owning the skill. + subtask_index: Subtask containing the skill. + events: Object events declared for this segment. + source_demo_index: Selected source episode index. + source_boundary: Original half-open action bounds in the source episode. + source_skill: Transformed source waypoints, including any observed-pose prefix. + source_window: Optional event-anchored window to retain. + + Returns: + Retained waypoints and their half-open source action bounds. + """ + + if source_window is None: + return source_skill, source_boundary + boundary_start, boundary_end = source_boundary + source_prefix = len(source_skill) - (boundary_end - boundary_start) + assert source_prefix in (0, 1), "source skill may only prepend its recorded EEF pose" + anchors = tuple( + event + for event in events + if event.point == SegmentEventPoint.SOURCE_ANNOTATION + and event.annotation_key == source_window.anchor_annotation_key + ) + assert len(anchors) == 1, "source-window anchor must match exactly one segment event" + pool = data_generator.src_demo_datagen_info_pool + demo_key = pool.demo_keys[source_demo_index] + + def sample_index_resolve(event: SegmentEventSpec) -> int: + """Resolve a source sample and classify annotation failures as source-window errors.""" + + try: + return pool.get_object_event_index(source_demo_index, event.annotation_key) + except Exception as error: + raise EpisodeGenerationError( + "source_window", + f"source annotation {event.annotation_key!r} query failed for {demo_key!r}: " + f"{type(error).__name__}: {error}", + ) from error + + anchor_sample = sample_index_resolve(anchors[0]) + effective_end = anchor_sample + 1 + source_window.post_event_sample_count + if not boundary_start < effective_end <= boundary_end: + raise EpisodeGenerationError( + "source_window", + f"{eef_name} subtask {subtask_index} source window [{boundary_start}, {effective_end}) " + f"must be a non-empty subset of [{boundary_start}, {boundary_end})", + ) + for event in events: + if event.point != SegmentEventPoint.SOURCE_ANNOTATION: + continue + sample = sample_index_resolve(event) + if not boundary_start <= sample < effective_end: + raise EpisodeGenerationError( + "source_window", + f"source event {event.annotation_key!r} sample {sample} is outside retained " + f"boundaries [{boundary_start}, {effective_end})", + ) + + retained_length = source_prefix + effective_end - boundary_start + assert 0 < retained_length <= len(source_skill), "source window cannot expand its demonstration" + retained = WaypointTrajectory() + retained.add_waypoint_sequence( + WaypointSequence(sequence=[source_skill[index] for index in range(retained_length)]) + ) + return retained, (boundary_start, effective_end) + + def _object_event_apply( + self, + planner: CuroboPlanner, + env_id: int, + current_joints: torch.Tensor, + event: PathObjectEvent, + carried_object: _CarriedObject | None, + object_collision_spheres: dict[str, ObjectCollisionSpheres], + ) -> _CarriedObject | None: + """Update attachment state and reuse the object's fitted collision spheres. + + Args: + planner: Arm planner whose attachment model is updated. + env_id: Environment containing the object geometry. + current_joints: Arm-local joint positions at the event [rad, m]. + event: Attach or detach event at this path boundary. + carried_object: Object carried before the event, or None. + object_collision_spheres: Episode geometry cache, updated on attachment. + + Returns: + Carried-object state after the event, or None after release. + """ + + updated_carried_object = _carried_object_apply(carried_object, event) + if event.spec.event_type == SegmentEventType.ATTACH: + assert event.tool_from_object is not None + object_ref = event.spec.object_ref + episode_geometry = object_collision_spheres.get(object_ref) + runtime_geometry = self._object_geometry_cache.get(object_ref) + if episode_geometry is not None and runtime_geometry is not None: + assert episode_geometry is runtime_geometry, f"episode geometry changed for {object_ref!r}" + cached_geometry = episode_geometry or runtime_geometry + try: + try: + geometry = planner.object_collision_spheres_fit( + object_ref, + env_id, + current_joints, + event.tool_from_object, + cached_geometry, + ) + finally: + planner.update_world() + except Exception as error: + raise EpisodeGenerationError( + "object_sphere_fit", + f"failed to bind attachment geometry for {object_ref!r}: {type(error).__name__}: {error}", + ) from error + if cached_geometry is not None and geometry is not cached_geometry: + raise EpisodeGenerationError( + "object_sphere_fit", + f"attachment geometry changed for {object_ref!r}", + ) + episode_geometry = object_collision_spheres.setdefault(object_ref, geometry) + runtime_geometry = self._object_geometry_cache.setdefault(object_ref, geometry) + if episode_geometry is not geometry or runtime_geometry is not geometry: + raise EpisodeGenerationError("object_sphere_fit", f"attachment geometry changed for {object_ref!r}") + return updated_carried_object + + def _skill_events_resolve( + self, + *, + data_generator: DataGenerator, + planner: CuroboPlanner, + segment_id: SegmentId, + events: tuple[SegmentEventSpec, ...], + source_demo_index: int, + source_boundary: tuple[int, int], + source_length: int, + merged_skill: Sequence[Waypoint], + ) -> tuple[dict[int, list[PathObjectEvent]], tuple[PathObjectPose, ...]]: + """Map source object events and poses to boundaries in the generated skill. + + Args: + data_generator: Owner of the source demonstrations and object-relative transforms. + planner: Arm model providing the attachment frame and target tool poses. + segment_id: Segment receiving the resolved events and keyframes. + events: Attach/detach events declared for this segment. + source_demo_index: Selected source demonstration index. + source_boundary: Half-open action bounds in the source demonstration. + source_length: Skill length before merge, including any prepended recorded tool pose. + merged_skill: Generated skill after entry interpolation and trajectory merging. + + Returns: + Events grouped by local pre-command boundary and environment-relative object poses. + Recorded post-command poses map to the following boundary; a segment-end event uses + the terminal boundary after its last command. + """ + + if not events: + return {}, () + pool = data_generator.src_demo_datagen_info_pool + assert len(pool.demo_keys) == len(pool.datagen_infos), "source demo keys and episodes are misaligned" + source_episode = pool.datagen_infos[source_demo_index] + boundary_start, boundary_end = source_boundary + source_prefix = source_length - (boundary_end - boundary_start) + assert source_prefix in (0, 1), "source skill may only prepend its recorded EEF pose" + merged_length = len(merged_skill) + interpolation_prefix = merged_length - source_length + assert interpolation_prefix >= 0, "merged skill cannot be shorter than its source" + + eef_name = segment_id.eef_name + resolved: dict[int, list[PathObjectEvent]] = {} + for event in events: + if event.point == SegmentEventPoint.START: + source_sample_index = boundary_start + skill_slot = 0 + elif event.point == SegmentEventPoint.END: + source_sample_index = boundary_end + skill_slot = merged_length + else: + assert event.point == SegmentEventPoint.SOURCE_ANNOTATION + source_sample_index = pool.get_object_event_index(source_demo_index, event.annotation_key) + if not boundary_start <= source_sample_index <= boundary_end: + raise EpisodeGenerationError( + "source_event", + f"source event {event.annotation_key!r} sample {source_sample_index} is outside " + f"segment {segment_id} state boundaries [{boundary_start}, {boundary_end}] for command slice " + f"[{boundary_start}, {boundary_end})", + ) + skill_slot = interpolation_prefix + source_prefix + source_sample_index - boundary_start + + tool_from_object = None + if event.event_type == SegmentEventType.ATTACH: + tool_link_name = planner.config.ee_link_name + assert tool_link_name is not None, "native SkillGen planners require a physical tool link" + assert ( + event.attachment_frame == tool_link_name + ), f"attachment frame {event.attachment_frame!r} does not match planner tool {tool_link_name!r}" + assert source_episode.target_eef_pose is not None and eef_name in source_episode.target_eef_pose + assert source_episode.object_poses is not None and event.object_ref in source_episode.object_poses + source_tool_poses = source_episode.target_eef_pose[eef_name] + source_object_poses = source_episode.object_poses[event.object_ref] + source_tool_sample_index = source_sample_index - 1 + if not ( + 0 <= source_tool_sample_index < len(source_tool_poses) + and 0 <= source_sample_index < len(source_object_poses) + ): + raise EpisodeGenerationError( + "source_event", + f"attach event {event.annotation_key or event.point.value!r} boundary sample " + f"{source_sample_index} requires preceding tool command {source_tool_sample_index} and " + "a matching object state", + ) + source_tool_pose = source_tool_poses[source_tool_sample_index] + source_object_pose = source_object_poses[source_sample_index] + tool_from_object = torch.linalg.solve(source_tool_pose, source_object_pose).clone() + + assert 0 <= skill_slot <= merged_length, "event slot must lie on the skill path boundary" + resolved.setdefault(skill_slot, []).append( + PathObjectEvent( + segment_id=segment_id, + local_boundary_index=skill_slot, + spec=event, + tool_from_object=tool_from_object, + ) + ) + + assert source_episode.target_eef_pose is not None and eef_name in source_episode.target_eef_pose + assert source_episode.object_poses is not None + source_tool_poses = source_episode.target_eef_pose[eef_name] + source_target_slot = interpolation_prefix + source_prefix + assert 0 <= boundary_start < len(source_tool_poses) + assert source_target_slot < merged_length + generated_target = merged_skill[source_target_slot].pose + source_target = source_tool_poses[boundary_start].to( + device=generated_target.device, dtype=generated_target.dtype + ) + source_to_generated = generated_target @ torch.linalg.inv(source_target) + + object_refs = tuple(dict.fromkeys(event.object_ref for event in events)) + source_object_poses = {} + for object_ref in object_refs: + assert object_ref in source_episode.object_poses, f"source episode has no object {object_ref!r}" + source_object_poses[object_ref] = source_episode.object_poses[object_ref] + assert boundary_start < len(source_object_poses[object_ref]) + last_sample = min(boundary_end, *(len(poses) - 1 for poses in source_object_poses.values())) + object_poses = tuple( + PathObjectPose( + segment_id=segment_id, + local_boundary_index=interpolation_prefix + source_prefix + sample_index - boundary_start, + object_ref=object_ref, + env_from_object=source_to_generated + @ source_object_poses[object_ref][sample_index].to( + device=generated_target.device, dtype=generated_target.dtype + ), + ) + for sample_index in range(boundary_start, last_sample + 1) + for object_ref in object_refs + ) + return resolved, object_poses + + def _transit_plan( + self, + data_generator: DataGenerator, + planner: CuroboPlanner, + env_id: int, + target_pose: torch.Tensor, + passthrough: dict[str, torch.Tensor], + start_joints: torch.Tensor, + carried_object: str | None, + carried_object_pose: torch.Tensor | None, + object_pose_overrides: Mapping[str, torch.Tensor] | None = None, + ) -> tuple[list[Waypoint], list[torch.Tensor]]: + """Plan a transit with object-pose overrides without moving simulator objects. + + Args: + data_generator: Owner of the embodiment's passthrough-action conversion. + planner: Arm planner used to build and retrieve the transit. + env_id: Environment supplying the static planning world. + target_pose: Environment-relative tool transform with shape ``(4, 4)`` [m]. + passthrough: Auxiliary commands held along the transit. + start_joints: Initial configuration in the planner's active joint order [rad, m]. + carried_object: Logical object attached to the tool, or ``None``. + carried_object_pose: Virtual environment-relative pose of the carried object [m]. + object_pose_overrides: Additional virtual object transforms in the environment frame [m]. + + Returns: + Aligned controller waypoints and planner-ordered joint configurations. + + Raises: + EpisodeGenerationError: The planner cannot find a transit. + """ + + virtual_poses = dict(object_pose_overrides or {}) + if carried_object is not None: + assert carried_object_pose is not None, "a carried object requires its virtual pose" + virtual_poses[carried_object] = carried_object_pose + succeeded = planner.update_world_and_plan_motion( + target_pose=target_pose, + expected_attached_object=carried_object, + env_id=env_id, + step_size=planner.step_size, + enable_retiming=planner.step_size is not None, + start_joint_positions=start_joints, + force_object_attachment=carried_object is not None, + retreat_distance=planner.config.retreat_distance if carried_object is not None else 0.0, + object_pose_overrides=virtual_poses, + ) + if not succeeded: + raise EpisodeGenerationError( + "motion_planning", f"transit planning failed for {planner.config.planning_group_name}" + ) + poses = planner.get_planned_poses() + joint_trajectory = planner.get_planned_joint_trajectory() + assert joint_trajectory is not None and poses, "planner must expose both pose and named joint paths" + assert joint_trajectory.joint_names == planner.active_joint_names, "planner joint path order is inconsistent" + positions = joint_trajectory.positions + assert len(poses) == len(positions), "planner path outputs are inconsistent" + transit: list[Waypoint] = [] + transit_positions: list[torch.Tensor] = [] + for pose, position in zip(poses, positions, strict=True): + transit_passthrough = deepcopy(passthrough) + transit_position = self._joint_positions_match_passthrough( + data_generator.datastream, + planner, + position, + transit_passthrough, + ) + transit.append( + Waypoint( + pose=pose, + passthrough_action=transit_passthrough, + noise=planner.config.motion_noise_scale, + ) + ) + transit_positions.append(transit_position) + return transit, transit_positions + + @staticmethod + def _joint_positions_match_passthrough( + datastream: Datastream, + planner: CuroboPlanner, + joint_positions: torch.Tensor, + passthrough: dict[str, torch.Tensor], + ) -> torch.Tensor: + """Make scheduler geometry match joints commanded outside the pose controller.""" + + result = joint_positions.clone() + active_index = {name: index for index, name in enumerate(planner.active_joint_names)} + for name, value in datastream.passthrough_actions_to_joint_positions(passthrough).items(): + if name not in active_index: + continue + assert isinstance(value, torch.Tensor) and value.numel() == 1 + result[active_index[name]] = value.reshape(()).to(device=result.device, dtype=result.dtype) + return result + + +def _carried_object_apply( + carried_object: _CarriedObject | None, + event: PathObjectEvent, +) -> _CarriedObject | None: + """Update which object the arm carries after an attach or detach event.""" + + if event.spec.event_type == SegmentEventType.ATTACH: + assert ( + carried_object is None + ), f"cannot attach {event.spec.object_ref!r} while carrying {carried_object.object_name!r}" + assert event.tool_from_object is not None, "attach event requires an object-to-tool transform" + return _CarriedObject(event.spec.object_ref, event.tool_from_object) + assert event.spec.event_type == SegmentEventType.DETACH + assert ( + carried_object is not None and carried_object.object_name == event.spec.object_ref + ), f"cannot detach uncarried object {event.spec.object_ref!r}" + return None + + +def _initial_auxiliary_joint_positions_apply( + planner: CuroboPlanner, + joint_positions: torch.Tensor, +) -> torch.Tensor: + """Apply the group's declared first-transit state without changing serial-arm joints.""" + + configured = planner.config.initial_auxiliary_joint_positions + if not configured: + return joint_positions + active_index = {name: index for index, name in enumerate(planner.active_joint_names)} + unknown = set(configured) - set(active_index) + assert not unknown, f"initial auxiliary joints are absent from planner state: {sorted(unknown)}" + result = joint_positions.clone() + for name, value in configured.items(): + result[active_index[name]] = value + return result + + +def _source_candidate_diagnostics( + data_generator: DataGenerator, + attempted: Sequence[int], + rejections: Sequence[tuple[int, EpisodeGenerationError]], +) -> tuple[tuple[str, str], ...]: + """Summarize source candidates and their path-building failures.""" + + demo_keys = data_generator.src_demo_datagen_info_pool.demo_keys + diagnostics = (("source_candidates_tried", ",".join(demo_keys[index] for index in attempted)),) + if not rejections: + return diagnostics + return diagnostics + ( + ( + "source_candidate_rejections", + ";".join(f"{demo_keys[index]}:{failure.stage}:{failure}" for index, failure in rejections), + ), + ) + + +def _passthrough_transitions_smooth( + waypoints: list[Waypoint], + eef_name: str, + *, + delay_steps: int, + interpolation_steps: int, + change_threshold: float = 0.5, +) -> None: + """Delay and interpolate abrupt passthrough-action changes in place. + + Args: + waypoints: Path whose selected passthrough channel is updated without adding samples. + eef_name: Passthrough channel to smooth. + delay_steps: Samples to retain the previous value after a detected change. + interpolation_steps: Samples over which to interpolate to the new value. + change_threshold: Maximum component change allowed without smoothing, in channel units. + """ + + if len(waypoints) < 2 or (delay_steps == 0 and interpolation_steps == 0): + return + values = torch.stack([waypoint.passthrough_action[eef_name] for waypoint in waypoints]) + smoothed = values.clone() + index = 1 + while index < len(values): + if float((values[index] - values[index - 1]).abs().max()) <= change_threshold: + index += 1 + continue + previous, target = values[index - 1], values[index] + delay_end = min(index + delay_steps, len(values)) + smoothed[index:delay_end] = previous + interpolation_end = min(delay_end + interpolation_steps, len(values)) + count = interpolation_end - delay_end + if count: + alpha = torch.arange(1, count + 1, device=values.device, dtype=values.dtype) / count + smoothed[delay_end:interpolation_end] = torch.lerp(previous, target, alpha[:, None]) + index = max(interpolation_end, index + 1) + for waypoint, value in zip(waypoints, smoothed, strict=True): + waypoint.passthrough_action[eef_name] = value + + +def _rigid_poses_interpolate(first: torch.Tensor, second: torch.Tensor, steps: int) -> tuple[torch.Tensor, ...]: + """Interpolate poses strictly between the endpoints using quaternion slerp. + + Args: + first: Initial rigid transform with shape ``(4, 4)`` [m]. + second: Final rigid transform in the same reference frame [m]. + steps: Number of equal intervals between endpoints; must exceed one. + + Returns: + The ``steps - 1`` interior poses, excluding both endpoints, on the first pose's device. + """ + + assert steps > 1 and first.shape == second.shape == (4, 4) + second = second.to(device=first.device, dtype=first.dtype) + alpha = torch.arange(1, steps, device=first.device, dtype=first.dtype) / steps + positions = first[:3, 3] + alpha[:, None] * (second[:3, 3] - first[:3, 3]) + first_quaternion = pose_math.quat_from_matrix(first[:3, :3]) + second_quaternion = pose_math.quat_from_matrix(second[:3, :3]) + dot = torch.dot(first_quaternion, second_quaternion) + if dot < 0.0: + second_quaternion = -second_quaternion + dot = -dot + dot = torch.clamp(dot, -1.0, 1.0) + if dot > 0.9995: + quaternions = first_quaternion + alpha[:, None] * (second_quaternion - first_quaternion) + else: + angle = torch.acos(dot) + quaternions = ( + torch.sin((1.0 - alpha) * angle)[:, None] * first_quaternion + + torch.sin(alpha * angle)[:, None] * second_quaternion + ) / torch.sin(angle) + quaternions = quaternions / torch.linalg.vector_norm(quaternions, dim=-1, keepdim=True) + return tuple(pose_math.make_pose(positions, pose_math.matrix_from_quat(quaternions)).unbind()) + + +def _arm_path_refine( + path: ArmPath, + *, + planner: CuroboPlanner, + datastream: Datastream, + max_joint_step_rad: float, +) -> ArmPath: + """Insert FK-derived waypoints to bound joint steps while preserving segment events. + + Args: + path: Complete arm path in the planner's active joint order. + planner: Model providing tool FK for inserted joint configurations. + datastream: Embodiment interface mapping inserted joints to passthrough commands. + max_joint_step_rad: Maximum component change between consecutive joint samples [rad]. + + Returns: + Refined path with remapped segment bounds, object events and pose keyframes. Existing + waypoints are retained; only adjacent object keyframes gain interpolated interior poses. + """ + + assert math.isfinite(max_joint_step_rad) and max_joint_step_rad > 0.0 + if len(path.waypoints) == 1: + return path + + ordered_segments = tuple(sorted(path.segment_bounds.items(), key=lambda item: item[1][0])) + positions: list[torch.Tensor] = [] + source_waypoints: list[Waypoint | None] = [] + passthrough_templates: list[dict[str, torch.Tensor] | None] = [] + segment_bounds: dict[SegmentId, tuple[int, int]] = {} + boundary_maps: dict[SegmentId, tuple[int, ...]] = {} + + for segment_id, (start, end) in ordered_segments: + refined_start = len(positions) + boundary_map = [0] * (end - start + 1) + for waypoint_index in range(start, end): + local_index = waypoint_index - start + target_positions = path.joint_positions[waypoint_index] + if waypoint_index == 0: + subdivisions = 1 + else: + previous_positions = path.joint_positions[waypoint_index - 1] + maximum_delta = float(torch.max(torch.abs(target_positions - previous_positions)).item()) + subdivision_ratio = maximum_delta / max_joint_step_rad + rounded_ratio = round(subdivision_ratio) + subdivisions = max( + 1, + ( + rounded_ratio + if math.isclose(subdivision_ratio, rounded_ratio, rel_tol=1.0e-6, abs_tol=1.0e-6) + else math.ceil(subdivision_ratio) + ), + ) + + boundary_map[local_index] = len(positions) - refined_start + for subdivision in range(1, subdivisions + 1): + is_original = subdivision == subdivisions + if is_original: + positions.append(target_positions.clone()) + source_waypoints.append(path.waypoints[waypoint_index]) + passthrough_templates.append(None) + continue + alpha = subdivision / subdivisions + positions.append(torch.lerp(previous_positions, target_positions, alpha)) + source_waypoints.append(None) + passthrough_templates.append(path.waypoints[waypoint_index - 1].passthrough_action) + segment_bounds[segment_id] = refined_start, len(positions) + boundary_map[-1] = len(positions) - refined_start + boundary_maps[segment_id] = tuple(boundary_map) + + inserted_indices = [index for index, waypoint in enumerate(source_waypoints) if waypoint is None] + if not inserted_indices: + return path + joint_positions = torch.stack(positions) + inserted_poses = planner.joint_positions_to_ee_poses(joint_positions[inserted_indices]) + pose_by_index = dict(zip(inserted_indices, inserted_poses, strict=True)) + + waypoints: list[Waypoint] = [] + for index, (position, source_waypoint, passthrough_template) in enumerate( + zip(positions, source_waypoints, passthrough_templates, strict=True) + ): + if source_waypoint is not None: + waypoints.append(source_waypoint) + continue + assert passthrough_template is not None + named_positions = planner.joint_positions_to_named_positions(position) + passthrough = datastream.joint_positions_to_passthrough_actions(named_positions, passthrough_template) + waypoints.append( + Waypoint( + pose=pose_by_index[index], + passthrough_action=passthrough, + noise=0.0, + joint_seed=position.clone(), + ) + ) + + maximum_refined_delta = float(torch.max(torch.abs(joint_positions[1:] - joint_positions[:-1])).item()) + assert ( + maximum_refined_delta <= max_joint_step_rad + 1.0e-6 + ), f"refined joint step {maximum_refined_delta} exceeds {max_joint_step_rad}" + object_events = tuple( + replace( + event, + local_boundary_index=( + 0 + if event.spec.point == SegmentEventPoint.START + else boundary_maps[event.segment_id][event.local_boundary_index] + ), + ) + for event in path.object_events + ) + object_pose_keyframes = [ + replace( + keyframe, + local_boundary_index=boundary_maps[keyframe.segment_id][keyframe.local_boundary_index], + ) + for keyframe in path.object_pose_keyframes + ] + grouped_keyframes: dict[tuple[SegmentId, str], list[PathObjectPose]] = {} + for keyframe in path.object_pose_keyframes: + grouped_keyframes.setdefault((keyframe.segment_id, keyframe.object_ref), []).append(keyframe) + for keyframes in grouped_keyframes.values(): + for first, second in zip(keyframes, keyframes[1:], strict=False): + if second.local_boundary_index != first.local_boundary_index + 1: + continue + first_boundary = boundary_maps[first.segment_id][first.local_boundary_index] + second_boundary = boundary_maps[second.segment_id][second.local_boundary_index] + if second_boundary - first_boundary <= 1: + continue + for offset, pose in enumerate( + _rigid_poses_interpolate( + first.env_from_object, second.env_from_object, second_boundary - first_boundary + ), + start=1, + ): + object_pose_keyframes.append( + replace(second, local_boundary_index=first_boundary + offset, env_from_object=pose) + ) + segment_order = {segment_id: index for index, segment_id in enumerate(segment_bounds)} + object_pose_keyframes.sort( + key=lambda keyframe: ( + segment_order[keyframe.segment_id], + keyframe.local_boundary_index, + keyframe.object_ref, + ) + ) + return ArmPath( + eef_name=path.eef_name, + waypoints=tuple(waypoints), + joint_positions=joint_positions, + segment_bounds=segment_bounds, + object_events=object_events, + object_pose_keyframes=tuple(object_pose_keyframes), + ) diff --git a/autodata_core/schedulegen/scheduling.py b/autodata_core/schedulegen/scheduling.py new file mode 100644 index 0000000..4d95c2c --- /dev/null +++ b/autodata_core/schedulegen/scheduling.py @@ -0,0 +1,640 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Schedule arm paths and map their events and contact rules to execution ticks.""" + +from __future__ import annotations + +import torch +from collections.abc import Mapping + +from autodata_core.schedulegen.types import ( + ArmPath, + ArmWaypointConflict, + ObjectStateSample, + ScheduledObjectEvent, + ScheduledObjectPose, + ScheduledRobotContact, + ScheduledWorldContact, +) +from autodata_core.scheduling import ( + Schedule, + ScheduleFailure, + SchedulePath, + SegmentWaypoint, + WaypointConflict, + schedule_paths, +) +from autodata_interfaces.tasks.schedule_constraint_spec import ( + NonOverlapConstraintSpec, + NonPreemptiveConstraintSpec, + PrecedenceConstraintSpec, + SchedulerStrategy, + ScheduleSpec, + SegmentId, +) +from autodata_interfaces.tasks.segment_spec import SegmentEventType, SegmentRobotContactSpec, SegmentWorldContactSpec + + +def _contact_interval(path: ArmPath, schedule: Schedule, segment_id: SegmentId) -> tuple[int, int]: + """Include held lane occupancy, including the terminal boundary, in contact permissions.""" + + # Contact permission follows lane occupancy, including waits and the terminal hold. + held_indices = (*get_scheduled_path_indices(path, schedule), len(path.waypoints) - 1) + start, stop = path.segment_bounds[segment_id] + active_ticks = tuple(tick for tick, index in enumerate(held_indices) if start <= index < stop) + assert active_ticks and active_ticks == tuple( + range(active_ticks[0], active_ticks[-1] + 1) + ), f"contact segment {segment_id} must own one contiguous scheduled interval" + return active_ticks[0], active_ticks[-1] + 1 + + +def schedule_world_contacts( + arm_paths: Mapping[str, ArmPath], + schedule: Schedule, + contacts_by_segment: Mapping[SegmentId, tuple[SegmentWorldContactSpec, ...]], +) -> tuple[ScheduledWorldContact, ...]: + """Map object/fixture permissions to their segment's held execution interval. + + Args: + arm_paths: Complete paths keyed by end effector. + schedule: Execution ticks for every segment waypoint. + contacts_by_segment: Task-defined object/fixture permissions. + + Returns: + Permissions sorted by start tick, segment and object/fixture pair. + """ + + path_by_segment = {segment_id: path for path in arm_paths.values() for segment_id in path.segment_bounds} + missing = set(contacts_by_segment) - set(path_by_segment) + assert not missing, f"world contacts reference segments without paths: {sorted(map(str, missing))}" + scheduled = [] + for segment_id, specs in contacts_by_segment.items(): + # Fixture contact stays permitted while this segment's last command is held. + start_tick, stop_tick = _contact_interval(path_by_segment[segment_id], schedule, segment_id) + scheduled.extend(ScheduledWorldContact(segment_id, spec, start_tick, stop_tick) for spec in specs) + return tuple( + sorted( + scheduled, + key=lambda contact: ( + contact.start_tick, + str(contact.segment_id), + contact.spec.object_ref, + contact.spec.fixture_ref, + ), + ) + ) + + +def schedule_robot_contacts( + arm_paths: Mapping[str, ArmPath], + schedule: Schedule, + contacts_by_segment: Mapping[SegmentId, tuple[SegmentRobotContactSpec, ...]], + scheduled_object_events: tuple[ScheduledObjectEvent, ...], + *, + attachment_link_names: Mapping[str, tuple[str, ...]] | None = None, +) -> tuple[ScheduledRobotContact, ...]: + """Map robot/object permissions through lane timing and optional release annotations. + + Args: + arm_paths: Complete paths keyed by end effector. + schedule: Execution ticks for every segment waypoint. + contacts_by_segment: Task-defined robot/object permissions. + scheduled_object_events: Resolved attach/detach events used by release permissions. + attachment_link_names: Hand/tool collision links per lane. When provided, these links + may contact an object from its grasp segment through its detach event. + + Returns: + Permissions sorted by start tick, segment, object and robot links. + """ + + path_by_segment = {segment_id: path for path in arm_paths.values() for segment_id in path.segment_bounds} + missing = set(contacts_by_segment) - set(path_by_segment) + assert not missing, f"robot contacts reference segments without paths: {sorted(map(str, missing))}" + scheduled = [] + for segment_id, specs in contacts_by_segment.items(): + first_tick, last_tick = _contact_interval(path_by_segment[segment_id], schedule, segment_id) + for spec in specs: + start_tick = first_tick + if spec.start_annotation_key: + # A release permission begins at the annotated detach, not at segment entry. + matching_events = tuple( + event + for event in scheduled_object_events + if event.path_event.segment_id == segment_id + and event.path_event.spec.annotation_key == spec.start_annotation_key + and event.path_event.spec.object_ref == spec.object_ref + ) + assert len(matching_events) == 1, ( + f"robot contact on {segment_id} must resolve exactly one event " + f"{spec.start_annotation_key!r} for {spec.object_ref!r}" + ) + assert ( + matching_events[0].path_event.spec.event_type == SegmentEventType.DETACH + ), "release contact must begin at a detach annotation" + start_tick = matching_events[0].tick + stop_tick = schedule.ticks_for(segment_id)[-1] if spec.clear_at_end else last_tick + assert ( + first_tick <= start_tick < stop_tick + ), f"robot contact on {segment_id} begins outside segment ownership" + scheduled.append(ScheduledRobotContact(segment_id, spec, start_tick, stop_tick)) + # Grasping/carrying permits the owning hand, never the other arm or the robot body. + for index, event in enumerate(scheduled_object_events): + if attachment_link_names is None or event.path_event.spec.event_type != SegmentEventType.ATTACH: + continue + segment_id = event.path_event.segment_id + object_ref = event.path_event.spec.object_ref + start_tick, _ = _contact_interval(path_by_segment[segment_id], schedule, segment_id) + stop_tick = next( + ( + later.tick + for later in scheduled_object_events[index + 1 :] + if later.path_event.spec.object_ref == object_ref + and later.path_event.spec.event_type == SegmentEventType.DETACH + ), + schedule.makespan_ticks + 1, + ) + links = tuple(sorted(attachment_link_names[segment_id.eef_name])) + if not links: + continue + scheduled.append( + ScheduledRobotContact(segment_id, SegmentRobotContactSpec(object_ref, links), start_tick, stop_tick) + ) + return tuple( + sorted( + scheduled, + key=lambda contact: ( + contact.start_tick, + str(contact.segment_id), + contact.spec.object_ref, + contact.spec.robot_link_names, + ), + ) + ) + + +def schedule_arm_paths( + arm_paths: Mapping[str, ArmPath], + arm_conflicts: tuple[ArmWaypointConflict, ...], + schedule_spec: ScheduleSpec, + *, + segment_resource_ids: Mapping[SegmentId, tuple[str, ...]] | None = None, + serialize_segments: bool = False, +) -> Schedule | ScheduleFailure: + """Schedule complete arm paths after every segment has been built. + + Segment provider details do not cross this boundary. Each arm path is split by its + declared bounds, path-global collision indices are localized to those segments, and + task-defined constraints are passed to the native scheduler unchanged. + + Args: + arm_paths: Complete unscheduled paths keyed by end-effector lane. + arm_conflicts: Cross-arm conflicts in complete-path waypoint coordinates. + schedule_spec: Native scheduling policy and task constraints. + segment_resource_ids: Additional task-local resource claims keyed by exact segment. + serialize_segments: Whether all cross-lane segment intervals must be disjoint. + + Returns: + A validated schedule, or a scheduling failure with no executable result. + """ + + assert isinstance(arm_paths, Mapping) and arm_paths, "arm_paths must be a non-empty mapping" + assert all( + isinstance(eef_name, str) and isinstance(path, ArmPath) for eef_name, path in arm_paths.items() + ), "arm_paths must map end-effector names to ArmPath values" + assert all( + eef_name == path.eef_name for eef_name, path in arm_paths.items() + ), "each arm_paths key must match its ArmPath.eef_name" + assert isinstance(arm_conflicts, tuple) and all( + isinstance(item, ArmWaypointConflict) for item in arm_conflicts + ), "arm_conflicts must contain ArmWaypointConflict values" + assert isinstance(schedule_spec, ScheduleSpec), "schedule_spec must be a ScheduleSpec" + assert segment_resource_ids is None or isinstance( + segment_resource_ids, Mapping + ), "segment_resource_ids must be a mapping" + assert isinstance(serialize_segments, bool), "serialize_segments must be a bool" + resource_ids_by_segment = {} if segment_resource_ids is None else dict(segment_resource_ids) + assert all( + isinstance(segment_id, SegmentId) and isinstance(resource_ids, tuple) + for segment_id, resource_ids in resource_ids_by_segment.items() + ), "segment_resource_ids must map SegmentId values to tuples" + assert schedule_spec.strategy in { + SchedulerStrategy.WAYPOINT_RETIMING, + SchedulerStrategy.BLOCK_SCHEDULING, + }, f"unsupported scheduling strategy: {schedule_spec.strategy}" + ordered_arm_paths = tuple(path for _, path in sorted(arm_paths.items())) + arm_path_by_eef = {path.eef_name: path for path in ordered_arm_paths} + assert len(arm_path_by_eef) == len(ordered_arm_paths), "arm paths must use distinct end-effector lanes" + + # Convert each provider's complete path into scheduler segments without copying geometry. + bounds_by_eef: dict[str, tuple[tuple[SegmentId, tuple[int, int]], ...]] = {} + scheduler_paths: list[SchedulePath] = [] + built_segment_ids: set[SegmentId] = set() + for arm_path in ordered_arm_paths: + bounds = tuple(sorted(arm_path.segment_bounds.items(), key=lambda item: (item[1][0], item[0]))) + bounds_by_eef[arm_path.eef_name] = bounds + built_segment_ids.update(segment_id for segment_id, _ in bounds) + scheduler_paths.extend( + SchedulePath( + segment_id=segment_id, + lane=arm_path.eef_name, + waypoint_count=end - start, + resource_ids=resource_ids_by_segment.get(segment_id, ()), + ) + for segment_id, (start, end) in bounds + ) + unknown_resource_segments = set(resource_ids_by_segment) - built_segment_ids + assert ( + not unknown_resource_segments + ), f"segment_resource_ids references segments without paths: {sorted(map(str, unknown_resource_segments))}" + + # Collision detection indexes complete arm paths; the scheduler indexes segment-local waypoints. + scheduler_conflicts: list[WaypointConflict] = [] + for conflict in sorted(arm_conflicts): + first = _waypoint_localize( + arm_path_by_eef, + bounds_by_eef, + eef_name=conflict.first_eef_name, + waypoint_index=conflict.first_waypoint_index, + ) + second = _waypoint_localize( + arm_path_by_eef, + bounds_by_eef, + eef_name=conflict.second_eef_name, + waypoint_index=conflict.second_waypoint_index, + ) + scheduler_conflicts.append(WaypointConflict(first, second)) + + return schedule_paths( + tuple(scheduler_paths), + conflicts=tuple(scheduler_conflicts), + precedence=tuple( + constraint for constraint in schedule_spec.constraints if isinstance(constraint, PrecedenceConstraintSpec) + ), + non_overlap=tuple( + constraint for constraint in schedule_spec.constraints if isinstance(constraint, NonOverlapConstraintSpec) + ), + non_preemptive=tuple( + constraint + for constraint in schedule_spec.constraints + if isinstance(constraint, NonPreemptiveConstraintSpec) + ), + strategy=schedule_spec.strategy, + max_block_size=schedule_spec.max_block_size, + serialize_segments=serialize_segments, + time_limit_s=schedule_spec.time_limit_s, + minimize_max_wait=schedule_spec.minimize_max_wait, + ) + + +def schedule_object_events( + arm_paths: Mapping[str, ArmPath], + schedule: Schedule, +) -> tuple[ScheduledObjectEvent, ...]: + """Map attach/detach events from segment boundaries to execution ticks. + + A boundary before local waypoint ``i`` activates at that waypoint's occupancy start. The first + writer on a persistent lane is occupied from tick zero; later waypoints use their scheduled + ticks. A terminal boundary activates one tick after its segment's final waypoint. Same-object + transitions on different lanes at one tick are rejected because they have no defined + within-tick ordering. + + Args: + arm_paths: Complete paths keyed by end-effector lane. + schedule: Accepted waypoint schedule for those paths. + + Returns: + Events ordered by execution tick, with stable per-lane declaration order for ties. + """ + + scheduled: list[ScheduledObjectEvent] = [] + for eef_name, path in sorted(arm_paths.items()): + assert eef_name == path.eef_name, "each arm_paths key must match its ArmPath.eef_name" + for event in path.object_events: + start, end = path.segment_bounds[event.segment_id] + ticks = schedule.ticks_for(event.segment_id) + assert len(ticks) == end - start, f"schedule length differs for segment {event.segment_id}" + # A lane's first pose is already occupied during any initial wait. + if event.local_boundary_index == 0 and start == 0: + tick = 0 + elif event.local_boundary_index < len(ticks): + tick = ticks[event.local_boundary_index] + else: + tick = ticks[-1] + 1 + assert tick <= schedule.makespan_ticks, "object event lies beyond the schedule makespan" + scheduled.append(ScheduledObjectEvent(tick=tick, path_event=event)) + scheduled.sort(key=lambda event: event.tick) + + # Validate the event stream before projecting poses: ownership must be single-valued. + owner_by_object: dict[str, str] = {} + object_by_lane: dict[str, str] = {} + lanes_by_tick_and_object: dict[tuple[int, str], set[str]] = {} + for scheduled_event in scheduled: + path_event = scheduled_event.path_event + event = path_event.spec + lane = path_event.segment_id.eef_name + lanes = lanes_by_tick_and_object.setdefault((scheduled_event.tick, event.object_ref), set()) + lanes.add(lane) + assert len(lanes) == 1, ( + f"simultaneous transitions for object {event.object_ref!r} at tick {scheduled_event.tick} " + "span multiple lanes" + ) + if event.event_type == SegmentEventType.ATTACH: + assert event.object_ref not in owner_by_object, ( + f"object {event.object_ref!r} is already carried by " + f"{owner_by_object[event.object_ref]!r} at tick {scheduled_event.tick}" + ) + assert ( + lane not in object_by_lane + ), f"lane {lane!r} already carries object {object_by_lane.get(lane)!r} at tick {scheduled_event.tick}" + owner_by_object[event.object_ref] = lane + object_by_lane[lane] = event.object_ref + else: + assert ( + owner_by_object.get(event.object_ref) == lane + ), f"lane {lane!r} cannot detach object {event.object_ref!r} at tick {scheduled_event.tick}" + del owner_by_object[event.object_ref] + del object_by_lane[lane] + return tuple(scheduled) + + +def get_scheduled_path_indices(path: ArmPath, schedule: Schedule) -> tuple[int, ...]: + """Map each execution tick to the waypoint held on one arm path. + + Args: + path: Complete unscheduled arm path. + schedule: Execution ticks for the path's segments. + + Returns: + Path waypoint index for every tick before the schedule makespan. + Initial, inter-segment and terminal waits repeat the held waypoint index. + """ + + scheduled: list[tuple[int, int]] = [] + for segment_id, (start, end) in path.segment_bounds.items(): + ticks = schedule.ticks_for(segment_id) + assert len(ticks) == end - start, f"schedule length differs for segment {segment_id}" + scheduled.extend((tick, start + local_index) for local_index, tick in enumerate(ticks)) + scheduled.sort() + assert len(scheduled) == len(path.waypoints), "schedule must cover every path waypoint" + timeline: list[int] = [] + cursor = 0 + # The last issued waypoint remains active during waits; waypoint zero covers the initial hold. + for tick in range(schedule.makespan_ticks): + while cursor + 1 < len(scheduled) and scheduled[cursor + 1][0] <= tick: + cursor += 1 + timeline.append(scheduled[cursor][1]) + return tuple(timeline) + + +def schedule_object_poses( + arm_paths: Mapping[str, ArmPath], + schedule: Schedule, +) -> tuple[ScheduledObjectPose, ...]: + """Map path-boundary object poses to their post-command execution samples. + + Args: + arm_paths: Complete paths keyed by end-effector name. + schedule: Execution ticks for every segment waypoint. + + Returns: + Object poses ordered by sample tick and end effector. + The initial pose uses sample tick -1, before any command executes. + """ + + scheduled: list[ScheduledObjectPose] = [] + for eef_name, path in sorted(arm_paths.items()): + assert eef_name == path.eef_name, "each arm_paths key must match its ArmPath.eef_name" + waypoint_ticks: dict[int, int] = {} + for segment_id, (start, end) in path.segment_bounds.items(): + ticks = schedule.ticks_for(segment_id) + assert len(ticks) == end - start, f"schedule length differs for segment {segment_id}" + waypoint_ticks.update((start + local_index, tick) for local_index, tick in enumerate(ticks)) + assert len(waypoint_ticks) == len(path.waypoints), "schedule must cover every path waypoint" + + for path_pose in path.object_pose_keyframes: + start, _ = path.segment_bounds[path_pose.segment_id] + global_boundary = start + path_pose.local_boundary_index + # Provider poses describe completed commands; -1 denotes the untouched reset state. + sample_tick = -1 if global_boundary == 0 else waypoint_ticks[global_boundary - 1] + assert sample_tick < schedule.makespan_ticks, "object pose lies beyond the schedule makespan" + scheduled.append(ScheduledObjectPose(sample_tick=sample_tick, path_pose=path_pose)) + + scheduled.sort(key=lambda pose: (pose.sample_tick, pose.path_pose.segment_id.eef_name)) + identities = tuple((pose.sample_tick, pose.path_pose.object_ref) for pose in scheduled) + assert len(identities) == len(set(identities)), "multiple object poses target one execution sample" + return tuple(scheduled) + + +def project_object_states( + initial_object_poses: Mapping[str, torch.Tensor], + tool_poses_by_eef: Mapping[str, torch.Tensor], + object_refs: tuple[str, ...], + scheduled_events: tuple[ScheduledObjectEvent, ...], + scheduled_object_poses: tuple[ScheduledObjectPose, ...] = (), + *, + makespan_ticks: int, +) -> tuple[ObjectStateSample, ...]: + """Predict object ownership and poses during a scheduled execution. + + Tool-pose row ``t`` is the state before command ``t``; row ``t + 1`` is the state afterward. + An attach applies the annotated object pose and makes it follow the tool. A detach keeps + the pose from before that command. The terminal boundary is included even though no + command follows it. + + Args: + initial_object_poses: Reset-time environment-relative object poses [m]. + tool_poses_by_eef: Environment-relative tool poses at boundaries ``0..makespan_ticks`` [m]. + object_refs: Exact episode object-geometry registry keys. + scheduled_events: Object transitions mapped to schedule ticks. + scheduled_object_poses: Provider object poses aligned to post-command execution samples. + makespan_ticks: Exclusive terminal schedule tick. + + Returns: + Immutable samples ordered by ``(boundary_tick, object_ref)``. + """ + + assert isinstance(initial_object_poses, Mapping) + assert isinstance(tool_poses_by_eef, Mapping) + assert isinstance(object_refs, tuple) and len(object_refs) == len(set(object_refs)) + assert isinstance(scheduled_events, tuple) and all( + isinstance(event, ScheduledObjectEvent) for event in scheduled_events + ) + assert isinstance(scheduled_object_poses, tuple) and all( + isinstance(pose, ScheduledObjectPose) for pose in scheduled_object_poses + ) + assert type(makespan_ticks) is int and makespan_ticks > 0 + assert tuple(event.tick for event in scheduled_events) == tuple(sorted(event.tick for event in scheduled_events)) + assert tuple(pose.sample_tick for pose in scheduled_object_poses) == tuple( + sorted(pose.sample_tick for pose in scheduled_object_poses) + ) + + tracked_objects = tuple(sorted(object_refs)) + attach_refs = { + event.path_event.spec.object_ref + for event in scheduled_events + if event.path_event.spec.event_type == SegmentEventType.ATTACH + } + assert attach_refs == set(tracked_objects), "object registry must exactly match scheduled attachments" + assert all(event.path_event.spec.object_ref in attach_refs for event in scheduled_events) + if not tracked_objects: + return () + + event_lanes = {event.path_event.segment_id.eef_name for event in scheduled_events} + assert event_lanes <= set(tool_poses_by_eef), "object event references an unknown tool lane" + reference = next(iter(tool_poses_by_eef.values())) + assert isinstance(reference, torch.Tensor) + tool_poses: dict[str, torch.Tensor] = {} + for eef_name, poses in tool_poses_by_eef.items(): + assert isinstance(poses, torch.Tensor) and poses.shape == (makespan_ticks + 1, 4, 4) + assert bool(torch.isfinite(poses).all()), f"tool timeline {eef_name!r} contains a non-finite pose" + tool_poses[eef_name] = poses.to(device=reference.device, dtype=reference.dtype) + + current_poses: dict[str, torch.Tensor] = {} + pose_history: dict[str, list[torch.Tensor]] = {object_ref: [] for object_ref in tracked_objects} + owner_history: dict[str, list[ScheduledObjectEvent | None]] = {object_ref: [] for object_ref in tracked_objects} + jump_history: dict[str, list[tuple[float, float] | None]] = {object_ref: [] for object_ref in tracked_objects} + active_attach: dict[str, ScheduledObjectEvent] = {} + active_object_by_lane: dict[str, str] = {} + for object_ref in tracked_objects: + assert object_ref in initial_object_poses, f"reset snapshot has no pose for object {object_ref!r}" + pose = initial_object_poses[object_ref] + assert isinstance(pose, torch.Tensor) and pose.shape == (4, 4) and bool(torch.isfinite(pose).all()) + current_poses[object_ref] = pose.to(device=reference.device, dtype=reference.dtype).detach().clone() + + poses_by_sample: dict[int, list[ScheduledObjectPose]] = {} + for scheduled_pose in scheduled_object_poses: + assert -1 <= scheduled_pose.sample_tick < makespan_ticks + assert scheduled_pose.path_pose.object_ref in tracked_objects + poses_by_sample.setdefault(scheduled_pose.sample_tick, []).append(scheduled_pose) + for scheduled_pose in poses_by_sample.pop(-1, ()): + path_pose = scheduled_pose.path_pose + expected_pose = path_pose.env_from_object.to(device=reference.device, dtype=reference.dtype) + position_delta, rotation_delta = _object_pose_delta(current_poses[path_pose.object_ref], expected_pose) + assert position_delta <= 1.0e-4 and rotation_delta <= 1.0e-3, ( + f"initial object pose {path_pose.object_ref!r} differs from provider evidence by " + f"{position_delta:.6f} m / {rotation_delta:.6f} rad" + ) + + events_by_tick: dict[int, list[ScheduledObjectEvent]] = {} + for event in scheduled_events: + assert event.tick <= makespan_ticks, "object event lies beyond the schedule makespan" + events_by_tick.setdefault(event.tick, []).append(event) + + for tick in range(makespan_ticks + 1): + # Boundary t contains the result of command t-1, not the result of command t. + for object_ref, attach in active_attach.items(): + lane = attach.path_event.segment_id.eef_name + tool_from_object = attach.path_event.tool_from_object + assert tool_from_object is not None + current_poses[object_ref] = tool_poses[lane][tick] @ tool_from_object.to( + device=reference.device, dtype=reference.dtype + ) + for scheduled_pose in poses_by_sample.get(tick - 1, ()): + path_pose = scheduled_pose.path_pose + if path_pose.object_ref not in active_attach: + current_poses[path_pose.object_ref] = path_pose.env_from_object.to( + device=reference.device, dtype=reference.dtype + ) + + # Events change ownership at this boundary, before the next command executes. + attachment_jumps: dict[str, tuple[float, float]] = {} + for event in events_by_tick.get(tick, ()): + path_event = event.path_event + spec = path_event.spec + object_ref = spec.object_ref + lane = path_event.segment_id.eef_name + if spec.event_type == SegmentEventType.ATTACH: + assert object_ref not in active_attach, f"object {object_ref!r} is already attached" + assert ( + lane not in active_object_by_lane + ), f"lane {lane!r} already carries object {active_object_by_lane.get(lane)!r}" + assert path_event.tool_from_object is not None + boundary_pose = tool_poses[lane][tick] @ path_event.tool_from_object.to( + device=reference.device, dtype=reference.dtype + ) + attachment_jumps[object_ref] = _object_pose_delta(current_poses[object_ref], boundary_pose) + current_poses[object_ref] = boundary_pose + active_attach[object_ref] = event + active_object_by_lane[lane] = object_ref + else: + assert spec.event_type == SegmentEventType.DETACH + attach = active_attach.get(object_ref) + assert attach is not None, f"cannot detach unowned object {object_ref!r}" + assert attach.path_event.segment_id.eef_name == lane, ( + f"lane {lane!r} cannot detach object {object_ref!r} owned by " + f"{attach.path_event.segment_id.eef_name!r}" + ) + tool_from_object = attach.path_event.tool_from_object + assert tool_from_object is not None + current_poses[object_ref] = tool_poses[lane][tick] @ tool_from_object.to( + device=reference.device, dtype=reference.dtype + ) + del active_attach[object_ref] + del active_object_by_lane[lane] + + for object_ref in tracked_objects: + pose_history[object_ref].append(current_poses[object_ref].detach().clone()) + owner_history[object_ref].append(active_attach.get(object_ref)) + jump_history[object_ref].append(attachment_jumps.get(object_ref)) + + # Copy only after the timeline is complete so saved states cannot alias mutable tensors. + immutable_poses = { + object_ref: tuple( + tuple(tuple(float(value) for value in row) for row in pose) for pose in torch.stack(poses).cpu().tolist() + ) + for object_ref, poses in pose_history.items() + } + return tuple( + ObjectStateSample( + boundary_tick=tick, + object_ref=object_ref, + env_from_object=immutable_poses[object_ref][tick], + active_attach_event=owner_history[object_ref][tick], + attachment_pose_jump=jump_history[object_ref][tick], + ) + for tick in range(makespan_ticks + 1) + for object_ref in tracked_objects + ) + + +def _object_pose_delta(first_pose: torch.Tensor, second_pose: torch.Tensor) -> tuple[float, float]: + """Return translation/rotation differences [m, rad], using float64 rotation math.""" + + position_delta = float(torch.linalg.vector_norm(first_pose[:3, 3] - second_pose[:3, 3]).item()) + first_rotation = first_pose[:3, :3].to(dtype=torch.float64) + second_rotation = second_pose[:3, :3].to(dtype=torch.float64) + relative_rotation = first_rotation.transpose(0, 1) @ second_rotation + cosine = torch.clamp((torch.trace(relative_rotation) - 1.0) * 0.5, -1.0, 1.0) + return position_delta, float(torch.acos(cosine).item()) + + +def _waypoint_localize( + arm_path_by_eef: dict[str, ArmPath], + bounds_by_eef: dict[str, tuple[tuple[SegmentId, tuple[int, int]], ...]], + *, + eef_name: str, + waypoint_index: int, +) -> SegmentWaypoint: + """Map an arm-global waypoint index into its containing half-open segment interval.""" + + arm_path = arm_path_by_eef.get(eef_name) + assert arm_path is not None, f"conflict references unknown arm path {eef_name!r}" + assert waypoint_index < len( + arm_path.waypoints + ), f"conflict waypoint {waypoint_index} is outside arm path {eef_name!r}" + for segment_id, (start, end) in bounds_by_eef[eef_name]: + if start <= waypoint_index < end: + return SegmentWaypoint(segment_id, waypoint_index - start) + raise AssertionError(f"conflict waypoint {waypoint_index} is not covered by arm path {eef_name!r}") + + +__all__ = [ + "get_scheduled_path_indices", + "schedule_object_events", + "schedule_object_poses", + "schedule_robot_contacts", + "schedule_world_contacts", + "project_object_states", + "schedule_arm_paths", +] diff --git a/autodata_core/schedulegen/types.py b/autodata_core/schedulegen/types.py new file mode 100644 index 0000000..3148da4 --- /dev/null +++ b/autodata_core/schedulegen/types.py @@ -0,0 +1,449 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Path, object-event and contact data shared by ScheduleGen components.""" + +from __future__ import annotations + +import math +import torch +from collections.abc import Mapping +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import TYPE_CHECKING + +from autodata_core.waypoint import Waypoint +from autodata_interfaces.tasks.schedule_constraint_spec import SegmentId +from autodata_interfaces.tasks.segment_spec import ( + SegmentEventPoint, + SegmentEventSpec, + SegmentEventType, + SegmentRobotContactSpec, + SegmentWorldContactSpec, +) + +if TYPE_CHECKING: + from autodata_interfaces.motion_planners.curobo.collision_spheres import ObjectCollisionSpheres + + +class EpisodeGenerationError(RuntimeError): + """Expected path-building, scheduling, validation or replay failure. + + Args: + stage: Failed operation recorded in the attempt result. + message: Description of the failed operation. + diagnostics: Additional scalar details for the attempt result. + """ + + def __init__( + self, + stage: str, + message: str, + diagnostics: tuple[tuple[str, str], ...] = (), + ) -> None: + """Record the failed stage, message and optional attempt diagnostics.""" + + super().__init__(message) + self.stage = stage + self.diagnostics = diagnostics + + +@dataclass(frozen=True) +class EpisodePaths: + """Complete unscheduled arm paths and their attached-object geometry. + + Args: + arm_paths: Paths keyed by end-effector name. + object_collision_spheres: One fitted sphere set per object attached along the paths. + """ + + arm_paths: Mapping[str, ArmPath] + object_collision_spheres: Mapping[str, ObjectCollisionSpheres] + + def __post_init__(self) -> None: + """Check attachment geometry coverage and freeze copies of the path and geometry maps.""" + + arm_paths = dict(self.arm_paths) + geometries = dict(self.object_collision_spheres) + attach_refs = { + event.spec.object_ref + for path in arm_paths.values() + for event in path.object_events + if event.spec.event_type == SegmentEventType.ATTACH + } + assert attach_refs == set(geometries), "every attachment must have exactly one sphere geometry" + assert all(name == geometry.object_name for name, geometry in geometries.items()) + object.__setattr__(self, "arm_paths", MappingProxyType(arm_paths)) + object.__setattr__(self, "object_collision_spheres", MappingProxyType(geometries)) + + +def _rigid_transform_copy(transform: torch.Tensor, name: str) -> torch.Tensor: + """Validate and copy one rigid homogeneous transform. + + Args: + transform: Homogeneous transform with shape (4, 4); translation is in [m]. + name: Field name used in validation errors. + + Returns: + A detached copy with a finite, proper rotation and homogeneous final row. + """ + + assert isinstance(transform, torch.Tensor), f"{name} must be a torch.Tensor" + result = transform.detach().clone() + assert result.shape == (4, 4), f"{name} must have shape (4, 4)" + assert bool(torch.isfinite(result).all()), f"{name} must be finite" + assert torch.allclose( + result[3], result.new_tensor((0.0, 0.0, 0.0, 1.0)), atol=1.0e-5, rtol=0.0 + ), f"invalid {name} homogeneous transform" + rotation = result[:3, :3] + identity = torch.eye(3, device=rotation.device, dtype=rotation.dtype) + assert torch.allclose( + rotation.transpose(0, 1) @ rotation, identity, atol=1.0e-4, rtol=0.0 + ), f"{name} rotation must be orthonormal" + assert torch.allclose( + torch.linalg.det(rotation), rotation.new_tensor(1.0), atol=1.0e-4, rtol=0.0 + ), f"{name} rotation must be proper" + return result + + +@dataclass(frozen=True) +class PathObjectEvent: + """An attach or detach event at a segment-local path boundary. + + Args: + segment_id: Segment containing the event. + local_boundary_index: Boundary before local waypoint ``i``, or the segment length for its + terminal boundary. + spec: Original validated descriptor event and its source annotation. + tool_from_object: Object transform in the attachment frame; translation is in [m]. + """ + + segment_id: SegmentId + local_boundary_index: int + spec: SegmentEventSpec + tool_from_object: torch.Tensor | None = None + + def __post_init__(self) -> None: + """Validate the event boundary and copy the rigid transform required by attachment.""" + + assert isinstance(self.segment_id, SegmentId), "segment_id must be a SegmentId" + assert ( + type(self.local_boundary_index) is int and self.local_boundary_index >= 0 + ), "local_boundary_index must be a non-negative integer" + assert isinstance(self.spec, SegmentEventSpec), "spec must be a SegmentEventSpec" + if self.spec.event_type == SegmentEventType.DETACH: + assert self.tool_from_object is None, "detach events do not use tool_from_object" + return + + assert self.spec.event_type == SegmentEventType.ATTACH + object.__setattr__(self, "tool_from_object", _rigid_transform_copy(self.tool_from_object, "tool_from_object")) + + +@dataclass(frozen=True) +class PathObjectPose: + """An object-pose sample at a segment-local path boundary. + + Args: + segment_id: Segment containing the object-pose sample. + local_boundary_index: Boundary before local waypoint ``i``, or the terminal boundary. + object_ref: Exact logical scene-object name. + env_from_object: Environment-relative object transform [m]. + """ + + segment_id: SegmentId + local_boundary_index: int + object_ref: str + env_from_object: torch.Tensor + + def __post_init__(self) -> None: + """Validate the object boundary and copy its environment-relative rigid transform.""" + + assert isinstance(self.segment_id, SegmentId), "segment_id must be a SegmentId" + assert type(self.local_boundary_index) is int and self.local_boundary_index >= 0 + assert self.object_ref and self.object_ref == self.object_ref.strip(), "object_ref must be non-empty" + object.__setattr__(self, "env_from_object", _rigid_transform_copy(self.env_from_object, "env_from_object")) + + +@dataclass(frozen=True) +class ScheduledObjectEvent: + """An attach or detach event mapped to an execution boundary tick. + + Args: + tick: Integer boundary tick at which the transition becomes active. + path_event: Path event and its source annotation. + """ + + tick: int + path_event: PathObjectEvent + + def __post_init__(self) -> None: + """Validate the nonnegative execution boundary and its path event.""" + + assert type(self.tick) is int and self.tick >= 0, "tick must be a non-negative integer" + assert isinstance(self.path_event, PathObjectEvent), "path_event must be a PathObjectEvent" + + +@dataclass(frozen=True) +class ScheduledObjectPose: + """An object pose mapped to a recorded execution sample. + + Args: + sample_tick: Post-command sample tick, or -1 for the pose before execution. + path_pose: Object pose and its segment-local boundary. + """ + + sample_tick: int + path_pose: PathObjectPose + + def __post_init__(self) -> None: + """Validate the path pose and allow tick minus one for the pre-execution sample.""" + + assert type(self.sample_tick) is int and self.sample_tick >= -1, "sample_tick must be at least -1" + assert isinstance(self.path_pose, PathObjectPose), "path_pose must be a PathObjectPose" + + +@dataclass(frozen=True, kw_only=True) +class ObjectStateSample: + """Predicted object state at one scheduled boundary. + + Args: + boundary_tick: Boundary that starts this execution sample, including the terminal boundary. + object_ref: Exact logical scene-object name. + env_from_object: Environment-relative object transform [m]. + active_attach_event: Exact active attachment, or ``None`` while released in the world. + attachment_pose_jump: Translation and rotation applied by an attach transition [m, rad], + or ``None`` when no attachment starts this sample. + """ + + boundary_tick: int + object_ref: str + env_from_object: tuple[tuple[float, float, float, float], ...] + active_attach_event: ScheduledObjectEvent | None + attachment_pose_jump: tuple[float, float] | None = None + + def __post_init__(self) -> None: + """Validate attachment timing, finite pose jumps and the rigid object transform.""" + + assert type(self.boundary_tick) is int and self.boundary_tick >= 0 + assert self.object_ref and self.object_ref == self.object_ref.strip(), "object_ref must be non-empty" + if self.active_attach_event is not None: + assert isinstance(self.active_attach_event, ScheduledObjectEvent) + assert self.active_attach_event.tick <= self.boundary_tick + spec = self.active_attach_event.path_event.spec + assert spec.event_type == SegmentEventType.ATTACH and spec.object_ref == self.object_ref + if self.attachment_pose_jump is not None: + assert self.active_attach_event is not None and self.active_attach_event.tick == self.boundary_tick + assert len(self.attachment_pose_jump) == 2 + jump = tuple(float(value) for value in self.attachment_pose_jump) + assert all(math.isfinite(value) and value >= 0.0 for value in jump) + object.__setattr__(self, "attachment_pose_jump", jump) + + transform = tuple(tuple(float(value) for value in row) for row in self.env_from_object) + matrix = torch.tensor(transform, dtype=torch.float64) + assert matrix.shape == (4, 4) and bool(torch.isfinite(matrix).all()) + assert torch.allclose(matrix[3], matrix.new_tensor((0.0, 0.0, 0.0, 1.0)), atol=1.0e-5, rtol=0.0) + rotation = matrix[:3, :3] + assert torch.allclose( + rotation.transpose(0, 1) @ rotation, + torch.eye(3, dtype=matrix.dtype), + atol=1.0e-4, + rtol=0.0, + ) + assert torch.allclose(torch.linalg.det(rotation), matrix.new_tensor(1.0), atol=1.0e-4, rtol=0.0) + object.__setattr__(self, "env_from_object", transform) + + @property + def owner_eef_name(self) -> str | None: + """Return the carrying end effector, or ``None`` while the object is released.""" + + if self.active_attach_event is None: + return None + return self.active_attach_event.path_event.segment_id.eef_name + + +@dataclass(frozen=True) +class ScheduledWorldContact: + """An object/fixture permission over a half-open interval of execution ticks. + + Args: + segment_id: Segment owning the permission. + spec: Task-defined object/fixture pair. + start_tick: First permitted boundary tick. + stop_tick: Exclusive end of the permitted interval. + """ + + segment_id: SegmentId + spec: SegmentWorldContactSpec + start_tick: int + stop_tick: int + + def __post_init__(self) -> None: + """Require an object/fixture permission over a nonempty half-open tick interval.""" + + assert isinstance(self.segment_id, SegmentId) + assert isinstance(self.spec, SegmentWorldContactSpec) + assert 0 <= self.start_tick < self.stop_tick + + +@dataclass(frozen=True) +class ScheduledRobotContact: + """A robot/object permission over a half-open interval of execution ticks. + + Args: + segment_id: Segment owning the permission. + spec: Task-defined object and allowed robot links. + start_tick: First permitted boundary tick. + stop_tick: Exclusive end of the permitted interval. + """ + + segment_id: SegmentId + spec: SegmentRobotContactSpec + start_tick: int + stop_tick: int + + def __post_init__(self) -> None: + """Require a robot/object permission over a nonempty half-open tick interval.""" + + assert isinstance(self.segment_id, SegmentId) + assert isinstance(self.spec, SegmentRobotContactSpec) + assert 0 <= self.start_tick < self.stop_tick + + +@dataclass(frozen=True) +class ArmPath: + """One arm's complete, unscheduled episode path. + + ``segment_bounds`` maps every segment to a half-open ``[start, end)`` interval in both + ``waypoints`` and ``joint_positions``. The intervals must partition the complete path exactly. + + Args: + eef_name: End-effector/lane name used by the embodiment adapter. + waypoints: Controller waypoints in path order. + joint_positions: Arm-local planner joints with shape ``(T, J)`` [rad, m]. Columns use the + corresponding arm planner's cuRobo joint order. + segment_bounds: Exact half-open waypoint bounds for every declared segment. + object_events: Attach/detach events in lane and boundary order. + object_pose_keyframes: Object poses in lane and boundary order. + """ + + eef_name: str + waypoints: tuple[Waypoint, ...] + joint_positions: torch.Tensor + segment_bounds: Mapping[SegmentId, tuple[int, int]] + object_events: tuple[PathObjectEvent, ...] = field(default_factory=tuple) + object_pose_keyframes: tuple[PathObjectPose, ...] = field(default_factory=tuple) + + def __post_init__(self) -> None: + """Check aligned finite paths, exact segment coverage and ordered object boundaries.""" + + assert self.eef_name and self.eef_name == self.eef_name.strip(), "eef_name must be non-empty and trimmed" + assert isinstance(self.waypoints, tuple) and self.waypoints, "waypoints must be a non-empty tuple" + assert all( + isinstance(waypoint, Waypoint) for waypoint in self.waypoints + ), "waypoints must contain Waypoint values" + assert isinstance(self.joint_positions, torch.Tensor), "joint_positions must be a torch.Tensor" + assert self.joint_positions.ndim == 2, "joint_positions must have shape (T, J)" + assert self.joint_positions.shape[0] == len( + self.waypoints + ), "joint_positions and waypoints must have the same length" + assert self.joint_positions.shape[1] > 0, "joint_positions must contain at least one joint" + assert bool(torch.isfinite(self.joint_positions).all()), "joint_positions must be finite" + assert isinstance(self.segment_bounds, Mapping) and self.segment_bounds, "segment_bounds must not be empty" + assert isinstance(self.object_events, tuple) and all( + isinstance(event, PathObjectEvent) for event in self.object_events + ), "object_events must contain PathObjectEvent values" + assert isinstance(self.object_pose_keyframes, tuple) and all( + isinstance(keyframe, PathObjectPose) for keyframe in self.object_pose_keyframes + ), "object_pose_keyframes must contain PathObjectPose values" + + waypoint_coverage = [0] * len(self.waypoints) + bounds = dict(self.segment_bounds) + for segment_id, interval in bounds.items(): + assert isinstance(segment_id, SegmentId), "segment_bounds keys must be SegmentId values" + assert ( + segment_id.eef_name == self.eef_name + ), f"segment {segment_id} belongs to {segment_id.eef_name!r}, expected {self.eef_name!r}" + assert isinstance(interval, tuple) and len(interval) == 2, "segment bounds must be (start, end) tuples" + start, end = interval + assert type(start) is int and type(end) is int, "segment bounds must contain integers" + assert 0 <= start < end <= len(self.waypoints), f"invalid half-open bounds {interval} for {segment_id}" + for waypoint_index in range(start, end): + waypoint_coverage[waypoint_index] += 1 + assert all( + count == 1 for count in waypoint_coverage + ), "segment bounds must partition the complete arm path without gaps or overlap" + segment_order = { + segment_id: index + for index, (segment_id, _) in enumerate(sorted(bounds.items(), key=lambda item: item[1][0])) + } + event_order: list[tuple[int, int]] = [] + for event in self.object_events: + assert event.segment_id in bounds, f"object event references unknown segment {event.segment_id}" + assert event.segment_id.eef_name == self.eef_name, "object event belongs to another arm path" + start, end = bounds[event.segment_id] + assert ( + event.local_boundary_index <= end - start + ), f"object event boundary {event.local_boundary_index} is outside segment {event.segment_id}" + if event.spec.point == SegmentEventPoint.START: + assert event.local_boundary_index == 0, "segment-start events must use boundary zero" + elif event.spec.point == SegmentEventPoint.END: + assert event.local_boundary_index == end - start, "segment-end events must use the terminal boundary" + event_order.append((segment_order[event.segment_id], event.local_boundary_index)) + assert event_order == sorted(event_order), "object_events must be in lane and boundary order" + keyframe_order: list[tuple[int, int, str]] = [] + keyframe_ids: set[tuple[SegmentId, int, str]] = set() + for keyframe in self.object_pose_keyframes: + assert keyframe.segment_id in bounds, f"object pose references unknown segment {keyframe.segment_id}" + assert keyframe.segment_id.eef_name == self.eef_name, "object pose belongs to another arm path" + start, end = bounds[keyframe.segment_id] + assert ( + keyframe.local_boundary_index <= end - start + ), f"object pose boundary {keyframe.local_boundary_index} is outside segment {keyframe.segment_id}" + keyframe_id = (keyframe.segment_id, keyframe.local_boundary_index, keyframe.object_ref) + assert keyframe_id not in keyframe_ids, f"duplicate object pose keyframe {keyframe_id}" + keyframe_ids.add(keyframe_id) + keyframe_order.append( + (segment_order[keyframe.segment_id], keyframe.local_boundary_index, keyframe.object_ref) + ) + assert keyframe_order == sorted(keyframe_order), "object_pose_keyframes must be in lane and boundary order" + object.__setattr__(self, "segment_bounds", MappingProxyType(bounds)) + + +@dataclass(frozen=True, order=True) +class ArmWaypointConflict: + """A forbidden simultaneous pair of original arm waypoints. + + Args: + first_eef_name: First path's end-effector/lane name. + first_waypoint_index: Original waypoint index on the first path. + second_eef_name: Second path's end-effector/lane name. + second_waypoint_index: Original waypoint index on the second path. + clearance_m: Minimum sampled sphere-surface clearance [m]. Negative values penetrate. + """ + + first_eef_name: str + first_waypoint_index: int + second_eef_name: str + second_waypoint_index: int + clearance_m: float + + def __post_init__(self) -> None: + """Require distinct arm lanes, nonnegative waypoint indices and finite clearance.""" + + assert self.first_eef_name and self.second_eef_name, "conflict lane names must be non-empty" + assert self.first_eef_name != self.second_eef_name, "a cross-arm conflict requires distinct lanes" + assert self.first_waypoint_index >= 0 and self.second_waypoint_index >= 0 + assert math.isfinite(self.clearance_m), "clearance_m must be finite" + + +__all__ = [ + "ArmPath", + "ArmWaypointConflict", + "ObjectStateSample", + "PathObjectEvent", + "PathObjectPose", + "ScheduledObjectEvent", + "ScheduledObjectPose", + "ScheduledRobotContact", + "ScheduledWorldContact", +] diff --git a/autodata_core/selection_strategy.py b/autodata_core/selection_strategy.py index 9368c16..da13b46 100644 --- a/autodata_core/selection_strategy.py +++ b/autodata_core/selection_strategy.py @@ -70,6 +70,68 @@ def select_source_demo( """ raise NotImplementedError + def source_demo_candidates( + self, + eef_pose: torch.Tensor, + object_pose: torch.Tensor | None, + src_subtask_datagen_infos: list, + **kwargs: Any, + ) -> tuple[int, ...]: + """Return eligible sources without replacement, preserving the ordinary first pick. + + Args: + eef_pose: Current end-effector transform with shape ``(4, 4)`` [m]. + object_pose: Reference-object transform [m], or None for object-free subtasks. + src_subtask_datagen_infos: Source demonstration slices covering this subtask. + **kwargs: Strategy-specific distance and eligibility settings. + + Returns: + Source indices with the ordinary pick first, followed by ranked alternatives. + """ + + selected = int( + self.select_source_demo( + eef_pose=eef_pose, + object_pose=object_pose, + src_subtask_datagen_infos=src_subtask_datagen_infos, + **kwargs, + ) + ) + ranked = self.rank_source_demos( + eef_pose=eef_pose, + object_pose=object_pose, + src_subtask_datagen_infos=src_subtask_datagen_infos, + **kwargs, + ) + assert len(ranked) == len(set(ranked)), "ranked source demos must be unique" + assert all( + type(index) is int and 0 <= index < len(src_subtask_datagen_infos) for index in ranked + ), "ranked source demos must be valid indices" + assert selected in ranked, "selected source demo must be eligible" + return (selected, *(index for index in ranked if index != selected)) + + def rank_source_demos( + self, + eef_pose: torch.Tensor, + object_pose: torch.Tensor | None, + src_subtask_datagen_infos: list, + **_kwargs: Any, + ) -> tuple[int, ...]: + """Rank eligible sources for use after the ordinary first pick. + + Args: + eef_pose: Current end-effector transform with shape ``(4, 4)`` [m]. + object_pose: Reference-object transform [m], or None for object-free subtasks. + src_subtask_datagen_infos: Source demonstration slices covering this subtask. + **_kwargs: Unused strategy-specific settings. + + Returns: + Eligible source indices in pool order. + """ + + del eef_pose, object_pose + return tuple(range(len(src_subtask_datagen_infos))) + class RandomStrategy(SelectionStrategy): """Uniform random pick over source demos.""" @@ -103,6 +165,70 @@ def select_source_demo( nn_k: int = 3, object_nodal_positions: torch.Tensor | None = None, ) -> int: + """Sample one of the nearest sources by reference-object pose. + + Args: + eef_pose: Unused end-effector transform [m]. + object_pose: Current reference-object transform with shape (4, 4) [m]. + src_subtask_datagen_infos: Source slices covering this subtask. + pos_weight: Weight applied to translation distance. + rot_weight: Weight applied to rotation distance. + nn_k: Maximum number of nearest candidates to sample from. + object_nodal_positions: Unused deformable-object input from the common interface. + + Returns: + Selected index in the source pool. + """ + dists = self._distances(object_pose, src_subtask_datagen_infos, pos_weight, rot_weight) + nn_k = min(nn_k, len(dists)) + rand_k = torch.randint(0, nn_k, (1,)).item() + return int(torch.argsort(dists, stable=True)[:nn_k][rand_k].item()) + + def rank_source_demos( + self, + eef_pose: torch.Tensor, + object_pose: torch.Tensor, + src_subtask_datagen_infos: list, + pos_weight: float = 1.0, + rot_weight: float = 1.0, + nn_k: int = 3, + ) -> tuple[int, ...]: + """Rank the nearest eligible sources by reference-object pose distance. + + Args: + eef_pose: Unused end-effector transform [m]. + object_pose: Current reference-object transform with shape ``(4, 4)`` [m]. + src_subtask_datagen_infos: Source demonstration slices covering this subtask. + pos_weight: Position-distance weight. + rot_weight: Rotation-distance weight. + nn_k: Maximum number of nearest sources to keep. + + Returns: + Source indices ordered by increasing distance, with pool order breaking ties. + """ + + del eef_pose + dists = self._distances(object_pose, src_subtask_datagen_infos, pos_weight, rot_weight) + return tuple(int(index) for index in torch.argsort(dists, stable=True)[: min(nn_k, len(dists))].tolist()) + + @staticmethod + def _distances( + object_pose: torch.Tensor, + src_subtask_datagen_infos: list, + pos_weight: float, + rot_weight: float, + ) -> torch.Tensor: + """Return weighted translation/rotation distances from source object poses. + + Args: + object_pose: Current reference-object transform with shape (4, 4) [m]. + src_subtask_datagen_infos: Source slices containing one reference object each. + pos_weight: Weight applied to translation distance. + rot_weight: Weight applied to rotation distance. + + Returns: + One distance score per source, in pool order. + """ src_object_poses = [] for di in src_subtask_datagen_infos: src_obj_pose = list(di.object_poses.values()) @@ -125,9 +251,7 @@ def select_source_demo( rot_dists = torch.acos(arc_cos_in) dists = pos_weight * pos_dists + rot_weight * rot_dists - nn_k = min(nn_k, len(dists)) - rand_k = torch.randint(0, nn_k, (1,)).item() - return torch.argsort(dists)[:nn_k][rand_k] + return dists class NearestNeighborRobotDistanceStrategy(SelectionStrategy): @@ -145,6 +269,71 @@ def select_source_demo( nn_k: int = 3, object_nodal_positions: torch.Tensor | None = None, ) -> int: + """Sample a source whose object-relative skill starts near the current tool pose. + + Args: + eef_pose: Current end-effector transform with shape (4, 4) [m]. + object_pose: Current reference-object transform with shape (4, 4) [m]. + src_subtask_datagen_infos: Source slices covering this subtask. + pos_weight: Weight applied to translation distance. + rot_weight: Weight applied to rotation distance. + nn_k: Maximum number of nearest candidates to sample from. + object_nodal_positions: Unused deformable-object input from the common interface. + + Returns: + Selected index in the source pool. + """ + dists = self._distances(eef_pose, object_pose, src_subtask_datagen_infos, pos_weight, rot_weight) + nn_k = min(nn_k, len(dists)) + rand_k = torch.randint(0, nn_k, (1,)).item() + return int(torch.argsort(dists, stable=True)[:nn_k][rand_k].item()) + + def rank_source_demos( + self, + eef_pose: torch.Tensor, + object_pose: torch.Tensor, + src_subtask_datagen_infos: list, + pos_weight: float = 1.0, + rot_weight: float = 1.0, + nn_k: int = 3, + ) -> tuple[int, ...]: + """Rank the nearest sources by their transformed starting end-effector pose. + + Args: + eef_pose: Current end-effector transform with shape ``(4, 4)`` [m]. + object_pose: Current reference-object transform with shape ``(4, 4)`` [m]. + src_subtask_datagen_infos: Source demonstration slices covering this subtask. + pos_weight: Position-distance weight. + rot_weight: Rotation-distance weight. + nn_k: Maximum number of nearest sources to keep. + + Returns: + Source indices ordered by increasing distance, with pool order breaking ties. + """ + + dists = self._distances(eef_pose, object_pose, src_subtask_datagen_infos, pos_weight, rot_weight) + return tuple(int(index) for index in torch.argsort(dists, stable=True)[: min(nn_k, len(dists))].tolist()) + + @staticmethod + def _distances( + eef_pose: torch.Tensor, + object_pose: torch.Tensor, + src_subtask_datagen_infos: list, + pos_weight: float, + rot_weight: float, + ) -> torch.Tensor: + """Compare the current tool pose with object-transformed source entry poses. + + Args: + eef_pose: Current end-effector transform with shape (4, 4) [m]. + object_pose: Current reference-object transform with shape (4, 4) [m]. + src_subtask_datagen_infos: Source slices containing tool and reference-object poses. + pos_weight: Weight applied to translation distance. + rot_weight: Weight applied to rotation distance. + + Returns: + One weighted distance score per source, in pool order. + """ src_eef_poses = [] src_object_poses = [] for di in src_subtask_datagen_infos: @@ -180,9 +369,7 @@ def select_source_demo( rot_dists = torch.acos(arc_cos_in) dists = pos_weight * pos_dists + rot_weight * rot_dists - nn_k = min(nn_k, len(dists)) - rand_k = torch.randint(0, nn_k, (1,)).item() - return torch.argsort(dists)[:nn_k][rand_k] + return dists class RegistrationCostStrategy(SelectionStrategy): diff --git a/autodata_core/waypoint.py b/autodata_core/waypoint.py index 0bbf49e..9156d35 100644 --- a/autodata_core/waypoint.py +++ b/autodata_core/waypoint.py @@ -285,6 +285,32 @@ class MultiWaypoint: def __init__(self, waypoints: dict[str, Waypoint]) -> None: self.waypoints = waypoints + def to_action(self, datastream: Datastream, env_id: int = 0) -> torch.Tensor: + """Encode the multi-EEF target without stepping the environment. + + Args: + datastream: Composed datastream providing embodiment-aware action encoding. + env_id: Vectorized environment index. + + Returns: + One batched environment action with shape ``(1, action_dim)``. + """ + + target_eef_pose_dict = {eef_name: waypoint.pose for eef_name, waypoint in self.waypoints.items()} + action_noise_dict = {eef_name: waypoint.noise for eef_name, waypoint in self.waypoints.items()} + passthrough_action_dict: dict[str, torch.Tensor] = {} + for eef_name in sorted(self.waypoints): + for channel_name, channel_tensor in self.waypoints[eef_name].passthrough_action.items(): + passthrough_action_dict.setdefault(channel_name, channel_tensor) + + action = datastream.target_eef_pose_to_action( + target_eef_pose_dict=target_eef_pose_dict, + passthrough_action_dict=passthrough_action_dict, + action_noise_dict=action_noise_dict, + env_id=env_id, + ) + return action.unsqueeze(0) if action.dim() == 1 else action + async def execute( self, datastream: Datastream, @@ -310,22 +336,7 @@ async def execute( """ env = datastream.get_env() - target_eef_pose_dict = {eef_name: waypoint.pose for eef_name, waypoint in self.waypoints.items()} - action_noise_dict = {eef_name: waypoint.noise for eef_name, waypoint in self.waypoints.items()} - passthrough_action_dict: dict[str, torch.Tensor] = {} - for eef_name in sorted(self.waypoints): - for channel_name, channel_tensor in self.waypoints[eef_name].passthrough_action.items(): - passthrough_action_dict.setdefault(channel_name, channel_tensor) - - play_action = datastream.target_eef_pose_to_action( - target_eef_pose_dict=target_eef_pose_dict, - passthrough_action_dict=passthrough_action_dict, - action_noise_dict=action_noise_dict, - env_id=env_id, - ) - - if play_action.dim() == 1: - play_action = play_action.unsqueeze(0) + play_action = self.to_action(datastream, env_id) if env_action_queue is None: env.step(play_action) diff --git a/autodata_examples/embodiments/gr1t2_cross_planning.yaml b/autodata_examples/embodiments/gr1t2_cross_planning.yaml new file mode 100644 index 0000000..1649ca0 --- /dev/null +++ b/autodata_examples/embodiments/gr1t2_cross_planning.yaml @@ -0,0 +1,17 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +schema: isaac-autodata.curobo-planning-groups.v1 +extends: gr1t2_planning.yaml +name: gr1t2_cross +full_state_collision_scope: planning_groups + +# Fixed-waist cross-reach uses optimized transits and the reviewed arm-group collision scope. +planner: + collision_activation_distance: 0.01 + enable_opt: true + approach_distance: 0.0 + retreat_distance: 0.0 + surface_sphere_radius: 0.015 + debug_planner: true + ik_candidate_count: 1 diff --git a/autodata_examples/embodiments/gr1t2_planning.yaml b/autodata_examples/embodiments/gr1t2_planning.yaml new file mode 100644 index 0000000..38bb1e0 --- /dev/null +++ b/autodata_examples/embodiments/gr1t2_planning.yaml @@ -0,0 +1,180 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +schema: isaac-autodata.curobo-planning-groups.v1 +name: gr1t2 +root_link: base_link +root_pose_source_frame: base_link +full_state_collision_scope: complete + +# Pink targets each hand-pitch frame with seven arm joints. Each hand has six independent joints +# and five mimic followers. Keep the waist fixed and retain the followers in the collision model. +inactive_joint_names: + - waist_yaw_joint + - waist_pitch_joint + - waist_roll_joint + +planning_groups: + left_arm: + eef_name: left + tool_link: left_hand_pitch_link + auxiliary_joint_names: + - L_index_proximal_joint + - L_middle_proximal_joint + - L_pinky_proximal_joint + - L_ring_proximal_joint + - L_thumb_proximal_yaw_joint + - L_thumb_proximal_pitch_joint + initial_auxiliary_joint_positions: 0.0 + # Intended hand contacts supplement the generated topology policy. Other pairs remain checked. + self_collision_ignore_pairs: + - [L_index_intermediate_link, L_middle_intermediate_link] + - [L_index_intermediate_link, L_middle_proximal_link] + - [L_index_intermediate_link, L_pinky_intermediate_link] + - [L_index_intermediate_link, L_pinky_proximal_link] + - [L_index_intermediate_link, L_ring_intermediate_link] + - [L_index_intermediate_link, L_ring_proximal_link] + - [L_index_intermediate_link, L_thumb_distal_link] + - [L_index_intermediate_link, L_thumb_proximal_base_link] + - [L_index_intermediate_link, L_thumb_proximal_link] + - [L_index_proximal_link, L_middle_intermediate_link] + - [L_index_proximal_link, L_pinky_intermediate_link] + - [L_index_proximal_link, L_ring_intermediate_link] + - [L_index_proximal_link, L_thumb_distal_link] + - [L_index_proximal_link, L_thumb_proximal_link] + - [L_middle_intermediate_link, L_pinky_intermediate_link] + - [L_middle_intermediate_link, L_pinky_proximal_link] + - [L_middle_intermediate_link, L_ring_intermediate_link] + - [L_middle_intermediate_link, L_ring_proximal_link] + - [L_middle_intermediate_link, L_thumb_distal_link] + - [L_middle_intermediate_link, L_thumb_proximal_base_link] + - [L_middle_intermediate_link, L_thumb_proximal_link] + - [L_middle_proximal_link, L_pinky_intermediate_link] + - [L_middle_proximal_link, L_ring_intermediate_link] + - [L_middle_proximal_link, L_thumb_distal_link] + - [L_middle_proximal_link, L_thumb_proximal_link] + - [L_pinky_intermediate_link, L_ring_intermediate_link] + - [L_pinky_intermediate_link, L_ring_proximal_link] + - [L_pinky_intermediate_link, L_thumb_distal_link] + - [L_pinky_intermediate_link, L_thumb_proximal_base_link] + - [L_pinky_intermediate_link, L_thumb_proximal_link] + - [L_pinky_proximal_link, L_ring_intermediate_link] + - [L_pinky_proximal_link, L_thumb_distal_link] + - [L_pinky_proximal_link, L_thumb_proximal_link] + - [L_ring_intermediate_link, L_thumb_distal_link] + - [L_ring_intermediate_link, L_thumb_proximal_base_link] + - [L_ring_intermediate_link, L_thumb_proximal_link] + - [L_ring_proximal_link, L_thumb_distal_link] + - [L_ring_proximal_link, L_thumb_proximal_link] + - [L_thumb_distal_link, left_hand_pitch_link] + - [L_thumb_proximal_base_link, left_hand_yaw_link] + - [L_thumb_proximal_link, left_hand_yaw_link] + right_arm: + eef_name: right + tool_link: right_hand_pitch_link + auxiliary_joint_names: + - R_index_proximal_joint + - R_middle_proximal_joint + - R_pinky_proximal_joint + - R_ring_proximal_joint + - R_thumb_proximal_yaw_joint + - R_thumb_proximal_pitch_joint + initial_auxiliary_joint_positions: 0.0 + self_collision_ignore_pairs: + - [R_index_intermediate_link, R_middle_intermediate_link] + - [R_index_intermediate_link, R_middle_proximal_link] + - [R_index_intermediate_link, R_pinky_intermediate_link] + - [R_index_intermediate_link, R_pinky_proximal_link] + - [R_index_intermediate_link, R_ring_intermediate_link] + - [R_index_intermediate_link, R_ring_proximal_link] + - [R_index_intermediate_link, R_thumb_distal_link] + - [R_index_intermediate_link, R_thumb_proximal_base_link] + - [R_index_intermediate_link, R_thumb_proximal_link] + - [R_index_proximal_link, R_middle_intermediate_link] + - [R_index_proximal_link, R_pinky_intermediate_link] + - [R_index_proximal_link, R_ring_intermediate_link] + - [R_index_proximal_link, R_thumb_distal_link] + - [R_index_proximal_link, R_thumb_proximal_link] + - [R_middle_intermediate_link, R_pinky_intermediate_link] + - [R_middle_intermediate_link, R_pinky_proximal_link] + - [R_middle_intermediate_link, R_ring_intermediate_link] + - [R_middle_intermediate_link, R_ring_proximal_link] + - [R_middle_intermediate_link, R_thumb_distal_link] + - [R_middle_intermediate_link, R_thumb_proximal_base_link] + - [R_middle_intermediate_link, R_thumb_proximal_link] + - [R_middle_proximal_link, R_pinky_intermediate_link] + - [R_middle_proximal_link, R_ring_intermediate_link] + - [R_middle_proximal_link, R_thumb_distal_link] + - [R_middle_proximal_link, R_thumb_proximal_link] + - [R_pinky_intermediate_link, R_ring_intermediate_link] + - [R_pinky_intermediate_link, R_ring_proximal_link] + - [R_pinky_intermediate_link, R_thumb_distal_link] + - [R_pinky_intermediate_link, R_thumb_proximal_base_link] + - [R_pinky_intermediate_link, R_thumb_proximal_link] + - [R_pinky_proximal_link, R_ring_intermediate_link] + - [R_pinky_proximal_link, R_thumb_distal_link] + - [R_pinky_proximal_link, R_thumb_proximal_link] + - [R_ring_intermediate_link, R_thumb_distal_link] + - [R_ring_intermediate_link, R_thumb_proximal_base_link] + - [R_ring_intermediate_link, R_thumb_proximal_link] + - [R_ring_proximal_link, R_thumb_distal_link] + - [R_ring_proximal_link, R_thumb_proximal_link] + - [R_thumb_distal_link, right_hand_pitch_link] + - [R_thumb_proximal_base_link, right_hand_yaw_link] + - [R_thumb_proximal_link, right_hand_yaw_link] + +sphere_fit: + # This is a ceiling, not a target: fitting stops as soon as the quality gate passes. Large fixed + # body meshes need more candidates than the small arm/hand links. + max_spheres_per_link: 200 + surface_samples_per_geometry: 1000 + candidates_per_geometry: 800 + # Inflate fitted spheres by 5.2 mm; fitting also enforces coverage and native sphere capacity. + inflation_m: 0.0052 + min_coverage_ratio: 0.95 + max_uncovered_distance_m: 0.01 + convexify_non_watertight: true + +robot_config: + attachment_sphere_count: 100 + self_collision_ignore_depth: 2 + max_acceleration: 15.0 + max_jerk: 500.0 + +planner: + world_config_file: collision_table.yml + static_objects: [table, scale, bin] + # Match the reviewed GR1T2 SkillGen collision world. Its per-arm transit planner omits the + # task table; the loose nut starts inside its beaker and is not an independent transit obstacle. + world_ignore_substrings: + - /Table + - /FactoryNut + - /Robot + - /World/GroundPlane + - /World/defaultGroundPlane + - /curobo + num_trajopt_seeds: 12 + num_graph_seeds: 12 + interpolation_dt: 0.05 + # The base task leaves arm actuator speeds unbounded; cap planning explicitly. + max_joint_velocity: 1.0 + collision_cache_size: {obb: 150, mesh: 150} + trajopt_tsteps: 32 + collision_activation_distance: 0.04 + approach_distance: 0.0 + # Release segments author their own distance; this frame maps the standard -Z direction to + # world-up while leaving ordinary transits unchanged. + retreat_distance: 0.0 + approach_retreat_frame: world + approach_direction: [0.0, 0.0, -1.0] + enable_graph: true + enable_graph_attempt: 5 + max_planning_attempts: 15 + enable_finetune_trajopt: true + # Keep optimized timing; the returned trajectory is sampled at the 20 Hz control rate. + time_dilation_factor: 1.0 + surface_sphere_radius: 0.01 + position_threshold: 0.005 + rotation_threshold: 0.05 + ik_candidate_count: 32 + debug_planner: true diff --git a/autodata_examples/embodiments/gr1t2_schedulegen.yaml b/autodata_examples/embodiments/gr1t2_schedulegen.yaml new file mode 100644 index 0000000..d041e7a --- /dev/null +++ b/autodata_examples/embodiments/gr1t2_schedulegen.yaml @@ -0,0 +1,68 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Embodiment descriptor for the GR1 (IK, Absolute-pose). +# +# Action vector layout (36-D): +# [0..3) left EEF position [m] +# [3..7) left EEF quaternion (x, y, z, w) +# [7..10) right EEF position [m] +# [10..14) right EEF quaternion (x, y, z, w) +# [14..36) 22 interleaved left/right hand joint positions +# +# Pose is absolute; tracked by the whole-body PinkIK controller. +# EEF observations use the upstream hand-roll frames; Pink targets the hand-pitch frames. + +type: absolute_pose_whole_body_bimanual +name: gr1t2 +description: GR1 humanoid with whole-body IK and dexterous hands, absolute-pose control. +planning_model_action_term: gr1_action + +eefs: + left: + pose_obs_keys: + pos: left_eef_pos + quat: left_eef_quat + # 11 left-hand joints: 5 proximal + 5 intermediate + 1 distal + gripper_action_indices: [0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 20] + joint_names: + - L_index_proximal_joint + - L_middle_proximal_joint + - L_pinky_proximal_joint + - L_ring_proximal_joint + - L_thumb_proximal_yaw_joint + - L_index_intermediate_joint + - L_middle_intermediate_joint + - L_pinky_intermediate_joint + - L_ring_intermediate_joint + - L_thumb_proximal_pitch_joint + - L_thumb_distal_joint + passthrough_presets: + open: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + + right: + pose_obs_keys: + pos: right_eef_pos + quat: right_eef_quat + # 11 right-hand joints: 5 proximal + 5 intermediate + 1 distal + gripper_action_indices: [5, 6, 7, 8, 9, 15, 16, 17, 18, 19, 21] + joint_names: + - R_index_proximal_joint + - R_middle_proximal_joint + - R_pinky_proximal_joint + - R_ring_proximal_joint + - R_thumb_proximal_yaw_joint + - R_index_intermediate_joint + - R_middle_intermediate_joint + - R_pinky_intermediate_joint + - R_ring_intermediate_joint + - R_thumb_proximal_pitch_joint + - R_thumb_distal_joint + passthrough_presets: + open: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + +action_layout: + left_pose_slice: [0, 7] + right_pose_slice: [7, 14] + hand_joints_slice: [14, 36] + canonicalize_quat: true diff --git a/autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml b/autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml new file mode 100644 index 0000000..bb7580f --- /dev/null +++ b/autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml @@ -0,0 +1,72 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: gr1t2_nut_pour_schedulegen +description: AutoData ScheduleGen planner profile over the upstream GR1T2 nut-pouring environment. +base_env: AutoData-NutPour-GR1T2-ScheduleGen-v0 +planner: gr1t2_nut_pour +viewer: + # Exact base-link-relative front view from the reviewed IsaacLab SkillGen task. + eye: [0.0, 2.0, 2.0] + lookat: [0.0, 0.0, 0.2] + origin_type: asset_body + asset_name: robot + body_name: base_link +scene: + rigid_objects: + override: + # Reviewed source layout for the executable fixed-waist arm chains. The reset event + # independently perturbs bowl and scale by +/-1 cm in XY and applies one shared +/-1 cm + # XY translation to beaker and nut. + sorting_beaker: + position: [-0.12757, 0.46167, 0.9861] + physics_material: {static_friction: 2.0, dynamic_friction: 2.0, restitution: 0.1} + factory_nut: + position: [-0.12757, 0.46167, 0.9995] + sorting_bowl: + position: [0.03185, 0.43028, 0.9860] + sorting_scale: + position: [0.21782, 0.56552, 0.9859] + black_sorting_bin: + scale: [0.8, 1.0, 1.0] + +events: + add: + # Keep the lightweight beaker from the reviewed task, but use a realistic bowl mass so + # incidental pour contact cannot displace the later motion-planning target. + set_sorting_bowl_mass: + func: isaaclab.envs.mdp:randomize_rigid_body_mass + mode: startup + params: + asset_cfg: sorting_bowl + mass_distribution_params: [0.2, 0.2] + operation: abs + set_sorting_beaker_mass: + func: isaaclab.envs.mdp:randomize_rigid_body_mass + mode: startup + params: + asset_cfg: sorting_beaker + mass_distribution_params: [0.01, 0.01] + operation: abs + +control: + # Match the reviewed ScheduleGen task objective while retaining the current + # Isaac Lab Pink controller implementation and DAQP solver. + pink_ik: + action_term: gr1_action + frame_tasks: + left_hand_pitch_link: + position_cost: 30.0 + orientation_cost: 5.0 + lm_damping: 50.0 + gain: 0.08 + right_hand_pitch_link: + position_cost: 30.0 + orientation_cost: 5.0 + lm_damping: 50.0 + gain: 0.08 + damping_task: + cost: 0.1 + null_space_posture_task: + cost: 0.1 + lm_damping: 50.0 diff --git a/autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen_cross_overlap.yaml b/autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen_cross_overlap.yaml new file mode 100644 index 0000000..3d77bb9 --- /dev/null +++ b/autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen_cross_overlap.yaml @@ -0,0 +1,26 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +extends: gr1t2_nut_pour_schedulegen.yaml +name: gr1t2_nut_pour_schedulegen_cross_overlap +description: GR1T2 ScheduleGen stress profile with fixed-waist cross-reach pickups for both arms. +scene: + rigid_objects: + override: + # Move both pickups across the centerline while preserving fixed-waist reachability. + sorting_beaker: + position: [0.04, 0.27, 0.9860] + factory_nut: + position: [0.04, 0.27, 0.9995] + sorting_bowl: + position: [-0.04539, 0.43, 0.9861] + sorting_scale: + position: [0.22236, 0.56, 0.9859] +control: + pink_ik: + # Track cross-body targets closely during grasp and pour replay. + frame_tasks: + left_hand_pitch_link: + gain: 0.5 + right_hand_pitch_link: + gain: 0.5 diff --git a/autodata_examples/gr1t2_nut_pour.py b/autodata_examples/gr1t2_nut_pour.py new file mode 100644 index 0000000..bf004b5 --- /dev/null +++ b/autodata_examples/gr1t2_nut_pour.py @@ -0,0 +1,244 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Register the GR1T2 nut-pouring example with an explicit physics backend.""" + +from __future__ import annotations + +import argparse +import math +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from isaaclab.assets import ArticulationCfg + from isaaclab.sim import UsdFileCfg + from isaaclab_tasks.contrib.pick_place.nutpour_gr1t2_pink_ik_env_cfg import NutPourGR1T2PinkIKEnvCfg + from pxr import Usd + +ENV_NAME = "AutoData-NutPour-GR1T2-ScheduleGen-v0" + + +def _mimic_joints_newton(root: Usd.Prim, solver_dt: float) -> None: + """Preserve the robot's composed mimic compliance at the solver timestep [s].""" + from pxr import Sdf, Usd, UsdPhysics, Vt + + assert solver_dt > 0 + for prim in Usd.PrimRange(root): + for schema in prim.GetPrimTypeInfo().GetAppliedAPISchemas(): + if not schema.startswith("PhysxMimicJointAPI:"): + continue + assert prim.IsA(UsdPhysics.RevoluteJoint), f"Expected an angular mimic joint: {prim.GetPath()}." + prefix = f"physxMimicJoint:{schema.rsplit(':', 1)[1]}" + frequency = prim.GetAttribute(f"{prefix}:naturalFrequency").Get() + damping_ratio = prim.GetAttribute(f"{prefix}:dampingRatio").Get() + assert frequency is not None and damping_ratio is not None, f"Missing mimic compliance: {prim.GetPath()}." + assert frequency > 0 and damping_ratio > 0, f"Missing compliant mimic settings: {prim.GetPath()}." + targets = prim.GetRelationship(f"{prefix}:referenceJoint").GetTargets() + assert len(targets) == 1, f"Expected one mimic reference: {prim.GetPath()}." + + # Match the implicit spring update without triggering MuJoCo's 2*dt reference clamp. + damping = 2 * frequency * damping_ratio + solver_dt * frequency**2 + denominator = 1 + solver_dt * damping + reference = (2 * denominator / damping, damping / (2 * frequency * math.sqrt(denominator))) + impedance = 1 - 1 / denominator + prim.AddAppliedSchema("MjcEqualityJointAPI") + prim.AddAppliedSchema("NewtonMimicAPI") + prim.CreateRelationship("newton:mimicJoint").SetTargets(targets) + prim.CreateAttribute("newton:mimicCoef0", Sdf.ValueTypeNames.Float).Set( + -prim.GetAttribute(f"{prefix}:offset").Get() + ) + prim.CreateAttribute("newton:mimicCoef1", Sdf.ValueTypeNames.Float).Set( + -prim.GetAttribute(f"{prefix}:gearing").Get() + ) + prim.CreateAttribute("mjc:solref", Sdf.ValueTypeNames.DoubleArray).Set(Vt.DoubleArray(reference)) + prim.CreateAttribute("mjc:solimp", Sdf.ValueTypeNames.DoubleArray).Set( + Vt.DoubleArray((impedance, impedance, 0.001, 0.5, 2.0)) + ) + + +def _robot_spawn_newton(prim_path: str, cfg: UsdFileCfg, **kwargs: Any) -> Usd.Prim: + """Spawn the robot with native Newton joint-equality settings.""" + from isaaclab.sim import SimulationContext, clone, spawn_from_usd + + @clone + def spawn(prim_path, cfg, **kwargs): + """Spawn the USD and configure mimic joints at the Newton solver timestep.""" + root = spawn_from_usd(prim_path, cfg, **kwargs) + sim = SimulationContext.instance() + _mimic_joints_newton(root, sim.get_physics_dt() / sim.cfg.physics.num_substeps) + return root + + return spawn(prim_path, cfg, **kwargs) + + +def _fixture_spawn_newton(prim_path: str, cfg: UsdFileCfg, **kwargs: Any) -> Usd.Prim: + """Preserve fixture visuals while using solid collision hulls and thin planar proxies.""" + import numpy as np + + from isaaclab.sim import clone, spawn_from_usd + from isaaclab.sim.schemas import UsdPhysicsMeshCollisionCfg, apply_mesh_collision_properties + from pxr import Gf, Usd, UsdGeom, UsdPhysics + + @clone + def spawn(prim_path, cfg, **kwargs): + """Spawn fixture collision proxies while retaining the original visual meshes.""" + root = spawn_from_usd(prim_path, cfg, **kwargs) + meshes = [ + prim + for prim in Usd.PrimRange(root) + if prim.IsA(UsdGeom.Mesh) + and prim.HasAPI(UsdPhysics.CollisionAPI) + and UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Get() + ] + assert meshes, f"The fixture {prim_path} must contain collision meshes." + xforms = UsdGeom.XformCache() + meters_per_unit = UsdGeom.GetStageMetersPerUnit(root.GetStage()) + planar_count = 0 + for prim in meshes: + points = UsdGeom.Mesh(prim).GetPointsAttr().Get() + assert points is not None and len(points) >= 3, f"Missing fixture mesh points {prim.GetPath()}." + transform = xforms.GetLocalToWorldTransform(prim) + assert transform.GetDeterminant() != 0, f"Singular fixture transform {prim.GetPath()}." + vertices = np.asarray([transform.Transform(Gf.Vec3d(point)) for point in points], dtype=np.float64) + vertices *= meters_per_unit + axes = np.linalg.svd(vertices - vertices.mean(axis=0), full_matrices=False)[2] + axes[-1] *= np.sign(np.linalg.det(axes)) + projected = vertices @ axes.T + lower, upper = projected.min(axis=0), projected.max(axis=0) + size = upper - lower + if size.min() < max(2e-6 * np.linalg.norm(size), 1e-8): + # MuJoCo requires volume; retain thin fixture surfaces with 0.5 mm box colliders. + box = UsdGeom.Cube.Define(root.GetStage(), prim.GetPath().AppendChild("collision_box")) + box.CreateSizeAttr(1.0) + box.CreateVisibilityAttr(UsdGeom.Tokens.invisible) + dimensions = np.maximum(size, 0.0005) / meters_per_unit + box_world = np.eye(4) + box_world[:3, :3] = axes * dimensions[:, None] + box_world[3, :3] = ((lower + upper) * 0.5) @ axes / meters_per_unit + # USD composes row-vector transforms; preserve the exact source mesh frame. + box_local = Gf.Matrix4d(*box_world.ravel().tolist()) * transform.GetInverse() + # Keep physical extents explicit for the planner's USD primitive reader. + scale = Gf.Matrix4d(1.0) + scale.SetScale(Gf.Vec3d(*dimensions)) + box_xform = UsdGeom.Xformable(box) + box_xform.AddTransformOp().Set(scale.GetInverse() * box_local) + box_xform.AddScaleOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Vec3d(*dimensions)) + assert np.allclose( + np.asarray(xforms.GetLocalToWorldTransform(box.GetPrim())), box_world, atol=1e-8, rtol=1e-8 + ), f"Fixture proxy transform mismatch {prim.GetPath()}." + UsdPhysics.CollisionAPI.Apply(box.GetPrim()).CreateCollisionEnabledAttr(True) + UsdPhysics.CollisionAPI(prim).CreateCollisionEnabledAttr(False) + planar_count += 1 + continue + applied = apply_mesh_collision_properties( + str(prim.GetPath()), + [UsdPhysicsMeshCollisionCfg(mesh_approximation_name="convexHull")], + stage=root.GetStage(), + ) + assert applied, f"Could not configure fixture collider {prim.GetPath()}." + print(f"[INFO]: Newton fixture {prim_path} uses {len(meshes)} solid colliders ({planar_count} thin boxes).") + return root + + return spawn(prim_path, cfg, **kwargs) + + +def _configure_robot_newton(robot: ArticulationCfg) -> None: + """Configure the GR1T2 hands and mimic joints for Newton. + + Args: + robot: Robot configuration to update before spawning. + """ + robot.spawn.func = _robot_spawn_newton + robot.spawn.make_uninstanceable = True + # Compliant drives avoid fighting the finger contact and mimic constraints. + driven = "[LR]_((index|middle|pinky|ring)_proximal|thumb_proximal_(yaw|pitch))_joint" + passive = "[LR]_((index|middle|pinky|ring)_intermediate|thumb_distal)_joint" + for name in ("left-hand", "right-hand"): + hand = robot.actuators[name] + hand.armature = 2e-4 + hand.stiffness = {driven: 174.53292, passive: 0.0} + hand.damping = {driven: 5.5848, passive: 0.0} + + +def _configure_newton(config: NutPourGR1T2PinkIKEnvCfg) -> None: + """Apply Newton solver, robot and fixture settings without changing control timing. + + Args: + config: Nut-pouring environment configuration with the Newton preset selected. + """ + # Resolve hand contacts at 0.1 ms without changing the control period. + config.sim.physics.num_substeps = 100 + # The humanoid scene exceeds Arena's small-hand contact budget. + config.sim.physics.solver_cfg.nconmax = 2048 + config.sim.physics.solver_cfg.njmax = 8192 + config.sim.physics.solver_cfg.use_mujoco_contacts = True + config.sim.physics.solver_cfg.ccd_iterations = 35 + # Resolve the small finger/object contacts at a 2 ms response time. + config.sim.physics.default_shape_cfg.ke = 2.5e5 + config.sim.physics.default_shape_cfg.kd = 1000.0 + _configure_robot_newton(config.scene.robot) + for fixture in (config.scene.table, config.scene.sorting_scale): + fixture.spawn.func = _fixture_spawn_newton + fixture.spawn.make_uninstanceable = True + + +def _environment_config(physics_backend: str, env_profile: str | None = None) -> NutPourGR1T2PinkIKEnvCfg: + """Create the existing nut-pouring task with the selected Arena physics preset. + + Args: + physics_backend: Physics preset, either ``physx`` or ``newton``. + env_profile: Optional AutoData environment profile, including when recording with Isaac Lab tools. + + Returns: + Task configuration with backend-specific settings applied. + """ + from isaaclab_arena.environments.isaaclab_arena_manager_based_env_cfg import ArenaPhysicsCfg + from isaaclab_tasks.contrib.pick_place.nutpour_gr1t2_pink_ik_env_cfg import NutPourGR1T2PinkIKEnvCfg + + from autodata_interfaces.env import EnvironmentProfile, apply_env_profile + from autodata_interfaces.env.pink_ik_action import PinkInverseKinematicsActionSharedUrdf + + config = NutPourGR1T2PinkIKEnvCfg() + # The table is a fixed fixture, not a dynamic object included in episode resets. + config.scene.table.spawn.rigid_props.kinematic_enabled = True + config.actions.gr1_action.class_type = PinkInverseKinematicsActionSharedUrdf + config.sim.physics = getattr(ArenaPhysicsCfg(), physics_backend) + if physics_backend == "newton": + _configure_newton(config) + if env_profile is not None: + apply_env_profile(config, EnvironmentProfile.from_yaml(env_profile), ENV_NAME) + return config + + +def register() -> list[str]: + """Register the example through AutoData's external-environment callback. + + The callback runs after simulator startup. ``--physics_backend`` selects Arena's PhysX or + Newton preset; the task's existing control period and source annotations remain applicable. + + Returns: + Arguments not consumed by this callback. + """ + import gymnasium as gym + + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--task", required=True) + parser.add_argument("--device", default="cpu") + parser.add_argument("--num_envs", type=int, default=1) + parser.add_argument("--enable_cameras", action="store_true") + parser.add_argument("--physics_backend", choices=("physx", "newton"), default="physx") + parser.add_argument("--env_profile", default=None) + args, remaining = parser.parse_known_args() + assert args.task == ENV_NAME, f"This callback registers only {ENV_NAME}." + + def environment_config() -> NutPourGR1T2PinkIKEnvCfg: + """Build the selected config through Isaac Lab's function-based registry.""" + return _environment_config(args.physics_backend, args.env_profile) + + gym.register( + id=ENV_NAME, + entry_point="isaaclab.envs:ManagerBasedRLEnv", + kwargs={"env_cfg_entry_point": environment_config}, + disable_env_checker=True, + ) + return remaining diff --git a/autodata_examples/task_diagnostics.py b/autodata_examples/task_diagnostics.py new file mode 100644 index 0000000..13b0bfc --- /dev/null +++ b/autodata_examples/task_diagnostics.py @@ -0,0 +1,110 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Task-specific attempt diagnostics for shipped examples.""" + +from __future__ import annotations + +import inspect +import torch +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from isaaclab.managers import TerminationTermCfg + + from autodata_interfaces.datastream.datastream import Datastream + + +def _term_parameter(success_term: TerminationTermCfg, name: str) -> Any: + """Return an effective termination parameter, including callable defaults.""" + + if name in success_term.params: + return success_term.params[name] + parameter = inspect.signature(success_term.func).parameters.get(name) + assert ( + parameter is not None and parameter.default is not inspect.Parameter.empty + ), f"success term {success_term.func.__name__!r} has no value for {name!r}" + return parameter.default + + +def _vector_format(vector: torch.Tensor) -> str: + """Format a vector as comma-separated scalar diagnostic values.""" + return ",".join(f"{float(value):.6f}" for value in vector) + + +def gr1t2_nut_pour_attempt_diagnostics( + datastream: Datastream, env_id: int, success_term: TerminationTermCfg +) -> tuple[tuple[str, str], ...]: + """Report exact terminal components of the GR1T2 nut-pour success predicate. + + The predicate's vertical deltas are deliberately signed to match the Isaac Lab task. Absolute + object positions are also recorded so one-sided vertical checks cannot hide a dropped object. + + Args: + datastream: Bound AutoData datastream providing env-relative object poses. + env_id: Vectorized environment index. + success_term: Isaac Lab termination term whose effective defaults define the thresholds. + + Returns: + Stable string diagnostics suitable for an attempt result sidecar. + """ + + object_poses = datastream.get_object_poses(env_ids=[env_id]) + object_parameters = { + "sorting_scale": "sorting_scale_cfg", + "sorting_bowl": "sorting_bowl_cfg", + "sorting_beaker": "sorting_beaker_cfg", + "factory_nut": "factory_nut_cfg", + "sorting_bin": "sorting_bin_cfg", + } + positions = { + label: object_poses[_term_parameter(success_term, parameter).name][0, :3, 3] + for label, parameter in object_parameters.items() + } + relations = ( + ( + "nut_in_bowl", + "nut_to_bowl", + "factory_nut", + "sorting_bowl", + ("max_nut_to_bowl_x", "max_nut_to_bowl_y", "max_nut_to_bowl_z"), + ), + ( + "bowl_on_scale", + "bowl_to_scale", + "sorting_bowl", + "sorting_scale", + ("max_bowl_to_scale_x", "max_bowl_to_scale_y", "max_bowl_to_scale_z"), + ), + ( + "beaker_in_bin", + "beaker_to_bin", + "sorting_beaker", + "sorting_bin", + ("max_beaker_to_bin_x", "max_beaker_to_bin_y", "max_beaker_to_bin_z"), + ), + ) + + diagnostics: list[tuple[str, str]] = [] + for component, relation, subject, reference, threshold_names in relations: + displacement = positions[subject] - positions[reference] + delta = torch.stack((displacement[0].abs(), displacement[1].abs(), displacement[2])) + limits = torch.tensor( + [_term_parameter(success_term, name) for name in threshold_names], + device=delta.device, + dtype=delta.dtype, + ) + passed = bool(torch.all(delta < limits).item()) + diagnostics.extend(( + (f"final_{component}", str(passed).lower()), + (f"final_{relation}_delta_m", _vector_format(delta)), + (f"final_{relation}_limit_m", _vector_format(limits)), + )) + + task_success = bool(success_term.func(datastream.get_env(), **success_term.params)[env_id].item()) + diagnostics.append(("final_task_success", str(task_success).lower())) + diagnostics.extend((f"final_{label}_position_m", _vector_format(position)) for label, position in positions.items()) + return tuple(diagnostics) + + +__all__ = ["gr1t2_nut_pour_attempt_diagnostics"] diff --git a/autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml b/autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml new file mode 100644 index 0000000..5716115 --- /dev/null +++ b/autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml @@ -0,0 +1,239 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: gr1t2_nut_pour_schedulegen +description: GR1T2 pours nuts into a bowl, then places the bowl on the scale. +algo: schedulegen +attempt_diagnostics: autodata_examples.task_diagnostics:gr1t2_nut_pour_attempt_diagnostics + +generation_policy: + name: gr1t2_nut_pour_schedulegen + seed: 10 + num_trials: 10 + guarantee_success: true + max_num_failures: 25 + keep_failed: true + use_skillgen: true + select_src_per_subtask: false + select_src_per_arm: false + source_selection_anchor: right.grasp_bowl + source_candidate_count: 3 + transform_first_robot_pose: false + interpolate_from_last_target_pose: true + skill_passthrough_delay_steps: 8 + skill_passthrough_interpolation_steps: 4 + max_joint_step_rad: 0.1 + final_hold_steps: 2 + terminal_convergence_steps: 10 + +subtasks: + left: + - name: grasp_beaker + object_ref: sorting_beaker + description: Grasp the beaker with the left hand. + subtask_start_signal: grasp_left + subtask_term_signal: grasp_left + subtask_term_offset_range: [0, 0] + selection_strategy: nearest_neighbor_object + selection_strategy_kwargs: {nn_k: 3} + num_interpolation_steps: 5 + segments: + - name: transit + kind: transit + provider: motion_planner + goal_segment_id: left.grasp_beaker.skill + - name: skill + kind: skill + provider: demonstration + events: + - event_type: attach + object_ref: sorting_beaker + point: source_annotation + annotation_key: beaker_grasp + attachment_frame: left_hand_pitch_link + + - name: pour_and_clear + object_ref: sorting_bowl + description: Pour into the bowl and move the beaker safely clear. + subtask_start_signal: pour_left + subtask_term_signal: pour_clear_left + selection_strategy: nearest_neighbor_object + selection_strategy_kwargs: {nn_k: 3} + num_interpolation_steps: 0 + segments: + - name: transit + kind: transit + provider: motion_planner + goal_segment_id: left.pour_and_clear.skill + - name: skill + kind: skill + provider: demonstration + + - name: release_beaker + object_ref: black_sorting_bin + description: Return the attached beaker to the bin and release it. + subtask_start_signal: beaker_release_start + selection_strategy: nearest_neighbor_object + selection_strategy_kwargs: {nn_k: 3} + num_interpolation_steps: 0 + segments: + - name: transit + kind: transit + provider: motion_planner + goal_segment_id: left.release_beaker.skill + - name: skill + kind: skill + provider: demonstration + demonstration_source_window: + anchor_annotation_key: beaker_release + post_event_sample_count: 2 + world_contacts: + - object_ref: sorting_beaker + fixture_ref: black_sorting_bin + robot_contacts: + - object_ref: sorting_beaker + robot_link_names: &left_beaker_release_links + - L_index_intermediate_link + - L_index_proximal_link + - L_middle_intermediate_link + - L_middle_proximal_link + - L_pinky_intermediate_link + - L_pinky_proximal_link + - L_ring_intermediate_link + - L_ring_proximal_link + - L_thumb_distal_link + - L_thumb_proximal_base_link + - L_thumb_proximal_link + - left_hand_pitch_link + start_annotation_key: beaker_release + events: + - event_type: detach + object_ref: sorting_beaker + point: source_annotation + annotation_key: beaker_release + - name: open_hold + kind: hold + provider: scripted + duration_steps: 10 + passthrough_preset: open + world_contacts: + - object_ref: sorting_beaker + fixture_ref: black_sorting_bin + robot_contacts: + - object_ref: sorting_beaker + robot_link_names: *left_beaker_release_links + right: + - name: grasp_bowl + object_ref: sorting_bowl + description: Grasp the bowl with the right hand after pouring finishes. + subtask_start_signal: grasp_right + subtask_term_signal: grasp_right + subtask_term_offset_range: [0, 0] + selection_strategy: nearest_neighbor_object + selection_strategy_kwargs: {nn_k: 3} + num_interpolation_steps: 3 + segments: + - name: transit + kind: transit + provider: motion_planner + goal_segment_id: right.grasp_bowl.skill + - name: skill + kind: skill + provider: demonstration + events: + - event_type: attach + object_ref: sorting_bowl + point: source_annotation + annotation_key: bowl_grasp + attachment_frame: right_hand_pitch_link + + - name: place_bowl + object_ref: sorting_scale + description: Place and release the bowl on the scale. + subtask_start_signal: place_bowl_on_scale_right + algo_params: + subtask_start_offset_range: [0, 0] + selection_strategy: nearest_neighbor_object + selection_strategy_kwargs: {nn_k: 3} + num_interpolation_steps: 3 + segments: + - name: transit + kind: transit + provider: motion_planner + goal_segment_id: right.place_bowl.skill + - name: skill + kind: skill + provider: demonstration + demonstration_source_window: + anchor_annotation_key: bowl_release + post_event_sample_count: 2 + world_contacts: + - object_ref: sorting_bowl + fixture_ref: sorting_scale + robot_contacts: + - object_ref: sorting_bowl + robot_link_names: &right_bowl_release_links + - R_index_intermediate_link + - R_index_proximal_link + - R_middle_intermediate_link + - R_middle_proximal_link + - R_pinky_intermediate_link + - R_pinky_proximal_link + - R_ring_intermediate_link + - R_ring_proximal_link + - R_thumb_distal_link + - R_thumb_proximal_base_link + - R_thumb_proximal_link + - right_hand_pitch_link + start_annotation_key: bowl_release + events: + - event_type: detach + object_ref: sorting_bowl + point: source_annotation + annotation_key: bowl_release + - name: open_hold + kind: hold + provider: scripted + duration_steps: 10 + passthrough_preset: open + world_contacts: + - object_ref: sorting_bowl + fixture_ref: sorting_scale + robot_contacts: + - object_ref: sorting_bowl + robot_link_names: *right_bowl_release_links + - name: clearance + kind: transit + provider: scripted + duration_steps: 10 + passthrough_preset: open + cartesian_offset_m: [0.0, 0.0, 0.05] + world_contacts: + - object_ref: sorting_bowl + fixture_ref: sorting_scale + robot_contacts: + - object_ref: sorting_bowl + robot_link_names: *right_bowl_release_links + clear_at_end: true +schedule: + strategy: waypoint_retiming + collision_margin_m: 0.0 + time_limit_s: 15.0 + constraints: + - type: precedence + before: left.pour_and_clear.skill.end + after: right.grasp_bowl.transit.start + min_lag_steps: 0 + - type: non_preemptive + segments: + - left.release_beaker.transit + - left.release_beaker.skill + - left.release_beaker.open_hold + - type: non_preemptive + segments: + - right.grasp_bowl.transit + - right.grasp_bowl.skill + - right.place_bowl.transit + - right.place_bowl.skill + - right.place_bowl.open_hold + - right.place_bowl.clearance diff --git a/autodata_interfaces/datastream/datastream.py b/autodata_interfaces/datastream/datastream.py index f92f001..1080bee 100644 --- a/autodata_interfaces/datastream/datastream.py +++ b/autodata_interfaces/datastream/datastream.py @@ -14,7 +14,10 @@ from autodata_core.pool import DataGenInfoPool from autodata_interfaces.embodiments.embodiment_adapter import EmbodimentAdapter from autodata_interfaces.embodiments.embodiment_types import ActionTargetFrame, NamedJointTrajectory +from autodata_interfaces.env.scene_state import get_scene_state from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy +from autodata_interfaces.tasks.schedule_constraint_spec import ScheduleSpec, SegmentId +from autodata_interfaces.tasks.segment_spec import SegmentRobotContactSpec, SegmentWorldContactSpec from autodata_interfaces.tasks.subtask_constraint_spec import SubtaskConstraint from autodata_interfaces.tasks.subtask_spec import Subtask, SubtaskAlgoParams from autodata_interfaces.tasks.task_descriptor import TaskDescriptor @@ -76,7 +79,7 @@ def __init__( asyncio_lock: asyncio.Lock | None = None, uses_start_signals: bool = False, ) -> None: - """Compose the three sources and build (or adopt) the source-demo pool. + """Compose the runtime interfaces and build or adopt the source-demo pool. Args: env: Simulation environment. @@ -85,16 +88,14 @@ def __init__( source_pool: A pre-built DataGenInfoPool to use. Mutually exclusive with ``source_dataset_path``. source_dataset_path: HDF5 path to load source demos from. Mutually exclusive with - ``source_pool``. + ``source_pool``. Both may be omitted when the task has no demonstration segments; + an empty pool is then created for the existing generation pipeline. asyncio_lock: (Optional) Lock guarding concurrent pool growth across async env tasks. Pass ``None`` (the default) for static pools that are fully loaded before generation starts (no locking overhead is incurred). select_demo_keys: (Optional) Subset of episode keys to load when reading from HDF5. - uses_start_signals: (For SkillGen) Whether the algorithm reads subtask start signals. + uses_start_signals: Whether the algorithm reads explicit skill starts (SkillGen and ScheduleGen). """ - # TODO: Decide on if uses_start_signals parameter should be refactored. Keeping it explicit for now as it's - # needed for DataGenInfoPool construction. - self.env = env self.task_descriptor = task_descriptor self.embodiment_adapter = embodiment_adapter @@ -122,12 +123,12 @@ def __init__( task_descriptor.validate_embodiment(embodiment_adapter) # Initialize the source-demo pool. - assert (source_pool is None) != ( - source_dataset_path is None - ), "Must provide exactly one of source_pool or source_dataset_path." + assert ( + source_pool is None or source_dataset_path is None + ), "source_pool and source_dataset_path are mutually exclusive" if source_pool is not None: self._pool = source_pool - else: + elif source_dataset_path is not None: self._pool = DataGenInfoPool.from_hdf5( file_path=source_dataset_path, task_descriptor=task_descriptor, @@ -137,6 +138,17 @@ def __init__( select_demo_keys=select_demo_keys, asyncio_lock=asyncio_lock, ) + else: + assert ( + not task_descriptor.requires_source_demos() + ), "task descriptor requires source demonstrations; provide source_pool or source_dataset_path" + self._pool = DataGenInfoPool( + task_descriptor=task_descriptor, + embodiment_adapter=embodiment_adapter, + device=env.device, + uses_start_signals=uses_start_signals, + asyncio_lock=asyncio_lock, + ) @property def device(self) -> torch.device: @@ -158,6 +170,15 @@ def get_eef_names(self) -> list[str]: return self.task_descriptor.get_eef_names() + def get_path_build_order(self) -> tuple[str, ...]: + """Return the path-building order required by cross-arm object-pose dependencies. + + Returns: + End-effector names ordered so each object-pose producer is built before its consumers. + """ + + return self.task_descriptor.get_path_build_order() + # ------------------------------------------------------------------ # Task queries # ------------------------------------------------------------------ @@ -182,6 +203,26 @@ def get_task_constraints(self) -> list[SubtaskConstraint]: return self.task_descriptor.get_task_constraints() + def get_schedule_spec(self) -> ScheduleSpec | None: + """Return the task's immutable segment-level schedule policy.""" + + return self.task_descriptor.get_schedule_spec() + + def get_segment_world_contacts(self) -> dict[SegmentId, tuple[SegmentWorldContactSpec, ...]]: + """Return task-defined object/fixture contacts keyed by scheduled segment.""" + + return self.task_descriptor.get_segment_world_contacts() + + def get_segment_robot_contacts(self) -> dict[SegmentId, tuple[SegmentRobotContactSpec, ...]]: + """Return task-defined robot/object contacts keyed by scheduled segment.""" + + return self.task_descriptor.get_segment_robot_contacts() + + def get_segment_resource_ids(self) -> dict[SegmentId, tuple[str, ...]]: + """Return additional task-local resource claims keyed by scheduled segment.""" + + return self.task_descriptor.get_segment_resource_ids() + def get_generation_policy(self) -> GenerationPolicy: """Return the cross-cutting generation flags (source-demo selection, interpolation seeding).""" @@ -575,15 +616,19 @@ def get_robot_planning_root_pose( assert poses.ndim == 3 and poses.shape[1:] == (4, 4), "planning-root poses must have shape (N, 4, 4)" return poses - def get_scene_state(self, is_relative: bool = True) -> dict: + def get_scene_state(self, is_relative: bool = True, env_ids: Sequence[int] | None = None) -> dict: """Return the raw scene-state snapshot from the underlying env. Used by the data generator to record the env's initial state at episode start. Prefer :meth:`get_object_poses` for object pose math; this method is the raw scene-state escape hatch for callers that need the full dict (e.g. recorder ``initial_state``). + + Args: + is_relative: Whether root positions are relative to environment origins. + env_ids: Environment rows to copy, or None to return the full native state. """ - return self.env.scene.get_state(is_relative=is_relative) + return get_scene_state(self.env.scene, is_relative=is_relative, env_ids=env_ids) # ------------------------------------------------------------------ # Collision-world source diff --git a/autodata_interfaces/env/__init__.py b/autodata_interfaces/env/__init__.py index b4a6d71..044da47 100644 --- a/autodata_interfaces/env/__init__.py +++ b/autodata_interfaces/env/__init__.py @@ -3,7 +3,7 @@ """Data generation interfaces for Isaac Lab environments.""" -from autodata_interfaces.env.env_profile import EnvironmentProfile +from autodata_interfaces.env.env_profile import CameraOverrideSpec, EnvironmentProfile, ViewerOverrideSpec from autodata_interfaces.env.isaaclab_env_interface import ( apply_env_profile, collect_autodata_entry, @@ -12,15 +12,25 @@ setup_env_config, setup_output_paths, ) +from autodata_interfaces.env.observation_render_wrapper import ( + ObservationRenderWrapper, + ViewportRenderWrapper, + observation_video_path_resolve, +) from autodata_interfaces.env.reset_request import EnvResetRequest __all__ = [ + "CameraOverrideSpec", "EnvironmentProfile", "EnvResetRequest", + "ObservationRenderWrapper", + "ViewportRenderWrapper", + "ViewerOverrideSpec", "apply_env_profile", "get_env_name_from_dataset", "setup_output_paths", "env_loop", "collect_autodata_entry", + "observation_video_path_resolve", "setup_env_config", ] diff --git a/autodata_interfaces/env/env_profile.py b/autodata_interfaces/env/env_profile.py index 937f358..b875609 100644 --- a/autodata_interfaces/env/env_profile.py +++ b/autodata_interfaces/env/env_profile.py @@ -3,7 +3,7 @@ """Declarative environment-profile schema for base-task variants. -An :class:`EnvironmentProfile` describes scene changes, event-term changes, and the +An :class:`EnvironmentProfile` describes viewport, scene, event, and controller changes plus the motion-planner profile of a task variant. It is overlaid on the parsed env config before ``gym.make`` by :func:`~autodata_interfaces.env.isaaclab_env_interface.apply_env_profile`; this module holds only the schema and its validation and does not import ``isaaclab``. @@ -11,11 +11,15 @@ from __future__ import annotations +import math import yaml from dataclasses import dataclass, field, fields +from pathlib import Path from typing import Any +_CAMERA_CONVENTIONS = {"opengl", "ros", "world"} _EVENT_MODES = {"startup", "reset", "interval"} +_VIEWER_ORIGIN_TYPES = {"world", "env", "asset_root", "asset_body"} @dataclass(kw_only=True) @@ -50,8 +54,14 @@ class RigidObjectOverrideSpec: Entries under ``scene.rigid_objects.override`` map an existing scene-asset name to this spec. """ + position: tuple[float, float, float] | None = None + """Optional replacement initial root position in the env frame [m].""" + scale: tuple[float, float, float] | None = None + """Optional replacement spawn scale per axis.""" rigid_props: dict[str, Any] = field(default_factory=dict) """Overrides merged into the asset's spawn ``RigidBodyPropertiesCfg`` fields.""" + physics_material: dict[str, float] | None = None + """Optional solver-common ``UsdPhysicsRigidBodyMaterialCfg`` spawn properties.""" @dataclass(kw_only=True) @@ -66,11 +76,62 @@ class RigidObjectsSpec: override: dict[str, RigidObjectOverrideSpec] = field(default_factory=dict) +@dataclass(kw_only=True) +class CameraOverrideSpec: + """A pose and optional optical-property patch for an existing scene camera. + + Entries under ``scene.cameras.override`` map an existing scene-camera name to this spec. + The pose is relative to the camera prim's parent, which is the environment frame for cameras + spawned directly below ``{ENV_REGEX_NS}``. + """ + + position: tuple[float, float, float] + """Camera position relative to its parent frame [m].""" + rotation_xyzw: tuple[float, float, float, float] + """Unit quaternion ``(x, y, z, w)`` relative to the parent frame.""" + prim_path: str | None = None + """Optional replacement sensor prim path, used to reparent the existing camera.""" + convention: str = "ros" + """Isaac Lab camera convention: ``ros``, ``opengl``, or ``world``.""" + clipping_range: tuple[float, float] | None = None + """Optional near and far clipping distances [m].""" + focal_length: float | None = None + """Optional pinhole-camera focal length [mm].""" + width: int | None = None + """Optional image width [px]; provided together with :attr:`height`.""" + height: int | None = None + """Optional image height [px]; provided together with :attr:`width`.""" + + +@dataclass(kw_only=True) +class CamerasSpec: + """Camera changes relative to the base task.""" + + override: dict[str, CameraOverrideSpec] = field(default_factory=dict) + + +@dataclass(kw_only=True) +class ViewerOverrideSpec: + """A pose and tracking-frame patch for the environment viewport camera.""" + + eye: tuple[float, float, float] + """Camera position relative to :attr:`origin_type` [m].""" + lookat: tuple[float, float, float] + """Camera target relative to :attr:`origin_type` [m].""" + origin_type: str = "world" + """Tracking frame: ``world``, ``env``, ``asset_root``, or ``asset_body``.""" + asset_name: str | None = None + """Scene asset tracked by ``asset_root`` or ``asset_body`` origins.""" + body_name: str | None = None + """Asset body tracked by an ``asset_body`` origin.""" + + @dataclass(kw_only=True) class SceneSpec: - """Scene changes relative to the base task; currently rigid objects only.""" + """Scene changes relative to the base task.""" rigid_objects: RigidObjectsSpec = field(default_factory=RigidObjectsSpec) + cameras: CamerasSpec = field(default_factory=CamerasSpec) @dataclass(kw_only=True) @@ -114,6 +175,61 @@ class EventsSpec: add: dict[str, EventAddSpec] = field(default_factory=dict) +@dataclass(kw_only=True) +class PinkIKFrameTaskOverrideSpec: + """Objective weights for one Pink IK frame task, selected by exact frame name.""" + + position_cost: float + """Position-error cost.""" + orientation_cost: float + """Orientation-error cost.""" + lm_damping: float + """Levenberg-Marquardt damping.""" + gain: float + """Task gain.""" + + +@dataclass(kw_only=True) +class PinkIKDampingTaskOverrideSpec: + """Objective weight for the unique Pink IK damping task.""" + + cost: float + """Joint-velocity damping cost.""" + + +@dataclass(kw_only=True) +class PinkIKNullSpacePostureTaskOverrideSpec: + """Objective weights for the unique Pink IK null-space posture task.""" + + cost: float + """Posture regularization cost.""" + lm_damping: float + """Levenberg-Marquardt damping.""" + + +@dataclass(kw_only=True) +class PinkIKControlOverrideSpec: + """Task-objective changes for one existing Pink IK action term.""" + + action_term: str + """Attribute name of the action term on the environment actions config.""" + additional_joint_names: tuple[str, ...] = () + """Additional articulation joints controlled by the existing Pink action term.""" + frame_tasks: dict[str, PinkIKFrameTaskOverrideSpec] = field(default_factory=dict) + """Frame name to objective-weight override.""" + damping_task: PinkIKDampingTaskOverrideSpec | None = None + """Optional override for the unique damping task.""" + null_space_posture_task: PinkIKNullSpacePostureTaskOverrideSpec | None = None + """Optional override for the unique null-space posture task.""" + + +@dataclass(kw_only=True) +class ControlSpec: + """Controller changes relative to the base task.""" + + pink_ik: PinkIKControlOverrideSpec | None = None + + @dataclass(kw_only=True) class EnvironmentProfile: """Declarative overlay for a base task's parsed env config. @@ -122,9 +238,11 @@ class EnvironmentProfile: name: Profile name, recorded in the generation-result sidecar. description: Human-readable summary of the variant. base_env: Env id the profile is written against; must equal the id used at apply time. + viewer: Optional viewport pose and tracking-frame override. scene: Scene changes (:class:`SceneSpec`). events: Event-term changes (:class:`EventsSpec`). actions: Parameter overrides for existing action terms. + control: Controller changes (:class:`ControlSpec`). planner: Name of the motion-planner profile tuned for this scene (key into :meth:`CuroboPlannerCfg.from_profile`), or None to fall back to task-name matching. """ @@ -132,8 +250,10 @@ class EnvironmentProfile: name: str base_env: str description: str = "" + viewer: ViewerOverrideSpec | None = None scene: SceneSpec = field(default_factory=SceneSpec) events: EventsSpec = field(default_factory=EventsSpec) + control: ControlSpec = field(default_factory=ControlSpec) planner: str | None = None actions: dict[str, dict[str, Any]] = field(default_factory=dict) """Action-term parameter overrides, applied before the action manager is built.""" @@ -153,6 +273,12 @@ def from_yaml(cls, path: str) -> EnvironmentProfile: planner: # optional actions: # optional : {: } + viewer: # optional + eye: [x, y, z] # [m], relative to origin + lookat: [x, y, z] # [m], relative to origin + origin_type: asset_body # world, env, asset_root, asset_body + asset_name: robot # required for asset origins + body_name: base_link # required for asset_body scene: # optional rigid_objects: add: @@ -165,7 +291,20 @@ def from_yaml(cls, path: str) -> EnvironmentProfile: rigid_props: {: } # optional override: : + position: [x, y, z] # optional initial root position [m] + scale: [x, y, z] # optional spawn scale rigid_props: {: } + cameras: + override: + : + position: [x, y, z] # [m], relative to parent + rotation_xyzw: [x, y, z, w] # unit quaternion + prim_path: "{ENV_REGEX_NS}/ValidationCam" # optional + convention: ros # ros, opengl, or world + clipping_range: [near, far] # optional [m] + focal_length: 18.15 # optional [mm] + width: 512 # optional, with height [px] + height: 320 events: # optional remove: [, ...] override: @@ -175,10 +314,21 @@ def from_yaml(cls, path: str) -> EnvironmentProfile: func: ":" mode: reset # optional params: {...} # *_cfg/*_cfgs values name scene assets + control: # optional + pink_ik: + action_term: gr1_action + frame_tasks: + : + position_cost: 30.0 + orientation_cost: 5.0 + lm_damping: 50.0 + gain: 0.08 + damping_task: {cost: 0.1} # optional + null_space_posture_task: # optional + cost: 0.1 + lm_damping: 50.0 """ - with open(path) as f: - data = yaml.safe_load(f) - return cls.from_dict(data) + return cls.from_dict(_profile_data_load(Path(path).expanduser().resolve())) @classmethod def from_dict(cls, data: dict[str, Any]) -> EnvironmentProfile: @@ -190,6 +340,7 @@ def from_dict(cls, data: dict[str, Any]) -> EnvironmentProfile: validate_profile_dict(data) objects_data = data.get("scene", {}).get("rigid_objects", {}) + cameras_data = data.get("scene", {}).get("cameras", {}) scene = SceneSpec( rigid_objects=RigidObjectsSpec( add={ @@ -197,9 +348,16 @@ def from_dict(cls, data: dict[str, Any]) -> EnvironmentProfile: for name, spec in objects_data.get("add", {}).items() }, override={ - name: RigidObjectOverrideSpec(**spec) for name, spec in objects_data.get("override", {}).items() + name: RigidObjectOverrideSpec(**_coerce_vector_fields(spec)) + for name, spec in objects_data.get("override", {}).items() }, - ) + ), + cameras=CamerasSpec( + override={ + name: CameraOverrideSpec(**_coerce_camera_vector_fields(spec)) + for name, spec in cameras_data.get("override", {}).items() + } + ), ) events_data = data.get("events", {}) @@ -209,12 +367,37 @@ def from_dict(cls, data: dict[str, Any]) -> EnvironmentProfile: add={name: EventAddSpec(**spec) for name, spec in events_data.get("add", {}).items()}, ) + control_data = data.get("control", {}) + pink_ik_data = control_data.get("pink_ik") + pink_ik = None + if pink_ik_data is not None: + damping_data = pink_ik_data.get("damping_task") + null_space_data = pink_ik_data.get("null_space_posture_task") + pink_ik = PinkIKControlOverrideSpec( + action_term=pink_ik_data["action_term"], + additional_joint_names=tuple(pink_ik_data.get("additional_joint_names", ())), + frame_tasks={ + frame_name: PinkIKFrameTaskOverrideSpec(**spec) + for frame_name, spec in pink_ik_data.get("frame_tasks", {}).items() + }, + damping_task=PinkIKDampingTaskOverrideSpec(**damping_data) if damping_data is not None else None, + null_space_posture_task=( + PinkIKNullSpacePostureTaskOverrideSpec(**null_space_data) if null_space_data is not None else None + ), + ) + return cls( name=data["name"], description=data.get("description", ""), base_env=data["base_env"], + viewer=( + ViewerOverrideSpec(**_coerce_viewer_vector_fields(data["viewer"])) + if data.get("viewer") is not None + else None + ), scene=scene, events=events, + control=ControlSpec(pink_ik=pink_ik), planner=data.get("planner"), actions=data.get("actions", {}), ) @@ -237,7 +420,7 @@ def validate_profile_dict(data: dict[str, Any]) -> None: assert isinstance(data, dict), f"Expected top-level dict, got {type(data).__name__}" required_keys = {"name", "base_env"} - optional_keys = {"description", "planner", "scene", "events", "actions"} + optional_keys = {"description", "planner", "viewer", "scene", "events", "control", "actions"} keys = set(data) missing = required_keys - keys assert not missing, f"Missing required top-level keys: {sorted(missing)}" @@ -252,6 +435,7 @@ def validate_profile_dict(data: dict[str, Any]) -> None: planner = data.get("planner") assert planner is None or isinstance(planner, str), f"'planner' must be a string, got {type(planner).__name__}" + _validate_viewer_dict(data.get("viewer")) _validate_scene_dict(data.get("scene", {})) _validate_events_dict(data.get("events", {})) actions = data.get("actions", {}) @@ -260,9 +444,43 @@ def validate_profile_dict(data: dict[str, Any]) -> None: isinstance(name, str) and isinstance(params, dict) and all(isinstance(key, str) for key in params) for name, params in actions.items() ), "Each action override must map a term name to a parameter dict with string keys." + _validate_control_dict(data.get("control", {})) + + +def _validate_viewer_dict(viewer: Any) -> None: + """Validate viewport placement and the frame used for its origin.""" + if viewer is None: + return + assert isinstance(viewer, dict), f"'viewer' must be a dict, got {type(viewer).__name__}" + viewer_keys = {f.name for f in fields(ViewerOverrideSpec)} + required_keys = {"eye", "lookat"} + missing = required_keys - set(viewer) + assert not missing, f"'viewer' missing required keys: {sorted(missing)}" + unknown = set(viewer) - viewer_keys + assert not unknown, f"'viewer' has unknown keys {sorted(unknown)}. Allowed: {sorted(viewer_keys)}" + + _validate_numeric_vector(viewer["eye"], length=3, label="viewer.eye") + _validate_numeric_vector(viewer["lookat"], length=3, label="viewer.lookat") + origin_type = viewer.get("origin_type", "world") + assert ( + isinstance(origin_type, str) and origin_type in _VIEWER_ORIGIN_TYPES + ), f"'viewer.origin_type' must be one of {sorted(_VIEWER_ORIGIN_TYPES)}, got {origin_type!r}" + asset_name = viewer.get("asset_name") + body_name = viewer.get("body_name") + if origin_type in {"world", "env"}: + assert ( + asset_name is None and body_name is None + ), f"'viewer.asset_name' and 'viewer.body_name' are invalid for {origin_type!r}" + elif origin_type == "asset_root": + assert isinstance(asset_name, str) and asset_name, f"'viewer.asset_name' is required for {origin_type!r}" + assert body_name is None, "'viewer.body_name' is invalid for 'asset_root'" + else: + assert isinstance(asset_name, str) and asset_name, "'viewer.asset_name' is required for 'asset_body'" + assert isinstance(body_name, str) and body_name, "'viewer.body_name' is required for 'asset_body'" def _validate_scene_dict(scene: dict[str, Any]) -> None: + """Validate rigid-object additions, overrides and requested scene removals.""" assert isinstance(scene, dict), f"'scene' must be a dict, got {type(scene).__name__}" scene_keys = {f.name for f in fields(SceneSpec)} unknown = set(scene) - scene_keys @@ -313,10 +531,84 @@ def _validate_scene_dict(scene: dict[str, Any]) -> None: f"scene.rigid_objects.override[{name!r}] has unknown keys {sorted(unknown)}. " f"Allowed: {sorted(override_keys)}" ) - rigid_props = spec.get("rigid_props") + position = spec.get("position") + if position is not None: + _validate_numeric_vector(position, length=3, label=f"scene.rigid_objects.override[{name!r}].position") + scale = spec.get("scale") + if scale is not None: + _validate_numeric_vector(scale, length=3, label=f"scene.rigid_objects.override[{name!r}].scale") + assert all( + value > 0.0 for value in scale + ), f"scene.rigid_objects.override[{name!r}].scale entries must be positive" + rigid_props = spec.get("rigid_props", {}) + assert isinstance(rigid_props, dict), ( + f"scene.rigid_objects.override[{name!r}] must provide a non-empty 'rigid_props' dict " + f"or a position/scale, got rigid_props={type(rigid_props).__name__}" + ) + physics_material = spec.get("physics_material") assert ( - isinstance(rigid_props, dict) and rigid_props - ), f"scene.rigid_objects.override[{name!r}] must provide a non-empty 'rigid_props' dict, got {rigid_props!r}" + physics_material is None or isinstance(physics_material, dict) and physics_material + ), f"scene.rigid_objects.override[{name!r}].physics_material must be a non-empty dict" + assert position is not None or scale is not None or rigid_props or physics_material, ( + f"scene.rigid_objects.override[{name!r}] must provide a position/scale " + "or non-empty 'rigid_props' or 'physics_material'" + ) + + cameras = scene.get("cameras", {}) + assert isinstance(cameras, dict), f"'scene.cameras' must be a dict, got {type(cameras).__name__}" + cameras_keys = {f.name for f in fields(CamerasSpec)} + unknown = set(cameras) - cameras_keys + assert not unknown, f"'scene.cameras' has unknown keys {sorted(unknown)}. Allowed: {sorted(cameras_keys)}" + + camera_overrides = cameras.get("override", {}) + assert isinstance( + camera_overrides, dict + ), f"'scene.cameras.override' must be a dict, got {type(camera_overrides).__name__}" + camera_override_keys = {f.name for f in fields(CameraOverrideSpec)} + required_camera_override_keys = {"position", "rotation_xyzw"} + for name, spec in camera_overrides.items(): + prefix = f"scene.cameras.override[{name!r}]" + assert isinstance(spec, dict), f"{prefix} must be a dict, got {type(spec).__name__}" + missing = required_camera_override_keys - set(spec) + assert not missing, f"{prefix} missing required keys: {sorted(missing)}" + unknown = set(spec) - camera_override_keys + assert not unknown, f"{prefix} has unknown keys {sorted(unknown)}. Allowed: {sorted(camera_override_keys)}" + + _validate_numeric_vector(spec["position"], length=3, label=f"{prefix}.position") + _validate_numeric_vector(spec["rotation_xyzw"], length=4, label=f"{prefix}.rotation_xyzw") + quaternion_norm = math.sqrt(sum(component * component for component in spec["rotation_xyzw"])) + assert math.isclose( + quaternion_norm, 1.0, rel_tol=1e-4, abs_tol=1e-4 + ), f"{prefix}.rotation_xyzw must be a unit quaternion in (x, y, z, w) order, got norm {quaternion_norm:.6f}" + + prim_path = spec.get("prim_path") + if prim_path is not None: + assert isinstance(prim_path, str) and prim_path, f"{prefix}.prim_path must be a non-empty string" + convention = spec.get("convention", "ros") + assert ( + convention in _CAMERA_CONVENTIONS + ), f"{prefix}.convention must be one of {sorted(_CAMERA_CONVENTIONS)}, got {convention!r}" + clipping_range = spec.get("clipping_range") + if clipping_range is not None: + _validate_numeric_vector(clipping_range, length=2, label=f"{prefix}.clipping_range") + assert ( + 0.0 < clipping_range[0] < clipping_range[1] + ), f"{prefix}.clipping_range must satisfy 0 < near < far, got {clipping_range!r}" + focal_length = spec.get("focal_length") + if focal_length is not None: + assert ( + isinstance(focal_length, (int, float)) and not isinstance(focal_length, bool) and focal_length > 0 + ), f"{prefix}.focal_length must be positive, got {focal_length!r}" + width = spec.get("width") + height = spec.get("height") + assert (width is None) == (height is None), f"{prefix}.width and height must be provided together" + if width is not None: + assert ( + isinstance(width, int) and not isinstance(width, bool) and width > 0 + ), f"{prefix}.width must be a positive integer, got {width!r}" + assert ( + isinstance(height, int) and not isinstance(height, bool) and height > 0 + ), f"{prefix}.height must be a positive integer, got {height!r}" def _validate_events_dict(events: dict[str, Any]) -> None: @@ -355,9 +647,142 @@ def _validate_events_dict(events: dict[str, Any]) -> None: assert mode in _EVENT_MODES, f"events.add[{name!r}].mode must be one of {sorted(_EVENT_MODES)}" +def _validate_control_dict(control: dict[str, Any]) -> None: + """Validate the supported Pink IK objective overrides.""" + assert isinstance(control, dict), f"'control' must be a dict, got {type(control).__name__}" + control_keys = {f.name for f in fields(ControlSpec)} + unknown = set(control) - control_keys + assert not unknown, f"'control' has unknown keys {sorted(unknown)}. Allowed: {sorted(control_keys)}" + + if "pink_ik" not in control: + return + pink_ik = control["pink_ik"] + assert isinstance(pink_ik, dict), f"'control.pink_ik' must be a dict, got {type(pink_ik).__name__}" + pink_ik_keys = {f.name for f in fields(PinkIKControlOverrideSpec)} + unknown = set(pink_ik) - pink_ik_keys + assert not unknown, f"'control.pink_ik' has unknown keys {sorted(unknown)}. Allowed: {sorted(pink_ik_keys)}" + assert "action_term" in pink_ik, "'control.pink_ik' missing required key 'action_term'" + assert ( + isinstance(pink_ik["action_term"], str) and pink_ik["action_term"] + ), "'control.pink_ik.action_term' must be a non-empty string" + + frame_tasks = pink_ik.get("frame_tasks", {}) + assert isinstance( + frame_tasks, dict + ), f"'control.pink_ik.frame_tasks' must be a dict, got {type(frame_tasks).__name__}" + frame_task_keys = {f.name for f in fields(PinkIKFrameTaskOverrideSpec)} + for frame_name, spec in frame_tasks.items(): + prefix = f"control.pink_ik.frame_tasks[{frame_name!r}]" + assert isinstance(frame_name, str) and frame_name, "Pink IK frame-task names must be non-empty strings" + assert isinstance(spec, dict), f"{prefix} must be a dict, got {type(spec).__name__}" + missing = frame_task_keys - set(spec) + assert not missing, f"{prefix} missing required keys: {sorted(missing)}" + unknown = set(spec) - frame_task_keys + assert not unknown, f"{prefix} has unknown keys {sorted(unknown)}. Allowed: {sorted(frame_task_keys)}" + for field_name, value in spec.items(): + _validate_nonnegative_number(value, label=f"{prefix}.{field_name}") + + damping_task = pink_ik.get("damping_task") + if damping_task is not None: + _validate_control_task_dict( + damping_task, + spec_type=PinkIKDampingTaskOverrideSpec, + label="control.pink_ik.damping_task", + ) + + null_space_task = pink_ik.get("null_space_posture_task") + if null_space_task is not None: + _validate_control_task_dict( + null_space_task, + spec_type=PinkIKNullSpacePostureTaskOverrideSpec, + label="control.pink_ik.null_space_posture_task", + ) + + additional_joint_names = pink_ik.get("additional_joint_names", []) + assert ( + isinstance(additional_joint_names, list) + and all(isinstance(name, str) and name for name in additional_joint_names) + and len(additional_joint_names) == len(set(additional_joint_names)) + ), "'control.pink_ik.additional_joint_names' must contain unique non-empty strings" + assert ( + frame_tasks or damping_task is not None or null_space_task is not None or additional_joint_names + ), "'control.pink_ik' must override at least one task or add controlled joints" + + +def _profile_data_load(path: Path, parents: tuple[Path, ...] = ()) -> dict[str, Any]: + """Load one profile and recursively merge an optional relative parent.""" + + path = path.resolve() + assert path.is_file(), f"environment profile does not exist: {path}" + assert path not in parents, f"cyclic environment-profile inheritance: {path}" + with path.open(encoding="utf-8") as stream: + data = yaml.safe_load(stream) + assert isinstance(data, dict), f"Expected top-level dict, got {type(data).__name__}" + parent = data.pop("extends", None) + if parent is None: + return data + assert isinstance(parent, str) and parent, "'extends' must name a relative environment profile" + base = _profile_data_load(path.parent / parent, (*parents, path)) + return _mapping_merge(base, data) + + +def _mapping_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]: + """Recursively merge mappings while replacing scalar and sequence leaves.""" + + result = dict(base) + for key, value in overlay.items(): + if isinstance(value, dict) and isinstance(result.get(key), dict): + result[key] = _mapping_merge(result[key], value) + else: + result[key] = value + return result + + +def _validate_control_task_dict(spec: Any, *, spec_type: type, label: str) -> None: + """Validate a scalar-only Pink IK auxiliary-task override.""" + assert isinstance(spec, dict), f"'{label}' must be a dict, got {type(spec).__name__}" + expected_keys = {f.name for f in fields(spec_type)} + missing = expected_keys - set(spec) + assert not missing, f"'{label}' missing required keys: {sorted(missing)}" + unknown = set(spec) - expected_keys + assert not unknown, f"'{label}' has unknown keys {sorted(unknown)}. Allowed: {sorted(expected_keys)}" + for field_name, value in spec.items(): + _validate_nonnegative_number(value, label=f"{label}.{field_name}") + + def _coerce_vector_fields(spec: dict[str, Any]) -> dict[str, Any]: """Coerce YAML-list vector fields of a rigid-object spec to tuples.""" - return {key: tuple(val) if key in ("position", "rotation", "scale") else val for key, val in spec.items()} + return { + key: tuple(val) if key in ("position", "rotation", "scale") and val is not None else val + for key, val in spec.items() + } + + +def _coerce_camera_vector_fields(spec: dict[str, Any]) -> dict[str, Any]: + """Coerce YAML-list vector fields of a camera override to tuples.""" + vector_fields = {"position", "rotation_xyzw", "clipping_range"} + return {key: tuple(value) if key in vector_fields and value is not None else value for key, value in spec.items()} + + +def _coerce_viewer_vector_fields(spec: dict[str, Any]) -> dict[str, Any]: + """Coerce YAML-list viewport vectors to tuples.""" + return {key: tuple(value) if key in {"eye", "lookat"} else value for key, value in spec.items()} + + +def _validate_numeric_vector(value: Any, *, length: int, label: str) -> None: + """Validate a fixed-length numeric profile vector.""" + assert ( + isinstance(value, (list, tuple)) + and len(value) == length + and all(isinstance(component, (int, float)) and not isinstance(component, bool) for component in value) + ), f"{label} must be a list of {length} numbers, got {value!r}" + + +def _validate_nonnegative_number(value: Any, *, label: str) -> None: + """Validate a finite nonnegative scalar controller parameter.""" + assert ( + isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value >= 0.0 + ), f"{label} must be a finite nonnegative number, got {value!r}" def convert_event_params(params: dict[str, Any], scene_entity_cfg_cls: type) -> dict[str, Any]: diff --git a/autodata_interfaces/env/isaaclab_env_interface.py b/autodata_interfaces/env/isaaclab_env_interface.py index f7b7234..c2e64a0 100644 --- a/autodata_interfaces/env/isaaclab_env_interface.py +++ b/autodata_interfaces/env/isaaclab_env_interface.py @@ -22,6 +22,7 @@ import isaaclab.sim as sim_utils from isaaclab.assets import RigidObjectCfg +from isaaclab.controllers.pink_ik import DampingTaskCfg, FrameTaskCfg, NullSpacePostureTaskCfg, PinkIKControllerCfg from isaaclab.envs.mdp.actions.pink_task_space_actions import PinkInverseKinematicsAction from isaaclab.managers import DatasetExportMode, EventTermCfg, SceneEntityCfg from isaaclab.managers.recorder_manager import RecorderManagerBaseCfg @@ -32,7 +33,7 @@ from isaaclab_tasks.utils.parse_cfg import parse_env_cfg from autodata_interfaces.env.datagen_info_recorder import add_step_success_recorder -from autodata_interfaces.env.env_profile import EnvironmentProfile, convert_event_params +from autodata_interfaces.env.env_profile import EnvironmentProfile, PinkIKControlOverrideSpec, convert_event_params from autodata_interfaces.env.pink_ik_action import PinkInverseKinematicsActionSharedUrdf from autodata_interfaces.env.recorders import make_action_state_recorder_manager_cfg from autodata_interfaces.env.reset_request import EnvResetRequest @@ -103,12 +104,79 @@ def get_env_name_from_dataset(input_file_path: str) -> str: return env_name +def _pink_task_cfg_unique( + task_cfgs: list[Any], task_cfg_type: type, *, action_term: str, frame: str | None = None +) -> Any: + """Resolve exactly one Pink task config, optionally by exact frame name.""" + matches = [ + task_cfg + for task_cfg in task_cfgs + if isinstance(task_cfg, task_cfg_type) and (frame is None or getattr(task_cfg, "frame", None) == frame) + ] + selection = task_cfg_type.__name__ if frame is None else f"{task_cfg_type.__name__} for frame {frame!r}" + assert ( + len(matches) == 1 + ), f"Pink IK action term {action_term!r} must contain exactly one {selection}; found {len(matches)}." + return matches[0] + + +def _apply_pink_ik_control_override(env_cfg: Any, override: PinkIKControlOverrideSpec) -> None: + """Apply a validated Pink IK objective override without replacing its controller.""" + actions_cfg = getattr(env_cfg, "actions", None) + assert actions_cfg is not None, "The base env does not define an actions config." + action_cfg = getattr(actions_cfg, override.action_term, None) + assert action_cfg is not None, f"The base env does not define action term {override.action_term!r}." + controller_cfg = getattr(action_cfg, "controller", None) + assert isinstance( + controller_cfg, PinkIKControllerCfg + ), f"Action term {override.action_term!r} does not use PinkIKControllerCfg." + task_cfgs = controller_cfg.variable_input_tasks + + # Resolve every target before mutation so a malformed base config cannot be partially patched. + frame_targets = { + frame_name: _pink_task_cfg_unique( + task_cfgs, + FrameTaskCfg, + action_term=override.action_term, + frame=frame_name, + ) + for frame_name in override.frame_tasks + } + damping_override = override.damping_task + damping_target = ( + _pink_task_cfg_unique(task_cfgs, DampingTaskCfg, action_term=override.action_term) + if damping_override is not None + else None + ) + null_space_override = override.null_space_posture_task + null_space_target = ( + _pink_task_cfg_unique(task_cfgs, NullSpacePostureTaskCfg, action_term=override.action_term) + if null_space_override is not None + else None + ) + existing_joint_names = list(action_cfg.pink_controlled_joint_names) + duplicate_joint_names = set(override.additional_joint_names) & set(existing_joint_names) + assert not duplicate_joint_names, f"Pink IK action term already controls joints: {sorted(duplicate_joint_names)}" + + for frame_name, frame_override in override.frame_tasks.items(): + target = frame_targets[frame_name] + target.position_cost = frame_override.position_cost + target.orientation_cost = frame_override.orientation_cost + target.lm_damping = frame_override.lm_damping + target.gain = frame_override.gain + if damping_override is not None: + damping_target.cost = damping_override.cost + if null_space_override is not None: + null_space_target.cost = null_space_override.cost + null_space_target.lm_damping = null_space_override.lm_damping + action_cfg.pink_controlled_joint_names = [*existing_joint_names, *override.additional_joint_names] + + def apply_env_profile(env_cfg: Any, profile: EnvironmentProfile, env_name: str) -> None: """Overlay ``profile`` onto a parsed env config in place, before ``gym.make``. - The scene and event managers build entities from the config instance's ``__dict__``, so - assets and event terms set here are consumed like class-declared ones, and event terms set - to None are skipped. + Scene and event changes are consumed like class-declared config. Controller changes patch + existing task configs without replacing the action term or controller implementation. Args: env_cfg: Parsed env config instance returned by ``parse_env_cfg``. @@ -128,6 +196,20 @@ def apply_env_profile(env_cfg: Any, profile: EnvironmentProfile, env_name: str) assert hasattr(term_cfg, parameter), f"Action term {term_name!r} has no parameter {parameter!r}." setattr(term_cfg, parameter, value) + if profile.viewer is not None: + from isaaclab_visualizers.kit import KitVisualizerCfg + + viewer = profile.viewer + track_path = viewer.asset_name + if viewer.origin_type == "asset_body": + track_path = f"{viewer.asset_name}/{viewer.body_name}" + env_cfg.sim.default_visualizer_cfg = KitVisualizerCfg( + eye=viewer.eye, + lookat=viewer.lookat, + origin_type="asset" if viewer.origin_type.startswith("asset_") else viewer.origin_type, + origin_track_path=track_path, + ) + # Scene: add rigid objects. for asset_name, add_spec in profile.scene.rigid_objects.add.items(): assert ( @@ -150,10 +232,20 @@ def apply_env_profile(env_cfg: Any, profile: EnvironmentProfile, env_name: str) ), ) - # Scene: override rigid-body properties of existing objects. + # Scene: override initial positions and rigid-body properties of existing objects. for asset_name, object_override in profile.scene.rigid_objects.override.items(): asset_cfg = getattr(env_cfg.scene, asset_name, None) assert asset_cfg is not None, f"Cannot override scene asset {asset_name!r}: the base env does not define it." + if object_override.position is not None: + asset_cfg.init_state.pos = object_override.position + if object_override.scale is not None: + asset_cfg.spawn.scale = object_override.scale + if object_override.physics_material is not None: + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + asset_cfg.spawn.physics_material = UsdPhysicsRigidBodyMaterialCfg(**object_override.physics_material) + if not object_override.rigid_props: + continue rigid_props = getattr(asset_cfg.spawn, "rigid_props", None) assert rigid_props is not None, f"Scene asset {asset_name!r} has no spawn rigid-body properties to override." for prop_name, value in object_override.rigid_props.items(): @@ -162,6 +254,34 @@ def apply_env_profile(env_cfg: Any, profile: EnvironmentProfile, env_name: str) ), f"Rigid-body properties of {asset_name!r} have no field {prop_name!r}." setattr(rigid_props, prop_name, value) + # Scene: override existing cameras without introducing a second render product. + for camera_name, camera_override in profile.scene.cameras.override.items(): + camera_cfg = getattr(env_cfg.scene, camera_name, None) + assert camera_cfg is not None, f"Cannot override scene camera {camera_name!r}: the base env does not define it." + offset_cfg = getattr(camera_cfg, "offset", None) + assert offset_cfg is not None, f"Scene asset {camera_name!r} is not a camera with an offset configuration." + spawn_cfg = getattr(camera_cfg, "spawn", None) + assert spawn_cfg is not None, f"Scene camera {camera_name!r} has no spawn configuration." + + if camera_override.prim_path is not None: + camera_cfg.prim_path = camera_override.prim_path + offset_cfg.pos = camera_override.position + offset_cfg.rot = camera_override.rotation_xyzw + offset_cfg.convention = camera_override.convention + if camera_override.clipping_range is not None: + assert hasattr( + spawn_cfg, "clipping_range" + ), f"Spawn configuration of scene camera {camera_name!r} has no clipping_range field." + spawn_cfg.clipping_range = camera_override.clipping_range + if camera_override.focal_length is not None: + assert hasattr( + spawn_cfg, "focal_length" + ), f"Spawn configuration of scene camera {camera_name!r} has no focal_length field." + spawn_cfg.focal_length = camera_override.focal_length + if camera_override.width is not None: + camera_cfg.width = camera_override.width + camera_cfg.height = camera_override.height + # Events: remove, override, then add. events_cfg = env_cfg.events for term_name in profile.events.remove: @@ -192,6 +312,9 @@ def apply_env_profile(env_cfg: Any, profile: EnvironmentProfile, env_name: str) "which does not exist on the base env or the profile's scene additions." ) + if profile.control.pink_ik is not None: + _apply_pink_ik_control_override(env_cfg, profile.control.pink_ik) + def setup_env_config( env_name: str, @@ -220,8 +343,8 @@ def setup_env_config( device: Device to run on. generation_policy_params: The task descriptor's generation config (source of truth). recorder_cfg: Optional recorder manager config; defaults to an action/state recorder. - env_profile: Optional environment profile overlaid on the parsed config (scene additions, - reset-event changes) before the generation-specific adjustments below. + env_profile: Optional environment profile overlaid on the parsed config (scene, event, + and controller changes) before the generation-specific adjustments below. enable_cameras: Record the task's image observations. Defaults to low-dimensional observations, excluding the cameras used for teleoperation previews. record_step_success: Also record whether the task's success term holds after each step, as @@ -245,6 +368,9 @@ def setup_env_config( if env_profile is not None: apply_env_profile(env_cfg, env_profile, env_name) + if enable_cameras: + env_cfg.num_rerenders_on_reset = max(1, env_cfg.num_rerenders_on_reset) + # Extract success checking function assert hasattr(env_cfg.terminations, "success"), "No success termination term was found in the environment." success_term = env_cfg.terminations.success @@ -292,6 +418,8 @@ def env_loop( generation_policy_params: GenerationPolicy, stats: dict, data_gen_tasks: asyncio.Future | None = None, + *, + stop_after_attempts: int | None = None, ) -> bool: """Synchronous step loop for the environment. @@ -301,48 +429,97 @@ def env_loop( when enough demos/attempts have been collected. The stop condition is read from ``generation_policy_params`` (the task descriptor's generation - config) rather than from ``env.cfg.datagen_config``: ``num_trials`` interpreted as successes + config) rather than from ``base_env.cfg.datagen_config``: ``num_trials`` interpreted as successes when ``guarantee_success`` is set, otherwise as total attempts. - Reset settling uses ``env.cfg.idle_action`` when configured, or zeros otherwise. A configured + Reset settling uses ``base_env.cfg.idle_action`` when configured, or zeros otherwise. A configured idle action must be a finite vector matching one environment's action dimensions. Args: - env: The environment to run the main step loop on. - env_reset_queue: The asyncio queue carrying :class:`EnvResetRequest` instances. + env: Environment to step; single-environment Gym video wrappers are supported. + env_reset_queue: Queue carrying :class:`EnvResetRequest` instances. env_action_queue: The asyncio queue carrying ``(env_id, action)`` pairs to execute. asyncio_event_loop: The main asyncio event loop. generation_policy_params: The task descriptor's generation config (source of truth). stats: Shared dict with ``num_success``, ``num_failures``, and ``num_attempts`` counters. data_gen_tasks: Gathered future for all data generation tasks. When provided, the loop exits early if all tasks finish unexpectedly (e.g. due to an unhandled exception). - + stop_after_attempts: Optional number of additional completed attempts before returning, + without resetting the run's counters or changing its generation policy. Returns: - Whether the generation policy's requested trial target was reached. + Whether the generation target or the additional-attempt limit was reached. False means + the run exhausted its failure allowance or execution stopped before either target. """ num_trials = generation_policy_params.num_trials guarantee_success = generation_policy_params.guarantee_success + max_attempts = num_trials + generation_policy_params.max_num_failures + assert stop_after_attempts is None or (type(stop_after_attempts) is int and stop_after_attempts > 0) + stop_at_attempt = None if stop_after_attempts is None else stats["num_attempts"] + stop_after_attempts + base_env = env.unwrapped if hasattr(env, "unwrapped") else env reset_settling_steps = generation_policy_params.reset_settling_steps assert reset_settling_steps >= 0, "reset_settling_steps must be non-negative" - idle_actions = torch.zeros(env.action_space.shape, dtype=torch.float32, device=env.device) - configured_idle_action = getattr(env.cfg, "idle_action", None) + idle_actions = torch.zeros(base_env.action_space.shape, dtype=torch.float32, device=base_env.device) + configured_idle_action = getattr(base_env.cfg, "idle_action", None) if reset_settling_steps > 0 and configured_idle_action is not None: - idle_action = torch.as_tensor(configured_idle_action, dtype=idle_actions.dtype, device=env.device) - assert ( - idle_action.shape == env.action_space.shape[1:] - ), f"env.cfg.idle_action must have shape {env.action_space.shape[1:]}, got {tuple(idle_action.shape)}." - assert torch.isfinite(idle_action).all(), "env.cfg.idle_action must contain only finite values." + idle_action = torch.as_tensor(configured_idle_action, dtype=idle_actions.dtype, device=base_env.device) + assert idle_action.shape == base_env.action_space.shape[1:], ( + f"base_env.cfg.idle_action must have shape {base_env.action_space.shape[1:]}, got" + f" {tuple(idle_action.shape)}." + ) + assert torch.isfinite(idle_action).all(), "base_env.cfg.idle_action must contain only finite values." idle_actions[:] = idle_action - env_id_tensor = torch.tensor([0], dtype=torch.int64, device=env.device) + env_id_tensor = torch.tensor([0], dtype=torch.int64, device=base_env.device) settling_requests: dict[int, EnvResetRequest] = {} settling_steps_remaining: dict[int, int] = {} prev_num_attempts = 0 - # simulate environment -- run everything in inference mode - with contextlib.suppress(KeyboardInterrupt) and torch.inference_mode(): + + def generation_status() -> bool | None: + """Report progress and return the terminal result, if generation is complete.""" + + nonlocal prev_num_attempts + if prev_num_attempts == stats["num_attempts"]: + return None + prev_num_attempts = stats["num_attempts"] + num_success = stats["num_success"] + num_attempts = stats["num_attempts"] + generated_success_rate = 100 * num_success / num_attempts if num_attempts > 0 else 0.0 + print("") + print("*" * 50, "\033[K") + if guarantee_success: + print( + f"{num_success}/{num_trials} successful demos generated ({num_attempts} attempts," + f" {stats['num_failures']} failures; {generated_success_rate:.1f}% success)\033[K" + ) + else: + print( + f"{num_attempts}/{num_trials} attempts completed " + f"({num_success} successful demos; {generated_success_rate:.1f}% success)\033[K" + ) + print("*" * 50, "\033[K") + + check_value = num_success if guarantee_success else num_attempts + if check_value >= num_trials: + print(f"Reached {num_trials} {'successes' if guarantee_success else 'attempts'}. Exiting.") + return True + if guarantee_success and num_attempts >= max_attempts: + print(f"Reached the {max_attempts}-attempt limit with {num_success}/{num_trials} successes.") + return False + if stop_at_attempt is not None and num_attempts >= stop_at_attempt: + return True + return None + + with contextlib.suppress(KeyboardInterrupt), torch.inference_mode(): while True: - # check if any environment needs to be reset while waiting for actions - while env_action_queue.qsize() + len(settling_requests) != env.num_envs: - asyncio_event_loop.run_until_complete(asyncio.sleep(0)) + status = generation_status() + if status is not None: + return status + while env_action_queue.qsize() + len(settling_requests) != base_env.num_envs: + # cuRobo planning and IK may require gradients while producers run. + with torch.enable_grad(), torch.inference_mode(False): + asyncio_event_loop.run_until_complete(asyncio.sleep(0)) + status = generation_status() + if status is not None: + return status if data_gen_tasks is not None and data_gen_tasks.done(): exc = data_gen_tasks.exception() if exc is not None: @@ -354,13 +531,16 @@ def env_loop( request, EnvResetRequest ), f"env_reset_queue entries must be EnvResetRequest instances, got {type(request).__name__}" assert ( - 0 <= request.env_id < env.num_envs - ), f"Reset environment index {request.env_id} is outside [0, {env.num_envs})." + 0 <= request.env_id < base_env.num_envs + ), f"Reset environment index {request.env_id} is outside [0, {base_env.num_envs})." assert ( request.env_id not in settling_requests ), f"Environment {request.env_id} already has a reset settling request in progress." env_id_tensor[0] = request.env_id - env.reset(env_ids=env_id_tensor) + if env is not base_env and base_env.num_envs == 1: + env.reset() + else: + base_env.reset(env_ids=env_id_tensor) if reset_settling_steps > 0: settling_requests[request.env_id] = request @@ -370,7 +550,7 @@ def env_loop( request.completion.set_result(None) env_reset_queue.task_done() - expected_action_count = env.num_envs - len(settling_requests) + expected_action_count = base_env.num_envs - len(settling_requests) assert env_action_queue.qsize() <= expected_action_count, ( f"Received {env_action_queue.qsize()} queued actions for only {expected_action_count} " "non-settling environments." @@ -380,9 +560,10 @@ def env_loop( # Settling environments use the idle action. Batch-fetch one real action for every # other environment so their generation trajectories continue without interruption. - action_count = env.num_envs - len(settling_requests) + action_count = base_env.num_envs - len(settling_requests) get_tasks = [env_action_queue.get() for _ in range(action_count)] - results = asyncio_event_loop.run_until_complete(asyncio.gather(*get_tasks)) if get_tasks else [] + with torch.enable_grad(), torch.inference_mode(False): + results = asyncio_event_loop.run_until_complete(asyncio.gather(*get_tasks)) if get_tasks else [] action_env_ids: set[int] = set() for env_id, action in results: assert ( @@ -391,7 +572,7 @@ def env_loop( assert env_id not in action_env_ids, f"Received multiple actions for environment {env_id}." action_env_ids.add(env_id) actions[env_id] = action - expected_action_env_ids = set(range(env.num_envs)) - settling_requests.keys() + expected_action_env_ids = set(range(base_env.num_envs)) - settling_requests.keys() assert ( action_env_ids == expected_action_env_ids ), f"Expected actions for environments {sorted(expected_action_env_ids)}, got {sorted(action_env_ids)}." @@ -410,15 +591,15 @@ def env_loop( settled_env_ids.append(env_id) if settled_env_ids: - settled_env_ids_tensor = torch.tensor(settled_env_ids, dtype=torch.int64, device=env.device) + settled_env_ids_tensor = torch.tensor(settled_env_ids, dtype=torch.int64, device=base_env.device) # Discard temporary settle frames, then capture the settled state as the generated # episode's initial state before releasing the corresponding generators. - env.recorder_manager.reset(env_ids=settled_env_ids_tensor) + base_env.recorder_manager.reset(env_ids=settled_env_ids_tensor) # Settling is not a reset: Arena correctly ignores post-reset callbacks here. # Snapshot the actual settled state through the public recorder API instead. - env.recorder_manager.add_to_episodes( + base_env.recorder_manager.add_to_episodes( "initial_state", - get_scene_state(env.scene, is_relative=True, env_ids=settled_env_ids_tensor), + get_scene_state(base_env.scene, is_relative=True, env_ids=settled_env_ids_tensor), env_ids=settled_env_ids_tensor, ) for env_id in settled_env_ids: @@ -428,24 +609,8 @@ def env_loop( request.completion.set_result(None) env_reset_queue.task_done() - if prev_num_attempts != stats["num_attempts"]: - prev_num_attempts = stats["num_attempts"] - num_success = stats["num_success"] - num_attempts = stats["num_attempts"] - generated_success_rate = 100 * num_success / num_attempts if num_attempts > 0 else 0.0 - print("") - print("*" * 50, "\033[K") - print(f"{num_success}/{num_attempts} ({generated_success_rate:.1f}%) successful demos generated\033[K") - print("*" * 50, "\033[K") - - # termination condition is on enough successes if guarantee_success else enough attempts - check_val = num_success if guarantee_success else num_attempts - if check_val >= num_trials: - print(f"Reached {num_trials} {'successes' if guarantee_success else 'attempts'}. Exiting.") - return True - # check that simulation is stopped or not - if env.sim.is_stopped(): + if base_env.sim.is_stopped(): return False # Do not close env here: async data generator tasks may still be running. diff --git a/autodata_interfaces/env/kit_visualizer.py b/autodata_interfaces/env/kit_visualizer.py new file mode 100644 index 0000000..eb5dfe3 --- /dev/null +++ b/autodata_interfaces/env/kit_visualizer.py @@ -0,0 +1,15 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Kit viewport capture with camera-driven rendering in headless mode.""" + +from isaaclab_visualizers.kit import KitVisualizer + + +class KitVisualizerHeadless(KitVisualizer): + """Keep observation cameras active when the viewport renders only on demand.""" + + def pumps_app_update(self) -> bool: + """Report whether simulation steps update the Kit app before cameras are read.""" + + return False if self.cfg.headless else super().pumps_app_update() diff --git a/autodata_interfaces/env/observation_render_wrapper.py b/autodata_interfaces/env/observation_render_wrapper.py new file mode 100644 index 0000000..27dc4e7 --- /dev/null +++ b/autodata_interfaces/env/observation_render_wrapper.py @@ -0,0 +1,207 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Gym rendering backed by live Isaac viewport and RGB observation frames.""" + +from __future__ import annotations + +import gymnasium as gym +import numpy as np +import torch +from collections.abc import Mapping +from typing import Any + + +def observation_video_path_resolve( + configured_path: str | None, + *, + default_image_observation_names: tuple[str, ...], + default_group_name: str = "policy", +) -> tuple[str, ...]: + """Resolve the nested observation path used for simulator video. + + An explicit one-component path is interpreted relative to ``default_group_name``. When no + path is configured, exactly one task-declared image observation is required; ambiguity fails + before simulator construction instead of selecting a camera by iteration order. + + Args: + configured_path: Optional dot-separated observation path. + default_image_observation_names: Task-declared image terms in the default group. + default_group_name: Observation group used for a one-component term. + + Returns: + Canonical nested mapping keys from observation root to RGB tensor. + """ + + assert ( + isinstance(default_group_name, str) and default_group_name and default_group_name == default_group_name.strip() + ) + assert isinstance(default_image_observation_names, tuple), "default image observation names must be a tuple" + assert all( + isinstance(name, str) and name and name == name.strip() and "." not in name + for name in default_image_observation_names + ), "default image observation names must be non-empty, trimmed local keys" + assert len(set(default_image_observation_names)) == len( + default_image_observation_names + ), "default image observation names must be unique" + + if configured_path is None: + assert len(default_image_observation_names) == 1, ( + "video recording requires --video_observation_path when the environment does not " + "declare exactly one image_obs_list entry" + ) + return default_group_name, default_image_observation_names[0] + + assert ( + isinstance(configured_path, str) and configured_path == configured_path.strip() and configured_path + ), "video observation path must be a non-empty, trimmed string" + components = tuple(configured_path.split(".")) + assert all( + component and component == component.strip() for component in components + ), "video observation path must contain non-empty dot-separated keys" + return (default_group_name, components[0]) if len(components) == 1 else components + + +class ObservationRenderWrapper(gym.Wrapper): + """Expose one live RGB observation through Gym's ``rgb_array`` render contract. + + Isaac Lab camera observations are refreshed as part of ``reset`` and ``step``. Caching the + returned observation makes Gymnasium's :class:`~gymnasium.wrappers.RecordVideo` consume the + exact frame aligned with each policy transition, without a fake physics step or a second + viewport render product. + + Args: + env: Environment whose observations contain the video frame. + observation_path: Nested mapping keys leading to a batched or unbatched RGB image. + environment_index: Batch row to record when the observation contains multiple envs. + """ + + def __init__( + self, + env: gym.Env, + *, + observation_path: tuple[str, ...], + environment_index: int = 0, + ) -> None: + """Select the RGB observation and environment row used by video recording.""" + super().__init__(env) + assert isinstance(observation_path, tuple) and observation_path, "observation_path must be non-empty" + assert all( + isinstance(component, str) and component and component == component.strip() + for component in observation_path + ), "observation_path must contain non-empty, trimmed keys" + assert type(environment_index) is int and environment_index >= 0, "environment_index must be non-negative" + self._observation_path = observation_path + self._environment_index = environment_index + self._frame: np.ndarray | None = None + self._frame_shape: tuple[int, int, int] | None = None + + @property + def render_mode(self) -> str: + """Gym render mode supplied by this observation adapter.""" + + return "rgb_array" + + @property + def observation_path(self) -> tuple[str, ...]: + """Nested observation keys backing the rendered frame.""" + + return self._observation_path + + def reset(self, *, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[Any, dict[str, Any]]: + """Reset the environment and retain its aligned RGB observation.""" + + observation, info = self.env.reset(seed=seed, options=options) + self._frame = self._frame_extract(observation) + return observation, info + + def step(self, action: Any) -> tuple[Any, Any, Any, Any, dict[str, Any]]: + """Step the environment and retain its aligned RGB observation.""" + + observation, reward, terminated, truncated, info = self.env.step(action) + self._frame = self._frame_extract(observation) + return observation, reward, terminated, truncated, info + + def render(self) -> np.ndarray: + """Return an immutable snapshot of the latest RGB observation.""" + + assert self._frame is not None, "video frame is unavailable before reset" + return self._frame.copy() + + def _frame_extract(self, observation: Any) -> np.ndarray: + """Return a copied RGB frame from the configured observation path.""" + value = observation + traversed: list[str] = [] + for component in self._observation_path: + assert isinstance( + value, Mapping + ), f"video observation {'.'.join(traversed) or ''} must be a mapping, got {type(value).__name__}" + assert ( + component in value + ), f"video observation path {'.'.join(self._observation_path)!r} is missing key {component!r}" + value = value[component] + traversed.append(component) + + if isinstance(value, torch.Tensor): + assert value.dtype == torch.uint8, "video observation tensor must use uint8 pixels" + frame = value.detach().cpu().numpy() + else: + assert isinstance(value, np.ndarray), "video observation must be a torch.Tensor or numpy.ndarray" + assert value.dtype == np.uint8, "video observation array must use uint8 pixels" + frame = value + + if frame.ndim == 4: + assert ( + self._environment_index < frame.shape[0] + ), f"video observation has {frame.shape[0]} environment rows, missing row {self._environment_index}" + frame = frame[self._environment_index] + else: + assert self._environment_index == 0, "an unbatched video observation supports only environment_index=0" + assert ( + frame.ndim == 3 and frame.shape[0] > 0 and frame.shape[1] > 0 + ), "video observation must have non-empty HWC image shape" + assert frame.shape[2] in (3, 4), "video observation must have RGB or RGBA channels in the final axis" + frame = np.ascontiguousarray(frame[:, :, :3]).copy() + if self._frame_shape is None: + self._frame_shape = frame.shape + assert frame.shape == self._frame_shape, ( + f"video observation shape changed from {self._frame_shape} to {frame.shape}; " + "one recording requires a fixed camera resolution" + ) + return frame + + +class ViewportRenderWrapper(gym.Wrapper): + """Expose the native Kit viewport through Gym's RGB recording interface. + + Captures the configured viewport without changing scene observation cameras or advancing + physics. The simulator owns the visualizer and releases its render resources at close. + """ + + def __init__(self, env: gym.Env) -> None: + """Select the existing Kit viewport without changing observation cameras.""" + super().__init__(env) + visualizers = [ + visualizer for visualizer in env.unwrapped.sim.visualizers if visualizer.cfg.visualizer_type == "kit" + ] + assert len(visualizers) == 1, "Viewport recording requires exactly one Kit visualizer." + self._visualizer = visualizers[0] + + @property + def render_mode(self) -> str: + """Gym render mode supplied by the viewport adapter.""" + return "rgb_array" + + def render(self) -> np.ndarray: + """Return the current native viewport frame.""" + frame = self._visualizer.render_rgb_array() + assert isinstance(frame, np.ndarray) and frame.dtype == np.uint8 + assert frame.ndim == 3 and frame.shape[2] in (3, 4), "Viewport capture must return RGB or RGBA." + return np.ascontiguousarray(frame[:, :, :3]) + + +__all__ = [ + "ObservationRenderWrapper", + "ViewportRenderWrapper", + "observation_video_path_resolve", +] diff --git a/autodata_interfaces/env/scene_state.py b/autodata_interfaces/env/scene_state.py index 29fe0fa..e98ba47 100644 --- a/autodata_interfaces/env/scene_state.py +++ b/autodata_interfaces/env/scene_state.py @@ -5,11 +5,14 @@ from __future__ import annotations +import torch from collections.abc import Sequence from typing import Any +from autodata_utils.tensor_utils import as_torch -def get_scene_state(scene: Any, is_relative: bool = True, env_ids: Sequence[int] | None = None) -> dict: + +def get_scene_state(scene: Any, is_relative: bool = True, env_ids: Sequence[int] | torch.Tensor | None = None) -> dict: """Return scene state in world or per-environment coordinates. Isaac Lab owns the coordinate conversion for every supported asset type. @@ -21,7 +24,7 @@ def get_scene_state(scene: Any, is_relative: bool = True, env_ids: Sequence[int] env_ids: Environment rows to include, in the requested order; None selects all. Returns: - Nested scene-state mapping containing cloned tensors. + Scene-state mapping; selected rows are detached copies. """ state = scene.get_state(is_relative=is_relative) @@ -29,8 +32,11 @@ def get_scene_state(scene: Any, is_relative: bool = True, env_ids: Sequence[int] return state def select_envs(value): + """Select independent environment rows from each state tensor.""" if isinstance(value, dict): return {key: select_envs(item) for key, item in value.items()} - return value[env_ids] + tensor = as_torch(value) + indices = torch.as_tensor(env_ids, device=tensor.device, dtype=torch.long) + return tensor.index_select(0, indices).detach() return select_envs(state) diff --git a/autodata_interfaces/tasks/generation_policy_spec.py b/autodata_interfaces/tasks/generation_policy_spec.py index 7efa53b..3346c21 100644 --- a/autodata_interfaces/tasks/generation_policy_spec.py +++ b/autodata_interfaces/tasks/generation_policy_spec.py @@ -3,6 +3,7 @@ from __future__ import annotations +import math from dataclasses import dataclass @@ -16,6 +17,9 @@ class GenerationPolicy: num_trials: Number of demos to generate. guarantee_success: If True, retry until ``num_trials`` successful demos; if False, stop after ``num_trials`` attempts regardless of success. + max_num_failures: Maximum additional failed attempts tolerated when ``guarantee_success`` + is True. Together with ``num_trials``, this defines a finite attempt budget. It does + not extend fixed-attempt runs. keep_failed: If True, also export failed trials (useful for debugging low success rates). source_dataset_path: Path to the source dataset of human demos. generation_path: Path the generated dataset is written to. @@ -34,11 +38,26 @@ class GenerationPolicy: first subtask's selection sticks for the rest of the episode. select_src_per_arm: If True, each EEF picks its own source demo. If False, all EEFs share the source demo selected by the first arm to choose. + source_selection_anchor: Explicit ``"."`` used to rank one shared episode + source independently of EEF declaration order. ``None`` retains ordinary selection. + source_demo_keys: Ordered subset of loaded source episodes eligible for selection. ``None`` + keeps every loaded episode eligible. + source_candidate_count: Maximum eligible source demos tried on one reset when complete-path + joint-trajectory solving fails the IK checks. Defaults to one, preserving ordinary generation behavior. transform_first_robot_pose: If True, prepend the recorded EEF pose to every subtask's target-pose sequence (anchors interpolation to the robot's recorded pose, not the controller target). If False, only the first subtask uses this anchoring. interpolate_from_last_target_pose: If True, non-first subtasks interpolate from the last executed waypoint instead of from the live robot pose. + skill_passthrough_delay_steps: Samples to hold the previous passthrough command after a + major source-skill transition. + skill_passthrough_interpolation_steps: Samples used to blend a delayed passthrough + transition to its new value. + max_joint_step_rad: Maximum joint change between consecutive validated controller + targets [rad]. ``None`` preserves the computed paths unchanged. + final_hold_steps: Additional synchronized holds after the scheduled paths finish. + terminal_convergence_steps: Maximum additional commands of the validated terminal target + used to reach the planner pose thresholds. """ # --- general parameters --- @@ -46,6 +65,7 @@ class GenerationPolicy: seed: int = 1 num_trials: int = 10 guarantee_success: bool = True + max_num_failures: int = 50 keep_failed: bool = False source_dataset_path: str | None = None generation_path: str | None = None @@ -60,6 +80,66 @@ class GenerationPolicy: select_src_per_arm: bool = False transform_first_robot_pose: bool = False interpolate_from_last_target_pose: bool = True + skill_passthrough_delay_steps: int = 0 + skill_passthrough_interpolation_steps: int = 0 + max_joint_step_rad: float | None = None + final_hold_steps: int = 0 + terminal_convergence_steps: int = 0 + source_selection_anchor: str | None = None + source_demo_keys: list[str] | None = None + source_candidate_count: int = 1 + + def remaining_attempts(self, num_attempts: int, num_success: int, num_pending: int = 0) -> int: + """Return how many episodes may start without exceeding the trial or failure limit. + + Pending episodes reserve one possible success each when successful demos are requested. + + Args: + num_attempts: Completed episodes, including failures. + num_success: Successful completed episodes. + num_pending: Episodes already being generated. + + Returns: + Number of additional episodes that may start. + """ + + assert 0 <= num_success <= num_attempts and num_pending >= 0 + completed = num_success if self.guarantee_success else num_attempts + budget = self.num_trials + (self.max_num_failures if self.guarantee_success else 0) + return max(0, min(self.num_trials - completed, budget - num_attempts) - num_pending) def __post_init__(self) -> None: + """Validate trial budgets, source selection and motion-execution settings.""" assert self.max_navigation_hold_steps > 0, "max_navigation_hold_steps must be positive." + assert type(self.num_trials) is int and self.num_trials > 0, "num_trials must be a positive integer" + assert isinstance(self.guarantee_success, bool), "guarantee_success must be a bool" + assert ( + type(self.max_num_failures) is int and self.max_num_failures >= 0 + ), "max_num_failures must be a non-negative integer" + assert self.source_selection_anchor is None or ( + isinstance(self.source_selection_anchor, str) and self.source_selection_anchor + ), "source_selection_anchor must be a non-empty string or None" + if self.source_demo_keys is not None: + assert isinstance(self.source_demo_keys, list), "source_demo_keys must be a list or None" + assert self.source_demo_keys, "source_demo_keys must be non-empty or None" + assert all( + isinstance(key, str) and key for key in self.source_demo_keys + ), "source_demo_keys must contain non-empty strings" + assert len(self.source_demo_keys) == len(set(self.source_demo_keys)), "source_demo_keys must be unique" + assert ( + type(self.source_candidate_count) is int and self.source_candidate_count >= 1 + ), "source_candidate_count must be a positive integer" + for name in ( + "skill_passthrough_delay_steps", + "skill_passthrough_interpolation_steps", + "final_hold_steps", + "terminal_convergence_steps", + ): + value = getattr(self, name) + assert type(value) is int and value >= 0, f"{name} must be a non-negative integer" + if self.max_joint_step_rad is not None: + assert ( + type(self.max_joint_step_rad) is float + and math.isfinite(self.max_joint_step_rad) + and self.max_joint_step_rad > 0.0 + ), "max_joint_step_rad must be a finite positive float or None" diff --git a/autodata_interfaces/tasks/subtask_spec.py b/autodata_interfaces/tasks/subtask_spec.py index 9a5029b..30deb9c 100644 --- a/autodata_interfaces/tasks/subtask_spec.py +++ b/autodata_interfaces/tasks/subtask_spec.py @@ -6,6 +6,8 @@ from dataclasses import MISSING, dataclass, field from typing import Any, get_origin, get_type_hints +from autodata_interfaces.tasks.segment_spec import SegmentSpec + @dataclass class SubtaskAlgoParams: @@ -88,9 +90,11 @@ class Subtask: """Configuration object used to specify subtasks used in data generation. Args: + name: Stable local identifier used by segment schedule constraints. + Empty for legacy task descriptors. object_ref: Reference object involved in the subtask. Empty string if no object is involved. - description: Human/agent readable description of the subtask. + description: Human-readable description of the subtask. subtask_start_signal: Boolean start signal name. Empty string if the subtask has no explicit start signal. subtask_term_signal: Boolean termination signal name. Empty string @@ -110,10 +114,13 @@ class Subtask: executing this subtask's segment. apply_noise_during_interpolation: Whether to apply ``action_noise`` during the interpolation phase as well. + segments: Ordered trajectory segments compiled for scheduled generation. + Empty for legacy task descriptors. algo_params: Algorithm-specific parameters (e.g. :class:`SkillGenSubtaskAlgoParams`). """ + name: str = "" object_ref: str = "" description: str = "" subtask_start_signal: str = "" @@ -126,6 +133,7 @@ class Subtask: num_interpolation_steps: int = 0 num_fixed_steps: int = 0 apply_noise_during_interpolation: bool = False + segments: tuple[SegmentSpec, ...] = field(default_factory=tuple) algo_params: SubtaskAlgoParams = MISSING @@ -134,6 +142,7 @@ class Subtask: "dexmimicgen": DexMimicGenSubtaskAlgoParams, "skillgen": SkillGenSubtaskAlgoParams, "softmimicgen": SoftMimicGenSubtaskAlgoParams, + "schedulegen": SkillGenSubtaskAlgoParams, } """Maps the ``algo:`` discriminator in a YAML task config to the corresponding :class:`SubtaskAlgoParams` subclass. diff --git a/autodata_interfaces/tasks/task_descriptor.py b/autodata_interfaces/tasks/task_descriptor.py index 23c2a07..5e296d1 100644 --- a/autodata_interfaces/tasks/task_descriptor.py +++ b/autodata_interfaces/tasks/task_descriptor.py @@ -9,9 +9,29 @@ from typing import TYPE_CHECKING, Any from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy +from autodata_interfaces.tasks.schedule_constraint_spec import ( + NonPreemptiveConstraintSpec, + PrecedenceConstraintSpec, + ScheduleSpec, + SegmentAnchorPoint, + SegmentId, +) +from autodata_interfaces.tasks.segment_spec import ( + SegmentEventPoint, + SegmentEventType, + SegmentKind, + SegmentProvider, + SegmentRobotContactSpec, + SegmentWorldContactSpec, +) from autodata_interfaces.tasks.subtask_constraint_spec import SubtaskConstraint from autodata_interfaces.tasks.subtask_spec import ALGO_PARAMS_REGISTRY, Subtask, SubtaskAlgoParams -from autodata_interfaces.tasks.task_descriptor_utils import build_constraint, build_subtask, validate_task_dict +from autodata_interfaces.tasks.task_descriptor_utils import ( + build_constraint, + build_schedule, + build_subtask, + validate_task_dict, +) if TYPE_CHECKING: from autodata_interfaces.embodiments.embodiment_adapter import EmbodimentAdapter @@ -23,19 +43,23 @@ class TaskDescriptor: Args: name: Task identifier. - description: Human/agent-readable task description. + description: Human-readable task description. subtasks: Per-end-effector ordered subtask lists. Keys are eef names; each value is the ordered sequence of :class:`Subtask` for that eef. constraints: Cross-subtask coordination/sequential constraints (multi-eef tasks). generation_policy: Data generation policy parameters. + attempt_diagnostics: Optional ``"module.path:function"`` callback for task-specific + terminal diagnostics. The generation entrypoint resolves it at composition time. """ name: str = MISSING description: str = "" subtasks: dict[str, list[Subtask]] = field(default_factory=dict) constraints: list[SubtaskConstraint] = field(default_factory=list) + schedule: ScheduleSpec | None = None generation_policy: GenerationPolicy = field(default_factory=GenerationPolicy) env: Any = None + attempt_diagnostics: str | None = None def bind_env(self, env: Any) -> None: """Attach the Isaac Lab env after construction. @@ -143,11 +167,102 @@ def get_task_constraints(self) -> list[SubtaskConstraint]: return self.constraints + def get_schedule_spec(self) -> ScheduleSpec | None: + """Return the episode-level schedule policy, if configured.""" + + return self.schedule + + def get_segment_world_contacts(self) -> dict[SegmentId, tuple[SegmentWorldContactSpec, ...]]: + """Return task-defined object/fixture contacts keyed by exact segment identity.""" + + return { + SegmentId(eef_name, subtask.name, segment.name): segment.world_contacts + for eef_name, subtasks in self.subtasks.items() + for subtask in subtasks + for segment in subtask.segments + if segment.world_contacts + } + + def get_segment_robot_contacts(self) -> dict[SegmentId, tuple[SegmentRobotContactSpec, ...]]: + """Return task-defined robot/object contacts keyed by exact segment identity.""" + + return { + SegmentId(eef_name, subtask.name, segment.name): segment.robot_contacts + for eef_name, subtasks in self.subtasks.items() + for subtask in subtasks + for segment in subtask.segments + if segment.robot_contacts + } + + def get_segment_resource_ids(self) -> dict[SegmentId, tuple[str, ...]]: + """Return additional task-local resource claims keyed by exact segment identity.""" + + return { + SegmentId(eef_name, subtask.name, segment.name): segment.resource_ids + for eef_name, subtasks in self.subtasks.items() + for subtask in subtasks + for segment in subtask.segments + if segment.resource_ids + } + + def get_path_build_order(self) -> tuple[str, ...]: + """Order path construction by cross-arm object-pose dependencies. + + Returns: + End-effector names, with each object-pose producer before its consumers. + + Raises: + AssertionError: A dependency names an unknown end effector or contains a cycle. + """ + + dependencies = {eef_name: set() for eef_name in self.subtasks} + for consumer_eef, subtasks in self.subtasks.items(): + for subtask in subtasks: + for segment in subtask.segments: + goal = segment.motion_goal + if goal is None or goal.object_pose_after_segment_id is None: + continue + producer_eef = goal.object_pose_after_segment_id.eef_name + assert producer_eef in dependencies, f"unknown producer EEF {producer_eef!r}" + if producer_eef != consumer_eef: + dependencies[consumer_eef].add(producer_eef) + + result: list[str] = [] + pending = dict(dependencies) + while pending: + ready = [eef_name for eef_name in self.subtasks if eef_name in pending and not pending[eef_name]] + assert ready, "object-pose dependencies require a cycle-free path construction order" + result.extend(ready) + for eef_name in ready: + pending.pop(eef_name) + for predecessors in pending.values(): + predecessors.difference_update(ready) + return tuple(result) + + def requires_source_demos(self) -> bool: + """Return whether generation requires a source-demonstration pool.""" + + subtasks = tuple(subtask for eef_subtasks in self.subtasks.values() for subtask in eef_subtasks) + return ( + not subtasks + or any(not subtask.segments for subtask in subtasks) + or any( + segment.provider == SegmentProvider.DEMONSTRATION + for subtask in subtasks + for segment in subtask.segments + ) + ) + def get_generation_policy(self) -> GenerationPolicy: """Return the cross-cutting generation flags.""" return self.generation_policy + def get_attempt_diagnostics(self) -> str | None: + """Return the optional task-diagnostics callable path.""" + + return self.attempt_diagnostics + @classmethod def from_yaml(cls, path: str | Path) -> TaskDescriptor: """Build a TaskDescriptor from a YAML config file. @@ -175,6 +290,15 @@ def from_yaml(cls, path: str | Path) -> TaskDescriptor: apply_noise_during_interpolation: algo_params: # optional, fields match the : # chosen algo's dataclass + segments: # ScheduleGen + - name: + kind: + provider: + goal_segment_id: .. # motion planner only + resource_ids: [, ...] # optional shared mutexes + world_contacts: # optional exact object/fixture pairs + - object_ref: + fixture_ref: - ... : [...] constraints: # optional, cross-subtask constraints @@ -200,8 +324,17 @@ def from_yaml(cls, path: str | Path) -> TaskDescriptor: use_navigation_controller: select_src_per_subtask: select_src_per_arm: + source_selection_anchor: . + source_demo_keys: [, ...] + source_candidate_count: transform_first_robot_pose: interpolate_from_last_target_pose: + skill_passthrough_delay_steps: + skill_passthrough_interpolation_steps: + max_joint_step_rad: + final_hold_steps: + terminal_convergence_steps: + attempt_diagnostics: # optional module.path:function """ with open(path) as f: @@ -224,12 +357,322 @@ def from_dict(cls, data: dict[str, Any]) -> TaskDescriptor: for eef_name, eef_subtasks in data["subtasks"].items() } constraints = [build_constraint(c) for c in data.get("constraints", [])] + schedule = build_schedule(data["schedule"]) if "schedule" in data else None generation_policy = GenerationPolicy(**data.get("generation_policy", {})) - return cls( + descriptor = cls( name=data["name"], description=data.get("description", ""), subtasks=subtasks, constraints=constraints, + schedule=schedule, generation_policy=generation_policy, + attempt_diagnostics=data.get("attempt_diagnostics"), ) + descriptor._validate_segments(require_schedule=data["algo"] == "schedulegen") + return descriptor + + def _validate_segments(self, *, require_schedule: bool) -> None: + """Check segment identities, dependencies, event pairing and schedule references. + + Args: + require_schedule: Whether every subtask must declare named schedule segments. + """ + segment_ids: set[SegmentId] = set() + resource_eefs: dict[str, set[str]] = {} + for eef_name, subtasks in self.subtasks.items(): + names = tuple(subtask.name for subtask in subtasks if subtask.name) + assert len(names) == len(set(names)), f"duplicate subtask name for {eef_name!r}" + for subtask_index, subtask in enumerate(subtasks): + assert require_schedule or not subtask.segments, "explicit segments require the ScheduleGen algorithm" + if require_schedule: + assert ( + subtask.name and subtask.segments + ), f"ScheduleGen subtask {eef_name!r} requires a name and segments" + segment_shape = tuple((segment.kind, segment.provider) for segment in subtask.segments) + skill_only_shape = ((SegmentKind.SKILL, SegmentProvider.DEMONSTRATION),) + motion_only_shape = ((SegmentKind.TRANSIT, SegmentProvider.MOTION_PLANNER),) + base_shape = ( + (SegmentKind.TRANSIT, SegmentProvider.MOTION_PLANNER), + (SegmentKind.SKILL, SegmentProvider.DEMONSTRATION), + ) + skill_motion_shape = skill_only_shape + motion_only_shape + base_motion_shape = base_shape + motion_only_shape + hold_shape = base_shape + ((SegmentKind.HOLD, SegmentProvider.SCRIPTED),) + direct_egress_shape = base_shape + ((SegmentKind.TRANSIT, SegmentProvider.SCRIPTED),) + hold_egress_shape = hold_shape + ((SegmentKind.TRANSIT, SegmentProvider.SCRIPTED),) + is_skill_only = segment_shape == skill_only_shape + is_motion_only = segment_shape == motion_only_shape + is_base = segment_shape == base_shape + is_skill_motion = segment_shape == skill_motion_shape + is_base_motion = segment_shape == base_motion_shape + is_hold = segment_shape == hold_shape + is_direct_egress = segment_shape == direct_egress_shape + is_hold_egress = segment_shape == hold_egress_shape + is_release = is_hold or is_direct_egress or is_hold_egress + assert ( + is_skill_only or is_motion_only or is_base or is_skill_motion or is_base_motion or is_release + ), ( + "current ScheduleGen runtime requires one motion-planned transit, one demonstration " + "skill, an optional incoming and/or outgoing motion-planned transit around that skill, " + "or the bounded scripted release suffix " + f"for {eef_name}.{subtask.name}; got {segment_shape}" + ) + if is_release: + assert ( + subtask_index == len(subtasks) - 1 + ), f"the bounded release form is supported only on the final subtask for {eef_name!r}" + + skill_index = None if is_motion_only else int(is_base or is_base_motion or is_release) + for segment_index, segment in enumerate(subtask.segments): + assert not segment.events or segment_index == skill_index, ( + "current ScheduleGen runtime supports events only on the demonstration " + f"skill for {eef_name}.{subtask.name}" + ) + assert ( + not segment.robot_contacts + or segment.kind == SegmentKind.SKILL + or (segment.provider == SegmentProvider.SCRIPTED) + ), ( + "robot contacts are supported only on demonstration or scripted " + f"segments; got {eef_name}.{subtask.name}.{segment.name}" + ) + annotation_keys = { + event.annotation_key + for event in segment.events + if event.point == SegmentEventPoint.SOURCE_ANNOTATION + } + for contact in segment.robot_contacts: + assert ( + not contact.start_annotation_key or contact.start_annotation_key in annotation_keys + ), ( + "robot-contact start_annotation_key must name a source-annotation " + f"event on {eef_name}.{subtask.name}.{segment.name}" + ) + + skill = subtask.segments[skill_index] if skill_index is not None else None + if is_base or is_base_motion or is_release: + assert skill is not None + transit = subtask.segments[0] + expected_goal_segment_id = SegmentId(eef_name, subtask.name, skill.name) + assert transit.goal_segment_id == expected_goal_segment_id, ( + "current ScheduleGen motion-planned transit must target its same-subtask " + f"demonstration skill {expected_goal_segment_id}; got {transit.goal_segment_id}" + ) + if is_motion_only or is_skill_motion or is_base_motion: + outgoing_motion = subtask.segments[-1] + assert outgoing_motion.motion_goal is not None, ( + f"outgoing motion-planned segment {eef_name}.{subtask.name}.{outgoing_motion.name} " + "requires an independent motion_goal" + ) + if not is_release: + assert all( + segment.demonstration_source_window is None + and segment.duration_steps == 0 + and not segment.passthrough_preset + and not segment.cartesian_offset_m + for segment in subtask.segments + ), ( + "legacy ScheduleGen transit/skill pairs and demonstration-only subtasks do not " + f"support release-hold provider fields for {eef_name}.{subtask.name}" + ) + else: + assert skill is not None + hold = subtask.segments[2] if is_hold or is_hold_egress else None + egress = subtask.segments[-1] if is_direct_egress or is_hold_egress else None + assert ( + transit.demonstration_source_window is None + and transit.duration_steps == 0 + and not transit.passthrough_preset + and not transit.cartesian_offset_m + ), f"release entry transit has unexpected provider fields for {eef_name}.{subtask.name}" + source_window = skill.demonstration_source_window + assert source_window is not None, ( + "the bounded release form requires a demonstration_source_window on " + f"{eef_name}.{subtask.name}.{skill.name}" + ) + assert ( + skill.duration_steps == 0 and not skill.passthrough_preset and not skill.cartesian_offset_m + ), ( + "release demonstration skill supports only demonstration_source_window " + f"provider fields for {eef_name}.{subtask.name}" + ) + matching_anchors = [ + event + for event in skill.events + if event.point == SegmentEventPoint.SOURCE_ANNOTATION + and event.annotation_key == source_window.anchor_annotation_key + ] + assert len(matching_anchors) == 1, ( + "demonstration_source_window anchor must match exactly one declared " + f"source-annotation event on {eef_name}.{subtask.name}.{skill.name}" + ) + release_event = matching_anchors[0] + assert release_event.event_type == SegmentEventType.DETACH, ( + "demonstration_source_window anchor must be a detach event on " + f"{eef_name}.{subtask.name}.{skill.name}" + ) + assert ( + len(skill.robot_contacts) == 1 + ), f"release form requires one robot contact on skill for {eef_name}.{subtask.name}" + skill_contact = skill.robot_contacts[0] + assert ( + skill_contact.start_annotation_key == release_event.annotation_key + and skill_contact.object_ref == release_event.object_ref + ), ( + "release source event and robot contact must name the same object " + f"and annotation on {eef_name}.{subtask.name}.{skill.name}" + ) + previous_contact = skill_contact + if hold is not None: + assert ( + len(hold.robot_contacts) == 1 + ), f"release form requires one robot contact on hold for {eef_name}.{subtask.name}" + hold_contact = hold.robot_contacts[0] + assert ( + hold_contact.object_ref == skill_contact.object_ref + and hold_contact.robot_link_names == skill_contact.robot_link_names + and not hold_contact.start_annotation_key + and not hold_contact.clear_at_end + ), ( + "release skill and hold must authorize the same exact " + f"robot/object pairs for {eef_name}.{subtask.name}" + ) + assert ( + hold.demonstration_source_window is None + and hold.duration_steps > 0 + and hold.passthrough_preset + and not hold.cartesian_offset_m + ), ( + "scripted hold requires positive duration_steps and a passthrough_preset for " + f"{eef_name}.{subtask.name}" + ) + previous_contact = hold_contact + if egress is not None: + assert ( + egress.demonstration_source_window is None + and egress.duration_steps >= 2 + and (hold is None or egress.passthrough_preset == hold.passthrough_preset) + and len(egress.cartesian_offset_m) == 3 + and any(value != 0.0 for value in egress.cartesian_offset_m) + ), ( + "scripted Cartesian egress requires at least two steps, any preceding hold's " + "passthrough preset, and a nonzero XYZ offset for " + f"{eef_name}.{subtask.name}" + ) + assert len(egress.robot_contacts) == 1, ( + "scripted Cartesian egress requires one terminal-clear robot contact for " + f"{eef_name}.{subtask.name}" + ) + egress_contact = egress.robot_contacts[0] + assert ( + egress_contact.object_ref == previous_contact.object_ref + and egress_contact.robot_link_names == previous_contact.robot_link_names + and not egress_contact.start_annotation_key + and egress_contact.clear_at_end + ), ( + "release suffix and egress must authorize the same exact robot/object pairs, " + f"with a strictly clear egress endpoint for {eef_name}.{subtask.name}" + ) + segment_names = tuple(segment.name for segment in subtask.segments) + assert len(segment_names) == len( + set(segment_names) + ), f"duplicate segment name under {eef_name}.{subtask.name}" + for segment_name in segment_names: + segment_id = SegmentId(eef_name, subtask.name, segment_name) + segment_ids.add(segment_id) + for segment in subtask.segments: + for resource_id in segment.resource_ids: + resource_eefs.setdefault(resource_id, set()).add(eef_name) + + if require_schedule: + assert self.schedule is not None, "ScheduleGen requires a schedule block" + assert require_schedule or not resource_eefs, "segment resource_ids are currently supported only by ScheduleGen" + for resource_id, eef_names in resource_eefs.items(): + assert ( + len(eef_names) >= 2 + ), f"resource {resource_id!r} must be claimed by segments on at least two end-effector lanes" + segments_by_id = { + SegmentId(eef_name, subtask.name, segment.name): segment + for eef_name, subtasks in self.subtasks.items() + for subtask in subtasks + for segment in subtask.segments + } + segment_indices = { + segment_id: index + for eef_name in self.subtasks + for index, segment_id in enumerate( + segment_id for segment_id in segments_by_id if segment_id.eef_name == eef_name + ) + } + for consumer_id, consumer in segments_by_id.items(): + goal = consumer.motion_goal + if goal is None or goal.object_pose_after_segment_id is None: + continue + assert require_schedule, "object_pose_after_segment_id is currently supported only by ScheduleGen" + producer_id = goal.object_pose_after_segment_id + assert producer_id in segments_by_id, f"motion goal references unknown effect segment {producer_id}" + assert producer_id != consumer_id, "a motion goal cannot consume its own object pose" + producer = segments_by_id[producer_id] + assert any( + event.event_type == SegmentEventType.DETACH and event.object_ref == goal.object_ref + for event in producer.events + ), ( + f"effect producer {producer_id} must detach motion-goal object {goal.object_ref!r} " + "before its terminal pose can be consumed" + ) + if producer_id.eef_name == consumer_id.eef_name: + assert ( + segment_indices[producer_id] < segment_indices[consumer_id] + ), f"effect producer {producer_id} must precede consumer {consumer_id} on its EEF lane" + continue + assert self.schedule is not None + assert any( + isinstance(constraint, PrecedenceConstraintSpec) + and constraint.before.segment_id == producer_id + and constraint.before.point == SegmentAnchorPoint.END + and constraint.after.segment_id == consumer_id + and constraint.after.point == SegmentAnchorPoint.START + for constraint in self.schedule.constraints + ), ( + f"cross-lane object-pose dependency {producer_id} -> {consumer_id} requires explicit " + "producer.end -> consumer.start precedence" + ) + self.get_path_build_order() + policy = self.generation_policy + if not self.requires_source_demos(): + assert policy.source_selection_anchor is None, "source_selection_anchor requires demonstration segments" + assert policy.source_demo_keys is None, "source_demo_keys requires demonstration segments" + if policy.source_selection_anchor is not None: + assert require_schedule, "explicit episode source selection is currently supported only by ScheduleGen" + assert ( + not policy.select_src_per_subtask and not policy.select_src_per_arm + ), "source_selection_anchor requires one shared source per episode" + eef_name, separator, subtask_name = policy.source_selection_anchor.partition(".") + assert ( + separator and eef_name in self.subtasks + ), "source_selection_anchor must name a known '.'" + assert any( + subtask.name == subtask_name for subtask in self.subtasks[eef_name] + ), f"source_selection_anchor references unknown subtask {policy.source_selection_anchor!r}" + else: + assert ( + policy.source_candidate_count == 1 + ), "source_candidate_count greater than one requires source_selection_anchor" + if self.schedule is not None: + referenced = { + segment_id + for constraint in self.schedule.constraints + for segment_id in constraint.referenced_segment_ids + } + missing = referenced - segment_ids + assert not missing, f"schedule references unknown segments: {sorted(map(str, missing))}" + for constraint in self.schedule.constraints: + if not isinstance(constraint, NonPreemptiveConstraintSpec): + continue + eef_names = {segment_id.eef_name for segment_id in constraint.segments} + assert len(eef_names) == 1, "non-preemptive segments must use one end-effector lane" + indices = tuple(segment_indices[segment_id] for segment_id in constraint.segments) + assert indices == tuple( + range(indices[0], indices[0] + len(indices)) + ), "non-preemptive segments must be a contiguous lane sequence in declaration order" diff --git a/autodata_interfaces/tasks/task_descriptor_utils.py b/autodata_interfaces/tasks/task_descriptor_utils.py index 6143c4f..8c7f2f5 100644 --- a/autodata_interfaces/tasks/task_descriptor_utils.py +++ b/autodata_interfaces/tasks/task_descriptor_utils.py @@ -9,6 +9,27 @@ from typing import Any, get_origin, get_type_hints from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy +from autodata_interfaces.tasks.schedule_constraint_spec import ( + NonOverlapConstraintSpec, + NonPreemptiveConstraintSpec, + PrecedenceConstraintSpec, + SchedulerStrategy, + ScheduleSpec, + SegmentAnchor, +) +from autodata_interfaces.tasks.segment_spec import ( + DemonstrationSourceWindowSpec, + MotionGoalSpec, + SegmentEventPoint, + SegmentEventSpec, + SegmentEventType, + SegmentId, + SegmentKind, + SegmentProvider, + SegmentRobotContactSpec, + SegmentSpec, + SegmentWorldContactSpec, +) from autodata_interfaces.tasks.subtask_constraint_spec import ( SubtaskConstraint, SubTaskConstraintCoordinationScheme, @@ -40,7 +61,13 @@ def validate_task_dict(data: dict[str, Any]) -> None: assert isinstance(data, dict), f"Expected top-level dict, got {type(data).__name__}" required_keys = {"name", "algo", "subtasks"} - optional_keys = {"description", "constraints", "generation_policy"} + optional_keys = { + "attempt_diagnostics", + "constraints", + "description", + "generation_policy", + "schedule", + } keys = set(data) missing = required_keys - keys assert not missing, f"Missing required top-level keys: {sorted(missing)}" @@ -55,7 +82,12 @@ def validate_task_dict(data: dict[str, Any]) -> None: assert ( data["algo"] in ALGO_PARAMS_REGISTRY ), f"Unknown algo {data['algo']!r}. Registered: {sorted(ALGO_PARAMS_REGISTRY)}" - + attempt_diagnostics = data.get("attempt_diagnostics") + assert attempt_diagnostics is None or ( + isinstance(attempt_diagnostics, str) + and attempt_diagnostics.strip() == attempt_diagnostics + and attempt_diagnostics + ), "'attempt_diagnostics' must be a non-empty, trimmed callable path" subtasks = data["subtasks"] assert isinstance( subtasks, dict @@ -64,6 +96,12 @@ def validate_task_dict(data: dict[str, Any]) -> None: algo_cls = ALGO_PARAMS_REGISTRY[data["algo"]] subtask_keys = {f.name for f in fields(Subtask)} algo_keys = {f.name for f in fields(algo_cls)} + segment_keys = {f.name for f in fields(SegmentSpec)} + event_keys = {f.name for f in fields(SegmentEventSpec)} + source_window_keys = {f.name for f in fields(DemonstrationSourceWindowSpec)} + motion_goal_keys = {f.name for f in fields(MotionGoalSpec)} + robot_contact_keys = {f.name for f in fields(SegmentRobotContactSpec)} + world_contact_keys = {f.name for f in fields(SegmentWorldContactSpec)} for eef_name, eef_subtasks in subtasks.items(): assert isinstance( @@ -85,6 +123,60 @@ def validate_task_dict(data: dict[str, Any]) -> None: f"{sorted(ap_unknown)} for algo {data['algo']!r}. " f"Allowed: {sorted(algo_keys)}" ) + segments = st.get("segments", []) + assert isinstance(segments, list), f"subtasks[{eef_name!r}][{i}].segments must be a list" + for segment in segments: + assert isinstance(segment, dict), "each segment must be a mapping" + assert {"name", "kind", "provider"}.issubset(segment), "segments require name, kind, and provider" + segment_unknown = set(segment) - segment_keys + assert not segment_unknown, f"segment has unknown keys: {sorted(segment_unknown)}" + events = segment.get("events", []) + assert isinstance(events, list), "segment.events must be a list" + for event in events: + assert isinstance(event, dict), "each segment event must be a mapping" + assert {"event_type", "object_ref"}.issubset( + event + ), "segment events require event_type and object_ref" + assert ( + not set(event) - event_keys + ), f"segment event has unknown keys: {sorted(set(event) - event_keys)}" + if "demonstration_source_window" in segment: + source_window = segment["demonstration_source_window"] + assert isinstance(source_window, dict), "segment.demonstration_source_window must be a mapping" + assert set(source_window) == source_window_keys, ( + "segment.demonstration_source_window requires exactly " + "anchor_annotation_key and post_event_sample_count" + ) + if "motion_goal" in segment: + motion_goal = segment["motion_goal"] + assert isinstance(motion_goal, dict), "segment.motion_goal must be a mapping" + required_motion_goal_keys = {"position_m", "rotation_xyzw"} + assert required_motion_goal_keys <= set( + motion_goal + ), "segment.motion_goal requires position_m and rotation_xyzw" + assert ( + not set(motion_goal) - motion_goal_keys + ), f"segment.motion_goal has unknown keys: {sorted(set(motion_goal) - motion_goal_keys)}" + robot_contacts = segment.get("robot_contacts", []) + assert isinstance(robot_contacts, list), "segment.robot_contacts must be a list" + for contact in robot_contacts: + assert isinstance(contact, dict), "each segment robot contact must be a mapping" + assert {"object_ref", "robot_link_names"}.issubset( + contact + ), "segment robot contacts require object_ref and robot_link_names" + assert ( + not set(contact) - robot_contact_keys + ), f"segment robot contact has unknown keys: {sorted(set(contact) - robot_contact_keys)}" + assert isinstance( + contact["robot_link_names"], list + ), "segment robot contact robot_link_names must be a list" + world_contacts = segment.get("world_contacts", []) + assert isinstance(world_contacts, list), "segment.world_contacts must be a list" + for contact in world_contacts: + assert isinstance(contact, dict), "each segment world contact must be a mapping" + assert ( + set(contact) == world_contact_keys + ), "segment world contacts require exactly object_ref and fixture_ref" constraints = data.get("constraints", []) assert isinstance(constraints, list), f"'constraints' must be a list, got {type(constraints).__name__}" @@ -105,6 +197,20 @@ def validate_task_dict(data: dict[str, Any]) -> None: not policy_unknown ), f"'generation_policy' has unknown keys {sorted(policy_unknown)}. Allowed: {sorted(policy_keys)}" + schedule = data.get("schedule") + if schedule is not None: + assert isinstance(schedule, dict), "'schedule' must be a mapping" + schedule_keys = { + "strategy", + "constraints", + "collision_margin_m", + "time_limit_s", + "max_block_size", + "minimize_max_wait", + } + assert not set(schedule) - schedule_keys, f"unknown schedule keys: {sorted(set(schedule) - schedule_keys)}" + assert isinstance(schedule.get("constraints", []), list), "schedule.constraints must be a list" + def resolve_task_algorithm(algorithm: str | None, task_descriptor_path: str) -> str: """Validate a task descriptor YAML and return its ``algo``. @@ -170,10 +276,96 @@ def build_subtask(st_data: dict[str, Any], algo_cls: type[SubtaskAlgoParams]) -> st_data = dict(st_data) # copy so we don't mutate caller's dict algo_kwargs = st_data.pop("algo_params", {}) + segment_data = st_data.pop("segments", []) st_kwargs = _coerce_tuples(st_data, get_type_hints(Subtask)) - return Subtask(**st_kwargs, algo_params=algo_cls.from_dict(algo_kwargs)) + return Subtask( + **st_kwargs, + segments=tuple(build_segment(segment) for segment in segment_data), + algo_params=algo_cls.from_dict(algo_kwargs), + ) + + +def build_segment(data: dict[str, Any]) -> SegmentSpec: + """Build one scheduled trajectory segment.""" + + values = dict(data) + events = values.pop("events", []) + source_window = values.pop("demonstration_source_window", None) + motion_goal = values.pop("motion_goal", None) + robot_contacts = values.pop("robot_contacts", []) + world_contacts = values.pop("world_contacts", []) + values["kind"] = SegmentKind(values["kind"]) + values["provider"] = SegmentProvider(values["provider"]) + if "goal_segment_id" in values: + values["goal_segment_id"] = SegmentId.from_string(values["goal_segment_id"]) + if motion_goal is not None and "object_pose_after_segment_id" in motion_goal: + motion_goal = dict(motion_goal) + motion_goal["object_pose_after_segment_id"] = SegmentId.from_string(motion_goal["object_pose_after_segment_id"]) + values = _coerce_tuples(values, get_type_hints(SegmentSpec)) + return SegmentSpec( + **values, + events=tuple(build_segment_event(event) for event in events), + motion_goal=( + MotionGoalSpec(**_coerce_tuples(motion_goal, get_type_hints(MotionGoalSpec))) + if motion_goal is not None + else None + ), + demonstration_source_window=( + DemonstrationSourceWindowSpec(**source_window) if source_window is not None else None + ), + robot_contacts=tuple( + SegmentRobotContactSpec(**{**contact, "robot_link_names": tuple(contact["robot_link_names"])}) + for contact in robot_contacts + ), + world_contacts=tuple(SegmentWorldContactSpec(**contact) for contact in world_contacts), + ) + + +def build_segment_event(data: dict[str, Any]) -> SegmentEventSpec: + """Build one object-state event.""" + + values = dict(data) + values["event_type"] = SegmentEventType(values["event_type"]) + if "point" in values: + values["point"] = SegmentEventPoint(values["point"]) + return SegmentEventSpec(**values) + + +def build_schedule(data: dict[str, Any]) -> ScheduleSpec: + """Build the compact waypoint-retiming schedule specification.""" + + values = dict(data) + constraints = values.pop("constraints", []) + if "strategy" in values: + values["strategy"] = SchedulerStrategy(values["strategy"]) + parsed_constraints = [] + for constraint in constraints: + assert isinstance(constraint, dict), "each schedule constraint must be a mapping" + item = dict(constraint) + constraint_type = item.pop("type", None) + if constraint_type == "precedence": + item["before"] = SegmentAnchor.from_string(item["before"]) + item["after"] = SegmentAnchor.from_string(item["after"]) + parsed_constraints.append(PrecedenceConstraintSpec(**item)) + elif constraint_type == "non_overlap": + assert set(item) == {"segments"}, "non_overlap requires exactly a segments field" + segments = item["segments"] + assert isinstance(segments, list) and len(segments) == 2, "non_overlap.segments must contain two IDs" + parsed_constraints.append( + NonOverlapConstraintSpec(tuple(SegmentId.from_string(value) for value in segments)) + ) + elif constraint_type == "non_preemptive": + assert set(item) == {"segments"}, "non_preemptive requires exactly a segments field" + segments = item["segments"] + assert isinstance(segments, list) and segments, "non_preemptive.segments must not be empty" + parsed_constraints.append( + NonPreemptiveConstraintSpec(tuple(SegmentId.from_string(value) for value in segments)) + ) + else: + assert False, f"unsupported schedule constraint type: {constraint_type!r}" + return ScheduleSpec(**values, constraints=tuple(parsed_constraints)) def build_constraint(c_data: dict[str, Any]) -> SubtaskConstraint: diff --git a/autodata_tests/core/test_algorithms.py b/autodata_tests/core/test_algorithms.py index 05d0651..cd9ad18 100644 --- a/autodata_tests/core/test_algorithms.py +++ b/autodata_tests/core/test_algorithms.py @@ -21,6 +21,7 @@ ) from autodata_core.data_generator import _EEFGenerationState from autodata_core.datagen_info import DatagenInfo +from autodata_core.schedulegen import ScheduleGen from autodata_interfaces.tasks.subtask_spec import SoftMimicGenSubtaskAlgoParams, Subtask @@ -30,6 +31,7 @@ def test_registry_contents(): "dexmimicgen": DexMimicGen, "softmimicgen": SoftMimicGen, "skillgen": SkillGen, + "schedulegen": ScheduleGen, } @@ -40,7 +42,7 @@ def test_base_class_not_registered(): def test_iter_algorithms(): - assert set(iter_algorithms()) == {MimicGen, DexMimicGen, SoftMimicGen, SkillGen} + assert set(iter_algorithms()) == {MimicGen, DexMimicGen, SoftMimicGen, SkillGen, ScheduleGen} @pytest.mark.parametrize( diff --git a/autodata_tests/core/test_data_generator.py b/autodata_tests/core/test_data_generator.py index 83d227f..11ec807 100644 --- a/autodata_tests/core/test_data_generator.py +++ b/autodata_tests/core/test_data_generator.py @@ -24,6 +24,13 @@ from autodata_interfaces.tasks.subtask_spec import MimicGenSubtaskAlgoParams, Subtask +def test_generation_result_preserves_positional_extras(): + extras = {"example": 1} + result = GenerationResult({}, True, extras) + assert result.extras is extras + assert result.diagnostics == () + + def _subtask(term_signal: str = "s", term_offset: tuple[int, int] = (0, 0)) -> Subtask: return Subtask( subtask_term_signal=term_signal, @@ -202,6 +209,7 @@ def test_unresponsive_navigation_fails_and_finalizes_the_attempt(monkeypatch): generator = _navigation_generator(active=True, reached=False) generator.datastream.generation_policy.max_navigation_hold_steps = 3 recorder = Mock() + recorder.get_episode.return_value = SimpleNamespace(data={"actions": torch.zeros(1, 1)}) generator.datastream.env = SimpleNamespace(recorder_manager=recorder) waypoint = Waypoint(pose=torch.eye(4), passthrough_action={}) monkeypatch.setattr(generator.algorithm, "plan_subtask_trajectory", lambda **kwargs: ([waypoint, waypoint], False)) @@ -258,3 +266,100 @@ def test_source_selection_preserves_positional_arguments(): ) assert selected == 0 + + +@pytest.mark.parametrize("recorded_steps", [False, True]) +def test_finalization_does_not_export_a_reset_snapshot_without_steps(recorded_steps): + recorder = Mock() + data = {"initial_state": {}} + if recorded_steps: + data["obs"] = torch.zeros(1, 2) + recorder.get_episode.return_value = SimpleNamespace(data=data) + generator = object.__new__(DataGenerator) + generator.datastream = SimpleNamespace(device="cpu", get_env=lambda: SimpleNamespace(recorder_manager=recorder)) + generator._finalize_episode_recording(env_id_tensor=torch.tensor([0]), success=False, export_demo=True) + recorder.set_success_to_episodes.assert_called_once() + assert recorder.export_episodes.call_count == int(recorded_steps) + + +@pytest.mark.parametrize( + "num_envs,num_trials,guarantee_success,fail_first,step_count,expected_attempts,expected_success", + [(5, 6, False, 0, 2, 6, 6), (5, 2, False, 0, 2, 2, 2), (3, 4, True, 2, 2, 6, 4), (3, 4, True, 100, 0, 6, 0)], +) +def test_generation_loop_reserves_exact_budget_and_holds_idle_relative_targets( + num_envs, num_trials, guarantee_success, fail_first, step_count, expected_attempts, expected_success +): + from autodata_interfaces.env.isaaclab_env_interface import env_loop + + policy = GenerationPolicy(num_trials=num_trials, guarantee_success=guarantee_success, max_num_failures=2) + env = SimpleNamespace( + num_envs=num_envs, + cfg=SimpleNamespace(), + device="cpu", + action_space=SimpleNamespace(shape=(num_envs, 1)), + action_manager=SimpleNamespace(action=torch.zeros(num_envs, 1)), + sim=SimpleNamespace(is_stopped=lambda: False), + positions=torch.zeros(num_envs), + ) + + def step(actions): + env.positions += actions[:, 0] + env.action_manager.action = actions.clone() + + def pose(env_ids, name): + result = torch.eye(4).repeat(len(env_ids), 1, 1) + result[:, 0, 3] = env.positions[env_ids] + return result + + def encode(target_eef_pose_dict, env_id, **kwargs): + return (target_eef_pose_dict["eef"][0, 3] - env.positions[env_id]).reshape(1) + + env.step = step + generator = object.__new__(DataGenerator) + generator.datastream = SimpleNamespace( + get_env=lambda: env, + get_generation_policy=lambda: policy, + get_eef_names=lambda: ["eef"], + get_robot_eef_pose=pose, + get_passthrough_actions=lambda ids: None if num_trials < num_envs else {}, + actions_to_passthrough_actions=lambda actions: {}, + target_eef_pose_to_action=encode, + ) + calls = [] + pending = set() + stats = {"num_success": 0, "num_failures": 0, "num_attempts": 0} + attempts = [] + + async def generate(env_id, env_action_queue, **kwargs): + index = len(calls) + calls.append(env_id) + assert len(pending) <= min(num_envs, num_trials) + for _ in range(step_count): + await env_action_queue.put((env_id, torch.ones(1))) + await env_action_queue.join() + return GenerationResult({}, success=index >= fail_first) + + generator.generate = generate + success_term = SimpleNamespace(func=lambda env: torch.zeros(num_envs, dtype=torch.bool), params={}) + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + action_queue = asyncio.Queue() + reset_queue = asyncio.Queue() + tasks = asyncio.gather(*( + generator.generate_loop(index, success_term, reset_queue, action_queue, False, stats, attempts, pending) + for index in range(num_envs) + )) + guarded = loop.create_task(asyncio.wait_for(tasks, timeout=2.0)) + try: + completed = env_loop(env, reset_queue, action_queue, loop, policy, stats, data_gen_tasks=guarded) + finally: + guarded.cancel() + loop.run_until_complete(asyncio.gather(guarded, return_exceptions=True)) + loop.close() + asyncio.set_event_loop(None) + assert completed is (expected_success >= num_trials if guarantee_success else True) + assert len(calls) == len(attempts) == stats["num_attempts"] == expected_attempts + assert stats["num_success"] == expected_success + assert stats["num_failures"] == expected_attempts - expected_success + assert not pending + assert env.positions.tolist() == [calls.count(index) * step_count for index in range(num_envs)] diff --git a/autodata_tests/core/test_datagen_info.py b/autodata_tests/core/test_datagen_info.py index 306c9f2..34b5bc4 100644 --- a/autodata_tests/core/test_datagen_info.py +++ b/autodata_tests/core/test_datagen_info.py @@ -17,6 +17,7 @@ def test_defaults_all_none(): assert di.subtask_start_signals is None assert di.target_eef_pose is None assert di.passthrough_action is None + assert di.object_event_signals is None assert di.to_dict() == {} @@ -39,6 +40,7 @@ def test_to_dict_key_names(): subtask_start_signals={}, target_eef_pose={}, passthrough_action={}, + object_event_signals={}, ) assert set(di.to_dict()) == { "eef_pose", @@ -48,6 +50,7 @@ def test_to_dict_key_names(): "subtask_start_signals", "target_eef_pose", "passthrough_action", + "object_event_signals", } @@ -83,3 +86,11 @@ def test_to_dict_deepcopies_object_nodal_positions(): out = di.to_dict() out["object_nodal_positions"]["rope"] += 1.0 assert torch.count_nonzero(di.object_nodal_positions["rope"]) == 0 + + +def test_to_dict_deepcopies_object_event_signals(): + """Source-event annotations are independent of a caller's exported copy.""" + info = DatagenInfo(object_event_signals={"grasp": torch.tensor([False, True])}) + exported = info.to_dict() + exported["object_event_signals"]["grasp"][1] = False + assert info.object_event_signals["grasp"][1] diff --git a/autodata_tests/core/test_pool.py b/autodata_tests/core/test_pool.py index 70f5490..8a37234 100644 --- a/autodata_tests/core/test_pool.py +++ b/autodata_tests/core/test_pool.py @@ -5,6 +5,7 @@ import torch import types +from pathlib import Path import pytest @@ -123,6 +124,23 @@ def _pool(task: TaskDescriptor, uses_start_signals: bool = False) -> DataGenInfo ) +def test_appending_after_a_subset_load_uses_an_unused_source_key(): + pool = _pool(_mimicgen_task()) + pool._add_episode(_mimicgen_episode(), demo_key="demo_1") + pool._add_episode(_mimicgen_episode()) + assert pool.demo_keys == ("demo_1", "demo_2") + + +def test_single_skill_can_load_without_an_unused_termination_mapping(): + task = _skillgen_task() + task.subtasks["franka"] = task.subtasks["franka"][:1] + pool = _pool(task, uses_start_signals=True) + episode = _skillgen_episode() + del episode.data["obs"]["datagen_info"]["subtask_term_signals"] + pool._add_episode(episode) + assert pool.subtask_boundaries["franka"] == [[(1, 10)]] + + def _episode(*, actions_len: int, datagen_info: dict, action_dim: int = 7) -> types.SimpleNamespace: return types.SimpleNamespace( data={"actions": torch.zeros(actions_len, action_dim), "obs": {"datagen_info": datagen_info}} @@ -212,6 +230,22 @@ def test_add_episode_parses_mimicgen_boundaries(): assert pool.subtask_boundaries["franka"] == [[(0, 5), (5, 10)]] +@pytest.mark.parametrize("uses_start_signals", [False, True]) +def test_add_episode_uses_first_trigger_when_signals_toggle(uses_start_signals): + """Later predicate changes must not move the first source subtask boundary.""" + pool = _pool(_skillgen_task() if uses_start_signals else _mimicgen_task(), uses_start_signals) + episode = _skillgen_episode() if uses_start_signals else _mimicgen_episode() + annotations = episode.data["obs"]["datagen_info"] + annotations["subtask_term_signals"]["grasp_1"] = torch.tensor([0, 0, 0, 0, 1, 0, 1, 0, 0, 0]) + if uses_start_signals: + annotations["subtask_start_signals"]["grasp_1"] = torch.tensor([0, 1, 0, 1, 1, 1, 1, 1, 1, 1]) + + pool._add_episode(episode) + + first_start, second_start = (1, 6) if uses_start_signals else (0, 5) + assert pool.subtask_boundaries["franka"] == [[(first_start, 5), (second_start, 10)]] + + def test_add_episode_populates_datagen_info_and_passthrough(): pool = _pool(_mimicgen_task()) pool._add_episode(_mimicgen_episode(actions_len=8, term_edge=3)) @@ -235,6 +269,40 @@ def test_add_episode_accepts_deformable_state_without_rigid_object_pose(): assert pool.subtask_boundaries["franka"] == [[(0, 4), (4, 8)]] +@pytest.mark.parametrize("sample", [0, 3, 9]) +def test_object_event_uses_exact_source_sample(sample): + """Object marks do not receive the completion signal's one-step end offset.""" + pool = _pool(_mimicgen_task()) + episode = _mimicgen_episode() + episode.data["obs"]["datagen_info"]["object_event_signals"] = {"grasp": _step_signal(10, sample)} + pool._add_episode(episode, demo_key="source") + assert pool.get_object_event_index(0, "grasp") == sample + assert "object_event_signals" in pool.datagen_infos[0].to_dict() + with pytest.raises(AssertionError, match="missing object event"): + pool.get_object_event_index(0, "release") + + +@pytest.mark.parametrize("signal", [torch.ones(9), torch.ones(1, 10), torch.full((10,), 0.5), torch.zeros(10)]) +def test_object_event_rejects_invalid_signal(signal): + """Malformed, nonbinary and unmarked events fail when the source is loaded.""" + pool = _pool(_mimicgen_task()) + episode = _mimicgen_episode() + episode.data["obs"]["datagen_info"]["object_event_signals"] = {"grasp": signal} + with pytest.raises((AssertionError, ValueError)): + pool._add_episode(episode) + + +def test_required_object_events_are_checked_before_source_is_added(): + """A task requesting internal marks cannot silently fall back to skill boundaries.""" + task = TaskDescriptor.from_yaml( + str(Path(__file__).resolve().parents[2] / "autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml") + ) + pool = DataGenInfoPool(task, _bimanual_adapter(), "cpu", uses_start_signals=True) + with pytest.raises(AssertionError, match="missing object_event_signals"): + pool._add_episode(_dexmimicgen_episode()) + assert pool.num_datagen_infos == 0 + + def test_add_episode_missing_datagen_info_error(): pool = _pool(_mimicgen_task()) bad = types.SimpleNamespace(data={"actions": torch.zeros(5, 7), "obs": {}}) diff --git a/autodata_tests/core/test_schedulegen.py b/autodata_tests/core/test_schedulegen.py new file mode 100644 index 0000000..8d0041a --- /dev/null +++ b/autodata_tests/core/test_schedulegen.py @@ -0,0 +1,860 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Path-building and replay invariants.""" + +import asyncio +import torch +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +import autodata_core.schedulegen.algorithm as algorithm_module +from autodata_core.algorithms import get_algorithm +from autodata_core.data_generator import DataGenerator +from autodata_core.datagen_info import DatagenInfo +from autodata_core.schedulegen import ScheduleGen +from autodata_core.schedulegen.collision import _joint_timeline_densify, _path_densify, scheduled_world_validate +from autodata_core.schedulegen.path_builder import PathBuilder +from autodata_core.schedulegen.scheduling import schedule_robot_contacts, schedule_world_contacts +from autodata_core.schedulegen.types import ( + ArmPath, + EpisodeGenerationError, + EpisodePaths, + PathObjectEvent, + ScheduledObjectEvent, +) +from autodata_core.scheduling import Schedule +from autodata_core.waypoint import Waypoint +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory +from autodata_interfaces.tasks.schedule_constraint_spec import SegmentId +from autodata_interfaces.tasks.segment_spec import ( + SegmentEventPoint, + SegmentEventSpec, + SegmentEventType, + SegmentRobotContactSpec, + SegmentWorldContactSpec, +) +from autodata_utils import pose_math + + +@pytest.mark.parametrize("collision_kind", ["self", "world"]) +def test_reset_transition_and_world_queries_use_dense_boundary_samples(collision_kind): + from autodata_core.schedulegen.collision import scheduled_robot_validate + + segment = SegmentId.from_string("left.move.transit") + path = ArmPath("left", (Waypoint(torch.eye(4), {}),) * 2, torch.full((2, 1), 2.0), {segment: (0, 2)}) + config = SimpleNamespace(ee_link_name="tool", position_threshold=0.01, rotation_threshold=0.01) + planner = SimpleNamespace( + active_joint_names=("joint",), + locked_joint_positions={}, + plan_visualizer=None, + planning_root_pose_refresh=lambda: None, + joint_positions_to_link_poses=lambda states, links: {"tool": torch.eye(4).repeat(len(states), 1, 1)}, + joint_positions_self_collision_free=lambda states, margin: ( + (states[:, 0] != 1) if collision_kind == "self" else torch.ones(len(states), dtype=torch.bool) + ), + update_world=lambda: None, + joint_positions_world_collision_free=lambda states, margin, **kwargs: states[:, 0] != 1, + ) + arguments = ( + SimpleNamespace(get_robot_joint_names=lambda: ["joint"]), + {"left": SimpleNamespace(active_joint_names=("joint",), config=config)}, + planner, + {"left": path}, + Schedule({segment: (0, 1)}, 2), + torch.zeros(1), + ) + if collision_kind == "self": + with pytest.raises(EpisodeGenerationError, match="self collision"): + scheduled_robot_validate(*arguments, collision_margin_m=0, densify_factor=2) + else: + robot = scheduled_robot_validate(*arguments, collision_margin_m=0, densify_factor=2) + assert robot.collision_sample_ticks == (0, 0.5, 1, 1.5, 2) + with pytest.raises(EpisodeGenerationError, match="schedule tick 0.5"): + scheduled_world_validate(planner, robot, {}, {}, collision_margin_m=0, object_manipulation_starts={}) + + +@pytest.mark.parametrize("has_release_contact", [False, True]) +def test_carried_object_checks_do_not_start_only_at_release(has_release_contact): + from autodata_core.schedulegen.collision import scheduled_robot_object_validate + from autodata_core.schedulegen.types import ScheduledRobotContact + + segment = SegmentId.from_string("left.release.skill") + contacts = ( + (ScheduledRobotContact(segment, SegmentRobotContactSpec("beaker", ("hand",)), 2, 3),) + if has_release_contact + else () + ) + robot = SimpleNamespace(initial_joint_positions=torch.zeros(1), joint_positions=torch.tensor([[1.0], [2.0]])) + planner = SimpleNamespace( + joint_positions_environment_spheres_collision_free=lambda states, *args, **kwargs: states[:, 0] != 1 + ) + with pytest.raises(EpisodeGenerationError, match="boundary tick 1"): + scheduled_robot_object_validate( + planner, + robot, + {"beaker": torch.ones(3, 1, 4)}, + collision_margin_m=0, + object_manipulation_starts={"beaker": 1}, + robot_contacts=contacts, + ) + + +def test_original_mesh_covers_object_until_manipulation_begins(): + from autodata_core.schedulegen.collision import scheduled_robot_object_validate + + robot = SimpleNamespace(initial_joint_positions=torch.zeros(1), joint_positions=torch.tensor([[1.0], [2.0]])) + query = Mock(side_effect=lambda states, *args: states[:, 0] == 2) + planner = SimpleNamespace(joint_positions_environment_spheres_collision_free=query) + assert scheduled_robot_object_validate( + planner, + robot, + {"beaker": torch.ones(3, 1, 4)}, + collision_margin_m=0, + object_manipulation_starts={"beaker": 2}, + robot_contacts=(), + ) == (1, 0) + assert query.call_args.args[0].tolist() == [[2.0]] + + +def test_projected_objects_are_checked_against_each_other(): + first = torch.tensor([[[-2.0, 0, 0, 0.1]], [[0.0, 0, 0, 0.1]], [[-2.0, 0, 0, 0.1]]]) + second = first.clone() + second[:, :, 0] *= -1 + robot = SimpleNamespace( + joint_positions=torch.zeros(2, 1), collision_joint_positions=torch.zeros(3, 1), collision_sample_ticks=(0, 1, 2) + ) + planner = SimpleNamespace( + update_world=lambda: None, + joint_positions_world_collision_free=lambda states, *args, **kwargs: torch.ones(len(states), dtype=torch.bool), + environment_spheres_world_collision_free=lambda spheres, *args, **kwargs: torch.ones( + len(spheres), dtype=torch.bool + ), + ) + with pytest.raises(EpisodeGenerationError, match="projected objects"): + scheduled_world_validate( + planner, + robot, + {"first": first, "second": second}, + {name: SimpleNamespace(obstacle_path=f"/{name}") for name in ("first", "second")}, + collision_margin_m=0, + object_manipulation_starts={"first": 0, "second": 0}, + ) + + +@pytest.mark.parametrize("rejection", (None, "world", "projected")) +def test_object_pairs_switch_from_live_meshes_to_projected_spheres(rejection): + """Keep native mesh checks before manipulation and pair checks after both meshes leave.""" + first = torch.tensor([[[-2.0, 0, 0, 0.1]], [[0.0, 0, 0, 0.1]], [[-2.0, 0, 0, 0.1]]]) + if rejection == "projected": + first[2, 0, 0] = 0 + second = first.clone() + second[:, :, 0] *= -1 + queries = [] + + def world_clear(spheres, margin, *, excluded_obstacle_paths): + """Distinguish a real mesh collision from overlap of its sampled approximation.""" + queries.append(excluded_obstacle_paths) + clear = torch.ones(len(spheres), dtype=torch.bool) + if rejection == "world" and excluded_obstacle_paths == ("/first",): + clear[-1] = False + return clear + + robot = SimpleNamespace( + joint_positions=torch.zeros(2, 1), collision_joint_positions=torch.zeros(3, 1), collision_sample_ticks=(0, 1, 2) + ) + planner = SimpleNamespace( + update_world=lambda: None, + joint_positions_world_collision_free=lambda states, *args, **kwargs: torch.ones(len(states), dtype=torch.bool), + environment_spheres_world_collision_free=world_clear, + ) + arguments = ( + planner, + robot, + {"first": first, "second": second}, + {name: SimpleNamespace(obstacle_path=f"/{name}") for name in ("first", "second")}, + ) + options = {"collision_margin_m": 0, "object_manipulation_starts": {"first": 0, "second": 2}} + if rejection is None: + assert scheduled_world_validate(*arguments, **options) == (3, 6, 0) + else: + tick = "1/2" if rejection == "world" else "2" + with pytest.raises(EpisodeGenerationError, match=f"boundary tick {tick}"): + scheduled_world_validate(*arguments, **options) + assert ("/first",) in queries, "The stationary second object's original mesh must remain checked." + + +def test_grasp_and_carry_permissions_allow_only_the_carrying_hand(): + grasp, release = (SegmentId.from_string(f"left.{name}.skill") for name in ("grasp", "release")) + path = ArmPath("left", (Waypoint(torch.eye(4), {}),) * 5, torch.zeros(5, 1), {grasp: (0, 3), release: (3, 5)}) + events = tuple( + ScheduledObjectEvent( + tick, + PathObjectEvent( + segment, + 0, + SegmentEventSpec(kind, "beaker", attachment_frame="tool" if kind == SegmentEventType.ATTACH else ""), + torch.eye(4) if kind == SegmentEventType.ATTACH else None, + ), + ) + for tick, segment, kind in ( + (2, grasp, SegmentEventType.ATTACH), + (4, release, SegmentEventType.DETACH), + ) + ) + contacts = schedule_robot_contacts( + {"left": path}, + Schedule({grasp: (0, 1, 2), release: (3, 4)}, 5), + {}, + events, + attachment_link_names={"left": ("hand",)}, + ) + assert len(contacts) == 1 + assert (contacts[0].start_tick, contacts[0].stop_tick) == (0, 4) + assert contacts[0].spec.robot_link_names == ("hand",) + + +def test_carried_object_uses_the_same_boundary_as_the_robot(): + from autodata_core.schedulegen.scheduling import project_object_states + + segment = SegmentId.from_string("left.carry.skill") + tools = torch.eye(4).repeat(4, 1, 1) + tools[:, 0, 3] = torch.arange(4) + event = ScheduledObjectEvent( + 0, + PathObjectEvent( + segment, 0, SegmentEventSpec(SegmentEventType.ATTACH, "beaker", attachment_frame="tool"), torch.eye(4) + ), + ) + states = project_object_states({"beaker": torch.eye(4)}, {"left": tools}, ("beaker",), (event,), makespan_ticks=3) + assert [state.boundary_tick for state in states] == [0, 1, 2, 3] + assert [state.env_from_object[0][3] for state in states] == [0, 1, 2, 3] + + +def test_provider_object_samples_follow_the_completed_command(): + from autodata_core.schedulegen.scheduling import project_object_states + from autodata_core.schedulegen.types import PathObjectPose, ScheduledObjectPose + + segment = SegmentId.from_string("left.release.skill") + poses = torch.eye(4).repeat(3, 1, 1) + poses[:, 0, 3] = torch.arange(3) + samples = tuple( + ScheduledObjectPose(tick - 1, PathObjectPose(segment, tick, "beaker", poses[tick])) for tick in (1, 2) + ) + events = ( + ScheduledObjectEvent( + 0, + PathObjectEvent( + segment, 0, SegmentEventSpec(SegmentEventType.ATTACH, "beaker", attachment_frame="tool"), torch.eye(4) + ), + ), + ScheduledObjectEvent(1, PathObjectEvent(segment, 1, SegmentEventSpec(SegmentEventType.DETACH, "beaker"))), + ) + states = project_object_states( + {"beaker": poses[0]}, {"left": poses}, ("beaker",), events, samples, makespan_ticks=2 + ) + assert [state.env_from_object[0][3] for state in states] == [0, 1, 2] + + +def test_buffered_generation_rejects_ignored_reset_settling(): + from autodata_core.schedulegen.batching import generate_buffered + from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy + + datastream = SimpleNamespace( + get_env=lambda: None, get_generation_policy=lambda: GenerationPolicy(reset_settling_steps=2) + ) + with pytest.raises(AssertionError, match="does not support reset_settling_steps"): + generate_buffered( + env=None, + data_generator=SimpleNamespace(datastream=datastream), + algorithm=SimpleNamespace(planning_contexts={0: None}), + success_term=None, + schedule_workers=1, + ) + + +@pytest.mark.parametrize( + "point, slot", [(SegmentEventPoint.START, 0), (SegmentEventPoint.END, 6), (SegmentEventPoint.SOURCE_ANNOTATION, 4)] +) +def test_attachment_events_support_boundaries_and_embedded_annotations(point, slot): + """Boundary events need no extra marks; internal marks keep their exact merged path slot.""" + pool = SimpleNamespace( + demo_keys=("source",), + datagen_infos=[ + DatagenInfo( + target_eef_pose={"left": torch.eye(4).repeat(10, 1, 1)}, + object_poses={"beaker": torch.eye(4).repeat(10, 1, 1)}, + ) + ], + get_object_event_index=Mock(return_value=3), + ) + event = SegmentEventSpec( + SegmentEventType.ATTACH, + "beaker", + point=point, + attachment_frame="hand", + annotation_key="grasp" if point == SegmentEventPoint.SOURCE_ANNOTATION else "", + ) + resolved, poses = PathBuilder({})._skill_events_resolve( + data_generator=SimpleNamespace(src_demo_datagen_info_pool=pool), + planner=SimpleNamespace(config=SimpleNamespace(ee_link_name="hand")), + segment_id=SegmentId("left", "pick", "skill"), + events=(event,), + source_demo_index=0, + source_boundary=(1, 5), + source_length=4, + merged_skill=tuple(Waypoint(pose=torch.eye(4), passthrough_action={}) for _ in range(6)), + ) + assert tuple(resolved) == (slot,) + assert torch.equal(resolved[slot][0].tool_from_object, torch.eye(4)) + assert poses + if point == SegmentEventPoint.SOURCE_ANNOTATION: + pool.get_object_event_index.assert_called_once_with(0, "grasp") + else: + pool.get_object_event_index.assert_not_called() + + +@pytest.mark.parametrize("collision_tick", [None, 1, 3]) +def test_unmanipulated_object_mesh_remains_a_world_obstacle(collision_tick): + """Initial reaches cannot ignore an object merely because it is manipulated later.""" + calls = [] + + def robot_query(states, margin, *, excluded_obstacle_paths): + """Report a collision only while the original mesh is active.""" + calls.append((states[:, 0].tolist(), excluded_obstacle_paths)) + free = torch.ones(len(states), dtype=torch.bool) + if collision_tick is not None and "/bowl" not in excluded_obstacle_paths: + free &= states[:, 0] != collision_tick + return free + + planner = SimpleNamespace( + update_world=lambda: None, + joint_positions_world_collision_free=robot_query, + joint_positions_world_collision_witness=lambda *args, **kwargs: ("finger", 0, "/bowl"), + environment_spheres_world_collision_free=lambda spheres, *args, **kwargs: torch.ones( + len(spheres), dtype=torch.bool + ), + ) + arguments = ( + planner, + SimpleNamespace( + joint_positions=torch.arange(4).reshape(4, 1), + collision_joint_positions=torch.arange(4).reshape(4, 1), + collision_sample_ticks=(0.0, 1.0, 2.0, 3.0), + ), + {"bowl": torch.ones(5, 1, 4)}, + {"bowl": SimpleNamespace(obstacle_path="/bowl")}, + ) + options = dict(collision_margin_m=0.0, object_manipulation_starts={"bowl": 2}) + if collision_tick == 1: + with pytest.raises(EpisodeGenerationError, match="schedule tick 1/4"): + scheduled_world_validate(*arguments, **options) + else: + assert scheduled_world_validate(*arguments, **options) == (4, 5, 0) + assert calls == [([0, 1], ()), ([2, 3], ("/bowl",))] + + +def test_contact_intervals_preserve_initial_inter_segment_and_terminal_holds(): + """Contact permissions follow held occupancy rather than nominal segment endpoints.""" + release = SegmentId.from_string("left.release.skill") + hold = SegmentId.from_string("left.release.open_hold") + path = ArmPath( + eef_name="left", + waypoints=tuple(Waypoint(torch.eye(4), {}) for _ in range(5)), + joint_positions=torch.zeros(5, 1), + segment_bounds={release: (0, 2), hold: (2, 5)}, + ) + schedule = Schedule({release: (3, 5), hold: (8, 10, 12)}, makespan_ticks=15) + world_spec = SegmentWorldContactSpec("beaker", "bin") + contacts = schedule_world_contacts({"left": path}, schedule, {release: (world_spec,), hold: (world_spec,)}) + assert [(contact.start_tick, contact.stop_tick) for contact in contacts] == [(0, 8), (8, 16)] + + detach = ScheduledObjectEvent( + 5, + PathObjectEvent( + release, + 1, + SegmentEventSpec(SegmentEventType.DETACH, "beaker", SegmentEventPoint.SOURCE_ANNOTATION, "release"), + ), + ) + robot_contacts = schedule_robot_contacts( + {"left": path}, + schedule, + { + release: (SegmentRobotContactSpec("beaker", ("finger",), start_annotation_key="release"),), + hold: (SegmentRobotContactSpec("beaker", ("finger",), clear_at_end=True),), + }, + (detach,), + ) + assert [(contact.start_tick, contact.stop_tick) for contact in robot_contacts] == [(5, 8), (8, 12)] + with pytest.raises(AssertionError, match="exactly one event"): + schedule_robot_contacts( + {"left": path}, + schedule, + {release: (SegmentRobotContactSpec("beaker", ("finger",), start_annotation_key="missing"),)}, + (detach,), + ) + + +@pytest.mark.parametrize("shared_model", [False, True]) +def test_environment_contexts_and_caches_are_isolated_during_replay(monkeypatch, shared_model): + contexts = {env_id: SimpleNamespace(group_planners={"left": object()}, full_state=None) for env_id in (0, 1)} + algorithm = get_algorithm("schedulegen", planning_contexts=contexts) + contexts.clear() + assert isinstance(algorithm, ScheduleGen) + first, second = algorithm._path_builders.values() + assert first is not second + assert first._object_geometry_cache is not second._object_geometry_cache + seen = [] + + async def execute(self, *, env_id, **kwargs): + await asyncio.sleep(0) + seen.append(env_id) + return False + + def pose_error(datastream, planner, env_id, pose): + assert planner is algorithm.planning_contexts[0 if shared_model else env_id].group_planners["left"] + return 0.0, 0.0 + + for context in algorithm.planning_contexts.values(): + context.group_planners["left"] = SimpleNamespace( + config=SimpleNamespace(position_threshold=0.01, rotation_threshold=0.01) + ) + monkeypatch.setattr( + algorithm_module, "_scheduled_waypoints_build", lambda path, schedule: (SimpleNamespace(pose=None),) + ) + monkeypatch.setattr(algorithm_module.MultiWaypoint, "execute", execute) + monkeypatch.setattr(algorithm_module, "_terminal_pose_error", pose_error) + datastream = SimpleNamespace( + get_generation_policy=lambda: SimpleNamespace(final_hold_steps=0, terminal_convergence_steps=1), + get_robot_joint_positions=lambda env_ids: torch.zeros(1, 1), + ) + + async def replay_both(): + return await asyncio.gather(*( + algorithm._schedule_replay( + data_generator=SimpleNamespace(datastream=datastream), + env_id=env_id, + success_term=None, + env_action_queue=None, + arm_paths={"left": object()}, + schedule=SimpleNamespace(makespan_ticks=1), + planning_env_id=0 if shared_model else None, + ) + for env_id in (0, 1) + )) + + assert asyncio.run(replay_both()) == [(False, None), (False, None)] + assert sorted(seen) == [0, 1] + + +@pytest.mark.parametrize("build_fails", [False, True]) +def test_episode_hook_preserves_shared_reset_recording_and_failure_handling(monkeypatch, build_fails): + context = SimpleNamespace(group_planners={"left": object()}, full_state=None) + algorithm = ScheduleGen({0: context}) + order = [] + + def build(*args, **kwargs): + order.append("build") + if build_fails: + raise EpisodeGenerationError("planning", "no path") + return object(), () + + def restore(*args): + order.append("restore") + + async def replay(**kwargs): + order.append("replay") + return True, 0 + + monkeypatch.setattr(PathBuilder, "build", build) + monkeypatch.setattr(ScheduleGen, "_state_restore", staticmethod(restore)) + monkeypatch.setattr(algorithm, "_schedule_replay", replay) + monkeypatch.setattr( + algorithm, + "_episode_validate", + lambda **kwargs: SimpleNamespace( + arm_paths={}, + schedule=None, + replay_joint_trajectory=None, + diagnostics_before_success=(), + diagnostics_after_success=(), + ), + ) + generator = object.__new__(DataGenerator) + generator.algorithm = algorithm + generator.datastream = SimpleNamespace( + get_eef_names=lambda: ["left"], + get_schedule_spec=lambda: object(), + get_scene_state=lambda **kwargs: {}, + get_object_poses=lambda **kwargs: {}, + get_robot_joint_positions=lambda **kwargs: torch.zeros(1, 1), + ) + generator.src_demo_datagen_info_pool = SimpleNamespace(demo_keys=[]) + generator.randomize_subtask_boundaries = Mock(return_value={}) + generator._reset_environment_for_generation = AsyncMock(return_value=(torch.tensor([0]), {"reset": True})) + generator._finalize_episode_recording = Mock() + result = asyncio.run(generator.generate(0, None, env_reset_queue=None, env_action_queue=None, export_demo=False)) + assert result.initial_state == {"reset": True} + assert result.success is not build_fails + assert dict(result.diagnostics)["stage"] == ("planning" if build_fails else "complete") + assert order == (["build", "restore"] if build_fails else ["build", "restore", "replay"]) + generator._reset_environment_for_generation.assert_awaited_once() + assert generator._finalize_episode_recording.call_args.kwargs["success"] is not build_fails + assert generator._finalize_episode_recording.call_args.kwargs["export_demo"] is False + + +@pytest.mark.parametrize("failed_step", [None, "object_events", "object_poses", "world_contacts", "robot_contacts"]) +def test_scheduled_validation_preserves_diagnostics_and_failure_stages(monkeypatch, failed_step): + """Tick mapping retains successful diagnostics and identifies the first rejected step.""" + import autodata_core.schedulegen.scheduling as scheduling_module + + context = SimpleNamespace(group_planners={"left": object()}, full_state=None) + algorithm = ScheduleGen({0: context}) + segment = SegmentId.from_string("left.pick.skill") + path = ArmPath("left", (Waypoint(torch.eye(4), {}),), torch.zeros(1, 1), {segment: (0, 1)}) + datastream = SimpleNamespace(get_segment_world_contacts=lambda: {}, get_segment_robot_contacts=lambda: {}) + steps = ("object_events", "object_poses", "world_contacts", "robot_contacts") + arguments = dict( + data_generator=SimpleNamespace(datastream=datastream), + episode_paths=EpisodePaths({"left": path}, {}), + initial_object_poses={}, + initial_joint_positions=torch.zeros(1), + schedule_spec=SimpleNamespace(collision_margin_m=0.0), + conflicts=(), + schedule=Schedule({segment: (0,)}, makespan_ticks=1), + ) + if failed_step is not None: + monkeypatch.setattr(scheduling_module, f"schedule_{failed_step}", Mock(side_effect=AssertionError("invalid"))) + with pytest.raises(EpisodeGenerationError, match="invalid") as caught: + algorithm._episode_validate_scheduled(**arguments) + assert caught.value.stage == f"{failed_step.removesuffix('s')}_lowering" + diagnostics = caught.value.diagnostics + expected_steps = steps[: steps.index(failed_step)] + else: + validated = algorithm._episode_validate_scheduled(**arguments) + assert validated.replay_joint_trajectory is None + assert validated.diagnostics_after_success == () + diagnostics = validated.diagnostics_before_success + expected_steps = steps + assert tuple(name for name, _ in diagnostics) == ( + "object_collision_spheres", + "collision_conflicts", + "makespan_ticks", + "schedule_segments", + *(f"scheduled_{step}" for step in expected_steps), + ) + + +def test_buffered_states_stack_without_aliasing_or_extra_environment_rows(): + from autodata_core.schedulegen.batching import _states_stack + + states = [{"robot": {"position": torch.full((1, 2), float(index))}} for index in range(3)] + stacked = _states_stack(states) + assert torch.equal(stacked["robot"]["position"], torch.tensor([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]])) + stacked["robot"]["position"].zero_() + assert states[2]["robot"]["position"].sum() == 4 + with pytest.raises(AssertionError, match="exactly one environment"): + _states_stack([stacked]) + + +@pytest.mark.parametrize("guarantee_success", [False, True]) +def test_buffered_preparation_failures_use_the_finite_attempt_budget_without_empty_exports(guarantee_success): + from autodata_core.algorithms import AlgorithmEpisodeResult + from autodata_core.schedulegen.algorithm import _PreparedEpisode + from autodata_core.schedulegen.batching import generate_buffered + from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy + + env = SimpleNamespace(num_envs=3, recorder_manager=SimpleNamespace(reset=Mock()), reset=Mock()) + datastream = SimpleNamespace( + device="cpu", + get_env=lambda: env, + get_generation_policy=lambda: GenerationPolicy( + num_trials=5, guarantee_success=guarantee_success, max_num_failures=2 + ), + get_schedule_spec=lambda: object(), + ) + generator = SimpleNamespace(datastream=datastream) + prepare = Mock( + side_effect=lambda *args: _PreparedEpisode( + planning_env_id=0, + initial_state={}, + initial_object_poses={}, + initial_joint_positions=torch.zeros(1), + selected_source={}, + result=AlgorithmEpisodeResult(False, (("stage", "planning"),)), + ) + ) + algorithm = SimpleNamespace(planning_contexts={0: object()}, _episode_prepare=prepare) + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + result = generate_buffered(env, generator, algorithm, None, schedule_workers=2) + finally: + loop.close() + asyncio.set_event_loop(None) + count = 7 if guarantee_success else 5 + assert result["completed"] is not guarantee_success + assert result["stats"] == {"num_success": 0, "num_failures": count, "num_attempts": count} + assert len(result["attempts"]) == prepare.call_count == count + assert env.reset.call_count == count + assert result["execution"]["schedule_workers"] == 2 + + +@pytest.mark.parametrize( + "lengths, initial_success, initial_attempts, success", + [ + ((2, 5, 3), 0, 0, True), + ((2,), 0, 0, True), + ((2, 5, 3), 3, 5, True), + ((2,), 3, 5, True), + ((2,), 9, 9, True), + ((2,), 3, 59, False), + ], +) +def test_buffered_replay_exports_unequal_slots_once_without_hold_tails( + monkeypatch, capsys, lengths, initial_success, initial_attempts, success +): + import autodata_core.schedulegen.batching as batching + from autodata_core.algorithms import AlgorithmEpisodeResult + from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy + + env = SimpleNamespace( + num_envs=3, + device="cpu", + cfg=SimpleNamespace(), + action_space=SimpleNamespace(shape=(3, 1)), + recorder_manager=SimpleNamespace(reset=Mock()), + reset_to=Mock(), + sim=SimpleNamespace(is_stopped=lambda: False), + ticks=0, + ) + actions = [] + + def step(action): + actions.append(action.clone()) + env.ticks += 1 + + env.step = step + datastream = SimpleNamespace( + device="cpu", + get_env=lambda: env, + get_generation_policy=GenerationPolicy, + reset_robot_joint_posture_target=Mock(), + ) + exported = [] + executed = [] + generator = SimpleNamespace( + datastream=datastream, + _finalize_episode_recording=lambda **kwargs: exported.append((int(kwargs["env_id_tensor"][0]), env.ticks)), + ) + + async def send(env_id, queue, value): + await queue.put((env_id, torch.tensor([float(value)]))) + await queue.join() + + async def execute(generator, prepared, env_id, success_term, queue): + executed.append(env_id) + for _ in range(prepared.length): + await send(env_id, queue, prepared.length) + return AlgorithmEpisodeResult(success=success) + + async def hold(self, datastream, success_term, env_id, env_action_queue): + await send(env_id, env_action_queue, -1) + + monkeypatch.setattr(batching.MultiWaypoint, "execute", hold) + ready = [ + SimpleNamespace( + length=length, + start_time_s=0.0, + initial_state={"robot": {"position": torch.tensor([[float(index)]])}}, + validated=SimpleNamespace( + arm_paths={"left": SimpleNamespace(waypoints=(object(),))}, replay_joint_trajectory=None + ), + ) + for index, length in enumerate(lengths) + ] + stats = { + "num_success": initial_success, + "num_failures": initial_attempts - initial_success, + "num_attempts": initial_attempts, + } + attempts = [] + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + batching._replay_wave( + env, generator, SimpleNamespace(_episode_execute=execute), None, ready, loop, stats, attempts + ) + finally: + loop.close() + asyncio.set_event_loop(None) + assert sorted(exported) == list(enumerate(lengths)) + assert sorted(executed) == list(range(len(lengths))) + assert env.ticks == max(lengths) + assert stats == { + "num_success": initial_success + success * len(lengths), + "num_failures": initial_attempts - initial_success + (not success) * len(lengths), + "num_attempts": initial_attempts + len(lengths), + } + assert sorted(attempt["env_id"] for attempt in attempts) == list(range(len(lengths))) + assert f"{initial_success + success * len(lengths)}/10 successful demos generated" in capsys.readouterr().out + assert not loop.is_running() + if len(lengths) > 1: + assert actions[-1][0].item() == -1 + + +@pytest.mark.parametrize( + "num_envs, guarantee_success, failure_budget, expected_batches, expected_success, completed", + [ + (5, True, 5, [5, 2, 1], 5, True), + (5, True, 2, [5, 2], 4, False), + (5, False, 5, [5], 3, True), + (2, True, 5, [2, 2, 2, 1, 1], 5, True), + ], +) +def test_buffered_retries_keep_run_totals_and_stop_at_the_requested_target( + monkeypatch, num_envs, guarantee_success, failure_budget, expected_batches, expected_success, completed +): + """Failed replays refill only missing demos; fixed-attempt runs and finite budgets remain bounded.""" + import autodata_core.schedulegen.batching as batching + from autodata_core.data_generator import GenerationResult + from autodata_core.schedulegen.algorithm import _PreparedEpisode + from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy + + env = SimpleNamespace(num_envs=num_envs, recorder_manager=SimpleNamespace(reset=Mock()), reset=Mock()) + policy = GenerationPolicy(num_trials=5, guarantee_success=guarantee_success, max_num_failures=failure_budget) + generator = SimpleNamespace( + datastream=SimpleNamespace( + device="cpu", + get_env=lambda: env, + get_generation_policy=lambda: policy, + get_schedule_spec=lambda: SimpleNamespace(collision_margin_m=0.0), + ) + ) + prepare = Mock( + side_effect=lambda *args: _PreparedEpisode(0, {}, {}, torch.zeros(1), {}, paths=SimpleNamespace(arm_paths={})) + ) + algorithm = SimpleNamespace( + planning_contexts={0: object()}, + _episode_prepare=prepare, + _conflicts_find=Mock(return_value=()), + _episode_schedule_solve=Mock(return_value=object()), + _state_restore=Mock(), + _episode_validate_scheduled=Mock(return_value=object()), + ) + outcomes = iter((True, False, False, True, True, True, False, True)) + batches = [] + + def replay(env, generator, algorithm, success_term, ready, loop, stats, attempts, **kwargs): + batches.append(len(ready)) + for env_id, _ in enumerate(ready): + batching.record_generation_attempt(GenerationResult({}, next(outcomes)), env_id, stats, attempts) + + monkeypatch.setattr(batching, "_replay_wave", replay) + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + result = batching.generate_buffered(env, generator, algorithm, None, schedule_workers=2) + finally: + loop.close() + asyncio.set_event_loop(None) + assert batches == expected_batches + assert result["stats"] == { + "num_success": expected_success, + "num_failures": sum(expected_batches) - expected_success, + "num_attempts": sum(expected_batches), + } + assert result["completed"] is completed + assert prepare.call_count == len(result["attempts"]) == sum(expected_batches) + assert [attempt["attempt"] for attempt in result["attempts"]] == list(range(1, sum(expected_batches) + 1)) + + +def test_carried_transit_uses_explicit_poses_without_simulator_access(): + captured = {} + + def plan(**kwargs): + captured.update(kwargs) + return True + + pose = torch.eye(4) + carried_pose = pose.clone() + carried_pose[0, 3] = 0.25 + overrides = {"bowl": pose} + planner = SimpleNamespace( + config=SimpleNamespace(planning_group_name="left_arm", motion_noise_scale=0.0, retreat_distance=0.1), + step_size=None, + active_joint_names=("joint",), + get_planned_joint_trajectory=lambda: NamedJointTrajectory(("joint",), torch.zeros(1, 1)), + get_planned_poses=lambda: [pose], + update_world_and_plan_motion=plan, + ) + generator = SimpleNamespace(datastream=SimpleNamespace(passthrough_actions_to_joint_positions=lambda actions: {})) + + waypoints, positions = PathBuilder({"left": planner})._transit_plan( + generator, planner, 0, pose, {}, torch.zeros(1), "beaker", carried_pose, overrides + ) + + assert captured["object_pose_overrides"]["beaker"] is carried_pose + assert captured["object_pose_overrides"]["bowl"] is pose + assert "beaker" not in overrides + assert captured["force_object_attachment"] + assert len(waypoints) == len(positions) == 1 + + +@pytest.mark.parametrize("finite", [True, False]) +def test_replay_stops_at_first_non_finite_robot_state(monkeypatch, finite): + monkeypatch.setattr(algorithm_module, "_scheduled_waypoints_build", lambda path, schedule: (object(),)) + + async def execute(self, **kwargs): + return False + + monkeypatch.setattr(algorithm_module.MultiWaypoint, "execute", execute) + positions = torch.tensor([[0.0 if finite else float("nan")]]) + datastream = SimpleNamespace( + get_generation_policy=lambda: SimpleNamespace(final_hold_steps=0, terminal_convergence_steps=0), + get_robot_joint_positions=lambda env_ids: positions, + ) + context = SimpleNamespace(group_planners={"left": object()}, full_state=None) + algorithm = ScheduleGen({0: context}) + replay = algorithm._schedule_replay( + data_generator=SimpleNamespace(datastream=datastream), + env_id=0, + success_term=None, + env_action_queue=None, + arm_paths={"left": object()}, + schedule=SimpleNamespace(makespan_ticks=1), + ) + if finite: + assert asyncio.run(replay) == (False, None) + else: + with pytest.raises(AssertionError, match="non-finite robot joints at replay tick 0"): + asyncio.run(replay) + + +@pytest.mark.parametrize("factor", [1, 3]) +def test_collision_sampling_preserves_ticks_and_waypoint_support(factor): + path = torch.tensor([[0.0], [1.0], [3.0]]) + dense, ticks = _joint_timeline_densify(path, factor) + conflict_dense, supports = _path_densify(path, factor) + assert torch.equal(dense, conflict_dense) + assert len(ticks) == len(supports) == 2 * factor + 1 + assert ticks[::factor] == (0.0, 1.0, 2.0) + assert supports[::factor] == ((0,), (1,), (2,)) + assert torch.equal(dense[::factor], path) + if factor > 1: + assert supports[1] == (0, 1) and supports[-2] == (1, 2) + assert ticks[1] == pytest.approx(1 / factor) + + +def test_pose_errors_agree_for_scalar_and_batched_targets(): + actual, target = torch.eye(4), torch.eye(4) + target[:3, 3] = torch.tensor([3.0, 4.0, 0.0]) + target[:2, :2] *= -1 + scalar = pose_math.pose_errors(actual, target) + batched = pose_math.pose_errors(actual.unsqueeze(0), target.unsqueeze(0)) + assert scalar[0].item() == pytest.approx(5.0) + assert scalar[1].item() == pytest.approx(torch.pi) + assert all(torch.equal(value.reshape(1), batch) for value, batch in zip(scalar, batched, strict=True)) diff --git a/autodata_tests/e2e/test_annotation.py b/autodata_tests/e2e/test_annotation.py index 80674d7..3abfe9b 100644 --- a/autodata_tests/e2e/test_annotation.py +++ b/autodata_tests/e2e/test_annotation.py @@ -6,6 +6,7 @@ import h5py import json import subprocess +import yaml from pathlib import Path import pytest @@ -15,6 +16,38 @@ from autodata_tests.utils.utils import assert_recorded_episodes, assert_valid_dataset +@pytest.mark.with_subprocess +def test_schedulegen_requires_manual_marks_without_legacy_skillgen_flag(tmp_path, capfd): + """The selected algorithm, not the legacy policy flag, determines whether skill starts are needed.""" + task = yaml.safe_load((Path(TestPaths.tasks_dir) / "gr1t2_nut_pour_schedulegen.yaml").read_text()) + task["generation_policy"]["use_skillgen"] = False + descriptor = tmp_path / "task.yaml" + descriptor.write_text(yaml.safe_dump(task)) + with pytest.raises(subprocess.CalledProcessError) as error: + run_subprocess([ + TestPaths.python_path, + str(Path(TestPaths.scripts_dir) / "annotate_demos.py"), + "--auto", + "--viz", + "none", + "--device", + "cpu", + "--env_name", + "IsaacContrib-Stack-Cube-Franka-IK-Rel", + "--task_descriptor", + str(descriptor), + "--embodiment", + str(Path(TestPaths.embodiments_dir) / "gr1t2_schedulegen.yaml"), + "--input_file", + str(Path(TestPaths.test_data_dir) / "annotated_dataset_franka_stack_mimicgen.hdf5"), + "--output_file", + str(tmp_path / "annotated.hdf5"), + ]) + assert error.value.returncode == 1 + out, err = capfd.readouterr() + assert "this task additionally needs skill start signals" in out + err + + @pytest.mark.with_subprocess @pytest.mark.parametrize( ("input_dataset", "task_descriptor", "env_name", "signal_names", "device", "require_all_demos"), diff --git a/autodata_tests/examples/test_gr1t2_nut_pour.py b/autodata_tests/examples/test_gr1t2_nut_pour.py new file mode 100644 index 0000000..2e39d09 --- /dev/null +++ b/autodata_tests/examples/test_gr1t2_nut_pour.py @@ -0,0 +1,44 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Native mimic settings for the GR1T2 example.""" + +import pytest + +pytest.importorskip("isaaclab") +from pxr import Sdf, Usd, UsdPhysics # noqa: E402 + +from autodata_examples.gr1t2_nut_pour import _mimic_joints_newton # noqa: E402 + + +@pytest.mark.parametrize( + ("frequency", "damping_ratio", "expected_reference", "expected_impedance"), + [ + (25.0, 0.005, (2.2877142857, 0.0174923488), 0.0008742350), + (17184.0, 558.47998046875, (0.0020001026, 4.0619149239), 0.9999486920), + ], +) +def test_mimic_settings_preserve_coefficients_and_implicit_response( + frequency, damping_ratio, expected_reference, expected_impedance +): + stage = Usd.Stage.CreateInMemory() + root = stage.DefinePrim("/robot", "Xform") + leader = UsdPhysics.RevoluteJoint.Define(stage, "/robot/leader") + follower = UsdPhysics.RevoluteJoint.Define(stage, "/robot/follower").GetPrim() + follower.AddAppliedSchema("PhysxMimicJointAPI:rotZ") + source = {"naturalFrequency": frequency, "dampingRatio": damping_ratio, "gearing": -1.128, "offset": 30.0} + for name, value in source.items(): + follower.CreateAttribute(f"physxMimicJoint:rotZ:{name}", Sdf.ValueTypeNames.Float).Set(value) + follower.CreateRelationship("physxMimicJoint:rotZ:referenceJoint").SetTargets([leader.GetPath()]) + + _mimic_joints_newton(root, solver_dt=0.001) + + assert "MjcEqualityJointAPI" in follower.GetPrimTypeInfo().GetAppliedAPISchemas() + assert follower.GetRelationship("newton:mimicJoint").GetTargets() == [leader.GetPath()] + assert follower.GetAttribute("newton:mimicCoef0").Get() == -30.0 + assert follower.GetAttribute("newton:mimicCoef1").Get() == pytest.approx(1.128) + assert follower.GetAttribute("mjc:solref").Get() == pytest.approx(expected_reference) + assert follower.GetAttribute("mjc:solref").Get()[0] >= 0.002 + assert follower.GetAttribute("mjc:solimp").Get()[:2] == pytest.approx([expected_impedance] * 2) + for name, value in source.items(): + assert follower.GetAttribute(f"physxMimicJoint:rotZ:{name}").Get() == pytest.approx(value) diff --git a/autodata_tests/interfaces/datastream/test_datastream.py b/autodata_tests/interfaces/datastream/test_datastream.py index 4bc4f8c..df032d8 100644 --- a/autodata_tests/interfaces/datastream/test_datastream.py +++ b/autodata_tests/interfaces/datastream/test_datastream.py @@ -86,6 +86,14 @@ def _datastream(): return datastream, task, embodiment_adapter, env +def test_robot_joint_positions_preserve_requested_order(): + datastream, _, _, _ = _datastream() + assert torch.equal( + datastream.get_robot_joint_positions([0], ("j6", "j1")), + torch.tensor([[0.6, 0.1]]), + ) + + @pytest.mark.parametrize("object_name", ["cube_1", "door"]) @pytest.mark.parametrize("env_id", [0, 1]) def test_object_prim_paths_cover_rigid_and_articulated_objects(object_name, env_id): @@ -130,7 +138,7 @@ def test_requires_exactly_one_demo_source(): task_descriptor=task, embodiment_adapter=embodiment_adapter, device=env.device, uses_start_signals=False ) # both provided - with pytest.raises(AssertionError, match="exactly one of source_pool"): + with pytest.raises(AssertionError, match="mutually exclusive"): Datastream( env=env, task_descriptor=task, @@ -139,7 +147,7 @@ def test_requires_exactly_one_demo_source(): source_dataset_path="x.hdf5", ) # neither provided - with pytest.raises(AssertionError, match="exactly one of source_pool"): + with pytest.raises(AssertionError, match="requires source demonstrations"): Datastream( env=env, task_descriptor=TaskDescriptor.from_dict(_task_dict()), embodiment_adapter=_embodiment_adapter() ) @@ -364,9 +372,12 @@ def test_get_scene_state_passthrough(): assert datastream.get_scene_state(is_relative=True) is _SCENE_STATE_SENTINEL -def test_robot_joint_positions_preserve_requested_order(): +def test_get_scene_state_selected_rows_are_independent(): datastream, _, _, _ = _datastream() - assert torch.equal( - datastream.get_robot_joint_positions([0], ("j6", "j1")), - torch.tensor([[0.6, 0.1]]), - ) + positions = torch.arange(12, dtype=torch.float32).reshape(3, 4) + datastream.env.scene.get_state = lambda **kwargs: {"rigid_object": {"bowl": {"root_pose": positions}}} + state = datastream.get_scene_state(env_ids=[2, 0]) + selected = state["rigid_object"]["bowl"]["root_pose"] + assert torch.equal(selected, positions[[2, 0]]) + selected.zero_() + assert torch.equal(positions, torch.arange(12, dtype=torch.float32).reshape(3, 4)) diff --git a/autodata_tests/interfaces/env/test_env_profile.py b/autodata_tests/interfaces/env/test_env_profile.py index dd2f5cd..37a5131 100644 --- a/autodata_tests/interfaces/env/test_env_profile.py +++ b/autodata_tests/interfaces/env/test_env_profile.py @@ -20,6 +20,23 @@ def _minimal_valid() -> dict: return {"name": "p", "base_env": "IsaacContrib-Stack-Cube-Franka-IK-Rel"} +@pytest.mark.parametrize( + "override", + [ + {"position": None, "scale": [1, 1, 1]}, + {"scale": None, "rigid_props": {"disable_gravity": True}}, + ], +) +def test_optional_object_vectors_preserve_null(override): + profile = EnvironmentProfile.from_dict({ + **_minimal_valid(), + "scene": {"rigid_objects": {"override": {"object": override}}}, + }) + spec = profile.scene.rigid_objects.override["object"] + assert spec.position is None + assert spec.scale == ((1, 1, 1) if override.get("scale") is not None else None) + + def _full_valid() -> dict: return { "name": "p", diff --git a/autodata_tests/interfaces/env/test_env_profile_apply.py b/autodata_tests/interfaces/env/test_env_profile_apply.py index f5bb068..8f2d775 100644 --- a/autodata_tests/interfaces/env/test_env_profile_apply.py +++ b/autodata_tests/interfaces/env/test_env_profile_apply.py @@ -42,6 +42,29 @@ def test_profile_rejects_unknown_action_parameters(): apply_env_profile(cfg, profile, "external-task") +def test_profile_static_material_is_scoped_to_the_asset_spawn(): + from isaaclab.sim import UsdFileCfg + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + material = {"static_friction": 2.0, "dynamic_friction": 2.0, "restitution": 0.1} + profile = EnvironmentProfile.from_dict({ + "name": "material", + "base_env": "external-task", + "scene": {"rigid_objects": {"override": {"beaker": {"physics_material": material}}}}, + }) + cfg = SimpleNamespace( + scene=SimpleNamespace(beaker=SimpleNamespace(spawn=UsdFileCfg(usd_path="beaker.usd"))), + events=SimpleNamespace(), + ) + + apply_env_profile(cfg, profile, "external-task") + + assert isinstance(cfg.scene.beaker.spawn.physics_material, UsdPhysicsRigidBodyMaterialCfg) + for name, value in material.items(): + assert getattr(cfg.scene.beaker.spawn.physics_material, name) == value + assert not vars(cfg.events) + + def _parse_base_cfg(): return parse_env_cfg(BASE_ENV, device="cpu", num_envs=1) @@ -70,21 +93,30 @@ def test_setup_humanoid_image_observations(env_name, enable_cameras, tmp_path): assert (env_cfg.observations.policy.robot_pov_cam is not None) == enable_cameras assert bool(env_cfg.image_obs_list) == enable_cameras assert env_cfg.observations.policy.concatenate_terms is False + if enable_cameras: + assert env_cfg.num_rerenders_on_reset >= 1 -def test_gr1_lazy_action_uses_shared_urdf(tmp_path): +@pytest.mark.parametrize( + ("env_name", "action_term"), + [ + ("IsaacContrib-PickPlace-GR1T2-Abs", "upper_body_ik"), + ("IsaacContrib-NutPour-GR1T2-Pink-IK-Abs", "gr1_action"), + ], +) +def test_gr1_lazy_action_uses_shared_urdf(tmp_path, env_name, action_term): """Adapt Lab's string-based action registration before the simulator instantiates it.""" from autodata_interfaces.env.pink_ik_action import PinkInverseKinematicsActionSharedUrdf env_cfg, _ = setup_env_config( - env_name="IsaacContrib-PickPlace-GR1T2-Abs", + env_name=env_name, output_dir=str(tmp_path), output_file_name="generated", num_envs=100, device="cpu", generation_policy_params=GenerationPolicy(), ) - assert env_cfg.actions.upper_body_ik.class_type is PinkInverseKinematicsActionSharedUrdf + assert getattr(env_cfg.actions, action_term).class_type is PinkInverseKinematicsActionSharedUrdf def test_apply_bin_stack_profile_overlays_scene_and_events(): diff --git a/autodata_tests/interfaces/tasks/test_subtask_spec.py b/autodata_tests/interfaces/tasks/test_subtask_spec.py index ff98aaf..2195475 100644 --- a/autodata_tests/interfaces/tasks/test_subtask_spec.py +++ b/autodata_tests/interfaces/tasks/test_subtask_spec.py @@ -83,6 +83,7 @@ def test_algo_params_registry_contents(): "dexmimicgen": DexMimicGenSubtaskAlgoParams, "skillgen": SkillGenSubtaskAlgoParams, "softmimicgen": SoftMimicGenSubtaskAlgoParams, + "schedulegen": SkillGenSubtaskAlgoParams, } for cls in ALGO_PARAMS_REGISTRY.values(): assert issubclass(cls, SubtaskAlgoParams) diff --git a/autodata_tests/interfaces/tasks/test_task_descriptor.py b/autodata_tests/interfaces/tasks/test_task_descriptor.py index ae22d65..0ca38c8 100644 --- a/autodata_tests/interfaces/tasks/test_task_descriptor.py +++ b/autodata_tests/interfaces/tasks/test_task_descriptor.py @@ -15,6 +15,25 @@ from autodata_tests.utils.constants import TestPaths +def test_legacy_algorithm_rejects_explicit_segment_providers(): + with pytest.raises(AssertionError, match="explicit segments require"): + TaskDescriptor.from_dict({ + "name": "unsupported", + "algo": "mimicgen", + "subtasks": { + "arm": [{ + "name": "move", + "segments": [{ + "name": "transit", + "kind": "transit", + "provider": "motion_planner", + "motion_goal": {"position_m": [0, 0, 0], "rotation_xyzw": [0, 0, 0, 1]}, + }], + }] + }, + }) + + def _stack_task_dict() -> dict: """A four-subtask single-arm stack task (each subtask has a term signal, like SkillGen).""" return { diff --git a/autodata_tests/utils/test_generation_planners.py b/autodata_tests/utils/test_generation_planners.py new file mode 100644 index 0000000..edd480d --- /dev/null +++ b/autodata_tests/utils/test_generation_planners.py @@ -0,0 +1,32 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""SkillGen's shared visualization options are forwarded without starting a simulator.""" + +import ast +from pathlib import Path + +import pytest + +from autodata_tests.utils.constants import TestPaths + + +def test_skillgen_saves_rerun_only_for_environment_zero(monkeypatch): + pytest.importorskip("curobo.geom.sdf.world") + from autodata_interfaces.motion_planners.curobo import curobo_planner + from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg + + script = Path(TestPaths.scripts_dir) / "generate_dataset.py" + tree = ast.parse(script.read_text()) + function = next( + node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_build_motion_planners" + ) + namespace = {} + exec(compile(ast.Module(body=[function], type_ignores=[]), str(script), "exec"), namespace) + monkeypatch.setattr(CuroboPlannerCfg, "from_profile", lambda profile: CuroboPlannerCfg()) + monkeypatch.setattr(curobo_planner, "CuroboPlanner", lambda **kwargs: kwargs["config"]) + planners = namespace["_build_motion_planners"]( + None, 2, "example", planner_profile="example", visualize_plan=True, rerun_output="plans.rrd" + ) + assert planners[0].rerun_output == "plans.rrd" and planners[0].visualize_plan + assert planners[1].rerun_output is None and not planners[1].visualize_plan diff --git a/autodata_tests/utils/test_generation_result.py b/autodata_tests/utils/test_generation_result.py index 37fe93b..54ec747 100644 --- a/autodata_tests/utils/test_generation_result.py +++ b/autodata_tests/utils/test_generation_result.py @@ -5,8 +5,14 @@ import json from pathlib import Path +from types import SimpleNamespace -from autodata_utils.generation_result import AttemptLog, attempts_file_for, write_generation_result +from autodata_utils.generation_result import ( + AttemptLog, + attempts_file_for, + record_generation_attempt, + write_generation_result, +) def test_write_generation_result_writes_completed_stats_atomically(tmp_path): @@ -44,6 +50,8 @@ def test_write_generation_result_records_env_profile_when_given(tmp_path): "path": "autodata_examples/env_profiles/franka_bin_stack.yaml", "planner": "franka_stack_cube_bin", }, + environment={"name": "example", "physics_manager": "example:Physics", "control_dt_s": 0.05}, + execution={"mode": "buffered", "num_envs": 2, "timings_s": {"replay_s": 1.5}}, ) with result_file.open(encoding="utf-8") as result_handle: @@ -53,6 +61,28 @@ def test_write_generation_result_records_env_profile_when_given(tmp_path): "path": "autodata_examples/env_profiles/franka_bin_stack.yaml", "planner": "franka_stack_cube_bin", } + assert result["environment"] == { + "name": "example", + "physics_manager": "example:Physics", + "control_dt_s": 0.05, + } + assert result["execution"] == {"mode": "buffered", "num_envs": 2, "timings_s": {"replay_s": 1.5}} + + +def test_record_generation_attempt_counts_pre_replay_failures(): + stats = {"num_success": 0, "num_failures": 0, "num_attempts": 0} + attempts = [] + for env_id, success in ((0, False), (1, True)): + record_generation_attempt( + SimpleNamespace(success=success, diagnostics=(("stage", "complete" if success else "planning"),)), + env_id, + stats, + attempts, + ) + assert stats == {"num_success": 1, "num_failures": 1, "num_attempts": 2} + assert [attempt["attempt"] for attempt in attempts] == [1, 2] + assert [attempt["env_id"] for attempt in attempts] == [0, 1] + assert attempts[0]["diagnostics"] == {"stage": "planning"} def test_rerun_with_the_same_result_file_keeps_the_earlier_attempt_log(tmp_path: Path) -> None: @@ -63,3 +93,29 @@ def test_rerun_with_the_same_result_file_keeps_the_earlier_attempt_log(tmp_path: earlier = Path(attempts_file_for(result_file, "run-a")).read_text().splitlines() assert [json.loads(line)["run_id"] for line in earlier] == ["run-a"] + + +def test_attempt_log_accepts_scoped_and_batched_initial_states(tmp_path): + """Metrics select row zero for a scoped snapshot and the environment row for a batch.""" + import torch + + for count in (1, 3): + path = tmp_path / f"{count}.jsonl" + poses = torch.arange(count * 7).reshape(count, 7) + result = SimpleNamespace( + success=True, + diagnostics=(), + extras={"planning_failed": False}, + initial_state={"rigid_object": {"bowl": {"root_pose": poses}}}, + ) + record_generation_attempt( + result, + 2, + {"num_success": 0, "num_failures": 0, "num_attempts": 0}, + [], + attempt_log=AttemptLog(str(path), "test"), + start_time_s=0.0, + ) + record = json.loads(path.read_text()) + assert record["initial_object_positions"]["bowl"] == poses[0 if count == 1 else 2, :2].tolist() + assert record["extras"] == {"planning_failed": False} diff --git a/autodata_tests/utils/test_manual_annotation.py b/autodata_tests/utils/test_manual_annotation.py new file mode 100644 index 0000000..325b2c2 --- /dev/null +++ b/autodata_tests/utils/test_manual_annotation.py @@ -0,0 +1,84 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Recreate bundled annotation boundaries through manual marking callbacks without a viewer.""" + +import ast +import h5py +import torch +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from autodata_core.pool import DataGenInfoPool +from autodata_interfaces.tasks.segment_spec import SegmentEventPoint +from autodata_interfaces.tasks.task_descriptor import TaskDescriptor +from autodata_interfaces.tasks.task_descriptor_utils import resolve_task_algorithm +from autodata_tests.utils.constants import TestPaths + + +@pytest.mark.parametrize( + "dataset,descriptor", + [ + ("annotated_dataset_franka_stack_mimicgen.hdf5", "franka_cube_stack.yaml"), + ("annotated_dataset_franka_stack_skillgen.hdf5", "franka_cube_stack_skillgen.yaml"), + ("annotated_dataset_gr1_pick_place_dexmimicgen.hdf5", "gr1_pick_place.yaml"), + ("annotated_dataset_g1_pick_place_dexmimicgen.hdf5", "g1_pick_place.yaml"), + ("annotated_dataset_franka_rope_softmimicgen.hdf5", "franka_rope_softmimicgen.yaml"), + ("annotated_dataset_franka_rope_softmimicgen_newton.hdf5", "franka_rope_softmimicgen.yaml"), + ("dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5", "gr1t2_nut_pour_schedulegen.yaml"), + ], +) +def test_manual_callbacks_recreate_bundled_annotations(dataset, descriptor): + # Load only the callback functions: importing the entry point would start Isaac Sim. + script = Path(TestPaths.scripts_dir) / "annotate_demos.py" + tree = ast.parse(script.read_text()) + names = {"_build_signal_names", "mark_subtask_cb", "annotate_episode_in_manual_mode"} + definitions = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names] + module = ast.Module( + body=[ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0), *definitions], + type_ignores=[], + ) + namespace = {"torch": torch, "SegmentEventPoint": SegmentEventPoint} + exec(compile(ast.fix_missing_locations(module), str(script), "exec"), namespace) + task_path = str(Path(TestPaths.tasks_dir) / descriptor) + task = TaskDescriptor.from_yaml(task_path) + algorithm = resolve_task_algorithm(None, task_path) + signals = namespace["_build_signal_names"](task, algorithm in ("skillgen", "schedulegen")) + source = Path(TestPaths.test_data_dir) / dataset + if descriptor == "gr1t2_nut_pour_schedulegen.yaml": + source = Path(TestPaths.repo_root) / "datasets/annotated_datasets" / dataset + + with h5py.File(source) as data: + for demo in data["data"].values(): + count = len(demo["actions"]) + expected = demo["obs/datagen_info"] + marks = iter([ + [ + DataGenInfoPool._find_first_rising_edge(expected[group][name][:], signal_name=name) + for group, name in arm_signals + ] + for arm_signals in signals.values() + if arm_signals + ]) + + def replay(env, episode, success_term): + for index in next(marks): + namespace["current_action_index"] = index + namespace["mark_subtask_cb"]() + return True + + namespace["replay_episode"] = replay + annotated = SimpleNamespace(data={"obs": {"datagen_info": {}}}) + env = SimpleNamespace(recorder_manager=SimpleNamespace(get_episode=lambda index: annotated)) + episode = SimpleNamespace(data={"actions": torch.empty(count, 0)}) + assert namespace["annotate_episode_in_manual_mode"](env, episode, None, signals) + for arm_signals in signals.values(): + for group, name in arm_signals: + actual = annotated.data["obs"]["datagen_info"][group][name] + # Automatic task flags may toggle; manual marks stay true. Both must locate the same boundary. + assert actual.shape == (count,) and actual.dtype == torch.bool + assert DataGenInfoPool._find_first_rising_edge(actual, signal_name=name) == ( + DataGenInfoPool._find_first_rising_edge(expected[group][name][:], signal_name=name) + ) diff --git a/autodata_tests/utils/test_validate_dataset.py b/autodata_tests/utils/test_validate_dataset.py index e9599a5..990c282 100644 --- a/autodata_tests/utils/test_validate_dataset.py +++ b/autodata_tests/utils/test_validate_dataset.py @@ -25,6 +25,20 @@ def _create_dataset(path: Path, *, include_actions: bool = True) -> None: demo.create_group("obs") +@pytest.mark.parametrize("invalid", ["nan_action", "nan_observation", "wrong_observation_length"]) +def test_array_checks_reject_invalid_values_and_lengths(tmp_path, invalid): + path = tmp_path / "invalid_arrays.hdf5" + _create_dataset(path) + with h5py.File(path, "a") as file: + demo = file["data/demo_0"] + if invalid == "nan_action": + demo["actions"][0, 0] = float("nan") + else: + demo["obs"].create_dataset("pose", data=[float("nan")] if invalid == "nan_observation" else [0, 1]) + assert validate_dataset.main([str(path)]) == 0 + assert validate_dataset.main([str(path), "--check_arrays"]) == 1 + + def test_main_returns_zero_for_valid_dataset(tmp_path: Path) -> None: """A structurally valid dataset should produce a successful exit status, with or without the report.""" diff --git a/autodata_utils/generation_result.py b/autodata_utils/generation_result.py index fc5bc4e..cb57079 100644 --- a/autodata_utils/generation_result.py +++ b/autodata_utils/generation_result.py @@ -12,9 +12,63 @@ import shutil import subprocess import tempfile -from collections.abc import Mapping +import time +from collections.abc import Mapping, Sequence from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from autodata_core.data_generator import GenerationResult + + +def record_generation_attempt( + result: GenerationResult, + env_id: int, + stats: dict[str, int], + attempts: list[dict[str, object]], + *, + attempt_log: AttemptLog | None = None, + start_time_s: float | None = None, +) -> None: + """Record one completed attempt in the shared counters and completion-ordered report. + + Args: + result: Recorded episode outcome, including failures before replay. + env_id: Environment used for the attempt. + stats: Mutable success, failure and attempt counters. + attempts: Mutable completion-ordered attempt records. + attempt_log: Optional native metrics log for the run. + start_time_s: Monotonic start time of this attempt [s], required when logging. + """ + + attempt_index = stats["num_attempts"] + 1 + if result.diagnostics: + details = ", ".join(f"{name}={value}" for name, value in result.diagnostics) + print(f"Generation attempt {attempt_index} (env {env_id}): {details}", flush=True) + attempts.append({ + "attempt": attempt_index, + "env_id": env_id, + "success": result.success, + "diagnostics": dict(result.diagnostics), + }) + stats["num_success" if result.success else "num_failures"] += 1 + stats["num_attempts"] += 1 + if attempt_log is not None: + from autodata_utils.tensor_utils import as_torch + + assert start_time_s is not None, "attempt logging requires a start time" + initial_positions = {} + for name, state in result.initial_state.get("rigid_object", {}).items(): + poses = as_torch(state["root_pose"]) + initial_positions[name] = poses[0 if len(poses) == 1 else env_id, :2].tolist() + attempt_log.write({ + "env_id": env_id, + "success": result.success, + "start_time_s": start_time_s, + "end_time_s": time.monotonic(), + "initial_object_positions": initial_positions, + "extras": result.extras, + }) def write_generation_result( @@ -24,6 +78,9 @@ def write_generation_result( stats: Mapping[str, int], env_profile: Mapping[str, str | None] | None = None, run_metadata: Mapping[str, Any] | None = None, + attempts: Sequence[Mapping[str, object]] | None = None, + environment: Mapping[str, str | float] | None = None, + execution: Mapping[str, object] | None = None, ) -> None: """Atomically write the final outcome of a completed data-generation run. @@ -37,6 +94,10 @@ def write_generation_result( because the generated dataset stores only the base env id and would otherwise not reveal that the scene was modified. run_metadata: How the run was configured and how long it took, stored under ``run``. + + attempts: Optional completion-ordered per-attempt outcomes and scalar diagnostics. + environment: Optional environment name, active physics manager, and control period [s]. + execution: Optional generation-mode settings, timings [s] and memory measurements [byte]. """ required_stats = ("num_success", "num_failures", "num_attempts") for stat_name in required_stats: @@ -60,6 +121,14 @@ def write_generation_result( if run_metadata is not None: result["run"] = dict(run_metadata) + if environment is not None: + result["environment"] = dict(environment) + if execution is not None: + result["execution"] = dict(execution) + if attempts is not None: + assert len(attempts) == stats["num_attempts"], "Attempt records must match num_attempts." + result["attempts"] = [dict(attempt) for attempt in attempts] + file_descriptor, temporary_file_name = tempfile.mkstemp( prefix=f".{result_path.name}.", suffix=".tmp", dir=result_path.parent, text=True ) diff --git a/datasets/annotated_datasets/dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5 b/datasets/annotated_datasets/dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5 new file mode 100644 index 0000000..6cd3734 --- /dev/null +++ b/datasets/annotated_datasets/dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:144f8e9ce848e2dd91518e04457726abe492527a9a8998b9479f0aff400644ea +size 65282937 diff --git a/docker/run_docker.sh b/docker/run_docker.sh index 24898a9..f5e1346 100755 --- a/docker/run_docker.sh +++ b/docker/run_docker.sh @@ -175,6 +175,17 @@ DOCKER_RUN_ARGS=( "--env" "DOCKER_RUN_GROUP_NAME=$(id -gn)" ) +# Linked worktrees keep their Git metadata outside the checkout. +if [ -f "${REPO_ROOT}/.git" ]; then + GIT_COMMON_DIR=$(git -C "${REPO_ROOT}" rev-parse --path-format=absolute --git-common-dir) + GIT_COMMON_RELATIVE=$(realpath --relative-to="${REPO_ROOT}" "${GIT_COMMON_DIR}") + GIT_COMMON_MOUNT=$(realpath -m "${WORKDIR}/${GIT_COMMON_RELATIVE}") + GIT_WORKTREE_RELATIVE=$(realpath --relative-to="${GIT_COMMON_DIR}" "${REPO_ROOT}") + GIT_WORKTREE_MOUNT=$(realpath -m "${GIT_COMMON_MOUNT}/${GIT_WORKTREE_RELATIVE}") + DOCKER_RUN_ARGS+=("-v" "${GIT_COMMON_DIR}:${GIT_COMMON_DIR}" "-v" "${GIT_COMMON_DIR}:${GIT_COMMON_MOUNT}") + DOCKER_RUN_ARGS+=("-v" "${REPO_ROOT}:${GIT_WORKTREE_MOUNT}") +fi + # Allow local X11 clients from the container (for the Kit viewer). if command -v xhost >/dev/null 2>&1; then xhost +local:docker >/dev/null 2>&1 || true diff --git a/docs/images/schedulegen_gr1t2_cross.gif b/docs/images/schedulegen_gr1t2_cross.gif new file mode 100644 index 0000000..360dc7b --- /dev/null +++ b/docs/images/schedulegen_gr1t2_cross.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ccc2b8340e123ab6bfe926aecccc734f8ef91f3eccaf8132799f97be27a6ad0 +size 3467812 diff --git a/docs/images/schedulegen_timing.svg b/docs/images/schedulegen_timing.svg new file mode 100644 index 0000000..b4ee47e --- /dev/null +++ b/docs/images/schedulegen_timing.svg @@ -0,0 +1,77 @@ + + + + + From arm paths to a joint schedule + Planned transits and demonstration skills keep their path order. + The right arm waits for pouring and clearance, then picks and places the bowl while + the left arm returns the beaker. Timing is illustrative. + + + + + + + + + + + + Build paths + Adapt skills and plan transits + + Schedule + Task order + collision constraints + + Replay + Restore state and record in simulation + + + Left arm + Beaker + Right arm + Bowl + + + + + + + + + + + + + + + + + + Transit + Grasp + Transit + Pour + clear + Return to bin + Release + Final hold + Wait before starting + Transit + Grasp + To scale + Place + + + Pour ends before bowl pickup starts + + Time (illustrative) + + + Planned transit + + Demonstration skill + + Wait / hold + Same paths; chosen start times + + diff --git a/docs/index.rst b/docs/index.rst index 9fd6179..ba0d7ce 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -117,6 +117,7 @@ Table of Contents pages/workflows/franka_rope_softmimicgen/index pages/workflows/humanoid_dexmimicgen/index pages/workflows/skillgen/index + pages/workflows/schedulegen/index .. toctree:: :maxdepth: 1 diff --git a/docs/pages/workflows/schedulegen/index.rst b/docs/pages/workflows/schedulegen/index.rst new file mode 100644 index 0000000..f63af95 --- /dev/null +++ b/docs/pages/workflows/schedulegen/index.rst @@ -0,0 +1,259 @@ +.. + Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: Apache-2.0 + +.. _schedulegen-workflow: + +ScheduleGen: Multi-Arm Data Generation +====================================== + +ScheduleGen generates multi-arm demonstrations by combining object-relative skills, +motion planning, and scheduling. It adapts contact-rich skills from a few demonstrations, +plans the connecting motions, then chooses when each arm moves. The arms can work in +parallel while respecting task order and avoiding the collisions found along their paths. + +See `ScheduleGen: Demonstration Generation via Skill Scheduling for Multi-Arm Imitation +Learning `_ for the method, experiments, and results. +This page describes the AutoData implementation and walks through **GR1T2 nut pouring** +with a fixed waist, using the same annotated demonstrations for normal and cross layouts. +The paper covers additional tasks and embodiments beyond this example. + +.. figure:: ../../../images/schedulegen_gr1t2_cross.gif + :width: 85% + :align: center + :alt: GR1T2 pours from a red beaker into a yellow bowl, returns the beaker to a bin, + and places the bowl on a scale in the cross layout. + + A generated cross-layout rollout. After pouring and clearing the bowl, the robot can + return the beaker while the other arm picks up and places the bowl. Playback is at + the recorded speed. + +Workflow at a Glance +-------------------- + +.. list-table:: GR1T2 nut pouring + :header-rows: 1 + :widths: 25 75 + + * - Property + - Value + * - Environment + - ``AutoData-NutPour-GR1T2-ScheduleGen-v0`` + * - Robot and control + - Fixed-waist GR1T2, absolute-pose Pink IK, two dexterous hands, 20 Hz control. + * - Physics + - PhysX or Arena's Newton/MJWarp preset, with task-specific hand/contact settings. + * - Source data + - Five supplied annotated demonstrations, shared by the normal and cross layouts. + * - Task + - Pour from the beaker, return it to the bin, and place the bowl on the scale. + +.. toctree:: + :maxdepth: 1 + + step_1_record_demonstrations + step_2_annotate_demonstrations + step_3_generate_dataset + step_4_validate_dataset + +Already have the supplied annotated dataset? Start at :doc:`step_3_generate_dataset`. + +How It Works +------------ + +ScheduleGen builds the paths **before** scheduling them. Scheduling changes their timing, +not their geometry. + +1. **Build paths.** Reset and save the initial scene state. Select and transform source + skills into the new object frames, solve their joint trajectories, and use cuRobo to + connect them with planned transits. Track when each hand grasps and releases an object. +2. **Find conflicts.** Check the arm paths and held-object geometry for configurations + that cannot occur together. These checks run on the GPU. +3. **Schedule.** Solve a mixed-integer linear program (MILP) on the CPU with SciPy/HiGHS. + It inserts waits to avoid conflicts, satisfy task constraints, and minimize the time + at which all arms finish, called the *makespan*. +4. **Replay and record.** Validate the scheduled motion, restore the saved initial state, + and execute the commands in simulation. Check task success and export demonstrations + through AutoData's recorder. + +.. figure:: ../../../images/schedulegen_timing.svg + :width: 100% + :align: center + :alt: A two-arm schedule separates planned transits, demonstration skills, and waits. + The bowl arm starts after pouring ends while the beaker arm returns to the bin. + + Scheduling preserves each arm's path order while choosing where to wait. The task + order shown here is explicit; collision checks may require additional waits. + Segment lengths are illustrative, not measured timings. + +This extends :doc:`SkillGen <../skillgen/index>` from planned single-arm transits to a +joint schedule across arms. AutoData's existing task descriptors, embodiment adapters, +source selection, asynchronous environment stepping, and dataset export remain in use. + +Before You Start +---------------- + +Complete the :doc:`AutoData installation <../../quickstart/installation>` and use the +cuRobo Docker image. Run the following command on the **host**, from the repository root: + +.. code-block:: bash + + ./docker/run_docker.sh -c + +Run the commands below **inside this container**, from the repository root. ``python`` +uses the locked environment at ``/opt/autodata/.venv``, including the scheduling, +robot-model and Pink IK dependencies. No additional package installation is required. + +You need a CUDA GPU, cuRobo kernels built for that GPU, and access to the task's USD assets. +The :ref:`SkillGen preflight ` explains the cuRobo and asset checks; +its Franka memory estimates do not apply to this humanoid. Start with one environment. +The first run also builds and caches the robot model and fitted collision spheres. + +Source Data and Generation +-------------------------- + +The included annotated dataset lets you skip recording and annotation. See +:doc:`step_3_generate_dataset` for the Git LFS download, complete generation command, +normal/cross configurations, failure handling and scaling. For your own recordings, +follow :doc:`step_1_record_demonstrations` and :doc:`step_2_annotate_demonstrations` first. + +The rest of this page explains the scheduling options and code structure. + +Task Order and Motion Continuity +--------------------------------- + +A subtask can contain named segments, such as a planned ``transit`` and a replayed ``skill``. +Constraints refer to those names, not to how a segment was produced. For example, the +supplied task waits until pouring and clearance finish before starting the bowl pickup: + +.. code-block:: yaml + + schedule: + strategy: waypoint_retiming + time_limit_s: 15.0 + constraints: + - type: precedence + before: left.pour_and_clear.skill.end + after: right.grasp_bowl.transit.start + min_lag_steps: 0 + +An endpoint is written as ``arm.subtask.segment.start`` or ``arm.subtask.segment.end``. +Precedence can relate any of these start/end pairs, with optional minimum and maximum +lags in control steps. ``non_overlap`` keeps two segment intervals disjoint without +choosing their order in advance. The scheduler also preserves each arm's own path order +and adds the collision constraints found for the current attempt. + +Two different options affect pauses: + +* **Soft continuity cost:** ``minimize_max_wait: true`` (the default) prefers the smallest + largest internal wait among equal-makespan schedules. It still allows pauses when needed; + initial start delays and terminal holds are not penalized. Set it to ``false`` for a + makespan-only objective. +* **Hard non-preemption:** a ``non_preemptive`` constraint forbids inserted waits inside + a listed chain of consecutive segments on one arm. The scheduler can delay the chain's + start, but cannot pause it after it starts. This does not remove deliberate holds already + present in a skill or scripted segment. + +For example, the supplied descriptor keeps the beaker's final transport and release together: + +.. code-block:: yaml + + - type: non_preemptive + segments: + - left.release_beaker.transit + - left.release_beaker.skill + - left.release_beaker.open_hold + +The right arm likewise has a continuous pickup-to-placement chain. These constraints do +not serialize the two arms: the scheduler can overlap the chains when task order and +collision checks allow it. The supplied example uses **both** hard chains and the soft cost. + +For coarser timing, ``strategy: block_scheduling`` keeps each block internally continuous; +``max_block_size: 0`` makes each segment a single block. Waypoint retiming instead permits +waits between individual waypoints unless a hard chain forbids them. Both strategies use +the same solver and constraint types. + +.. _schedulegen-generation-modes: + +Choose a Generation Mode +------------------------ + +Both modes plan paths, schedule them, and replay the accepted schedules. They differ in +how planning contexts and simulation environments are used: + +.. list-table:: Generation modes + :header-rows: 1 + :widths: 22 39 39 + + * - Mode + - Planning and scheduling + - Replay + * - ``per_environment`` (default) + - Each environment owns its planner context and generates its own candidate. + - Environments execute through AutoData's shared asynchronous stepping loop. + * - ``buffered`` + - One planning context builds a buffer of candidates. Independent CPU schedule + solves can use ``--schedule_workers``; GPU planning and validation remain serial. + - Restore each accepted candidate's initial state and replay the batch across + ``--num_envs`` environments, allowing different episode lengths. + +See :doc:`step_3_generate_dataset` for a buffered generation example. + +``--schedule_workers`` applies only to buffered mode. It parallelizes MILP solves, not +cuRobo planning. Per-environment mode uses more planner memory as ``--num_envs`` grows; +buffered mode shares that memory but still needs simulation and replay buffers. More +environments do not guarantee faster generation or the same physical success rate. + +Inspect Plans and Rollouts +--------------------------- + +Use :doc:`step_4_validate_dataset` to check the exported data, inspect simulator videos +and view planned paths in Rerun. The front viewport is separate from the robot's observation +camera. Simulator video recording currently supports one environment; plan visualization +shows environment 0. + +Inspect the object frames, held-object geometry, planned transits, and actual contacts in +the rollout. A valid schedule is not proof of a successful grasp or pour. If an attempt +fails, use its JSON diagnostics and video to distinguish planning failures, infeasible +constraints, validation failures, and physical task failures before changing the settings. + +Where to Look in the Code +------------------------- + +* **ScheduleGen** (:autodata_code_link:``) builds, + schedules, validates, and replays complete episodes through the generation interface. +* **Path building** (:autodata_code_link:``) adapts + source skills and connects them with motion plans. +* **Scheduling** (:autodata_code_link:``) implements + the MILP independently of this task and robot. +* **Buffered generation** (:autodata_code_link:``) + shares planning contexts and uses the existing asynchronous replay loop. +* **cuRobo setup** (:autodata_code_link:``) + builds named planning groups using the robot's kinematic model, generated configs, + fitted collision spheres, and self-collision pairs. See also + :doc:`motion planner configuration <../../advanced/motion_planners>`. + +To adapt the example, start with its task, embodiment, robot-planning, and environment +configurations. Keep scene-specific reset ranges and contacts there rather than adding +task branches to the scheduler. Re-annotate source skills and object events when their +boundaries change, then check one complete generated episode before scaling up. + +.. _schedulegen-citation: + +Citation +-------- + +If you use ScheduleGen in your research, please cite our paper: + +.. code-block:: bibtex + + @misc{jawale2026schedulegendemonstrationgenerationskill, + title = {ScheduleGen: Demonstration Generation via Skill Scheduling for Multi-Arm Imitation Learning}, + author = {Neel Jawale and Stephan Pleines and Soha Pouya and Yuke Zhu and + Ajay Mandlekar and Caelan Garrett}, + year = {2026}, + eprint = {2610.39429}, + archivePrefix = {arXiv}, + primaryClass = {cs.RO}, + url = {https://arxiv.org/abs/2610.39429}, + } diff --git a/docs/pages/workflows/schedulegen/step_1_record_demonstrations.rst b/docs/pages/workflows/schedulegen/step_1_record_demonstrations.rst new file mode 100644 index 0000000..f7345f8 --- /dev/null +++ b/docs/pages/workflows/schedulegen/step_1_record_demonstrations.rst @@ -0,0 +1,127 @@ +.. + Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: Apache-2.0 + +Step 1: Record Source Demonstrations +==================================== + +Record successful demonstrations of the complete nut-pouring task. ScheduleGen will +reuse the contact-rich parts and replace the connecting motions with motion plans. +The recorder saves actions, observations and each episode's initial state in HDF5. + +.. tip:: + + No teleop hardware? Use the :ref:`included annotated dataset ` + and continue to :doc:`step_3_generate_dataset`. Annotation of existing recordings + requires only a keyboard and a Kit window, not a headset. + +Before Recording +---------------- + +GR1T2 uses the existing IsaacTeleop wrist-pose and dexterous-hand retargeting pipeline. +Follow :ref:`the humanoid CloudXR setup ` to start the runtime +and connect an Apple Vision Pro. These instructions do not add a new device integration. +Use the current IsaacTeleop hardware and network requirements linked there. + +The task accepts 36 action values: two absolute end-effector poses (position [m] and +an XYZW quaternion), followed by 22 hand-joint targets [rad] in the embodiment's declared +order. A single-arm keyboard or SpaceMouse command is not a replacement for that bimanual +pose-and-finger stream. + +Start the cuRobo development container from the repository root on the host: + +.. code-block:: bash + + ./docker/run_docker.sh -c + +Run the following commands inside the container. If CloudXR is already running in another +terminal, first load its environment as described in the humanoid workflow: + +.. code-block:: bash + + source ~/.cloudxr/run/cloudxr.env + +Record with Your Selected Backend +--------------------------------- + +.. tabs:: + + .. group-tab:: Newton + + .. code-block:: bash + + python submodules/IsaacLab-Arena/submodules/IsaacLab/scripts/tools/record_demos.py \ + --task AutoData-NutPour-GR1T2-ScheduleGen-v0 \ + --external_callback autodata_examples.gr1t2_nut_pour.register \ + --physics_backend newton \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml \ + --device cuda:0 \ + --viz kit \ + --step_hz 20 \ + --xr \ + --cloudxr_env avp \ + --no-auto_launch_cloudxr \ + --no-reset_sim_buffer_each_episode \ + --num_demos 5 \ + --dataset_file datasets/gr1t2_schedulegen/source_newton.hdf5 + + .. group-tab:: PhysX + + .. code-block:: bash + + python submodules/IsaacLab-Arena/submodules/IsaacLab/scripts/tools/record_demos.py \ + --task AutoData-NutPour-GR1T2-ScheduleGen-v0 \ + --external_callback autodata_examples.gr1t2_nut_pour.register \ + --physics_backend physx \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml \ + --device cuda:0 \ + --viz kit \ + --step_hz 20 \ + --xr \ + --cloudxr_env avp \ + --no-auto_launch_cloudxr \ + --num_demos 5 \ + --dataset_file datasets/gr1t2_schedulegen/source_physx.hdf5 + +Keep the callback and profile in the command. They select the task, object layout, +controller settings and backend-specific hand/contact configuration. This example uses +``--physics_backend``; the Arena rope workflow's ``--presets`` flag is not interchangeable +with it. The recorder enables external cameras by default; the old Isaac Lab +``--enable_cameras`` recording flag is not needed. + +For Newton, keep ``--no-reset_sim_buffer_each_episode``: restoring the scene and flushing +the solver's buffers are different operations. Use the same backend and profile for +recording, annotation and replay of your own demonstrations. + +What to Demonstrate +------------------- + +1. Grasp the red beaker with the left hand. +2. Pour into the yellow bowl and move the beaker clear. +3. Return the beaker to the bin and release it. +4. Pick up the bowl with the right hand, then place and release it on the scale. + +The bowl hand can begin after pouring and clearance; it need not wait for the beaker to +reach the bin. Record clear skill boundaries, complete finger closures and releases, +and smooth motion. Avoid pushing the bowl during pouring or moving an object before +the grasp is secure. Discard failed grasps instead of treating them as source skills. + +Start XR and recording using the controls in the humanoid workflow. The recorder exports +episodes only when the live task-success condition holds for its required number of steps. + +Hardware-Free Checks +-------------------- + +A scripted stream of the same wrist-pose/finger commands can exercise the controller, +physics, reset and recorder without a headset. Such a check must use real task-success +evaluation and must not restore recorded states each step or supply motion-planner posture +targets. It checks the software after retargeting, not live hand tracking, calibration, +CloudXR networking or headset rendering. Those still require a hardware session. + +Validate the recorded file, using the filename for your selected backend: + +.. code-block:: bash + + python scripts/validate_dataset.py datasets/gr1t2_schedulegen/source_newton.hdf5 + +Continue to :doc:`step_2_annotate_demonstrations`. diff --git a/docs/pages/workflows/schedulegen/step_2_annotate_demonstrations.rst b/docs/pages/workflows/schedulegen/step_2_annotate_demonstrations.rst new file mode 100644 index 0000000..0bae4e2 --- /dev/null +++ b/docs/pages/workflows/schedulegen/step_2_annotate_demonstrations.rst @@ -0,0 +1,177 @@ +.. + Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: Apache-2.0 + +Step 2: Annotate Demonstrations +=============================== + +ScheduleGen uses **SkillGen-style skill windows, separately for each arm**. DexMimicGen +normally marks where consecutive subtasks end. Here, also mark where each reusable skill +starts so motion planning can replace the approach to it. Do not annotate the future +motion-planned transits or scheduler-inserted waits. + +The same ``scripts/annotate_demos.py`` tool handles all these annotations. It replays an +episode for each arm and prints the marks expected by the task descriptor. The supplied +descriptor already enables skill-start annotation; no extra annotation mode is needed. + +.. important:: + + Keep the recording's physics backend and environment profile. Write a new output file; + do not overwrite the raw demonstration or modify the supplied annotated dataset. + +Run Manual Annotation +--------------------- + +Inside the development container, run: + +.. tabs:: + + .. group-tab:: Newton + + .. code-block:: bash + + python scripts/annotate_demos.py \ + --env_name AutoData-NutPour-GR1T2-ScheduleGen-v0 \ + --external_callback autodata_examples.gr1t2_nut_pour:register \ + --physics_backend newton \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml \ + --task_descriptor autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml \ + --embodiment autodata_examples/embodiments/gr1t2_schedulegen.yaml \ + --input_file datasets/gr1t2_schedulegen/source_newton.hdf5 \ + --output_file datasets/gr1t2_schedulegen/source_newton_annotated.hdf5 \ + --device cuda:0 \ + --viz kit + + .. group-tab:: PhysX + + .. code-block:: bash + + python scripts/annotate_demos.py \ + --env_name AutoData-NutPour-GR1T2-ScheduleGen-v0 \ + --external_callback autodata_examples.gr1t2_nut_pour:register \ + --physics_backend physx \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml \ + --task_descriptor autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml \ + --embodiment autodata_examples/embodiments/gr1t2_schedulegen.yaml \ + --input_file datasets/gr1t2_schedulegen/source_physx.hdf5 \ + --output_file datasets/gr1t2_schedulegen/source_physx_annotated.hdf5 \ + --device cuda:0 \ + --viz kit + +Newton defaults to preserving solver buffers between restores; PhysX keeps its established +reset behavior. Add ``--enable_cameras`` if the annotated output needs RGB observations. +Input images are not simply copied: annotation records observations during replay. +``--auto`` does not provide the skill starts and internal object events required here. + +Controls +-------- + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Key + - Action + * - ``N`` + - Begin or resume replay. + * - ``B`` + - Pause replay to inspect a boundary. + * - ``S`` + - Mark the next printed signal at the current action index. + * - ``Q`` + - Skip the episode. + +Marks are taken before the current action is applied. Use the visible robot/object state, +not a guessed timestamp. Each press of ``S`` accepts one signal. A skill's start must be +at a later action index than the previous skill's end, even when the visible states are +close. For example, if one skill ends at action 100, start the next at action 101 or later. +The tool repeats a pass if the mark count is incomplete and +does not export a replay that fails the task-success check. + +Marks for This Task +------------------- + +The following order comes from the shipped task descriptor. Names reused between start +and end marks belong to separate HDF5 groups. + +.. list-table:: Left arm + :header-rows: 1 + :widths: 18 32 50 + + * - Mark + - Signal + - Meaning + * - Skill start + - ``grasp_left`` + - Begin the beaker grasp, after the approach. + * - Object event + - ``beaker_grasp`` + - The beaker is securely held by the left hand. + * - Skill end + - ``grasp_left`` + - Finish the grasp skill, before transport to the bowl. + * - Skill start + - ``pour_left`` + - Begin pouring after arriving above the bowl. + * - Skill end + - ``pour_clear_left`` + - Finish pouring and move the beaker clear of the bowl. + * - Skill start + - ``beaker_release_start`` + - Begin the release skill after arriving at the bin. + * - Object event + - ``beaker_release`` + - Release the beaker; it is no longer carried by the hand. + +.. list-table:: Right arm + :header-rows: 1 + :widths: 18 32 50 + + * - Mark + - Signal + - Meaning + * - Skill start + - ``grasp_right`` + - Begin the bowl grasp after the approach. + * - Object event + - ``bowl_grasp`` + - The bowl is securely held by the right hand. + * - Skill end + - ``grasp_right`` + - Finish the grasp skill, before transport to the scale. + * - Skill start + - ``place_bowl_on_scale_right`` + - Begin placement/release after arriving at the scale. + * - Object event + - ``bowl_release`` + - Release the bowl onto the scale. + +Each arm's final subtask ends implicitly with the episode. Its explicit **start** is still +required. The descriptor also limits release windows around their object events; do not +omit those marks because a final termination signal is implicit. +Record and retain at least two actions after each ``beaker_release`` and ``bowl_release`` +mark for the configured release windows. The penultimate action is too late. + +Grasp/release marks update the planner's carried-object collision model. They do not weld +objects to the robot in simulation and do not impose task-order constraints. Those remain +in the task YAML. Events at a segment's explicit start/end need no internal event mark. + +Expected Output +--------------- + +The annotated HDF5 contains the recorded data plus aligned signals under: + +.. code-block:: text + + obs/datagen_info/subtask_start_signals/ + obs/datagen_info/subtask_term_signals/ + obs/datagen_info/object_event_signals/ + +There is no separate annotation sidecar. Validate the file and inspect a complete annotated +episode before generation: + +.. code-block:: bash + + python scripts/validate_dataset.py datasets/gr1t2_schedulegen/source_newton_annotated.hdf5 + +Continue to :doc:`step_3_generate_dataset`. diff --git a/docs/pages/workflows/schedulegen/step_3_generate_dataset.rst b/docs/pages/workflows/schedulegen/step_3_generate_dataset.rst new file mode 100644 index 0000000..09328eb --- /dev/null +++ b/docs/pages/workflows/schedulegen/step_3_generate_dataset.rst @@ -0,0 +1,160 @@ +.. + Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: Apache-2.0 + +Step 3: Generate a Dataset +========================== + +Start with one environment and one successful demonstration. Inspect the result before +raising the trial count or enabling parallel generation. Run these commands inside the +cuRobo development container described in :doc:`index`. + +.. _schedulegen-source-data: + +Choose the Annotated Source +--------------------------- + +The included source is +:autodata_code_link:``. +It is about 62 MiB, self-contained, and contains five demonstrations with skill boundaries +and internal grasp/release marks. The supplied normal/cross examples share this source; +it has also been exercised with both physics backends. Do not substitute the humanoid +steering-wheel pick-and-place dataset. + +If the checkout contains only a Git LFS pointer, fetch the file from the **host**: + +.. code-block:: bash + + git lfs pull --include="datasets/annotated_datasets/dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5" + +If you completed Steps 1–2, use your new annotated file instead. Keep its recording +backend/profile consistent for your first generation check. There is no events sidecar +or ``--source_event_annotations`` argument. + +Configuration Files +------------------- + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - File + - Purpose + * - :autodata_code_link:`` + - Subtasks, segment providers, grasp/release events, task order and scheduling options. + * - :autodata_code_link:`` + - End-effector observations, pose targets, hand joints and the 36-value action layout. + * - :autodata_code_link:`` + - Arm joint groups, tool frames, robot collision geometry and cuRobo settings. + * - `Environment profile `_ + - Object placement/randomization, controller settings, object properties and front view. + +Generate the Normal Layout +-------------------------- + +.. code-block:: bash + + python scripts/generate_dataset.py \ + --alg schedulegen \ + --env_name AutoData-NutPour-GR1T2-ScheduleGen-v0 \ + --external_callback autodata_examples.gr1t2_nut_pour:register \ + --physics_backend newton \ + --task_descriptor autodata_examples/tasks/gr1t2_nut_pour_schedulegen.yaml \ + --embodiment autodata_examples/embodiments/gr1t2_schedulegen.yaml \ + --robot_planning autodata_examples/embodiments/gr1t2_planning.yaml \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml \ + --input_file datasets/annotated_datasets/dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5 \ + --output_file datasets/gr1t2_schedulegen/normal_newton.hdf5 \ + --result_file datasets/gr1t2_schedulegen/normal_newton.json \ + --generation_num_trials 1 \ + --generation_max_failures 10 \ + --generation_mode per_environment \ + --num_envs 1 \ + --device cuda:0 \ + --viz none \ + --record_metric_inputs \ + --record_video \ + --video_dir datasets/gr1t2_schedulegen/video_newton + +For PhysX, use ``--physics_backend physx`` and distinct output/result/video paths, such as +``normal_physx.hdf5``, ``normal_physx.json`` and ``video_physx``. The other configurations +are unchanged. To use your own Newton recording, replace ``--input_file`` with +``datasets/gr1t2_schedulegen/source_newton_annotated.hdf5``. + +``--record_video`` saves the profile's front viewport and enables camera observations. +For generation without video, omit both video arguments. Add ``--enable_cameras`` if you +still want the robot's RGB observations in the dataset. Start the container once and +reuse it for subsequent checks; first-use assets, shaders and robot models can take time. +``--record_metric_inputs`` saves the per-step inputs needed by the standard metrics report +in Step 4; omit it when those extra measurements are not needed. + +Add ``--visualize_plan`` to open Rerun for environment zero. The default **Arm plans** tab +plays motion-planned transits in preparation order on the ``planning`` timeline; it does not +show live physics or the intervening demonstration segments. For the complete proposed +episode, open **Scheduled robot** and select its ``full_state_schedule_`` timeline. +That preview includes both arms, demonstration segments and scheduled waits. Add +``--rerun_output datasets/plans.rrd`` to save the recording instead of opening a live viewer. + +Trials, Failures and Files +-------------------------- + +The supplied descriptor sets ``guarantee_success: true``. Thus ``--generation_num_trials`` +is a target number of **successful demonstrations**, not a fixed attempt count. The +failure allowance bounds additional attempts; reaching that limit can leave a valid but +smaller dataset. Read the JSON counters rather than assuming the target was reached. + +The descriptor also sets ``keep_failed: true``. Failed physical replays may be exported +to a separate failure HDF5; planning failures can occur before there are steps to export. +Do not mix failure files into successful policy-training data. Set ``keep_failed: false`` +in your task configuration if those recordings are not wanted. + +The HDF5 writer replaces an existing file at the selected output path. Reusing a disposable +path is convenient for local checks; choose a new path for data you intend to retain. + +Try the Cross Layout +-------------------- + +The fixed-waist cross layout increases overlap between the arms' paths. Use the same +annotated source and task descriptor, replacing these arguments together: + +.. code-block:: bash + + --robot_planning autodata_examples/embodiments/gr1t2_cross_planning.yaml \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen_cross_overlap.yaml \ + --output_file datasets/gr1t2_schedulegen/cross_newton.hdf5 \ + --result_file datasets/gr1t2_schedulegen/cross_newton.json \ + --video_dir datasets/gr1t2_schedulegen/video_cross_newton + +The cross planner checks the moving arm/hand groups rather than the full fixed robot. +This is not whole-body collision coverage. Neither layout's sampled checks guarantee +collision avoidance between samples or successful physical contact; simulation and task +evaluation still matter. + +Scale After Inspecting One Episode +---------------------------------- + +Raise the trial count and choose an appropriate failure allowance only after validating +the first output. The two :ref:`generation modes ` are: + +* ``per_environment``: independent planner contexts, with asynchronous synchronized stepping. +* ``buffered``: shared planning context, optional parallel CPU schedule solves, batched replay. + +For a small buffered run, replace the corresponding arguments above with: + +.. code-block:: bash + + --generation_mode buffered \ + --num_envs 5 \ + --schedule_workers 2 \ + --generation_num_trials 10 + +Remove ``--record_video`` and ``--video_dir`` when using multiple environments; the video +wrapper currently supports one environment. The requested demo count applies to the whole +run, not each batch. Later batches fill only the missing successful demos, subject to the +same attempt budget. Progress counters remain cumulative across batches. + +More environments do not guarantee higher throughput or unchanged success rates. Independent +planner contexts can consume substantial GPU memory; buffered generation shares planner memory +but still allocates simulation state. + +Continue to :doc:`step_4_validate_dataset`. diff --git a/docs/pages/workflows/schedulegen/step_4_validate_dataset.rst b/docs/pages/workflows/schedulegen/step_4_validate_dataset.rst new file mode 100644 index 0000000..768d4fe --- /dev/null +++ b/docs/pages/workflows/schedulegen/step_4_validate_dataset.rst @@ -0,0 +1,123 @@ +.. + Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: Apache-2.0 + +Step 4: Validate and Inspect the Dataset +======================================== + +A completed process is not enough: check the attempt counters, exported episodes and +physical task outcome before using the data for learning. + +Check the Files +--------------- + +Inside the development container: + +.. code-block:: bash + + python scripts/validate_dataset.py datasets/gr1t2_schedulegen/normal_newton.hdf5 --check_arrays + +The file must contain episodes with actions, observations and initial state. The +``--check_arrays`` option also rejects non-finite numeric values and observation lengths +that differ from the action count. Without this option, validation checks only structure. +The generation JSON should agree with the successful exports. Its per-attempt diagnostics distinguish +planning failure, scheduling infeasibility, motion validation and physical task failure. +For nut pouring, inspect the final nut-in-bowl, bowl-on-scale and beaker-in-bin checks. + +For the standard metrics report, also pass the matching generation result: + +.. code-block:: bash + + python scripts/validate_dataset.py \ + datasets/gr1t2_schedulegen/normal_newton.hdf5 \ + --report \ + --result_file datasets/gr1t2_schedulegen/normal_newton.json \ + --source datasets/annotated_datasets/dataset_gr1t2_nut_pour_schedulegen_annotated.hdf5 \ + --report_file datasets/gr1t2_schedulegen/normal_newton_report.json + +Some metrics require per-step inputs. Add ``--record_metric_inputs`` during generation +when those metrics are needed; missing measurements should not be interpreted as zeros. +Use your actual source filename in the report if you recorded your own demonstrations. + +Inspect the Recorded Rollout +---------------------------- + +The video saved during generation shows the execution that produced the dataset. Look for: + +* A secure beaker grasp, followed by pouring without pushing the bowl away. +* Clearance above the bowl before its pickup starts. +* Overlapping beaker return and bowl handling when the paths allow it. +* Stable releases, with the nut in the bowl, the bowl on the scale and the beaker in the bin. + +The front-view video is separate from the robot's observation camera. To record the +robot's camera instead, add ``--video_observation_path policy.robot_pov_cam`` to a +single-environment generation command. This does not change either camera pose. + +Replay with Isaac Lab +--------------------- + +Use the same backend and profile as the saved episode: + +.. code-block:: bash + + python submodules/IsaacLab-Arena/submodules/IsaacLab/scripts/tools/replay_demos.py \ + --task AutoData-NutPour-GR1T2-ScheduleGen-v0 \ + --external_callback autodata_examples.gr1t2_nut_pour.register \ + --physics_backend newton \ + --env_profile autodata_examples/env_profiles/gr1t2_nut_pour_schedulegen.yaml \ + --dataset_file datasets/gr1t2_schedulegen/normal_newton.hdf5 \ + --device cuda:0 \ + --num_envs 1 \ + --viz kit + +Use ``--physics_backend physx`` and the PhysX filename for PhysX data. For cross data, +also use the cross environment profile. Leave the replay tool's solver-buffer-reset +option disabled for Newton. Action replay can diverge from recorded physics; it is an +additional inspection, not a replacement for generation's recorded task outcome. + +The supplied GR1T2 examples keep the waist fixed. For robots with shared planning joints, +generation can also apply per-step posture targets that are not stored in the action array. +These exports are not yet complete action-only demonstrations. Keep shared joints fixed +when generating data for policy training until posture commands are included in the recorded actions. + +Inspect Plans in Rerun +---------------------- + +Add ``--visualize_plan`` to the generation command to open a live Rerun viewer of the +planned paths and collision spheres. A display is needed for the viewer; ``--viz none`` +only disables the simulator visualizer. To save a Rerun recording instead of opening the +viewer, also add: + +.. code-block:: bash + + --rerun_output datasets/gr1t2_schedulegen/plans.rrd + +Check robot/object frames, the active arm's spheres, carried-object geometry and the +planned transits. Rerun shows planning geometry; the simulator video is needed to judge +contacts and physical execution. + +Troubleshooting +--------------- + +.. list-table:: + :header-rows: 1 + :widths: 28 72 + + * - Symptom + - First check + * - Source file cannot be opened + - Confirm it is the complete Git LFS HDF5, not a pointer or an unrelated pick-and-place file. + * - Missing skill start or object event + - Compare the annotation groups with the task's printed mark list. Use manual annotation. + * - Incorrect hand motion + - Check the GR1T2 callback, embodiment action layout and recording profile before changing gains. + * - Planner cannot reach a target + - Inspect the reset, tool frames, model joint limits and the matching normal/cross planning config. + * - Scheduler is infeasible + - Inspect task-order/continuity constraints and collision conflicts; timing cannot repair an unreachable path. + * - Contacts fail despite a valid schedule + - Inspect the recorded grasp, pour and release windows, object properties and actual rollout. + * - GPU memory is exhausted + - Reduce independent planner contexts or try buffered generation. Do not assume ten contexts fit every GPU. + * - Few or no successful exports + - Read the attempt/failure counters and stages before increasing the failure allowance. diff --git a/scripts/annotate_demos.py b/scripts/annotate_demos.py index 5bb1209..0f06518 100644 --- a/scripts/annotate_demos.py +++ b/scripts/annotate_demos.py @@ -17,14 +17,14 @@ * ``N`` -- begin / resume playback * ``B`` -- pause playback -* ``S`` -- mark a subtask signal at the current step +* ``S`` -- mark the next skill boundary or object event at the current step * ``Q`` -- skip the current episode Automatic mode: Pass ``--auto`` to annotate subtask termination signals without keyboard input (``--viz none`` supported). ``--signal_obs_group`` selects the observation group holding the per-subtask boolean -terms (default ``subtask_terms``). SkillGen start signals still require manual mode. +terms (default ``subtask_terms``). SkillGen and ScheduleGen skill starts and object events require manual mode. """ """Launch Isaac Sim Simulator first.""" @@ -39,7 +39,7 @@ PROCESS_START = time.monotonic() parser = argparse.ArgumentParser( - description="Manually annotate AutoData source demonstrations with subtask signals.", + description="Annotate AutoData source demonstrations with skill boundaries and object events.", formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( @@ -57,6 +57,7 @@ default=None, help="Flush simulation buffers before replay. Defaults to enabled for PhysX and disabled for Newton.", ) +parser.add_argument("--env_profile", default=None, help="AutoData environment profile used when recording the source.") parser.add_argument( "--task_descriptor", type=str, @@ -118,7 +119,6 @@ import contextlib # noqa: E402 import gymnasium as gym # noqa: E402 -import math # noqa: E402 import numpy as np # noqa: E402 import os # noqa: E402 import random # noqa: E402 @@ -133,11 +133,13 @@ from isaaclab.managers import DatasetExportMode, RecorderTermCfg, TerminationTermCfg # noqa: E402 from isaaclab.utils.datasets import EpisodeData, HDF5DatasetFileHandler # noqa: E402 +from autodata_core.algorithms import REGISTERED_ALGORITHMS # noqa: E402 from autodata_core.pool import DataGenInfoPool # noqa: E402 from autodata_examples.envs import register_environment_for_run # noqa: E402 from autodata_interfaces.datastream import Datastream # noqa: E402 from autodata_interfaces.embodiments import embodiment_adapter_from_yaml # noqa: E402 from autodata_interfaces.env import ( # noqa: E402 + EnvironmentProfile, collect_autodata_entry, get_env_name_from_dataset, setup_env_config, @@ -149,7 +151,9 @@ ) from autodata_interfaces.env.recorders import PreStepCameraObservationsRecorder # noqa: E402 from autodata_interfaces.env.registration import register_external_environment # noqa: E402 +from autodata_interfaces.tasks.segment_spec import SegmentEventPoint # noqa: E402 from autodata_interfaces.tasks.task_descriptor import TaskDescriptor # noqa: E402 +from autodata_interfaces.tasks.task_descriptor_utils import resolve_task_algorithm # noqa: E402 from autodata_utils.dataset_metadata import exported_dataset_files, merge_autodata_entry # noqa: E402 is_paused = False @@ -184,38 +188,37 @@ def mark_subtask_cb() -> None: def _build_signal_names( task_descriptor: TaskDescriptor, annotate_start_signals: bool, -) -> tuple[dict[str, list[str]], dict[str, list[str]]]: - """Resolve the per-EEF subtask term (and start) signal names to annotate. +) -> dict[str, list[tuple[str, str]]]: + """List each arm's skill boundaries and optional object events in replay order. + + Args: + task_descriptor: Task defining skill boundaries and named object events. + annotate_start_signals: Whether to mark skill starts as well as terminations. Returns: - ``(term_signal_names, start_signal_names)`` dicts, each mapping eef name to an ordered list - of signal names. + Per-arm ordered pairs of HDF5 signal group and annotation name. Events within + a skill follow their declaration order in the task descriptor. """ - term_signal_names: dict[str, list[str]] = {} - start_signal_names: dict[str, list[str]] = {} + signals: dict[str, list[tuple[str, str]]] = {} for eef_name in task_descriptor.get_eef_names(): - eef_term_names = task_descriptor.get_term_signal_names(eef_name) - - # Start signals (one per subtask, keyed by term-signal name) are needed only for SkillGen. - if annotate_start_signals: - assert all(name for name in eef_term_names), ( - f"Missing 'subtask_term_signal' for one or more subtasks of eef '{eef_name}'. When " - "annotating for SkillGen, every subtask (including the last) must specify" - "'subtask_term_signal' (its name is reused as the start-signal key)." - ) - start_signal_names[eef_name] = list(eef_term_names) - else: - start_signal_names[eef_name] = [] - - # Termination signals: every subtask except the final one (which ends the trajectory). - non_final_term_names = eef_term_names[:-1] - assert all(name for name in non_final_term_names), ( - f"Missing 'subtask_term_signal' for a non-final subtask of eef '{eef_name}'. Every " - "subtask except the last must specify 'subtask_term_signal'." - ) - term_signal_names[eef_name] = non_final_term_names - - return term_signal_names, start_signal_names + signals[eef_name] = [] + subtasks = task_descriptor.get_subtasks(eef_name) + for index, subtask in enumerate(subtasks): + if annotate_start_signals: + start_name = subtask.subtask_start_signal or subtask.subtask_term_signal + assert start_name, f"Missing start signal for {eef_name} subtask {index}." + signals[eef_name].append(("subtask_start_signals", start_name)) + for segment in subtask.segments: + signals[eef_name].extend( + ("object_event_signals", event.annotation_key) + for event in segment.events + if event.point == SegmentEventPoint.SOURCE_ANNOTATION + ) + if index < len(subtasks) - 1: + assert subtask.subtask_term_signal, f"Missing termination signal for {eef_name} subtask {index}." + signals[eef_name].append(("subtask_term_signals", subtask.subtask_term_signal)) + assert len(signals[eef_name]) == len(set(signals[eef_name])), f"Duplicate annotation names for {eef_name}." + return signals def main() -> int: @@ -250,20 +253,26 @@ def main() -> int: presets=args_cli.presets, ) - # Start signals are required only by SkillGen. - annotate_start_signals = generation_policy.use_skillgen + # SkillGen and ScheduleGen mark skill windows rather than only subtask ends. + algorithm_name = resolve_task_algorithm(None, args_cli.task_descriptor) + annotate_start_signals = REGISTERED_ALGORITHMS[algorithm_name].uses_subtask_start_signals assert not (args_cli.auto and annotate_start_signals), ( - "--auto only annotates subtask termination signals; SkillGen additionally needs subtask " - "start signals, which have no automatic source yet. Annotate SkillGen datasets in manual " + "--auto only annotates subtask termination signals; this task additionally needs skill " + "start signals, which have no automatic source yet. Annotate these datasets in manual " "mode (drop --auto)." ) # Resolve the subtask signals to annotate - term_signal_names, start_signal_names = _build_signal_names(task_descriptor, annotate_start_signals) - total_signals = sum(len(names) for names in term_signal_names.values()) + sum( - len(names) for names in start_signal_names.values() - ) + signal_names = _build_signal_names(task_descriptor, annotate_start_signals) + term_signal_names = { + eef: [name for group, name in signals if group == "subtask_term_signals"] + for eef, signals in signal_names.items() + } + assert not args_cli.auto or all( + group == "subtask_term_signals" for signals in signal_names.values() for group, _ in signals + ), "--auto cannot annotate skill starts or object events; use manual mode." + total_signals = sum(len(names) for names in signal_names.values()) assert total_signals > 0, ( "No subtask signals to annotate: every eef declares only a single end-of-trajectory subtask. " "Manual annotation requires at least one non-final subtask with a 'subtask_term_signal'." @@ -280,6 +289,7 @@ def main() -> int: device=args_cli.device, generation_policy_params=generation_policy, recorder_cfg=DatagenInfoRecorderManagerCfg(), + env_profile=EnvironmentProfile.from_yaml(args_cli.env_profile) if args_cli.env_profile else None, enable_cameras=args_cli.record_images, record_step_success=args_cli.record_metric_inputs, ) @@ -360,9 +370,7 @@ def main() -> int: env, episode, success_term, term_signal_names, task_descriptor, args_cli.signal_obs_group ) else: - annotated = annotate_episode_in_manual_mode( - env, episode, success_term, term_signal_names, start_signal_names, annotate_start_signals - ) + annotated = annotate_episode_in_manual_mode(env, episode, success_term, signal_names) if annotated and not skip_episode: env.recorder_manager.set_success_to_episodes( @@ -454,9 +462,7 @@ def annotate_episode_in_manual_mode( env, episode: EpisodeData, success_term: TerminationTermCfg | None, - term_signal_names: dict[str, list[str]], - start_signal_names: dict[str, list[str]], - annotate_start: bool, + signal_names: dict[str, list[tuple[str, str]]], ) -> bool: """Interactively annotate one episode's subtask signals. @@ -468,36 +474,29 @@ def annotate_episode_in_manual_mode( env: The environment to replay in. episode: The recorded episode to annotate. success_term: Optional success termination term. - term_signal_names: Per-EEF ordered subtask termination-signal names to annotate. - start_signal_names: Per-EEF ordered subtask start-signal names to annotate (may be empty). - annotate_start: Whether subtask start signals are annotated (SkillGen); when True the marks - interleave start/termination per subtask, otherwise every mark is a termination. + signal_names: Per-arm ordered pairs of HDF5 signal group and annotation name. Returns: True if the episode was fully annotated, False if it was skipped or never succeeded. """ global is_paused, marked_subtask_action_indices, skip_episode - term_signal_action_indices: dict[str, int] = {} - start_signal_action_indices: dict[str, int] = {} + annotations: dict[tuple[str, str], int] = {} - for eef_name, eef_term_names in term_signal_names.items(): - eef_start_names = start_signal_names[eef_name] - # Nothing to annotate for this eef (e.g. a single end-of-trajectory subtask). - if len(eef_term_names) == 0 and len(eef_start_names) == 0: + for eef_name, signals in signal_names.items(): + if not signals: continue while True: is_paused = True skip_episode = False print(f'\tPlaying the episode for subtask annotations for eef "{eef_name}".') - print("\tSubtask signals to annotate:") - if len(eef_start_names) > 0: - print(f"\t\t- Start:\t{eef_start_names}") - print(f"\t\t- Termination:\t{eef_term_names}") + print("\tSignals to mark in order:") + for group, name in signals: + print(f"\t\t- {group}: {name}") print('\n\tPress "N" to begin.') print('\tPress "B" to pause.') - print('\tPress "S" to annotate subtask signals.') + print('\tPress "S" to mark the next annotation.') print('\tPress "Q" to skip the episode.\n') marked_subtask_action_indices = [] @@ -506,25 +505,11 @@ def annotate_episode_in_manual_mode( print("\tSkipping the episode.") return False - print(f"\tSubtasks marked at action indices: {marked_subtask_action_indices}") - expected_count = len(eef_term_names) + len(eef_start_names) + print(f"\tAnnotations marked at action indices: {marked_subtask_action_indices}") + expected_count = len(signals) if task_succeeded and expected_count == len(marked_subtask_action_indices): print(f'\tAll {expected_count} subtask signals for eef "{eef_name}" were annotated.') - # When annotating both signal types the marks interleave start, term, start, term, ... - # ending with the final subtask's start, otherwise every mark is a termination. - for marked_index in range(expected_count): - if not annotate_start: - term_signal_action_indices[eef_term_names[marked_index]] = marked_subtask_action_indices[ - marked_index - ] - elif marked_index % 2 == 0: - start_signal_action_indices[eef_start_names[marked_index // 2]] = marked_subtask_action_indices[ - marked_index - ] - else: - term_signal_action_indices[eef_term_names[math.floor(marked_index / 2)]] = ( - marked_subtask_action_indices[marked_index] - ) + annotations.update(zip(signals, marked_subtask_action_indices, strict=True)) break if not task_succeeded: @@ -540,18 +525,10 @@ def annotate_episode_in_manual_mode( num_steps = len(episode.data["actions"]) annotated_episode = env.recorder_manager.get_episode(0) - for signal_name, action_index in term_signal_action_indices.items(): - # Termination signal: False until the subtask completes, True from that step onward. + for (group, signal_name), action_index in annotations.items(): signal = torch.ones(num_steps, dtype=torch.bool) signal[:action_index] = False - # These are complete trajectories; EpisodeData.add() appends a single timestep. - annotated_episode.data["obs"]["datagen_info"].setdefault("subtask_term_signals", {})[signal_name] = signal - - if annotate_start: - for signal_name, action_index in start_signal_action_indices.items(): - signal = torch.ones(num_steps, dtype=torch.bool) - signal[:action_index] = False - annotated_episode.data["obs"]["datagen_info"].setdefault("subtask_start_signals", {})[signal_name] = signal + annotated_episode.data["obs"]["datagen_info"].setdefault(group, {})[signal_name] = signal return True diff --git a/scripts/generate_dataset.py b/scripts/generate_dataset.py index 0d02cda..9ed69fd 100755 --- a/scripts/generate_dataset.py +++ b/scripts/generate_dataset.py @@ -8,11 +8,11 @@ python scripts/generate_dataset.py \\ --env_name \\ - [--alg {mimicgen|dexmimicgen|skillgen|softmimicgen}] \\ + [--alg {mimicgen|dexmimicgen|skillgen|softmimicgen|schedulegen}] \\ --task_descriptor \\ --embodiment \\ --env_profile \\ - --input_file \\ + [--input_file ] \\ --output_file \\ --generation_num_trials \\ --num_envs @@ -22,13 +22,14 @@ * ``mimicgen`` — single-arm MimicGen. * ``dexmimicgen`` — two-arm MimicGen with subtask coordination constraints. -* ``skillgen`` — single-arm SkillGen. SkillGen depends on a motion-planner interface; until the - planner code is ported into this repo, the CLI satisfies that interface with the upstream Arena - ``CuroboPlanner``. +* ``skillgen`` — single-arm SkillGen using the native cuRobo planner interface. +* ``schedulegen`` — complete multi-arm path construction, collision/task scheduling, state restore, + and synchronized replay with native arm-local cuRobo configuration. * ``softmimicgen`` — one- or two-arm MimicGen with deformable-object nodal registration. The CLI composes a :class:`Datastream` from the task descriptor YAML, the embodiment YAML, the -live env, and the HDF5 source dataset, then hands it to :class:`DataGenerator`. +live env, and an optional HDF5 source dataset, then hands it to :class:`DataGenerator`. A source +dataset is optional only for an all-motion-planned ScheduleGen task. """ """Launch Isaac Sim Simulator first.""" @@ -48,9 +49,12 @@ # Hardcoded to keep argparse importable without pulling in the heavy core package. # Add new algorithms here when registering them in autodata_core.algorithms. -_ALG_CHOICES = ["mimicgen", "dexmimicgen", "skillgen", "softmimicgen"] +_ALG_CHOICES = ["mimicgen", "dexmimicgen", "skillgen", "softmimicgen", "schedulegen"] parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) +planning_args = parser.add_argument_group("Motion planning (SkillGen and ScheduleGen)") +schedule_args = parser.add_argument_group("ScheduleGen execution") +recording_args = parser.add_argument_group("Recording and reports") parser.add_argument( "--env_name", type=str, @@ -89,18 +93,41 @@ ), ) parser.add_argument("--generation_num_trials", type=int, default=None, help="Number of demos to generate.") +parser.add_argument( + "--generation_max_failures", + type=int, + default=None, + help="Override the task descriptor's finite failed-attempt budget.", +) parser.add_argument("--num_envs", type=int, default=1, help="Number of parallel environments.") parser.add_argument( "--presets", choices=("physx", "newton"), default=None, help="Physics backend preset for Arena environments." ) -parser.add_argument("--input_file", type=str, required=True, help="Source dataset HDF5 file.") +schedule_args.add_argument( + "--generation_mode", + choices=("per_environment", "buffered"), + default="per_environment", + help="Per-environment generation or buffered ScheduleGen planning/scheduling with vectorized replay.", +) +schedule_args.add_argument( + "--schedule_workers", + type=int, + default=1, + help="Concurrent CPU schedule solves in buffered mode; planning and validation remain serial.", +) +parser.add_argument( + "--input_file", + type=str, + default=None, + help="Source dataset HDF5 file; optional for an all-motion-planned ScheduleGen task.", +) parser.add_argument( "--output_file", type=str, default="./datasets/output_dataset.hdf5", help="Destination HDF5 for generated episodes.", ) -parser.add_argument( +recording_args.add_argument( "--result_file", type=str, default=None, @@ -109,7 +136,7 @@ "log with one JSON line per attempt is written next to it (..attempts.jsonl)." ), ) -parser.add_argument( +recording_args.add_argument( "--record_metric_inputs", action="store_true", help=( @@ -122,10 +149,34 @@ action="store_true", help="Pause after every subtask for interactive debugging.", ) -parser.add_argument( +planning_args.add_argument( "--visualize_plan", action="store_true", - help="Visualize SkillGen motion plans in a Rerun viewer (env 0 only; requires the rerun package).", + help="Visualize SkillGen or ScheduleGen plans in Rerun (environment zero only).", +) +planning_args.add_argument( + "--rerun_output", + type=str, + default=None, + help="Save SkillGen or ScheduleGen visualization to this .rrd file instead of opening a viewer.", +) +planning_args.add_argument("--robot_planning", type=str, default=None, help="Planning-groups YAML for ScheduleGen.") +recording_args.add_argument( + "--record_video", + action="store_true", + help="Save every generated rollout from the configured simulator viewport (single environment).", +) +recording_args.add_argument( + "--video_dir", + type=str, + default="./datasets/visual_validation", + help="Directory for generated rollout MP4 files.", +) +recording_args.add_argument( + "--video_observation_path", + type=str, + default=None, + help="Record this dot-separated RGB observation instead of the configured simulator viewport.", ) parser.add_argument( @@ -146,7 +197,28 @@ task_descriptor = TaskDescriptor.from_yaml(args_cli.task_descriptor) embodiment_adapter = embodiment_adapter_from_yaml(args_cli.embodiment) task_descriptor.validate_embodiment(embodiment_adapter) - +if args_cli.input_file is None and (args_cli.alg != "schedulegen" or task_descriptor.requires_source_demos()): + parser.error("--input_file is required for tasks containing demonstration segments.") +if args_cli.alg == "schedulegen" and args_cli.robot_planning is None: + parser.error("--robot_planning is required for schedulegen.") +if args_cli.num_envs < 1 or args_cli.schedule_workers < 1: + parser.error("--num_envs and --schedule_workers must be positive.") +if args_cli.generation_mode == "buffered" and args_cli.alg != "schedulegen": + parser.error("--generation_mode buffered requires --alg schedulegen.") +if args_cli.generation_mode != "buffered" and args_cli.schedule_workers != 1: + parser.error("--schedule_workers applies only to buffered generation.") +if args_cli.alg != "schedulegen" and args_cli.robot_planning is not None: + parser.error("--robot_planning applies only to ScheduleGen.") +if args_cli.alg not in ("skillgen", "schedulegen") and (args_cli.visualize_plan or args_cli.rerun_output): + parser.error("plan visualization requires SkillGen or ScheduleGen.") + +args_cli.record_images = args_cli.record_images or args_cli.record_video +record_viewport = args_cli.record_video and args_cli.video_observation_path is None +viewport_headless = record_viewport and "kit" not in (args_cli.visualizer or []) +if viewport_headless: + args_cli.visualizer = [name for name in (args_cli.visualizer or []) if name != "none"] + ["kit"] + args_cli.visualizer_explicit = True + args_cli.headless = True app_launcher = AppLauncher(args_cli, enable_cameras=args_cli.record_images) simulation_app = app_launcher.app @@ -157,23 +229,30 @@ import numpy as np # noqa: E402 import platform # noqa: E402 import random # noqa: E402 +import resource # noqa: E402 import sys # noqa: E402 +import time # noqa: E402 import torch # noqa: E402 import traceback # noqa: E402 import uuid # noqa: E402 from pathlib import Path # noqa: E402 from typing import Any # noqa: E402 +import isaaclab_mimic.envs # noqa: E402, F401 +from isaaclab.utils.string import string_to_callable # noqa: E402 + from autodata_core import DataGenerator, get_algorithm # noqa: E402 from autodata_core.algorithms import REGISTERED_ALGORITHMS # noqa: E402 -from autodata_core.data_generator import GenerationResult # noqa: E402 from autodata_examples.envs import register_environment_for_run # noqa: E402 from autodata_interfaces.datastream import Datastream # noqa: E402 -from autodata_interfaces.env import ( # noqa: E402 +from autodata_interfaces.env import ViewportRenderWrapper # noqa: E402 +from autodata_interfaces.env import ( EnvironmentProfile, + ObservationRenderWrapper, collect_autodata_entry, env_loop, get_env_name_from_dataset, + observation_video_path_resolve, setup_env_config, setup_output_paths, ) @@ -188,58 +267,6 @@ input_record, write_generation_result, ) -from autodata_utils.tensor_utils import as_torch # noqa: E402 - - -async def run_data_generator( - env: Any, - env_id: int, - env_reset_queue: asyncio.Queue, - env_action_queue: asyncio.Queue, - data_generator: DataGenerator, - success_term, - pause_subtask: bool, - stats: dict, - attempt_log: AttemptLog | None, -) -> None: - """Repeatedly call ``data_generator.generate``, tally outcomes into ``stats`` and log each attempt.""" - while True: - attempt_start = time.monotonic() - try: - result = await data_generator.generate( - env_id=env_id, - success_term=success_term, - env_reset_queue=env_reset_queue, - env_action_queue=env_action_queue, - pause_subtask=pause_subtask, - ) - except Exception as exc: - sys.stderr.write(traceback.format_exc()) - sys.stderr.flush() - raise exc - - if result.success: - stats["num_success"] += 1 - else: - stats["num_failures"] += 1 - stats["num_attempts"] += 1 - if attempt_log is not None: - attempt_log.write(_attempt_record(env_id, result, attempt_start, time.monotonic())) - - -def _attempt_record(env_id: int, result: GenerationResult, start_time: float, end_time: float) -> dict: - """One attempt-log line; times [s] are monotonic-clock readings.""" - return { - "env_id": env_id, - "success": result.success, - "start_time_s": start_time, - "end_time_s": end_time, - "initial_object_positions": { - name: as_torch(state["root_pose"])[env_id, :2].tolist() - for name, state in result.initial_state.get("rigid_object", {}).items() - }, - "extras": result.extras, - } def _hardware(device: str) -> dict[str, str | None]: @@ -258,7 +285,7 @@ def _hardware(device: str) -> dict[str, str | None]: def build_datastream( env: Any, - input_file: str, + input_file: str | None, task_descriptor: TaskDescriptor, embodiment_adapter: EmbodimentAdapter, ) -> Datastream: @@ -273,7 +300,10 @@ def build_datastream( source_dataset_path=input_file, uses_start_signals=task_descriptor.get_generation_policy().use_skillgen, ) - print(f"Loaded {datastream.num_source_demos} source episodes into the datagen pool") + if datastream.num_source_demos: + print(f"Loaded {datastream.num_source_demos} source episodes into the datagen pool") + else: + print("Task requires no source demonstrations; using an empty datagen pool") return datastream @@ -289,24 +319,29 @@ def setup_async_generation( asyncio_event_loop = asyncio.get_event_loop() env_reset_queue: asyncio.Queue = asyncio.Queue() env_action_queue: asyncio.Queue = asyncio.Queue() - env = datastream.get_env() - data_generator = DataGenerator(datastream=datastream, algorithm=algorithm) + data_generator = DataGenerator( + datastream=datastream, + algorithm=algorithm, + demo_keys=datastream.get_generation_policy().source_demo_keys, + ) stats = {"num_success": 0, "num_failures": 0, "num_attempts": 0} + attempts: list[dict[str, Any]] = [] + pending_env_ids: set[int] = set() tasks = [] for env_id in range(num_envs): task = asyncio_event_loop.create_task( - run_data_generator( - env=env, + data_generator.generate_loop( env_id=env_id, env_reset_queue=env_reset_queue, env_action_queue=env_action_queue, - data_generator=data_generator, success_term=success_term, pause_subtask=pause_subtask, stats=stats, attempt_log=attempt_log, + attempts=attempts, + pending_env_ids=pending_env_ids, ) ) tasks.append(task) @@ -318,11 +353,18 @@ def setup_async_generation( "action_queue": env_action_queue, "info_pool": datastream.source_pool, "stats": stats, + "attempts": attempts, } def _build_motion_planners( - datastream, num_envs: int, env_name: str, *, planner_profile: str | None = None, visualize_plan: bool = False + datastream, + num_envs: int, + env_name: str, + *, + planner_profile: str | None = None, + visualize_plan: bool = False, + rerun_output: str | None = None, ) -> dict: """Construct one cuRobo v1 motion planner per env_id satisfying the SkillGen interface. @@ -331,6 +373,17 @@ def _build_motion_planners( The planner config comes from ``planner_profile`` (named by the environment profile) when given, else from task-name matching. Rerun plan visualization is opt-in via ``visualize_plan`` and limited to env 0. + + Args: + datastream: Environment, task and embodiment interfaces used by each planner. + num_envs: Number of independent planners to construct. + env_name: Task name used when no planner profile is provided. + planner_profile: Optional named robot/planner configuration. + visualize_plan: Whether environment zero logs plans to Rerun. + rerun_output: Optional recording path instead of opening a Rerun viewer. + + Returns: + Motion planners keyed by environment index. """ from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg @@ -344,6 +397,7 @@ def _build_motion_planners( # Visualization is rerun-based; limit to env_id 0 to keep simulation responsive. if env_id == 0: planner_config.visualize_plan = planner_config.visualize_plan or visualize_plan + planner_config.rerun_output = rerun_output else: planner_config.visualize_spheres = False planner_config.visualize_plan = False @@ -356,21 +410,43 @@ def _build_motion_planners( def _close_motion_planners(planners: dict | None) -> None: + """Close each shared plan visualizer once and release planner references.""" if not planners: return - for env_id, planner in planners.items(): - if getattr(planner, "plan_visualizer", None) is not None: - print(f"Closing plan visualizer for environment {env_id}") - planner.plan_visualizer.close() + closed_visualizers: set[int] = set() + for env_id, planner_or_groups in planners.items(): + if hasattr(planner_or_groups, "group_planners") and hasattr(planner_or_groups, "full_state"): + groups = (*planner_or_groups.group_planners.values(), planner_or_groups.full_state) + else: + groups = planner_or_groups.values() if isinstance(planner_or_groups, dict) else (planner_or_groups,) + for planner in groups: + visualizer = getattr(planner, "plan_visualizer", None) + if visualizer is not None and id(visualizer) not in closed_visualizers: + print(f"Closing plan visualizer for environment {env_id}") + visualizer.close() + closed_visualizers.add(id(visualizer)) planner.plan_visualizer = None planners.clear() def main() -> None: + """Create the selected environment and algorithm, generate episodes and save run results.""" register_external_environment(args_cli, environment_args) + if args_cli.rerun_output is not None: + assert args_cli.visualize_plan, "--rerun_output requires --visualize_plan" + if args_cli.record_video: + assert args_cli.num_envs == 1, "video recording currently supports exactly one environment" output_dir, output_file_name = setup_output_paths(args_cli.output_file) - # The env name (CLI override) falls back to the name recorded in the source dataset. - env_name = args_cli.env_name.split(":")[-1] if args_cli.env_name else get_env_name_from_dataset(args_cli.input_file) + env_profile = EnvironmentProfile.from_yaml(args_cli.env_profile) if args_cli.env_profile else None + # A profile names the base task it patches. Without a profile, preserve the ordinary source + # dataset fallback; an explicit CLI environment remains the highest-priority override. + if args_cli.env_name: + env_name = args_cli.env_name.split(":")[-1] + elif env_profile is not None: + env_name = env_profile.base_env + else: + assert args_cli.input_file is not None, "--env_name or --env_profile is required without --input_file" + env_name = get_env_name_from_dataset(args_cli.input_file) # The task descriptor's GenerationPolicy is the source for generation policy parameters. generation_policy_params = task_descriptor.get_generation_policy() @@ -378,6 +454,9 @@ def main() -> None: # The CLI --generation_num_trials, when given, overrides the descriptor's num_trials. if args_cli.generation_num_trials is not None: generation_policy_params.num_trials = args_cli.generation_num_trials + if args_cli.generation_max_failures is not None: + assert args_cli.generation_max_failures >= 0 + generation_policy_params.max_num_failures = args_cli.generation_max_failures random.seed(generation_policy_params.seed) np.random.seed(generation_policy_params.seed) @@ -400,8 +479,6 @@ def main() -> None: # The environment profile, when given, overlays scene/reset changes onto the base task and # names the motion-planner profile tuned for the resulting scene. - env_profile = EnvironmentProfile.from_yaml(args_cli.env_profile) if args_cli.env_profile else None - recorder_cfg = load_callable(args_cli.recorder_cfg)() if args_cli.recorder_cfg else None if args_cli.record_metric_inputs: recorder_cfg = recorder_cfg or make_action_state_recorder_manager_cfg(record_images=args_cli.record_images) @@ -418,19 +495,56 @@ def main() -> None: env_profile=env_profile, enable_cameras=args_cli.record_images, ) - env_cfg.seed = generation_policy_params.seed - env = gym.make(env_name, cfg=env_cfg, **env_make_kwargs.get(env_name, {})).unwrapped - # Environment initialization can reseed or consume the global RNGs. + + if viewport_headless: + from isaaclab_visualizers.kit import KitVisualizer, KitVisualizerCfg + + from autodata_interfaces.env.kit_visualizer import KitVisualizerHeadless + + visualizers = env_cfg.sim.visualizer_cfgs or [] + if not isinstance(visualizers, list): + visualizers = [visualizers] + kit_cfg = next((cfg for cfg in visualizers if cfg.visualizer_type == "kit"), None) + if kit_cfg is None: + kit_cfg = KitVisualizerCfg(class_type=KitVisualizerHeadless) + visualizers = [*visualizers, kit_cfg] + elif kit_cfg.class_type is KitVisualizer: + kit_cfg.class_type = KitVisualizerHeadless + kit_cfg.headless = True + env_cfg.sim.visualizer_cfgs = visualizers + base_env = gym.make(env_name, cfg=env_cfg, **env_make_kwargs.get(env_name, {})).unwrapped random.seed(generation_policy_params.seed) np.random.seed(generation_policy_params.seed) torch.manual_seed(generation_policy_params.seed) + env = base_env + if args_cli.record_video: + if args_cli.video_observation_path is not None: + observation_path = observation_video_path_resolve( + args_cli.video_observation_path, + default_image_observation_names=tuple(getattr(env_cfg, "image_obs_list", ())), + ) + env = ObservationRenderWrapper(env, observation_path=observation_path) + else: + env = ViewportRenderWrapper(env) + env = gym.wrappers.RecordVideo( + env, + video_folder=args_cli.video_dir, + episode_trigger=(lambda _: True) if args_cli.generation_mode == "per_environment" else None, + step_trigger=(lambda step: step == 0) if args_cli.generation_mode == "buffered" else None, + name_prefix=f"{task_descriptor.name}-{args_cli.alg}", + disable_logger=True, + ) - env.reset() + if args_cli.record_images: + # Initialize dynamic render transforms before resetting the scene used for recording. + base_env.sim.step(render=False) + base_env.scene.update(base_env.cfg.sim.dt) + base_env.reset() # Build the Datastream first; the motion planners read all world state through it. datastream = build_datastream( - env=env, + env=base_env, input_file=args_cli.input_file, task_descriptor=task_descriptor, embodiment_adapter=embodiment_adapter, @@ -440,6 +554,9 @@ def main() -> None: # SkillGen needs one curobo planner per env. Mimic/DexMimic take no kwargs. motion_planners: dict | None = None alg_kwargs: dict = {} + planner_started = time.perf_counter() + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() if args_cli.alg == "skillgen": motion_planners = _build_motion_planners( datastream, @@ -447,62 +564,127 @@ def main() -> None: env_name, planner_profile=env_profile.planner if env_profile else None, visualize_plan=args_cli.visualize_plan, + rerun_output=args_cli.rerun_output, ) alg_kwargs["motion_planners"] = motion_planners + elif args_cli.alg == "schedulegen": + from autodata_interfaces.motion_planners.curobo import curobo_planning_context_create + + diagnostics_path = task_descriptor.get_attempt_diagnostics() + attempt_diagnostics = string_to_callable(diagnostics_path) if diagnostics_path is not None else None + motion_planners = {} + planning_env_count = 1 if args_cli.generation_mode == "buffered" else args_cli.num_envs + for env_id in range(planning_env_count): + planning_context = curobo_planning_context_create( + datastream, + args_cli.robot_planning, + env_id=env_id, + visualize_plan=args_cli.visualize_plan, + rerun_output=args_cli.rerun_output if env_id == 0 else None, + ) + motion_planners[env_id] = planning_context + alg_kwargs.update( + planning_contexts=motion_planners, + attempt_diagnostics=attempt_diagnostics, + ) algorithm = get_algorithm(args_cli.alg, **alg_kwargs) autodata_entry = None if args_cli.record_metric_inputs: noises = [spec.action_noise for specs in task_descriptor.subtasks.values() for spec in specs] - noises += [getattr(planner.config, "motion_noise_scale", 0.0) for planner in (motion_planners or {}).values()] + noises += [ + getattr(planner.config, "motion_noise_scale", 0.0) + for planner_or_context in (motion_planners or {}).values() + for planner in ( + planner_or_context.group_planners.values() + if hasattr(planner_or_context, "group_planners") + else (planner_or_context,) + ) + ] autodata_entry = { - **collect_autodata_entry(env, embodiment_adapter, run_id), + **collect_autodata_entry(base_env, embodiment_adapter, run_id), "action_noise": max(noises, default=0.0), } + planner_init_s = time.perf_counter() - planner_started + generation_started = time.perf_counter() + generation_start = time.monotonic() attempts_file = attempts_file_for(args_cli.result_file, run_id) if autodata_entry and args_cli.result_file else None attempt_log = AttemptLog(attempts_file, run_id) if attempts_file else None try: - async_components = setup_async_generation( - datastream=datastream, - num_envs=args_cli.num_envs, - success_term=success_term, - algorithm=algorithm, - pause_subtask=args_cli.pause_subtask, - attempt_log=attempt_log, - ) + if args_cli.generation_mode == "buffered": + from autodata_core.schedulegen.batching import generate_buffered - data_gen_tasks = asyncio.ensure_future(asyncio.gather(*async_components["tasks"])) - generation_completed = False - generation_start = time.monotonic() - try: - generation_completed = env_loop( - env, - async_components["reset_queue"], - async_components["action_queue"], - async_components["event_loop"], - generation_policy_params=generation_policy_params, - stats=async_components["stats"], - data_gen_tasks=data_gen_tasks, + data_generator = DataGenerator( + datastream=datastream, algorithm=algorithm, demo_keys=generation_policy_params.source_demo_keys + ) + async_components = generate_buffered( + env, data_generator, algorithm, success_term, args_cli.schedule_workers, attempt_log=attempt_log + ) + generation_completed = async_components["completed"] + else: + async_components = setup_async_generation( + datastream=datastream, + num_envs=args_cli.num_envs, + success_term=success_term, + algorithm=algorithm, + pause_subtask=args_cli.pause_subtask, + attempt_log=attempt_log, ) - generation_end = time.monotonic() - except asyncio.CancelledError: - print("Async tasks cancelled.") - finally: - data_gen_tasks.cancel() + + data_gen_tasks = asyncio.ensure_future(asyncio.gather(*async_components["tasks"])) + generation_completed = False try: - async_components["event_loop"].run_until_complete(data_gen_tasks) + generation_completed = env_loop( + env, + async_components["reset_queue"], + async_components["action_queue"], + async_components["event_loop"], + generation_policy_params=generation_policy_params, + stats=async_components["stats"], + data_gen_tasks=data_gen_tasks, + ) except asyncio.CancelledError: - print("Remaining async tasks cleaned up.") - except Exception as exc: - print(f"Error cleaning up async tasks: {exc}") - _close_motion_planners(motion_planners) - - if generation_completed and args_cli.result_file: + print("Async tasks cancelled.") + finally: + data_gen_tasks.cancel() + try: + async_components["event_loop"].run_until_complete(data_gen_tasks) + except asyncio.CancelledError: + print("Remaining async tasks cleaned up.") + except Exception as exc: + print(f"Error cleaning up async tasks: {exc}") + generation_end = time.monotonic() + if args_cli.result_file: write_generation_result( result_file=args_cli.result_file, algorithm=args_cli.alg, requested_trials=generation_policy_params.num_trials, stats=async_components["stats"], + attempts=async_components["attempts"], + execution={ + **async_components.get("execution", {}), + "mode": args_cli.generation_mode, + "num_envs": args_cli.num_envs, + "planner_context_count": len(motion_planners or {}), + "planner_init_s": planner_init_s, + "generation_s": time.perf_counter() - generation_started, + "cpu_peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024, + **( + { + "cuda_peak_allocated_bytes": torch.cuda.max_memory_allocated(), + "cuda_peak_reserved_bytes": torch.cuda.max_memory_reserved(), + } + if torch.cuda.is_available() + else {} + ), + }, + environment={ + "name": env_name, + "physics_manager": ( + f"{base_env.sim.physics_manager.__module__}:{base_env.sim.physics_manager.__qualname__}" + ), + "control_dt_s": float(base_env.step_dt), + }, env_profile=( {"name": env_profile.name, "path": args_cli.env_profile, "planner": env_profile.planner} if env_profile @@ -530,7 +712,10 @@ def main() -> None: } ), ) + if not generation_completed: + print(f"Generation target was not reached; wrote the run outcome to {args_cli.result_file}", flush=True) finally: + _close_motion_planners(motion_planners) env.close() if autodata_entry is not None: for dataset_file in exported_dataset_files( diff --git a/scripts/validate_dataset.py b/scripts/validate_dataset.py index 81dfbbc..e73f85e 100644 --- a/scripts/validate_dataset.py +++ b/scripts/validate_dataset.py @@ -20,6 +20,7 @@ import h5py import importlib import json +import numpy as np import os import sys @@ -56,8 +57,13 @@ def _decode(value: object) -> str: return value if isinstance(value, str) else str(value) -def validate_file(path: str) -> ValidationResult: - """Structurally validate one HDF5 dataset and collect its metadata.""" +def validate_file(path: str, *, check_arrays: bool = False) -> ValidationResult: + """Validate one HDF5 dataset and collect its metadata. + + Args: + path: Dataset to read. + check_arrays: Whether to also check finite numeric values and observation/action alignment. + """ result = ValidationResult(path) @@ -101,10 +107,35 @@ def validate_file(path: str) -> ValidationResult: if field in demo and not isinstance(demo[field], expected_kind): kind = "group" if expected_kind is h5py.Group else "dataset" result.issues.append(f"{name}: '{field}' must be a {kind}") + if check_arrays and isinstance(demo.get("actions"), h5py.Dataset): + _validate_arrays(demo, result) return result +def _validate_arrays(episode: h5py.Group, result: ValidationResult) -> None: + """Check numeric values in chunks and observation lengths without loading image arrays.""" + actions = episode["actions"] + if actions.ndim == 0 or len(actions) == 0: + result.issues.append(f"{episode.name}: actions must have a nonempty time dimension") + return + + def check(name: str, node: h5py.Group | h5py.Dataset) -> None: + """Check one episode array and append any invalid values or lengths.""" + if not isinstance(node, h5py.Dataset): + return + if name.startswith("obs/") and (node.ndim == 0 or len(node) != len(actions)): + result.issues.append(f"{episode.name}/{name}: observation length differs from actions") + if np.issubdtype(node.dtype, np.inexact): + chunks = ( + (node[()],) if node.ndim == 0 else (node[start : start + 256] for start in range(0, len(node), 256)) + ) + if any(not np.isfinite(chunk).all() for chunk in chunks): + result.issues.append(f"{episode.name}/{name}: contains non-finite numeric values") + + episode.visititems(check) + + def _read_env_metadata(data: h5py.Group, result: ValidationResult) -> None: """Parse the env_args attribute of the dataset (env id + sim args).""" @@ -167,6 +198,9 @@ def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Validate AutoData demonstration HDF5 datasets.") parser.add_argument("files", nargs="+", help="HDF5 dataset file(s) to validate.") + parser.add_argument( + "--check_arrays", action="store_true", help="Check finite values and observation/action lengths." + ) parser.add_argument("--report", action="store_true", help="Also report the metrics of a single dataset.") parser.add_argument("--result_file", help="Generation result (generate_dataset.py --result_file) of the dataset.") parser.add_argument("--source", help="Source dataset the generation started from.") @@ -186,7 +220,7 @@ def main(argv: list[str] | None = None) -> int: except ValueError as exc: parser.error(str(exc)) - results = [validate_file(path) for path in args.files] + results = [validate_file(path, check_arrays=args.check_arrays) for path in args.files] print_results(results) num_invalid = sum(not r.valid for r in results)