Datasets:
Download code/robohome/src/engine/source/packages/benchmark/domain_randomization.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 18.1 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/benchmark/domain_randomization.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome@86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/benchmark/domain_randomization.py
-
curl -L -o domain_randomization.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/benchmark/domain_randomization.py
18.1 kB
| from __future__ import annotations | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import yaml # type: ignore[import-untyped] | |
| from packages.core.files import atomic_write_text | |
| PROJECT_ROOT = Path(__file__).resolve().parents[2] | |
| DEFAULT_POLICY = PROJECT_ROOT / "configs/scene_generation/domain_randomization_v1.yaml" | |
| _AXIS = {"x": 0, "y": 1, "z": 2} | |
| class CompiledOverrides: | |
| applied: list[dict[str, Any]] | |
| deferred: list[dict[str, Any]] | |
| class DomainRandomizationCompiler: | |
| """Compile declarative episode factors into a stronger USD override layer.""" | |
| def __init__(self, policy_path: Path | None = None) -> None: | |
| selected = policy_path or Path( | |
| os.environ.get("RHG_DOMAIN_RANDOMIZATION_POLICY", DEFAULT_POLICY) | |
| ) | |
| payload = yaml.safe_load(selected.read_text(encoding="utf-8")) | |
| if payload.get("schema_version") != "1.0" or not isinstance( | |
| payload.get("operations"), dict | |
| ): | |
| raise ValueError(f"invalid domain-randomization policy: {selected}") | |
| self.policy_path = selected | |
| self.operations: dict[str, dict[str, Any]] = payload["operations"] | |
| def validate(self, operations: list[object], entity_ids: set[str]) -> None: | |
| for raw in operations: | |
| if not isinstance(raw, dict): | |
| raise ValueError("scene override operation must be an object") | |
| operation = str(raw.get("operation", "")) | |
| if operation not in self.operations: | |
| raise ValueError(f"domain-randomization policy has no operation {operation!r}") | |
| entity_id = str(raw.get("entity_id", "")) | |
| if entity_id != "robot" and entity_id not in entity_ids: | |
| raise ValueError(f"scene override references unknown entity {entity_id!r}") | |
| policy = self.operations[operation] | |
| missing_fields = [ | |
| field for field in policy.get("required_fields", []) if not raw.get(field) | |
| ] | |
| if missing_fields: | |
| raise ValueError(f"scene override {operation!r} requires fields {missing_fields}") | |
| if policy.get("value_type", "float") == "float": | |
| value = raw.get("value") | |
| if isinstance(value, bool) or not isinstance(value, (int, float)): | |
| raise ValueError(f"scene override {operation!r} requires a numeric value") | |
| def compile( | |
| self, | |
| *, | |
| episode_root: Path, | |
| override_layer: Path, | |
| operations: list[object], | |
| entity_prim_paths: dict[str, str], | |
| robot_prim_path: str, | |
| ) -> CompiledOverrides: | |
| normalized = [ | |
| self._normalize(item, entity_prim_paths, robot_prim_path) for item in operations | |
| ] | |
| if not override_layer.is_file(): | |
| atomic_write_text(override_layer, _empty_layer()) | |
| if not normalized: | |
| return CompiledOverrides(applied=[], deferred=[]) | |
| try: | |
| result = self._compile_with_pxr(episode_root, override_layer, normalized) | |
| except ImportError: | |
| worker_python = os.environ.get("RHG_USD_PYTHON") or os.environ.get("SCENESMITH_PYTHON") | |
| if worker_python and Path(worker_python).resolve() != Path(sys.executable).resolve(): | |
| result = self._compile_external( | |
| Path(worker_python), episode_root, override_layer, normalized | |
| ) | |
| else: | |
| result = self._compile_portable_fallback(override_layer, normalized) | |
| return result | |
| def _compile_external( | |
| self, | |
| python: Path, | |
| episode_root: Path, | |
| override_layer: Path, | |
| operations: list[dict[str, Any]], | |
| ) -> CompiledOverrides: | |
| with tempfile.TemporaryDirectory(prefix="rhg-usd-worker-") as temporary: | |
| payload = Path(temporary) / "request.json" | |
| result_path = Path(temporary) / "result.json" | |
| payload.write_text( | |
| json.dumps( | |
| { | |
| "episode_root": str(episode_root.resolve()), | |
| "override_layer": str(override_layer.resolve()), | |
| "operations": operations, | |
| "result": str(result_path), | |
| } | |
| ), | |
| encoding="utf-8", | |
| ) | |
| environment = os.environ.copy() | |
| existing_python_path = environment.get("PYTHONPATH", "") | |
| environment["PYTHONPATH"] = str(PROJECT_ROOT) + ( | |
| os.pathsep + existing_python_path if existing_python_path else "" | |
| ) | |
| completed = subprocess.run( | |
| [ | |
| str(python), | |
| "-m", | |
| "packages.benchmark.domain_randomization", | |
| payload.as_posix(), | |
| ], | |
| cwd=PROJECT_ROOT, | |
| env=environment, | |
| capture_output=True, | |
| text=True, | |
| timeout=120, | |
| check=False, | |
| ) | |
| if completed.returncode != 0 or not result_path.is_file(): | |
| detail = (completed.stderr or completed.stdout).strip() | |
| raise RuntimeError(f"USD domain-randomization worker failed: {detail}") | |
| result = json.loads(result_path.read_text(encoding="utf-8")) | |
| return CompiledOverrides( | |
| applied=list(result["applied"]), deferred=list(result["deferred"]) | |
| ) | |
| def _normalize( | |
| self, | |
| raw: object, | |
| entity_prim_paths: dict[str, str], | |
| robot_prim_path: str, | |
| ) -> dict[str, Any]: | |
| if not isinstance(raw, dict): | |
| raise ValueError("scene override operation must be an object") | |
| operation = str(raw.get("operation", "")) | |
| if operation not in self.operations: | |
| raise ValueError(f"domain-randomization policy has no operation {operation!r}") | |
| entity_id = str(raw.get("entity_id", "")) | |
| if entity_id == "robot": | |
| prim_path = robot_prim_path | |
| else: | |
| try: | |
| prim_path = entity_prim_paths[entity_id] | |
| except KeyError as error: | |
| raise ValueError( | |
| f"scene override references unknown entity {entity_id!r}" | |
| ) from error | |
| return { | |
| **raw, | |
| "entity_id": entity_id, | |
| "prim_path": prim_path, | |
| "policy": self.operations[operation], | |
| } | |
| def _compile_with_pxr( | |
| self, episode_root: Path, override_layer: Path, operations: list[dict[str, Any]] | |
| ) -> CompiledOverrides: | |
| from pxr import Gf, Sdf, Usd, UsdGeom # type: ignore[import-not-found] | |
| stage = Usd.Stage.Open(str(episode_root)) | |
| if stage is None: | |
| raise ValueError(f"cannot open episode stage: {episode_root}") | |
| layer = Sdf.Layer.FindOrOpen(str(override_layer)) or Sdf.Layer.CreateNew( | |
| str(override_layer) | |
| ) | |
| stage.SetEditTarget(layer) | |
| applied: list[dict[str, Any]] = [] | |
| deferred: list[dict[str, Any]] = [] | |
| for item in operations: | |
| policy = item["policy"] | |
| primitive = str(policy["primitive"]) | |
| prim = stage.GetPrimAtPath(item["prim_path"]) | |
| if not prim.IsValid(): | |
| deferred.append(_public(item, "target_prim_missing")) | |
| continue | |
| targets = [prim] | |
| if primitive.startswith("descendant_"): | |
| selector = policy.get("selector", {}) | |
| pattern = re.compile(str(selector.get("name_pattern", ".*"))) | |
| type_names = set(selector.get("type_names", [])) | |
| targets = [ | |
| candidate | |
| for candidate in Usd.PrimRange(prim) | |
| if pattern.fullmatch(candidate.GetName()) | |
| and (not type_names or candidate.GetTypeName() in type_names) | |
| ] | |
| primitive = primitive.removeprefix("descendant_") | |
| if not targets: | |
| deferred.append(_public(item, "selector_matched_no_prims")) | |
| continue | |
| for target in targets: | |
| value = item.get("value") | |
| if primitive == "translate": | |
| xform = UsdGeom.Xformable(target) | |
| axis = _AXIS[str(policy["axis"])] | |
| vector = [0.0, 0.0, 0.0] | |
| vector[axis] = float(value) | |
| if policy.get("mode") == "absolute": | |
| existing = _local_translation(xform, Gf) | |
| vector[axis] = float(value) - existing[axis] | |
| suffix = "rhg_absolute" | |
| else: | |
| suffix = f"rhg_{item['operation']}" | |
| xform.AddTranslateOp(opSuffix=suffix).Set(Gf.Vec3d(*vector)) | |
| elif primitive == "rotate": | |
| if policy.get("axis") != "z" or policy.get("unit") != "degrees": | |
| raise ValueError("rotate currently requires axis=z and unit=degrees") | |
| UsdGeom.Xformable(target).AddRotateZOp(opSuffix=f"rhg_{item['operation']}").Set( | |
| float(value) | |
| ) | |
| elif primitive == "uniform_scale": | |
| scale = float(value) | |
| UsdGeom.Xformable(target).AddScaleOp(opSuffix=f"rhg_{item['operation']}").Set( | |
| Gf.Vec3f(scale, scale, scale) | |
| ) | |
| elif primitive == "scale_to_extent": | |
| axis = _AXIS[str(policy["axis"])] | |
| bounds = UsdGeom.BBoxCache( | |
| Usd.TimeCode.Default(), [UsdGeom.Tokens.default_] | |
| ).ComputeLocalBound(target) | |
| extent = list(bounds.GetRange().GetSize()) | |
| scale = [1.0, 1.0, 1.0] | |
| if extent[axis] <= 0: | |
| deferred.append(_public(item, "target_extent_is_zero")) | |
| continue | |
| scale[axis] = float(value) / float(extent[axis]) | |
| UsdGeom.Xformable(target).AddScaleOp(opSuffix=f"rhg_{item['operation']}").Set( | |
| Gf.Vec3f(*scale) | |
| ) | |
| elif primitive in {"property_set", "property_scale", "metadata"}: | |
| attribute = target.GetAttribute(str(policy["property"])) | |
| if not attribute: | |
| attribute = target.CreateAttribute( | |
| str(policy["property"]), | |
| _sdf_type(policy.get("value_type", "float"), Sdf), | |
| custom=True, | |
| ) | |
| output = value | |
| if primitive == "property_scale": | |
| current = attribute.Get() | |
| if not isinstance(current, (int, float)): | |
| current = policy.get("default_base") | |
| if not isinstance(current, (int, float)): | |
| deferred.append(_public(item, "property_has_no_numeric_base_value")) | |
| continue | |
| output = float(current) * float(value) | |
| attribute.Set(_typed_value(output, policy.get("value_type", "float"))) | |
| elif primitive == "reference_set": | |
| references = target.GetReferences() | |
| references.ClearReferences() | |
| if not references.AddReference(str(value)): | |
| deferred.append(_public(item, "asset_reference_rejected")) | |
| continue | |
| elif primitive == "variant_select": | |
| field = str(policy.get("variant_set_field", "variant_set")) | |
| set_name = str(item.get(field, "")) | |
| variant_set = target.GetVariantSets().GetVariantSet(set_name) | |
| if not set_name or not variant_set.IsValid(): | |
| deferred.append(_public(item, "variant_set_missing")) | |
| continue | |
| if not variant_set.SetVariantSelection(str(value)): | |
| deferred.append(_public(item, "variant_selection_rejected")) | |
| continue | |
| else: | |
| raise ValueError(f"unsupported domain-randomization primitive {primitive!r}") | |
| applied.append( | |
| {**_public(item, "applied"), "target_prim_path": str(target.GetPath())} | |
| ) | |
| layer.Save() | |
| return CompiledOverrides(applied=applied, deferred=deferred) | |
| def _compile_portable_fallback( | |
| self, override_layer: Path, operations: list[dict[str, Any]] | |
| ) -> CompiledOverrides: | |
| # The fallback authors concrete translation/property values for deterministic stages. | |
| # Operations requiring composed bounds or base property values remain explicit runtime work. | |
| entries: dict[str, dict[str, list[str]]] = {} | |
| applied: list[dict[str, Any]] = [] | |
| deferred: list[dict[str, Any]] = [] | |
| for item in operations: | |
| policy = item["policy"] | |
| primitive = str(policy["primitive"]) | |
| entry = entries.setdefault( | |
| str(item["prim_path"]), {"properties": [], "xform_order": []} | |
| ) | |
| if primitive == "translate": | |
| vector = [0.0, 0.0, 0.0] | |
| vector[_AXIS[str(policy["axis"])]] = float(item["value"]) | |
| operation_name = f"xformOp:translate:rhg_{item['operation']}" | |
| entry["properties"].append( | |
| f"double3 {operation_name} = ({vector[0]}, {vector[1]}, {vector[2]})" | |
| ) | |
| entry["xform_order"].append(operation_name) | |
| elif primitive == "rotate": | |
| operation_name = f"xformOp:rotateZ:rhg_{item['operation']}" | |
| entry["properties"].append(f"float {operation_name} = {float(item['value'])}") | |
| entry["xform_order"].append(operation_name) | |
| elif primitive == "uniform_scale": | |
| operation_name = f"xformOp:scale:rhg_{item['operation']}" | |
| scale = float(item["value"]) | |
| entry["properties"].append(f"float3 {operation_name} = ({scale}, {scale}, {scale})") | |
| entry["xform_order"].append(operation_name) | |
| elif primitive in {"property_set", "metadata"}: | |
| value_type = str(policy.get("value_type", "float")) | |
| value = _usda_value(item["value"], value_type) | |
| entry["properties"].append(f"custom {value_type} {policy['property']} = {value}") | |
| else: | |
| deferred.append(_public(item, "requires_pxr_composed_stage")) | |
| continue | |
| applied.append(_public(item, "applied_fallback")) | |
| atomic_write_text(override_layer, _layer_with_entries(entries)) | |
| return CompiledOverrides(applied=applied, deferred=deferred) | |
| def _local_translation(xform: Any, gf: Any) -> list[float]: | |
| result = xform.GetLocalTransformation() | |
| matrix = result[0] if isinstance(result, tuple) else result | |
| value = matrix.ExtractTranslation() if matrix is not None else gf.Vec3d(0.0) | |
| return [float(value[0]), float(value[1]), float(value[2])] | |
| def _sdf_type(name: str, sdf: Any) -> Any: | |
| return {"float": sdf.ValueTypeNames.Float, "string": sdf.ValueTypeNames.String}.get( | |
| name, sdf.ValueTypeNames.String | |
| ) | |
| def _typed_value(value: Any, value_type: str) -> Any: | |
| return float(value) if value_type == "float" else str(value) | |
| def _public(item: dict[str, Any], status: str) -> dict[str, Any]: | |
| return {key: value for key, value in item.items() if key != "policy"} | {"status": status} | |
| def _empty_layer() -> str: | |
| return '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' | |
| def _layer_with_entries(entries: dict[str, dict[str, list[str]]]) -> str: | |
| tree: dict[str, Any] = {"properties": [], "children": {}} | |
| for path, entry in entries.items(): | |
| node = tree | |
| for part in (part for part in path.split("/") if part): | |
| node = node["children"].setdefault(part, {"properties": [], "children": {}}) | |
| node["properties"].extend(entry["properties"]) | |
| if entry["xform_order"]: | |
| order = ", ".join(json.dumps(name) for name in entry["xform_order"]) | |
| node["properties"].append(f"uniform token[] xformOpOrder = [{order}]") | |
| def render(node: dict[str, Any], depth: int) -> list[str]: | |
| lines = [] | |
| indent = " " * depth | |
| lines.extend(f"{indent}{value}" for value in node["properties"]) | |
| for name, child in node["children"].items(): | |
| lines.append(f'{indent}over "{name}" {{') | |
| lines.extend(render(child, depth + 1)) | |
| lines.append(f"{indent}}}") | |
| return lines | |
| bodies = render(tree, 0) | |
| return _empty_layer() + "\n".join(bodies) + ("\n" if bodies else "") | |
| def _usda_value(value: Any, value_type: str) -> str: | |
| return json.dumps(str(value)) if value_type == "string" else str(float(value)) | |
| def _worker(payload_path: Path) -> None: | |
| payload = json.loads(payload_path.read_text(encoding="utf-8")) | |
| compiler = DomainRandomizationCompiler() | |
| result = compiler._compile_with_pxr( # noqa: SLF001 | |
| Path(payload["episode_root"]), | |
| Path(payload["override_layer"]), | |
| list(payload["operations"]), | |
| ) | |
| Path(payload["result"]).write_text( | |
| json.dumps({"applied": result.applied, "deferred": result.deferred}), | |
| encoding="utf-8", | |
| ) | |
| if __name__ == "__main__": | |
| if len(sys.argv) != 2: | |
| raise SystemExit("usage: python -m packages.benchmark.domain_randomization REQUEST.json") | |
| _worker(Path(sys.argv[1])) | |