diff --git a/docs/source/api/lab/isaaclab.cloner.rst b/docs/source/api/lab/isaaclab.cloner.rst index e62630515597..b82da7bb583e 100644 --- a/docs/source/api/lab/isaaclab.cloner.rst +++ b/docs/source/api/lab/isaaclab.cloner.rst @@ -75,7 +75,9 @@ Additional Public Classes :show-inheritance: .. autoclass:: InclusionSet + :members: :show-inheritance: + :exclude-members: __init__ .. autoclass:: ReplicateContext :members: diff --git a/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst new file mode 100644 index 000000000000..b4cdd620e8ea --- /dev/null +++ b/source/isaaclab/changelog.d/inclusion-world-layouts.added.rst @@ -0,0 +1,4 @@ +* Added :attr:`~isaaclab.cloner.InclusionSet.match_tags` to declare variant compatibility using + existing semantic tags, including multiple acceptable values. Matching groups stayed factorized + until the scene's clone strategy selected concrete worlds, avoiding exhaustive combination + expansion without inclusion callbacks, separate variant labels, or inclusion-owned sampling settings. diff --git a/source/isaaclab/changelog.d/inclusion-world-layouts.minor b/source/isaaclab/changelog.d/inclusion-world-layouts.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/cloner/__init__.pyi b/source/isaaclab/isaaclab/cloner/__init__.pyi index 09718dfa6f1a..ef2eb17b1062 100644 --- a/source/isaaclab/isaaclab/cloner/__init__.pyi +++ b/source/isaaclab/isaaclab/cloner/__init__.pyi @@ -30,7 +30,7 @@ __all__ = [ ] from .clone_plan import ClonePlan, PrototypeWorldTopology, grid_transforms, make_clone_plan, path, query, to_warp -from .cloner_cfg import CloneCfg, InclusionSet, add, expand_env_regex_ns +from .cloner_cfg import CloneCfg, InclusionSet, add, expand_env_regex_ns, make_valid_clone_combinations from .cloner_strategies import random, sequential from .collision_filter import filter_collisions from .fabric_notices import disabled_fabric_change_notifies @@ -38,7 +38,6 @@ from .replicate_context import ReplicateContext from .replicate_session import ( ReplicateSession, clone_plan_from_env_0, - make_valid_clone_combinations, num_spawn_variants, replicate, ) diff --git a/source/isaaclab/isaaclab/cloner/clone_plan.py b/source/isaaclab/isaaclab/cloner/clone_plan.py index 0a5d33aae9d7..7e1c8a74aa10 100644 --- a/source/isaaclab/isaaclab/cloner/clone_plan.py +++ b/source/isaaclab/isaaclab/cloner/clone_plan.py @@ -86,7 +86,7 @@ def to_warp(topology: PrototypeWorldTopology, device: str) -> PrototypeWorldTopo def make_clone_plan( asset_cfgs: Sequence[Any], - world_prototypes: Sequence[Sequence[int]], + world_prototypes: Sequence[Sequence[int | Sequence[int]]], num_worlds: int, *, weights: Sequence[float] | None = None, @@ -100,10 +100,15 @@ def make_clone_plan( Args: asset_cfgs: Asset prototype definitions, retained by reference. world_prototypes: Asset indices in each world prototype, including repeated instances. + A slot may instead contain candidate indices. Such factorized groups are selected + before their individual slots, without enumerating the Cartesian product. Only selected + concrete worlds are materialized and identical selections reuse one prototype. num_worlds: Number of destination worlds. weights: Relative world-prototype weights; ``None`` gives every prototype equal weight. shared_assets: Asset indices instantiated once in the shared world ``-1``. - clone_strategy: Function selecting world-prototype indices from weights. + clone_strategy: Function selecting world-prototype indices from weights. For factorized + groups, also selects each slot's concrete candidates with uniform candidate weights. + The same strategy owns both decisions and any randomness they require. env_template: Destination-world path template with one ``{}`` slot for the world ID. positions: Destination-world origins [m], shape [num_worlds, 3]; None preserves authored placement. @@ -114,11 +119,6 @@ def make_clone_plan( compositions = (shared_assets, *world_prototypes) if len(compositions) == 1: raise ValueError("At least one world prototype is required; an empty world is ().") - members = np.asarray([asset for world in compositions for asset in world]) - if members.size and ( - not np.issubdtype(members.dtype, np.integer) or (members < 0).any() or (members >= len(asset_cfgs)).any() - ): - raise ValueError("World members must be integer indices into asset_cfgs.") weights = np.ones(len(compositions) - 1) if weights is None else np.asarray(weights, dtype=np.float64) if weights.shape != (len(compositions) - 1,) or not np.isfinite(weights).all() or (weights < 0).any(): raise ValueError("Each world prototype requires one finite, non-negative weight.") @@ -129,6 +129,38 @@ def make_clone_plan( has_valid_ids = is_world_layout and (layout >= 0).all() and (layout < len(weights)).all() if not has_valid_ids: raise ValueError("clone_strategy must select one valid world-prototype index per destination.") + if any(not isinstance(slot, (int, np.integer)) for world in compositions[1:] for slot in world): + groups = [] + for world in compositions[1:]: + group = [] + for slot in world: + choices = np.asarray([slot] if isinstance(slot, (int, np.integer)) else slot) + is_index_list = choices.ndim == 1 and choices.size and np.issubdtype(choices.dtype, np.integer) + if not is_index_list or (choices < 0).any() or (choices >= len(asset_cfgs)).any(): + raise ValueError("World choices must be nonempty integer indices into asset_cfgs.") + group.append(choices) + groups.append(group) + selected = [None] * num_worlds + for group_id in np.unique(layout): + env_ids = np.flatnonzero(layout == group_id) + columns = [] + for choices in groups[group_id]: + ids = np.asarray(clone_strategy(np.ones(len(choices)), len(env_ids))) + is_candidate_layout = ids.shape == (len(env_ids),) and np.issubdtype(ids.dtype, np.integer) + if not is_candidate_layout or (ids < 0).any() or (ids >= len(choices)).any(): + raise ValueError("clone_strategy must select one valid candidate index per destination.") + columns.append(choices[ids]) + rows = zip(*columns, strict=True) if columns else [()] * len(env_ids) + for env_id, row in zip(env_ids, rows, strict=True): + selected[env_id] = tuple(int(member) for member in row) + prototype_ids = {world: index for index, world in enumerate(dict.fromkeys(selected))} + layout = np.asarray([prototype_ids[world] for world in selected], dtype=np.int32) + compositions = (shared_assets, *prototype_ids) + members = np.asarray([asset for world in compositions for asset in world]) + if members.size and ( + not np.issubdtype(members.dtype, np.integer) or (members < 0).any() or (members >= len(asset_cfgs)).any() + ): + raise ValueError("World members must be integer indices into asset_cfgs.") topology = PrototypeWorldTopology( num_asset_prototypes=len(asset_cfgs), world_prototypes=np.ascontiguousarray(members, dtype=np.int32), diff --git a/source/isaaclab/isaaclab/cloner/cloner_cfg.py b/source/isaaclab/isaaclab/cloner/cloner_cfg.py index 6f951e36c5ec..01a558ab0692 100644 --- a/source/isaaclab/isaaclab/cloner/cloner_cfg.py +++ b/source/isaaclab/isaaclab/cloner/cloner_cfg.py @@ -5,15 +5,20 @@ from __future__ import annotations +import itertools import warnings -from collections.abc import Callable +from collections.abc import Callable, Sequence from dataclasses import MISSING +from typing import TYPE_CHECKING import numpy as np from ..utils import configclass from .cloner_strategies import sequential +if TYPE_CHECKING: + from ..sim.spawners.spawner_cfg import SpawnerCfg + DEFAULT_ENV_TEMPLATE = "/World/envs/env_{}" """Default path template for a replicated env prim; ``{}`` marks the environment index.""" @@ -39,7 +44,7 @@ def expand_env_regex_ns(path_expr: str, env_template: str = DEFAULT_ENV_TEMPLATE @configclass class InclusionSet: - """Legal clone combination defined by explicitly listing active assets.""" + """Legal world layouts for explicitly selected scene assets.""" assets: list[str] = MISSING """Scene asset names active in this clone combination.""" @@ -47,6 +52,16 @@ class InclusionSet: weight: float = 1.0 """Relative sampling weight for this clone combination.""" + match_tags: list[str] = [] + """Semantic tag types whose values must overlap across the selected assets. + + Each selected variant must share a value for every listed tag type. Multiple values for a + tag express alternatives: a fixture supporting several sizes can match any one of them. + Assets not claimed by any inclusion set remain independent and do not participate in matching. + Empty keeps the existing independent Cartesian product. Matching groups remain factorized + until the scene's clone strategy selects concrete variants for its environments. + """ + @configclass class CloneCfg: @@ -65,6 +80,10 @@ class CloneCfg: Each entry names the assets that are active in one legal combination. Assets not referenced by any entry are active in every combination. An empty list keeps the homogeneous/default behavior. + + Inclusion sets declare semantic compatibility through :attr:`InclusionSet.match_tags`. + Planning resolves compatible groups before replication. The clone strategy selects groups + and concrete variants; inclusion definitions do not own environment counts or random seeds. """ clone_template: str = DEFAULT_ENV_TEMPLATE @@ -82,6 +101,88 @@ def __post_init__(self) -> None: warnings.warn("CloneCfg.replicate_physics is deprecated and ignored.", DeprecationWarning, stacklevel=2) +def make_valid_clone_combinations( + asset_names: Sequence[str], + variant_cfgs: Sequence[Sequence[SpawnerCfg]], + clone_combinations: Sequence[InclusionSet] | None = None, + *, + all_asset_names: Sequence[str] | None = None, +) -> tuple[tuple[tuple[int | tuple[int, ...], ...], ...], np.ndarray]: + """Resolve inclusion membership and semantic compatibility before replication. + + Repeated names create repeated instances. Unclaimed assets join every world independently. + Without matching tags, preserve the existing exhaustive product. With matching tags, return + compact compatible groups: each slot lists its candidate prototype IDs, without expanding + the Cartesian product within a group. Concrete selection belongs to clone-plan construction. + + Args: + asset_names: Names of the replicated asset declarations. + variant_cfgs: Concrete spawner configurations for each replicated declaration, including + semantic tags inherited from their multi-asset wrapper. + clone_combinations: Legal world definitions; None uses the default independent product. + all_asset_names: Scene names, including shared assets that do not enter world memberships. + + Returns: + World definitions and their relative weights. A definition contains concrete prototype IDs + or tuples of alternative IDs per slot. Inclusion weight is split equally across definitions. + + Raises: + ValueError: Candidate groups are empty or misaligned, asset names are unknown, or no + compatible world exists. + """ + if len(asset_names) != len(variant_cfgs) or any(not candidates for candidates in variant_cfgs): + raise ValueError("Each asset requires a nonempty group of variant configurations.") + known = set(asset_names if all_asset_names is None else all_asset_names) + combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),) + claimed = set().union(*(combination.assets for combination in combinations)) + offsets = np.cumsum([0, *(len(candidates) for candidates in variant_cfgs)]) + worlds, weights = [], [] + for combination in combinations: + if unknown := set(combination.assets) - known: + raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.") + names, choices, candidates = [], [], [] + for index, name in enumerate(asset_names): + count = combination.assets.count(name) if name in claimed else 1 + names.extend([name] * count) + choices.extend([tuple(range(int(offsets[index]), int(offsets[index + 1])))] * count) + candidates.extend([variant_cfgs[index]] * count) + start = len(worlds) + if not combination.match_tags: + worlds.extend(itertools.product(*choices)) + else: + buckets = [] + common = None + for name, ids, configs in zip(names, choices, candidates, strict=True): + if name not in combination.assets: + buckets.append(None) + continue + groups = {} + for prototype, cfg in zip(ids, configs, strict=True): + tags = cfg.semantic_tags or () + values = [ + tuple(dict.fromkeys(value for tag, value in tags if tag == key)) + for key in combination.match_tags + ] + for key in itertools.product(*values): + groups.setdefault(key, []).append(prototype) + buckets.append(groups) + common = list(groups) if common is None else [key for key in common if key in groups] + for key in [()] if common is None else common: + worlds.append( + tuple( + tuple(group[key]) if group is not None else ids + for group, ids in zip(buckets, choices, strict=True) + ) + ) + # Identical groups can arise when all candidates carry several matching values. + worlds[start:] = dict.fromkeys(worlds[start:]) + count = len(worlds) - start + if not count: + raise ValueError("An inclusion set must define at least one compatible world.") + weights.extend([combination.weight / count] * count) + return tuple(worlds), np.asarray(weights, dtype=np.float64) + + def add(this: CloneCfg, other: InclusionSet) -> CloneCfg: """Append one clone combination to ``this`` and return it. diff --git a/source/isaaclab/isaaclab/cloner/replicate_session.py b/source/isaaclab/isaaclab/cloner/replicate_session.py index 65d65d60249c..974fd30d5e2e 100644 --- a/source/isaaclab/isaaclab/cloner/replicate_session.py +++ b/source/isaaclab/isaaclab/cloner/replicate_session.py @@ -22,7 +22,7 @@ from ..utils.version import has_kit from .clone_plan import ClonePlan, grid_transforms, make_clone_plan from .clone_plan import path as cloner_path -from .cloner_cfg import DEFAULT_ENV_TEMPLATE, CloneCfg, InclusionSet, expand_env_regex_ns +from .cloner_cfg import DEFAULT_ENV_TEMPLATE, CloneCfg, expand_env_regex_ns from .cloner_strategies import sequential from .replicate_context import ReplicateContext from .usd import UsdReplicateContext @@ -37,47 +37,6 @@ def num_spawn_variants(spawn_cfg: Any) -> int: return 1 -def make_valid_clone_combinations( - asset_names: Sequence[str], - variant_counts: Sequence[int], - clone_combinations: Sequence[InclusionSet] | None = None, - *, - all_asset_names: Sequence[str] | None = None, -) -> tuple[tuple[tuple[int, ...], ...], np.ndarray]: - """Expand named combinations into world memberships and relative weights. - - Repeated names create repeated instances. Each combination's weight is divided equally - between its variant combinations; neither padding nor duplicate weighted worlds is needed. - - Args: - asset_names: Names of the replicated asset declarations. - variant_counts: Number of concrete prototypes for each declaration. - clone_combinations: Allowed memberships; unnamed assets are present once in every world. - all_asset_names: Scene names, including shared assets that do not enter world memberships. - - Returns: - World prototypes indexing the flat variant library, and one weight per world prototype. - """ - if len(asset_names) != len(variant_counts) or any(count <= 0 for count in variant_counts): - raise ValueError("Each asset requires one positive variant count.") - known = set(asset_names if all_asset_names is None else all_asset_names) - combinations = clone_combinations or (InclusionSet(assets=list(dict.fromkeys(asset_names))),) - claimed = set().union(*(combination.assets for combination in combinations)) - offsets = np.cumsum([0, *variant_counts]) - worlds, weights = [], [] - for combination in combinations: - if unknown := set(combination.assets) - known: - raise ValueError(f"Unknown assets in clone combination: {sorted(unknown)}.") - choices = [] - for index, name in enumerate(asset_names): - count = combination.assets.count(name) if name in claimed else 1 - choices.extend([range(*offsets[index : index + 2])] * count) - variants = tuple(itertools.product(*choices)) - worlds.extend(variants) - weights.extend([combination.weight / len(variants)] * len(variants)) - return tuple(worlds), np.asarray(weights, dtype=np.float64) - - def replicate(plan: ClonePlan, *, replicate_physics: bool | None = None) -> None: """Execute one topology through its declared clone contexts. @@ -185,7 +144,7 @@ def __init__( env_spacing: float, *, clone_strategy: Callable[[np.ndarray, int], np.ndarray] = sequential, - world_prototypes: Sequence[Sequence[int]] | None = None, + world_prototypes: Sequence[Sequence[int | Sequence[int]]] | None = None, weights: Sequence[float] | None = None, replicate_physics: bool | None = None, env_template: str = DEFAULT_ENV_TEMPLATE, @@ -215,7 +174,7 @@ def _prepare_cloning( env_spacing: float, *, clone_strategy: Callable[[np.ndarray, int], np.ndarray] = sequential, - world_prototypes: Sequence[Sequence[int]] | None = None, + world_prototypes: Sequence[Sequence[int | Sequence[int]]] | None = None, weights: Sequence[float] | None = None, env_template: str = DEFAULT_ENV_TEMPLATE, positions: np.ndarray | None = None, diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index e3581ee63a86..814886ff6cd5 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -183,7 +183,9 @@ def _read_usd_export_base(self): logger.warning(f"USD export is unavailable: reading the engine at startup failed ({error}).") self._usd_export_base = error - def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | None, np.ndarray | None]: + def _collect_asset_cfgs( + self, + ) -> tuple[list[Any], tuple[tuple[int | tuple[int, ...], ...], ...] | None, np.ndarray | None]: """Flatten user-declared cfgs and declare shared prim roots for clone planning. Expands :class:`~isaaclab.assets.RigidObjectCollectionCfg` into its members, @@ -219,9 +221,10 @@ def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | nested_material_names = {name for name, cfg in flat_items if id(cfg) in nested_visual_material_ids} scene_asset_names = [name for name in scene_asset_names if name not in nested_material_names] + combinations = self.cloner_cfg.clone_combinations cfgs: list[Any] = [] clone_asset_names: list[str] = [] - variant_counts: list[int] = [] + variant_cfgs: list[list[sim_utils.SpawnerCfg]] = [] prototype_indices: list[int] = [] prototype_count = 0 for asset_name, child in flat_items: @@ -233,18 +236,36 @@ def _collect_asset_cfgs(self) -> tuple[list[Any], tuple[tuple[int, ...], ...] | count = cloner.num_spawn_variants(getattr(child, "spawn", None)) is_per_env = cloner.path.match(child.prim_path, self._env_fmt) is not None is_spawned = isinstance(child, (AssetBaseCfg, CameraCfg)) and child.spawn is not None - if is_per_env and is_spawned: + if is_per_env and is_spawned and combinations: clone_asset_names.append(asset_name) - variant_counts.append(count) + spawn = child.spawn + if isinstance(spawn, sim_utils.MultiAssetSpawnerCfg): + candidates = [copy.copy(candidate) for candidate in spawn.assets_cfg] + if spawn.semantic_tags: + for candidate in candidates: + candidate.semantic_tags = [*(candidate.semantic_tags or ()), *spawn.semantic_tags] + elif isinstance(spawn, sim_utils.MultiUsdFileCfg) and not isinstance(spawn.usd_path, str): + candidates = [copy.copy(spawn) for _ in spawn.usd_path] + for candidate, usd_path in zip(candidates, spawn.usd_path, strict=True): + candidate.usd_path = usd_path + else: + candidates = [spawn] + variant_cfgs.append(candidates) prototype_indices.extend(range(prototype_count, prototype_count + count)) prototype_count += count - combinations = self.cloner_cfg.clone_combinations if combinations and clone_asset_names: worlds, weights = cloner.make_valid_clone_combinations( - clone_asset_names, variant_counts, combinations, all_asset_names=scene_asset_names + clone_asset_names, variant_cfgs, combinations, all_asset_names=scene_asset_names + ) + worlds = tuple( + tuple( + prototype_indices[slot] if isinstance(slot, int) else tuple(prototype_indices[i] for i in slot) + for slot in world + ) + for world in worlds ) - return cfgs, tuple(tuple(prototype_indices[index] for index in world) for world in worlds), weights + return cfgs, worlds, weights return cfgs, None, None def filter_collisions(self, global_prim_paths: list[str] | None = None): diff --git a/source/isaaclab/test/cloner/test_clone_plan_algebra.py b/source/isaaclab/test/cloner/test_clone_plan_algebra.py index ba2c2a015f91..7b376460d592 100644 --- a/source/isaaclab/test/cloner/test_clone_plan_algebra.py +++ b/source/isaaclab/test/cloner/test_clone_plan_algebra.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Tests for the cloner path/query algebra. +"""Tests for inclusion definitions and the cloner path/query algebra. These exercise :class:`isaaclab.cloner.path` and :class:`isaaclab.cloner.query`, which are pure string/array operations over topology and path templates. They need no stage, no @@ -21,7 +21,7 @@ from isaaclab import cloner from isaaclab.assets import AssetBaseCfg -from isaaclab.cloner import make_clone_plan +from isaaclab.cloner import InclusionSet, make_clone_plan, make_valid_clone_combinations from isaaclab.sim import CuboidCfg ## @@ -105,9 +105,26 @@ def test_clone_ownership_and_import_boundaries(): assert result.returncode == 0, result.stderr assert result.stdout.strip() == "False", "generic clone topology and queries imported the USD backend" + assert not {"variants", "layouts", "num_worlds", "seed"} & InclusionSet.__dataclass_fields__.keys(), ( + "Inclusion rules select semantic configurations rather than positional variant pins" + ) + + assert not hasattr(cloner, "MatchedWorlds"), "InclusionSet owns declarative semantic matching" + assert not hasattr(InclusionSet, "worlds"), "Users configure semantic matching without overriding methods" + source = Path(__file__).resolve().parents[3] for file in source.glob("*/isaaclab*/**/*.py"): tree = ast.parse(file.read_text()) + if file.name == "replicate_session.py": + assert not any( + isinstance(node, (ast.FunctionDef, ast.ClassDef)) + and node.name in {"InclusionSet", "make_valid_clone_combinations"} + or isinstance(node, ast.Attribute) + and node.attr in {"layouts", "worlds"} + or isinstance(node, ast.Name) + and node.id == "InclusionSet" + for node in ast.walk(tree) + ), "Inclusion definitions must resolve legal layouts before ReplicateSession consumes them" # Only cloning execution and its lifecycle owners may access context instances. if "cloner" not in file.parts and file.name not in {"simulation_context.py", "render_context.py"}: assert not any( @@ -218,9 +235,20 @@ def test_world_topology_weights_empty_worlds_and_invalid_membership(): result = cloner.query.get_asset_prototype_world_index(topology, selector) for actual, expected in zip(result, (indices, starts), strict=True): np.testing.assert_array_equal(actual, expected) - for members in ((2,), (-1,), (0.5,), ("0",)): + # Factorized and concrete definitions can share one plan; identical sampled worlds reuse a prototype. + grouped = make_clone_plan(assets, (((0, 1),), (0,)), 4, shared_assets=(1,)) + np.testing.assert_array_equal(grouped.topology.world_prototype_layout, [0, 1, 0, 0]) + np.testing.assert_array_equal(grouped.topology.world_prototype_starts, [0, 1, 2, 3]) + np.testing.assert_array_equal(grouped.topology.world_prototypes, [1, 0, 1]) + for members in ((2,), (-1,), (0.5,), ("0",), ((),), ((0, 2),), (np.array([[0]]),)): with pytest.raises(ValueError, match="integer indices"): make_clone_plan(assets, (members,), 1) + + def invalid_candidates(weights, count): + return np.full(count, 0 if len(weights) == 1 else -1, dtype=np.int32) + + with pytest.raises(ValueError, match="valid candidate index"): + make_clone_plan(assets, (((0, 1),),), 1, clone_strategy=invalid_candidates) for selector in ("/Banana", np.array([0.5]), np.array([[0]])): with pytest.raises(TypeError, match="integer IDs"): cloner.query.get_asset_prototype_world_index(plan.topology, selector) @@ -327,3 +355,104 @@ def test_batched_world_queries(device, worlds, num_worlds, shared, selectors): starts = short[1] if device == "numpy" else short[1].numpy() np.testing.assert_array_equal(values, [-99]) assert starts[-1, -1] == len(expected) + + +def test_inclusion_semantic_groups_remain_factorized_until_scene_selection(): + """One thousand variants in five categories need five groups, not 200**8 worlds per group.""" + variants = [CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("category", str(i % 5))]) for i in range(1000)] + names = [f"object_{index}" for index in range(8)] + rules = [InclusionSet(assets=names, match_tags=["category"])] + groups, weights = make_valid_clone_combinations(names, [variants] * 8, rules) + assert len(groups) == 5 + assert all(len(group) == 8 and all(len(slot) == 200 for slot in group) for group in groups) + np.testing.assert_array_equal(weights, [0.2] * 5) + plan = make_clone_plan(variants * 8, groups, 128, weights=weights) + topology = plan.topology + assert len(topology.world_prototype_layout) == 128 + assert len(topology.world_prototype_starts) <= 130 + categories = [] + for prototype in topology.world_prototype_layout: + start, end = topology.world_prototype_starts[prototype + 1 : prototype + 3] + row = topology.world_prototypes[start:end] + assert len(row) == 8 + assert len(set(row % 1000 % 5)) == 1 + categories.append(row[0] % 5) + np.testing.assert_array_equal(np.bincount(categories), [26, 25, 26, 25, 26]) + + # The existing random strategy and external NumPy seed own both levels of selection. + state = np.random.get_state() + try: + np.random.seed(42) + random_plan = make_clone_plan(variants * 8, groups, 128, weights=weights, clone_strategy=cloner.random) + np.random.seed(42) + repeated = make_clone_plan(variants * 8, groups, 128, weights=weights, clone_strategy=cloner.random) + finally: + np.random.set_state(state) + np.testing.assert_array_equal(random_plan.topology.world_prototypes, repeated.topology.world_prototypes) + np.testing.assert_array_equal(random_plan.topology.world_prototype_layout, repeated.topology.world_prototype_layout) + rows = random_plan.topology.world_prototypes.reshape(-1, 8) + assert (rows % 5 == rows[:, :1] % 5).all() + assert (rows[:, 0] % 1000 != rows[:, 1] % 1000).any() + + +def test_inclusion_multi_value_tags_repeated_instances_and_unclaimed_assets(): + gears = [ + CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", size), ("assembly", "drive")]) + for size in ("small", "medium", "large") + ] + fixtures = [gear.copy() for gear in gears] + fixtures.append( + CuboidCfg( + size=(1.0, 1.0, 1.0), + semantic_tags=[ + ("size", "small"), + ("size", "medium"), + ("size", "large"), + ("assembly", "drive"), + ], + ) + ) + # A size match alone is insufficient when the assembly differs. + fixtures.append(CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", "small"), ("assembly", "other")])) + robot = CuboidCfg(size=(1.0, 1.0, 1.0)) + groups, weights = make_valid_clone_combinations( + ["robot", "gear", "fixture"], + [[robot], gears, fixtures], + [InclusionSet(assets=["gear", "gear", "fixture"], match_tags=["size", "assembly"], weight=3.0)], + ) + assert groups == ( + ((0,), (1,), (1,), (4, 7)), + ((0,), (2,), (2,), (5, 7)), + ((0,), (3,), (3,), (6, 7)), + ) + np.testing.assert_array_equal(weights, [1.0] * 3) + plan = make_clone_plan([robot, *gears, *fixtures], groups, 6, weights=weights) + np.testing.assert_array_equal( + plan.topology.world_prototypes, [0, 1, 1, 4, 0, 1, 1, 7, 0, 2, 2, 5, 0, 2, 2, 7, 0, 3, 3, 6, 0, 3, 3, 7] + ) + # No matching configured retains the existing independent product and weights. + worlds, weights = make_valid_clone_combinations(["gear", "fixture"], [gears[:2], fixtures[:3]]) + assert worlds == ((0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)) + np.testing.assert_array_equal(weights, [1 / 6] * 6) + # A collection's members retain separate columns, despite sharing one scene name. + worlds, _ = make_valid_clone_combinations(["collection", "collection"], [gears[:2], fixtures[:2]]) + assert worlds == ((0, 2), (0, 3), (1, 2), (1, 3)) + + +@pytest.mark.parametrize("invalid", ["missing-tag", "incompatible", "unknown", "empty"]) +def test_inclusion_matching_rejects_invalid_definitions(invalid): + part = CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", "small")]) + tool = CuboidCfg(size=(1.0, 1.0, 1.0), semantic_tags=[("size", "large")]) + inclusion = InclusionSet(assets=["part", "tool"], match_tags=["size"]) + candidates = [[part], [tool]] + message = "at least one compatible world" + if invalid == "missing-tag": + tool.semantic_tags = None + elif invalid == "unknown": + inclusion.assets.append("unknown") + message = "Unknown assets" + elif invalid == "empty": + candidates[0] = [] + message = "nonempty group" + with pytest.raises(ValueError, match=message): + make_valid_clone_combinations(["part", "tool"], candidates, [inclusion]) diff --git a/source/isaaclab_newton/changelog.d/inclusion-world-layouts.skip b/source/isaaclab_newton/changelog.d/inclusion-world-layouts.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/changelog.d/pinned-clone-variants.skip b/source/isaaclab_newton/changelog.d/pinned-clone-variants.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py index dafee5374c5b..c6ba8ee22f23 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object_mesh_variants.py @@ -19,6 +19,7 @@ import isaaclab.sim as sim_utils from isaaclab.assets import RigidObjectCfg +from isaaclab.cloner import InclusionSet from isaaclab.scene import InteractiveScene, InteractiveSceneCfg from isaaclab.sim import build_simulation_context from isaaclab.test.utils import DeviceScope, test_devices @@ -149,6 +150,43 @@ def test_native_selection_preserves_initial_worlds_and_unused_variant(device: st torch.testing.assert_close(asset.mesh_variant_ids.torch.cpu(), torch.tensor([2, 1], dtype=torch.int32)) +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_semantic_worlds_choose_initial_variants(device: str) -> None: + """Semantic rules select the right native variants, including inherited wrapper tags.""" + + scene_cfg = _VariantSceneCfg(num_envs=4, env_spacing=2.0) + third = scene_cfg.object.spawn.assets_cfg[0].copy() + third.radius, third.mass_props.mass = 0.06, 27.0 + scene_cfg.object.spawn.assets_cfg.append(third) + scene_cfg.fixture = _variant_object() + scene_cfg.fixture.prim_path = "{ENV_REGEX_NS}/Fixture" + scene_cfg.fixture.spawn.static = True + scene_cfg.fixture.init_state.pos = (0.5, 0.0, 0.2) + for obj, tags in zip(scene_cfg.object.spawn.assets_cfg, ([("assembly", "spare")], [], [("assembly", "drive")])): + obj.semantic_tags = tags + scene_cfg.fixture.spawn.assets_cfg[0].semantic_tags = [("assembly", "spare")] + scene_cfg.fixture.spawn.assets_cfg[1].semantic_tags = [("assembly", "spare"), ("assembly", "drive")] + scene_cfg.object.spawn.semantic_tags = [("domain", "mechanical")] + scene_cfg.fixture.spawn.semantic_tags = [("domain", "mechanical")] + scene_cfg.clone_cfg.clone_combinations = [ + InclusionSet(assets=["object", "fixture"], match_tags=["assembly", "domain"]), + ] + sim_cfg = SimulationCfg( + device=device, + gravity=(0.0, 0.0, 0.0), + physics=NewtonCfg(solver_cfg=MJWarpSolverCfg(use_mujoco_contacts=False), use_cuda_graph=False), + ) + with build_simulation_context(sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + scene = InteractiveScene(scene_cfg) + sim.register_interactive_scene(scene) + sim.reset() + asset, fixture = scene["object"], scene["fixture"] + torch.testing.assert_close(asset.mesh_variant_ids.torch.cpu(), torch.tensor([0, 0, 2, 2], dtype=torch.int32)) + torch.testing.assert_close(asset.data.body_mass.torch[:, 0].cpu(), torch.tensor([1.0, 1.0, 27.0, 27.0])) + torch.testing.assert_close(fixture.data.body_mass.torch[:, 0].cpu(), torch.tensor([1.0, 8.0, 8.0, 8.0])) + + @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) @pytest.mark.parametrize( "solver_cfg, static",