embodichain.lab.task_program.integrations.simulation.scene_expansion#

SimulationSceneExpansionHost provides physical preparation and initial-state restoration for the single-row Task Program scene expansion API. It supports pose changes to existing rigid objects while capturing the supported rigid, robot, and articulation state of a fixed scene.

SimulationSceneExpansionHost

Prepare existing-rigid-object variants through the Gym reset lifecycle.

SimulationSceneInitialState

Owned B=1 physical state for a fixed-topology scene host.

Reset ordering and recording#

The callable host passes a trusted zero-argument episode_prepare callback to BaseEnv.reset. The callback runs after normal reset and reset events, before physical-objective initialization and the final observation. EmbodiedEnv.reset then clears the old bridge and seeds recording from that observation. The hook is removed from forwarded options, so it does not become an observation or event-functor argument. A preparation hook requires a complete B=1 reset. Callback signatures are checked before seeding or resetting state.

The host preflights entity identity and state capture, applies arena-local rigid poses, clears moved-body dynamics, and advances the configured number of physics substeps for settling. Settling is preparation rather than a recorded expert action. Sensors and observation history are reset again after state changes; current contact samples are refreshed without advancing physics or contact history. The initial validator then checks the actual settled scene. Empty initial checks remain unavailable even when restoration or convergence checks pass. Subsequent Task Program bridge creation constructs fresh providers and a fresh motion generator with current collision bindings, including when the new episode starts at the same clock value as the previous one.

Owned initial states#

capture_initial_state and the host preparation callback produce immutable numeric copies of supported entity state. The snapshot contains rigid poses and velocities, articulation/robot roots, full joint positions and velocities, controller position/velocity targets, joint forces, backend, control period, and caller-supplied parent scene provenance. Obtain snapshots from the host; their ownership token is part of restoration validation.

The content-derived initial_state_id excludes temporary physical slots. to_metadata exports the state into JSON-compatible episode provenance. Asset contents and physical parameters must remain fixed for the host lifetime. The host measures mass, inertia, local COM, rigid friction/damping and articulation drive/limit fields at construction. It checks them before capture and restoration, and after reset events. Drift beyond absolute/relative 1e-6 is rejected. Reset-time parameter randomization requires independent initial-state preparation and a new host with those fixed parameters. Entity replacement, changed joint names/body types, incompatible backend/control period, and foreign-host snapshots are rejected before restoration writes. Rigid groups, deformables, and explicit rigid constraints are unsupported.

restore_initial_state uses the same reset hook, restores saved physical and controller values. Measured joint positions use absolute tolerance 1e-4 because the public state setter clamps small native joint-limit excursions. The host explicitly passes this allowance to the shared restoration service. The shared service’s default remains strict, controller position targets remain strict, and larger excursions fail before reset writes. Poses, velocities, controller targets, and efforts retain tolerance 1e-5. Quaternion signs are treated as equivalent. It resets sensor/observation history and runs the initial validator again. Restoration does not settle a second time. The mandatory scene.restore_state check records round-trip errors for measured joint positions and other fields, together with the source initial-state ID. Numerical backend round trips can change the actual state’s content hash while passing these tolerances. These checks do not relax task acceptance criteria or the robot’s joint limits.

This is an episode initial-state snapshot. Clearing solver history and external forces does not reproduce a backend’s complete mid-trajectory checkpoint.

Using the concrete host#

The application supplies task-specific initial and measured checks:

from collections.abc import Callable

from embodichain.lab.gym.envs.embodied_env import EmbodiedEnv
from embodichain.lab.sim.motion.expansion import ValidationResult
from embodichain.lab.sim.scene.expansion import SceneVariant
from embodichain.lab.task_program.integrations.scene_expansion import (
    SceneVariantEpisodeResult,
    execute_scene_variant,
)
from embodichain.lab.task_program.integrations.simulation.scene_expansion import (
    SimulationSceneExpansionHost,
    SimulationSceneInitialState,
)

def evaluate_and_capture(
    env: EmbodiedEnv,
    variant: SceneVariant,
    *,
    initial_validator: Callable[[], ValidationResult],
    measured_validator: Callable[[], ValidationResult],
) -> tuple[
    SimulationSceneExpansionHost,
    SimulationSceneInitialState,
    SceneVariantEpisodeResult,
]:
    host = SimulationSceneExpansionHost(
        env, initial_validator=initial_validator, settle_steps=8
    )
    result = execute_scene_variant(
        env,
        variant,
        prepare_scene=host,
        measured_validator=measured_validator,
    )
    snapshot = host.initial_state
    assert snapshot is not None
    env.reset(options={"save_data": result.accepted})
    return host, snapshot, result

