# ----------------------------------------------------------------------------
# Copyright (c) 2021-2026 DexForce Technology Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
"""Source-independent preparation, sampling and selected-row scene application."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from copy import deepcopy
from dataclasses import dataclass
import hashlib
import itertools
import json
from pathlib import Path
from types import MappingProxyType
from typing import TYPE_CHECKING
import numpy as np
import torch
from embodichain.compute.geometry._hierarchical import _sample_hierarchy
from .._support_grid import _prepare_support
from .._validation import _identifier, _rigid_pose
from ..geometry import SupportSurfaceConfig, detect_support_region
from ..query import _backend_tensor
from .contracts import ScenePoseChange, SceneVariant
from .conditions import SceneLayoutCondition, _condition_prepared
from ._root_support import _root_support_offsets
from ._layout_numeric import (
_hierarchy_batch_limit,
_numeric_geometry,
_sample_poses,
_specification,
)
from ._policy import (
SceneRandomizationPolicyCfg,
_policy_data,
_validate_backend,
_validate_generation_parameters,
)
if TYPE_CHECKING:
from embodichain.lab.sim import SimulationManager
__all__ = [
"SceneLayoutInput",
"PreparedSceneRandomization",
"SceneRandomizationBatch",
"SceneVariantApplicationResult",
"scene_layout_input_from_sim",
"prepare_scene_randomization",
"generate_scene_variants",
"apply_scene_variants",
]
_ALGORITHM = "scene.hierarchical_batch_rejection/v1"
def _digest(value: object) -> str:
return hashlib.sha256(
json.dumps(
value, sort_keys=True, separators=(",", ":"), allow_nan=False
).encode()
).hexdigest()
def _owned_array(value: object, *, faces: bool = False) -> np.ndarray:
try:
raw = np.asarray(value)
if faces and raw.dtype.kind not in "iu":
raise ValueError("Triangle indices must be integers.")
array = np.array(value, dtype=np.int64 if faces else np.float64, copy=True)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError("Scene geometry must contain finite numeric arrays.") from exc
if (
array.ndim != 2
or array.shape[1] != 3
or not len(array)
or not np.isfinite(array).all()
):
raise ValueError("Scene geometry requires nonempty finite (N, 3) arrays.")
array.setflags(write=False)
return array
[docs]
@dataclass(frozen=True)
class PreparedSceneRandomization:
"""Own reusable numeric geometry, policy, permissions and source identity."""
source: SceneLayoutInput
_policy: dict
geometry_sha256: str
movable_uids: tuple[str, ...]
_geometry: dict
_table: tuple
_movable_roots: tuple[int, ...]
@property
def policy(self) -> dict:
"""Return an owned policy snapshot, preserving prepared geometry ownership."""
return deepcopy(self._policy)
[docs]
def prepare_scene_randomization(
source: SceneLayoutInput,
policy: SceneRandomizationPolicyCfg | Mapping,
*,
cache_dir: str | Path | None = None,
) -> PreparedSceneRandomization:
"""Prepare source-independent hierarchy and conservative support geometry.
Args:
source: Owned authored scene geometry and explicit support tree.
policy: CPU/CUDA sampling policy, without runtime seed or file inputs.
cache_dir: Optional content-addressed support-cache directory.
Returns:
Prepared geometry reusable across generation calls and ordinary resets.
"""
if not isinstance(source, SceneLayoutInput):
raise TypeError("source must be a SceneLayoutInput")
policy = _policy_data(policy)
parents = dict(source.parent_by_uid)
ordered = []
def visit(parent: str) -> None:
for uid in sorted(uid for uid in parents if parents[uid] == parent):
ordered.append(uid)
visit(uid)
visit(source.support_uid)
roots = [uid for uid in ordered if parents[uid] == source.support_uid]
targets = policy["intra_group"]["targets"]
if set(targets) - (set(ordered) - set(roots)):
raise ValueError("Intra-group targets must name non-root members.")
def subtree(uid: str) -> set[str]:
children = {uid}
for child in ordered[ordered.index(uid) + 1 :]:
if parents[child] in children:
children.add(child)
return children
permitted = set(source.movable_entity_ids)
selected_roots = set(
roots if policy["group_targets"] is None else policy["group_targets"]
)
if selected_roots - set(roots):
raise ValueError("group_targets must name group roots.")
if set(policy["group_xy_offset_bounds_m"]) - selected_roots:
raise ValueError("Group offset bounds must reference selected group roots.")
if policy["group_targets"] is None:
selected_roots = {uid for uid in roots if subtree(uid) <= permitted}
elif any(not subtree(uid) <= permitted for uid in selected_roots):
raise ValueError("A moving group contains fixed entities.")
if not policy["randomize_groups"]:
selected_roots.clear()
moving = set().union(*(subtree(uid) for uid in selected_roots | set(targets)))
if not moving or moving - permitted:
raise ValueError(
"No permitted layout changes, or a moving subtree contains fixed entities."
)
active = set()
for uid in targets:
parent = parents[uid]
while parent != source.support_uid:
active.add(parent)
parent = parents[parent]
if set(policy["intra_group"]["support_overrides"]) - active:
raise ValueError("Support overrides must reference active member parents.")
nodes = []
for uid in ordered:
parent = parents[uid]
pose = np.asarray(source.poses[uid])
relative = (
pose
if parent == source.support_uid
else np.linalg.inv(source.poses[parent]) @ pose
)
points = source.vertices[uid]
nodes.append(
{
"uid": uid,
"parent": -1 if parent == source.support_uid else ordered.index(parent),
"relative_pose": relative.tolist(),
"corners": [
list(v)
for v in itertools.product(*zip(points.min(0), points.max(0)))
],
}
)
key = _digest(
{
"source": source.fingerprint,
"extractor": "scene-layout-support/v4",
"root_offsets": policy["group_xy_offset_bounds_m"],
"movable_roots": sorted(selected_roots),
"intra": policy["intra_group"],
}
)
geometry = None
table = None
authored_table = (
tuple(tuple(point[:2]) for point in source.main_support_bounds)
if source.main_support_bounds is not None
else None
)
path = None if cache_dir is None else Path(cache_dir) / (key + ".json")
if path is not None and path.exists():
from .persistence import _read_json
cached = _read_json(path)
if cached.get("key") != key or cached.get("sha256") != _digest(
{"geometry": cached.get("geometry"), "table": cached.get("table")}
):
raise ValueError("Prepared support cache contents changed.")
geometry = cached["geometry"]
bounds = np.asarray(cached["table"], dtype=np.float64)
if (
bounds.shape != (2, 2)
or not np.isfinite(bounds).all()
or np.any(bounds[0] >= bounds[1])
):
raise ValueError("Prepared main support bounds are invalid.")
table = tuple(tuple(float(value) for value in row) for row in bounds)
if authored_table is not None and table != authored_table:
raise ValueError("Prepared bounds differ from the authored main support.")
if geometry is None:
supports = {}
for parent in sorted(active):
children = [uid for uid in ordered if parents[uid] == parent]
child_points = []
for child in children:
rel = np.linalg.inv(source.poses[parent]) @ np.asarray(
source.poses[child]
)
child_points.append(source.vertices[child] @ rel[:3, :3].T + rel[:3, 3])
intra = policy["intra_group"]
support = _prepare_support(
source.vertices[parent],
source.faces[parent],
child_points,
resolution=intra["grid_resolution_m"],
margin=intra["boundary_margin_m"],
override=intra["support_overrides"].get(parent),
)
inverse = np.linalg.inv(support["parent_from_support"])
support["root_min_z"] = {}
for child in children:
rel = (
inverse
@ np.linalg.inv(source.poses[parent])
@ np.asarray(source.poses[child])
)
support["root_min_z"][child] = float(
(source.vertices[child] @ rel[:3, :3].T)[:, 2].min()
)
supports[parent] = support
geometry = {"nodes": nodes, "supports": supports}
if table is None:
table = authored_table
if table is None:
transform = np.asarray(source.poses[source.support_uid])
points = (
source.vertices[source.support_uid] @ transform[:3, :3].T
+ transform[:3, 3]
)
region = detect_support_region(
source.support_uid,
points,
source.faces[source.support_uid],
config=SupportSurfaceConfig(preserve_holes=True),
)
rectangle = region.optimization_rectangle
if rectangle is None:
raise ValueError(
"Main support has no conservative rectangular sampling region."
)
lo_x, lo_y, hi_x, hi_y = rectangle.bounds
table = ((lo_x, lo_y), (hi_x, hi_y))
offsets = _root_support_offsets(
source, nodes, table, policy["group_xy_offset_bounds_m"], selected_roots
)
if offsets:
geometry["root_support_offsets"] = offsets
if path is not None:
from .persistence import _write_atomic
payload = {"geometry": geometry, "table": table}
_write_atomic(path, {"key": key, "sha256": _digest(payload), **payload})
return PreparedSceneRandomization(
source,
deepcopy(policy),
_digest(geometry),
tuple(sorted(moving)),
geometry,
table,
tuple(ordered.index(uid) for uid in roots if uid in selected_roots),
)
class _VariantPool(Sequence[SceneVariant]):
def __init__(
self,
parent: str,
seed: int,
uids: tuple[str, ...],
poses: np.ndarray,
ordinals: np.ndarray,
metadata: tuple[tuple[str, str], ...],
) -> None:
self.parent, self.seed, self.uids, self.metadata = parent, seed, uids, metadata
self.poses, self.ordinals = np.array(poses, copy=True), np.array(
ordinals, copy=True
)
self.poses.setflags(write=False)
self.ordinals.setflags(write=False)
def __len__(self) -> int:
return len(self.ordinals)
def __getitem__(
self, index: int | slice
) -> SceneVariant | tuple[SceneVariant, ...]:
if isinstance(index, slice):
return tuple(self[i] for i in range(*index.indices(len(self))))
ordinal = int(self.ordinals[index])
return SceneVariant(
self.parent,
self.seed,
ordinal,
tuple(
ScenePoseChange(uid, pose)
for uid, pose in zip(self.uids, self.poses[index])
),
tuple(sorted((*self.metadata, ("proposal_ordinal", str(ordinal))))),
)
[docs]
@dataclass(frozen=True)
class SceneRandomizationBatch:
"""Owned lazy proposals and exact bounded generation accounting."""
prepared: PreparedSceneRandomization
variants: Sequence[SceneVariant]
attempts: int
status: str
seed: int
start_ordinal: int
next_ordinal: int
requested_count: int | None = None
max_attempts: int | None = None
[docs]
def generate_scene_variants(
prepared: PreparedSceneRandomization,
*,
seed: int = 0,
candidate_count: int = 10,
max_attempts: int = 1000,
start_ordinal: int = 0,
conditions: SceneLayoutCondition | None = None,
) -> SceneRandomizationBatch:
"""Generate a batch without loading meshes or constructing simulation objects.
Args:
prepared: Reusable geometry and policy.
seed: Addressed random stream seed.
candidate_count: Requested valid layouts.
max_attempts: Whole-layout proposal budget.
start_ordinal: First logical proposal; allows bounded continuation.
conditions: Optional owned arena-pose anchors. They restrict existing
root XY/member XY-yaw domains and never authorize extra motion.
Moving ancestors must be anchored explicitly. Empty conditions
preserve the ordinary sequence. Infeasible geometry exhausts the
declared proposal budget without moving or repairing anchors.
Returns:
Complete or budget-exhausted proposals with exact continuation ordinal.
"""
if conditions is not None:
prepared = _condition_prepared(prepared, conditions)
_validate_generation_parameters(
seed=seed,
candidate_count=candidate_count,
max_attempts=max_attempts,
collision_margin_m=prepared.policy["collision_margin_m"],
)
if type(start_ordinal) is not int or start_ordinal < 0:
raise ValueError("start_ordinal must be nonnegative.")
policy = {**deepcopy(prepared.policy), "seed": seed, "_table": prepared._table}
device = torch.device(policy["device"])
if device.type == "cuda" and (
not torch.cuda.is_available()
or (device.index is not None and device.index >= torch.cuda.device_count())
):
raise ValueError("Requested CUDA device is unavailable.")
spec = _specification(prepared._geometry, policy, device)
anchored_roots = (
tuple(
i
for i in prepared._movable_roots
if prepared._geometry["nodes"][i]["uid"] in conditions.poses
)
if conditions is not None
else ()
)
limit = (
_hierarchy_batch_limit(policy["batch_size"], len(spec[-1]))
if policy["randomize_groups"]
else policy["batch_size"]
)
support_offsets = prepared._geometry.get("root_support_offsets", {})
root_support_offsets = {
i: torch.as_tensor(
support_offsets[node["uid"]], dtype=spec[0].dtype, device=device
)
for i, node in enumerate(prepared._geometry["nodes"])
if node["uid"] in support_offsets
}
deltas, samples, ordinals = [], [], []
accepted = attempts = 0
while attempts < max_attempts and accepted < candidate_count:
count = min(limit, max_attempts - attempts)
delta, sample, valid = _sample_hierarchy(
*spec,
torch.tensor(prepared._table, dtype=torch.float64, device=device),
start=start_ordinal + attempts,
count=count,
randomize_groups=policy["randomize_groups"],
sibling_margin=policy["intra_group"]["sibling_margin_m"],
group_margin=policy["collision_margin_m"],
support_gap=policy["intra_group"]["support_gap_m"],
movable_roots=prepared._movable_roots,
anchored_roots=anchored_roots,
root_support_offsets=root_support_offsets,
root_offset_bounds={
i: torch.tensor(
policy["group_xy_offset_bounds_m"][node["uid"]],
dtype=torch.float64,
device=device,
)
for i, node in enumerate(prepared._geometry["nodes"])
if node["uid"] in policy["group_xy_offset_bounds_m"]
},
)
selected = torch.nonzero(valid, as_tuple=False).flatten()[
: candidate_count - accepted
]
picked = selected.cpu().numpy() + start_ordinal + attempts
deltas.append(delta[selected].cpu().numpy())
samples.append(sample[selected].cpu().numpy())
ordinals.append(picked)
accepted += len(picked)
attempts = (
int(picked[-1]) - start_ordinal + 1
if accepted == candidate_count
else attempts + count
)
delta = np.concatenate(deltas)
relative = _sample_poses(prepared._geometry, policy, np.concatenate(samples))
uids, poses, _ = _numeric_geometry(prepared._geometry, policy, delta, relative)
chosen = [i for i, uid in enumerate(uids) if uid in prepared.movable_uids]
pool = _VariantPool(
prepared.source.scene_id,
seed,
tuple(uids[i] for i in chosen),
poses[:, chosen],
np.concatenate(ordinals),
(
("generator", _ALGORITHM),
("source_sha256", prepared.source.fingerprint),
("geometry_sha256", prepared.geometry_sha256),
*(
(("conditions_sha256", _digest(conditions.to_dict())),)
if conditions is not None and conditions.poses
else ()
),
),
)
return SceneRandomizationBatch(
prepared,
pool,
attempts,
"completed" if accepted == candidate_count else "budget_exhausted",
seed,
start_ordinal,
start_ordinal + attempts,
candidate_count,
max_attempts,
)
[docs]
@dataclass(frozen=True)
class SceneVariantApplicationResult:
"""Selected-row pose publication and host-owned cache invalidations."""
env_ids: tuple[int, ...]
variant_ids: tuple[str, ...]
changed_uids: tuple[str, ...]
refresh_required: tuple[str, ...] = ("geometry", "planning", "observations")
[docs]
def apply_scene_variants(
sim: SimulationManager,
variants: Sequence[SceneVariant],
*,
env_ids: Sequence[int] | torch.Tensor,
movable_entity_ids: Sequence[str],
) -> SceneVariantApplicationResult:
"""Preflight all rows, then batch rigid pose writes without physics steps.
Args:
sim: Prepared caller-owned simulation.
variants: One validated proposal per selected row, in corresponding order.
env_ids: Unique selected rows; replica offsets never enter the poses.
movable_entity_ids: Explicit allowed native UID set.
Returns:
Applied identities and refresh requests. Native failures propagate and
do not guarantee rollback of earlier writes.
"""
raw = (
env_ids.detach().cpu().tolist()
if isinstance(env_ids, torch.Tensor)
else list(env_ids)
)
if any(type(i) is not int or not 0 <= i < sim.num_envs for i in raw) or len(
set(raw)
) != len(raw):
raise ValueError("env_ids must contain unique valid environment rows.")
if len(raw) != len(variants):
raise ValueError("One variant is required for each selected row.")
permitted = set(movable_entity_ids)
entities = set(sim.get_rigid_object_uid_list())
writes = {}
for row, variant in zip(raw, variants):
if not isinstance(variant, SceneVariant):
raise TypeError("variants must contain SceneVariant objects")
for change in variant.pose_changes:
uid = change.entity_uid
if uid not in permitted or uid not in entities:
raise ValueError(
f"Scene change requires a permitted existing rigid entity: {uid!r}"
)
entity = sim.get_rigid_object(uid)
if not all(
callable(getattr(entity, name, None))
for name in ("set_local_pose", "clear_dynamics")
):
raise ValueError(f"Entity {uid!r} does not support rigid pose writes.")
writes.setdefault(uid, []).append((row, change.arena_pose))
tensors = {
uid: _backend_tensor([pose for _, pose in values], device=sim.device).squeeze(0)
for uid, values in writes.items()
}
for uid, values in writes.items():
rows = [row for row, _ in values]
entity = sim.get_rigid_object(uid)
entity.clear_dynamics(env_ids=rows)
entity.set_local_pose(tensors[uid], env_ids=rows)
if writes:
sim.sync_render_state()
return SceneVariantApplicationResult(
tuple(raw), tuple(v.variant_id for v in variants), tuple(sorted(writes))
)