For another execution from that exact saved initial state, reuse the owning host and pass prepare_scene=lambda _: host.restore_initial_state(snapshot) to execute_scene_variant. Evaluate the new execution independently. Workspace checks may be included in initial_validator using embodichain.lab.task_program.integrations.simulation.workspace; they remain separate from collision planning and measured task acceptance.

Public interfaces#

class embodichain.lab.task_program.integrations.simulation.scene_expansion.SimulationSceneExpansionHost[source]#

Prepare existing-rigid-object variants through the Gym reset lifecycle.

Parameters:
  • environment (EmbodiedEnv) – Initialized B=1 Gym environment, optionally wrapped.

  • initial_validator (Callable[[], ValidationResult]) – Required checks of the actual scene after settling. The callback may include task semantics, support and workspace IK.

  • settle_steps (int) – Nonnegative physics substeps before initial-state checks.

  • settling (SettlingCfg | None) – Optional measured convergence policy; overrides settle_steps. Failed or unverified convergence rejects the candidate.

Pass this host as prepare_scene to execute_scene_variant. The reset hook applies the candidate after ordinary reset events and before physical objectives, final observations and recorder seeding. Each subsequent Task Program bridge builds fresh providers and a fresh planner collision world.

Methods:

__init__(environment, *, initial_validator)

capture_initial_state(*, parent_scene_id)

Capture every supported physical entity without advancing physics.

restore_initial_state(snapshot)

Restore a captured state after normal reset events and recheck it.

Attributes:

initial_state

Return the last actual initial state, absent before preparation.

__init__(environment, *, initial_validator, settle_steps=0, settling=None)[source]#
capture_initial_state(*, parent_scene_id)[source]#

Capture every supported physical entity without advancing physics.

Parameters:

parent_scene_id (str) – Stable source scene/asset/configuration identity.

Return type:

SimulationSceneInitialState

Returns:

Owned full initial state suitable for restoration on this host.

Raises:

ValueError – If topology changed or any state cannot be captured fully.

property initial_state: SimulationSceneInitialState | None#

Return the last actual initial state, absent before preparation.

Returns:

Captured immutable state, including states rejected by the validator.

restore_initial_state(snapshot)[source]#

Restore a captured state after normal reset events and recheck it.

Parameters:

snapshot (SimulationSceneInitialState) – Immutable state captured by this host with identical assets, topology, physics backend and control period.

Return type:

ScenePreparationResult

Returns:

Fresh checks and the actual restored state identity, linked to the source snapshot. Restoration does not settle again. A mandatory state check requires measured joint positions within absolute tolerance 1e-4 to account for native joint-limit clipping. Every other field, including controller targets, uses 1e-5. Quaternion signs are equivalent. Backend round trips may produce a different content hash even when this passes.

Raises:

ValueError – For foreign snapshots or changed topology before writes.

class embodichain.lab.task_program.integrations.simulation.scene_expansion.SimulationSceneInitialState[source]#

Owned B=1 physical state for a fixed-topology scene host.

Parameters:
  • parent_scene_id (str) – Asset/configuration identity supplied by the candidate.

  • physics_backend (str) – Backend used for capture and required for restoration.

  • step_dt (float) – Authoritative Gym control period.

Snapshots include every supported rigid body, robot and articulation, with velocities, full joint state and controller targets. Storage is immutable numeric tuples, independent of simulator read buffers. Restoration clears solver history and external forces; this is an episode initial-state snapshot, not a bitwise mid-trajectory checkpoint. Physical parameters and asset contents are fixed for the lifetime of the owning host.

Methods:

__init__(parent_scene_id, physics_backend, ...)

to_metadata()

Export the actual initial state for the existing episode metadata.

Attributes:

initial_state_id

Return a content identity independent of physical slot assignments.

__init__(parent_scene_id, physics_backend, step_dt, _states, _owner)#
property initial_state_id: str#

Return a content identity independent of physical slot assignments.

Returns:

SHA-256 identity of scene provenance and complete captured state.

to_metadata()[source]#

Export the actual initial state for the existing episode metadata.

Return type:

dict[str, object]

Returns:

JSON-compatible poses, velocities, joint/controller state and scene provenance. Native handles and temporary environment IDs are absent.