diff --git a/.gitattributes b/.gitattributes index 021777f7c41d466e746a98edfd3b33e84e9818b8..fb9ca22f115a2d0f419ed563636feb04c243576c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -205,3 +205,5 @@ source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-Semibold-webf source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-Semibold-webfont.ttf filter=lfs diff=lfs merge=lfs -text source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-SemiboldItalic-webfont.ttf filter=lfs diff=lfs merge=lfs -text source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/fontawesome-webfont.ttf filter=lfs diff=lfs merge=lfs -text +source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7za.exe filter=lfs diff=lfs merge=lfs -text +source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7zzs filter=lfs diff=lfs merge=lfs -text diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/max_collision.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/max_collision.py new file mode 100644 index 0000000000000000000000000000000000000000..627f9849c26fcb9fdb1e1cf89e6ef221e51cabba --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/max_collision.py @@ -0,0 +1,49 @@ +import torch as th + +from omnigibson.utils.usd_utils import RigidContactAPI +from omnigibson.termination_conditions.termination_condition_base import FailureCondition + + +class MaxCollision(FailureCondition): + """ + MaxCollision (failure condition) used for navigation tasks + Episode terminates if the robot has collided more than max_collisions_allowed times + Note that we ignore collisions with any floor objects. + + Args: + robot_idn (int): robot identifier to evaluate collision checking with. Default is 0, corresponding to the first + robot added to the scene + ignore_self_collisions (bool): Whether to ignore robot self-collisions or not + max_collisions (int): Maximum number of collisions allowed for any robots in the scene before a termination + is triggered + """ + + def __init__(self, robot_idn=0, ignore_self_collisions=True, max_collisions=500): + self._robot_idn = robot_idn + self._ignore_self_collisions = ignore_self_collisions + self._max_collisions = max_collisions + self._n_collisions = None + + # Run super init + super().__init__() + + def reset(self, task, env, env_indices): + # Call super first + super().reset(task, env, env_indices) + + # Also reset collision counter + if self._n_collisions is None: + self._n_collisions = th.zeros(env.num_envs, dtype=th.int64) + self._n_collisions[env_indices] = 0 + + def _step(self, task, env, action): + # Terminate if the robot has collided more than self._max_collisions times + for env_idx in range(env.num_envs): + robot = env.scenes[env_idx].robots[self._robot_idn] + floors = list(env.scenes[env_idx].object_registry("category", "floors", [])) + ignore_objs = floors + [robot] if self._ignore_self_collisions else floors + in_contact = RigidContactAPI.is_in_contact( + scene_idx=robot.scene.idx, query_set=[robot], with_set=None, ignore_set=ignore_objs, current_only=False + ) + self._n_collisions[env_idx] += int(in_contact) + return self._n_collisions > self._max_collisions diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/point_goal.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/point_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..47bd4ccc46dcb03322d9b62c8af0b39bb77a33c6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/point_goal.py @@ -0,0 +1,43 @@ +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.termination_conditions.termination_condition_base import SuccessCondition + + +class PointGoal(SuccessCondition): + """ + PointGoal (success condition) used for PointNavFixed/RandomTask + Episode terminates if point goal is reached within @distance_tol by the @robot_idn robot's base + + Args: + robot_idn (int): robot identifier to evaluate point goal with. Default is 0, corresponding to the first + robot added to the scene + distance_tol (float): Distance (m) tolerance between goal position and @robot_idn's robot base position + that is accepted as a success + distance_axes (str): Which axes to calculate distances when calculating the goal. Any combination of "x", + "y", and "z" is valid (e.g.: "xy" or "xyz" or "y") + """ + + def __init__(self, robot_idn=0, distance_tol=0.5, distance_axes="xyz"): + self._robot_idn = robot_idn + self._distance_tol = distance_tol + self._distance_axes = [i for i, axis in enumerate("xyz") if axis in distance_axes] + + # Run super init + super().__init__() + + def _step(self, task, env, action): + # Make sure task is of type PointNavigation -- we import at runtime to avoid circular imports + from omnigibson.tasks.point_navigation_task import PointNavigationTask + + assert isinstance( + task, PointNavigationTask + ), f"Cannot use {self.__class__.__name__} with a non-PointNavigationTask task instance!" + # Terminate if point goal is reached (distance below threshold) + results = th.zeros(env.num_envs, dtype=th.bool) + for env_idx in range(env.num_envs): + current = task.get_current_pos(env, env_idx) + goal = task.get_goal_pos(env_idx) + dist = T.l2_distance(current[self._distance_axes], goal[self._distance_axes]) + results[env_idx] = dist < self._distance_tol + return results diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/predicate_goal.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/predicate_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..b321e1f5a2c78cffbaba16a92a1971b72e6ec84b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/predicate_goal.py @@ -0,0 +1,53 @@ +import torch as th + + +from omnigibson.termination_conditions.termination_condition_base import SuccessCondition + + +class PredicateGoal(SuccessCondition): + """ + PredicateGoal (success condition) used for BehaviorTask + Episode terminates if all the predicates are satisfied + + Args: + check_goal_fn (method): function that checks goal satisfaction. Function signature should be: + + (all_satisfied, results) = check_goal_fn() + + where @all_satisfied is a bool and @results maps "satisfied"/"unsatisfied" to lists of indices. + """ + + def __init__(self, check_goal_fn): + # Store internal vars + self._check_goal_fn = check_goal_fn + self._goal_status = None + + # Run super + super().__init__() + + def reset(self, task, env, env_indices): + # Run super first + super().reset(task, env, env_indices) + + # Reset status + if self._goal_status is None: + self._goal_status = [{"satisfied": [], "unsatisfied": []} for _ in range(env.num_envs)] + for idx in env_indices: + self._goal_status[idx] = {"satisfied": [], "unsatisfied": []} + + def _step(self, task, env, action): + # Terminate if all goal conditions are met in the task + results = th.zeros(env.num_envs, dtype=th.bool) + for env_idx in range(env.num_envs): + done, self._goal_status[env_idx] = self._check_goal_fn(env_idx) + results[env_idx] = done + return results + + @property + def goal_status(self): + """ + Returns: + list[dict]: Current goal status for the active predicate(s), mapping "satisfied" and "unsatisfied" to a list + of the predicates matching either of those conditions for each env + """ + return self._goal_status diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/reaching_goal.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/reaching_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd132fbb9cf60fef0152a7ac118d71fdb8809ea --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/reaching_goal.py @@ -0,0 +1,34 @@ +import torch as th + +import omnigibson.utils.transform_utils as T +from omnigibson.termination_conditions.termination_condition_base import SuccessCondition + + +class ReachingGoal(SuccessCondition): + """ + ReachingGoal (success condition) used for reaching-type tasks + Episode terminates if reaching goal is reached within @distance_tol by the @robot_idn robot's end effector + + Args: + robot_idn (int): robot identifier to evaluate point goal with. Default is 0, corresponding to the first + robot added to the scene + distance_tol (float): Distance (m) tolerance between goal position and @robot_idn's robot eef position + that is accepted as a success + """ + + def __init__(self, robot_idn=0, distance_tol=0.5): + self._robot_idn = robot_idn + self._distance_tol = distance_tol + + # Run super init + super().__init__() + + def _step(self, task, env, action): + # Terminate if point goal is reached (distance below threshold) + results = th.zeros(env.num_envs, dtype=th.bool) + for env_idx in range(env.num_envs): + robot = env.scenes[env_idx].robots[self._robot_idn] + eef_pos = robot.get_eef_position() + dist = T.l2_distance(eef_pos, task.get_goal_pos(env_idx)) + results[env_idx] = dist < self._distance_tol + return results diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/termination_condition_base.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/termination_condition_base.py new file mode 100644 index 0000000000000000000000000000000000000000..41ef2a3e008955ca642fd3f59fb5bde6a54e1429 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/termination_condition_base.py @@ -0,0 +1,167 @@ +from abc import ABCMeta, abstractmethod + +import torch as th + +from omnigibson.utils.python_utils import Registerable, classproperty + +REGISTERED_TERMINATION_CONDITIONS = dict() +REGISTERED_SUCCESS_CONDITIONS = dict() +REGISTERED_FAILURE_CONDITIONS = dict() + + +def register_success_condition(cls): + if cls.__name__ not in REGISTERED_SUCCESS_CONDITIONS: + REGISTERED_SUCCESS_CONDITIONS[cls.__name__] = cls + + +def register_failure_condition(cls): + if cls.__name__ not in REGISTERED_FAILURE_CONDITIONS: + REGISTERED_FAILURE_CONDITIONS[cls.__name__] = cls + + +class BaseTerminationCondition(Registerable, metaclass=ABCMeta): + """ + Base TerminationCondition class + Condition-specific _step() method is implemented in subclasses + """ + + def __init__(self): + # Initialize internal vars that will be filled in at runtime + self._num_envs = None + self._done = None + + @abstractmethod + def _step(self, task, env, action): + """ + Step the termination condition and return whether the episode should terminate. Overwritten by subclasses. + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + + Returns: + th.Tensor: (num_envs,) bool tensor indicating whether each env should terminate + """ + raise NotImplementedError() + + def step(self, task, env, action): + """ + Step the termination condition and return whether the episode should terminate. + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + action (n-array): 1D flattened array of actions executed by all agents in the environment + + Returns: + 2-tuple: + - th.Tensor: (num_envs,) bool tensor indicating whether each env should terminate or not + - th.Tensor: (num_envs,) bool tensor indicating whether a success was reached under this termination condition + """ + # Step internally and store the done state internally as well + self._done = self._step(task=task, env=env, action=action) + + # We are successful if done is True AND this is a success condition + success = self._done & self._terminate_is_success + + return self._done, success + + def reset(self, task, env, env_indices): + """ + Termination condition-specific reset + + Args: + task (BaseTask): Task instance + env (Environment): Environment instance + env_indices (th.Tensor): Indices of environments to reset + """ + if self._num_envs is None: + self._num_envs = env.num_envs + self._done = th.zeros(self._num_envs, dtype=th.bool) + self._done[env_indices] = False + + @property + def done(self): + """ + Returns: + th.Tensor: (num_envs,) bool tensor indicating whether this termination condition has triggered + """ + assert self._done is not None, "At least one step() must occur before done can be calculated!" + return self._done + + @property + def success(self): + """ + Returns: + th.Tensor: (num_envs,) bool tensor indicating whether this termination condition is a success + """ + assert self._done is not None, "At least one step() must occur before success can be calculated!" + return self._done & self._terminate_is_success + + @classproperty + def _terminate_is_success(cls): + """ + Returns: + bool: Whether this termination condition corresponds to a success + """ + raise NotImplementedError() + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseTerminationCondition") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_TERMINATION_CONDITIONS + return REGISTERED_TERMINATION_CONDITIONS + + +class SuccessCondition(BaseTerminationCondition): + """ + Termination condition corresponding to a success + """ + + def __init_subclass__(cls, **kwargs): + # Register as part of locomotion controllers + super().__init_subclass__(**kwargs) + register_success_condition(cls) + + @classproperty + def _terminate_is_success(cls): + # Done --> success + return True + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("SuccessCondition") + return classes + + +class FailureCondition(BaseTerminationCondition): + """ + Termination condition corresponding to a failure + """ + + def __init_subclass__(cls, **kwargs): + # Register as part of locomotion controllers + super().__init_subclass__(**kwargs) + register_failure_condition(cls) + + @classproperty + def _terminate_is_success(cls): + # Done --> not success + return False + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("FailureCondition") + return classes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/timeout.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..a01f2839f2a427e33b189efbe45c6080506a646c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/timeout.py @@ -0,0 +1,23 @@ +from omnigibson.termination_conditions.termination_condition_base import FailureCondition + + +class Timeout(FailureCondition): + """ + Timeout (failure condition) + Episode terminates if max_step steps have passed + + Args: + max_steps (int): Maximum number of episode steps before timeout occurs + """ + + def __init__(self, max_steps=500): + # Store internal vars + self._max_steps = max_steps + + # Run super + super().__init__() + + def _step(self, task, env, action): + # Terminate if number of steps passed exceeds threshold + # env.episode_steps is (num_envs,) tensor + return env.episode_steps >= self._max_steps diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/transition_rules.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/transition_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f218b4cc9cf32478dfe01b2342ea09c5e0d0dc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/transition_rules.py @@ -0,0 +1,2613 @@ +import math +import operator +import random +from abc import ABCMeta, abstractmethod +from collections import defaultdict, namedtuple +from copy import copy + +import networkx as nx +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.object_states import ( + ContactParticles, + ContainedParticles, + Contains, + Cooked, + Covered, + Filled, + Heated, + HeatSourceOrSink, + MaxTemperature, + OnTop, + Open, + Saturated, + SlicerActive, + ToggledOn, +) +from omnigibson.objects.dataset_object import DatasetObject +from omnigibson.utils.asset_utils import get_all_object_category_models +from bddl.knowledge_base import CookingRecipe, MachineRecipe, MixingRecipe, SubstanceCookingRecipe +from omnigibson.utils.bddl_utils import ( + get_knowledge_base, + translate_bddl_recipe_to_og_recipe, + translate_bddl_washer_rule_to_og_washer_rule, +) +from omnigibson.utils.python_utils import Registerable, classproperty, torch_delete +from omnigibson.utils.registry_utils import Registry +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.usd_utils import RigidContactAPI +from omnigibson.systems.system_base import VisualParticleSystem +from omnigibson.systems.macro_particle_system import MacroPhysicalParticleSystem + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Default melting temperature +m.MELTING_TEMPERATURE = 100.0 + +# Default "trash" system if an invalid mixing rule transition occurs +m.DEFAULT_GARBAGE_SYSTEM = "sludge" + +# Tuple of attributes of objects created in transitions. +# `states` field is dict mapping object state class to arguments to pass to setter for that class +_attrs_fields = ["category", "model", "name", "scale", "obj", "pos", "orn", "bb_pos", "bb_orn", "states", "callback"] +# States: dict: mapping state nameargs to pass to the state setter for @obj in order to set the object state +# callback: function: signature callback(obj) -> None to execute after states are set, if any +ObjectAttrs = namedtuple("ObjectAttrs", _attrs_fields, defaults=(None,) * len(_attrs_fields)) + +# Tuple of lists of objects to be added or removed returned from transitions, if not None +TransitionResults = namedtuple("TransitionResults", ["add", "remove"], defaults=(None, None)) + +# Global dicts that will contain mappings +REGISTERED_RULES = dict() + + +class TransitionRuleAPI: + """ + Containing methods to check and execute arbitrary discrete state transitions within the simulator + """ + + def __init__(self, scene): + # Recipes and washer conditions come from the knowledge base; load once on first API use (not at import time). + import_recipes() + + self.scene = scene + + # Set of active rules + self.active_rules = set() + + # Maps USDObject instances to dictionary with the following keys: + # "states": None or dict mapping object states to arguments to set for that state when the object is initialized + # "callback": None or function to execute when the object is initialized + self.obj_init_info = dict() + + self.all_rules = set([rule(scene) for rule in RULES_REGISTRY.objects]) + + def get_rule_candidates(self, rule, objects): + """ + Computes valid input object candidates for transition rule @rule, if any exist + + Args: + rule (BaseTransitionRule): Transition rule whose candidates should be computed + objects (list of USDObject): List of objects that will be used to compute object candidates + + Returns: + None or dict: None if no valid candidates are found, otherwise mapping from filter key to list of object + instances that satisfy that filter + """ + obj_candidates = rule.get_object_candidates(objects=objects) + n_filters_satisfied = sum(len(candidates) > 0 for candidates in obj_candidates.values()) + # Return object candidates if all filters are met, otherwise return None + return obj_candidates if n_filters_satisfied == len(rule.candidate_filters) else None + + def prune_active_rules(self): + """ + Prunes the active transition rules, removing any whose filter requirements are not satisfied by all current + objects on the scene. Useful when the current object set changes, e.g.: an object is removed from the simulator + """ + # Need explicit tuple to iterate over because refresh_rules mutates the ACTIVE_RULES set in place + self.refresh_rules(rules=tuple(self.active_rules)) + + def refresh_all_rules(self): + """ + Refreshes all registered rules given the current set of objects in the scene + """ + # Clear all active rules + self.active_rules = set() + + # Refresh all registered rules + self.refresh_rules(rules=self.all_rules) + + def refresh_rules(self, rules): + """ + Refreshes the specified transition rules @rules based on current set of objects in the simulator. + This will prune any pre-existing rules in self.active_rules if no valid candidates are found, or add / update + the entry if valid candidates are found + + Args: + rules (list of BaseTransitionRule): List of transition rules whose candidate lists should be refreshed + """ + for rule in rules: + # Skip if rule is not enabled + if not rule.ENABLED: + continue + + # Check if rule is still valid, if so, update its entry + object_candidates = self.get_rule_candidates(rule=rule, objects=self.scene.objects) + + # Update candidates if valid, otherwise pop the entry if it exists in self.active_rules + if object_candidates is not None: + # We have a valid rule which should be active, so grab and initialize all of its conditions + # NOTE: The rule may ALREADY exist in ACTIVE_RULES, but we still need to refresh its candidates because + # the relevant candidate set / information for the rule + its conditions may have changed given the + # new set of objects + rule.refresh(object_candidates=object_candidates) + self.active_rules.add(rule) + elif rule in self.active_rules: + self.active_rules.remove(rule) + + def step(self): + """ + Steps all active transition rules, checking if any are satisfied, and if so, executing their transition + """ + # First apply any transition object init states from before, and then clear the dictionary + for obj, info in self.obj_init_info.items(): + if info["states"] is not None: + for state, args in info["states"].items(): + obj.states[state].set_value(*args) + if info["callback"] is not None: + info["callback"](obj) + self.obj_init_info = dict() + + # Iterate over all active rules and process the rule for every valid object candidate combination + # Cast to list before iterating since ACTIVE_RULES may get updated mid-iteration + added_obj_attrs = [] + removed_objs = [] + for rule in tuple(self.active_rules): + output = rule.step() + # Store objects to be added / removed if we have a valid output + if output is not None: + added_obj_attrs += output.add + removed_objs += output.remove + + self.execute_transition(added_obj_attrs=added_obj_attrs, removed_objs=removed_objs) + + def execute_transition(self, added_obj_attrs, removed_objs): + """ + Executes the transition for the given added and removed objects. + + :param added_obj_attrs: List of ObjectAttrs instances to add to the scene + :param removed_objs: List of USDObject instances to remove from the scene + """ + # Process all transition results + if len(removed_objs) > 0: + # First remove pre-existing objects + og.sim.batch_remove_objects(removed_objs) + + # Then add new objects + if len(added_obj_attrs) > 0: + for added_obj_attr in added_obj_attrs: + new_obj = added_obj_attr.obj + self.scene.add_object(new_obj) + # By default, added_obj_attr is populated with all Nones -- so these will all be pass-through operations + # unless pos / orn (or, conversely, bb_pos / bb_orn) is specified + if added_obj_attr.pos is not None or added_obj_attr.orn is not None: + new_obj.set_position_orientation(position=added_obj_attr.pos, orientation=added_obj_attr.orn) + elif isinstance(new_obj, DatasetObject) and ( + added_obj_attr.bb_pos is not None or added_obj_attr.bb_orn is not None + ): + new_obj.set_bbox_center_position_orientation( + position=added_obj_attr.bb_pos, orientation=added_obj_attr.bb_orn + ) + else: + raise ValueError( + "Expected at least one of pos, orn, bb_pos, or bb_orn to be specified in ObjectAttrs!" + ) + # Additionally record any requested states if specified to be updated during the next transition step + if added_obj_attr.states is not None or added_obj_attr.callback is not None: + self.obj_init_info[new_obj] = { + "states": added_obj_attr.states, + "callback": added_obj_attr.callback, + } + + def clear(self): + """ + Clears any internal state when the simulator is restarted (e.g.: when a new stage is opened) + """ + # Clear internal dictionaries + self.active_rules = set() + self.obj_init_info = dict() + + +class ObjectCandidateFilter(metaclass=ABCMeta): + """ + Defines a filter to apply for inferring which objects are valid candidates for checking a transition rule's + condition requirements. + + NOTE: These filters should describe STATIC properties about an object -- i.e.: properties that should NOT change + at runtime, once imported + """ + + @abstractmethod + def __call__(self, obj): + """Returns true if the given object passes the filter.""" + return False + + +class ObjectPropertyFilter(ObjectCandidateFilter): + """Filter for arbitrary object properties""" + + def __init__(self, name, value): + self.property = name + self.value = value + + def __call__(self, obj): + return getattr(obj, self.property) == self.value + + +class CategoryFilter(ObjectCandidateFilter): + """Filter for object categories.""" + + def __init__(self, category): + self.category = category + + def __call__(self, obj): + return obj.category == self.category + + +class AbilityFilter(ObjectCandidateFilter): + """Filter for object abilities.""" + + def __init__(self, ability): + self.ability = ability + + def __call__(self, obj): + return self.ability in obj._abilities + + +class NameFilter(ObjectCandidateFilter): + """Filter for object names.""" + + def __init__(self, name): + self.name = name + + def __call__(self, obj): + return self.name in obj.name + + +class NotFilter(ObjectCandidateFilter): + """Logical-not of a filter""" + + def __init__(self, f): + self.f = f + + def __call__(self, obj): + return not self.f(obj) + + +class OrFilter(ObjectCandidateFilter): + """Logical-or of a set of filters.""" + + def __init__(self, filters): + self.filters = filters + + def __call__(self, obj): + return any(f(obj) for f in self.filters) + + +class AndFilter(ObjectCandidateFilter): + """Logical-and of a set of filters.""" + + def __init__(self, filters): + self.filters = filters + + def __call__(self, obj): + return all(f(obj) for f in self.filters) + + +class RuleCondition: + """ + Defines a transition rule condition for filtering a given set of input object candidates. + + NOTE: These filters should describe DYNAMIC properties about object candidates -- i.e.: properties that MAY change + at runtime, once imported + """ + + def refresh(self, object_candidates): + """ + Refreshes any internal state for this rule condition, given set of input object candidates @object_candidates + + Args: + object_candidates (dict): Maps filter name to valid object(s) that satisfy that filter + """ + # No-op by default + pass + + @abstractmethod + def __call__(self, object_candidates): + """ + Filters @object_candidates and updates the candidates in-place, returning True if there are still valid + candidates + + Args: + object_candidates (dict): Maps filter name to valid object(s) that satisfy that filter + + Returns: + bool: Whether there are still valid candidates in @object_candidates + """ + # Default is False + return False + + @property + def modifies_filter_names(self): + """ + Returns: + set: Filter name(s) whose values may be modified in-place by this condition + """ + raise NotImplementedError + + +class TouchingAnyCondition(RuleCondition): + """ + Rule condition that prunes object candidates from @filter_1_name, only keeping any that are touching any object + from @filter_2_name + + Note that this condition uses the RigidContactAPI for contact checking, which persists contact state + across physics steps even when both bodies fall asleep (current_only=False queries the "recent" + contact matrix that retains the last observed value for sleeping pairs). + """ + + def __init__(self, filter_1_name, filter_2_name): + """ + Args: + filter_1_name (str): Name of the filter whose object candidates will be pruned based on whether or not + they are touching any object from @filter_2_name + filter_2_name (str): Name of the filter whose object candidates will be used to prune the candidates from + @filter_1_name + """ + self._filter_1_name = filter_1_name + self._filter_2_name = filter_2_name + + def __call__(self, object_candidates): + # Keep any object that has non-zero impulses between itself and any of the @filter_2_name's objects + objs = [] + + with_set_by_scene = defaultdict(list) + for obj in object_candidates[self._filter_2_name]: + with_set_by_scene[obj.scene].append(obj) + + # Batch check for each object + for obj in object_candidates[self._filter_1_name]: + if obj.scene not in with_set_by_scene: + continue + if RigidContactAPI.is_in_contact( + scene_idx=obj.scene.idx, + query_set=[obj], + with_set=with_set_by_scene[obj.scene], + ignore_set=None, + current_only=False, + ): + objs.append(obj) + + # Update candidates + object_candidates[self._filter_1_name] = objs + + # If objs is empty, return False, otherwise, True + return len(objs) > 0 + + @property + def modifies_filter_names(self): + # Only modifies values from filter 1 + return {self._filter_1_name} + + +class StateCondition(RuleCondition): + """ + Rule condition that checks all objects from @filter_name whether a state condition is equal to @val for + """ + + def __init__( + self, + filter_name, + state, + val, + op=operator.eq, + ): + """ + Args: + filter_name (str): Name of the filter whose object candidates will be pruned based on whether or not + the state @state's value is equal to @val + state (BaseObjectState): Object state whose value should be queried as a rule condition + val (any): The value @state should be in order for this condition to be satisfied + op (function): Binary operator to apply between @state's getter and @val. Default is operator.eq, + which does state.get_value() == val. + Expected signature: + def op(state_getter, val) --> bool + """ + self._filter_name = filter_name + self._state = state + self._val = val + self._op = op + + def __call__(self, object_candidates): + # Keep any object whose states are satisfied + object_candidates[self._filter_name] = [ + obj + for obj in object_candidates[self._filter_name] + if self._op(obj.states[self._state].get_value(), self._val) + ] + + # Condition met if any object meets the condition + return len(object_candidates[self._filter_name]) > 0 + + @property + def modifies_filter_names(self): + return {self._filter_name} + + +class ChangeConditionWrapper(RuleCondition): + """ + Rule condition wrapper that checks whether the output from @condition + """ + + def __init__( + self, + condition, + ): + """ + Args: + condition (RuleCondition): Condition whose output will be additionally filtered whether or not its relevant + values have changed since the previous time this condition was called + """ + self._condition = condition + self._last_valid_candidates = {filter_name: set() for filter_name in self.modifies_filter_names} + + def refresh(self, object_candidates): + # Refresh nested condition + self._condition.refresh(object_candidates=object_candidates) + + def __call__(self, object_candidates): + # Call wrapped method first + valid = self._condition(object_candidates=object_candidates) + # Iterate over all current candidates -- if there's a mismatch in last valid candidates and current, + # then we store it, otherwise, we don't + for filter_name in self.modifies_filter_names: + # Compute current valid candidates + objs = [ + obj for obj in object_candidates[filter_name] if obj not in self._last_valid_candidates[filter_name] + ] + # Store last valid objects -- these are all candidates that were validated by self._condition at the + # current timestep + self._last_valid_candidates[filter_name] = set(object_candidates[filter_name]) + # Update current object candidates with the change-filtered ones + object_candidates[filter_name] = objs + valid = valid and len(objs) > 0 + + # Valid if any object conditions have changed and we still have valid objects + return valid + + @property + def modifies_filter_names(self): + # Return wrapped names + return self._condition.modifies_filter_names + + +class OrConditionWrapper(RuleCondition): + """ + Logical OR between multiple RuleConditions + """ + + def __init__(self, conditions): + """ + Args: + conditions (list of RuleConditions): Conditions to take logical OR over. This will generate + the UNION of all candidates. + """ + self._conditions = conditions + + def refresh(self, object_candidates): + # Refresh nested conditions + for condition in self._conditions: + condition.refresh(object_candidates=object_candidates) + + def __call__(self, object_candidates): + # Iterate over all conditions and aggregate their results + pruned_candidates = dict() + for condition in self._conditions: + # Copy the candidates because they get modified in place + pruned_candidates[condition] = copy(object_candidates) + condition(object_candidates=pruned_candidates[condition]) + + # For each filter, take the union over object candidates across each condition. + # If the result is empty, we immediately return False. + for filter_name in object_candidates: + object_candidates[filter_name] = list( + set.union(*[set(candidates[filter_name]) for candidates in pruned_candidates.values()]) + ) + if len(object_candidates[filter_name]) == 0: + return False + + return True + + @property + def modifies_filter_names(self): + # Return all wrapped names + return set.union(*(condition.modifies_filter_names for condition in self._conditions)) + + +class AndConditionWrapper(RuleCondition): + """ + Logical AND between multiple RuleConditions + """ + + def __init__(self, conditions): + """ + Args: + conditions (list of RuleConditions): Conditions to take logical AND over. This will generate + the INTERSECTION of all candidates. + """ + self._conditions = conditions + + def refresh(self, object_candidates): + # Refresh nested conditions + for condition in self._conditions: + condition.refresh(object_candidates=object_candidates) + + def __call__(self, object_candidates): + # Iterate over all conditions and aggregate their results + pruned_candidates = dict() + for condition in self._conditions: + # Copy the candidates because they get modified in place + pruned_candidates[condition] = copy(object_candidates) + condition(object_candidates=pruned_candidates[condition]) + + # For each filter, take the intersection over object candidates across each condition. + # If the result is empty, we immediately return False. + for filter_name in object_candidates: + object_candidates[filter_name] = list( + set.intersection(*[set(candidates[filter_name]) for candidates in pruned_candidates.values()]) + ) + if len(object_candidates[filter_name]) == 0: + return False + + return True + + @property + def modifies_filter_names(self): + # Return all wrapped names + return set.union(*(condition.modifies_filter_names for condition in self._conditions)) + + +class BaseTransitionRule(Registerable): + """ + Defines a set of categories of objects and how to transition their states. + """ + + ENABLED = True + + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + + # Register this system, and + # make sure at least one filter is specified -- in general, there should never be a rule + # where no filter is specified + # Only run this check for actual rules that are being registered + if cls.__name__ not in cls._do_not_register_classes: + global RULES_REGISTRY + RULES_REGISTRY.add(obj=cls) + assert ( + len(cls.candidate_filters) > 0 + ), "At least one of individual_filters or group_filters must be specified!" + + def __init__(self, scene): + self.scene = scene + self.candidates = None + # Delay condition generation until the first time it's accessed + self.conditions = None + + @classproperty + def candidate_filters(cls): + """ + Object candidate filters that this transition rule cares about. + For each name, filter key-value pair, the global transition rule step will produce a + single dictionary of valid filtered objects. + For example, if the group filters are: + + {"apple": CategoryFilter("apple"), "knife": CategoryFilter("knife")}, + + the transition rule step will produce the following dictionary: + + {"apple": [apple0, apple1, ...], "knife": [knife0, knife1, ...]} + + based on the current instances of each object type in the scene and pass them to conditions in @self.conditions + + NOTE: There should always be at least one filter applied for every rule! + + Returns: + dict: Maps filter name to filter for inferring valid object candidates for this transition rule + """ + raise NotImplementedError + + def _generate_conditions(self): + """ + Generates rule condition(s)s for this transition rule. These conditions are used to prune object + candidates at runtime, to determine whether a transition rule should occur at the given timestep + + Returns: + list of RuleCondition: Condition(s) to enforce to determine whether a transition rule should occur + """ + raise NotImplementedError + + def get_object_candidates(self, objects): + """ + Given the set of objects @objects, compute the valid object candidate combinations that may be valid for + this TransitionRule + + Args: + objects (list of USDObject): Objects to filter for valid transition rule candidates + + Returns: + dict: Maps filter name to valid object(s) that satisfy that filter + """ + # Iterate over all objects and add to dictionary if valid + filters = self.candidate_filters + obj_dict = {filter_name: [] for filter_name in filters.keys()} + + for obj in objects: + for fname, f in filters.items(): + if f(obj): + obj_dict[fname].append(obj) + + return obj_dict + + def refresh(self, object_candidates): + """ + Refresh any internal state for this rule, given set of input object candidates @object_candidates + + Args: + object_candidates (dict): Maps filter name to valid object(s) that satisfy that filter + """ + # Store candidates + self.candidates = object_candidates + + # Refresh all conditions + if self.conditions is None: + self.conditions = self._generate_conditions() + for condition in self.conditions: + condition.refresh(object_candidates=object_candidates) + + def transition(self, object_candidates): + """ + Rule to apply for each set of objects satisfying the condition. + + Args: + object_candidates (dict): Dictionary mapping corresponding keys from @cls.candidate_filters to list of individual + object instances where the filter is satisfied + + Returns: + TransitionResults: results from the executed transition + """ + raise NotImplementedError() + + def step(self): + """ + Takes a step for this transition rule, checking if all of @self.conditions are satisified, and if so, taking + a transition via @self.transition() + + Returns: + None or TransitionResults: If a transition occurs, returns its results, otherwise, returns None + """ + # Copy the candidates dictionary since it may be mutated in place by @conditions + object_candidates = {filter_name: candidates.copy() for filter_name, candidates in self.candidates.items()} + if self.conditions is None: + self.conditions = self._generate_conditions() + for condition in self.conditions: + if not condition(object_candidates=object_candidates): + # Condition was not met, so immediately terminate + return + + # All conditions are met, take the transition + return self.transition(object_candidates=object_candidates) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("BaseTransitionRule") + return classes + + @classproperty + def _cls_registry(cls): + # Global registry + global REGISTERED_RULES + return REGISTERED_RULES + + +# Global dicts that will contain mappings. Must be placed here immediately AFTER BaseTransitionRule! +RULES_REGISTRY = Registry( + name="TransitionRuleRegistry", + class_types=BaseTransitionRule, + default_key="__name__", +) + + +class WasherDryerRule(BaseTransitionRule): + """ + Transition rule to apply to cloth washers and dryers. + """ + + def _generate_conditions(self): + assert len(self.candidate_filters.keys()) == 1 + machine_type = list(self.candidate_filters.keys())[0] + return [ + ChangeConditionWrapper( + condition=AndConditionWrapper( + conditions=[ + StateCondition(filter_name=machine_type, state=ToggledOn, val=True, op=operator.eq), + StateCondition(filter_name=machine_type, state=Open, val=False, op=operator.eq), + ] + ) + ) + ] + + def _compute_global_rule_info(self): + """ + Helper function to compute global information necessary for checking rules. This is executed exactly + once per self.transition() step + + Returns: + dict: Keyword-mapped global rule information + """ + # Compute all obj collision points (handles both cloth and rigid objects) + obj_collision_points = [obj.collision_points_world for obj in self.scene.objects] + return dict(obj_collision_points=obj_collision_points) + + def _compute_container_info(self, object_candidates, container, global_info): + """ + Helper function to compute container-specific information necessary for checking rules. This is executed once + per container per self.transition() step + + Args: + object_candidates (dict): Dictionary mapping corresponding keys from @cls.candidate_filters to list of individual + object instances where the filter is satisfied + container (StatefulObject): Relevant container object for computing information + global_info (dict): Output of @self._compute_global_rule_info(); global information which may be + relevant for computing container information + + Returns: + dict: Keyword-mapped container information + """ + del object_candidates + obj_collision_points = global_info["obj_collision_points"] + + # Check each object's collision points + in_volume_objs = [] + for obj, collision_points in zip(self.scene.objects, obj_collision_points): + # Check if any of the collision points is in volume + points_in_volume = container.states[ContainedParticles].link.check_points_in_volume(collision_points) + # If any point is in volume, include this object + if th.any(points_in_volume): + in_volume_objs.append(obj) + + # Remove the container itself + if container in in_volume_objs: + in_volume_objs.remove(container) + + return dict(in_volume_objs=in_volume_objs) + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("WasherDryerRule") + return classes + + +class WasherRule(WasherDryerRule): + """ + Transition rule to apply to cloth washers. + 1. remove "dirty" particles from the washer if the necessary solvent is present. + 2. wet the objects inside by making them either Saturated with or Covered by water. + """ + + cleaning_conditions = None + + @classmethod + def register_cleaning_conditions(cls, conditions): + """ + Register cleaning conditions for this rule. + + Args: + conditions (dict): ictionary mapping the system name (str) to None or list of system names (str). None + represents "never", empty list represents "always", or non-empty list represents at least one of the + systems in the list needs to be present in the washer for the key system to be removed. + E.g. "rust" -> None: "never remove rust from the washer" + E.g. "dust" -> []: "always remove dust from the washer" + E.g. "cooking_oil" -> ["sodium_carbonate", "vinegar"]: "remove cooking_oil from the washer if either + sodium_carbonate or vinegar is present" + For keys not present in the dictionary, the default is []: "always remove" + """ + cls.cleaning_conditions = conditions + + @classproperty + def candidate_filters(cls): + return { + "washer": CategoryFilter("washer"), + } + + def transition(self, object_candidates): + global_info = self._compute_global_rule_info() + for washer in object_candidates["washer"]: + # Remove the systems if the conditions are met + systems_to_remove = [] + for system in self.scene.active_systems.values(): + # Never remove + if system.name in self.cleaning_conditions and self.cleaning_conditions[system.name] is None: + continue + if not washer.states[Contains].get_value(system): + continue + + solvents = self.cleaning_conditions.get(system.name, []) + # Always remove + if len(solvents) == 0: + systems_to_remove.append(system) + else: + solvents = [ + self.scene.get_system(solvent) for solvent in solvents if self.scene.is_system_active(solvent) + ] + # If any of the solvents are present + if any(washer.states[Contains].get_value(solvent) for solvent in solvents): + systems_to_remove.append(system) + + container_info = self._compute_container_info( + object_candidates=object_candidates, container=washer, global_info=global_info + ) + in_volume_objs = container_info["in_volume_objs"] + for system in systems_to_remove: + if isinstance(system, VisualParticleSystem): + # If the system is a visual particle system, remove it from the objects in the washer + for obj in in_volume_objs: + obj.states[Covered].set_value(system, False) + else: + washer.states[Contains].set_value(system, False) + + if gm.USE_GPU_DYNAMICS: + # Make the objects wet + water = self.scene.get_system("water", force_init=True) + for obj in in_volume_objs: + if Saturated in obj.states: + obj.states[Saturated].set_value(water, True) + else: + obj.states[Covered].set_value(water, True) + + return TransitionResults(add=[], remove=[]) + + +class DryerRule(WasherDryerRule): + """ + Transition rule to apply to cloth dryers. + 1. dry the objects inside by making them not Saturated with water. + 2. remove all water from the dryer. + """ + + @classproperty + def candidate_filters(cls): + return { + "dryer": CategoryFilter("clothes_dryer"), + } + + def transition(self, object_candidates): + water = self.scene.get_system("water", force_init=False) + if water.initialized: + global_info = self._compute_global_rule_info() + for dryer in object_candidates["dryer"]: + container_info = self._compute_container_info( + object_candidates=object_candidates, container=dryer, global_info=global_info + ) + in_volume_objs = container_info["in_volume_objs"] + for obj in in_volume_objs: + if Saturated in obj.states: + obj.states[Saturated].set_value(water, False) + dryer.states[Contains].set_value(water, False) + + return TransitionResults(add=[], remove=[]) + + +class SlicingRule(BaseTransitionRule): + """ + Transition rule to apply to sliced / slicer object pairs. + """ + + @classproperty + def candidate_filters(cls): + return { + "sliceable": AbilityFilter("sliceable"), + "slicer": AbilityFilter("slicer"), + } + + def _generate_conditions(self): + # sliceables should be touching any slicer + return [ + TouchingAnyCondition(filter_1_name="sliceable", filter_2_name="slicer"), + StateCondition(filter_name="slicer", state=SlicerActive, val=True, op=operator.eq), + ] + + def transition(self, object_candidates): + objs_to_add, objs_to_remove = [], [] + + for sliceable_obj in object_candidates["sliceable"]: + # Object parts offset annotation are w.r.t the base link of the whole object. + pos, orn = sliceable_obj.get_position_orientation() + + # Load object parts + for i, part in enumerate(sliceable_obj.metadata["object_parts"].values()): + # List of dicts gets replaced by {'0':dict, '1':dict, ...} + + # Get bounding box info + part_bb_pos = th.tensor(part["bb_pos"], dtype=th.float32) + part_bb_orn = th.tensor(part["bb_orn"], dtype=th.float32) + + # Scale the offset accordingly. + # If the scale of the sliceable object is uniform, we can just take its scale + if th.all(sliceable_obj.scale == sliceable_obj.scale[0]): + scale = sliceable_obj.scale + else: + # Determine the relative scale to apply to the object part from the original object + # Note that proper (rotated) scaling can only be applied when the relative orientation of + # the object part is a multiple of 90 degrees wrt the parent object, so we assert that here + assert T.check_quat_right_angle( + part_bb_orn + ), "Sliceable objects should only have relative object part orientations that are factors of 90 degrees!" + scale = th.abs(T.quat2mat(part_bb_orn) @ sliceable_obj.scale) + + # Calculate global part bounding box pose. + part_bb_pos = pos + T.quat2mat(orn) @ (part_bb_pos * scale) + part_bb_orn = T.quat_multiply(orn, part_bb_orn) + part_obj_name = f"half_{sliceable_obj.name}_{i}" + part_obj = DatasetObject( + name=part_obj_name, + category=part["category"], + model=part["model"], + bounding_box=th.tensor(part["bb_size"], dtype=th.float32) + * scale, # equiv. to scale=(part["bb_size"] / self.native_bbox) * (scale) + ) + + sliceable_obj_state = sliceable_obj.dump_state() + # Propagate non-physical states of the whole object to the half objects, e.g. cooked, saturated, etc. + # Add the new object to the results. + new_obj_attrs = ObjectAttrs( + obj=part_obj, + bb_pos=part_bb_pos, + bb_orn=part_bb_orn, + callback=lambda obj: obj.load_non_kin_state(sliceable_obj_state), + ) + objs_to_add.append(new_obj_attrs) + + # Delete original object from stage. + objs_to_remove.append(sliceable_obj) + + return TransitionResults(add=objs_to_add, remove=objs_to_remove) + + +class DicingRule(BaseTransitionRule): + """ + Transition rule to apply to diceable / slicer object pairs. + """ + + @classproperty + def candidate_filters(cls): + return { + "diceable": AbilityFilter("diceable"), + "slicer": AbilityFilter("slicer"), + } + + def _generate_conditions(self): + # sliceables should be touching any slicer + return [ + TouchingAnyCondition(filter_1_name="diceable", filter_2_name="slicer"), + StateCondition(filter_name="slicer", state=SlicerActive, val=True, op=operator.eq), + ] + + def transition(self, object_candidates): + objs_to_remove = [] + + for diceable_obj in object_candidates["diceable"]: + # We expect all diced particle systems to follow the naming convention (cooked__)diced__ + system_name = "diced__" + diceable_obj.category.removeprefix("half_") + if Cooked in diceable_obj.states and diceable_obj.states[Cooked].get_value(): + system_name = "cooked__" + system_name + system = self.scene.get_system(system_name) + system.generate_particles_from_link( + diceable_obj, diceable_obj.root_link, check_contact=False, use_visual_meshes=False + ) + + # Delete original object from stage. + objs_to_remove.append(diceable_obj) + + return TransitionResults(add=[], remove=objs_to_remove) + + +class MeltingRule(BaseTransitionRule): + """ + Transition rule to apply to meltable objects to simulate melting + Once the object reaches the melting temperature, remove the object and spawn the melted substance in its place. + """ + + @classproperty + def candidate_filters(cls): + # We want to find all meltable objects + return {"meltable": AbilityFilter("meltable")} + + def _generate_conditions(self): + return [StateCondition(filter_name="meltable", state=MaxTemperature, val=m.MELTING_TEMPERATURE, op=operator.ge)] + + def transition(self, object_candidates): + objs_to_remove = [] + + # Convert the meltable object into its melted substance + for meltable_obj in object_candidates["meltable"]: + # All meltable xyz, half_xyz and diced__xyz transform into melted__xyz + root_category = meltable_obj.category.removeprefix("half_").removeprefix("diced__") + system_name = f"melted__{root_category}" + system = self.scene.get_system(system_name) + system.generate_particles_from_link( + meltable_obj, meltable_obj.root_link, check_contact=False, use_visual_meshes=False + ) + + # Delete original object from stage. + objs_to_remove.append(meltable_obj) + + return TransitionResults(add=[], remove=objs_to_remove) + + +class RecipeRule(BaseTransitionRule): + """ + Transition rule to approximate recipe-based transitions + """ + + # Maps recipe name to recipe information + _RECIPES = None + + def __init_subclass__(cls, **kwargs): + # Run super first + super().__init_subclass__(**kwargs) + + # Initialize recipes + cls._recipes = dict() + + def __init__(self, scene): + super().__init__(scene) + + # Maps active recipe name to recipe information + self._active_recipes = None + + # Maps object category name to indices in the flattened object array for efficient computation + self._category_idxs = None + + # Flattened array of all simulator objects, sorted by category + self._objects = None + + # Maps object to idx within the _objects array + self._objects_to_idx = None + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + input_states=None, + output_states=None, + fillable_categories=None, + **kwargs, + ): + """ + Adds a recipe to this recipe rule to check against. This defines a valid mapping of inputs that will transform + into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + input_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute + output_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system"] to a list of states that should be set after the output objects are spawned + fillable_categories (None or set of str): If specified, set of fillable categories which are allowed + for this recipe. If None, any fillable is allowed + kwargs (dict): Any additional keyword-arguments to be stored as part of this recipe + """ + + input_states = input_states if input_states is not None else defaultdict(lambda: defaultdict(list)) + output_states = output_states if output_states is not None else defaultdict(lambda: defaultdict(list)) + + input_object_tree = None + if cls.is_multi_instance and len(input_objects) > 0: + # Build a tree of input object categories according to the kinematic binary states + # Example: 'raw_egg': {'binary_object': [(OnTop, 'bagel_dough', True)]} results in an edge + # from 'bagel_dough' to 'raw_egg', i.e. 'bagel_dough' is the parent of 'raw_egg'. + input_object_tree = nx.DiGraph() + for obj_category, state_checks in input_states.items(): + for state_class, second_obj_category, state_value in state_checks["binary_object"]: + input_object_tree.add_edge(second_obj_category, obj_category) + + if nx.is_empty(input_object_tree): + input_object_tree = None + else: + assert nx.is_tree(input_object_tree), f"Input object tree must be a tree! Now: {input_object_tree}." + root_nodes = [node for node in input_object_tree.nodes() if input_object_tree.in_degree(node) == 0] + assert len(root_nodes) == 1, f"Input object tree must have exactly one root node! Now: {root_nodes}." + assert ( + input_objects[root_nodes[0]] == 1 + ), f"Input object tree root node must have exactly one instance! Now: {cls._recipes[name]['input_objects'][root_nodes[0]]}." + + # Store information for this recipe + cls._recipes[name] = { + "name": name, + "input_objects": input_objects, + "input_systems": input_systems, + "output_objects": output_objects, + "output_systems": output_systems, + "input_states": input_states, + "output_states": output_states, + "fillable_categories": fillable_categories, + "input_object_tree": input_object_tree, + **kwargs, + } + + def _validate_recipe_container_is_valid(self, recipe, container): + """ + Validates that @container's category satisfies @recipe's fillable_categories + + Args: + recipe (dict): Recipe whose fillable_categories should be checked against @container + container (StatefulObject): Container whose category should match one of @recipe's fillable_categories, + if specified + + Returns: + bool: True if @container is valid, else False + """ + fillable_categories = recipe["fillable_categories"] + return fillable_categories is None or container.category in fillable_categories + + def _validate_recipe_systems_are_contained(self, recipe, container): + """ + Validates whether @recipe's input_systems are all contained in @container or not + + Args: + recipe (dict): Recipe whose systems should be checked + container (USDObject): Container object that should contain all of @recipe's input systems + + Returns: + bool: True if all the input systems are contained + """ + for system_name in recipe["input_systems"]: + system = self.scene.get_system(system_name) + if not container.states[Contains].get_value(system=system): + return False + return True + + def _validate_nonrecipe_systems_not_contained(self, recipe, container): + """ + Validates whether all systems not relevant to @recipe are not contained in @container + + Args: + recipe (dict): Recipe whose systems should be checked + container (USDObject): Container object that should contain all of @recipe's input systems + + Returns: + bool: True if none of the non-relevant systems are contained + """ + for system in self.scene.active_systems.values(): + if system.name not in recipe["input_systems"] and container.states[Contains].get_value(system=system): + return False + return True + + def _validate_recipe_objects_are_contained_and_states_satisfied(self, recipe, container_info): + """ + Validates whether @recipe's input_objects are contained in the container and whether their states are satisfied + + Args: + recipe (dict): Recipe whose objects should be checked + container_info (dict): Output of @self._compute_container_info(); container-specific information which may + be relevant for computing whether recipe is executable. This will be populated with execution info. + + Returns: + bool: True if all the input object quantities are contained + """ + in_volume = container_info["in_volume"] + + # Store necessary information for execution + container_info["execution_info"] = dict() + category_to_valid_indices = self._filter_input_objects_by_unary_and_binary_system_states(recipe=recipe) + container_info["execution_info"]["category_to_valid_indices"] = category_to_valid_indices + + if not self.is_multi_instance: + return self._validate_recipe_objects_non_multi_instance( + recipe=recipe, + category_to_valid_indices=category_to_valid_indices, + in_volume=in_volume, + ) + else: + return self._validate_recipe_objects_multi_instance( + recipe=recipe, + category_to_valid_indices=category_to_valid_indices, + container_info=container_info, + ) + + def _filter_input_objects_by_unary_and_binary_system_states(self, recipe): + # Filter input objects based on a subset of input states (unary states and binary system states) + # Map object categories (str) to valid indices (th.tensor) + category_to_valid_indices = dict() + for obj_category in recipe["input_objects"]: + if obj_category not in recipe["input_states"]: + # If there are no input states, all objects of this category are valid + category_to_valid_indices[obj_category] = self._category_idxs[obj_category] + else: + category_to_valid_indices[obj_category] = [] + for idx in self._category_idxs[obj_category]: + obj = self._objects[idx] + success = True + + # Check if unary states are satisfied + for state_class, state_value in recipe["input_states"][obj_category]["unary"]: + if obj.states[state_class].get_value() != state_value: + success = False + break + if not success: + continue + + # Check if binary system states are satisfied + for state_class, system_name, state_value in recipe["input_states"][obj_category]["binary_system"]: + system = self.scene.get_system(system_name) + if obj.states[state_class].get_value(system=system) != state_value: + success = False + break + if not success: + continue + + category_to_valid_indices[obj_category].append(idx) + + # Convert to numpy array for faster indexing + category_to_valid_indices[obj_category] = th.tensor( + category_to_valid_indices[obj_category], dtype=th.int32 + ) + return category_to_valid_indices + + def _validate_recipe_objects_non_multi_instance(self, recipe, category_to_valid_indices, in_volume): + # Check if sufficiently number of objects are contained + for obj_category, obj_quantity in recipe["input_objects"].items(): + if th.sum(in_volume[category_to_valid_indices[obj_category]]) < obj_quantity: + return False + return True + + def _validate_recipe_objects_multi_instance(self, recipe, category_to_valid_indices, container_info): + in_volume = container_info["in_volume"] + input_object_tree = recipe["input_object_tree"] + + # Map object category to a set of objects that are used in this execution + relevant_objects = defaultdict(set) + + # Map system name to a set of particle indices that are used in this execution + relevant_systems = defaultdict(set) + + # Number of instances of this recipe that can be produced + num_instances = 0 + + # Define a recursive function to check the kinematic tree + def check_kinematic_tree(obj, should_check_in_volume=False): + """ + Recursively check if the kinematic tree is satisfied. + Return True/False, and a set of objects that belong to the subtree rooted at the current node + + Args: + obj (USDObject): Subtree root node to check + should_check_in_volume (bool): Whether to check if the object is in the volume or not + Returns: + bool: True if the subtree rooted at the current node is satisfied + set: Set of objects that belong to the subtree rooted at the current node + """ + + # Check if obj is in volume + if should_check_in_volume and not in_volume[self._objects_to_idx[obj]]: + return False, set() + + # If the object is a leaf node, return True and the set containing the object + if input_object_tree.out_degree(obj.category) == 0: + return True, set([obj]) + + children_categories = list(input_object_tree.successors(obj.category)) + + all_subtree_objs = set() + for child_cat in children_categories: + assert ( + len(input_states[child_cat]["binary_object"]) == 1 + ), "Each child node should have exactly one binary object state, i.e. one parent in the input_object_tree" + state_class, _, state_value = input_states[child_cat]["binary_object"][0] + num_valid_children = 0 + children_objs = [self._objects[i] for i in category_to_valid_indices[child_cat]] + for child_obj in children_objs: + # If the child doesn't satisfy the binary object state, skip + if child_obj.states[state_class].get_value(obj) != state_value: + continue + # Recursively check if the subtree rooted at the child is valid + subtree_valid, subtree_objs = check_kinematic_tree(child_obj) + # If the subtree is valid, increment the number of valid children and aggregate the objects + if subtree_valid: + num_valid_children += 1 + all_subtree_objs |= subtree_objs + + # If there are not enough valid children, return False + if num_valid_children < recipe["input_objects"][child_cat]: + return False, set() + + # If all children categories have sufficient number of objects that satisfy the binary object state, + # e.g. five pieces of pepperoni and two pieces of basil on the pizza, the subtree rooted at the + # current node is valid. Return True and the set of objects in the subtree (all descendants plus + # the current node) + return True, all_subtree_objs | {obj} + + # If multi-instance is True but doesn't require kinematic states between objects + if input_object_tree is None: + num_instances = float("inf") + # Compute how many instances of this recipe can be produced. + # Example: if a recipe requires 1 apple and 2 bananas, and there are 3 apples and 4 bananas in the + # container, then 2 instance of the recipe can be produced. + for obj_category, obj_quantity in recipe["input_objects"].items(): + quantity_in_volume = th.sum(in_volume[category_to_valid_indices[obj_category]]) + num_inst = quantity_in_volume // obj_quantity + if num_inst < 1: + return False + num_instances = min(num_instances, num_inst) + + # If at least one instance of the recipe can be executed, add all valid objects to be relevant_objects. + # This can be considered as a special case of below where there are no binary kinematic states required. + for obj_category in recipe["input_objects"]: + relevant_objects[obj_category] = set(self._objects[category_to_valid_indices[obj_category]]) + + # If multi-instance is True and requires kinematic states between objects + else: + root_node_category = [node for node in input_object_tree.nodes() if input_object_tree.in_degree(node) == 0][ + 0 + ] + # A list of objects belonging to the root node category + root_nodes = [self._objects[i] for i in category_to_valid_indices[root_node_category]] + input_states = recipe["input_states"] + + for root_node in root_nodes: + # should_check_in_volume is True only for the root nodes. + # Example: the bagel dough needs to be in_volume of the container, but the raw egg on top doesn't. + tree_valid, relevant_object_set = check_kinematic_tree(obj=root_node, should_check_in_volume=True) + if tree_valid: + # For each valid tree, increment the number of instances and aggregate the objects + num_instances += 1 + for obj in relevant_object_set: + relevant_objects[obj.category].add(obj) + + # If there are no valid trees, return False + if num_instances == 0: + return False + + # Note that for multi instance recipes, the relevant system particles are NOT the ones in the container. + # Instead, they are the ones that are related to the relevant objects, e.g. salt covering the bagel dough. + for obj_category, objs in relevant_objects.items(): + for state_class, system_name, state_value in recipe["input_states"][obj_category]["binary_system"]: + # If the state value is False, skip + if not state_value: + continue + system = self.scene.get_system(system_name) + for obj in objs: + if state_class in [Filled, Contains]: + contained_particle_idx = obj.states[ContainedParticles].get_value(system).in_volume.nonzero() + relevant_systems[system_name] |= contained_particle_idx + elif state_class in [Covered]: + covered_particle_idx = obj.states[ContactParticles].get_value(system) + relevant_systems[system_name] |= covered_particle_idx + + # Now we populate the execution info with the relevant objects and systems as well as the number of + # instances of the recipe that can be produced. + container_info["execution_info"]["relevant_objects"] = relevant_objects + container_info["execution_info"]["relevant_systems"] = relevant_systems + container_info["execution_info"]["num_instances"] = num_instances + return True + + def _validate_nonrecipe_objects_not_contained(self, recipe, container_info): + """ + Validates whether all objects not relevant to @recipe are not contained in the container + represented by @in_volume + + Args: + recipe (dict): Recipe whose systems should be checked + container_info (dict): Output of @self._compute_container_info(); container-specific information + which may be relevant for computing whether recipe is executable + + Returns: + bool: True if none of the non-relevant objects are contained + """ + in_volume = container_info["in_volume"] + # These are object indices whose objects satisfy the input states + category_to_valid_indices = container_info["execution_info"]["category_to_valid_indices"] + nonrecipe_objects_in_volume = ( + in_volume + if len(recipe["input_objects"]) == 0 + else torch_delete( + in_volume, + th.cat([category_to_valid_indices[obj_category] for obj_category in category_to_valid_indices]), + ) + ) + return not th.any(nonrecipe_objects_in_volume) + + def _validate_recipe_systems_exist(self, recipe): + """ + Validates whether @recipe's input_systems are all active or not + + Args: + recipe (dict): Recipe whose systems should be checked + + Returns: + bool: True if all the input systems are active + """ + for system_name in recipe["input_systems"]: + if not self.scene.is_system_active(system_name=system_name): + return False + return True + + def _validate_recipe_objects_exist(self, recipe): + """ + Validates whether @recipe's input_objects exist in the current scene or not + + Args: + recipe (dict): Recipe whose objects should be checked + + Returns: + bool: True if all the input objects exist in the scene + """ + for obj_category, obj_quantity in recipe["input_objects"].items(): + if len(self.scene.object_registry("category", obj_category, default_val=set())) < obj_quantity: + return False + return True + + def _validate_recipe_fillables_exist(self, recipe): + """ + Validates that recipe @recipe's necessary fillable categorie(s) exist in the current scene + + Args: + recipe (dict): Recipe whose fillable categories should be checked + + Returns: + bool: True if there is at least a single valid fillable category in the current scene, else False + """ + fillable_categories = recipe["fillable_categories"] + if fillable_categories is None: + # Any is valid + return True + # Otherwise, at least one valid type must exist + for category in fillable_categories: + if len(self.scene.object_registry("category", category, default_val=set())) > 0: + return True + + # None found, return False + return False + + def _is_recipe_active(self, recipe): + """ + Helper function to determine whether a given recipe @recipe should be actively checked for or not. + + Args: + recipe (dict): Maps relevant keyword to corresponding recipe info + + Returns: + bool: True if the recipe is active, else False + """ + # Check valid active systems + if not self._validate_recipe_systems_exist(recipe=recipe): + return False + + # Check valid object quantities + if not self._validate_recipe_objects_exist(recipe=recipe): + return False + + # Check valid fillable categories + if not self._validate_recipe_fillables_exist(recipe=recipe): + return False + + return True + + def _is_recipe_executable(self, recipe, container, global_info, container_info): + """ + Helper function to determine whether a given recipe @recipe should be immediately executed or not. + + Args: + recipe (dict): Maps relevant keyword to corresponding recipe info + container (StatefulObject): Container in which @recipe may be executed + global_info (dict): Output of @self._compute_global_rule_info(); global information which may be + relevant for computing whether recipe is executable + container_info (dict): Output of @self._compute_container_info(); container-specific information + which may be relevant for computing whether recipe is executable + + Returns: + bool: True if the recipe is active, else False + """ + # Verify the container category is valid + if not self._validate_recipe_container_is_valid(recipe=recipe, container=container): + return False + + # Verify all required systems are contained in the container + if not self.relax_recipe_systems and not self._validate_recipe_systems_are_contained( + recipe=recipe, container=container + ): + return False + + # Verify all required object quantities are contained in the container and their states are satisfied + if not self._validate_recipe_objects_are_contained_and_states_satisfied( + recipe=recipe, container_info=container_info + ): + return False + + # Verify no non-relevant system is contained + if not self.ignore_nonrecipe_systems and not self._validate_nonrecipe_systems_not_contained( + recipe=recipe, container=container + ): + return False + + # Verify no non-relevant object is contained if we're not ignoring them + if not self.ignore_nonrecipe_objects and not self._validate_nonrecipe_objects_not_contained( + recipe=recipe, container_info=container_info + ): + return False + + return True + + def _compute_global_rule_info(self): + """ + Helper function to compute global information necessary for checking rules. This is executed exactly + once per self.transition() step + + Returns: + dict: Keyword-mapped global rule information + """ + # Compute all relevant object AABB positions + obj_positions = th.stack([obj.aabb_center for obj in self._objects]) + return dict(obj_positions=obj_positions) + + def _compute_container_info(self, object_candidates, container, global_info): + """ + Helper function to compute container-specific information necessary for checking rules. This is executed once + per container per self.transition() step + + Args: + object_candidates (dict): Dictionary mapping corresponding keys from @cls.candidate_filters to list of individual + object instances where the filter is satisfied + container (StatefulObject): Relevant container object for computing information + global_info (dict): Output of @self._compute_global_rule_info(); global information which may be + relevant for computing container information + + Returns: + dict: Keyword-mapped container information + """ + del object_candidates + obj_positions = global_info["obj_positions"] + # Compute in volume for all relevant object positions + # We check for either the object AABB being contained OR the object being on top of the container, in the + # case that the container is too flat for the volume to contain the object + in_volume = container.states[ContainedParticles].link.check_points_in_volume(obj_positions) | th.tensor( + [obj.states[OnTop].get_value(container) for obj in self._objects] + ) + + # Container itself is never within its own volume + in_volume[self._objects_to_idx[container]] = False + + return dict(in_volume=in_volume) + + def refresh(self, object_candidates): + # Run super first + super().refresh(object_candidates=object_candidates) + + # Cache active recipes given the current set of objects + self._active_recipes = dict() + self._category_idxs = dict() + self._objects = [] + self._objects_to_idx = dict() + + # Prune any recipes whose objects / system requirements are not met by the current set of objects / systems + objects_by_category = defaultdict(list) + scene_objects_by_category = self.scene.object_registry.get_dict("category") + for cat, objs in scene_objects_by_category.items(): + objects_by_category[cat].extend(objs) + + for name, recipe in self._recipes.items(): + # If all pre-requisites met, add to active recipes + if self._is_recipe_active(recipe=recipe): + self._active_recipes[name] = recipe + + # Finally, compute relevant objects and category mapping based on relevant categories + i = 0 + for category, objects in objects_by_category.items(): + # Exclude fixed base objects for performance + objects = [obj for obj in objects if not obj.fixed_base] + self._category_idxs[category] = i + th.arange(len(objects)) + self._objects += list(objects) + for obj in objects: + self._objects_to_idx[obj] = i + i += 1 + + @classproperty + def candidate_filters(cls): + # Fillable object required + # We also will filter out any fixed_base objects, because otherwise all cabinets, fridges, etc. would become valid containers! + return {"container": AndFilter([AbilityFilter(ability="fillable"), ObjectPropertyFilter("fixed_base", False)])} + + def transition(self, object_candidates): + objs_to_add, objs_to_remove = [], [] + + # Compute global info + global_info = self._compute_global_rule_info() + + # Iterate over all fillable objects, to execute recipes for each one + for container in object_candidates["container"]: + recipe_results = None + # Compute container info + container_info = self._compute_container_info( + object_candidates=object_candidates, + container=container, + global_info=global_info, + ) + + # Check every recipe to find if any is valid + for name, recipe in self._active_recipes.items(): + if self._is_recipe_executable( + recipe=recipe, container=container, global_info=global_info, container_info=container_info + ): + # Otherwise, all conditions met, we found a valid recipe and so we execute and terminate early + og.log.info(f"Executing recipe: {name} in container {container.name}!") + + # Take the transform and terminate early + recipe_results = self._execute_recipe( + container=container, + recipe=recipe, + container_info=container_info, + ) + objs_to_add += recipe_results.add + objs_to_remove += recipe_results.remove + break + + # Otherwise, if we didn't find a valid recipe, we execute a garbage transition instead if requested + if recipe_results is None and self.use_garbage_fallback_recipe: + og.log.info( + f"Did not find a valid recipe for rule {self.__class__.__name__}; generating {m.DEFAULT_GARBAGE_SYSTEM} in {container.name}!" + ) + + # Generate garbage fluid + garbage_results = self._execute_recipe( + container=container, + recipe=dict( + name="garbage", + input_objects=dict(), + input_systems=[], + output_objects=dict(), + output_systems=[m.DEFAULT_GARBAGE_SYSTEM], + output_states=defaultdict(lambda: defaultdict(list)), + ), + container_info=container_info, + ) + objs_to_add += garbage_results.add + objs_to_remove += garbage_results.remove + + return TransitionResults(add=objs_to_add, remove=objs_to_remove) + + def _execute_recipe(self, container, recipe, container_info): + """ + Transforms all items contained in @container into @output_system, generating volume of @output_system + proportional to the number of items transformed. + + Args: + container (USDObject): Container object which will have its contained elements transformed into + @output_system + recipe (dict): Recipe to execute. Should include, at the minimum, "input_objects", "input_systems", + "output_objects", and "output_systems" keys + container_info (dict): Output of @self._compute_container_info(); container-specific information which may + be relevant for computing whether recipe is executable. + + Returns: + TransitionResults: Results of the executed recipe transition + """ + objs_to_add, objs_to_remove = [], [] + + in_volume = container_info["in_volume"] + if self.is_multi_instance: + execution_info = container_info["execution_info"] + + # Compute total volume of all contained items + volume = 0 + + if not self.is_multi_instance: + # Remove either all systems or only the ones specified in the input systems of the recipe + contained_particles_state = container.states[ContainedParticles] + for system_name, system in self.scene.active_systems.items(): + if not self.ignore_nonrecipe_systems or system_name in recipe["input_systems"]: + if container.states[Contains].get_value(system): + if self.scene.is_physical_particle_system(system_name): + volume += ( + contained_particles_state.get_value(system).n_in_volume + * math.pi + * (system.particle_radius**3) + * 4 + / 3 + ) + container.states[Contains].set_value(system, False) + else: + # Remove the particles that are involved in this execution + for system_name, particle_idxs in execution_info["relevant_systems"].items(): + system = self.scene.get_system(system_name) + volume += len(particle_idxs) * math.pi * (system.particle_radius**3) * 4 / 3 + system.remove_particles(idxs=th.tensor(list(particle_idxs))) + + if not self.is_multi_instance: + # Remove either all objects or only the ones specified in the input objects of the recipe + object_mask = th.clone(in_volume) + if self.ignore_nonrecipe_objects: + object_category_mask = th.zeros_like(object_mask, dtype=bool) + for obj_category in recipe["input_objects"].keys(): + object_category_mask[self._category_idxs[obj_category]] = True + object_mask &= object_category_mask + mask_indices = object_mask.nonzero().flatten().tolist() + objs_to_remove.extend([self._objects[i] for i in mask_indices]) + else: + # Remove the objects that are involved in this execution + for obj_category, objs in execution_info["relevant_objects"].items(): + objs_to_remove.extend(objs) + + volume += sum(obj.volume for obj in objs_to_remove) + + # Compute full AABB containing all objects in objs_to_remove + full_aabb = None + if objs_to_remove: + aabbs = [obj.aabb for obj in objs_to_remove] + full_aabb = ( + th.min(th.stack([aabb[0] for aabb in aabbs]), dim=0).values, + th.max(th.stack([aabb[1] for aabb in aabbs]), dim=0).values, + ) + + # Define callback for spawning new objects inside container + def _spawn_object_in_container(obj): + # For simplicity sake, sample only OnTop + # TODO: Can we sample inside intelligently? + state = OnTop + # TODO: What to do if setter fails? + if not obj.states[state].set_value(container, True): + log.warning( + f"Failed to spawn object {obj.name} in container {container.name}! Directly placing on top instead." + ) + pos = th.tensor(container.aabb_center, dtype=th.float32) + th.tensor( + [0, 0, container.aabb_extent[2] / 2.0 + obj.aabb_extent[2] / 2.0], dtype=th.float32 + ) + obj.set_bbox_center_position_orientation(position=pos) + + # Spawn in new objects + for category, n_instances in recipe["output_objects"].items(): + # Multiply by number of instances of execution if this is a multi-instance recipe + if self.is_multi_instance: + n_instances *= execution_info["num_instances"] + + output_states = dict() + for state_type, state_value in recipe["output_states"][category]["unary"]: + output_states[state_type] = (state_value,) + for state_type, system_name, state_value in recipe["output_states"][category]["binary_system"]: + output_states[state_type] = (self.scene.get_system(system_name), state_value) + n_category_objs = len(container.scene.object_registry("category", category, [])) + models = get_all_object_category_models(category=category) + + bounding_box_size = None + if full_aabb is not None and n_instances > 0: + # Compute the 3D bounding box size for the new objects + full_aabb_extent = full_aabb[1] - full_aabb[0] # Get the full AABB extent + + # Determine how to divide the space in the x-y plane + # Calculate factors for grid layout + n_rows = int(math.ceil(n_instances**0.5)) + n_columns = math.ceil(n_instances / n_rows) + + # Calculate the size for each instance in the x-y plane + bounding_box_size = th.tensor( + [full_aabb_extent[0] / n_columns, full_aabb_extent[1] / n_rows, full_aabb_extent[2]], + dtype=th.float32, + ) + + for i in range(n_instances): + obj = DatasetObject( + name=f"{category}_{n_category_objs + i}", + category=category, + model=random.choice(models), + bounding_box=bounding_box_size, + ) + new_obj_attrs = ObjectAttrs( + obj=obj, + callback=_spawn_object_in_container, + states=output_states, + pos=th.ones(3) * (100.0 + i), + ) + objs_to_add.append(new_obj_attrs) + + # Spawn in new fluid + if len(recipe["output_systems"]) > 0: + # Only one system is allowed to be spawned + assert len(recipe["output_systems"]) == 1, "Only a single output system can be spawned for a given recipe!" + out_system = self.scene.get_system(recipe["output_systems"][0]) + out_system.generate_particles_from_link( + obj=container, + link=contained_particles_state.link, + # When ignore_nonrecipe_objects is True, we don't necessarily remove all objects in the container. + # Therefore, we need to check for contact when generating output systems. + check_contact=self.ignore_nonrecipe_objects, + max_samples=math.ceil(volume / (math.pi * (out_system.particle_radius**3) * 4 / 3)), + ) + + # Return transition results + return TransitionResults(add=objs_to_add, remove=objs_to_remove) + + @classproperty + def relax_recipe_systems(cls): + """ + Returns: + bool: Whether to relax the requirement of having all systems in the recipe contained in the container + """ + raise NotImplementedError("Must be implemented by subclass!") + + @classproperty + def ignore_nonrecipe_systems(cls): + """ + Returns: + bool: Whether contained systems not relevant to the recipe should be ignored or not + """ + raise NotImplementedError("Must be implemented by subclass!") + + @classproperty + def ignore_nonrecipe_objects(cls): + """ + Returns: + bool: Whether contained rigid objects not relevant to the recipe should be ignored or not + """ + raise NotImplementedError("Must be implemented by subclass!") + + @classproperty + def use_garbage_fallback_recipe(cls): + """ + Returns: + bool: Whether this recipe rule should use a garbage fallback recipe if all conditions are met but no + valid recipe is found for a given container + """ + raise NotImplementedError("Must be implemented by subclass!") + + @classproperty + def is_multi_instance(cls): + """ + Returns: + bool: Whether this rule can be applied multiple times to the same container, e.g. to cook multiple doughs + """ + return False + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("RecipeRule") + return classes + + +class CookingPhysicalParticleRule(RecipeRule): + """ + Transition rule to apply to "cook" physical particles. + It comes with two forms of recipes: + 1. xyz -> cooked__xyz, e.g. diced__chicken -> cooked__diced__chicken + 2. xyz + cooked__water -> cooked__xyz, e.g. rice + cooked__water -> cooked__rice + During execution, we replace the input particles (xyz) with the output particles (cooked__xyz), and remove the + cooked__water if it was used as an input. + """ + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + **kwargs, + ): + """ + Adds a recipe to this recipe rule to check against. This defines a valid mapping of inputs that will transform + into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + """ + assert len(input_objects) == 0, f"No input objects can be specified for {cls.__name__}, recipe: {name}!" + assert len(output_objects) == 0, f"No output objects can be specified for {cls.__name__}, recipe: {name}!" + + assert ( + len(input_systems) == 1 or len(input_systems) == 2 + ), f"Only one or two input systems can be specified for {cls.__name__}, recipe: {name}!" + if len(input_systems) == 2: + assert ( + input_systems[1] == "cooked__water" + ), f"Second input system must be cooked__water for {cls.__name__}, recipe: {name}!" + assert ( + len(output_systems) == 1 + ), f"Exactly one output system needs to be specified for {cls.__name__}, recipe: {name}!" + + super().add_recipe( + name=name, + input_objects=input_objects, + input_systems=input_systems, + output_objects=output_objects, + output_systems=output_systems, + **kwargs, + ) + + @classproperty + def candidate_filters(cls): + # Modify the container filter to include the heatable ability as well + candidate_filters = super().candidate_filters + candidate_filters["container"] = AndFilter( + filters=[candidate_filters["container"], AbilityFilter(ability="heatable")] + ) + return candidate_filters + + def _generate_conditions(self): + # Only heated objects are valid + return [StateCondition(filter_name="container", state=Heated, val=True, op=operator.eq)] + + @classproperty + def relax_recipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_systems(cls): + return True + + @classproperty + def ignore_nonrecipe_objects(cls): + return True + + @classproperty + def use_garbage_fallback_recipe(cls): + return False + + def _execute_recipe(self, container, recipe, container_info): + system = self.scene.get_system(recipe["input_systems"][0]) + contained_particles_state = container.states[ContainedParticles].get_value(system) + in_volume_idx = th.where(contained_particles_state.in_volume)[0] + assert len(in_volume_idx) > 0, "No particles found in the container when executing recipe!" + + # Remove uncooked particles + system.remove_particles(idxs=in_volume_idx) + + # Generate cooked particles + cooked_system = self.scene.get_system(recipe["output_systems"][0]) + pre_gen_count = cooked_system.n_particles + particle_positions = contained_particles_state.positions[in_volume_idx] + cooked_system.generate_particles(positions=particle_positions) + + # Stabilize generated particles + if isinstance(cooked_system, MacroPhysicalParticleSystem): + new_particle_indices = th.arange(pre_gen_count, cooked_system.n_particles) + lin_vel, ang_vel = cooked_system.get_particles_velocities() + lin_vel[new_particle_indices] = 0 + ang_vel[new_particle_indices] = 0 + cooked_system.set_particles_velocities(lin_vels=lin_vel, ang_vels=ang_vel) + + # Remove water if the cooking requires water + if len(recipe["input_systems"]) > 1: + cooked_water_system = self.scene.get_system(recipe["input_systems"][1]) + container.states[Contains].set_value(cooked_water_system, False) + + return TransitionResults(add=[], remove=[]) + + +class ToggleableMachineRule(RecipeRule): + """ + Transition mixing rule that leverages a single toggleable machine (e.g. electric mixer, coffee machine, blender), + which require toggledOn in order to trigger the recipe event. + It comes with two forms of recipes: + 1. output is a single object, e.g. flour + butter + sugar -> dough, machine is electric mixer + 2. output is a system, e.g. strawberry + milk -> smoothie, machine is blender + """ + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + input_states=None, + output_states=None, + fillable_categories=None, + **kwargs, + ): + """ + Adds a recipe to this recipe rule to check against. This defines a valid mapping of inputs that will transform + into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + input_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute + output_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system"] to a list of states that should be set after the output objects are spawned + fillable_categories (None or set of str): If specified, set of fillable categories which are allowed + for this recipe. If None, any fillable is allowed + """ + if len(output_objects) > 0: + assert ( + len(output_objects) == 1 + ), f"Only one category of output object can be specified for {cls.__name__}, recipe: {name}!" + assert ( + output_objects[list(output_objects.keys())[0]] == 1 + ), f"Only one instance of output object can be specified for {cls.__name__}, recipe: {name}!" + + super().add_recipe( + name=name, + input_objects=input_objects, + input_systems=input_systems, + output_objects=output_objects, + output_systems=output_systems, + input_states=input_states, + output_states=output_states, + fillable_categories=fillable_categories, + **kwargs, + ) + + @classproperty + def candidate_filters(cls): + # Modify the container filter to include toggleable ability as well + candidate_filters = super().candidate_filters + candidate_filters["container"] = AndFilter( + filters=[ + candidate_filters["container"], + AbilityFilter(ability="toggleable"), + # Exclude washer and clothes dryer because they are handled by WasherRule and DryerRule + NotFilter(CategoryFilter("washer")), + NotFilter(CategoryFilter("clothes_dryer")), + NotFilter(CategoryFilter("hot_tub")), + NotFilter(CategoryFilter("oven")), + NotFilter(CategoryFilter("microwave")), + ] + ) + return candidate_filters + + def _generate_conditions(self): + # Container must be toggledOn, and should only be triggered once + return [ + ChangeConditionWrapper( + condition=StateCondition(filter_name="container", state=ToggledOn, val=True, op=operator.eq) + ) + ] + + @classproperty + def relax_recipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_objects(cls): + return False + + @classproperty + def use_garbage_fallback_recipe(cls): + return True + + +class MixingToolRule(RecipeRule): + """ + Transition mixing rule that leverages "mixingTool" ability objects, which require touching between a mixing tool + and a container in order to trigger the recipe event. + Example: water + lemon_juice + sugar -> lemonade, mixing tool is spoon + """ + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + input_states=None, + output_states=None, + **kwargs, + ): + """ + Adds a recipe to this recipe rule to check against. This defines a valid mapping of inputs that will transform + into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + input_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute + output_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system"] to a list of states that should be set after the output objects are spawned + """ + assert len(output_objects) == 0, f"No output objects can be specified for {cls.__name__}, recipe: {name}!" + assert len(input_systems) > 0, f"Some input systems need to be specified for {cls.__name__}, recipe: {name}!" + assert ( + len(output_systems) == 1 + ), f"Exactly one output system needs to be specified for {cls.__name__}, recipe: {name}!" + + super().add_recipe( + name=name, + input_objects=input_objects, + input_systems=input_systems, + output_objects=output_objects, + output_systems=output_systems, + input_states=input_states, + output_states=output_states, + **kwargs, + ) + + @classproperty + def candidate_filters(cls): + # Add mixing tool filter as well + candidate_filters = super().candidate_filters + candidate_filters["mixingTool"] = AbilityFilter(ability="mixingTool") + return candidate_filters + + def _generate_conditions(self): + # Mixing tool must be touching the container, and should only be triggered once + return [ + ChangeConditionWrapper( + condition=TouchingAnyCondition(filter_1_name="container", filter_2_name="mixingTool") + ) + ] + + @classproperty + def relax_recipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_objects(cls): + return True + + @classproperty + def use_garbage_fallback_recipe(cls): + return True + + +class CookingRule(RecipeRule): + """ + Transition mixing rule that approximates cooking recipes via a container and heatsource. + It is subclassed by CookingObjectRule and CookingSystemRule. + """ + + def __init__(self, scene): + super().__init__(scene=scene) + + # Counter that increments monotonically + self.counter = 0 + + # Maps recipe name to current number of consecutive heating steps + self._heat_steps = None + + # Maps recipe name to the last timestep that it was active + self._last_heat_timestep = None + + def refresh(self, object_candidates): + # Run super first + super().refresh(object_candidates=object_candidates) + + # Iterate through all (updated) active recipes and store in internal variables if not already recorded + self._heat_steps = dict() if self._heat_steps is None else self._heat_steps + self._last_heat_timestep = dict() if self._last_heat_timestep is None else self._last_heat_timestep + + for name in self._active_recipes.keys(): + if name not in self._heat_steps: + self._heat_steps[name] = 0 + self._last_heat_timestep[name] = -1 + + def _validate_recipe_fillables_exist(self, recipe): + """ + Validates that recipe @recipe's necessary fillable categorie(s) exist in the current scene + + Args: + recipe (dict): Recipe whose fillable categories should be checked + + Returns: + bool: True if there is at least a single valid fillable category in the current scene, else False + """ + fillable_categories = recipe["fillable_categories"] + if fillable_categories is None: + # Any is valid + return True + # Otherwise, at least one valid type must exist + for category in fillable_categories: + if len(self.scene.object_registry("category", category, default_val=set())) > 0: + return True + + # None found, return False + return False + + def _validate_recipe_heatsources_exist(self, recipe): + """ + Validates that recipe @recipe's necessary heatsource categorie(s) exist in the current scene + + Args: + recipe (dict): Recipe whose heatsource categories should be checked + + Returns: + bool: True if there is at least a single valid heatsource category in the current scene, else False + """ + heatsource_categories = recipe["heatsource_categories"] + if heatsource_categories is None: + # Any is valid + return True + # Otherwise, at least one valid type must exist + for category in heatsource_categories: + if len(self.scene.object_registry("category", category, default_val=set())) > 0: + return True + + # None found, return False + return False + + def _validate_recipe_heatsource_is_valid(self, recipe, heatsource_categories): + """ + Validates that there is a valid heatsource category in @heatsource_categories compatible with @recipe + + Args: + recipe (dict): Recipe whose heatsource_categories should be checked against @heatsource_categories + heatsource_categories (set of str): Set of potential heatsource categories + + Returns: + bool: True if there is a compatible category in @heatsource_categories, else False + """ + required_heatsource_categories = recipe["heatsource_categories"] + # Either no specific required and there is at least 1 heatsource or there is at least 1 matching heatsource + # between the required and available + return (required_heatsource_categories is None and len(heatsource_categories) > 0) or len( + required_heatsource_categories.intersection(heatsource_categories) + ) > 0 + + def _compute_container_info(self, object_candidates, container, global_info): + # Run super first + info = super()._compute_container_info( + object_candidates=object_candidates, container=container, global_info=global_info + ) + + # Compute whether each heatsource is affecting the container + info["heatsource_categories"] = set( + obj.category + for obj in object_candidates["heatSource"] + if obj.states[HeatSourceOrSink].affects_obj(container) + ) + + return info + + def _is_recipe_active(self, recipe): + # Check for heatsource categories first + if not self._validate_recipe_heatsources_exist(recipe=recipe): + return False + + # Otherwise, run super normally + return super()._is_recipe_active(recipe=recipe) + + def _is_recipe_executable(self, recipe, container, global_info, container_info): + # Check for heatsource compatibility first + if not self._validate_recipe_heatsource_is_valid( + recipe=recipe, heatsource_categories=container_info["heatsource_categories"] + ): + return False + + # Run super + executable = super()._is_recipe_executable( + recipe=recipe, + container=container, + global_info=global_info, + container_info=container_info, + ) + + # If executable, increment heat counter by 1, if we were also active last timestep, else, reset to 1 + if executable: + name = recipe["name"] + self._heat_steps[name] = ( + self._heat_steps[name] + 1 if self._last_heat_timestep[name] == self.counter - 1 else 1 + ) + self._last_heat_timestep[name] = self.counter + + # If valid number of timesteps met, recipe is indeed executable + executable = self._heat_steps[name] >= recipe["timesteps"] + + return executable + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + input_states=None, + output_states=None, + fillable_categories=None, + heatsource_categories=None, + timesteps=None, + ): + """ + Adds a recipe to this cooking recipe rule to check against. This defines a valid mapping of inputs that + will transform into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + input_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute + output_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system"] to a list of states that should be set after the output objects are spawned + fillable_categories (None or set of str): If specified, set of fillable categories which are allowed + for this recipe. If None, any fillable is allowed + heatsource_categories (None or set of str): If specified, set of heatsource categories which are allowed + for this recipe. If None, any heatsource is allowed + timesteps (None or int): Number of subsequent heating steps required for the recipe to execute. If None, + it will be set to be 1, i.e.: instantaneous execution + """ + super().add_recipe( + name=name, + input_objects=input_objects, + input_systems=input_systems, + output_objects=output_objects, + output_systems=output_systems, + input_states=input_states, + output_states=output_states, + fillable_categories=fillable_categories, + heatsource_categories=heatsource_categories, + timesteps=1 if timesteps is None else timesteps, + ) + + @classproperty + def candidate_filters(cls): + # Add mixing tool filter as well + candidate_filters = super().candidate_filters + candidate_filters["heatSource"] = AbilityFilter(ability="heatSource") + return candidate_filters + + def _generate_conditions(self): + # Define a class to increment this class's internal time counter every time it is triggered + class TimeIncrementCondition(RuleCondition): + def __init__(self, rule): + self.rule = rule + + def __call__(self, object_candidates): + # This is just a pass-through, but also increment the time + self.rule.counter += 1 + return True + + def modifies_filter_names(self): + return set() + + # Any heatsource must be active + return [ + TimeIncrementCondition(rule=self), + StateCondition(filter_name="heatSource", state=HeatSourceOrSink, val=True, op=operator.eq), + ] + + @classproperty + def use_garbage_fallback_recipe(cls): + return False + + @classproperty + def _do_not_register_classes(cls): + # Don't register this class since it's an abstract template + classes = super()._do_not_register_classes + classes.add("CookingRule") + return classes + + +class CookingObjectRule(CookingRule): + """ + Cooking rule when output is objects (e.g. one dough can produce many bagels as output). + Example: bagel_dough + egg + sesame_seed -> bagel, heat source is oven, fillable is baking_sheet. + This is the only rule where is_multi_instance is True, where multiple copies of the recipe can be executed. + """ + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + input_states=None, + output_states=None, + fillable_categories=None, + heatsource_categories=None, + timesteps=None, + ): + """ + Adds a recipe to this cooking recipe rule to check against. This defines a valid mapping of inputs that + will transform into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + input_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute + output_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system"] to a list of states that should be set after the output objects are spawned + fillable_categories (None or set of str): If specified, set of fillable categories which are allowed + for this recipe. If None, any fillable is allowed + heatsource_categories (None or set of str): If specified, set of heatsource categories which are allowed + for this recipe. If None, any heatsource is allowed + timesteps (None or int): Number of subsequent heating steps required for the recipe to execute. If None, + it will be set to be 1, i.e.: instantaneous execution + """ + assert len(output_systems) == 0, f"No output systems can be specified for {cls.__name__}, recipe: {name}!" + super().add_recipe( + name=name, + input_objects=input_objects, + input_systems=input_systems, + output_objects=output_objects, + output_systems=output_systems, + input_states=input_states, + output_states=output_states, + fillable_categories=fillable_categories, + heatsource_categories=heatsource_categories, + timesteps=timesteps, + ) + + @classproperty + def relax_recipe_systems(cls): + # We don't require systems like seasoning/cheese/sesame seeds/etc. to be contained in the baking sheet + return True + + @classproperty + def ignore_nonrecipe_systems(cls): + return True + + @classproperty + def ignore_nonrecipe_objects(cls): + return True + + @classproperty + def is_multi_instance(cls): + return True + + +class CookingSystemRule(CookingRule): + """ + Cooking rule when output is a system. + Example: beef + tomato + chicken_stock -> stew, heat source is stove, fillable is stockpot. + """ + + @classmethod + def add_recipe( + cls, + name, + input_objects, + input_systems, + output_objects, + output_systems, + input_states=None, + output_states=None, + fillable_categories=None, + heatsource_categories=None, + timesteps=None, + ): + """ + Adds a recipe to this cooking recipe rule to check against. This defines a valid mapping of inputs that + will transform into the outputs + + Args: + name (str): Name of the recipe + input_objects (dict): Maps object categories to number of instances required for the recipe + input_systems (list): List of system names required for the recipe + output_objects (dict): Maps object categories to number of instances to be spawned in the container when the recipe executes + output_systems (list): List of system names to be spawned in the container when the recipe executes. Currently the length is 1. + input_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute + output_states (None or defaultdict(lambda: defaultdict(list))): Maps object categories to + ["unary", "bianry_system"] to a list of states that should be set after the output objects are spawned + fillable_categories (None or set of str): If specified, set of fillable categories which are allowed + for this recipe. If None, any fillable is allowed + heatsource_categories (None or set of str): If specified, set of heatsource categories which are allowed + for this recipe. If None, any heatsource is allowed + timesteps (None or int): Number of subsequent heating steps required for the recipe to execute. If None, + it will be set to be 1, i.e.: instantaneous execution + """ + assert len(output_objects) == 0, f"No output objects can be specified for {cls.__name__}, recipe: {name}!" + super().add_recipe( + name=name, + input_objects=input_objects, + input_systems=input_systems, + output_objects=output_objects, + output_systems=output_systems, + input_states=input_states, + output_states=output_states, + fillable_categories=fillable_categories, + heatsource_categories=heatsource_categories, + timesteps=timesteps, + ) + + @classproperty + def relax_recipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_systems(cls): + return False + + @classproperty + def ignore_nonrecipe_objects(cls): + return False + + +_RECIPES_IMPORTED = False + + +def import_recipes(): + global _RECIPES_IMPORTED + if _RECIPES_IMPORTED: + return + + # Import all recipes from the shared KnowledgeBase + for tr in get_knowledge_base().all_transition_rules(): + if tr.recipe is None: + continue + og_recipe = translate_bddl_recipe_to_og_recipe(tr.recipe) + + if isinstance(tr.recipe, CookingRecipe): + has_output_system = len(og_recipe["output_systems"]) > 0 + if has_output_system: + CookingSystemRule.add_recipe(**og_recipe) + else: + CookingObjectRule.add_recipe(**og_recipe) + elif isinstance(tr.recipe, MixingRecipe): + MixingToolRule.add_recipe(**og_recipe) + elif isinstance(tr.recipe, MachineRecipe): + ToggleableMachineRule.add_recipe(**og_recipe) + elif isinstance(tr.recipe, SubstanceCookingRecipe): + CookingPhysicalParticleRule.add_recipe(**og_recipe) + + # Washer rule + if get_knowledge_base().washer_rule is not None: + WasherRule.register_cleaning_conditions( + translate_bddl_washer_rule_to_og_washer_rule(get_knowledge_base().washer_rule) + ) + + _RECIPES_IMPORTED = True diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_conversion_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_conversion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9be094cf217b797f0b1631ad9d4efbc26dc2bc0f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_conversion_utils.py @@ -0,0 +1,2592 @@ +import io +import json +import math +import os +import pathlib +import shutil +import xml.etree.ElementTree as ET +from collections import OrderedDict +from copy import deepcopy +from datetime import datetime +from pathlib import Path +from xml.dom import minidom + +import click +import torch as th +import trimesh + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.objects import DatasetObject +from omnigibson.prims.material_prim import MaterialPrim +from omnigibson.scenes import Scene +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.urdfpy_utils import URDF +from omnigibson.utils.usd_utils import create_primitive_mesh +from omnigibson.utils.urdf_preprocessing import link_has_dedicated_collision +# from omnigibson.utils.python_utils import assert_valid_key + +# Create module logger +log = create_module_logger(module_name=__name__) + +_LIGHT_MAPPING = { + 0: "Rect", + 2: "Sphere", + 4: "Disk", +} + +_OBJECT_STATE_TEXTURES = { + "burnt", + "cooked", + "frozen", + "soaked", + "toggledon", +} + +_MTL_MAP_TYPE_MAPPINGS = { + "map_Kd": "diffuse", + "map_bump": "normal", + "map_Pm": "metalness", + "map_Pr": "glossiness", + "map_Tf": "refraction", + "map_Ks": "reflection", + "map_Ns": "reflection_ior", +} + +_META_LINK_RENAME_MAPPING = { + "fillable": "container", + "fluidsink": "particlesink", + "fluidsource": "particlesource", +} + +_ALLOWED_META_TYPES = { + "particlesource": "dimensionless", + "togglebutton": "primitive", + "attachment": "dimensionless", + "heatsource": "dimensionless", + "particleapplier": "primitive", + "particleremover": "primitive", + "particlesink": "primitive", + "slicer": "primitive", + "container": "primitive", + "collision": "convexmesh", + "lights": "light", +} + +_OPACITY_CATEGORIES = {"tree", "low_resolution_tree", "bush"} + +_VISUAL_ONLY_CATEGORIES = { + "carpet", +} + +_ALLOW_INSTANCING = False + + +class _TorchEncoder(json.JSONEncoder): + """ + Custom JSON encoder for PyTorch tensors. + + This encoder converts PyTorch tensors to lists, making them JSON serializable. + + Methods: + default(o): Overrides the default method to handle PyTorch tensors. + """ + + def default(self, o): + if isinstance(o, th.Tensor): + return o.tolist() + return json.JSONEncoder.default(self, o) + + +def _space_string_to_tensor(string): + """ + Converts a space-separated string of numbers into a PyTorch tensor. + + Examples: + "0 1 2" => tensor([0., 1., 2.]) + + Args: + string (str): Space-separated string of numbers to convert. + + Returns: + torch.Tensor: Tensor containing the numerical values from the input string. + """ + return th.tensor([float(x) for x in string.split(" ") if len(x) > 0]) + + +def _tensor_to_space_script(array): + """ + Converts a numeric array into the string format in mujoco. + + Examples: + [0, 1, 2] => "0 1 2" + + Args: + array (th.Tensor): Array to convert to a string + + Returns: + str: String equivalent of @array + """ + return " ".join(["{}".format(x) for x in array.tolist()]) + + +def _rename_prim(prim, name): + """ + Renames a given prim to a new name. + + Args: + prim (Usd.Prim): The prim to be renamed. + name (str): The new name for the prim. + + Returns: + Usd.Prim: The renamed prim at the new path. + """ + path_from = prim.GetPrimPath().pathString + path_to = f"{'/'.join(path_from.split('/')[:-1])}/{name}" + lazy.omni.kit.commands.execute("MovePrim", path_from=path_from, path_to=path_to) + return lazy.isaacsim.core.utils.prims.get_prim_at_path(path_to) + + +def _get_visual_objs_from_urdf(urdf_path): + """ + Extracts visual objects from a URDF file. + + Args: + urdf_path (str): Path to the URDF file. + + Returns: + OrderedDict: A dictionary mapping link names to dictionaries of visual meshes. Each link name (e.g., 'base_link') + maps to another dictionary where the keys are visual mesh names and the values are the corresponding + visual object file paths. If no visual object file is found for a mesh, the value will be None. + """ + visual_objs = OrderedDict() + # Parse URDF + tree = ET.parse(urdf_path) + root = tree.getroot() + for ele in root: + if ele.tag == "link": + name = ele.get("name").replace("-", "_") + if name.startswith("meta__"): + continue + visual_objs[name] = OrderedDict() + for sub_ele in ele: + if sub_ele.tag == "visual": + visual_mesh_name = sub_ele.get("name", "").replace("-", "_") + if not visual_mesh_name: + visual_mesh_name = None + obj_file = None if sub_ele.find(".//mesh") is None else sub_ele.find(".//mesh").get("filename") + if obj_file is None: + log.debug(f"Warning: No obj file found associated with {name}/{visual_mesh_name}!") + assert ( + visual_mesh_name not in visual_objs[name] + ), f"Visual mesh name {visual_mesh_name} already exists for link {name}!" + visual_objs[name][visual_mesh_name] = obj_file + + return visual_objs + + +def _force_asset_pipeline_materials(obj_prim, obj_category, obj_model, usd_path, dataset_root): + """ + Updates the object to use V-Ray materials rendered through the asset pipeline instead of + its currently assigned materials. + + This function performs the following steps: + 1. Removes existing material prims from the object. + 2. Extracts visual objects and their associated material files from the object's URDF file. + 3. Copies material files to the USD directory and creates new materials. + 4. Applies rendering channels to the new materials. + 5. Binds the new materials to the visual meshes of the object. + 6. Copies state-conditioned texture maps (e.g., cooked, soaked) for the object. + + Args: + obj_prim (Usd.Prim): The USD prim representing the object. + obj_category (str): The category of the object (e.g., "ceilings", "walls"). + obj_model (str): The model name of the object. + usd_path (str): The path to the USD file. + dataset_root (str): The root path of the dataset containing the object files. + + Raises: + AssertionError: If more than one material file is found in an OBJ file. + AssertionError: If a valid visual prim is not found for a mesh. + """ + usd_dir = os.path.dirname(usd_path) + + # Remove the material prims as we will create them explictly later. + stage = lazy.omni.usd.get_context().get_stage() + for prim in obj_prim.GetChildren(): + looks_prim = None + if prim.GetName() == "Looks": + looks_prim = prim + elif prim.GetPrimTypeInfo().GetTypeName() == "Xform": + looks_prim_path = f"{str(prim.GetPrimPath())}/Looks" + looks_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(looks_prim_path) + if not looks_prim: + continue + for subprim in looks_prim.GetChildren(): + if subprim.GetPrimTypeInfo().GetTypeName() != "Material": + continue + log.debug( + f"Removed material prim {subprim.GetPath()}:", + stage.RemovePrim(subprim.GetPath()), + ) + + # Remove the materials copied over by the URDF importer + urdf_importer_mtl_dir = os.path.join(usd_dir, "materials") + if os.path.exists(urdf_importer_mtl_dir): + shutil.rmtree(urdf_importer_mtl_dir) + + # Grab all visual objs for this object + urdf_path = f"{dataset_root}/objects/{obj_category}/{obj_model}/urdf/{obj_model}_with_meta_links.urdf" + visual_objs = _get_visual_objs_from_urdf(urdf_path) + + # Extract absolute paths to mtl files for each link + link_mtl_files = OrderedDict() # maps link name to dictionary mapping mesh name to mtl file + mtl_infos = OrderedDict() # maps mtl name to dictionary mapping material channel name to png file + for link_name, link_meshes in visual_objs.items(): + link_mtl_files[link_name] = OrderedDict() + for mesh_name, obj_file in link_meshes.items(): + # Get absolute path and open the obj file if it exists: + if obj_file is not None: + obj_path = os.path.abspath(f"{dataset_root}/objects/{obj_category}/{obj_model}/urdf/{obj_file}") + with open(obj_path, "r") as f: + mtls = [] + for line in f.readlines(): + if "mtllib" in line and line[0] != "#": + mtls.append(line.split("mtllib ")[-1].split("\n")[0]) + + if mtls: + assert len(mtls) == 1, f"Only one mtl is supported per obj file in omniverse -- found {len(mtls)}!" + mtl = mtls[0] + # TODO: Make name unique + mtl_name = ".".join(os.path.basename(mtl).split(".")[:-1]).replace("-", "_").replace(".", "_") + mtl_dir = os.path.dirname(obj_path) + link_mtl_files[link_name][mesh_name] = mtl_name + mtl_infos[mtl_name] = OrderedDict() + # Open the mtl file + mtl_path = os.path.join(mtl_dir, mtl) + with open(mtl_path, "r") as f: + # Read any lines beginning with map that aren't commented out + for line in f.readlines(): + if line[:4] == "map_": + map_type, map_path_relative_to_mtl_dir = line.split(" ") + map_path_relative_to_mtl_dir = map_path_relative_to_mtl_dir.split("\n")[0] + print("Found map path in file as ", map_path_relative_to_mtl_dir) + map_path_absolute = os.path.abspath(os.path.join(mtl_dir, map_path_relative_to_mtl_dir)) + print("Absolute map path is ", map_path_absolute) + map_path_relative_to_usd_dir = os.path.relpath(map_path_absolute, usd_dir) + print("USD path is ", usd_dir) + print("Material path relative to USD is", map_path_relative_to_usd_dir) + mtl_infos[mtl_name][_MTL_MAP_TYPE_MAPPINGS[map_type]] = map_path_relative_to_usd_dir + + print("Found material file:", mtl_name, mtl_infos[mtl_name]) + + # Next, for each material information, we create a new material + shaders = OrderedDict() # maps mtl name to shader prim + for mtl_name, mtl_info in mtl_infos.items(): + # Create the Vray material + mtl_created_list = [] + print(f"Creating Vray material {mtl_name}...") + lazy.omni.kit.commands.execute( + "CreateAndBindMdlMaterialFromLibrary", + mdl_name="omnigibson_vray_mtl.mdl", + mtl_name="OmniGibsonVRayMtl", + mtl_created_list=mtl_created_list, + ) + vray_mat = lazy.omni.isaac.core.utils.prims.get_prim_at_path(mtl_created_list[0]) + + # Apply all rendering channels for this material + for mat_type, mat_file in mtl_info.items(): + lazy.omni.usd.create_material_input( + vray_mat, f"{mat_type}_texture", mat_file, lazy.pxr.Sdf.ValueTypeNames.Asset + ) + + # Rename material + shade = lazy.pxr.UsdShade.Material(vray_mat) + shaders[mtl_name] = shade + + # Bind each (visual) mesh to its appropriate material in the object + # We'll loop over each link, create a list of 2-tuples each consisting of (mesh_prim_path, mtl_name) to be bound + root_prim_path = obj_prim.GetPrimPath().pathString + for link_name, mesh_mtl_names in link_mtl_files.items(): + for mesh_name, mtl_name in mesh_mtl_names.items(): + if mesh_name is not None: + # Omni only accepts a-z, A-Z as valid start characters for prim names + # So we check if there is an invalid character, and modify it as we know Omni does + if not ord("a") <= ord(mesh_name[0]) <= ord("z") and not ord("A") <= ord(mesh_name[0]) <= ord("Z"): + mesh_name = "a_" + mesh_name[1:] + mesh_prim_path = f"{root_prim_path}/{link_name}/visuals/{mesh_name}" + visual_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(mesh_prim_path) + assert visual_prim, f"Error: Did not find valid visual prim at {mesh_prim_path}!" + else: + visuals_scope_prim_path = f"{root_prim_path}/{link_name}/visuals" + visuals_scope_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(visuals_scope_prim_path) + assert visuals_scope_prim, f"Error: Did not find valid visuals scope prim at {visuals_scope_prim_path}!" + (visual_prim,) = visuals_scope_prim.GetChildren() + assert visual_prim, f"Error: Did not find valid visual prim at {visuals_scope_prim_path}!" + + # Bind the created link material to the visual prim + log.debug( + f"Binding material {mtl_name}, shader {shaders[mtl_name]}, to prim {visual_prim.GetPath().pathString}..." + ) + lazy.pxr.UsdShade.MaterialBindingAPI(visual_prim).Bind( + shaders[mtl_name], lazy.pxr.UsdShade.Tokens.strongerThanDescendants + ) + + +def _add_xform_properties(prim): + """ + Adds and configures transformation properties for a given USD prim. + + This function ensures that the specified USD prim has the necessary transformation + properties (scale, translate, and orient) and removes any unwanted transformation + properties. It also sets the order of the transformation operations. + + Args: + prim (pxr.Usd.Prim): The USD prim to which the transformation properties will be added. + + Notes: + - The function removes the following properties if they exist: + "xformOp:rotateX", "xformOp:rotateXZY", "xformOp:rotateY", "xformOp:rotateYXZ", + "xformOp:rotateYZX", "xformOp:rotateZ", "xformOp:rotateZYX", "xformOp:rotateZXY", + "xformOp:rotateXYZ", "xformOp:transform". + - If the prim does not have "xformOp:scale", "xformOp:translate", or "xformOp:orient", + these properties are added with default values. + - The order of the transformation operations is set to translate, orient, and scale. + """ + properties_to_remove = [ + "xformOp:rotateX", + "xformOp:rotateXZY", + "xformOp:rotateY", + "xformOp:rotateYXZ", + "xformOp:rotateYZX", + "xformOp:rotateZ", + "xformOp:rotateZYX", + "xformOp:rotateZXY", + "xformOp:rotateXYZ", + "xformOp:transform", + ] + prop_names = prim.GetPropertyNames() + xformable = lazy.pxr.UsdGeom.Xformable(prim) + xformable.ClearXformOpOrder() + # TODO: wont be able to delete props for non root links on articulated objects + for prop_name in prop_names: + if prop_name in properties_to_remove: + prim.RemoveProperty(prop_name) + if "xformOp:scale" not in prop_names: + xform_op_scale = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeScale, + lazy.pxr.UsdGeom.XformOp.PrecisionDouble, + "", + ) + xform_op_scale.Set(lazy.pxr.Gf.Vec3d([1.0, 1.0, 1.0])) + else: + xform_op_scale = lazy.pxr.UsdGeom.XformOp(prim.GetAttribute("xformOp:scale")) + + if "xformOp:translate" not in prop_names: + xform_op_translate = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeTranslate, + lazy.pxr.UsdGeom.XformOp.PrecisionDouble, + "", + ) + else: + xform_op_translate = lazy.pxr.UsdGeom.XformOp(prim.GetAttribute("xformOp:translate")) + + if "xformOp:orient" not in prop_names: + xform_op_rot = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeOrient, + lazy.pxr.UsdGeom.XformOp.PrecisionDouble, + "", + ) + else: + xform_op_rot = lazy.pxr.UsdGeom.XformOp(prim.GetAttribute("xformOp:orient")) + xformable.SetXformOpOrder([xform_op_translate, xform_op_rot, xform_op_scale]) + + +def _generate_meshes_for_primitive_meta_links(stage, obj_model, link_name, meta_link_type, meta_link_infos): + """ + Process a meta link by creating visual meshes or lights below it. + + Args: + stage (pxr.Usd.Stage): The USD stage where the meta link will be processed. + obj_model (str): The object model name. + link_name (str): Name of the meta link's parent link (e.g. what part of the object the meta link is attached to). + meta_link_type (str): The type of the meta link. Must be one of the allowed meta types. + meta_link_infos (dict): A dictionary containing meta link information. The keys are link IDs and the values are lists of mesh information dictionaries. + + Returns: + None + + Raises: + AssertionError: If the meta_link_type is not in the allowed meta types or if the mesh_info_list has unexpected keys or invalid number of meshes. + ValueError: If an invalid light type or mesh type is encountered. + + Notes: + - Handles specific meta link types such as "togglebutton", "particleapplier", "particleremover", "particlesink", and "particlesource". + - For "particleapplier" meta link type, adjusts the orientation if the mesh type is "cone". + - Creates lights or primitive shapes based on the meta link type and mesh information. + - Sets various attributes for lights and meshes, including color, intensity, size, and scale. + - Makes meshes invisible and sets their local pose. + """ + assert meta_link_type in _ALLOWED_META_TYPES + if _ALLOWED_META_TYPES[meta_link_type] not in ["primitive", "light"] and meta_link_type != "particlesource": + return + + is_light = _ALLOWED_META_TYPES[meta_link_type] == "light" + + for link_id, mesh_info_list in meta_link_infos.items(): + if len(mesh_info_list) == 0: + continue + + # TODO: Remove this after this is fixed. + if type(mesh_info_list) is dict: + keys = [str(x) for x in range(len(mesh_info_list))] + assert set(mesh_info_list.keys()) == set(keys), "Unexpected keys" + mesh_info_list = [mesh_info_list[k] for k in keys] + + if meta_link_type in [ + "togglebutton", + "particleapplier", + "particleremover", + "particlesink", + "particlesource", + ]: + assert len(mesh_info_list) == 1, f"Invalid number of meshes for {meta_link_type}" + + meta_link_in_parent_link_pos, meta_link_in_parent_link_orn = ( + th.tensor(mesh_info_list[0]["position"]), + th.tensor(mesh_info_list[0]["orientation"]), + ) + + # For particle applier only, the orientation of the meta link matters (particle should shoot towards the negative z-axis) + # If the meta link is created based on the orientation of the first mesh that is a cone, we need to rotate it by 180 degrees + # because the cone is pointing in the wrong direction. This is already done in update_obj_urdf_with_meta_links; + # we just need to make sure meta_link_in_parent_link_orn is updated correctly. + if meta_link_type == "particleapplier" and mesh_info_list[0]["type"] == "cone": + meta_link_in_parent_link_orn = T.quat_multiply( + meta_link_in_parent_link_orn, T.axisangle2quat(th.tensor([math.pi, 0.0, 0.0])) + ) + + for i, mesh_info in enumerate(mesh_info_list): + is_mesh = False + if is_light: + # Create a light + light_type = _LIGHT_MAPPING[mesh_info["type"]] + stage.DefinePrim(f"/{obj_model}/meta__{link_name}_lights_{link_id}_0_link/lights", "Scope") + prim_path = f"/{obj_model}/meta__{link_name}_lights_{link_id}_0_link/lights/light_{i}" + prim = getattr(lazy.pxr.UsdLux, f"{light_type}Light").Define(stage, prim_path).GetPrim() + lazy.pxr.UsdLux.ShapingAPI.Apply(prim).GetShapingConeAngleAttr().Set(180.0) + else: + if meta_link_type == "particlesource": + mesh_type = "Cylinder" + else: + # Create a primitive shape + mesh_type = mesh_info["type"].capitalize() if mesh_info["type"] != "box" else "Cube" + # Create the visuals prim + stage.DefinePrim(f"/{obj_model}/meta__{link_name}_{meta_link_type}_{link_id}_0_link/visuals", "Scope") + prim_path = f"/{obj_model}/meta__{link_name}_{meta_link_type}_{link_id}_0_link/visuals/mesh_{i}" + assert hasattr(lazy.pxr.UsdGeom, mesh_type) + # togglebutton has to be a sphere + if meta_link_type in ["togglebutton"]: + is_mesh = True + # particle applier has to be a cone or cylinder because of the visualization of the particle flow + elif meta_link_type in ["particleapplier"]: + assert mesh_type in [ + "Cone", + "Cylinder", + ], f"Invalid mesh type for particleapplier: {mesh_type}" + prim = ( + create_primitive_mesh(prim_path, mesh_type, stage=stage).GetPrim() + if is_mesh + else getattr(lazy.pxr.UsdGeom, mesh_type).Define(stage, prim_path).GetPrim() + ) + + _add_xform_properties(prim=prim) + + # Get the mesh/light pose in the parent link frame + mesh_in_parent_link_pos, mesh_in_parent_link_orn = ( + th.tensor(mesh_info["position"]), + th.tensor(mesh_info["orientation"]), + ) + + # Get the mesh/light pose in the meta link frame + mesh_in_parent_link_tf = th.eye(4) + mesh_in_parent_link_tf[:3, :3] = T.quat2mat(mesh_in_parent_link_orn) + mesh_in_parent_link_tf[:3, 3] = mesh_in_parent_link_pos + meta_link_in_parent_link_tf = th.eye(4) + meta_link_in_parent_link_tf[:3, :3] = T.quat2mat(meta_link_in_parent_link_orn) + meta_link_in_parent_link_tf[:3, 3] = meta_link_in_parent_link_pos + mesh_in_meta_link_tf = th.linalg.inv(meta_link_in_parent_link_tf) @ mesh_in_parent_link_tf + mesh_in_meta_link_pos, mesh_in_meta_link_orn = ( + mesh_in_meta_link_tf[:3, 3], + T.mat2quat(mesh_in_meta_link_tf[:3, :3]), + ) + + if is_light: + prim.GetAttribute("inputs:color").Set( + lazy.pxr.Gf.Vec3f(*(th.tensor(mesh_info["color"]) / 255.0).tolist()) + ) + prim.GetAttribute("inputs:intensity").Set(mesh_info["intensity"]) + if light_type == "Rect": + prim.GetAttribute("inputs:width").Set(mesh_info["length"]) + prim.GetAttribute("inputs:height").Set(mesh_info["width"]) + elif light_type == "Disk": + prim.GetAttribute("inputs:radius").Set(mesh_info["length"]) + elif light_type == "Sphere": + prim.GetAttribute("inputs:radius").Set(mesh_info["length"]) + else: + raise ValueError(f"Invalid light type: {light_type}") + else: + if mesh_type == "Cylinder": + if not is_mesh: + prim.GetAttribute("radius").Set(0.5) + prim.GetAttribute("height").Set(1.0) + if meta_link_type == "particlesource": + desired_radius = 0.0125 + desired_height = 0.05 + height_offset = -desired_height / 2.0 + else: + desired_radius = mesh_info["size"][0] + desired_height = mesh_info["size"][2] + height_offset = desired_height / 2.0 + prim.GetAttribute("xformOp:scale").Set( + lazy.pxr.Gf.Vec3f(desired_radius * 2, desired_radius * 2, desired_height) + ) + # Offset the position by half the height because in 3dsmax the origin of the cylinder is at the center of the base + mesh_in_meta_link_pos += T.quat_apply(mesh_in_meta_link_orn, th.tensor([0.0, 0.0, height_offset])) + elif mesh_type == "Cone": + if not is_mesh: + prim.GetAttribute("radius").Set(0.5) + prim.GetAttribute("height").Set(1.0) + desired_radius = mesh_info["size"][0] + desired_height = mesh_info["size"][2] + height_offset = -desired_height / 2.0 + prim.GetAttribute("xformOp:scale").Set( + lazy.pxr.Gf.Vec3f(desired_radius * 2, desired_radius * 2, desired_height) + ) + # Flip the orientation of the z-axis because in 3dsmax the cone is pointing in the opposite direction + mesh_in_meta_link_orn = T.quat_multiply( + mesh_in_meta_link_orn, T.axisangle2quat(th.tensor([math.pi, 0.0, 0.0])) + ) + # Offset the position by half the height because in 3dsmax the origin of the cone is at the center of the base + mesh_in_meta_link_pos += T.quat_apply(mesh_in_meta_link_orn, th.tensor([0.0, 0.0, height_offset])) + elif mesh_type == "Cube": + if not is_mesh: + prim.GetAttribute("size").Set(1.0) + prim.GetAttribute("xformOp:scale").Set(lazy.pxr.Gf.Vec3f(*mesh_info["size"])) + height_offset = mesh_info["size"][2] / 2.0 + mesh_in_meta_link_pos += T.quat_apply(mesh_in_meta_link_orn, th.tensor([0.0, 0.0, height_offset])) + elif mesh_type == "Sphere": + if not is_mesh: + prim.GetAttribute("radius").Set(0.5) + desired_radius = mesh_info["size"][0] + prim.GetAttribute("xformOp:scale").Set( + lazy.pxr.Gf.Vec3f(desired_radius * 2, desired_radius * 2, desired_radius * 2) + ) + else: + raise ValueError(f"Invalid mesh type: {mesh_type}") + + # Set local pose directly on the USD xform ops added by + # _add_xform_properties. Quaternion is reordered to (w, x, y, z) + # to match Gf.Quatd's constructor. + prim.GetAttribute("xformOp:translate").Set(lazy.pxr.Gf.Vec3d(*mesh_in_meta_link_pos.tolist())) + prim.GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*mesh_in_meta_link_orn[[3, 0, 1, 2]].tolist())) + + +def _process_glass_link(prim): + """ + Processes the given USD prim to update any glass parts to use the glass material. + + This function traverses the children of the given prim to find any Mesh-type prims + that do not have a CollisionAPI, indicating they are visual elements. It collects + the paths of these prims and ensures they are bound to a glass material. + + Args: + prim (pxr.Usd.Prim): The USD prim to process. + + Raises: + AssertionError: If no glass prim paths are found. + """ + # Update any glass parts to use the glass material instead. We walk all + # descendants because convert_urdf_to_usd nests visual meshes under a + # `visuals` Xform child (e.g. /{model}/{link}/visuals/) — the + # old fixed-depth walk only matched meshes sitting directly under the + # link or under a Scope and missed those. + glass_prim_paths = [ + descendant.GetPath().pathString + for descendant in lazy.pxr.Usd.PrimRange(prim.GetChild("visuals")) + if descendant.GetTypeName() == "Mesh" + ] + + assert glass_prim_paths, f"No visual Mesh prims found under {prim.GetPath()}" + + stage = lazy.isaacsim.core.utils.stage.get_current_stage() + root_path = stage.GetDefaultPrim().GetPath().pathString + glass_mtl_prim_path = f"{root_path}/Looks/OmniGlass" + if not lazy.isaacsim.core.utils.prims.get_prim_at_path(glass_mtl_prim_path): + mtl_created = [] + lazy.omni.kit.commands.execute( + "CreateAndBindMdlMaterialFromLibrary", + mdl_name="OmniGlass.mdl", + mtl_name="OmniGlass", + mtl_created_list=mtl_created, + ) + + for glass_prim_path in glass_prim_paths: + print(f"Applying glass material {glass_mtl_prim_path} to {glass_prim_path}") + lazy.omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=glass_prim_path, + material_path=glass_mtl_prim_path, + strength=None, + ) + + +def import_obj_metadata(usd_path, obj_category, obj_model, dataset_root, force_asset_pipeline_materials=False): + """ + Imports metadata for a given object model from the dataset. This metadata consist of information + that is NOT included in the URDF file and instead included in the various JSON files shipped in + iGibson and BEHAVIOR-1K datasets. + + Args: + usd_path (str): Path to USD file + obj_category (str): The category of the object. + obj_model (str): The model name of the object. + dataset_root (str): The root directory of the dataset. + force_asset_pipeline_materials (bool, optional): Flag to force the use of asset pipeline materials. Defaults to False. + + Raises: + ValueError: If the bounding box size is not found in the metadata. + + Returns: + bool: Success status of the conversion + """ + usd_path = pathlib.Path(usd_path) + usd_dir = usd_path.parent + model_root_path = usd_dir.parent + + # Load model + lazy.isaacsim.core.utils.stage.open_stage(str(usd_path)) + stage = lazy.isaacsim.core.utils.stage.get_current_stage() + prim = stage.GetDefaultPrim() + + data = dict() + for data_group in {"metadata", "mvbb_meta", "material_groups", "heights_per_link"}: + data_path = model_root_path / f"misc/{data_group}.json" + if data_path.exists(): + # Load data + with open(data_path, "r") as f: + data[data_group] = json.load(f) + + # If certain metadata doesn't exist, populate with some core info + if "base_link_offset" not in data["metadata"]: + data["metadata"]["base_link_offset"] = [0, 0, 0] + if "bbox_size" not in data["metadata"]: + raise ValueError("We cannot work without a bbox size.") + + # Pop bb and base link offset and meta links info + base_link_offset = data["metadata"].pop("base_link_offset") + default_bb = data["metadata"].pop("bbox_size") + + # Manually modify material groups info + if "material_groups" in data: + data["material_groups"] = { + "groups": data["material_groups"][0], + "links": data["material_groups"][1], + } + + # Manually modify metadata + if "openable_joint_ids" in data["metadata"]: + data["metadata"]["openable_joint_ids"] = { + str(pair[0]): pair[1] for pair in data["metadata"]["openable_joint_ids"] + } + + # Grab light info if any + meta_links = data["metadata"].get("meta_links", dict()) + + log.debug("Process meta links") + + # Convert primitive meta links + for link_name, link_metadata in meta_links.items(): + for meta_link_type, meta_link_infos in link_metadata.items(): + _generate_meshes_for_primitive_meta_links(stage, obj_model, link_name, meta_link_type, meta_link_infos) + + # Get all meta links, set them to guide purpose, and add some metadata + # Here we want to include every link that has the meta__ prefix. + # This includes meta links that get added into the URDF in earlier + # stages. + meta_link_prims = [ + p for p in prim.GetChildren() if p.GetName().startswith("meta__") and p.GetName().endswith("_link") + ] + for meta_prim in meta_link_prims: + # Get meta link information + unparsed_meta = meta_prim.GetName()[6:-5] # remove meta__ and _link + meta_parts = unparsed_meta.rsplit("_", 3) + assert len(meta_parts) == 4, f"Invalid meta link name: {unparsed_meta}" + link_name, meta_link_type, link_id, link_sub_id = meta_parts + + # Add the is_meta_link, meta_link_type, and meta_link_id attributes + meta_prim.CreateAttribute("ig:isMetaLink", lazy.pxr.Sdf.ValueTypeNames.Bool) + meta_prim.GetAttribute("ig:isMetaLink").Set(True) + meta_prim.CreateAttribute("ig:metaLinkType", lazy.pxr.Sdf.ValueTypeNames.String) + meta_prim.GetAttribute("ig:metaLinkType").Set(meta_link_type) + meta_prim.CreateAttribute("ig:metaLinkId", lazy.pxr.Sdf.ValueTypeNames.String) + meta_prim.GetAttribute("ig:metaLinkId").Set(link_id) + meta_prim.CreateAttribute("ig:metaLinkSubId", lazy.pxr.Sdf.ValueTypeNames.Int) + meta_prim.GetAttribute("ig:metaLinkSubId").Set(int(link_sub_id)) + + # Set the purpose of the visual meshes to be guide + visual_prim = meta_prim.GetChild("visuals") + if visual_prim.IsValid(): + # If it's an imageable, set the purpose to guide + if visual_prim.GetTypeName() == "Mesh": + purpose_attr = lazy.pxr.UsdGeom.Imageable(visual_prim).CreatePurposeAttr() + purpose_attr.Set(lazy.pxr.UsdGeom.Tokens.guide) + for visual_mesh in visual_prim.GetChildren(): + if visual_mesh.GetTypeName() == "Mesh": + purpose_attr = lazy.pxr.UsdGeom.Imageable(visual_mesh).CreatePurposeAttr() + purpose_attr.Set(lazy.pxr.UsdGeom.Tokens.guide) + + log.debug("Done processing meta links") + + # Iterate over dict and replace any lists of dicts as dicts of dicts (with each dict being indexed by an integer) + data = _recursively_replace_list_of_dict(data) + + log.debug("Done recursively replacing") + + # Create attributes for bb, offset, category, model and store values + prim.CreateAttribute("ig:nativeBB", lazy.pxr.Sdf.ValueTypeNames.Vector3f) + prim.CreateAttribute("ig:offsetBaseLink", lazy.pxr.Sdf.ValueTypeNames.Vector3f) + prim.CreateAttribute("ig:category", lazy.pxr.Sdf.ValueTypeNames.String) + prim.CreateAttribute("ig:model", lazy.pxr.Sdf.ValueTypeNames.String) + prim.GetAttribute("ig:nativeBB").Set(lazy.pxr.Gf.Vec3f(*default_bb)) + prim.GetAttribute("ig:offsetBaseLink").Set(lazy.pxr.Gf.Vec3f(*base_link_offset)) + prim.GetAttribute("ig:category").Set(obj_category) + prim.GetAttribute("ig:model").Set(obj_model) + + log.debug(f"data: {data}") + + # Store remaining data as metadata + prim.SetCustomData(data) + + # Add material channels + if force_asset_pipeline_materials: + _force_asset_pipeline_materials( + obj_prim=prim, + obj_category=obj_category, + obj_model=obj_model, + usd_path=str(usd_path), + dataset_root=dataset_root, + ) + for link, link_tags in data["metadata"]["link_tags"].items(): + if "glass" in link_tags: + _process_glass_link(prim.GetChild(link)) + + # Rename model to be named if not already named that + old_prim_path = prim.GetPrimPath().pathString + if old_prim_path.split("/")[-1] != obj_model: + new_prim_path = "/".join(old_prim_path.split("/")[:-1]) + f"/{obj_model}" + lazy.omni.kit.commands.execute("MovePrim", path_from=old_prim_path, path_to=new_prim_path) + prim = stage.GetDefaultPrim() + + # Hacky way to avoid new prim being created at /World + class DummyScene: + prim_path = "" + + og.sim.render() + + mat_prims = find_all_prim_children_with_type(prim_type="Material", root_prim=prim) + for i, mat_prim in enumerate(mat_prims): + mat = MaterialPrim(mat_prim.GetPrimPath().pathString, f"mat{i}") + mat.load(DummyScene) + + # Save stage + stage.Save() + + # Return the root prim + return prim + + +def _recursively_replace_list_of_dict(dic): + """ + Recursively processes a dictionary to replace specific values and structures that can be stored + in USD. + + This function performs the following transformations: + - Replaces `None` values with `lazy.pxr.lazy.pxr.UsdGeom.Tokens.none`. + - Converts empty lists or tuples to `lazy.pxr.Vt.Vec3fArray()`. + - Converts lists of dictionaries to a dictionary with string keys. + - Converts nested lists or tuples to specific `lazy.pxr.Vt` array types based on their length: + - Length 2: `lazy.pxr.Vt.Vec2fArray` + - Length 3: `lazy.pxr.Vt.Vec3fArray` + - Length 4: `lazy.pxr.Vt.Vec4fArray` + - Converts lists of integers to `lazy.pxr.Vt.IntArray`. + - Converts lists of floats to `lazy.pxr.Vt.FloatArray`. + - Replaces `None` values within lists with `lazy.pxr.lazy.pxr.UsdGeom.Tokens.none`. + - Recursively processes nested dictionaries. + + Args: + dic (dict): The dictionary to process. + + Returns: + dict: The processed dictionary with the specified transformations applied. + """ + for k, v in dic.items(): + if v is None: + # Replace None + dic[k] = lazy.pxr.lazy.pxr.UsdGeom.Tokens.none + elif isinstance(v, list) or isinstance(v, tuple): + if len(v) == 0: + dic[k] = lazy.pxr.Vt.Vec3fArray() + elif isinstance(v[0], dict): + # Replace with dict in place + v = {str(i): vv for i, vv in enumerate(v)} + dic[k] = v + elif isinstance(v[0], list) or isinstance(v[0], tuple): + # # Flatten the lists + # dic[k] = [] + # for vv in v: + # dic[k] += vv + if len(v[0]) == 1: + # Do nothing + pass + if len(v[0]) == 2: + dic[k] = lazy.pxr.Vt.Vec2fArray(v) + elif len(v[0]) == 3: + dic[k] = lazy.pxr.Vt.Vec3fArray(v) + elif len(v[0]) == 4: + dic[k] = lazy.pxr.Vt.Vec4fArray(v) + else: + raise ValueError(f"No support for storing matrices of length {len(v[0])}!") + elif isinstance(v[0], int): + dic[k] = lazy.pxr.Vt.IntArray(v) + elif isinstance(v[0], float): + dic[k] = lazy.pxr.Vt.FloatArray(v) + else: + # Replace any Nones + for i, ele in enumerate(v): + if ele is None: + v[i] = lazy.pxr.lazy.pxr.UsdGeom.Tokens.none + if isinstance(v, dict): + # Iterate through nested dictionaries + dic[k] = _recursively_replace_list_of_dict(v) + + return dic + + +def _create_urdf_import_config( + use_convex_decomposition=False, + merge_fixed_joints=False, + import_inertia_tensor=True, +): + """ + Creates and configures a URDF import configuration. + + This function sets up the import configuration for URDF files by executing the + "URDFCreateImportConfig" command and adjusting various settings such as drive type, + joint merging, convex decomposition, base fixing, inertia tensor import, distance scale, + density, drive strength, position drive damping, self-collision, up vector, default prim + creation, and physics scene creation. + + Args: + use_convex_decomposition (bool): Whether to have omniverse use internal convex decomposition + on any collision meshes + merge_fixed_joints (bool): Whether to merge fixed joints or not + import_inertia_tensor (bool): Whether to import the URDF's native inertia tensor or not + + Returns: + import_config: The configured URDF import configuration object. + """ + # Set up import configuration + _, import_config = lazy.omni.kit.commands.execute("URDFCreateImportConfig") + drive_mode = ( + import_config.default_drive_type.__class__ + ) # Hacky way to get class for default drive type, options are JOINT_DRIVE_{NONE / POSITION / VELOCITY} + + import_config.set_merge_fixed_joints(merge_fixed_joints) + import_config.set_convex_decomp(use_convex_decomposition) + import_config.set_fix_base(False) + import_config.set_import_inertia_tensor(import_inertia_tensor) + import_config.set_distance_scale(1.0) + import_config.set_density(0.0) + import_config.set_default_drive_type(drive_mode.JOINT_DRIVE_NONE) + import_config.set_default_drive_strength(0.0) + import_config.set_default_position_drive_damping(0.0) + import_config.set_self_collision(False) + import_config.set_up_vector(0, 0, 1) + import_config.set_make_default_prim(True) + import_config.set_create_physics_scene(True) + return import_config + + +def _migrate_materials_to_looks(stage): + """ + Migrates material prims from the /meshes hierarchy to /Looks hierarchy and updates all material bindings. + + This is necessary for IsaacSim 5.1+ where materials are placed under the /meshes hierarchy, + which gets deleted during post-processing. By moving materials to /Looks, we preserve them + and follow USD best practices. + + Args: + stage (pxr.Usd.Stage): The USD stage containing the materials to migrate + + Returns: + dict: Mapping from old material paths to new material paths + """ + # Get the meshes prim - this is where materials are currently located + meshes_prim = stage.GetPrimAtPath("/meshes") + if not meshes_prim.IsValid(): + log.debug("No /meshes prim found, skipping material migration") + return {} + + # Find all Material prims under /meshes + material_prims = [] + for prim in lazy.pxr.Usd.PrimRange(meshes_prim): + if prim.GetTypeName() == "Material": + material_prims.append(prim) + + if not material_prims: + log.debug("No materials found in /meshes hierarchy") + return {} + + log.debug(f"Found {len(material_prims)} material prims to migrate") + + # Get the /Looks scope + looks_prim = stage.GetDefaultPrim().GetChild("Looks") + looks_path = looks_prim.GetPath() + + # Map from old paths to new paths + material_path_mapping = {} + + # Move each material to /Looks + for material_prim in material_prims: + old_path = material_prim.GetPath() + material_name = material_prim.GetName() + + # Create a unique name in /Looks if there's a conflict + new_path = looks_path.AppendChild(material_name) + counter = 0 + while stage.GetPrimAtPath(new_path).IsValid(): + new_path = looks_path.AppendChild(f"{material_name}_{counter}") + counter += 1 + + # Copy the material prim to the new location + success = lazy.pxr.Sdf.CopySpec(stage.GetRootLayer(), old_path, stage.GetRootLayer(), new_path) + + if success: + material_path_mapping[str(old_path)] = str(new_path) + log.debug(f"Moved material from {old_path} to {new_path}") + else: + log.warning(f"Failed to copy material from {old_path} to {new_path}") + + # Update all material bindings to point to new paths + for prim in stage.Traverse(): + # Check if this prim has material bindings + if lazy.pxr.UsdShade.MaterialBindingAPI.CanApply(prim): + binding_api = lazy.pxr.UsdShade.MaterialBindingAPI(prim) + + # Get direct binding + direct_binding = binding_api.GetDirectBinding() + if direct_binding: + material_path = direct_binding.GetMaterialPath() + material_path_str = str(material_path) + + # If this material was moved, update the binding + if material_path_str in material_path_mapping: + new_material_path = material_path_mapping[material_path_str] + new_material_prim = stage.GetPrimAtPath(new_material_path) + + if new_material_prim.IsValid(): + new_material = lazy.pxr.UsdShade.Material(new_material_prim) + binding_api.Bind(new_material) + log.debug( + f"Updated material binding on {prim.GetPath()} from {material_path_str} to {new_material_path}" + ) + + return material_path_mapping + + +# Prim types that carry authored geometry in the URDF importer output. +_GEOM_TYPES = {"Sphere", "Cube", "Cone", "Cylinder", "Mesh"} + + +def resolve_imported_geometry(referenced_wrapper_prim): + """Return the single mesh-bearing child under an importer wrapper, or None if it's ambiguous. + + The wrapper's name varies by source format (World for OBJ, Scene for DAE, node_STL_BINARY_* for + STL), so we look up the lone Xform child and its "mesh". None means the wrapper should be pruned. + """ + xform_children = [child for child in referenced_wrapper_prim.GetChildren() if child.GetTypeName() == "Xform"] + if len(xform_children) != 1: + return None + child_prim = xform_children[0].GetChild("mesh") + if child_prim is None or not child_prim.IsValid(): + return None + return child_prim + + +def _ensure_geom_xform_ops(prim): + """Add identity translate/orient/scale xformOps (in canonical order) to a geometry prim if missing. + + 5.1 can emit geometry prims with no transform ops, which the downstream AABB re-centering assumes + exist. No-op for non-geometry prims. + """ + if prim.GetTypeName() not in _GEOM_TYPES: + return + + prop_names = prim.GetPropertyNames() + xformable = lazy.pxr.UsdGeom.Xformable(prim) + + if "xformOp:translate" in prop_names: + xform_op_translate = lazy.pxr.UsdGeom.XformOp(prim.GetAttribute("xformOp:translate")) + if prim.GetAttribute("xformOp:translate").Get() is None: + xform_op_translate.Set(lazy.pxr.Gf.Vec3d([0.0, 0.0, 0.0])) + else: + xform_op_translate = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeTranslate, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + xform_op_translate.Set(lazy.pxr.Gf.Vec3d([0.0, 0.0, 0.0])) + + if "xformOp:orient" in prop_names: + xform_op_orient = lazy.pxr.UsdGeom.XformOp(prim.GetAttribute("xformOp:orient")) + if prim.GetAttribute("xformOp:orient").Get() is None: + xform_op_orient.Set(lazy.pxr.Gf.Quatd(1.0, lazy.pxr.Gf.Vec3d([0.0, 0.0, 0.0]))) + else: + xform_op_orient = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeOrient, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + xform_op_orient.Set(lazy.pxr.Gf.Quatd(1.0, lazy.pxr.Gf.Vec3d([0.0, 0.0, 0.0]))) + + if "xformOp:scale" in prop_names: + xform_op_scale = lazy.pxr.UsdGeom.XformOp(prim.GetAttribute("xformOp:scale")) + if prim.GetAttribute("xformOp:scale").Get() is None: + xform_op_scale.Set(lazy.pxr.Gf.Vec3d([1.0, 1.0, 1.0])) + else: + xform_op_scale = xformable.AddXformOp( + lazy.pxr.UsdGeom.XformOp.TypeScale, lazy.pxr.UsdGeom.XformOp.PrecisionDouble, "" + ) + xform_op_scale.Set(lazy.pxr.Gf.Vec3d([1.0, 1.0, 1.0])) + + ordered_ops = xformable.GetOrderedXformOps() + if not ordered_ops: + xformable.SetXformOpOrder([xform_op_translate, xform_op_orient, xform_op_scale]) + + +def convert_urdf_to_usd( + urdf_path, + obj_category, + obj_model, + dataset_root, + use_omni_convex_decomp=False, + use_usda=False, + merge_fixed_joints=False, + import_inertia_tensor=True, +): + """ + Imports an object from a URDF file into the current stage. + + Args: + urdf_path (str): Path to URDF file to import + obj_category (str): The category of the object. + obj_model (str): The model name of the object. + dataset_root (str): Dataset root directory to use for writing imported USD file. + use_omni_convex_decomp (bool): Whether to use omniverse's built-in convex decomposer for collision meshes + use_usda (bool): If set, will write files to .usda files instead of .usd + (bigger memory footprint, but human-readable) + merge_fixed_joints (bool): whether to merge fixed joints or not + import_inertia_tensor (bool): Whether to import the URDF's native inertia tensor or not + + Returns: + 2-tuple: + - str: Absolute path to post-processed URDF file used to generate USD + - str: Absolute path to the imported USD file + """ + # Preprocess input URDF to account for meta links + urdf_path = _add_meta_links_to_urdf( + urdf_path=urdf_path, obj_category=obj_category, obj_model=obj_model, dataset_root=dataset_root + ) + # Import URDF + cfg = _create_urdf_import_config( + use_convex_decomposition=use_omni_convex_decomp, + merge_fixed_joints=merge_fixed_joints, + import_inertia_tensor=import_inertia_tensor, + ) + + # Pre-clear the scene. + og.clear() + + model_root_path = pathlib.Path(dataset_root) / "objects" / obj_category / obj_model + usd_dir = model_root_path / "usd" + usd_filename = obj_model + (".usda" if use_usda else ".usd") + usd_path = usd_dir / usd_filename + log.debug(f"Importing {obj_category}, {obj_model} into path {usd_path}...") + # Only import if it doesn't exist + lazy.omni.kit.commands.execute( + "URDFParseAndImportFile", + urdf_path=urdf_path, + import_config=cfg, + dest_path=str(usd_path), + ) + + # Also clear again to release the file. + og.clear() + + # Find all the relevant files + configuration_dir = usd_dir / "configuration" + physics_usd_path = configuration_dir / f"{obj_model}_physics.usd" + sensor_usd_path = configuration_dir / f"{obj_model}_sensor.usd" + + # Remove the mixed and sensor files + usd_path.unlink() + sensor_usd_path.unlink() + + # Move the materials directory contents + current_materials = configuration_dir / "materials" / "textures" + new_materials = model_root_path / "material" + if current_materials.exists(): + new_materials.mkdir(parents=True, exist_ok=True) + for texture in current_materials.iterdir(): + texture.rename(new_materials / texture.name) + + # Load the physics stage and prepare to flatten it and save it. + physics_stage = lazy.pxr.Usd.Stage.Open(str(physics_usd_path)) + + # Prior to flattening things, we want to remove all instanceable flags and refs. We do this because + # if you flatten with instancing the flatten function ends up duplicating the whole mesh tree. + # We keep track to reenable them post-flattening + instanceable_prims_and_refs = {} + for prim in physics_stage.Traverse(): + arcs = lazy.pxr.Usd.PrimCompositionQuery.GetDirectReferences(prim).GetCompositionArcs() + if not arcs: + continue + assert len(arcs) == 1, f"Expected only one reference arc for {prim.GetPath()}" + instanceable_prims_and_refs[str(prim.GetPath())] = ( + str(arcs[0].GetTargetPrimPath()), + prim.IsInstanceable(), + ) + for instanceable_prim_path, _ in instanceable_prims_and_refs.items(): + instanceable_prim = physics_stage.GetPrimAtPath(instanceable_prim_path) + instanceable_prim.SetInstanceable(False) + instanceable_prim.GetReferences().ClearReferences() + + # Flatten everything and save at the target location. + physics_stage.Flatten() + physics_stage.Export(str(usd_path)) + del physics_stage + + # Now reload at the correct path. + side_stage = lazy.pxr.Usd.Stage.Open(str(usd_path)) + + # Return everything back to its original reference state. + for instanceable_prim_path, (ref, is_instanceable) in instanceable_prims_and_refs.items(): + instanceable_prim = side_stage.GetPrimAtPath(instanceable_prim_path) + instanceable_prim.SetInstanceable(is_instanceable and _ALLOW_INSTANCING) + instanceable_prim.GetReferences().AddReference("", ref) + + # Also update the asset paths + def _update_path(asset_path): + # Get the absolute path - the asset path is relative to where the USD is. + absolute_asset_path = (usd_dir / asset_path).resolve() + absolute_original_materials_path = current_materials.resolve() + + # If the file is not in our current materials directory, we don't update. + if not absolute_asset_path.is_relative_to(absolute_original_materials_path): + return asset_path + + # Otherwise, first get the new absolute path of the asset in the new folder + relative_to_material_dir = absolute_asset_path.relative_to(absolute_original_materials_path) + absolute_moved_path = new_materials / relative_to_material_dir + + # Finally, find where that file is relative to the path where the USD goes. + final_path = os.path.relpath(absolute_moved_path, usd_dir.resolve()) + print("Updating", asset_path, "to", final_path) + return final_path + + lazy.pxr.UsdUtils.ModifyAssetPaths(side_stage.GetRootLayer(), _update_path) + + # Go through all of the prims in the visuals and colliders trees, and promote the mesh prims + # one level up, so instead of visuals -> linkname -> mesh we just have visuals -> linkname where + # the linkname prim has the mesh and xforms combined. + visuals_prim = side_stage.GetPrimAtPath("/visuals") + colliders_prim = side_stage.GetPrimAtPath("/colliders") + links = list(visuals_prim.GetChildren()) + list(colliders_prim.GetChildren()) + wrappers = [wrapper for link in links for wrapper in link.GetChildren()] + + for parent_prim in wrappers: + parent_path = parent_prim.GetPath() + grandparent_path = parent_path.GetParentPath() + + # The child is usually behind one reference, but 5.1 can emit a direct primitive collider (no reference). + references = parent_prim.GetPrimStack()[0].referenceList.prependedItems + if not references: + for prim_to_update in lazy.pxr.Usd.PrimRange(parent_prim): + _ensure_geom_xform_ops(prim_to_update) + continue + assert len(references) == 1, f"Expected exactly one reference for {parent_path}, got {len(references)}" + referenced_wrapper_path_str = str(references[0].primPath) + referenced_wrapper_prim = side_stage.GetPrimAtPath(referenced_wrapper_path_str) + assert referenced_wrapper_prim.IsValid() + + # Wrapper name varies by mesh format, so resolve the geometry name-agnostically. + child_prim = resolve_imported_geometry(referenced_wrapper_prim) + if child_prim is None: + # No mesh child for this link; drop the wrapper. + del side_stage.GetRootLayer().GetPrimAtPath(grandparent_path).nameChildren[parent_path.name] + continue + for prim_to_update in lazy.pxr.Usd.PrimRange(child_prim): + _ensure_geom_xform_ops(prim_to_update) + child_path = child_prim.GetPath() + + # Duplicate the properties on the parent prim onto the child. + for attr in parent_prim.GetAttributes(): + if attr.IsAuthored(): + # Get attribute info + attr_name = attr.GetName() + attr_type = attr.GetTypeName() + + # Create or get the attribute on destination + dest_attr = child_prim.CreateAttribute(attr_name, attr_type) + + # Copy the value + if attr.HasValue(): + dest_attr.Set(attr.Get()) + + # Delete the parent prim + del side_stage.GetRootLayer().GetPrimAtPath(grandparent_path).nameChildren[parent_path.name] + + # Move the child prim to the parent's path. + assert lazy.pxr.Sdf.CopySpec(side_stage.GetRootLayer(), child_path, side_stage.GetRootLayer(), parent_path) + + # Migrate materials from /meshes to /Looks before deleting the meshes hierarchy + # This is necessary for IsaacSim 5.1+ where materials are now placed under /meshes + _migrate_materials_to_looks(side_stage) + + # Remove the meshes hierarchy altogether + del side_stage.GetRootLayer().rootPrims["meshes"] + + # Delete any collision groups + for child_prim in list(side_stage.Traverse()): + if child_prim.GetTypeName() == "PhysicsCollisionGroup": + del ( + side_stage.GetRootLayer() + .GetPrimAtPath(child_prim.GetPath().GetParentPath()) + .nameChildren[child_prim.GetPath().name] + ) + + # Find references to correct. The idea here is that we do not want our `visuals` or `collisions` + # prims to be references, because we want to be able to put properties on the meshes underneath. + # Instead, we'll just make the mesh prims instanceable. + found_reference_prims = {} + for possible_referrer in list(side_stage.Traverse()): + if not possible_referrer.IsValid(): + continue + # Check if the prim has a reference on it + references = possible_referrer.GetPrimStack()[0].referenceList.prependedItems + if references: + assert possible_referrer.GetName() in ["visuals", "collisions"] + assert ( + len(references) == 1 + ), f"Expected exactly one reference for {possible_referrer.GetPath()}, got {len(references)}" + referrer_path = possible_referrer.GetPath() + referee_path = references[0].primPath + # Isaac Sim's URDF importer emits a placeholder `visuals` / + # `collisions` reference on every link, even stub meta-links that + # have no geometry — those references are dangling. Just drop the + # empty referrer prim so we don't choke on it below. + if not side_stage.GetPrimAtPath(referee_path).IsValid(): + del ( + side_stage.GetRootLayer() + .GetPrimAtPath(referrer_path.GetParentPath()) + .nameChildren[referrer_path.name] + ) + continue + found_reference_prims[referrer_path] = referee_path + del side_stage.GetRootLayer().GetPrimAtPath(referrer_path.GetParentPath()).nameChildren[referrer_path.name] + + # Create references for all of the individual meshes + for referrer_prim_path, referee_path in found_reference_prims.items(): + referee_prim = side_stage.GetPrimAtPath(referee_path) + + # Create an XFormPrim for the collisions/visuals tree + referrer_prim = lazy.pxr.UsdGeom.Xform.Define(side_stage, referrer_prim_path) + + # For each of the mesh originals, add a reference to the collisions/visuals prim + for mesh_original in referee_prim.GetChildren(): + # Get its type + assert mesh_original.IsValid(), f"Can't find mesh {mesh_original.GetPath()}" + prim_type = mesh_original.GetTypeName() + + # Create the prim + name = mesh_original.GetName() + mesh_prim = side_stage.DefinePrim(referrer_prim.GetPath().AppendChild(name), prim_type) + + # Add the collision APIs + if referrer_prim_path.name == "collisions": + lazy.pxr.UsdPhysics.CollisionAPI.Apply(mesh_prim) + mesh_collision_api = lazy.pxr.UsdPhysics.MeshCollisionAPI.Apply(mesh_prim) + mesh_collision_api.GetApproximationAttr().Set("convexHull") + + # Add the reference to the actual collisions + mesh_prim.GetReferences().AddReference("", mesh_original.GetPath()) + + # Make it instanceable + mesh_prim.SetInstanceable(_ALLOW_INSTANCING) + + # Flatten everything and save at the target location. + side_stage.Save() + del side_stage + + # Remove the old stage files. + shutil.rmtree(configuration_dir) + + return urdf_path, str(usd_path) + + +def _pretty_print_xml(current, parent=None, index=-1, depth=0, use_tabs=False): + """ + Recursively formats an XML element tree to be pretty-printed with indentation. + + Args: + current (xml.etree.ElementTree.Element): The current XML element to format. + parent (xml.etree.ElementTree.Element, optional): The parent XML element. Defaults to None. + index (int, optional): The index of the current element in the parent's children. Defaults to -1. + depth (int, optional): The current depth in the XML tree, used for indentation. Defaults to 0. + use_tabs (bool, optional): If True, use tabs for indentation; otherwise, use spaces. Defaults to False. + + Returns: + None + """ + space = "\t" if use_tabs else " " * 4 + for i, node in enumerate(current): + _pretty_print_xml(node, current, i, depth + 1) + if parent is not None: + if index == 0: + parent.text = "\n" + (space * depth) + else: + parent[index - 1].tail = "\n" + (space * depth) + if index == len(parent) - 1: + current.tail = "\n" + (space * (depth - 1)) + + +def _convert_to_xml_string(inp): + """ + Converts any type of {bool, int, float, list, tuple, array, string, th.Tensor} into a URDF-compatible string. + Note that an input string / th.Tensor results in a no-op action. + + Args: + inp: Input to convert to string + + Returns: + str: String equivalent of @inp + + Raises: + ValueError: If the input type is unsupported. + """ + if type(inp) in {list, tuple, th.Tensor}: + return _tensor_to_space_script(inp) + elif type(inp) in {int, float, bool, th.float32, th.float64, th.int32, th.int64}: + return str(inp).lower() + elif type(inp) in {str}: + return inp + else: + raise ValueError("Unsupported type received: got {}".format(type(inp))) + + +def _create_urdf_joint( + name, + parent, + child, + pos=(0, 0, 0), + rpy=(0, 0, 0), + joint_type="fixed", + axis=None, + damping=None, + friction=None, + limits=None, +): + """ + Generates URDF joint + Args: + name (str): Name of this joint + parent (str or ET.Element): Name of parent link or parent link element itself for this joint + child (str or ET.Element): Name of child link or child link itself for this joint + pos (list or tuple or th.Tensor): (x,y,z) offset pos values when creating the collision body + rpy (list or tuple or th.Tensor): (r,p,y) offset rot values when creating the joint + joint_type (str): What type of joint to create. Must be one of {fixed, revolute, prismatic} + axis (None or 3-tuple): If specified, should be (x,y,z) axis corresponding to DOF + damping (None or float): If specified, should be damping value to apply to joint + friction (None or float): If specified, should be friction value to apply to joint + limits (None or 2-tuple): If specified, should be min / max limits to the applied joint + Returns: + ET.Element: Generated joint element + """ + # Create the initial joint + jnt = ET.Element("joint", name=name, type=joint_type) + # Create origin subtag + ET.SubElement( + jnt, + "origin", + attrib={"rpy": _convert_to_xml_string(rpy), "xyz": _convert_to_xml_string(pos)}, + ) + # Make sure parent and child are both names (str) -- if they're not str already, we assume it's the element ref + if not isinstance(parent, str): + parent = parent.get("name") + if not isinstance(child, str): + child = child.get("name") + # Create parent and child subtags + parent = ET.SubElement(jnt, "parent", link=parent) + child = ET.SubElement(jnt, "child", link=child) + # Add additional parameters if specified + if axis is not None: + ET.SubElement(jnt, "axis", xyz=_convert_to_xml_string(axis)) + dynamic_params = {} + if damping is not None: + dynamic_params["damping"] = _convert_to_xml_string(damping) + if friction is not None: + dynamic_params["friction"] = _convert_to_xml_string(friction) + if dynamic_params: + ET.SubElement(jnt, "dynamics", **dynamic_params) + if limits is not None: + ET.SubElement(jnt, "limit", lower=limits[0], upper=limits[1]) + + # Return this element + return jnt + + +def _create_urdf_link(name, subelements=None, mass=None, inertia=None): + """ + Generates URDF link element + Args: + name (str): Name of this link + subelements (None or list): If specified, specifies all nested elements that should belong to this link + (e.g.: visual, collision body elements) + mass (None or float): If specified, will add an inertial tag with specified mass value + inertia (None or 6-array): If specified, will add an inertial tag with specified inertia value + Value should be (ixx, iyy, izz, ixy, ixz, iyz) + Returns: + ET.Element: Generated link + """ + # Create the initial link + link = ET.Element("link", name=name) + # Add all subelements if specified + if subelements is not None: + for ele in subelements: + link.append(ele) + # Add mass subelement if requested + if mass is not None or inertia is not None: + inertial = ET.SubElement(link, "inertial") + if mass is not None: + ET.SubElement(inertial, "mass", value=_convert_to_xml_string(mass)) + if inertia is not None: + axes = ["ixx", "iyy", "izz", "ixy", "ixz", "iyz"] + inertia_vals = {ax: str(i) for ax, i in zip(axes, inertia)} + ET.SubElement(inertial, "inertia", **inertia_vals) + + # Return this element + return link + + +def _create_urdf_meta_link( + root_element, + meta_link_name, + parent_link_name="base_link", + pos=(0, 0, 0), + rpy=(0, 0, 0), +): + """ + Creates the appropriate URDF joint and link for a meta link and appends it to the root element. + + Args: + root_element (Element): The root XML element to which the meta link will be appended. + meta_link_name (str): The name of the meta link to be created. + parent_link_name (str, optional): The name of the parent link. Defaults to "base_link". + pos (tuple, optional): The position of the joint in the form (x, y, z). Defaults to (0, 0, 0). + rpy (tuple, optional): The roll, pitch, and yaw of the joint in the form (r, p, y). Defaults to (0, 0, 0). + + Returns: + None + """ + # Create joint + jnt = _create_urdf_joint( + name=f"{meta_link_name}_joint", + parent=parent_link_name, + child=f"{meta_link_name}_link", + pos=pos, + rpy=rpy, + joint_type="fixed", + ) + # Create child link + link = _create_urdf_link( + name=f"{meta_link_name}_link", + mass=0.0001, + inertia=[0.00001, 0.00001, 0.00001, 0, 0, 0], + ) + + # Add to root element + root_element.append(jnt) + root_element.append(link) + + +def _save_xmltree_as_urdf(root_element, name, dirpath, unique_urdf=False): + """ + Generates a URDF file corresponding to @xmltree at @dirpath with name @name.urdf. + Args: + root_element (ET.Element): Element tree that compose the URDF + name (str): Name of this file (name assigned to robot tag) + dirpath (str): Absolute path to the location / filename for the generated URDF + unique_urdf (bool): Whether to use a unique identifier when naming urdf (uses current datetime) + Returns: + str: Path to newly created urdf (fpath/.urdf) + """ + # Write to fpath, making sure the directory exists (if not, create it) + Path(dirpath).mkdir(parents=True, exist_ok=True) + # Get file + date = datetime.now().isoformat(timespec="microseconds").replace(".", "_").replace(":", "_").replace("-", "_") + fname = f"{name}_{date}.urdf" if unique_urdf else f"{name}.urdf" + fpath = os.path.join(dirpath, fname) + with open(fpath, "w") as f: + # Write top level header line first + f.write('\n') + # Convert xml to string form and write to file + _pretty_print_xml(current=root_element) + xml_str = ET.tostring(root_element, encoding="unicode") + f.write(xml_str) + + # Return path to file + return fpath + + +def _add_meta_links_to_urdf(urdf_path, obj_category, obj_model, dataset_root): + """ + Adds meta links to a URDF file based on metadata. + + This function reads a URDF file and corresponding metadata, processes the metadata to add meta links, and then + saves an updated version of the URDF file with these meta links. + + Args: + urdf_path (str): Path to URDF + obj_category (str): The category of the object. + obj_model (str): The model name of the object. + dataset_root (str): The root directory of the dataset. + + Returns: + str: The path to the updated URDF file. + """ + # Load urdf + tree = ET.parse(urdf_path) + root = tree.getroot() + + # Load metadata + metadata_fpath = pathlib.Path(dataset_root) / "objects" / obj_category / obj_model / "misc/metadata.json" + with open(metadata_fpath, "r") as f: + metadata = json.load(f) + + # Pop meta links + assert not ( + "links" in metadata and "meta_links" in metadata + ), "Only expected one of links and meta_links to be found in metadata, but found both!" + + if "meta_links" in metadata: + # Rename meta links, e.g. from "fillable" to "container" + for link, meta_link in metadata["meta_links"].items(): + for meta_link_name in list(meta_link.keys()): + meta_link_attrs = meta_link[meta_link_name] + if meta_link_name in _META_LINK_RENAME_MAPPING: + metadata["meta_links"][link][_META_LINK_RENAME_MAPPING[meta_link_name]] = meta_link_attrs + del metadata["meta_links"][link][meta_link_name] + + with open(metadata_fpath, "w") as f: + json.dump(metadata, f) + + meta_links = metadata.pop("meta_links") + log.debug("meta_links:", meta_links) + for parent_link_name, child_link_attrs in meta_links.items(): + for meta_link_name, ml_attrs in child_link_attrs.items(): + assert ( + meta_link_name in _ALLOWED_META_TYPES + ), f"meta_link_name {meta_link_name} not in {_ALLOWED_META_TYPES}" + + for ml_id, attrs_list in ml_attrs.items(): + # If the attrs list is a dictionary (legacy format), convert it to a list + if isinstance(attrs_list, dict): + keys = [int(k) for k in attrs_list.keys()] + assert set(keys) == set( + range(len(keys)) + ), f"Expected keys to be 0-indexed integers, but got {keys}" + int_key_dict = {int(k): v for k, v in attrs_list.items()} + attrs_list = [int_key_dict[i] for i in range(len(keys))] + + if len(attrs_list) > 0: + if _ALLOWED_META_TYPES[meta_link_name] != "dimensionless": + # If not dimensionless, we create one meta link for a list of meshes below it + attrs_list = [attrs_list[0]] + else: + # Otherwise, we create one meta link for each frame + # For non-attachment meta links, we expect only one instance per type + # E.g. heatsource_leftstove_0, heatsource_rightstove_0, but not heatsource_leftstove_1 + if meta_link_name != "attachment": + assert ( + len(attrs_list) == 1 + ), f"Expected only one instance for meta_link {meta_link_name}_{ml_id}, but found {len(attrs_list)}" + + for i, attrs in enumerate(attrs_list): + pos = th.as_tensor(attrs["position"]) + quat = th.as_tensor(attrs["orientation"]) + + # For particle applier only, the orientation of the meta link matters (particle should shoot towards the negative z-axis) + # If the meta link is created based on the orientation of the first mesh that is a cone, we need to rotate it by 180 degrees + # because the cone is pointing in the wrong direction. + if meta_link_name == "particleapplier" and attrs["type"] == "cone": + assert ( + len(attrs_list) == 1 + ), f"Expected only one instance for meta_link {meta_link_name}_{ml_id}, but found {len(attrs_list)}" + quat = T.quat_multiply(quat, T.axisangle2quat(th.tensor([math.pi, 0.0, 0.0]))) + + # Create meta link + _create_urdf_meta_link( + root_element=root, + meta_link_name=f"meta__{parent_link_name}_{meta_link_name}_{ml_id}_{i}", + parent_link_name=parent_link_name, + pos=pos, + rpy=T.quat2euler(quat), + ) + + # Export this URDF + return _save_xmltree_as_urdf( + root_element=root, + name=f"{obj_model}_with_meta_links", + dirpath=os.path.dirname(urdf_path), + unique_urdf=False, + ) + + +def convert_scene_urdf_to_json(urdf, json_path): + """ + Converts a scene from a URDF file to a JSON file. + + This function loads the scene described by the URDF file into the OmniGibson simulator, + plays the simulation, and saves the scene to a JSON file. After saving, it removes the + "init_info" from the JSON file and saves it again. + + Args: + urdf (str): The file path to the URDF file describing the scene. + json_path (str): The file path where the JSON file will be saved. + """ + # First, load the requested objects from the URDF into OG + _load_scene_from_urdf(urdf=urdf) + log.debug("Loaded scene from URDF") + + # Play the simulator, then save + og.sim.play() + log.debug("Played simulator") + Path(os.path.dirname(json_path)).mkdir(parents=True, exist_ok=True) + og.sim.save(json_paths=[json_path]) + log.debug("Saved scene to JSON") + + # Load the json, remove the init_info because we don't need it, then save it again + with open(json_path, "r") as f: + scene_info = json.load(f) + scene_info.pop("init_info") + + with open(json_path, "w+") as f: + json.dump(scene_info, f, cls=_TorchEncoder, indent=4) + + +def _load_scene_from_urdf(urdf): + """ + Loads a scene from a URDF file. + + Args: + urdf (str): Path to the URDF file. + + Raises: + ValueError: If an object fails to load. + + This function performs the following steps: + 1. Extracts object configuration information from the URDF file. + 2. Creates a new scene without a floor plane and imports it into the simulator. + 3. Iterates over the objects' information and attempts to load each object into the scene. + - If the USD file for an object does not exist, it prints a message and skips the object. + - If an object fails to load, it raises a ValueError with the object's name. + 4. Sets the bounding box center position and orientation for each loaded object. + 5. Takes a simulation step to finalize the scene setup. + """ + # First, grab object info from the urdf + objs_info = _get_objects_config_from_scene_urdf(urdf=urdf) + + # Load all the objects manually into a scene + scene = Scene(use_floor_plane=False) + og.sim.import_scene(scene) + + for obj_name, obj_info in objs_info.items(): + try: + if not os.path.exists( + DatasetObject.get_usd_path(obj_info["cfg"]["category"], obj_info["cfg"]["model"]).replace( + ".usd", ".encrypted.usd" + ) + ): + raise FileNotFoundError(f"Missing USD asset for object {obj_name}") + log.debug(f"Loading object {obj_name}") + obj = DatasetObject( + name=obj_name, + **obj_info["cfg"], + ) + scene.add_object(obj) + obj.set_bbox_center_position_orientation(position=obj_info["bbox_pos"], orientation=obj_info["bbox_quat"]) + except Exception as e: + raise ValueError(f"Failed to load object {obj_name}") from e + + +def _get_objects_config_from_scene_urdf(urdf): + """ + Parses a URDF file to extract object configuration information. + + Args: + urdf (str): Path to the URDF file. + + Returns: + dict: A dictionary containing the configuration of objects extracted from the URDF file. + """ + tree = ET.parse(urdf) + root = tree.getroot() + objects_cfg = dict() + _get_objects_config_from_element(root, model_pose_info=objects_cfg) + return objects_cfg + + +def _get_objects_config_from_element(element, model_pose_info): + """ + Extracts and populates object configuration information from an URDF element. + + This function processes an URDF element to extract joint and link information, + populating the provided `model_pose_info` dictionary with the relevant data. + + Args: + element (xml.etree.ElementTree.Element): The URDF element containing object configuration data. + model_pose_info (dict): A dictionary to be populated with the extracted configuration information. + + The function performs two passes through the URDF element: + 1. In the first pass, it extracts joint information and populates `model_pose_info` with joint pose data. + 2. In the second pass, it extracts link information, imports object models, and updates `model_pose_info` with + additional configuration details such as category, model, bounding box, rooms, scale, and object scope. + + The function also handles nested elements by recursively calling itself for child elements. + + Note: + - Joint names with hyphens are replaced with underscores. + - The function asserts that each link name (except "world") is present in `model_pose_info` after the first pass. + """ + # First pass through, populate the joint pose info + for ele in element: + if ele.tag == "joint": + name, pos, quat, fixed_jnt = _get_joint_info(ele) + name = name.replace("-", "_") + model_pose_info[name] = { + "bbox_pos": pos, + "bbox_quat": quat, + "cfg": { + "fixed_base": fixed_jnt, + }, + } + + # Second pass through, import object models + for ele in element: + if ele.tag == "link": + # This is a valid object, import the model + name = ele.get("name").replace("-", "_") + if name == "world": + # Skip this + pass + else: + log.debug(name) + assert name in model_pose_info, f"Did not find {name} in current model pose info!" + model_pose_info[name]["cfg"]["category"] = ele.get("category") + model_pose_info[name]["cfg"]["visual_only"] = ele.get("category") in _VISUAL_ONLY_CATEGORIES + model_pose_info[name]["cfg"]["model"] = ele.get("model") + model_pose_info[name]["cfg"]["bounding_box"] = ( + _space_string_to_tensor(ele.get("bounding_box")) if "bounding_box" in ele.keys() else None + ) + in_rooms = ele.get("rooms", "") + if in_rooms: + in_rooms = in_rooms.split(",") + model_pose_info[name]["cfg"]["in_rooms"] = in_rooms + model_pose_info[name]["cfg"]["scale"] = ( + _space_string_to_tensor(ele.get("scale")) if "scale" in ele.keys() else None + ) + model_pose_info[name]["cfg"]["bddl_object_scope"] = ele.get("object_scope", None) + + # If there's children nodes, we iterate over those + for child in ele: + _get_objects_config_from_element(child, model_pose_info=model_pose_info) + + +def _get_joint_info(joint_element): + """ + Extracts joint information from an URDF element. + + Args: + joint_element (xml.etree.ElementTree.Element): The URDF element containing joint information. + + Returns: + tuple: A tuple containing: + - child (str or None): The name of the child link, or None if not specified. + - pos (numpy.ndarray or None): The position as a tensor, or None if not specified. + - quat (numpy.ndarray or None): The orientation as a quaternion, or None if not specified. + - fixed_jnt (bool): True if the joint is fixed, False otherwise. + """ + child, pos, quat, fixed_jnt = None, None, None, None + fixed_jnt = joint_element.get("type") == "fixed" + for ele in joint_element: + if ele.tag == "origin": + quat = T.euler2quat(_space_string_to_tensor(ele.get("rpy"))) + pos = _space_string_to_tensor(ele.get("xyz")) + elif ele.tag == "child": + child = ele.get("link") + return child, pos, quat, fixed_jnt + + +def make_mesh_positive(mesh_fpath, scale, output_suffix="mirror"): + assert "." not in mesh_fpath + for sc, letter in zip(scale, "xyz"): + if sc < 0: + output_suffix += f"_{letter}" + for filetype in [".obj", ".stl", ".dae"]: + fpath = f"{mesh_fpath}{filetype}" + out_fpath = f"{mesh_fpath}_{output_suffix}{filetype}" + kwargs = dict() + if filetype == ".dae": + kwargs["force"] = "mesh" + if os.path.exists(fpath): + try: + tm = trimesh.load(fpath, **kwargs) + tm.apply_scale(scale) + tm.export(out_fpath) + if filetype == ".obj": + # Update header lines + lines = [] + with open(fpath, "r") as f: + for line in f.readlines(): + if line.startswith("v "): + break + lines.append(line) + start = False + with open(out_fpath, "r") as f: + for line in f.readlines(): + if line.startswith("v "): + start = True + if start: + lines.append(line) + with open(out_fpath, "w+") as f: + f.writelines(lines) + except KeyError: + # Degenerate mesh, so immediately return + return None + return output_suffix + + +def make_asset_positive(urdf_fpath, output_suffix="mirror"): + assert urdf_fpath.endswith(".urdf") + out_lines = [] + + with open(urdf_fpath, "r") as f: + for line in f.readlines(): + # print(line) + out_line = line + if " max_vertices: + ms.apply_filter("meshing_decimation_quadric_edge_collapse", targetfacenum=max_faces) + max_faces -= 2 + vertices_reduced = ms.current_mesh().vertex_matrix() + faces_reduced = ms.current_mesh().face_matrix() + vertex_normals_reduced = ms.current_mesh().vertex_normal_matrix() + return trimesh.Trimesh( + vertices=vertices_reduced, + faces=faces_reduced, + vertex_normals=vertex_normals_reduced, + ).convex_hull + + +def generate_collision_meshes( + trimesh_mesh, method="coacd", hull_count=32, discard_not_volume=True, error_handling=False +): + """ + Generates a set of collision meshes from a trimesh mesh using CoACD. + + Args: + trimesh_mesh (trimesh.Trimesh): The trimesh mesh to generate the collision mesh from. + method (str): Method to generate collision meshes. Valid options are {"coacd", "convex"} + hull_count (int): If @method="coacd", this sets the max number of hulls to generate + discard_not_volume (bool): If @method="coacd" and set to True, this discards any generated hulls + that are not proper volumes + error_handling (bool): If true, will run coacd_runner.py and handle the coacd assertion fault by using convex hull instead + + Returns: + List[trimesh.Trimesh]: The collision meshes. + """ + # If the mesh is convex or the mesh is a proper volume and similar to its convex hull, simply return that directly + if trimesh_mesh.is_convex or ( + trimesh_mesh.is_volume and (trimesh_mesh.volume / trimesh_mesh.convex_hull.volume) > 0.90 + ): + hulls = [trimesh_mesh.convex_hull] + + elif method == "coacd": + if error_handling: + # Run CoACD with error handling + import subprocess + import sys + import tempfile + import pickle + import os + + # Create separate temp files with proper extensions + with tempfile.NamedTemporaryFile(suffix=".pkl", delete=False) as f: + data_path = f.name + pickle.dump((trimesh_mesh.vertices, trimesh_mesh.faces, hull_count), f) + + script_path = tempfile.mktemp(suffix=".py") + result_path = tempfile.mktemp(suffix=".pkl") + + # Run subprocess with clean file paths + success = ( + subprocess.call( + [sys.executable, os.path.join(os.path.dirname(__file__), "coacd_runner.py"), data_path, result_path] + ) + == 0 + ) + + # Process results or fallback + if success and os.path.exists(result_path): + with open(result_path, "rb") as f: + result = pickle.load(f) + + # Process results as before + hulls = [] + coacd_vol = 0.0 + for vs, fs in result: + hull = trimesh.Trimesh(vertices=vs, faces=fs, process=False) + if discard_not_volume and not hull.is_volume: + continue + hulls.append(hull) + coacd_vol += hull.convex_hull.volume + + # Check if we found any valid hulls + if len(hulls) == 0: + print("No valid collision meshes generated, falling back to convex hull") + hulls = [trimesh_mesh.convex_hull] + else: + # Compare volume ratios as in original code + vol_ratio = coacd_vol / trimesh_mesh.convex_hull.volume + if 0.95 < vol_ratio < 1.05: + print("MINIMAL CHANGE -- USING CONVEX HULL INSTEAD") + hulls = [trimesh_mesh.convex_hull] + else: + print("CoACD processing failed, falling back to convex hull") + hulls = [trimesh_mesh.convex_hull] + + # Clean up temp files + for path in [data_path, script_path, result_path]: + if os.path.exists(path): + os.remove(path) + else: + try: + import coacd + except ImportError: + raise ImportError("Please install the `coacd` package to use this function.") + + # Get the vertices and faces + coacd_mesh = coacd.Mesh(trimesh_mesh.vertices, trimesh_mesh.faces) + + # Run CoACD with the hull count + result = coacd.run_coacd( + coacd_mesh, + max_convex_hull=hull_count, + max_ch_vertex=60, + ) + + # Convert the returned vertices and faces to trimesh meshes + # and assert that they are volumes (and if not, discard them if required) + hulls = [] + coacd_vol = 0.0 + for vs, fs in result: + hull = trimesh.Trimesh(vertices=vs, faces=fs, process=False) + if discard_not_volume and not hull.is_volume: + continue + hulls.append(hull) + coacd_vol += hull.convex_hull.volume + + # Assert that we got _some_ collision meshes + assert len(hulls) > 0, "No collision meshes generated!" + + # Compare coacd's generation compared to the original mesh's convex hull + # If the difference is small (<10% volume difference), simply keep the convex hull + vol_ratio = coacd_vol / trimesh_mesh.convex_hull.volume + if 0.95 < vol_ratio < 1.05: + print("MINIMAL CHANGE -- USING CONVEX HULL INSTEAD") + # from IPython import embed; embed() + hulls = [trimesh_mesh.convex_hull] + + elif method == "convex": + hulls = [trimesh_mesh.convex_hull] + + else: + raise ValueError(f"Invalid collision mesh generation method specified: {method}") + + # Sanity check all convex hulls + # For whatever reason, some convex hulls are not true volumes, so we take the convex hull again + # See https://github.com/mikedh/trimesh/issues/535 + hulls = [hull.convex_hull if not hull.is_volume else hull for hull in hulls] + + # For each hull, simplify so that the complexity is guaranteed to be Omniverse-GPU compatible + # See https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/rigid-bodies.html#collision-settings + simplified_hulls = [simplify_convex_hull(hull) for hull in hulls] + + return simplified_hulls + + +def get_collision_approximation_for_urdf( + urdf_path, + collision_method="coacd", + hull_count=32, + coacd_links=None, + convex_links=None, + no_decompose_links=None, + visual_only_links=None, + ignore_links=None, +): + """ + Computes collision approximation for all collision meshes (which are assumed to be non-convex) in + the given URDF. + + NOTE: This is an in-place operation! It will overwrite @urdf_path + + Args: + urdf_path (str): Absolute path to the URDF to decompose + collision_method (str): Default collision method to use. Valid options are: {"coacd", "convex"} + hull_count (int): Maximum number of convex hulls to decompose individual visual meshes into. + Only relevant if @collision_method is "coacd" + coacd_links (None or list of str): If specified, links that should use CoACD to decompose collision meshes + convex_links (None or list of str): If specified, links that should use convex hull to decompose collision meshes + no_decompose_links (None or list of str): If specified, links that should not have any special collision + decomposition applied. This will only use the convex hull + visual_only_links (None or list of str): If specified, link names corresponding to links that should have + no collision associated with them (so any pre-existing collisions will be removed!) + ignore_links (None or list of str): If specified, link names corresponding to links that should be skipped + during collision generation process + """ + # Load URDF + urdf_dir = os.path.dirname(urdf_path) + tree = ET.parse(urdf_path) + root = tree.getroot() + + # Next, iterate over each visual mesh and define collision meshes for them + coacd_links = set() if coacd_links is None else set(coacd_links) + convex_links = set() if convex_links is None else set(convex_links) + no_decompose_links = set() if no_decompose_links is None else set(no_decompose_links) + visual_only_links = set() if visual_only_links is None else set(visual_only_links) + ignore_links = set() if ignore_links is None else set(ignore_links) + col_mesh_rel_folder = "meshes/collision" + col_mesh_folder = pathlib.Path(urdf_dir) / col_mesh_rel_folder + col_mesh_folder.mkdir(exist_ok=True, parents=True) + + for link in root.findall("link"): + link_name = link.attrib["name"] + old_cols = link.findall("collision") + # Completely skip this link if this a link to explicitly skip or we have no collision tags + if link_name in ignore_links or len(old_cols) == 0: + continue + + # Keep an existing collision proxy instead of regenerating a hull; coacd/convex links override. + if ( + link_name not in coacd_links + and link_name not in convex_links + and link_name not in visual_only_links + and link_has_dedicated_collision(link) + ): + print(f"Preserving provided collision for link {link_name} (dedicated collision found)...") + continue + + print(f"Generating collision approximation for link {link_name}...") + generated_new_col = False + idx = 0 + if link_name not in visual_only_links: + for vis in link.findall("visual"): + # Get origin + origin = vis.find("origin") + # Check all geometries + geoms = vis.findall("geometry/*") + # We should only have a single geom, so assert here + assert len(geoms) == 1 + # Check whether we actually need to generate a collision approximation + # No need if the geom type is not a mesh (i.e.: it's a primitive -- so we assume if a collision is already + # specified, it's that same primitive) + geom = geoms[0] + if geom.tag != "mesh": + continue + mesh_path = os.path.join(os.path.dirname(urdf_path), geom.attrib["filename"]) + tm = trimesh.load(mesh_path, force="mesh", process=False) + + if link_name in coacd_links: + method = "coacd" + elif link_name in convex_links: + method = "convex" + elif link_name in no_decompose_links: + # Output will just be ignored, so skip + continue + else: + method = collision_method + collision_meshes = generate_collision_meshes( + trimesh_mesh=tm, + method=method, + hull_count=hull_count, + ) + # Save and merge precomputed collision mesh + collision_filenames_and_scales = [] + for i, collision_mesh in enumerate(collision_meshes): + processed_collision_mesh = collision_mesh.copy() + collision_filename = f"{link_name}_col_{idx}.obj" + + # OmniGibson requires unit-bbox collision meshes, so here we do that scaling + bounding_box = processed_collision_mesh.bounding_box.extents + assert all( + x > 0 for x in bounding_box + ), f"Bounding box extents are not all positive: {bounding_box}" + collision_scale = 1.0 / bounding_box + collision_scale_matrix = th.eye(4) + collision_scale_matrix[:3, :3] = th.diag(th.as_tensor(collision_scale)) + processed_collision_mesh.apply_transform(collision_scale_matrix.numpy()) + processed_collision_mesh.export(col_mesh_folder / collision_filename, file_type="obj") + collision_filenames_and_scales.append((collision_filename, 1 / collision_scale)) + + idx += 1 + + for collision_filename, collision_scale in collision_filenames_and_scales: + collision_xml = ET.SubElement(link, "collision") + collision_xml.attrib = {"name": collision_filename.replace(".obj", "")} + # Add origin info if defined + if origin is not None: + collision_xml.append(deepcopy(origin)) + collision_geometry_xml = ET.SubElement(collision_xml, "geometry") + collision_mesh_xml = ET.SubElement(collision_geometry_xml, "mesh") + collision_mesh_xml.attrib = { + "filename": os.path.join(col_mesh_rel_folder, collision_filename), + "scale": " ".join([str(item) for item in collision_scale]), + } + + if link_name not in no_decompose_links: + generated_new_col = True + + # If we generated a new set of collision meshes, remove the old ones + if generated_new_col or link_name in visual_only_links: + for col in old_cols: + link.remove(col) + + # Save the URDF file + _save_xmltree_as_urdf( + root_element=root, + name=os.path.splitext(os.path.basename(urdf_path))[0], + dirpath=os.path.dirname(urdf_path), + unique_urdf=False, + ) + + +def generate_urdf_for_mesh( + asset_path, + out_dir, + category, + mdl, + collision_method=None, + hull_count=32, + up_axis="z", + scale=1.0, + check_scale=False, + rescale=False, + overwrite=False, +): + """ + Generate URDF file for either single mesh or articulated files. + Each submesh in articulated files (glb, gltf) will be extracted as a separate link. + + Args: + asset_path (str): Path to the input mesh file (.obj, .glb, .gltf) + out_dir (str): Output directory + category (str): Category name for the object + mdl (str): Model name + collision_method (str or None): Method for generating collision meshes ("convex", "coacd", or None) + hull_count (int): Maximum number of convex hulls for COACD method + up_axis (str): Up axis for the model ("y" or "z") + scale (float): User choice scale, will be overwritten if check_scale and rescale + check_scale (bool): Whether to check mesh size based on heuristic + rescale (bool): Whether to rescale mesh if check_scale + overwrite (bool): Whether to overwrite existing files + """ + + # Convert out_dir to Path object + if isinstance(out_dir, str): + out_dir = pathlib.Path(out_dir) + if isinstance(asset_path, str): + asset_path = pathlib.Path(asset_path) + + # Validate that the filename starts with a letter. Isaac 4.5 has issues if you don't do this. + assert asset_path.stem[ + 0 + ].isalpha(), f"Invalid asset path: {asset_path}. Isaac Sim expects the filename to start with a letter." + + # Create directory structure + if not overwrite: + assert not out_dir.exists(), f"Object directory {out_dir} already exists!" + out_dir.mkdir(parents=True, exist_ok=True) + + obj_name = "_".join([category, mdl]) + + visual_mesh = trimesh.load(str(asset_path), force="mesh", process=False, skip_materials=True) + if isinstance(visual_mesh, list): + visual_mesh = visual_mesh[0] # Take first mesh if multiple + + # Generate collision meshes if requested + collision_meshes = [] + if collision_method is not None: + collision_meshes = generate_collision_meshes( + visual_mesh, method=collision_method, hull_count=hull_count, error_handling=True + ) + + # Keep track of the base transform + rpy = [0, 0, 0] + + # Handle rotation for up_axis if needed + if up_axis == "y": + rpy = [math.pi / 2, 0, 0] + + # Compute new scale if check_scale = True + new_scale = 1.0 + + if check_scale: + # Find the link with the biggest bounding box + bbox_size = visual_mesh.bounding_box.extents + + click.echo(f"Visual mesh bounding box size: {bbox_size}") + + # Check if any dimension is too large (> 100) + if any(size > 5.0 for size in bbox_size): + if any(size > 50.0 for size in bbox_size): + if any(size > 500.0 for size in bbox_size): + new_scale = 0.001 + else: + new_scale = 0.01 + else: + new_scale = 0.1 + + click.echo( + "Warning: The bounding box sounds a bit large. " + "We just wanted to confirm this is intentional. You can skip this check by passing check_scale = False." + ) + + # Check if any dimension is too small (< 0.01) + elif all(size < 0.005 for size in bbox_size): + new_scale = 1000.0 + click.echo( + "Warning: The bounding box sounds a bit small. " + "We just wanted to confirm this is intentional. You can skip this check by passing check_scale = False." + ) + + else: + click.echo("Size is reasonable, no scaling") + + # Rescale mesh if rescale= True, else scale based on function input scale + if rescale: + click.echo(f"Original scale {scale} be overwrtten to {new_scale}") + scale = new_scale + + # Create directory structure for the output + obj_link_mesh_folder = out_dir / "shape" + obj_link_mesh_folder.mkdir(exist_ok=True) + obj_link_collision_mesh_folder = obj_link_mesh_folder / "collision" + obj_link_collision_mesh_folder.mkdir(exist_ok=True) + + # Process collision meshes + collision_info = [] + for i, collision_mesh in enumerate(collision_meshes): + # Export collision mesh filename + collision_filename = f"{obj_name}_base_link_collision_{i}.obj" + + # Scale collision mesh to unit bbox if needed + bounding_box = collision_mesh.bounding_box.extents + assert all(x > 0 for x in bounding_box), f"Invalid bounding box: {bounding_box}" + + collision_scale = 1.0 / bounding_box + collision_scale_matrix = th.eye(4) + collision_scale_matrix[:3, :3] = th.diag(th.as_tensor(collision_scale)) + + # Create a copy to avoid modifying the original + scaled_collision_mesh = collision_mesh.copy() + scaled_collision_mesh.apply_transform(collision_scale_matrix.numpy()) + + # Export collision mesh + collision_path = obj_link_collision_mesh_folder / collision_filename + scaled_collision_mesh.export(collision_path, file_type="obj") + + # Since we've already applied the transform, scale includes only the sizing adjustment + collision_info.append({"filename": collision_path, "scale": 1.0 / collision_scale}) + + # Generate URDF XML + tree_root = ET.Element("robot") + tree_root.attrib = {"name": mdl} + + # Create a base_link as the root + base_link = ET.SubElement(tree_root, "link") + base_link.attrib = {"name": "base_link"} + + rpy_str = " ".join(str(item) for item in rpy) + + # Add visual geometry + visual_xml = ET.SubElement(base_link, "visual") + visual_origin_xml = ET.SubElement(visual_xml, "origin") + visual_origin_xml.attrib = {"xyz": "0 0 0", "rpy": rpy_str} + visual_geometry_xml = ET.SubElement(visual_xml, "geometry") + visual_mesh_xml = ET.SubElement(visual_geometry_xml, "mesh") + visual_mesh_xml.attrib = { + "filename": str(asset_path), + "scale": f"{scale} {scale} {scale}", + } + + # Add collision geometries + for i, collision in enumerate(collision_info): + collision_xml = ET.SubElement(base_link, "collision") + collision_xml.attrib = {"name": f"base_link_collision_{i}"} + collision_origin_xml = ET.SubElement(collision_xml, "origin") + collision_origin_xml.attrib = {"xyz": "0 0 0", "rpy": rpy_str} # Zero transform since already applied + collision_geometry_xml = ET.SubElement(collision_xml, "geometry") + collision_mesh_xml = ET.SubElement(collision_geometry_xml, "mesh") + collision_mesh_xml.attrib = { + "filename": str(collision["filename"]), + "scale": " ".join(str(item) for item in scale * collision["scale"]), + } + + # Save URDF file + xmlstr = minidom.parseString(ET.tostring(tree_root)).toprettyxml(indent=" ") + xmlio = io.StringIO(xmlstr) + tree = ET.parse(xmlio) + + urdf_dir = out_dir / "urdf" + urdf_dir.mkdir(exist_ok=True) + urdf_path = urdf_dir / f"{mdl}.urdf" + with open(urdf_path, "wb") as f: + tree.write(f, xml_declaration=True) + + return str(urdf_path) + + +def record_obj_metadata_from_urdf(urdf_path, obj_dir, joint_setting="zero", overwrite=False): + """ + Records object metadata and writes it to misc/metadata.json within the object directory. + + Args: + urdf_path (str): Path to object URDF + obj_dir (str): Absolute path to the object's root directory + joint_setting (str): Setting for joints when calculating canonical metadata. Valid options + are {"low", "zero", "high"} (i.e.: lower joint limit, all 0 values, or upper joint limit) + overwrite (bool): Whether to overwrite any pre-existing data + """ + # Load the URDF file into urdfpy + robot = URDF.load(urdf_path) + + # Do FK with everything at desired configuration + if joint_setting == "zero": + val = lambda jnt: 0.0 + elif joint_setting == "low": + val = lambda jnt: jnt.limit.lower + elif joint_setting == "high": + val = lambda jnt: jnt.limit.upper + else: + raise ValueError(f"Got invalid joint_setting: {joint_setting}! Valid options are ['low', 'zero', 'high']") + joint_cfg = {joint.name: val(joint) for joint in robot.joints if joint.joint_type in ("prismatic", "revolute")} + vfk = robot.visual_trimesh_fk(cfg=joint_cfg) + + scene = trimesh.Scene() + for mesh, transform in vfk.items(): + scene.add_geometry(geometry=mesh, transform=transform) + + # Base link offset is pos offset from robot root link -> overall AABB center + # Since robot is placed at origin, this is simply the AABB centroid + base_link_offset = scene.bounding_box.centroid + + # BBox size is simply the extent of the overall AABB + bbox_size = scene.bounding_box.extents + + # Save metadata json + out_metadata = { + "meta_links": {}, + "link_tags": {}, + "object_parts": [], + "base_link_offset": base_link_offset.tolist(), + "bbox_size": bbox_size.tolist(), + "orientations": [], + } + misc_dir = pathlib.Path(obj_dir) / "misc" + misc_dir.mkdir(exist_ok=overwrite) + with open(misc_dir / "metadata.json", "w") as f: + json.dump(out_metadata, f) + + +def import_og_asset_from_urdf( + category, + model, + dataset_name, + urdf_path=None, + collision_method="coacd", + coacd_links=None, + convex_links=None, + no_decompose_links=None, + visual_only_links=None, + merge_fixed_joints=False, + import_inertia_tensor=True, + hull_count=32, + overwrite=False, + use_usda=False, +): + """ + Imports an asset from URDF format into OmniGibson-compatible USD format. This will write the new USD + (and copy the URDF if it does not already exist within @dataset_name) to @dataset_name + + Args: + category (str): Category to assign to imported asset + model (str): Model name to assign to imported asset + urdf_path (None or str): If specified, external URDF that should be copied into the dataset first before + converting into USD format. Otherwise, assumes that the urdf file already exists within @dataset_name dir + collision_method (None or str): If specified, collision decomposition method to use to generate + OmniGibson-compatible collision meshes. Valid options are {"coacd", "convex"} + coacd_links (None or list of str): If specified, links that should use CoACD to decompose collision meshes + convex_links (None or list of str): If specified, links that should use convex hull to decompose collision meshes + no_decompose_links (None or list of str): If specified, links that should not have any special collision + decomposition applied. This will only use the convex hull + visual_only_links (None or list of str): If specified, links that should have no colliders associated with it + merge_fixed_joints (bool): Whether to merge fixed joints or not + import_inertia_tensor (bool): Whether to import the URDF's native inertia tensor or not + dataset_name (str): Dataset name to which the USD will be written. Lives in get_dataset_path(dataset_name) + hull_count (int): Maximum number of convex hulls to decompose individual visual meshes into. + Only relevant if @collision_method is "coacd" + overwrite (bool): If set, will overwrite any pre-existing files + use_usda (bool): If set, will write files to .usda files instead of .usd + (bigger memory footprint, but human-readable) + + Returns: + 3-tuple: + - str: Absolute path to post-processed URDF file + - str: Absolute path to generated USD file + - Usd.Prim: Generated root USD prim (currently on active stage) + """ + # Make sure all scaling is positive + dataset_root = get_dataset_path(dataset_name) + model_dir = os.path.join(dataset_root, "objects", category, model) + os.makedirs(model_dir, exist_ok=overwrite) + # urdf_path = make_asset_positive(urdf_fpath=urdf_path) + + # Update collisions if requested + if collision_method is not None: + print("Generating collision approximation for URDF...") + get_collision_approximation_for_urdf( + urdf_path=urdf_path, + collision_method=collision_method, + hull_count=hull_count, + coacd_links=coacd_links, + convex_links=convex_links, + no_decompose_links=no_decompose_links, + visual_only_links=visual_only_links, + ) + + # Generate metadata + print("Recording object metadata from URDF...") + record_obj_metadata_from_urdf( + urdf_path=urdf_path, + obj_dir=model_dir, + joint_setting="zero", + overwrite=overwrite, + ) + + # Convert to USD + print("Converting obj URDF to USD...") + og.launch() + assert len(og.sim.scenes) == 0 + urdf_path, usd_path = convert_urdf_to_usd( + urdf_path=urdf_path, + obj_category=category, + obj_model=model, + dataset_root=dataset_root, + use_omni_convex_decomp=False, # We already pre-decomposed the values, so don' use omni convex decomp + use_usda=use_usda, + merge_fixed_joints=merge_fixed_joints, + import_inertia_tensor=import_inertia_tensor, + ) + + prim = import_obj_metadata( + usd_path=usd_path, + obj_category=category, + obj_model=model, + dataset_root=dataset_root, + ) + print( + f"\nConversion complete! Object has been successfully imported into OmniGibson-compatible USD, located at:\n\n{usd_path}\n" + ) + + return urdf_path, usd_path, prim diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7623e1bfd3f801b47917344ec9b93c838fa25d4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_utils.py @@ -0,0 +1,674 @@ +import argparse +import contextlib +from importlib.metadata import version +import inspect +import json +import os +from packaging.version import Version +import pathlib +import shutil +import subprocess +import tempfile +from collections import defaultdict +from copy import deepcopy +from pathlib import Path +from urllib.request import urlretrieve +import zipfile + +from huggingface_hub import hf_hub_download +from cryptography.fernet import Fernet + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.utils.ui_utils import create_module_logger + +if os.getenv("OMNIGIBSON_NO_OMNIVERSE", default=0) != "1": + import omnigibson.lazy as lazy + +# Create module logger +log = create_module_logger(module_name=__name__) + +# The latest version of the dataset that should be downloaded +BEHAVIOR_1K_ASSET_VERSION = "3.9.0" +OMNIGIBSON_ROBOT_ASSETS_VERSION = "3.8.2" +# The minimum compatible version of the dataset that should be used. +MINIMUM_ROBOT_ASSETS_VERSION = "3.8.2" + + +def is_dot_file(p): + """ + Check if a filename starts with a dot. + Note that while this does not actually correspond to checking for hidden files on Windows, the + files we want to ignore will still start with a dot and thus this works. + + Returns: + bool: true if a folder is hidden in the OS + """ + return p.startswith(".") + + +def get_dataset_path(dataset_name): + return os.path.join(gm.DATA_PATH, dataset_name) + + +def get_key_path(): + return os.path.join(gm.DATA_PATH, "omnigibson.key") + + +def get_avg_category_specs(): + """ + Load average object specs (dimension and mass) for objects + + Returns: + dict: Average category specifications for all object categories + """ + avg_obj_dim_file = os.path.join(og.example_config_path, "avg_category_specs.json") + if os.path.exists(avg_obj_dim_file): + with open(avg_obj_dim_file) as f: + return json.load(f) + else: + log.warning( + "Requested average specs of the object categories in the BEHAVIOR-1K Dataset of objects, but the " + "file cannot be found. Did you download the dataset? Returning an empty dictionary" + ) + return dict() + + +def get_behavior_1k_category_ids(): + """ + Get OmniGibson object categories + + Returns: + str: file path to the scene name + """ + behavior_1k_assets_path = get_dataset_path("behavior-1k-assets") + categories_files = os.path.join(behavior_1k_assets_path, "metadata", "categories.txt") + name_to_id = {} + with open(categories_files, "r") as fp: + for i, l in enumerate(fp.readlines()): + name_to_id[l.rstrip()] = i + return defaultdict(lambda: 255, name_to_id) + + +def get_available_behavior_1k_scenes(): + """ + OmniGibson interactive scenes + + Returns: + list: Available OmniGibson interactive scenes + """ + behavior_1k_assets_path = get_dataset_path("behavior-1k-assets") + behavior_1k_scenes_path = os.path.join(behavior_1k_assets_path, "scenes") + available_behavior_1k_scenes = sorted( + [f for f in os.listdir(behavior_1k_scenes_path) if (not is_dot_file(f) and f != "background")] + ) + return available_behavior_1k_scenes + + +def get_scene_path(scene_name, dataset_name="behavior-1k-assets"): + """ + Get OmniGibson scene path + + Args: + scene_name (str): scene name, e.g., "Rs_int" + + Returns: + str: file path to the scene name + """ + dataset_path = get_dataset_path(dataset_name) + scenes_path = os.path.join(dataset_path, "scenes") + log.info("Scene name: {}".format(scene_name)) + assert scene_name in os.listdir(scenes_path), "Scene {} does not exist".format(scene_name) + return os.path.join(scenes_path, scene_name) + + +def get_task_instance_path(scene_name, instance_name, mode="train"): + """ + Get task instance path + + Args: + scene_name (str): scene name, e.g., "Rs_int" + instance_name (str): instance name, e.g., "house_double_floor_lower_task_turning_on_radio_0_0_template" + mode (str): Instance split to load. One of "train", "public_test", or "hidden_test". + + Returns: + str: file path to the scene name + """ + mode_to_dir = { + "train": "scenes", + "public_test": os.path.join("scene_test", "public"), + "hidden_test": os.path.join("scene_test", "private"), + } + assert mode in mode_to_dir, f"Invalid task instance mode: {mode}" + task_instances_path_2026 = os.path.join( + gm.DATA_PATH, "2026-challenge-task-instances", mode_to_dir[mode], scene_name, "json", f"{instance_name}.json" + ) + return task_instances_path_2026 if os.path.exists(task_instances_path_2026) else None + + +def get_category_path(category_name, dataset_name="behavior-1k-assets"): + """ + Get OmniGibson object category path + + Args: + category_name (str): object category + + Returns: + str: file path to the object category + """ + dataset_path = get_dataset_path(dataset_name) + categories_path = os.path.join(dataset_path, "objects") + assert category_name in os.listdir(categories_path), "Category {} does not exist".format(category_name) + return os.path.join(categories_path, category_name) + + +def get_model_path(category_name, model_name, dataset_name="behavior-1k-assets"): + """ + Get OmniGibson object model path + + Args: + category_name (str): object category + model_name (str): object model + + Returns: + str: file path to the object model + """ + category_path = get_category_path(category_name, dataset_name=dataset_name) + assert model_name in os.listdir(category_path), "Model {} from category {} in dataset {} does not exist".format( + model_name, category_name, dataset_name + ) + return os.path.join(category_path, model_name) + + +def get_all_system_categories(include_cloth=False): + """ + Get OmniGibson all system categories + + Args: + include_cloth (bool): whether to include cloth category; default to only include non-cloth particle systems + + Returns: + list: all system categories + """ + behavior_1k_assets_path = get_dataset_path("behavior-1k-assets") + categories_path = os.path.join(behavior_1k_assets_path, "systems") + + categories = [f for f in os.listdir(categories_path) if not is_dot_file(f)] + if include_cloth: + categories.append("cloth") + return sorted(categories) + + +def get_all_object_categories(): + """ + Get OmniGibson all object categories + + Returns: + list: all object categories + """ + categories = {x.name for x in Path(gm.DATA_PATH).glob("*/objects/*") if x.is_dir() and not is_dot_file(x.name)} + return sorted(categories) + + +def get_all_object_models(): + """ + Get OmniGibson all object models + + Returns: + list: all object model paths + """ + return sorted({str(x) for x in Path(gm.DATA_PATH).glob("*/objects/*/*") if x.is_dir() and not is_dot_file(x.name)}) + + +def get_all_object_category_models(category): + """ + Get all object models from @category + + Args: + category (str): Object category name + + Returns: + list of str: all object models belonging to @category + """ + behavior_1k_assets_path = get_dataset_path("behavior-1k-assets") + categories_path = os.path.join(behavior_1k_assets_path, "objects", category) + return sorted(os.listdir(categories_path)) if os.path.exists(categories_path) else [] + + +def get_all_object_category_models_with_abilities(category, abilities): + """ + Get all object models from @category whose assets are properly annotated with necessary requirements to support + abilities @abilities + + Args: + category (str): Object category name + abilities (dict): Dictionary mapping requested abilities to keyword arguments to pass to the corresponding + object state constructors. The abilities' required annotations will be guaranteed for the returned + models + + Returns: + list of str: all object models belonging to @category which are properly annotated with necessary requirements + to support the requested list of @abilities + """ + # Avoid circular imports + from omnigibson.object_states.factory import get_requirements_for_ability, get_states_and_params_for_ability + from omnigibson.objects.dataset_object import DatasetObject + + # Get all valid models + all_models = get_all_object_category_models(category=category) + + # Generate all object states required per object given the requested set of abilities. We must + # apply the same per-(ability, state) param transform that object hydration uses (via the shared + # get_states_and_params_for_ability helper), otherwise a state's asset compatibility is checked + # with the wrong kwargs -- e.g. flammable's HeatSourceOrSink would be validated with + # requires_on_fire=False and wrongly demand a heatsource meta link. + abilities_info = { + ability: get_states_and_params_for_ability(ability, params) for ability, params in abilities.items() + } + + # Get mapping for class init kwargs + state_init_default_kwargs = dict() + + for ability, state_types_and_params in abilities_info.items(): + for state_type, _ in state_types_and_params: + # Add each state's dependencies, too. Note that only required dependencies are added. + for dependency in state_type.get_dependencies(): + if all(other_state != dependency for other_state, _ in state_types_and_params): + state_types_and_params.append((dependency, dict())) + + for state_type, _ in state_types_and_params: + default_kwargs = inspect.signature(state_type.__init__).parameters + state_init_default_kwargs[state_type] = { + kwarg: val.default + for kwarg, val in default_kwargs.items() + if kwarg != "self" and val.default != inspect._empty + } + + # Iterate over all models and sanity check each one, making sure they satisfy all the requested @abilities + valid_models = [] + + def supports_abilities(info, obj_prim): + for ability, states_and_params in info.items(): + # Check ability requirements + for requirement in get_requirements_for_ability(ability): + if not requirement.is_compatible_asset(prim=obj_prim)[0]: + return False + + # Check all link states + for state_type, params in states_and_params: + kwargs = deepcopy(state_init_default_kwargs[state_type]) + kwargs.update(params) + if not state_type.is_compatible_asset(prim=obj_prim, **kwargs)[0]: + return False + return True + + for model in all_models: + usd_path = DatasetObject.get_usd_path(category=category, model=model) + usd_path = usd_path.replace(".usd", ".encrypted.usd") + with decrypted(usd_path) as fpath: + stage = lazy.pxr.Usd.Stage.Open(fpath) + prim = stage.GetDefaultPrim() + if supports_abilities(abilities_info, prim): + valid_models.append(model) + + return valid_models + + +def get_attachment_meta_links(category, model): + """ + Get attachment meta links for an object model + + Args: + category (str): Object category name + model (str): Object model name + + Returns: + list of str: all attachment meta links for the object model + """ + # Avoid circular imports + from omnigibson.object_states import AttachedTo + from omnigibson.objects.dataset_object import DatasetObject + + usd_path = DatasetObject.get_usd_path(category=category, model=model) + usd_path = usd_path.replace(".usd", ".encrypted.usd") + with decrypted(usd_path) as fpath: + stage = lazy.pxr.Usd.Stage.Open(fpath) + prim = stage.GetDefaultPrim() + attachment_meta_links = [] + for child in prim.GetChildren(): + if child.GetTypeName() == "Xform": + if any(meta_link_type in child.GetName() for meta_link_type in AttachedTo.meta_link_types): + attachment_meta_links.append(child.GetName()) + return attachment_meta_links + + +def get_omnigibson_robot_asset_version(): + """ + Returns: + str: OmniGibson assets version + """ + try: + return (Path(get_dataset_path("omnigibson-robot-assets")) / "VERSION").read_text().strip() + except FileNotFoundError: + return None + + +def get_omnigibson_git_hash(): + """ + Returns: + str: OmniGibson commit hash + """ + try: + git_hash = subprocess.check_output( + ["git", "-C", Path(og.__file__).parent, "rev-parse", "HEAD"], shell=False, stderr=subprocess.DEVNULL + ) + return git_hash.decode("utf-8").strip() + except subprocess.CalledProcessError: + return None + + +def get_omnigibson_version(): + return og.__version__ + + +def get_bddl_version(): + return version("bddl") + + +def get_behavior_1k_assets_version(): + """ + Returns: + str: BEHAVIOR-1K dataset version + """ + try: + return (Path(get_dataset_path("behavior-1k-assets")) / "VERSION").read_text().strip() + except FileNotFoundError: + return None + + +def check_minimum_behavior_1k_assets_version(min_version_str): + current_version = get_behavior_1k_assets_version() + if current_version is None: + return False + + return Version(current_version) >= Version(min_version_str) + + +def get_texture_file(mesh_file): + """ + Get texture file + + Args: + mesh_file (str): path to mesh obj file + + Returns: + str: texture file path + """ + model_dir = os.path.dirname(mesh_file) + with open(mesh_file, "r") as f: + lines = [line.strip() for line in f.readlines() if "mtllib" in line] + if len(lines) == 0: + return + mtl_file = lines[0].split()[1] + mtl_file = os.path.join(model_dir, mtl_file) + + with open(mtl_file, "r") as f: + lines = [line.strip() for line in f.readlines() if "map_Kd" in line] + if len(lines) == 0: + return + texture_file = lines[0].split()[1] + texture_file = os.path.join(model_dir, texture_file) + + return texture_file + + +def download_and_unpack_zipped_dataset(dataset_name): + tempdir = tempfile.mkdtemp() + real_target = get_dataset_path(dataset_name) + if dataset_name == "behavior-1k-assets": + online_filename = f"behavior-1k-assets-{BEHAVIOR_1K_ASSET_VERSION}.zip" + elif dataset_name == "omnigibson-robot-assets": + online_filename = f"omnigibson-robot-assets-{OMNIGIBSON_ROBOT_ASSETS_VERSION}.zip" + else: + online_filename = f"{dataset_name}.zip" + local_path = hf_hub_download( + repo_id="behavior-1k/zipped-datasets", + filename=online_filename, + repo_type="dataset", + local_dir=tempdir, + ) + with zipfile.ZipFile(local_path, "r") as zip_ref: + zip_ref.extractall(real_target) + shutil.rmtree(tempdir) + + +def ensure_omnigibson_robot_assets_version(): + current_version = get_omnigibson_robot_asset_version() + if current_version is None or Version(current_version) < Version(MINIMUM_ROBOT_ASSETS_VERSION): + raise RuntimeError( + f"OmniGibson robot assets version {current_version} is older than the minimum compatible version " + f"{MINIMUM_ROBOT_ASSETS_VERSION}. Please run `python -m omnigibson.utils.asset_utils --update_omnigibson_robot_assets` to remove the existing installation and redownload." + ) + + +def download_omnigibson_robot_assets(upgrade: bool = False): + """ + Download OmniGibson robot assets + + Args: + upgrade (bool): If True, remove existing installation and redownload if no version or older version + """ + dataset_path = get_dataset_path("omnigibson-robot-assets") + current_version = get_omnigibson_robot_asset_version() + needs_upgrade = current_version is None or Version(current_version) < Version(MINIMUM_ROBOT_ASSETS_VERSION) + upgraded = False + if os.path.exists(dataset_path): + if upgrade and needs_upgrade: + print(f"Removing existing omnigibson-robot-assets (version: {current_version}) to upgrade...") + shutil.rmtree(dataset_path) + download_and_unpack_zipped_dataset("omnigibson-robot-assets") + upgraded = True + else: + print(f"OmniGibson robot assets already downloaded (version: {current_version}).") + else: + download_and_unpack_zipped_dataset("omnigibson-robot-assets") + upgraded = True + if upgraded: + new_version = get_omnigibson_robot_asset_version() + print(f"Successfully downloaded OmniGibson robot assets version {new_version}.") + + +def print_user_agreement(): + print( + "\n\nBEHAVIOR DATA BUNDLE END USER LICENSE AGREEMENT\n" + "Last revision: December 8, 2022\n" + "This License Agreement is for the BEHAVIOR Data Bundle (“Data”). It works with OmniGibson (“Software”) which is a software stack licensed under the MIT License, provided in this repository: https://github.com/StanfordVL/OmniGibson. The license agreements for OmniGibson and the Data are independent. This BEHAVIOR Data Bundle contains artwork and images (“Third Party Content”) from third parties with restrictions on redistribution. It requires measures to protect the Third Party Content which we have taken such as encryption and the inclusion of restrictions on any reverse engineering and use. Recipient is granted the right to use the Data under the following terms and conditions of this License Agreement (“Agreement”):\n\n" + '1. Use of the Data is permitted after responding "Yes" to this agreement. A decryption key will be installed automatically.\n' + "2. Data may only be used for non-commercial academic research. You may not use a Data for any other purpose.\n" + "3. The Data has been encrypted. You are strictly prohibited from extracting any Data from OmniGibson or reverse engineering.\n" + "4. You may only use the Data within OmniGibson.\n" + "5. You may not redistribute the key or any other Data or elements in whole or part.\n" + '6. THE DATA AND SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR SOFTWARE OR THE USE OR OTHER DEALINGS IN THE DATA OR SOFTWARE.\n\n' + ) + + +def download_key(): + if not os.path.exists(get_key_path()): + _ = (() == ()) + (() == ()) + __ = ((_ << _) << _) * _ + ___ = ( + ("c%"[:: (([] != []) - (() == ()))]) + * (((_ << _) << _) + (((_ << _) * _) + ((_ << _) + (_ + (() == ()))))) + % ( + (__ + (((_ << _) << _) + (_ << _))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ * _)))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ * _)))), + (__ + (((_ << _) << _) + ((_ << _) * _))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (((_ << _) << _) + (((_ << _) * _) + ((_ << _) + _))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ * _)))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + (((_ << _) * _) + _))), + (__ + (((_ << _) << _) + (() == ()))), + (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ * _) + (() == ())))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + _))), + (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + (_ * _)))), + (__ + (((_ << _) << _) + ((_ * _) + (() == ())))), + (__ + (((_ << _) << _) + (() == ()))), + (__ + (((_ << _) << _) + ((_ << _) * _))), + (__ + (((_ << _) << _) + ((_ << _) + (() == ())))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + _))), + (__ + (((_ << _) << _) + (_ + (() == ())))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (() == ()))))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + (() == ())))), + (__ + (((_ << _) << _) + _)), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))), + (__ + (((_ << _) * _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + (_ + (() == ())))), + (__ + (((_ << _) << _) + ((_ * _) + (() == ())))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))), + (__ + (((_ << _) << _) + ((_ * _) + (() == ())))), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))), + (__ + (((_ << _) << _) + ((_ << _) + (() == ())))), + (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + (() == ())))), + (__ + (((_ << _) << _) + _)), + (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))), + (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))), + (((_ << _) << _) + ((_ << _) + ((_ * _) + _))), + (__ + (((_ << _) << _) + ((_ << _) + (_ + (() == ()))))), + (__ + (((_ << _) << _) + ((_ * _) + (() == ())))), + (__ + (((_ << _) << _) + (((_ << _) * _) + ((_ << _) + (() == ()))))), + ) + ) + path = ___ + assert urlretrieve(path, get_key_path()), "Key download failed." + + +def download_behavior_1k_assets(accept_license=False): + """ + Download BEHAVIOR-1K dataset + """ + # Print user agreement + if os.path.exists(get_key_path()): + print("BEHAVIOR-1K dataset encryption key already installed.") + else: + if not accept_license: + print("\n") + print_user_agreement() + while input("Do you agree to the above terms for using BEHAVIOR-1K dataset? [y/n]") != "y": + print("You need to agree to the terms for using BEHAVIOR-1K dataset.") + + download_key() + + if os.path.exists(get_dataset_path("behavior-1k-assets")): + print("BEHAVIOR-1K dataset already installed.") + else: + download_and_unpack_zipped_dataset("behavior-1k-assets") + + +def download_2026_challenge_task_instances(): + if not os.path.exists(get_dataset_path("2026-challenge-task-instances")): + download_and_unpack_zipped_dataset("2026-challenge-task-instances") + print("2026 BEHAVIOR Challenge Task Instances updated.") + + +def download_2025_challenge_task_instances(): + if not os.path.exists(get_dataset_path("2025-challenge-task-instances")): + download_and_unpack_zipped_dataset("2025-challenge-task-instances") + print("2025 BEHAVIOR Challenge Tasks Instances updated.") + + +def decrypt_file(encrypted_filename, decrypted_filename): + with open(get_key_path(), "rb") as filekey: + key = filekey.read() + fernet = Fernet(key) + + with open(encrypted_filename, "rb") as enc_f: + encrypted = enc_f.read() + + decrypted = fernet.decrypt(encrypted) + + with open(decrypted_filename, "wb") as decrypted_file: + decrypted_file.write(decrypted) + + +def encrypt_file(original_filename, encrypted_filename=None, encrypted_file=None): + with open(get_key_path(), "rb") as filekey: + key = filekey.read() + fernet = Fernet(key) + + with open(original_filename, "rb") as org_f: + original = org_f.read() + + encrypted = fernet.encrypt(original) + + if encrypted_file is not None: + encrypted_file.write(encrypted) + else: + with open(encrypted_filename, "wb") as encrypted_file: + encrypted_file.write(encrypted) + + +@contextlib.contextmanager +def decrypted(encrypted_filename): + decrypted_filename_template = pathlib.Path(encrypted_filename.replace(".encrypted", "")) + decrypted_fd, decrypted_filename = tempfile.mkstemp( + suffix=decrypted_filename_template.suffix, prefix=decrypted_filename_template.stem, dir=og.tempdir + ) + os.close(decrypted_fd) + decrypt_file(encrypted_filename=encrypted_filename, decrypted_filename=decrypted_filename) + yield decrypted_filename + os.remove(decrypted_filename) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--download_omnigibson_robot_assets", action="store_true", help="download assets file") + parser.add_argument("--update_omnigibson_robot_assets", action="store_true", help="update assets file") + parser.add_argument("--download_behavior_1k_assets", action="store_true", help="download BEHAVIOR-1K Dataset") + parser.add_argument( + "--download_2025_challenge_task_instances", + action="store_true", + help="download 2025 BEHAVIOR Challenge Tasks dataset", + ) + parser.add_argument( + "--download_2026_challenge_task_instances", + action="store_true", + help="download 2026 BEHAVIOR Challenge Tasks dataset", + ) + parser.add_argument("--accept_license", action="store_true", help="pre-accept the BEHAVIOR-1K dataset license") + args = parser.parse_args() + + if args.download_omnigibson_robot_assets: + download_omnigibson_robot_assets() + if args.update_omnigibson_robot_assets: + download_omnigibson_robot_assets(upgrade=True) + if args.download_behavior_1k_assets: + download_behavior_1k_assets(accept_license=args.accept_license) + if args.download_2025_challenge_task_instances: + download_2025_challenge_task_instances() + if args.download_2026_challenge_task_instances: + download_2026_challenge_task_instances() + + og.shutdown() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/backend_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/backend_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d405044c8ffef93ae66aa5c72b0d369f0ad0bcda --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/backend_utils.py @@ -0,0 +1,175 @@ +import numpy as np +import torch as th + +import omnigibson.utils.transform_utils as TT +import omnigibson.utils.transform_utils_np as NT + + +# Global function for adding custom compute functions +def add_compute_function(name, np_function, th_function): + """ + Adds a custom compute function defined by @name + + Args: + name (str): name of the function to add + np_function (callable): numpy version of the function + th_function (callable): torch version of the function + """ + _ComputeNumpyBackend.set_custom_method(name, np_function) + _ComputeTorchBackend.set_custom_method(name, th_function) + + +class _ComputeBackend: + # Dictionary mapping custom externally-defined function name to function + _custom_fcns = None + + array = None + int_array = None + bool_array = None + bool_zeros = None + prod = None + cat = None + zeros = None + ones = None + to_numpy = None + from_numpy = None + to_torch = None + from_torch = None + allclose = None + arr_type = None + as_int = None + as_float32 = None + pinv = None + meshgrid = None + full = None + logical_or = None + all = None + abs = None + sqrt = None + norm = None + mean = None + sum = None + copy = None + eye = None + view = None + arange = None + where = None + squeeze = None + T = None + indices_where = None + item_bool = None + + @classmethod + def get_custom_method(cls, method_name): + """ + Gets a custom method from the internal backend + + Args: + method_name (str): Name of the method to get + """ + return cls._custom_fcns[method_name] + + @classmethod + def set_custom_method(cls, method_name, method): + """ + Sets a custom method to the internal backend + + Args: + method_name (str): Name of the method + method (callable): Custom method to add + """ + if cls._custom_fcns is None: + cls._custom_fcns = dict() + cls._custom_fcns[method_name] = method + + @classmethod + def set_methods_from_backend(cls, backend): + for attr, fcn in backend.__dict__.items(): + # Do not override reserved functions + if attr.startswith("__"): + continue + # Set function to this backend + setattr(cls, attr, fcn) + + +class _ComputeTorchBackend(_ComputeBackend): + array = lambda *args: th.tensor(*args, dtype=th.float32) + int_array = lambda *args: th.tensor(*args, dtype=th.int32) + bool_array = lambda *args: th.tensor(*args, dtype=th.bool) + bool_zeros = lambda *args: th.zeros(*args, dtype=th.bool) + prod = th.prod + cat = th.cat + zeros = lambda *args: th.zeros(*args, dtype=th.float32) + ones = lambda *args: th.ones(*args, dtype=th.float32) + to_numpy = lambda x: x.numpy() + from_numpy = lambda x: th.from_numpy(x) if isinstance(x, np.ndarray) else th.as_tensor(x) + to_torch = lambda x: x + from_torch = lambda x: x + allclose = th.allclose + arr_type = th.Tensor + as_int = lambda arr: arr.int() + as_float32 = lambda arr: arr.float() + pinv = th.linalg.pinv + meshgrid = lambda idx_a, idx_b: th.meshgrid(idx_a, idx_b, indexing="xy") + full = lambda shape, fill_value: th.full(shape, fill_value, dtype=th.float32) + logical_or = th.logical_or + all = th.all + abs = th.abs + sqrt = th.sqrt + norm = lambda val, dim=None, keepdim=False: th.norm(val, dim=dim, keepdim=keepdim) + mean = lambda val, dim=None, keepdim=False: th.mean(val, dim=dim, keepdim=keepdim) + sum = lambda val, dim=None, keepdim=False: th.sum(val, dim=dim, keepdim=keepdim) + copy = lambda arr: arr.clone() + eye = th.eye + view = lambda arr, shape: arr.view(shape) + arange = th.arange + where = th.where + squeeze = lambda arr, dim=None: arr.squeeze(dim=dim) + T = TT + indices_where = lambda mask: th.nonzero(mask, as_tuple=False).squeeze(-1) + item_bool = lambda x: bool(x.item()) + item_int = lambda x: int(x.item()) + item_float = lambda x: float(x.item()) + + +class _ComputeNumpyBackend(_ComputeBackend): + array = lambda *args: np.array(*args, dtype=np.float32) + int_array = lambda *args: np.array(*args, dtype=np.int32) + bool_array = lambda *args: np.array(*args, dtype=bool) + bool_zeros = lambda *args: np.zeros(*args, dtype=bool) + prod = np.prod + cat = lambda tensors, dim=0: np.concatenate(tensors, axis=dim) + zeros = lambda *args: np.zeros(*args, dtype=np.float32) + ones = lambda *args: np.ones(*args, dtype=np.float32) + to_numpy = lambda x: x + from_numpy = lambda x: x + to_torch = lambda x: th.from_numpy(x) if isinstance(x, np.ndarray) else th.as_tensor(x) + from_torch = lambda x: x.numpy() + allclose = np.allclose + arr_type = np.ndarray + as_int = lambda arr: arr.astype(int) + as_float32 = lambda arr: arr.astype(np.float32) + pinv = np.linalg.pinv + meshgrid = lambda idx_a, idx_b: np.ix_(idx_a, idx_b) + full = lambda shape, fill_value: np.full(shape, fill_value, dtype=np.float32) + logical_or = np.logical_or + all = np.all + abs = np.abs + sqrt = np.sqrt + norm = lambda val, dim=None, keepdim=False: np.linalg.norm(val, axis=dim, keepdims=keepdim) + mean = lambda val, dim=None, keepdim=False: np.mean(val, axis=dim, keepdims=keepdim) + sum = lambda val, dim=None, keepdim=False: np.sum(val, axis=dim, keepdims=keepdim) + copy = lambda arr: arr.copy() + eye = np.eye + view = lambda arr, shape: arr.reshape(shape) + arange = np.arange + where = np.where + squeeze = lambda arr, dim=None: arr.squeeze(axis=dim) + T = NT + indices_where = lambda mask: np.nonzero(mask)[0] + item_bool = lambda x: bool(x) + item_int = lambda x: int(x) + item_float = lambda x: float(x) + + +_compute_backend = _ComputeBackend diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/bddl_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/bddl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f239d38f6610b6df8488c2fae72489b9978f8261 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/bddl_utils.py @@ -0,0 +1,1550 @@ +import random +import re +from collections import defaultdict +from copy import deepcopy + +import networkx as nx +import torch as th + +from bddl.condition_evaluation import Negation +from bddl.knowledge_base import KnowledgeBase +from bddl import predicates as bddl_predicates +from bddl.predicates import Predicate + +import omnigibson as og +from omnigibson import object_states +from omnigibson.macros import create_module_macros +from omnigibson.object_states.factory import _KINEMATIC_STATE_SET, get_system_states +from omnigibson.object_states.object_state_base import AbsoluteObjectState, RelativeObjectState +from omnigibson.utils.asset_utils import ( + get_all_object_categories, + get_all_object_category_models_with_abilities, + get_attachment_meta_links, +) +from omnigibson.utils.constants import PrimType +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.MIN_DYNAMIC_SCALE = 0.5 +m.DYNAMIC_SCALE_INCREMENT = 0.1 + +GOOD_MODELS = { + # "jar": {"kijnrj"}, + # "carton": {"causya", "msfzpz", "sxlklf"}, + # "hamper": {"drgdfh", "hlgjme", "iofciz", "pdzaca", "ssfvij"}, + # "hanging_plant": set(), + # "hardback": {"esxakn"}, + # "notebook": {"hwhisw"}, + # "paperback": {"okcflv"}, + # "plant_pot": {"ihnfbi", "vhglly", "ygrtaz"}, + # "pot_plant": {"cvthyv", "dbjcic", "cecdwu"}, + # "recycling_bin": {"nuoypc"}, + # "tray": {"gsxbym", "huwhjg", "txcjux", "uekqey", "yqtlhy"}, +} + +GOOD_BBOXES = { + # "basil": { + # "dkuhvb": [0.07286304, 0.0545199, 0.03108144], + # }, + # "basil_jar": { + # "swytaw": [0.22969539, 0.19492961, 0.30791675], + # }, + # "bicycle_chain": { + # "czrssf": [0.242, 0.012, 0.021], + # }, + # "clam": { + # "ihhbfj": [0.078, 0.081, 0.034], + # }, + # "envelope": { + # "urcigc": [0.004, 0.06535058, 0.10321216], + # }, + # "mail": { + # "azunex": [0.19989018, 0.005, 0.12992871], + # "gvivdi": [0.28932137, 0.005, 0.17610794], + # "mbbwhn": [0.27069291, 0.005, 0.13114884], + # "ojkepk": [0.19092424, 0.005, 0.13252979], + # "qpwlor": [0.22472473, 0.005, 0.18983322], + # }, + # "pill_bottle": { + # "csvdbe": [0.078, 0.078, 0.109], + # "wsasmm": [0.078, 0.078, 0.109], + # }, + # "plant_pot": { + # "ihnfbi": [0.24578613, 0.2457865, 0.18862737], + # }, + # "razor": { + # "jocsgp": [0.046, 0.063, 0.204], + # }, + # "recycling_bin": { + # "nuoypc": [0.69529409, 0.80712041, 1.07168694], + # }, + # "tupperware": { + # "mkstwr": [0.33, 0.33, 0.21], + # }, + # "copper_wire": { + # "nzafel": [0.1762, 0.17655, 0.0631], + # }, + # "backpack": { + # "gvbiwl": [0.7397, 0.6109, 0.6019], + # }, +} + +BAD_CLOTH_MODELS = { + # "bandana": {"wbhliu"}, + # "curtain": {"ohvomi", "shbakk"}, + # "cardigan": {"itrkhr"}, + # "sweatshirt": {"nowqqh"}, + # "jeans": {"nmvvil", "pvzxyp"}, + # "pajamas": {"rcgdde"}, + # "polo_shirt": {"vqbvph"}, + # "vest": {"girtqm"}, # bddl NOT FIXED + # "onesie": {"pbytey"}, + # "dishtowel": {"ltydgg"}, + # "dress": {"gtghon"}, + # "hammock": {"aiftuk", "fglfga", "klhkgd", "lqweda", "qewdqa"}, + # "jacket": {"kiiium", "nogevo", "remcyk"}, + # "quilt": {"mksdlu", "prhems"}, + # "pennant": {"tfnwti"}, + # "pillowcase": {"dtoahb", "yakvci"}, + # "rubber_glove": {"leuiso"}, + # "scarf": {"kclcrj"}, + # "sock": {"vpafgj"}, + # "tank_top": {"fzldgi"}, +} + + +def synset_from_bddl_inst(bddl_inst): + """Derive synset from a BDDL instance name, e.g. 'almond.n.01_1' -> 'almond.n.01'.""" + return "_".join(bddl_inst.split("_")[:-1]) + + +def is_system_bddl_inst(bddl_inst): + """Check if a BDDL instance refers to a substance/system.""" + return is_substance_synset(synset_from_bddl_inst(bddl_inst)) + + +def og_categories_from_bddl_inst(bddl_inst): + """Get OG categories for a BDDL instance.""" + synset_obj = get_knowledge_base().get_synset(synset_from_bddl_inst(bddl_inst)) + synset_and_descendants = [synset_obj] + sorted(synset_obj.descendants, key=lambda s: s.name) + if synset_obj.is_substance: + return [ps.name for s in synset_and_descendants for ps in s.particle_systems] + return [c.name for s in synset_and_descendants if s.is_leaf for c in s.categories] + + +def is_substance_synset(synset): + synset_obj = get_knowledge_base().get_synset(synset) + return synset_obj is not None and synset_obj.is_substance + + +def get_system_name_by_synset(synset): + synset_obj = get_knowledge_base().get_synset(synset) + synset_and_descendants = [synset_obj] + sorted(synset_obj.descendants, key=lambda s: s.name) + systems = [ps.name for s in synset_and_descendants for ps in s.particle_systems] + assert len(systems) == 1, f"Got zero or multiple systems for {synset}: {systems}" + return systems[0] + + +def process_single_condition(condition): + """ + Processes a single BDDL condition + + Args: + condition (Condition): Condition to process + + Returns: + 2-tuple: + - Expression: Condition's expression + - bool: Whether this evaluated condition is positive or negative + """ + if not isinstance(condition.children[0], Negation) and not isinstance(condition.children[0], Predicate): + log.debug(("Skipping over sampling of predicate that is not a negation or a generic predicate")) + return None, None + + if isinstance(condition.children[0], Negation): + condition = condition.children[0].children[0] + positive = False + else: + condition = condition.children[0] + positive = True + + return condition, positive + + +PREDICATE_TO_STATE = { + bddl_predicates.Inside: object_states.Inside, + bddl_predicates.NextTo: object_states.NextTo, + bddl_predicates.OnTop: object_states.OnTop, + bddl_predicates.Under: object_states.Under, + bddl_predicates.Touching: object_states.Touching, + bddl_predicates.Covered: object_states.Covered, + bddl_predicates.Contains: object_states.Contains, + bddl_predicates.Saturated: object_states.Saturated, + bddl_predicates.Filled: object_states.Filled, + bddl_predicates.Cooked: object_states.Cooked, + bddl_predicates.Frozen: object_states.Frozen, + bddl_predicates.Hot: object_states.Heated, + bddl_predicates.Open: object_states.Open, + bddl_predicates.ToggledOn: object_states.ToggledOn, + bddl_predicates.OnFire: object_states.OnFire, + bddl_predicates.Attached: object_states.AttachedTo, + bddl_predicates.Overlaid: object_states.Overlaid, + bddl_predicates.Folded: object_states.Folded, + bddl_predicates.Unfolded: object_states.Unfolded, + bddl_predicates.Draped: object_states.Draped, +} + +KINEMATIC_STATES_BDDL = frozenset([state.__name__.lower() for state in _KINEMATIC_STATE_SET] + ["attached"]) +UNSAMPLEABLE_PREDICATES = frozenset([bddl_predicates.InSource, bddl_predicates.Future, bddl_predicates.Real]) + + +def evaluate_bddl_predicate(predicate_cls, *entities): + """Evaluate a BDDL predicate against simulator objects. + + Args: + predicate_cls: A :class:`~bddl.predicates.Predicate` subclass. + *entities: Raw simulator objects (or None for nonexistent objects). + + Returns: + bool: Whether the predicate is satisfied. + """ + if predicate_cls is bddl_predicates.InSource: + return True + if predicate_cls is bddl_predicates.Future: + return entities[0] is None + if predicate_cls is bddl_predicates.Real: + return entities[0] is not None + + state_class = PREDICATE_TO_STATE[predicate_cls] + if predicate_cls.arity == 2: + obj1, obj2 = entities[0], entities[1] + if obj1 is None or not obj1.initialized: + return False + if obj2 is None or not obj2.initialized: + return False + return obj1.states[state_class].get_value(obj2) + else: + obj = entities[0] + if obj is None or not obj.initialized: + return False + return obj.states[state_class].get_value() + + +def sample_bddl_predicate(predicate_cls, *args, **kwargs): + """Request the simulator to set a BDDL predicate to a desired state. + + Args: + predicate_cls: A :class:`~bddl.predicates.Predicate` subclass. + *args: For unary predicates: (obj, binary_state). For binary: (obj1, obj2, binary_state). + **kwargs: Extra arguments forwarded to set_value (e.g. reset_before_sampling). + + Returns: + bool or None: Whether sampling succeeded. + """ + if predicate_cls in UNSAMPLEABLE_PREDICATES: + raise NotImplementedError(f"Cannot sample unsampleable predicate: {predicate_cls.__name__}") + + state_class = PREDICATE_TO_STATE[predicate_cls] + if predicate_cls.arity == 2: + obj1, obj2, binary_state = args[0], args[1], args[2] + if obj2 is None or not obj2.initialized: + return None + return obj1.states[state_class].set_value(obj2, binary_state, **kwargs) + else: + obj, binary_state = args[0], args[1] + return obj.states[state_class].set_value(binary_state, **kwargs) + + +# Shared KnowledgeBase instance for all of OmniGibson. Use the getter for lazy access. +_KB = None + + +def get_knowledge_base(): + global _KB + if _KB is None: + _KB = KnowledgeBase(verbose=False) + + return _KB + + +def get_behavior_activities(): + return sorted(set(t.name.rsplit("-", 1)[0] for t in get_knowledge_base().all_tasks())) + + +def _populate_input_output_objects_systems(og_recipe, input_synsets, output_synsets): + # Map input/output synsets into input/output objects and systems. + for synsets, obj_key, system_key in zip( + (input_synsets, output_synsets), ("input_objects", "output_objects"), ("input_systems", "output_systems") + ): + for synset, count in synsets.items(): + assert ( + get_knowledge_base().get_synset(synset).is_leaf + ), f"Synset {synset} must be a leaf node in the taxonomy!" + if is_substance_synset(synset): + og_recipe[system_key].append(get_system_name_by_synset(synset)) + else: + obj_categories = [c.name for c in get_knowledge_base().get_synset(synset).categories] + assert ( + len(obj_categories) == 1 + ), f"Object synset {synset} must map to exactly one object category! Now: {obj_categories}." + og_recipe[obj_key][obj_categories[0]] = count + + # Assert only one of output_objects or output_systems is not None + assert ( + len(og_recipe["output_objects"]) == 0 or len(og_recipe["output_systems"]) == 0 + ), "Recipe can only generate output objects or output systems, but not both!" + + +def _populate_input_output_states(og_recipe, input_states, output_states): + # Apply post-processing for input/output states if specified. + # States are dicts mapping synset keys to lists of StateCondition instances. + for synsets_to_states, states_key in zip((input_states, output_states), ("input_states", "output_states")): + if synsets_to_states is None: + continue + for synsets, state_conditions in synsets_to_states.items(): + # For unary/binary states, synsets is a single synset or a comma-separated pair of synsets, respectively + synset_split = synsets.split(",") + if len(synset_split) == 1: + first_synset = synset_split[0] + second_synset = None + else: + first_synset, second_synset = synset_split + + # Assert the first synset is an object because the systems don't have any states. + assert ( + get_knowledge_base().get_synset(first_synset).is_leaf + ), f"Input/output state synset {first_synset} must be a leaf node in the taxonomy!" + assert not is_substance_synset( + first_synset + ), f"Input/output state synset {first_synset} must be applied to an object, not a substance!" + obj_categories = [c.name for c in get_knowledge_base().get_synset(first_synset).categories] + assert ( + len(obj_categories) == 1 + ), f"Input/output state synset {first_synset} must map to exactly one object category! Now: {obj_categories}." + first_obj_category = obj_categories[0] + + if second_synset is None: + for sc in state_conditions: + state_class = PREDICATE_TO_STATE[sc.predicate] + assert issubclass( + state_class, AbsoluteObjectState + ), f"Input/output state type {sc.predicate.__name__} must be a unary state!" + og_recipe[states_key][first_obj_category]["unary"].append((state_class, sc.value)) + else: + assert ( + get_knowledge_base().get_synset(second_synset).is_leaf + ), f"Input/output state synset {second_synset} must be a leaf node in the taxonomy!" + if is_substance_synset(second_synset): + second_obj_category = get_system_name_by_synset(second_synset) + is_substance = True + else: + obj_categories = [c.name for c in get_knowledge_base().get_synset(second_synset).categories] + assert ( + len(obj_categories) == 1 + ), f"Input/output state synset {second_synset} must map to exactly one object category! Now: {obj_categories}." + second_obj_category = obj_categories[0] + is_substance = False + + for sc in state_conditions: + state_class = PREDICATE_TO_STATE[sc.predicate] + assert issubclass( + state_class, RelativeObjectState + ), f"Input/output state type {sc.predicate.__name__} must be a binary state!" + assert is_substance == ( + state_class in get_system_states() + ), f"Input/output state type {sc.predicate.__name__} system state inconsistency found!" + if is_substance: + og_recipe[states_key][first_obj_category]["binary_system"].append( + (state_class, second_obj_category, sc.value) + ) + else: + assert ( + states_key != "output_states" + ), f"Output state type {sc.predicate.__name__} can only be used in input states!" + og_recipe[states_key][first_obj_category]["binary_object"].append( + (state_class, second_obj_category, sc.value) + ) + + +def _populate_filter_categories(og_recipe, filter_name, synsets): + # Map synsets to categories. + if synsets is not None: + og_recipe[f"{filter_name}_categories"] = set() + for synset in synsets: + assert ( + get_knowledge_base().get_synset(synset).is_leaf + ), f"Synset {synset} must be a leaf node in the taxonomy!" + assert not is_substance_synset(synset), f"Synset {synset} must be applied to an object, not a substance!" + for category in [c.name for c in get_knowledge_base().get_synset(synset).categories]: + og_recipe[f"{filter_name}_categories"].add(category) + + +def translate_bddl_recipe_to_og_recipe(recipe): + """Translate a BDDL Recipe dataclass to an OG recipe dict. + + Args: + recipe (bddl.transition_rules.Recipe): A parsed BDDL recipe instance. + + Returns: + dict: OG-format recipe dict ready for ``RecipeRule.add_recipe(**og_recipe)``. + """ + from bddl.knowledge_base import CookingRecipe, MachineRecipe + + # Determine fillable/heatsource synsets from recipe type + fillable_synsets = None + heatsource_synsets = None + timesteps = 1 + if isinstance(recipe, CookingRecipe): + fillable_synsets = recipe.container_synsets or None + heatsource_synsets = recipe.heatsource_synsets or None + timesteps = recipe.timesteps if recipe.timesteps is not None else 1 + elif isinstance(recipe, MachineRecipe): + fillable_synsets = recipe.machine_synsets or None + + og_recipe = { + "name": recipe.name, + "input_objects": dict(), + "input_systems": list(), + "output_objects": dict(), + "output_systems": list(), + "input_states": defaultdict(lambda: defaultdict(list)), + "output_states": defaultdict(lambda: defaultdict(list)), + "fillable_categories": None, + "heatsource_categories": None, + "timesteps": timesteps, + } + + _populate_input_output_objects_systems( + og_recipe=og_recipe, input_synsets=recipe.input_synsets, output_synsets=recipe.output_synsets + ) + _populate_input_output_states( + og_recipe=og_recipe, input_states=recipe.input_states, output_states=recipe.output_states + ) + _populate_filter_categories(og_recipe=og_recipe, filter_name="fillable", synsets=fillable_synsets) + _populate_filter_categories(og_recipe=og_recipe, filter_name="heatsource", synsets=heatsource_synsets) + + return og_recipe + + +def translate_bddl_washer_rule_to_og_washer_rule(washer_rule): + """Translate a BDDL WasherRecipe to an OG washer rule dict. + + Args: + washer_rule (bddl.knowledge_base.WasherRecipe): Parsed washer recipe. + + Returns: + dict: Maps system name (str) to None (never remove), [] (always remove), + or list of system names (remove if any solvent present). + """ + og_washer_rule = dict() + for solute, solvents in washer_rule.conditions.items(): + assert get_knowledge_base().get_synset(solute).is_leaf, f"Synset {solute} must be a leaf node in the taxonomy!" + assert is_substance_synset(solute), f"Synset {solute} must be a substance synset!" + solute_name = get_system_name_by_synset(solute) + if solvents is None: + og_washer_rule[solute_name] = None + else: + solvent_names = [] + for solvent in solvents: + assert ( + get_knowledge_base().get_synset(solvent).is_leaf + ), f"Synset {solvent} must be a leaf node in the taxonomy!" + assert is_substance_synset(solvent), f"Synset {solvent} must be a substance synset!" + solvent_name = get_system_name_by_synset(solvent) + solvent_names.append(solvent_name) + og_washer_rule[solute_name] = solvent_names + return og_washer_rule + + +class BDDLSampler: + def __init__(self, env, env_idx, activity_conditions, object_scope): + # Avoid circular imports here + from omnigibson.scenes.traversable_scene import TraversableScene + + # Store internal variables from inputs + self._env = env + self._scene = env.scenes[env_idx] + self._scene_model = self._scene.scene_model if isinstance(self._scene, TraversableScene) else None + self._agent = self._scene.robots[0] + + self._compiled_task = None + self._activity_conditions = activity_conditions + self._object_scope = object_scope + self._object_instance_to_synset = { + obj_inst: obj_cat + for obj_cat in self._activity_conditions.parsed_objects + for obj_inst in self._activity_conditions.parsed_objects[obj_cat] + } + self._substance_instances = { + obj_inst + for obj_inst in self._object_scope.keys() + if is_substance_synset(self._object_instance_to_synset[obj_inst]) + } + + # Initialize other variables that will be filled in later + self._sampling_whitelist = None # Maps str to str to list + self._sampling_blacklist = None # Maps str to str to list + self._room_type_to_object_instance = None # dict + self._inroom_object_instances = None # set of str + self._object_sampling_orders = None # dict mapping str to list of str + self._sampled_objects = None # set of USDObject + self._future_obj_instances = None # set of str + self._inroom_object_conditions = None # list of (condition, positive) tuple + self._inroom_object_scope_filtered_initial = None # dict mapping str to sim object or None + self._attached_objects = defaultdict(set) # dict mapping str to set of str + + def _sample_predicate(self, predicate_cls, *args, **kwargs): + """Wrapper around sample_bddl_predicate that resolves string instance names to sim objects.""" + resolved = [self._object_scope.get(a, a) if isinstance(a, str) else a for a in args] + return sample_bddl_predicate(predicate_cls, *resolved, **kwargs) + + def assign_objects(self, sampling_whitelist=None, sampling_blacklist=None): + """Assign inroom objects and import sampleable objects into the scene. + + This is phase 1 of sampling: it finds/imports all objects needed by the + task without requiring compiled conditions. After this call, the object + scope is populated and room instances can be determined for compilation. + + Args: + sampling_whitelist (None or dict): Maps synset name to dict of + category -> list of valid models. + sampling_blacklist (None or dict): Maps synset name to dict of + category -> list of invalid models. + + Returns: + 2-tuple: + - bool: Whether object assignment was successful + - None or str: None if successful, otherwise the error message + """ + log.info("Assigning objects for task...") + self._sampling_whitelist = sampling_whitelist + self._sampling_blacklist = sampling_blacklist + + # Derive future object instances from parsed initial conditions + self._future_obj_instances = { + cond[1] for cond in self._activity_conditions.parsed_initial_conditions if cond[0] == "future" + } + + error_msg = self._parse_inroom_object_room_assignment() + if error_msg: + log.error(error_msg) + return False, error_msg + + error_msg = self._parse_attached_states() + if error_msg: + log.error(error_msg) + return False, error_msg + + error_msg = self._build_inroom_object_scope() + if error_msg: + log.error(error_msg) + return False, error_msg + + error_msg = self._import_sampleable_objects() + if error_msg: + log.error(error_msg) + return False, error_msg + + self._object_scope["agent.n.01_1"] = self._agent + + return True, None + + def sample_states(self, compiled_task, validate_goal=False): + """Sample object states to satisfy initial (and optionally goal) conditions. + + This is phase 2 of sampling: it requires a compiled task with condition + trees. Must be called after :meth:`assign_objects` and after the task + has been compiled with the correct scene layout. + + Args: + compiled_task: A :class:`CompiledTask` with compiled condition trees. + validate_goal (bool): Whether the goal should also be validated. + + Returns: + 2-tuple: + - bool: Whether sampling was successful + - None or str: None if successful, otherwise the error message + """ + log.info("Sampling states...") + self._compiled_task = compiled_task + + error_msg = self._build_sampling_order() + if error_msg: + log.error(error_msg) + return False, error_msg + + accept_scene, feedback = self._sample_all_conditions(validate_goal=validate_goal) + if not accept_scene: + return accept_scene, feedback + + log.info("Sampling succeeded!") + return True, None + + def _sample_all_conditions(self, validate_goal=False): + """ + Run sampling for this BEHAVIOR task + + Args: + validate_goal (bool): Whether the goal should be validated or not + + Returns: + 2-tuple: + - bool: Whether sampling was successful or not + - None or str: None if successful, otherwise the associated error message + """ + # Auto-initialize all sampleable objects + og.sim.play() + try: + # Update the scene to include the latest robots / objects + self._scene.update_initial_file() + self._scene.reset() + + error_msg = self._sample_initial_conditions() + if error_msg: + log.error(error_msg) + return False, error_msg + + if validate_goal: + error_msg = self._sample_goal_conditions() + if error_msg: + log.error(error_msg) + return False, error_msg + + error_msg = self._sample_initial_conditions_final() + if error_msg: + log.error(error_msg) + return False, error_msg + + self._scene.update_initial_file() + + return True, None + finally: + og.sim.stop() + + def _parse_inroom_object_room_assignment(self): + """ + Infers which rooms each object is assigned to + """ + self._room_type_to_object_instance = dict() + self._inroom_object_instances = set() + for cond in self._activity_conditions.parsed_initial_conditions: + if cond[0] == "inroom": + obj_inst, room_type = cond[1], cond[2] + obj_synset = self._object_instance_to_synset[obj_inst] + abilities = get_knowledge_base().get_synset(obj_synset).abilities + if "sceneObject" not in abilities: + # Invalid room assignment + return ( + f"You have assigned room type for [{obj_synset}], but [{obj_synset}] is sampleable. " + f"Only non-sampleable (scene) objects can have room assignment." + ) + if self._scene_model is not None and room_type not in self._scene.seg_map.room_sem_name_to_ins_name: + # Missing room type + return f"Room type [{room_type}] missing in scene [{self._scene_model}]." + if room_type not in self._room_type_to_object_instance: + self._room_type_to_object_instance[room_type] = [] + self._room_type_to_object_instance[room_type].append(obj_inst) + + if obj_inst in self._inroom_object_instances: + # Duplicate room assignment + return f"Object [{obj_inst}] has more than one room assignment" + + self._inroom_object_instances.add(obj_inst) + + def _parse_attached_states(self): + """ + Infers which objects are attached to which other objects. + If a category-level attachment is specified, it will be expanded to all instances of that category. + E.g. if the goal condition requires corks to be attached to bottles, every cork needs to be able to + attach to every bottle. + """ + for cond in self._activity_conditions.parsed_initial_conditions: + if cond[0] == "attached": + obj_inst, parent_inst = cond[1], cond[2] + if obj_inst not in self._object_scope or parent_inst not in self._object_scope: + return f"Object [{obj_inst}] or parent [{parent_inst}] in attached initial condition not found in object scope" + self._attached_objects[obj_inst].add(parent_inst) + + ground_attached_conditions = [] + conditions_to_check = self._activity_conditions.parsed_goal_conditions.copy() + while conditions_to_check: + new_conditions_to_check = [] + for cond in conditions_to_check: + if cond[0] == "attached": + ground_attached_conditions.append(cond) + else: + new_conditions_to_check.extend([ele for ele in cond if isinstance(ele, list)]) + conditions_to_check = new_conditions_to_check + + for cond in ground_attached_conditions: + obj_inst, parent_inst = cond[1].lstrip("?"), cond[2].lstrip("?") + if obj_inst in self._object_scope: + obj_insts = [obj_inst] + elif obj_inst in self._activity_conditions.parsed_objects: + obj_insts = self._activity_conditions.parsed_objects[obj_inst] + else: + return f"Object [{obj_inst}] in attached goal condition not found in object scope or parsed objects" + + if parent_inst in self._object_scope: + parent_insts = [parent_inst] + elif parent_inst in self._activity_conditions.parsed_objects: + parent_insts = self._activity_conditions.parsed_objects[parent_inst] + else: + return f"Parent [{parent_inst}] in attached goal condition not found in object scope or parsed objects" + + for obj_inst in obj_insts: + for parent_inst in parent_insts: + self._attached_objects[obj_inst].add(parent_inst) + + def _build_sampling_order(self): + """ + Sampling orders is a list of lists: [[batch_1_inst_1, ... batch_1_inst_N], [batch_2_inst_1, batch_2_inst_M], ...] + Sampling should happen for batch 1 first, then batch 2, so on and so forth + Example: OnTop(plate, table) should belong to batch 1, and OnTop(apple, plate) should belong to batch 2 + """ + unsampleable_conditions = [] + sampling_groups = {group: [] for group in ("kinematic", "particle", "unary")} + self._object_sampling_conditions = {group: [] for group in ("kinematic", "particle", "unary")} + self._object_sampling_orders = {group: [] for group in ("kinematic", "particle", "unary")} + self._inroom_object_conditions = [] + + # First, sort initial conditions into kinematic, particle and unary groups + # bddl.condition_evaluation.HEAD, each with one child. + # This child is either a ObjectStateUnaryPredicate/ObjectStateBinaryPredicate or + # a Negation of a ObjectStateUnaryPredicate/ObjectStateBinaryPredicate + for condition in self._compiled_task.initial_conditions: + condition, positive = process_single_condition(condition) + if condition is None: + continue + + # Sampled conditions must always be positive + # Non-positive (e.g.: NOT onTop) is not restrictive enough for sampling + if condition.STATE_NAME in KINEMATIC_STATES_BDDL and not positive: + return "Initial condition has negative kinematic conditions: {}".format(condition.body) + + # Store any unsampleable conditions separately + if type(condition) in UNSAMPLEABLE_PREDICATES: + unsampleable_conditions.append(condition) + continue + + # Infer the group the condition and its object instances belong to + # (a) Kinematic (binary) conditions, where (ent0, ent1) are both objects + # (b) Particle (binary) conditions, where (ent0, ent1) are (object, substance) + # (d) Unary conditions, where (ent0,) is an object + # Binary conditions have length 2: (ent0, ent1) + if len(condition.body) == 2: + group = "particle" if condition.body[1] in self._substance_instances else "kinematic" + else: + assert len(condition.body) == 1, ( + f"Got invalid parsed initial condition; body length should either be 2 or 1. " + f"Got body: {condition.body} for condition: {condition}" + ) + group = "unary" + sampling_groups[group].append(condition.body) + self._object_sampling_conditions[group].append((condition, positive)) + + # If the condition involves any non-sampleable object (e.g.: furniture), it's a non-sampleable condition + # This means that there's no ordering constraint in terms of sampling, because we know the, e.g., furniture + # object already exists in the scene and is placed, so these specific conditions can be sampled without + # any dependencies + if len(self._inroom_object_instances.intersection(set(condition.body))) > 0: + self._inroom_object_conditions.append((condition, positive)) + + # Now, sort each group, ignoring the futures (since they don't get sampled) + # First handle kinematics, then particles, then unary + + # Start with the non-sampleable objects as the first sampled set, then infer recursively + cur_batch = self._inroom_object_instances + while len(cur_batch) > 0: + next_batch = set() + for cur_batch_inst in cur_batch: + inst_batch = set() + for condition, _ in self._object_sampling_conditions["kinematic"]: + if condition.body[1] == cur_batch_inst: + inst_batch.add(condition.body[0]) + next_batch.add(condition.body[0]) + if len(inst_batch) > 0: + self._object_sampling_orders["kinematic"].append(inst_batch) + cur_batch = next_batch + + # Now parse particles -- simply unordered, since particle systems shouldn't impact each other + self._object_sampling_orders["particle"].append({cond[0] for cond in sampling_groups["particle"]}) + sampled_particle_entities = {cond[1] for cond in sampling_groups["particle"]} + + # Finally, parse unaries -- this is simply unordered, since it is assumed that unary predicates do not + # affect each other + self._object_sampling_orders["unary"].append({cond[0] for cond in sampling_groups["unary"]}) + + # Aggregate future objects and any unsampleable obj instances + # Unsampleable obj instances are strictly a superset of future obj instances + unsampleable_obj_instances = {cond.body[-1] for cond in unsampleable_conditions} + self._future_obj_instances = { + cond.body[0] for cond in unsampleable_conditions if isinstance(cond, bddl_predicates.Future) + } + + nonparticle_entities = set(self._object_scope.keys()) - self._substance_instances + + # Sanity check kinematic objects -- any non-system must be kinematically sampled + remaining_kinematic_entities = ( + nonparticle_entities + - unsampleable_obj_instances + - self._inroom_object_instances + - set.union(*(self._object_sampling_orders["kinematic"] + [set()])) + ) + + # Possibly remove the agent entity if we're in an empty scene -- i.e.: no kinematic sampling needed for the + # agent + if self._scene_model is None: + remaining_kinematic_entities -= {"agent.n.01_1"} + + if len(remaining_kinematic_entities) != 0: + return ( + f"Some objects do not have any kinematic condition defined for them in the initial conditions: " + f"{', '.join(remaining_kinematic_entities)}" + ) + + # Sanity check particle systems -- any non-future system must be sampled as part of particle groups + remaining_particle_entities = self._substance_instances - unsampleable_obj_instances - sampled_particle_entities + if len(remaining_particle_entities) != 0: + return ( + f"Some systems do not have any particle condition defined for them in the initial conditions: " + f"{', '.join(remaining_particle_entities)}" + ) + + def _build_inroom_object_scope(self): + """ + Store simulator object options for non-sampleable objects in self.inroom_object_scope + { + "living_room": { + "table1": { + "living_room_0": [URDFObject, URDFObject, URDFObject], + "living_room_1": [URDFObject] + }, + "table2": { + "living_room_0": [URDFObject, URDFObject], + "living_room_1": [URDFObject, URDFObject] + }, + "chair1": { + "living_room_0": [URDFObject], + "living_room_1": [URDFObject] + }, + } + } + """ + room_type_to_scene_objs = {} + for room_type in self._room_type_to_object_instance: + room_type_to_scene_objs[room_type] = {} + for obj_inst in self._room_type_to_object_instance[room_type]: + room_type_to_scene_objs[room_type][obj_inst] = {} + obj_synset = self._object_instance_to_synset[obj_inst] + synset_whitelist = ( + None if self._sampling_whitelist is None else self._sampling_whitelist.get(obj_synset, None) + ) + synset_blacklist = ( + None if self._sampling_blacklist is None else self._sampling_blacklist.get(obj_synset, None) + ) + + # We allow burners to be used as if they are stoves + # No need to safeguard check for subtree_substances because inroom objects will never be substances + _so = get_knowledge_base().get_synset(obj_synset) + categories = [ + c.name + for s in [_so] + sorted(_so.descendants, key=lambda x: x.name) + if s.is_leaf + for c in s.categories + ] + + # Grab all models that fully support all abilities for the corresponding category + valid_models = { + cat: set( + get_all_object_category_models_with_abilities( + cat, get_knowledge_base().get_category(cat).synset.abilities + ) + ) + for cat in categories + } + valid_models = { + cat: (models if cat not in GOOD_MODELS else models.intersection(GOOD_MODELS[cat])) + - BAD_CLOTH_MODELS.get(cat, set()) + for cat, models in valid_models.items() + } + valid_models = { + cat: self._filter_model_choices_by_attached_states(models, cat, obj_inst) + for cat, models in valid_models.items() + } + + # Filter based on white / blacklist + if synset_whitelist is not None: + valid_models = { + cat: models.intersection(set(synset_whitelist[cat].keys())) + if cat in synset_whitelist + else set() + for cat, models in valid_models.items() + } + + if synset_blacklist is not None: + valid_models = { + cat: models - set(synset_blacklist[cat].keys()) if cat in synset_blacklist else models + for cat, models in valid_models.items() + } + + room_insts = ( + [None] if self._scene_model is None else self._scene.seg_map.room_sem_name_to_ins_name[room_type] + ) + for room_inst in room_insts: + # A list of scene objects that satisfy the requested categories + room_objs = self._scene.object_registry("in_rooms", room_inst, default_val=[]) + scene_objs = [ + obj + for obj in room_objs + if obj.category in categories and obj.model in valid_models[obj.category] + ] + + if len(scene_objs) != 0: + room_type_to_scene_objs[room_type][obj_inst][room_inst] = scene_objs + + error_msg = self._consolidate_room_instance(room_type_to_scene_objs, "initial_pre-sampling") + if error_msg: + return error_msg + self._inroom_object_scope = room_type_to_scene_objs + + def _filter_object_scope(self, input_object_scope, conditions, condition_type): + """ + Filters the object scope based on given @input_object_scope, @conditions, and @condition_type + + Args: + input_object_scope (dict): + conditions (list): List of conditions to filter scope with, where each list entry is + a tuple of (condition, positive), where @positive is True if the condition has a positive + evaluation. + condition_type (str): What type of condition to sample, e.g., "initial" + + Returns: + 2-tuple: + + - dict: Filtered object scope + - list of str: The name of children object(s) that have the highest proportion of kinematic sampling + failures + """ + filtered_object_scope = {} + # Maps child obj name (SCOPE name) to parent obj name (OBJECT name) to T / F, + # ie: if the kinematic relationship was sampled successfully + problematic_objs = defaultdict(dict) + for room_type in input_object_scope: + filtered_object_scope[room_type] = {} + for scene_obj in input_object_scope[room_type]: + filtered_object_scope[room_type][scene_obj] = {} + for room_inst in input_object_scope[room_type][scene_obj]: + # These are a list of candidate simulator objects that need sampling test + for obj in input_object_scope[room_type][scene_obj][room_inst]: + # Temporarily set object_scope to point to this candidate object + self._object_scope[scene_obj] = obj + + success = True + # If this candidate object is not involved in any conditions, + # success will be True by default and this object will qualify + parent_obj_name = obj.name + conditions_to_sample = [] + for condition, positive in conditions: + # Sample positive kinematic conditions that involve this candidate object + if ( + condition.STATE_NAME in KINEMATIC_STATES_BDDL + and positive + and scene_obj in condition.body + ): + child_scope_name = condition.body[0] + entity = self._object_scope[child_scope_name] + conditions_to_sample.append((condition, positive, entity, child_scope_name)) + + # If we're sampling kinematics, sort children based on (a) whether they are cloth or not, and + # then (b) their AABB, so that first all rigid objects are sampled before all cloth objects, + # and within each group the larger objects are sampled first. This is needed because rigid + # objects currently don't detect collisions with cloth objects (rigid-object contact checks + # is empty even when a cloth object is in contact with it). + rigid_conditions = [c for c in conditions_to_sample if c[2].prim_type != PrimType.CLOTH] + cloth_conditions = [c for c in conditions_to_sample if c[2].prim_type == PrimType.CLOTH] + conditions_to_sample = list( + reversed(sorted(rigid_conditions, key=lambda x: th.prod(x[2].aabb_extent))) + ) + list(reversed(sorted(cloth_conditions, key=lambda x: th.prod(x[2].aabb_extent)))) + + # Sample! + for condition, positive, entity, child_scope_name in conditions_to_sample: + kwargs = dict() + # Reset if we're sampling a kinematic state + if condition.STATE_NAME in {"inside", "ontop", "under"}: + kwargs["reset_before_sampling"] = True + kwargs["use_trav_map"] = True + elif condition.STATE_NAME in {"attached"}: + kwargs["bypass_alignment_checking"] = True + kwargs["check_physics_stability"] = True + kwargs["can_joint_break"] = False + success = condition.sample(self._sample_predicate, binary_state=positive, **kwargs) + log_msg = " ".join( + [ + f"{condition_type} kinematic condition sampling", + room_type, + scene_obj, + str(room_inst), + parent_obj_name, + condition.STATE_NAME, + str(condition.body), + str(success), + ] + ) + log.warning(log_msg) + + # Record the result for the child object + assert ( + parent_obj_name not in problematic_objs[child_scope_name] + ), f"Multiple kinematic relationships attempted for pair {condition.body}" + problematic_objs[child_scope_name][parent_obj_name] = success + # If any condition fails for this candidate object, skip + if not success: + break + + # If this candidate object fails, move on to the next candidate object + if not success: + continue + + if room_inst not in filtered_object_scope[room_type][scene_obj]: + filtered_object_scope[room_type][scene_obj][room_inst] = [] + filtered_object_scope[room_type][scene_obj][room_inst].append(obj) + + # Compute most problematic objects + if len(problematic_objs) == 0: + max_problematic_objs = [] + else: + problematic_objs_by_proportion = defaultdict(list) + for child_scope_name, parent_obj_names in problematic_objs.items(): + problematic_objs_by_proportion[ + th.mean(th.tensor(list(parent_obj_names.values()), dtype=th.float32)).item() + ].append(child_scope_name) + max_problematic_objs = problematic_objs_by_proportion[min(problematic_objs_by_proportion.keys())] + + return filtered_object_scope, max_problematic_objs + + def _consolidate_room_instance(self, filtered_object_scope, condition_type): + """ + Consolidates room instances + + Args: + filtered_object_scope (dict): Filtered object scope + condition_type (str): What type of condition to sample, e.g., "initial" + + Returns: + None or str: Error message, if any + """ + for room_type in filtered_object_scope: + # For each room_type, filter in room_inst that has successful + # sampling options for all obj_inst in this room_type + room_inst_satisfied = set.intersection( + *[ + set(filtered_object_scope[room_type][obj_inst].keys()) + for obj_inst in filtered_object_scope[room_type] + ] + ) + + if len(room_inst_satisfied) == 0: + error_msg = "{}: Room type [{}] of scene [{}] do not contain or cannot sample all the objects needed.\nThe following are the possible room instances for each object, the intersection of which is an empty set.\n".format( + condition_type, room_type, self._scene_model + ) + for obj_inst in filtered_object_scope[room_type]: + error_msg += ( + "{}: ".format(obj_inst) + ", ".join(filtered_object_scope[room_type][obj_inst].keys()) + "\n" + ) + + return error_msg + + for obj_inst in filtered_object_scope[room_type]: + filtered_object_scope[room_type][obj_inst] = { + key: val + for key, val in filtered_object_scope[room_type][obj_inst].items() + if key in room_inst_satisfied + } + + def _filter_model_choices_by_attached_states(self, model_choices, category, obj_inst): + # If obj_inst is a child object that depends on a parent object that has been imported or exists in the scene, + # we filter in only models that match the parent object's attachment meta links. + if obj_inst in self._attached_objects: + parent_insts = self._attached_objects[obj_inst] + parent_objects = [] + for parent_inst in parent_insts: + # If parent_inst is not an inroom object, it must be a non-sampleable object that has already been imported. + # Grab it from the object_scope + if parent_inst not in self._inroom_object_instances: + assert self._object_scope[parent_inst] is not None + parent_objects.append([self._object_scope[parent_inst]]) + # If parent_inst is an inroom object, it can refer to multiple objects in the scene in different rooms. + # We gather all of them and require that the model choice supports attachment to at least one of them. + else: + for _, parent_inst_to_parent_objs in self._inroom_object_scope.items(): + if parent_inst in parent_inst_to_parent_objs: + parent_objects.append(sum(parent_inst_to_parent_objs[parent_inst].values(), [])) + + # Help function to check if a child object can attach to a parent object + def can_attach(child_attachment_links, parent_attachment_links): + for child_link_name in child_attachment_links: + child_category = re.search(r"attachment_(.+?)_\d+_link$", child_link_name).group(1) + if child_category.endswith("F"): + continue + assert child_category.endswith("M") + target_parent_category = child_category[:-1] + "F" + for parent_link_name in parent_attachment_links: + parent_category = re.search(r"attachment_(.+?)_\d+_link$", parent_link_name).group(1) + if parent_category == target_parent_category: + return True + return False + + # Filter out models that don't support the attached states + new_model_choices = set() + for model_choice in model_choices: + child_attachment_links = get_attachment_meta_links(category, model_choice) + # The child model choice needs to be able to attach to all parent instances. + # For in-room parent instances, there might be multiple parent objects (e.g. different wall nails), + # and the child object needs to be able to attach to at least one of them. + if all( + any( + can_attach( + child_attachment_links, get_attachment_meta_links(parent_obj.category, parent_obj.model) + ) + for parent_obj in parent_objs_per_inst + ) + for parent_objs_per_inst in parent_objects + ): + new_model_choices.add(model_choice) + + return new_model_choices + + # If obj_inst is a prent object that other objects depend on, we filter in only models that have at least some + # attachment links. + elif any(obj_inst in parents for parents in self._attached_objects.values()): + # Filter out models that don't support the attached states + new_model_choices = set() + for model_choice in model_choices: + if len(get_attachment_meta_links(category, model_choice)) > 0: + new_model_choices.add(model_choice) + return new_model_choices + + # If neither of the above cases apply, we don't need to filter the model choices + else: + return model_choices + + def _import_sampleable_objects(self): + """ + Import all objects that can be sampled + + Args: + env (Environment): Current active environment instance + """ + assert og.sim.is_stopped(), "Simulator should be stopped when importing sampleable objects" + + # Move the robot object frame to a far away location, similar to other newly imported objects below + self._agent.set_position_orientation( + position=th.tensor([300, 300, 300], dtype=th.float32), orientation=th.tensor([0, 0, 0, 1], dtype=th.float32) + ) + + self._sampled_objects = set() + num_new_obj = 0 + # Only populate self.object_scope for sampleable objects + available_categories = set(get_all_object_categories()) + + # Attached states introduce dependencies among objects during import time. + # For example, when importing a child object instance, we need to make sure the imported model can be attached + # to the parent object instance. We sort the object instances such that parent object instances are imported + # before child object instances. + dependencies = {key: self._attached_objects.get(key, {}) for key in self._object_instance_to_synset.keys()} + for obj_inst in list(reversed(list(nx.algorithms.topological_sort(nx.DiGraph(dependencies))))): + obj_synset = self._object_instance_to_synset[obj_inst] + synset_whitelist = ( + None if self._sampling_whitelist is None else self._sampling_whitelist.get(obj_synset, None) + ) + synset_blacklist = ( + None if self._sampling_blacklist is None else self._sampling_blacklist.get(obj_synset, None) + ) + + # Don't populate agent + if obj_synset == "agent.n.01": + continue + + # Populate based on whether it's a substance or not + if is_substance_synset(obj_synset): + assert len(self._activity_conditions.parsed_objects[obj_synset]) == 1, "Systems are singletons" + obj_inst = self._activity_conditions.parsed_objects[obj_synset][0] + _so = get_knowledge_base().get_synset(obj_synset) + system_name = [ + ps.name for s in [_so] + sorted(_so.descendants, key=lambda x: x.name) for ps in s.particle_systems + ][0] + self._object_scope[obj_inst] = ( + None if obj_inst in self._future_obj_instances else self._scene.get_system(system_name) + ) + else: + _so = get_knowledge_base().get_synset(obj_synset) + valid_categories = set( + [ + c.name + for s in [_so] + sorted(_so.descendants, key=lambda x: x.name) + if s.is_leaf + for c in s.categories + ] + ) + categories = list(valid_categories.intersection(available_categories)) + if len(categories) == 0: + return ( + f"None of the following categories could be found in the dataset for synset {obj_synset}: " + f"{valid_categories}" + ) + + # Don't explicitly sample if future + if obj_inst in self._future_obj_instances: + self._object_scope[obj_inst] = None + continue + # Don't sample if already in room + if obj_inst in self._inroom_object_instances: + continue + + # Shuffle categories and sample to find a valid model + random.shuffle(categories) + model_choices = set() + for category in categories: + # Get all available models that support all of its synset abilities + model_choices = set( + get_all_object_category_models_with_abilities( + category=category, + abilities=get_knowledge_base().get_category(category).synset.abilities, + ) + ) + model_choices = ( + model_choices + if category not in GOOD_MODELS + else model_choices.intersection(GOOD_MODELS[category]) + ) + model_choices -= BAD_CLOTH_MODELS.get(category, set()) + model_choices = self._filter_model_choices_by_attached_states(model_choices, category, obj_inst) + + # Filter based on white / blacklist + if synset_whitelist is not None: + model_choices = ( + model_choices.intersection(set(synset_whitelist[category].keys())) + if category in synset_whitelist + else set() + ) + + if synset_blacklist is not None: + model_choices = ( + model_choices - set(synset_blacklist[category].keys()) + if category in synset_blacklist + else model_choices + ) + + # Filter by category + if len(model_choices) > 0: + break + + if len(model_choices) == 0: + # We failed to find ANY valid model across ALL valid categories + return f"Missing valid object models for all categories: {categories}" + + # Randomly select an object model + model = random.choice(list(model_choices)) + + # Potentially add additional kwargs + obj_kwargs = dict() + + size = synset_whitelist.get(category, dict()).get(model, None) if synset_whitelist else None + + # if size is one dimension, this is a scale; if it's three dimensions, this is a bounding box + if size is not None: + if isinstance(size, (int, float)): + obj_kwargs["scale"] = th.tensor(size, dtype=th.float32) + elif isinstance(size, list) and len(size) == 3: + obj_kwargs["bounding_box"] = th.tensor(size, dtype=th.float32) + else: + return f"Invalid size for object {obj_inst} with model {model} in category {category}: {size}" + + # Create the object. This is imported here to avoid a circular import. + from omnigibson.objects.dataset_object import DatasetObject + + simulator_obj = DatasetObject( + name=f"{category}_{len(self._scene.objects)}", + category=category, + model=model, + prim_type=( + PrimType.CLOTH + if "cloth" in get_knowledge_base().get_synset(obj_synset).abilities + else PrimType.RIGID + ), + **obj_kwargs, + ) + num_new_obj += 1 + + # Load the object into the simulator + self._scene.add_object(simulator_obj) + + # Set these objects to be far-away locations + simulator_obj.set_position_orientation( + position=th.tensor([100.0, 100.0, -100.0]) + th.ones(3) * num_new_obj * 5.0 + ) + + self._sampled_objects.add(simulator_obj) + self._object_scope[obj_inst] = simulator_obj + + og.sim.play() + og.sim.stop() + + def _sample_initial_conditions(self): + """ + Sample initial conditions + + Returns: + None or str: If successful, returns None. Otherwise, returns an error message + """ + error_msg, self._inroom_object_scope_filtered_initial = self._sample_conditions( + self._inroom_object_scope, self._inroom_object_conditions, "initial" + ) + return error_msg + + def _sample_goal_conditions(self): + """ + Sample goal conditions + + Returns: + None or str: If successful, returns None. Otherwise, returns an error message + """ + # ground_goal_state_options is list[list[HEAD]] post-#2040; shuffle a copy of the outer list + ground_goal_state_options = list(self._compiled_task.ground_goal_state_options) + random.shuffle(ground_goal_state_options) + log.debug(("number of ground_goal_state_options", len(ground_goal_state_options))) + num_goal_condition_set_to_test = 10 + + goal_condition_success = False + # Try to fulfill different set of ground goal conditions (maximum num_goal_condition_set_to_test) + for goal_condition_set in ground_goal_state_options[:num_goal_condition_set_to_test]: + goal_condition_processed = [] + for condition in goal_condition_set: + condition, positive = process_single_condition(condition) + if condition is None: + continue + goal_condition_processed.append((condition, positive)) + + error_msg, _ = self._sample_conditions( + self._inroom_object_scope_filtered_initial, goal_condition_processed, "goal" + ) + if not error_msg: + # if one set of goal conditions (and initial conditions) are satisfied, sampling is successful + goal_condition_success = True + break + + if not goal_condition_success: + return error_msg + + def _sample_initial_conditions_final(self, dynamic_scale=False): + """ + Sample final initial conditions + + Returns: + None or str: If successful, returns None. Otherwise, returns an error message + """ + # Sample kinematics first, then particle states, then unary states + state = og.sim.dump_state(serialized=False) + for group in ("kinematic", "particle", "unary"): + log.info(f"Sampling {group} states...") + if len(self._object_sampling_orders[group]) > 0: + for cur_batch in self._object_sampling_orders[group]: + conditions_to_sample = [] + for condition, positive in self._object_sampling_conditions[group]: + # Sample conditions that involve the current batch of objects + child_scope_name = condition.body[0] + if child_scope_name in cur_batch: + entity = self._object_scope[child_scope_name] + conditions_to_sample.append((condition, positive, entity, child_scope_name)) + + # If we're sampling kinematics, sort children based on (a) whether they are cloth or not, and then + # (b) their AABB, so that first all rigid objects are sampled before cloth objects, and within each + # group the larger objects are sampled first + if group == "kinematic": + rigid_conditions = [c for c in conditions_to_sample if c[2].prim_type != PrimType.CLOTH] + cloth_conditions = [c for c in conditions_to_sample if c[2].prim_type == PrimType.CLOTH] + conditions_to_sample = list( + reversed(sorted(rigid_conditions, key=lambda x: th.prod(x[2].aabb_extent))) + ) + list(reversed(sorted(cloth_conditions, key=lambda x: th.prod(x[2].aabb_extent)))) + + # Sample! + for condition, positive, entity, child_scope_name in conditions_to_sample: + success = False + + kwargs = dict() + # Reset if we're sampling a kinematic state + if condition.STATE_NAME in {"inside", "ontop", "under"}: + kwargs["reset_before_sampling"] = True + kwargs["use_trav_map"] = True + elif condition.STATE_NAME in {"attached"}: + kwargs["bypass_alignment_checking"] = True + kwargs["check_physics_stability"] = True + kwargs["can_joint_break"] = False + + while True: + num_trials = 3 + for _ in range(num_trials): + success = condition.sample(self._sample_predicate, binary_state=positive, **kwargs) + log_msg = " ".join( + [ + "initial final kinematic condition sampling", + condition.STATE_NAME, + str(condition.body), + str(success), + ] + ) + log.warning(log_msg) + if success: + # Update state + state = og.sim.dump_state(serialized=False) + break + if success: + # After the final round of kinematic sampling, we assign in_rooms to newly imported objects + if group == "kinematic": + parent = self._object_scope[condition.body[1]] + entity.in_rooms = deepcopy(parent.in_rooms) + + # Can terminate immediately + break + + # Can't re-sample non-kinematics or rescale cloth or agent, so in + # those cases terminate immediately + if ( + group != "kinematic" + or condition.STATE_NAME == "attached" + or "agent" in child_scope_name + or entity.prim_type == PrimType.CLOTH + ): + break + + if dynamic_scale: + # If any scales are equal or less than the lower threshold, terminate immediately + new_scale = entity.scale - m.DYNAMIC_SCALE_INCREMENT + if th.any(new_scale < m.MIN_DYNAMIC_SCALE): + break + + # Re-scale and re-attempt + # Re-scaling is not respected unless sim cycle occurs + og.sim.stop() + entity.scale = new_scale + log.info( + f"Kinematic sampling {condition.STATE_NAME} {condition.body} failed, rescaling obj: {child_scope_name} to {entity.scale}" + ) + og.sim.play() + og.sim.load_state(state, serialized=False) + og.sim.step_physics() + else: + break + if not success: + # Update object registry because we just assigned in_rooms to newly imported objects + self._scene.object_registry.update(keys=["in_rooms"]) + return f"Sampleable object conditions failed: {condition.STATE_NAME} {condition.body}" + + # Update object registry because we just assigned in_rooms to newly imported objects + self._scene.object_registry.update(keys=["in_rooms"]) + + # One more sim step to make sure the object states are propagated correctly + # E.g. after sampling Filled.set_value(True), Filled.get_value() will become True only after one step + og.sim.step() + + def _sample_conditions(self, input_object_scope, conditions, condition_type): + """ + Sample conditions + + Args: + input_object_scope (dict): + conditions (list): List of conditions to filter scope with, where each list entry is + a tuple of (condition, positive), where @positive is True if the condition has a positive + evaluation. + condition_type (str): What type of condition to sample, e.g., "initial" + + Returns: + None or str: If successful, returns None. Otherwise, returns an error message + """ + error_msg, problematic_objs = "", [] + while not any( + th.any(self._object_scope[obj_inst].scale < m.MIN_DYNAMIC_SCALE).item() for obj_inst in problematic_objs + ): + filtered_object_scope, problematic_objs = self._filter_object_scope( + input_object_scope, conditions, condition_type + ) + error_msg = self._consolidate_room_instance(filtered_object_scope, condition_type) + if error_msg is None: + break + # Re-scaling is not respected unless sim cycle occurs + og.sim.stop() + for obj_inst in problematic_objs: + obj = self._object_scope[obj_inst] + # If the object's initial condition is attachment, or it's agent or cloth, we can't / shouldn't scale + # down, so play again and then terminate immediately + if obj_inst in self._attached_objects or "agent" in obj_inst or obj.prim_type == PrimType.CLOTH: + og.sim.play() + return error_msg, None + assert th.all(obj.scale > m.DYNAMIC_SCALE_INCREMENT) + obj.scale -= m.DYNAMIC_SCALE_INCREMENT + og.sim.play() + + if error_msg: + return error_msg, None + return self._maximum_bipartite_matching(filtered_object_scope, condition_type), filtered_object_scope + + def _maximum_bipartite_matching(self, filtered_object_scope, condition_type): + """ + Matches objects from @filtered_object_scope to specific room instances it can be + sampled from + + Args: + filtered_object_scope (dict): Filtered object scope + condition_type (str): What type of condition to sample, e.g., "initial" + + Returns: + None or str: If successful, returns None. Otherwise, returns an error message + """ + # For each room instance, perform maximum bipartite matching between object instance in scope to simulator objects + # Left nodes: a list of object instance in scope + # Right nodes: a list of simulator objects + # Edges: if the simulator object can support the sampling requirement of ths object instance + for room_type in filtered_object_scope: + # The same room instances will be shared across all scene obj in a given room type + some_obj = list(filtered_object_scope[room_type].keys())[0] + room_insts = list(filtered_object_scope[room_type][some_obj].keys()) + success = False + # Loop through each room instance + for room_inst in room_insts: + graph = nx.Graph() + # For this given room instance, gether mapping from obj instance to a list of simulator obj + obj_inst_to_obj_per_room_inst = {} + for obj_inst in filtered_object_scope[room_type]: + obj_inst_to_obj_per_room_inst[obj_inst] = filtered_object_scope[room_type][obj_inst][room_inst] + top_nodes = [] + log_msg = "MBM for room instance [{}]".format(room_inst) + log.debug((log_msg)) + for obj_inst in obj_inst_to_obj_per_room_inst: + for obj in obj_inst_to_obj_per_room_inst[obj_inst]: + # Create an edge between obj instance and each of the simulator obj that supports sampling + graph.add_edge(obj_inst, obj) + log_msg = "Adding edge: {} <-> {}".format(obj_inst, obj.name) + log.debug((log_msg)) + top_nodes.append(obj_inst) + # Need to provide top_nodes that contain all nodes in one bipartite node set + # The matches will have two items for each match (e.g. A -> B, B -> A) + matches = nx.bipartite.maximum_matching(graph, top_nodes=top_nodes) + if len(matches) == 2 * len(obj_inst_to_obj_per_room_inst): + log.debug(("Object scope finalized:")) + for obj_inst, obj in matches.items(): + if obj_inst in obj_inst_to_obj_per_room_inst: + self._object_scope[obj_inst] = obj + log.debug((obj_inst, obj.name)) + success = True + break + if not success: + return "{}: Room type [{}] of scene [{}] do not have enough simulator objects that can successfully sample all the objects needed. This is usually caused by specifying too many object instances in the object scope or the conditions are so stringent that too few simulator objects can satisfy them via sampling.\n".format( + condition_type, room_type, self._scene_model + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/coacd_runner.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/coacd_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..7f49118b9629322049e6a203a3857e6fa07a9796 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/coacd_runner.py @@ -0,0 +1,24 @@ +""" +Subprocess to run coacd to prevent the generate_collision_meshes() in asset_conversion_utils.py from crashing +""" + +import pickle +import coacd +import sys + +try: + with open(sys.argv[1], "rb") as f: + vertices, faces, hull_count = pickle.load(f) + mesh = coacd.Mesh(vertices, faces) + result = coacd.run_coacd( + mesh, + max_convex_hull=hull_count, + decimate=True, + max_ch_vertex=60, + ) + with open(sys.argv[2], "wb") as f: + pickle.dump(result, f) + sys.exit(0) +except Exception as e: + print("Error in CoACD:", e) + sys.exit(1) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/config_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dd467c38201fe2fae9eae336e1d2811f406db587 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/config_utils.py @@ -0,0 +1,79 @@ +import collections.abc +import json +import os + +import torch as th +import yaml + +# File I/O related + + +def parse_config(config): + """ + Parse OmniGibson config file / object + + Args: + config (dict or str): Either config dictionary or path to yaml config to load + + Returns: + dict: Parsed config + """ + if isinstance(config, collections.abc.Mapping): + return config + else: + assert isinstance(config, str) + + if not os.path.exists(config): + raise IOError( + "config path {} does not exist. Please either pass in a dict or a string that represents the file path to the config yaml.".format( + config + ) + ) + with open(config, "r") as f: + config_data = yaml.load(f, Loader=yaml.FullLoader) + return config_data + + +def parse_str_config(config): + """ + Parse string config + + Args: + config (str): Yaml cfg as a string to load + + Returns: + dict: Parsed config + """ + return yaml.safe_load(config) + + +def dump_config(config): + """ + Converts YML config into a string + + Args: + config (dict): Config to dump + + Returns: + str: Config as a string + """ + return yaml.dump(config) + + +def load_default_config(): + """ + Loads a default configuration to use for OmniGibson + + Returns: + dict: Loaded default configuration file + """ + from omnigibson import example_config_path + + return parse_config(f"{example_config_path}/default_cfg.yaml") + + +class TorchEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, th.Tensor): + return obj.tolist() + return json.JSONEncoder.default(self, obj) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/constants.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..218b1132a09770b8dc792f536406df5b0429b44f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/constants.py @@ -0,0 +1,210 @@ +""" +Constant Definitions +""" + +import hashlib +from enum import Enum, IntEnum +from functools import cache + +import torch as th + +from omnigibson.utils.asset_utils import get_all_object_categories, get_all_system_categories + +MAX_INSTANCE_COUNT = th.iinfo(th.int32).max +MAX_CLASS_COUNT = th.iinfo(th.int32).max +MAX_VIEWER_SIZE = 2048 + +# Category name assigned to all robots +ROBOT_CATEGORY = "agent" + + +class ViewerMode(IntEnum): + NAVIGATION = 0 + MANIPULATION = 1 + PLANNING = 2 + + +class LightingMode(str, Enum): + # See https://stackoverflow.com/a/58608362 for info on string enums + STAGE = "stage" + CAMERA = "camera" + RIG_DEFAULT = "Default" + RIG_GREY = "Grey Studio" + RIG_COLORED = "Colored Lights" + + +class SimulatorMode(IntEnum): + GUI = 1 + HEADLESS = 2 + VR = 3 + + +# Specific methods for applying / removing particles +class ParticleModifyMethod(str, Enum): + ADJACENCY = "adjacency" + PROJECTION = "projection" + + +# Specific condition types for applying / removing particles +class ParticleModifyCondition(str, Enum): + FUNCTION = "function" + SATURATED = "saturated" + TOGGLEDON = "toggled_on" + GRAVITY = "gravity" + + +# Object categories -- grabbed directly from the dataset to begin with +# This will be automatically added to when objects are added with custom categories +OBJECT_CATEGORIES = set(get_all_object_categories()) + +# Structure categories that need to always be loaded for stability purposes +STRUCTURE_CATEGORIES = frozenset({"floors", "walls", "ceilings", "lawn", "driveway", "fence", "roof", "background"}) + +# Ground categories / prim names used for filtering collisions, e.g.: during motion planning +GROUND_CATEGORIES = frozenset({"floors", "lawn", "driveway", "carpet"}) + +# Structural door categories used for filtering collisions with structure categories +STRUCTURAL_DOOR_CATEGORIES = frozenset({"sliding_door", "garage_door"}) + +# Joint friction magic values +DEFAULT_PRISMATIC_JOINT_FRICTION = 0.3 +DEFAULT_REVOLUTE_JOINT_FRICTION = 0.2 + +# Joint damping value +DEFAULT_PRISMATIC_JOINT_DAMPING = 5.0 +DEFAULT_REVOLUTE_JOINT_DAMPING = 0.05 + + +class PrimType(IntEnum): + RIGID = 0 + CLOTH = 1 + + +class EmitterType(IntEnum): + FIRE = 0 + STEAM = 1 + + +# Valid primitive mesh types +PRIMITIVE_MESH_TYPES = { + "Cone", + "Cube", + "Cylinder", + "Disk", + "Plane", + "Sphere", + "Torus", +} + +# Valid geom types +GEOM_TYPES = {"Sphere", "Cube", "Cone", "Cylinder", "Mesh"} + +# Valid joint axis +JointAxis = ["X", "Y", "Z"] + + +# TODO: Clean up this class to be better enum with sanity checks +# Joint types +class JointType: + JOINT = "Joint" + JOINT_FIXED = "FixedJoint" + JOINT_PRISMATIC = "PrismaticJoint" + JOINT_REVOLUTE = "RevoluteJoint" + JOINT_SPHERICAL = "SphericalJoint" + + _STR_TO_TYPE = { + "Joint": JOINT, + "FixedJoint": JOINT_FIXED, + "PrismaticJoint": JOINT_PRISMATIC, + "RevoluteJoint": JOINT_REVOLUTE, + "SphericalJoint": JOINT_SPHERICAL, + } + + _TYPE_TO_STR = { + JOINT: "Joint", + JOINT_FIXED: "FixedJoint", + JOINT_PRISMATIC: "PrismaticJoint", + JOINT_REVOLUTE: "RevoluteJoint", + JOINT_SPHERICAL: "SphericalJoint", + } + + @classmethod + def get_type(cls, str_type): + assert str_type in cls._STR_TO_TYPE, f"Invalid string joint type name received: {str_type}" + return cls._STR_TO_TYPE[str_type] + + @classmethod + def get_str(cls, joint_type): + assert joint_type in cls._TYPE_TO_STR, f"Invalid joint type name received: {joint_type}" + return cls._TYPE_TO_STR[joint_type] + + @classmethod + def is_valid(cls, joint_type): + return joint_type in cls._TYPE_TO_STR if isinstance(joint_type, cls) else joint_type in cls._STR_TO_TYPE + + +# Object category specs +AVERAGE_OBJ_DENSITY = 67.0 + + +class OccupancyGridState: + OBSTACLES = 0.0 + UNKNOWN = 0.5 + FREESPACE = 1.0 + + +MAX_TASK_RELEVANT_OBJS = 50 +TASK_RELEVANT_OBJS_OBS_DIM = 9 +AGENT_POSE_DIM = 6 + +# TODO: What the hell is this magic list?? It's not used anywhere +UNDER_OBJECTS = [ + "breakfast_table", + "coffee_table", + "console_table", + "desk", + "gaming_table", + "pedestal_table", + "pool_table", + "stand", + "armchair", + "chaise_longue", + "folding_chair", + "highchair", + "rocking_chair", + "straight_chair", + "swivel_chair", + "bench", +] + + +@cache +def semantic_class_name_to_id(): + """ + Get mapping from semantic class name to class id + + Returns: + dict: class name to class id + """ + systems = get_all_system_categories(include_cloth=True) + + all_semantics = sorted( + set(list(OBJECT_CATEGORIES) + systems + ["background", "unlabelled", "object", "light", "agent"]) + ) + + # Assign a unique class id to each class name with hashing, the upper limit here is the max of int32 + max_int32 = th.iinfo(th.int32).max + 1 + class_name_to_class_id = {s: int(hashlib.md5(s.encode()).hexdigest(), 16) % max_int32 for s in all_semantics} + + return class_name_to_class_id + + +@cache +def semantic_class_id_to_name(): + """ + Get mapping from semantic class id to class name + + Returns: + dict: class id to class name + """ + return {v: k for k, v in semantic_class_name_to_id().items()} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/control_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/control_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e93339de44dc34e69fcc63e006e4ef225e7d2758 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/control_utils.py @@ -0,0 +1,140 @@ +""" +Set of utilities for helping to execute robot control +""" + +import torch as th + +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T + + +class FKSolver: + """ + Class for thinly wrapping Lula Forward Kinematics solver + """ + + def __init__( + self, + robot_description_path, + robot_urdf_path, + ): + # Create robot description and kinematics + self.robot_description = lazy.lula.load_robot(robot_description_path, robot_urdf_path) + self.kinematics = self.robot_description.kinematics() + + def get_link_poses( + self, + joint_positions, + link_names, + ): + """ + Given @joint_positions, get poses of the desired links (specified by @link_names) + + Args: + joint_positions (n-array): Joint positions in configuration space + link_names (list): List of robot link names we want to specify (e.g. "gripper_link") + + Returns: + link_poses (dict): Dictionary mapping each robot link name to its pose + """ + # TODO: Refactor this to go over all links at once + link_poses = {} + for link_name in link_names: + pose3_lula = self.kinematics.pose(joint_positions, link_name) + + # get position + link_position = th.tensor(pose3_lula.translation, dtype=th.float32) + + # get orientation + rotation_lula = pose3_lula.rotation + link_orientation = th.tensor( + [rotation_lula.x(), rotation_lula.y(), rotation_lula.z(), rotation_lula.w()], dtype=th.float32 + ) + link_poses[link_name] = (link_position, link_orientation) + return link_poses + + +class IKSolver: + """ + Class for thinly wrapping Lula IK solver + """ + + def __init__( + self, + robot_description_path, + robot_urdf_path, + eef_name, + reset_joint_pos, + ): + # Create robot description, kinematics, and config + self.robot_description = lazy.lula.load_robot(robot_description_path, robot_urdf_path) + self.kinematics = self.robot_description.kinematics() + self.config = lazy.lula.CyclicCoordDescentIkConfig() + self.eef_name = eef_name + self.reset_joint_pos = reset_joint_pos + + def solve( + self, + target_pos, + target_quat=None, + tolerance_pos=0.002, + tolerance_quat=0.01, + weight_pos=1.0, + weight_quat=0.05, + bfgs_orientation_weight=100.0, + max_iterations=10, + initial_joint_pos=None, + ): + """ + Backs out joint positions to achieve desired @target_pos and @target_quat + + Args: + target_pos (3-array): desired (x,y,z) local target cartesian position in robot's base coordinate frame + target_quat (4-array or None): If specified, desired (x,y,z,w) local target quaternion orientation in + robot's base coordinate frame. If None, IK will be position-only (will override settings such that + orientation's tolerance is very high and weight is 0) + tolerance_pos (float): Maximum position error (L2-norm) for a successful IK solution + tolerance_quat (float): Maximum orientation error (per-axis L2-norm) for a successful IK solution + weight_pos (float): Weight for the relative importance of position error during CCD + weight_quat (float): Weight for the relative importance of position error during CCD + bfgs_orientation_weight (float): Weight when applying BFGS algorithm during optimization. Only used if + target_quat is specified + max_iterations (int): Number of iterations used for each cyclic coordinate descent. + initial_joint_pos (None or n-array): If specified, will set the initial cspace seed when solving for joint + positions. Otherwise, will use self.reset_joint_pos + + Returns: + None or n-array: Joint positions for reaching desired target_pos and target_quat, otherwise None if no + solution was found + """ + pos = ( + target_pos.to(th.float64) if isinstance(target_pos, th.Tensor) else th.tensor(target_pos, dtype=th.float64) + ).reshape(3, 1) + + if target_quat is None: + rot = T.quat2mat(th.tensor([0, 0, 0, 1.0], dtype=th.float64)) + else: + rot = T.quat2mat( + target_quat.to(th.float64) + if isinstance(target_quat, th.Tensor) + else th.tensor(target_quat, dtype=th.float64) + ) + ik_target_pose = lazy.lula.Pose3(lazy.lula.Rotation3(rot), pos) + + # Set the cspace seed and tolerance + initial_joint_pos = self.reset_joint_pos if initial_joint_pos is None else initial_joint_pos + self.config.cspace_seeds = [initial_joint_pos] + self.config.position_tolerance = tolerance_pos + self.config.orientation_tolerance = 100.0 if target_quat is None else tolerance_quat + + self.config.ccd_position_weight = weight_pos + self.config.ccd_orientation_weight = 0.0 if target_quat is None else weight_quat + self.config.bfgs_orientation_weight = 0.0 if target_quat is None else bfgs_orientation_weight + self.config.max_num_descents = max_iterations + + # Compute target joint positions + ik_results = lazy.lula.compute_ik_ccd(self.kinematics, ik_target_pose, self.eef_name, self.config) + if ik_results.success: + return th.tensor(ik_results.cspace_position, dtype=th.float32) + else: + return None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/data_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..02bf00768d56471cc45cf3de4cac23cf631b81f9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/data_utils.py @@ -0,0 +1,193 @@ +from omnigibson.robots import REGISTERED_ROBOTS +import numpy as np + + +def merge_scene_files(scene_a, scene_b, keep_robot_from="b"): + """ + Merge two scene files, keeping the robot from the specified scene + and merging all other objects. + + Design decisions: + - Scene B is considered the most up-to-date version and its data is preferred + when there are conflicts + - For objects that exist in both scenes, we perform sanity checks on objects_info + but always use Scene B's version + - For states of objects that exist in both scenes, we always use Scene B's version + without sanity checking + - For system registry, we always use Scene B's version (no merging) + + Args: + scene_a (dict): First scene file + scene_b (dict): Second scene file (considered the most up-to-date version for conflicts) + keep_robot_from (str or None): Which scene to keep the robot from ('a', 'b', or None) + If None, no robot will be included + + Returns: + dict: Merged scene file + """ + assert isinstance(scene_a, dict), "Scene A must be a dictionary" + assert isinstance(scene_b, dict), "Scene B must be a dictionary" + assert keep_robot_from in ["a", "b", None], "keep_robot_from must be 'a', 'b', or None" + + # Sanity check to make sure the two scene files are compatible + if "init_info" in scene_a and "init_info" in scene_b: + assert ( + scene_a["init_info"]["args"]["scene_model"] == scene_b["init_info"]["args"]["scene_model"] + ), "Scene models must match for merging" + + # Initialize merged scene file + result = { + "metadata": scene_b["metadata"], # Just use metadata from scene_b + "init_info": scene_b["init_info"], # Start with init_info from scene_b + "objects_info": {"init_info": {}}, + "state": { + "pos": [0.0, 0.0, 0.0], + "ori": [0.0, 0.0, 0.0, 1.0], + "registry": { + "system_registry": {}, + "object_registry": {}, + }, + }, + } + + # Update init_info settings + result["init_info"]["args"]["load_room_types"] = None + result["init_info"]["args"]["load_room_instances"] = None + result["init_info"]["args"]["include_robots"] = keep_robot_from is not None + + # Find robots in both scenes + robots_a = {} + robots_b = {} + + for obj_name, obj in scene_a["objects_info"]["init_info"].items(): + if obj["class_name"].lower() in REGISTERED_ROBOTS or obj["class_name"] == "Robot": + # change class_name to "Robot" for compatibility + obj["class_name"] = "Robot" + robots_a[obj_name] = obj + + for obj_name, obj in scene_b["objects_info"]["init_info"].items(): + if obj["class_name"].lower() in REGISTERED_ROBOTS or obj["class_name"] == "Robot": + # change class_name to "Robot" for compatibility + obj["class_name"] = "Robot" + robots_b[obj_name] = obj + + # Merge non-robot objects from both scenes + # Start with all objects from scene_a (excluding robots) + for obj_name, obj in scene_a["objects_info"]["init_info"].items(): + if obj_name not in robots_a: + result["objects_info"]["init_info"][obj_name] = obj + + # Add all objects from scene_b (excluding robots) and check for conflicts + for obj_name, obj in scene_b["objects_info"]["init_info"].items(): + if obj_name not in robots_b: + if obj_name in result["objects_info"]["init_info"]: + # Object exists in both scenes, perform sanity check + sanity_check_object_compatibility(obj_name, result["objects_info"]["init_info"][obj_name], obj) + # Always use scene_b's version as the most up-to-date + result["objects_info"]["init_info"][obj_name] = obj + + # Add robot based on keep_robot_from + if keep_robot_from == "a" and robots_a: + for robot_name, robot in robots_a.items(): + result["objects_info"]["init_info"][robot_name] = robot + elif keep_robot_from == "b" and robots_b: + for robot_name, robot in robots_b.items(): + result["objects_info"]["init_info"][robot_name] = robot + + # Handle state information + # First add states for all non-robot objects from scene_a + for obj_name in scene_a["objects_info"]["init_info"]: + if obj_name not in robots_a and obj_name in scene_a["state"]["registry"]["object_registry"]: + result["state"]["registry"]["object_registry"][obj_name] = scene_a["state"]["registry"]["object_registry"][ + obj_name + ] + + # Then add states for all non-robot objects from scene_b + # Always use scene_b's version without sanity checking + for obj_name in scene_b["objects_info"]["init_info"]: + if obj_name not in robots_b and obj_name in scene_b["state"]["registry"]["object_registry"]: + result["state"]["registry"]["object_registry"][obj_name] = scene_b["state"]["registry"]["object_registry"][ + obj_name + ] + + # Add robot state based on keep_robot_from + if keep_robot_from == "a": + for robot_name in robots_a: + if robot_name in scene_a["state"]["registry"]["object_registry"]: + result["state"]["registry"]["object_registry"][robot_name] = scene_a["state"]["registry"][ + "object_registry" + ][robot_name] + elif keep_robot_from == "b": + for robot_name in robots_b: + if robot_name in scene_b["state"]["registry"]["object_registry"]: + result["state"]["registry"]["object_registry"][robot_name] = scene_b["state"]["registry"][ + "object_registry" + ][robot_name] + + # Use system_registry from scene_b (considered more up-to-date) + result["state"]["registry"]["system_registry"] = scene_b["state"]["registry"]["system_registry"] + + # Validate merged scene + validate_merged_scene(result, require_robot=(keep_robot_from is not None)) + + return result + + +def sanity_check_object_compatibility(obj_name, obj_a, obj_b): + """ + Sanity check if two object definitions are compatible. + This is only applied to objects_info, not to states. + + Args: + obj_name (str): Name of the object + obj_a (dict): Object definition from scene_a + obj_b (dict): Object definition from scene_b + + Raises: + AssertionError: If objects are incompatible + """ + # Check basic properties must match exactly + assert obj_a["class_module"] == obj_b["class_module"], f"Object {obj_name} has different class_module in two scenes" + assert obj_a["class_name"] == obj_b["class_name"], f"Object {obj_name} has different class_name in two scenes" + + # For args, we'll check critical properties exactly and allow small differences in numeric values + args_a = obj_a["args"] + args_b = obj_b["args"] + + # Critical properties must match exactly + assert args_a["name"] == args_b["name"], f"Object {obj_name} has different name in args" + assert args_a["category"] == args_b["category"], f"Object {obj_name} has different category in args" + assert args_a["model"] == args_b["model"], f"Object {obj_name} has different model in args" + if "fixed_base" in args_a or "fixed_base" in args_b: + assert args_a["fixed_base"] == args_b["fixed_base"], f"Object {obj_name} has different fixed_base in args" + if "visual_only" in args_a or "visual_only" in args_b: + assert args_a["visual_only"] == args_b["visual_only"], f"Object {obj_name} has different visual_only in args" + assert args_a["in_rooms"] == args_b["in_rooms"], f"Object {obj_name} has different in_rooms in args" + + # For scale, they should be identical + if "scale" in args_a and "scale" in args_b: + scale_a = np.array(args_a["scale"]) + scale_b = np.array(args_b["scale"]) + assert np.allclose(scale_a, scale_b), f"Object {obj_name} has different scale in args" + + +def validate_merged_scene(scene, require_robot=True): + """ + Validate that the merged scene is coherent and complete. + + Args: + scene (dict): Scene to validate + require_robot (bool): Whether to require exactly one robot + """ + # Check that all objects in objects_info have corresponding state + for obj_name in scene["objects_info"]["init_info"]: + assert obj_name in scene["state"]["registry"]["object_registry"], f"Missing state for object: {obj_name}" + + # Robot check (if required) + if require_robot: + robot_count = 0 + for obj in scene["objects_info"]["init_info"].values(): + if obj["class_name"] == "Robot": + robot_count += 1 + + assert robot_count == 1, f"Scene must have exactly one robot, found {robot_count}" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/deprecated_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/deprecated_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f4857bafdf1a8d64727ec912a4acd53f95c467d3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/deprecated_utils.py @@ -0,0 +1,1057 @@ +""" +A set of utility functions slated to be deprecated once Omniverse bugs are fixed +""" + +import math +from typing import List, Optional, Tuple, Union + +import carb +import numpy as np +import omni +import omni.timeline +import torch +import warp as wp +from isaacsim.core.prims import Articulation as _ArticulationView +from isaacsim.core.prims import RigidPrim as _RigidPrimView +from isaacsim.core.prims import XFormPrim as _XFormPrimView +from isaacsim.core.utils.prims import get_prim_at_path +from omni.kit.primitive.mesh.command import CreateMeshPrimWithDefaultXformCommand as CMPWDXC +from omni.kit.primitive.mesh.command import _get_all_evaluators +from omni.replicator.core import random_colours +from PIL import Image, ImageDraw +from pxr import Gf, PhysxSchema, UsdPhysics + +DEG2RAD = math.pi / 180.0 + + +class CreateMeshPrimWithDefaultXformCommand(CMPWDXC): + def __init__(self, prim_type: str, **kwargs): + """ + Creates primitive. + + Args: + prim_type (str): It supports Plane/Sphere/Cone/Cylinder/Disk/Torus/Cube. + + kwargs: + object_origin (Gf.Vec3f): Position of mesh center in stage units. + + u_patches (int): The number of patches to tessellate U direction. + + v_patches (int): The number of patches to tessellate V direction. + + w_patches (int): The number of patches to tessellate W direction. + It only works for Cone/Cylinder/Cube. + + half_scale (float): Half size of mesh in centimeters. Default is None, which means it's controlled by settings. + + u_verts_scale (int): Tessellation Level of U. It's a multiplier of u_patches. + + v_verts_scale (int): Tessellation Level of V. It's a multiplier of v_patches. + + w_verts_scale (int): Tessellation Level of W. It's a multiplier of w_patches. + It only works for Cone/Cylinder/Cube. + For Cone/Cylinder, it's to tessellate the caps. + For Cube, it's to tessellate along z-axis. + + above_ground (bool): It will offset the center of mesh above the ground plane if it's True, + False otherwise. It's False by default. This param only works when param object_origin is not given. + Otherwise, it will be ignored. + + stage (Usd.Stage): If specified, stage to create prim on + """ + + self._prim_type = prim_type[0:1].upper() + prim_type[1:].lower() + self._usd_context = omni.usd.get_context() + self._selection = self._usd_context.get_selection() + self._stage = kwargs.get("stage", self._usd_context.get_stage()) + self._settings = carb.settings.get_settings() + self._default_path = kwargs.get("prim_path", None) + self._select_new_prim = kwargs.get("select_new_prim", True) + self._prepend_default_prim = kwargs.get("prepend_default_prim", True) + self._above_round = kwargs.get("above_ground", False) + + self._attributes = {**kwargs} + # Supported mesh types should have an associated evaluator class + self._evaluator_class = _get_all_evaluators()[prim_type] + assert isinstance(self._evaluator_class, type) + + +class ArticulationView(_ArticulationView): + """ArticulationView with some additional functionality implemented.""" + + def set_joint_limits( + self, + values: Union[np.ndarray, torch.Tensor], + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + ) -> None: + """Sets joint limits for articulation joints in the view. + + Args: + values (Union[np.ndarray, torch.Tensor, wp.array]): joint limits for articulations in the view. shape (M, K, 2). + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints + to manipulate. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, "cpu") + new_values = self._physics_view.get_dof_limits() + values = self._backend_utils.move_data(values, device="cpu") + new_values = self._backend_utils.assign( + values, + new_values, + [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices], + ) + self._physics_view.set_dof_limits(new_values, indices) + else: + indices = self._backend_utils.to_list( + self._backend_utils.resolve_indices(indices, self.count, self._device) + ) + dof_types = self._backend_utils.to_list(self.get_dof_types()) + joint_indices = self._backend_utils.to_list( + self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + ) + values = self._backend_utils.to_list(values) + articulation_read_idx = 0 + for i in indices: + dof_read_idx = 0 + for dof_index in joint_indices: + dof_val = values[articulation_read_idx][dof_read_idx] + if dof_types[dof_index] == omni.physics.tensors.DofType.Rotation: + dof_val /= DEG2RAD + prim = get_prim_at_path(self._dof_paths[i][dof_index]) + prim.GetAttribute("physics:lowerLimit").Set(dof_val[0]) + prim.GetAttribute("physics:upperLimit").Set(dof_val[1]) + dof_read_idx += 1 + articulation_read_idx += 1 + return + + def get_joint_limits( + self, + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + clone: bool = True, + ) -> Union[np.ndarray, torch.Tensor, wp.array]: + """Gets joint limits for articulation in the view. + + Args: + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints + to query. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + clone (Optional[bool]): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: joint limits for articulations in the view. shape (M, K). + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return None + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + values = self._backend_utils.move_data(self._physics_view.get_dof_limits(), self._device) + if clone: + values = self._backend_utils.clone_tensor(values, device=self._device) + result = values[ + self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices + ] + return result + else: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + dof_types = self._backend_utils.to_list(self.get_dof_types()) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + values = np.zeros(shape=(indices.shape[0], joint_indices.shape[0], 2), dtype="float32") + articulation_write_idx = 0 + indices = self._backend_utils.to_list(indices) + joint_indices = self._backend_utils.to_list(joint_indices) + for i in indices: + dof_write_idx = 0 + for dof_index in joint_indices: + prim = get_prim_at_path(self._dof_paths[i][dof_index]) + values[articulation_write_idx][dof_write_idx][0] = prim.GetAttribute("physics:lowerLimit").Get() + values[articulation_write_idx][dof_write_idx][1] = prim.GetAttribute("physics:upperLimit").Get() + if dof_types[dof_index] == omni.physics.tensors.DofType.Rotation: + values[articulation_write_idx][dof_write_idx] = ( + values[articulation_write_idx][dof_write_idx] * DEG2RAD + ) + dof_write_idx += 1 + articulation_write_idx += 1 + values = self._backend_utils.convert(values, dtype="float32", device=self._device, indexed=True) + return values + + def get_joint_position_targets( + self, + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + clone: bool = True, + ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]: + """Get the joint position targets of articulations in the view + + Args: + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints + to query. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: joint positions of articulations in the view. + Shape is (M, K). + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return None + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + current_joint_positions = self._physics_view.get_dof_position_targets() + if clone: + current_joint_positions = self._backend_utils.clone_tensor(current_joint_positions, device=self._device) + result = current_joint_positions[ + self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices + ] + return result + else: + carb.log_warn("Physics Simulation View is not created yet in order to use get_joint_position_targets") + return None + + def get_joint_velocity_targets( + self, + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + clone: bool = True, + ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]: + """Get the joint velocity targets of articulations in the view + + Args: + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints + to query. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: joint velocities of articulations in the view. + Shape is (M, K). + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return None + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + current_joint_velocities = self._physics_view.get_dof_velocity_targets() + if clone: + current_joint_velocities = self._backend_utils.clone_tensor( + current_joint_velocities, device=self._device + ) + result = current_joint_velocities[ + self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices + ] + return result + else: + carb.log_warn("Physics Simulation View is not created yet in order to use get_joint_velocity_targets") + return None + + def set_max_velocities( + self, + values: Union[np.ndarray, torch.Tensor, wp.array], + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + ) -> None: + """Sets maximum velocities for articulation in the view. + + Args: + values (Union[np.ndarray, torch.Tensor, wp.array]): maximum velocities for articulations in the view. shape (M, K). + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints + to manipulate. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, "cpu") + new_values = self._physics_view.get_dof_max_velocities() + new_values = self._backend_utils.assign( + self._backend_utils.move_data(values, device="cpu"), + new_values, + [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices], + ) + self._physics_view.set_dof_max_velocities(new_values, indices) + else: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + articulation_read_idx = 0 + indices = self._backend_utils.to_list(indices) + joint_indices = self._backend_utils.to_list(joint_indices) + values = self._backend_utils.to_list(values) + for i in indices: + dof_read_idx = 0 + for dof_index in joint_indices: + prim = PhysxSchema.PhysxJointAPI(get_prim_at_path(self._dof_paths[i][dof_index])) + if not prim.GetMaxJointVelocityAttr(): + prim.CreateMaxJointVelocityAttr().Set(values[articulation_read_idx][dof_read_idx]) + else: + prim.GetMaxJointVelocityAttr().Set(values[articulation_read_idx][dof_read_idx]) + dof_read_idx += 1 + articulation_read_idx += 1 + return + + def get_max_velocities( + self, + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + clone: bool = True, + ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]: + """Gets maximum velocities for articulation in the view. + + Args: + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints + to query. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + clone (Optional[bool]): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: maximum velocities for articulations in the view. shape (M, K). + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return None + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, "cpu") + max_velocities = self._physics_view.get_dof_max_velocities() + if clone: + max_velocities = self._backend_utils.clone_tensor(max_velocities, device="cpu") + result = self._backend_utils.move_data( + max_velocities[ + self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices + ], + device=self._device, + ) + return result + else: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + max_velocities = np.zeros(shape=(indices.shape[0], joint_indices.shape[0]), dtype="float32") + indices = self._backend_utils.to_list(indices) + joint_indices = self._backend_utils.to_list(joint_indices) + articulation_write_idx = 0 + for i in indices: + dof_write_idx = 0 + for dof_index in joint_indices: + prim = PhysxSchema.PhysxJointAPI(get_prim_at_path(self._dof_paths[i][dof_index])) + max_velocities[articulation_write_idx][dof_write_idx] = prim.GetMaxJointVelocityAttr().Get() + dof_write_idx += 1 + articulation_write_idx += 1 + max_velocities = self._backend_utils.convert( + max_velocities, dtype="float32", device=self._device, indexed=True + ) + return max_velocities + + def set_joint_positions( + self, + positions: Optional[Union[np.ndarray, torch.Tensor, wp.array]], + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + ) -> None: + """Set the joint positions of articulations in the view + + .. warning:: + + This method will immediately set (teleport) the affected joints to the indicated value. + Use the ``set_joint_position_targets`` or the ``apply_action`` methods to control the articulation joints. + + Args: + positions (Optional[Union[np.ndarray, torch.Tensor, wp.array]]): joint positions of articulations in the view to be set to in the next frame. + shape is (M, K). + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints + to manipulate. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + + .. hint:: + + This method belongs to the methods used to set the articulation kinematic states: + + ``set_velocities`` (``set_linear_velocities``, ``set_angular_velocities``), + ``set_joint_positions``, ``set_joint_velocities``, ``set_joint_efforts`` + + Example: + + .. code-block:: python + + >>> # set all the articulation joints. + >>> # Since there are 5 envs, the joint positions are repeated 5 times + >>> positions = np.tile(np.array([0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8, 0.04, 0.04]), (num_envs, 1)) + >>> prims.set_joint_positions(positions) + >>> + >>> # set only the fingers in closed position: panda_finger_joint1 (7) and panda_finger_joint2 (8) to 0.0 + >>> # for the first, middle and last of the 5 envs + >>> positions = np.tile(np.array([0.0, 0.0]), (3, 1)) + >>> prims.set_joint_positions(positions, indices=np.array([0, 2, 4]), joint_indices=np.array([7, 8])) + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + new_dof_pos = self._physics_view.get_dof_positions() + new_dof_pos = self._backend_utils.assign( + self._backend_utils.move_data(positions, device=self._device), + new_dof_pos, + [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices], + ) + self._physics_view.set_dof_positions(new_dof_pos, indices) + + # THIS IS THE FIX: + # FIX V1: COMMENT OUT THE BELOW LINE AND SET TARGETS INSTEAD + # FIX V2: DECOUPLE INSTANTANEOUS POSITION FROM TARGETS + # self._physics_view.set_dof_position_targets(new_dof_pos, indices) + # self.set_joint_position_targets(positions, indices, joint_indices) + else: + carb.log_warn("Physics Simulation View is not created yet in order to use set_joint_positions") + + def set_joint_velocities( + self, + velocities: Optional[Union[np.ndarray, torch.Tensor, wp.array]], + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + ) -> None: + """Set the joint velocities of articulations in the view + + .. warning:: + + This method will immediately set the affected joints to the indicated value. + Use the ``set_joint_velocity_targets`` or the ``apply_action`` methods to control the articulation joints. + + Args: + velocities (Optional[Union[np.ndarray, torch.Tensor, wp.array]]): joint velocities of articulations in the view to be set to in the next frame. + shape is (M, K). + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints + to manipulate. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + + .. hint:: + + This method belongs to the methods used to set the articulation kinematic states: + + ``set_velocities`` (``set_linear_velocities``, ``set_angular_velocities``), + ``set_joint_positions``, ``set_joint_velocities``, ``set_joint_efforts`` + + Example: + + .. code-block:: python + + >>> # set the velocities for all the articulation joints to the indicated values. + >>> # Since there are 5 envs, the joint velocities are repeated 5 times + >>> velocities = np.tile(np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]), (num_envs, 1)) + >>> prims.set_joint_velocities(velocities) + >>> + >>> # set the fingers velocities: panda_finger_joint1 (7) and panda_finger_joint2 (8) to -0.1 + >>> # for the first, middle and last of the 5 envs + >>> velocities = np.tile(np.array([-0.1, -0.1]), (3, 1)) + >>> prims.set_joint_velocities(velocities, indices=np.array([0, 2, 4]), joint_indices=np.array([7, 8])) + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + new_dof_vel = self._physics_view.get_dof_velocities() + new_dof_vel = self._backend_utils.assign( + self._backend_utils.move_data(velocities, device=self._device), + new_dof_vel, + [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices], + ) + self._physics_view.set_dof_velocities(new_dof_vel, indices) + + # THIS IS THE FIX: + # FIX V1: COMMENT OUT THE BELOW LINE AND SET TARGETS INSTEAD + # FIX V2: DECOUPLE INSTANTANEOUS VELOCITY FROM TARGETS + # self._physics_view.set_dof_velocity_targets(new_dof_vel, indices) + # self.set_joint_velocity_targets(velocities, indices, joint_indices) + else: + carb.log_warn("Physics Simulation View is not created yet in order to use set_joint_velocities") + return + + def set_joint_efforts( + self, + efforts: Optional[Union[np.ndarray, torch.Tensor, wp.array]], + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + ) -> None: + """Set the joint efforts of articulations in the view + + .. note:: + + This method can be used for effort control. For this purpose, there must be no joint drive + or the stiffness and damping must be set to zero. + + Args: + efforts (Optional[Union[np.ndarray, torch.Tensor, wp.array]]): efforts of articulations in the view to be set to in the next frame. + shape is (M, K). + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints + to manipulate. Shape (K,). + Where K <= num of dofs. + Defaults to None (i.e: all dofs). + + .. hint:: + + This method belongs to the methods used to set the articulation kinematic states: + + ``set_velocities`` (``set_linear_velocities``, ``set_angular_velocities``), + ``set_joint_positions``, ``set_joint_velocities``, ``set_joint_efforts`` + + Example: + + .. code-block:: python + + >>> # set the efforts for all the articulation joints to the indicated values. + >>> # Since there are 5 envs, the joint efforts are repeated 5 times + >>> efforts = np.tile(np.array([10, 20, 30, 40, 50, 60, 70, 80, 90]), (num_envs, 1)) + >>> prims.set_joint_efforts(efforts) + >>> + >>> # set the fingers efforts: panda_finger_joint1 (7) and panda_finger_joint2 (8) to 10 + >>> # for the first, middle and last of the 5 envs + >>> efforts = np.tile(np.array([10, 10]), (3, 1)) + >>> prims.set_joint_efforts(efforts, indices=np.array([0, 2, 4]), joint_indices=np.array([7, 8])) + """ + if not self._is_initialized: + carb.log_warn("ArticulationView needs to be initialized.") + return + + if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device) + + # THIS IS THE FIX: COMMENT OUT THE BELOW LINE AND USE ACTUATION FORCES INSTEAD + # new_dof_efforts = self._backend_utils.create_zeros_tensor( + # shape=[self.count, self.num_dof], dtype="float32", device=self._device + # ) + new_dof_efforts = self._physics_view.get_dof_actuation_forces() + new_dof_efforts = self._backend_utils.assign( + self._backend_utils.move_data(efforts, device=self._device), + new_dof_efforts, + [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices], + ) + self._physics_view.set_dof_actuation_forces(new_dof_efforts, indices) + else: + carb.log_warn("Physics Simulation View is not created yet in order to use set_joint_efforts") + return + + def _invalidate_physics_handle_callback(self, event): + # Overwrite super method, add additional de-initialization + if event.type == int(omni.timeline.TimelineEventType.STOP): + self._physics_view = None + self._invalidate_physics_handle_event = None + self._is_initialized = False + + @property + def initialized(self): + # THIS IS THE FIX: another crazy bug from isaac, specifically isaac 4.5 + return self._is_initialized + + def _on_prim_deletion(self, prim_path): + _XFormPrimView._on_prim_deletion(self, prim_path) + self._physics_view = None + + +class RigidPrimView(_RigidPrimView): + def get_linear_velocities( + self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None, clone: bool = True + ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]: + """Get the linear velocities of prims in the view. + + Args: + indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indices to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view) + clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: linear velocities of the prims in the view. shape is (M, 3). + + Example: + + .. code-block:: python + + >>> # get all rigid prim linear velocities. Returned shape is (5, 3) for the example: 5 envs, linear (3) + >>> prims.get_linear_velocities() + [[0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.]] + >>> + >>> # get only the rigid prim linear velocities for the first, middle and last of the 5 envs. + >>> # Returned shape is (3, 3) for the example: 3 envs selected, linear (3) + >>> prims.get_linear_velocities(indices=np.array([0, 2, 4])) + [[0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.]] + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + + if self.is_physics_handle_valid(): + linear_velocities = self._physics_view.get_velocities() + if clone: + # THIS LINE WAS NAMED INCORRECTLY!!! + linear_velocities = self._backend_utils.clone_tensor(linear_velocities, device=self._device) + return linear_velocities[indices, 0:3] + else: + linear_velocities = np.zeros(shape=(indices.shape[0], 3), dtype=np.float32) + write_idx = 0 + indices = self._backend_utils.to_list(indices) + for i in indices: + if self._rigid_body_apis[i] is None: + if self._prims[i].HasAPI(UsdPhysics.RigidBodyAPI): + rigid_api = UsdPhysics.RigidBodyAPI(self._prims[i]) + else: + rigid_api = UsdPhysics.RigidBodyAPI.Apply(self._prims[i]) + self._rigid_body_apis[i] = rigid_api + linear_velocities[write_idx] = np.array( + self._rigid_body_apis[i].GetVelocityAttr().Get(), dtype=np.float32 + ) + write_idx += 1 + linear_velocities = self._backend_utils.convert( + linear_velocities, dtype="float32", device=self._device, indexed=True + ) + return linear_velocities + + def get_angular_velocities( + self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None, clone: bool = True + ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]: + """Get the angular velocities of prims in the view. + + Args: + indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indices to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view) + clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: angular velocities of the prims in the view. shape is (M, 3). + + Example: + + .. code-block:: python + + >>> # get all rigid prim angular velocities. Returned shape is (5, 3) for the example: 5 envs, angular (3) + >>> prims.get_angular_velocities() + [[0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.]] + >>> + >>> # get only the rigid prim angular velocities for the first, middle and last of the 5 envs + >>> # Returned shape is (5, 3) for the example: 3 envs selected, angular (3) + >>> prims.get_angular_velocities(indices=np.array([0, 2, 4])) + [[0. 0. 0.] + [0. 0. 0.] + [0. 0. 0.]] + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + if self.is_physics_handle_valid(): + angular_velocities = self._physics_view.get_velocities() + if clone: + # THIS LINE WAS NAMED INCORRECTLY!! + angular_velocities = self._backend_utils.clone_tensor(angular_velocities, device=self._device) + return angular_velocities[indices, 3:6] + else: + angular_velocities = np.zeros(shape=(indices.shape[0], 3), dtype=np.float32) + write_idx = 0 + indices = self._backend_utils.to_list(indices) + for i in indices: + if self._rigid_body_apis[i] is None: + if self._prims[i].HasAPI(UsdPhysics.RigidBodyAPI): + rigid_api = UsdPhysics.RigidBodyAPI(self._prims[i]) + else: + rigid_api = UsdPhysics.RigidBodyAPI.Apply(self._prims[i]) + self._rigid_body_apis[i] = rigid_api + angular_velocities[write_idx] = np.array( + self._rigid_body_apis[i].GetAngularVelocityAttr().Get(), dtype="float32" + ) + write_idx += 1 + angular_velocities = self._backend_utils.convert( + angular_velocities, dtype="float32", device=self._device, indexed=True + ) + return angular_velocities + + def get_world_poses( + self, + indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None, + clone: bool = True, + usd: bool = True, + ) -> Union[ + Tuple[np.ndarray, np.ndarray], Tuple[torch.Tensor, torch.Tensor], Tuple[wp.indexedarray, wp.indexedarray] + ]: + """Get the poses of the prims in the view with respect to the world's frame. + + Args: + indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indices to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + usd (bool, optional): True to query from usd. Otherwise False to query from Fabric data. Defaults to True. + + Returns: + Union[Tuple[np.ndarray, np.ndarray], Tuple[torch.Tensor, torch.Tensor], Tuple[wp.indexedarray, wp.indexedarray]]: + first index is positions in the world frame of the prims. shape is (M, 3). + second index is quaternion orientations in the world frame of the prims. + quaternion is scalar-first (w, x, y, z). shape is (M, 4). + + Example: + + .. code-block:: python + + >>> # get all rigid prim poses with respect to the world's frame. + >>> # Returned shape is position (5, 3) and orientation (5, 4) for the example: 5 envs + >>> positions, orientations = prims.get_world_poses() + >>> positions + [[ 1.4999989e+00 -7.4999851e-01 -1.5118626e-07] + [ 1.4999989e+00 7.5000149e-01 -2.5988294e-07] + [-1.0017333e-06 -7.4999845e-01 7.6070329e-08] + [-9.5906785e-07 7.5000149e-01 1.0593490e-07] + [-1.5000011e+00 -7.4999851e-01 1.9655154e-07]] + >>> orientations + [[ 9.9999994e-01 -8.8168377e-07 -4.1946004e-07 -1.5067183e-08] + [ 9.9999994e-01 -8.8691013e-07 -4.2665880e-07 -2.7188951e-09] + [ 1.0000000e+00 -9.5171310e-07 -2.2615541e-07 5.5922797e-08] + [ 1.0000000e+00 -8.9923367e-07 -1.4408238e-07 1.3476099e-08] + [ 1.0000000e+00 -7.9806580e-07 -1.3064776e-07 5.3154917e-08]] + >>> + >>> # get only the rigid prim poses with respect to the world's frame for the first, middle and last of the 5 envs. + >>> # Returned shape is position (3, 3) and orientation (3, 4) for the example: 3 envs selected + >>> positions, orientations = prims.get_world_poses(indices=np.array([0, 2, 4])) + >>> positions + [[ 1.4999989e+00 -7.4999851e-01 -1.5118626e-07] + [-1.0017333e-06 -7.4999845e-01 7.6070329e-08] + [-1.5000011e+00 -7.4999851e-01 1.9655154e-07]] + >>> orientations + [[ 9.9999994e-01 -8.8168377e-07 -4.1946004e-07 -1.5067183e-08] + [ 1.0000000e+00 -9.5171310e-07 -2.2615541e-07 5.5922797e-08] + [ 1.0000000e+00 -7.9806580e-07 -1.3064776e-07 5.3154917e-08]] + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + if self.is_physics_handle_valid(): + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + pose = self._physics_view.get_transforms() + if clone: + pose = self._backend_utils.clone_tensor(pose, device=self._device) + pos = pose[indices, 0:3] + + # We AVOID native self._backend_utils.xyzw2wxyz(pose[indices, 3:7]) because it's slow!! + rot = pose[:, [6, 3, 4, 5]][indices] + return pos, rot + else: + return _XFormPrimView.get_world_poses(self, indices=indices, usd=usd) + + def enable_gravities(self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None) -> None: + """Enable gravity on rigid bodies (enabled by default). + + Args: + indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indicies to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + if self.is_physics_handle_valid(): + indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") + data = self._physics_view.get_disable_gravities().reshape(self._count) + data = self._backend_utils.assign( + self._backend_utils.create_tensor_from_list([False] * len(indices), dtype="uint8"), data, indices + ) + self._physics_view.set_disable_gravities(data, indices) + else: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + indices = self._backend_utils.to_list(indices) + for i in indices: + if self._physx_rigid_body_apis[i] is None: + if self._prims[i].HasAPI(PhysxSchema.PhysxRigidBodyAPI): + rigid_api = PhysxSchema.PhysxRigidBodyAPI(self._prims[i]) + else: + rigid_api = PhysxSchema.PhysxRigidBodyAPI.Apply(self._prims[i]) + self._physx_rigid_body_apis[i] = rigid_api + self._physx_rigid_body_apis[i].GetDisableGravityAttr().Set(False) + + def disable_gravities(self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None) -> None: + """Disable gravity on rigid bodies (enabled by default). + + Args: + indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indicies to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") + if self.is_physics_handle_valid(): + data = self._physics_view.get_disable_gravities().reshape(self._count) + data = self._backend_utils.assign( + self._backend_utils.create_tensor_from_list([True] * len(indices), dtype="uint8"), data, indices + ) + self._physics_view.set_disable_gravities(data, indices) + else: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + indices = self._backend_utils.to_list(indices) + for i in indices: + if self._physx_rigid_body_apis[i] is None: + if self._prims[i].HasAPI(PhysxSchema.PhysxRigidBodyAPI): + rigid_api = PhysxSchema.PhysxRigidBodyAPI(self._prims[i]) + else: + rigid_api = PhysxSchema.PhysxRigidBodyAPI.Apply(self._prims[i]) + self._physx_rigid_body_apis[i] = rigid_api + self._physx_rigid_body_apis[i].GetDisableGravityAttr().Set(True) + return + + def get_coms( + self, indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, clone: bool = True + ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]: + """Get rigid body center of mass (COM) of bodies in the view. + + Args: + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to query. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True. + + Returns: + Union[np.ndarray, torch.Tensor, wp.indexedarray]: rigid body center of mass positions and orientations of prims in the view. + position shape is (M, 1, 3), orientation shape is (M, 1, 4). + + Example: + + .. code-block:: python + + >>> # get all rigid body center of mass. + >>> # Returned shape is (5, 1, 3) for positions and (5, 1, 4) for orientations for the example: 5 envs + >>> positions, orientations = prims.get_coms() + >>> positions + [[[0. 0. 0.]] + [[0. 0. 0.]] + [[0. 0. 0.]] + [[0. 0. 0.]] + [[0. 0. 0.]]] + >>> orientations + [[[1. 0. 0. 0.]] + [[1. 0. 0. 0.]] + [[1. 0. 0. 0.]] + [[1. 0. 0. 0.]] + [[1. 0. 0. 0.]]] + >>> + >>> # get rigid body center of mass for the first, middle and last of the 5 envs. + >>> # Returned shape is (3, 1, 3) for positions and (3, 1, 4) for orientations + >>> positions, orientations = prims.get_coms(indices=np.array([0, 2, 4])) + >>> positions + [[[0. 0. 0.]] + [[0. 0. 0.]] + [[0. 0. 0.]]] + >>> orientations + [[[1. 0. 0. 0.]] + [[1. 0. 0. 0.]] + [[1. 0. 0. 0.]]] + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + if self.is_physics_handle_valid(): + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + current_values = self._backend_utils.move_data( + self._physics_view.get_coms().reshape((self.count, 7)), self._device + ) + if clone: + current_values = self._backend_utils.clone_tensor(current_values, device=self._device) + positions = current_values[ + self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, 0:3 + ] + orientations = self._backend_utils.xyzw2wxyz( + current_values[self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, 3:7] + ) + return positions, orientations + else: + indices = self._backend_utils.resolve_indices(indices, self.count, self._device) + positions = np.zeros((indices.shape[0], 1, 3), dtype=np.float32) + orientations = np.zeros((indices.shape[0], 1, 4), dtype=np.float32) + indices = self._backend_utils.to_list(indices) + write_idx = 0 + for i in indices: + positions[write_idx][0] = np.array(self._prims[i].GetAttribute("physics:centerOfMass").Get()) + orientations[write_idx][0] = np.array([1, 0, 0, 0]) + write_idx += 1 + positions = self._backend_utils.convert(positions, device=self._device, dtype="float32", indexed=True) + orientations = self._backend_utils.convert(orientations, device=self._device, dtype="float32", indexed=True) + return positions, orientations + + def set_coms( + self, + positions: Union[np.ndarray, torch.Tensor, wp.array] = None, + orientations: Union[np.ndarray, torch.Tensor, wp.array] = None, + indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, + ) -> None: + """Set body center of mass (COM) positions and orientations for bodies in the view. + + Args: + positions (Union[np.ndarray, torch.Tensor, wp.array]): body center of mass positions for bodies in the view. shape (M, 1, 3). + orientations (Union[np.ndarray, torch.Tensor, wp.array]): body center of mass orientations for bodies in the view. shape (M, 1, 4). + indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims + to manipulate. Shape (M,). + Where M <= size of the encapsulated prims in the view. + Defaults to None (i.e: all prims in the view). + + Example: + + .. code-block:: python + + >>> # set the center of mass for all the rigid bodies to the specified values. + >>> # Since there are 5 envs, the inertias are repeated 5 times + >>> positions = np.tile(np.array([0.01, 0.02, 0.03]), (num_envs, 1, 1)) + >>> orientations = np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (num_envs, 1, 1)) + >>> prims.set_coms(positions, orientations) + >>> + >>> # set the rigid bodies center of mass for the first, middle and last of the 5 envs + >>> positions = np.tile(np.array([0.01, 0.02, 0.03]), (3, 1, 1)) + >>> orientations = np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (3, 1, 1)) + >>> prims.set_coms(positions, orientations, indices=np.array([0, 2, 4])) + """ + if not self._is_valid: + raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths)) + indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") + if self.is_physics_handle_valid(): + coms = self._physics_view.get_coms().reshape((self.count, 7)) + if positions is not None: + if self._backend == "warp": + coms = self._backend_utils.assign( + self._backend_utils.move_data(positions, device="cpu"), + coms, + [indices, wp.array([0, 1, 2], dtype=wp.int32, device="cpu")], + ) + else: + coms[self._backend_utils.expand_dims(indices, 1), 0:3] = self._backend_utils.move_data( + positions, device="cpu" + ) + if orientations is not None: + if self._backend == "warp": + coms = self._backend_utils.assign( + self._backend_utils.move_data(self._backend_utils.wxyz2xyzw(orientations), device="cpu"), + coms, + [indices, wp.array([3, 4, 5, 6], dtype=wp.int32, device="cpu")], + ) + else: + coms[self._backend_utils.expand_dims(indices, 1), 3:7] = self._backend_utils.move_data( + orientations[:, :, [1, 2, 3, 0]], device="cpu" + ) + self._physics_view.set_coms(coms, indices) + else: + # Note: this does NOT set orientation, as it is not supported in USD + positions = self._backend_utils.to_list(positions) + write_idx = 0 + for i in indices: + properties = self._prims[i].GetPropertyNames() + position = Gf.Vec3f(*positions[write_idx][0]) + if "physics:centerOfMass" not in properties: + carb.log_error( + "physics:centerOfMass property needs to be set for {} before setting its position".format( + self.name + ) + ) + xform_op = self._prims[i].GetAttribute("physics:centerOfMass") + xform_op.Set(position) + write_idx += 1 + + +def colorize_bboxes(bboxes_2d_data, bboxes_2d_rgb, num_channels=3): + """Colorizes 2D bounding box data for visualization. + + We are overriding the replicator native version of this function to fix a bug. + In their version of this function, the ordering of the rectangle corners is incorrect and we fix it here. + + Args: + bboxes_2d_data (numpy.ndarray): 2D bounding box data from the sensor. + bboxes_2d_rgb (numpy.ndarray): RGB data from the sensor to embed bounding box. + num_channels (int): Specify number of channels i.e. 3 or 4. + """ + semantic_id_list = [] + bbox_2d_list = [] + rgb_img = Image.fromarray(bboxes_2d_rgb) + rgb_img_draw = ImageDraw.Draw(rgb_img) + for bbox_2d in bboxes_2d_data: + semantic_id_list.append(bbox_2d[0]) + bbox_2d_list.append(bbox_2d) + semantic_id_list_np = np.unique(np.array(semantic_id_list)) + color_list = random_colours(len(semantic_id_list_np.tolist()), False, num_channels) + for bbox_2d in bbox_2d_list: + index = np.where(semantic_id_list_np == bbox_2d[0])[0][0] + bbox_color = color_list[index] + outline = (bbox_color[0], bbox_color[1], bbox_color[2]) + if num_channels == 4: + outline = ( + bbox_color[0], + bbox_color[1], + bbox_color[2], + bbox_color[3], + ) + rgb_img_draw.rectangle([(bbox_2d[1], bbox_2d[2]), (bbox_2d[3], bbox_2d[4])], outline=outline, width=2) + bboxes_2d_rgb = np.array(rgb_img) + return bboxes_2d_rgb diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/geometry_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/geometry_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..673f5c4e3091db2c1c9002c770d8bd551f3ecd7f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/geometry_utils.py @@ -0,0 +1,179 @@ +""" +A set of helper utility functions for dealing with 3D geometry +""" + +import math + +import torch as th + +import omnigibson.utils.transform_utils as T + + +def wrap_angle(theta): + """ " + Converts an angle to the range [-pi, pi). + + Args: + theta (float): angle in radians + + Returns: + float: angle in radians in range [-pi, pi) + """ + return (theta + math.pi) % (2 * math.pi) - math.pi + + +def get_particle_positions_in_frame(pos, quat, scale, particle_positions): + """ + Transforms particle positions @positions into the frame specified by @pos and @quat with new scale @scale, + where @pos and @quat are assumed to be specified in the same coordinate frame that @particle_positions is specified + + Args: + pos (3-array): (x,y,z) pos of the new frame + quat (4-array): (x,y,z,w) quaternion orientation of the new frame + scale (3-array): (x,y,z) local scale of the new frame + particle_positions ((N, 3) array): positions + + Returns: + (N,) array: updated particle positions in the new coordinate frame + """ + + # Get pose of origin (global frame) in new_frame + origin_in_new_frame = T.pose_inv(T.pose2mat((pos, quat))) + # Batch the transforms to get all particle points in the local link frame + positions_tensor = th.tile(th.eye(4).reshape(1, 4, 4), (len(particle_positions), 1, 1)) # (N, 4, 4) + # Scale by the new scale# + positions_tensor[:, :3, 3] = particle_positions + particle_positions = (origin_in_new_frame @ positions_tensor)[:, :3, 3] # (N, 3) + # Scale by the new scale + return particle_positions / scale.reshape(1, 3) + + +def get_particle_positions_from_frame(pos, quat, scale, particle_positions): + """ + Transforms particle positions @positions from the frame specified by @pos and @quat with new scale @scale. + + This is similar to @get_particle_positions_in_frame, but does the reverse operation, inverting @pos and @quat + + Args: + pos (3-array): (x,y,z) pos of the local frame + quat (4-array): (x,y,z,w) quaternion orientation of the local frame + scale (3-array): (x,y,z) local scale of the local frame + particle_positions ((N, 3) array): positions + + Returns: + (N,) array: updated particle positions in the parent coordinate frame + """ + # Scale by the new scale + particle_positions = particle_positions * scale.reshape(1, 3) + + # Get pose of origin (global frame) in new_frame + origin_in_new_frame = T.pose2mat((pos, quat)) + # Batch the transforms to get all particle points in the local link frame + positions_tensor = th.tile(th.eye(4).reshape(1, 4, 4), (len(particle_positions), 1, 1)) # (N, 4, 4) + # Scale by the new scale# + positions_tensor[:, :3, 3] = particle_positions + return (origin_in_new_frame @ positions_tensor)[:, :3, 3] # (N, 3) + + +def check_points_in_cube(size, particle_positions): + """ + Checks which points are within a cube with specified size @size. + + NOTE: Assumes the cube and positions are expressed + in the same coordinate frame such that the cube's dimensions are axis-aligned with (x,y,z) + + Args: + size float: length of each side of the cube, specified in its local frame + particle_positions ((N, 3) array): positions to check for whether it is in the cube + + Returns: + (N,) array: boolean numpy array specifying whether each point lies in the cube. + """ + return ((-size / 2.0 < particle_positions) & (particle_positions < size / 2.0)).sum(dim=-1) == 3 + + +def check_points_in_cone(size, particle_positions): + """ + Checks which points are within a cone with specified size @size. + + NOTE: Assumes the cone and positions are + expressed in the same coordinate frame such that the cone's height is aligned with the z-axis + + Args: + size (2-array): (radius, height) dimensions of the cone, specified in its local frame + particle_positions ((N, 3) array): positions to check for whether it is in the cone + + Returns: + (N,) array: boolean numpy array specifying whether each point lies in the cone. + """ + radius, height = size + in_height = (-height / 2.0 < particle_positions[:, -1]) & (particle_positions[:, -1] < height / 2.0) + in_radius = th.norm(particle_positions[:, :-1], dim=-1) < ( + radius * (1 - (particle_positions[:, -1] + height / 2.0) / height) + ) + return in_height & in_radius + + +def check_points_in_cylinder(size, particle_positions): + """ + Checks which points are within a cylinder with specified size @size. + + NOTE: Assumes the cylinder and positions are + expressed in the same coordinate frame such that the cylinder's height is aligned with the z-axis + + Args: + size (2-array): (radius, height) dimensions of the cylinder, specified in its local frame + particle_positions ((N, 3) array): positions to check for whether it is in the cylinder + + Returns: + (N,) array: boolean numpy array specifying whether each point lies in the cylinder. + """ + radius, height = size + in_height = (-height / 2.0 < particle_positions[:, -1]) & (particle_positions[:, -1] < height / 2.0) + in_radius = th.norm(particle_positions[:, :-1], dim=-1) < radius + return in_height & in_radius + + +def check_points_in_sphere(size, particle_positions): + """ + Checks which points are within a sphere with specified size @size. + + NOTE: Assumes the sphere and positions are expressed in the same coordinate frame + + Args: + size (float): radius dimensions of the sphere + particle_positions ((N, 3) array): positions to check for whether it is in the sphere + + Returns: + (N,) array: boolean numpy array specifying whether each point lies in the sphere + """ + return th.norm(particle_positions, dim=-1) < size + + +def check_points_in_convex_hull_mesh(mesh_face_centroids, mesh_face_normals, particle_positions): + """ + Checks which points are within a sphere with specified size @size. + + NOTE: Assumes the mesh and positions are expressed in the same coordinate frame + + Args: + mesh_face_centroids (D, 3): (x,y,z) location of the centroid of each mesh face, expressed in its local frame + mesh_face_normals (D, 3): (x,y,z) normalized direction vector of each mesh face, expressed in its local frame + particle_positions ((N, 3) array): positions to check for whether it is in the mesh + + Returns: + (N,) array: boolean numpy array specifying whether each point lies in the mesh + """ + # For every mesh point / normal and particle position pair, we check whether it is "inside" (i.e.: the point lies + # BEHIND the normal plane -- this is easily done by taking the dot product with the vector from the point to the + # particle position with the normal, and validating that the value is < 0) + D, _ = mesh_face_centroids.shape + N, _ = particle_positions.shape + mesh_points = th.tile(mesh_face_centroids.reshape(1, D, 3), (N, 1, 1)) + mesh_normals = th.tile(mesh_face_normals.reshape(1, D, 3), (N, 1, 1)) + particle_positions = th.tile(particle_positions.reshape(N, 1, 3), (1, D, 1)) + # All arrays are now (N, D, 3) shape -- efficient for batching + in_range = ((particle_positions - mesh_points) * mesh_normals).sum(dim=-1) < 0 # shape (N, D) + # All D normals must be satisfied for a single point to be considered inside the hull + in_range = in_range.sum(dim=-1) == D + return in_range diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/git_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/git_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..08f6ee5460184196f270e9a020870be960dc4b9b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/git_utils.py @@ -0,0 +1,28 @@ +from pathlib import Path + +import bddl +import git + +import omnigibson as og + + +def git_info(directory): + repo = git.Repo(directory) + try: + branch_name = repo.active_branch.name + except TypeError: + branch_name = "[DETACHED]" + return { + "directory": str(directory), + "code_diff": repo.git.diff(None), + "code_diff_staged": repo.git.diff("--staged"), + "commit_hash": repo.head.commit.hexsha, + "branch_name": branch_name, + } + + +def project_git_info(): + return { + "OmniGibson": git_info(Path(og.root_path).parent), + "bddl": git_info(Path(bddl.__file__).parent.parent), + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/grasping_planning_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/grasping_planning_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce20acad2ca641ee92a9de1b3e9fd261219925c3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/grasping_planning_utils.py @@ -0,0 +1,545 @@ +import math +import random + +import torch as th + +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.object_states.open_state import _get_relevant_joints +from omnigibson.utils.constants import JointType + +m = create_module_macros(module_path=__file__) + +m.REVOLUTE_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS = (0.4, 0.6) +m.PRISMATIC_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS = (0.2, 0.8) +m.ROTATION_ARC_SEGMENT_LENGTHS = 0.05 +m.OPENNESS_THRESHOLD_TO_OPEN = 0.8 +m.OPENNESS_THRESHOLD_TO_CLOSE = 0.05 + + +def get_grasp_poses_for_object_sticky(target_obj): + """ + Obtain a grasp pose for an object from top down, to be used with sticky grasping. + The grasp pose should be in the world frame. + + Args: + target_obj (StatefulObject): Object to get a grasp pose for + + Returns: + list: List of grasp poses. + """ + + aabb_min_world, aabb_max_world = target_obj.aabb + + bbox_center_world = (aabb_min_world + aabb_max_world) / 2 + bbox_extent_world = aabb_max_world - aabb_min_world + + grasp_center_pos = bbox_center_world + th.tensor([0, 0, bbox_extent_world[2] / 2]) + towards_object_in_world_frame = bbox_center_world - grasp_center_pos + towards_object_in_world_frame /= th.norm(towards_object_in_world_frame) + + # Identity quaternion for top-down grasping (x-forward, y-right, z-down) + grasp_quat = T.euler2quat(th.tensor([0, 0, 0], dtype=th.float32)) + + grasp_pose = (grasp_center_pos, grasp_quat) + grasp_poses = [grasp_pose] + + return grasp_poses + + +def get_grasp_poses_for_object_sticky_from_arbitrary_direction(target_obj): + """ + Obtain a grasp pose for an object from an arbitrary direction to be used with sticky grasping. + + Args: + target_obj (StatefulObject): Object to get a grasp pose for + + Returns: + list: List of grasp candidates, where each grasp candidate is a tuple containing the grasp pose and the approach direction. + """ + bbox_center_in_world, bbox_quat_in_world, bbox_extent_in_base_frame, _ = target_obj.get_base_aligned_bbox( + visual=False + ) + + # Pick an axis and a direction. + approach_axis = random.choice([0, 1, 2]) + approach_direction = random.choice([-1, 1]) if approach_axis != 2 else 1 + constant_dimension_in_base_frame = approach_direction * bbox_extent_in_base_frame * th.eye(3)[approach_axis] + randomizable_dimensions_in_base_frame = bbox_extent_in_base_frame - th.abs(constant_dimension_in_base_frame) + dim_lo, dim_hi = th.tensor([-1, -1, 0]), th.tensor([1, 1, 1]) + random_dimensions_in_base_frame = (dim_hi - dim_lo) * th.rand( + dim_lo.size() + ) + dim_lo # note that we don't allow going below center + grasp_center_in_base_frame = ( + random_dimensions_in_base_frame * randomizable_dimensions_in_base_frame + constant_dimension_in_base_frame + ) + + grasp_center_pos = T.mat2pose( + T.pose2mat((bbox_center_in_world, bbox_quat_in_world)) # base frame to world frame + @ T.pose2mat((grasp_center_in_base_frame, [0, 0, 0, 1])) # grasp pose in base frame + )[0] + th.tensor([0, 0, 0.02]) + towards_object_in_world_frame = bbox_center_in_world - grasp_center_pos + towards_object_in_world_frame /= th.norm(towards_object_in_world_frame) + + # For the grasp, we want the X+ direction to be the direction of the object's surface. + # The other two directions can be randomized. + rand_vec = th.rand(3) + rand_vec /= th.norm(rand_vec) + grasp_x = towards_object_in_world_frame + grasp_y = th.linalg.cross(rand_vec, grasp_x) + grasp_y /= th.norm(grasp_y) + grasp_z = th.linalg.cross(grasp_x, grasp_y) + grasp_z /= th.norm(grasp_z) + grasp_mat = th.tensor([grasp_x, grasp_y, grasp_z]).T + grasp_quat = T.mat2quat(grasp_mat) + + grasp_pose = (grasp_center_pos, grasp_quat) + grasp_candidate = [(grasp_pose, towards_object_in_world_frame)] + + return grasp_candidate + + +def get_grasp_position_for_open(robot, target_obj, should_open, relevant_joint=None, num_waypoints="default"): + """ + Computes the grasp position for opening or closing a joint. + + Args: + robot (BaseRobot): the robot object + target_obj (USDObject): the object to open/close a joint of + should_open (bool): a boolean indicating whether we are opening or closing + relevant_joint (Joint or None): the joint to open/close if we want to do a particular one in advance + num_waypoints (int or str): the number of waypoints to interpolate between the start and end poses (default is "default") + + Returns: + None (if no grasp was found), or Tuple, containing: + relevant_joint: the joint that is being targeted for open/close by the returned grasp + offset_grasp_pose_in_world_frame: the grasp pose in the world frame + waypoints: the interpolated waypoints between the start and end poses + approach_direction_in_world_frame: the approach direction in the world frame + grasp_required: a boolean indicating whether a grasp is required for the opening/closing based on which side of the joint we are + required_pos_change: the required change in position of the joint to open/close + """ + # Pick a moving link of the object. + relevant_joints = [relevant_joint] if relevant_joint is not None else _get_relevant_joints(target_obj)[1] + if len(relevant_joints) == 0: + raise ValueError("Cannot open/close object without relevant joints.") + + # Make sure what we got is an appropriately open/close joint. + relevant_joints = relevant_joints[th.randperm(relevant_joints.size(0))] + selected_joint = None + for joint in relevant_joints: + current_position = joint.get_state()[0][0] + joint_range = joint.upper_limit - joint.lower_limit + openness_fraction = (current_position - joint.lower_limit) / joint_range + if (should_open and openness_fraction < m.OPENNESS_FRACTION_TO_OPEN) or ( + not should_open and openness_fraction > m.OPENNESS_THRESHOLD_TO_CLOSE + ): + selected_joint = joint + break + + if selected_joint is None: + return None + + if selected_joint.joint_type == JointType.JOINT_REVOLUTE: + return (selected_joint,) + grasp_position_for_open_on_revolute_joint( + robot, target_obj, selected_joint, should_open, num_waypoints=num_waypoints + ) + elif selected_joint.joint_type == JointType.JOINT_PRISMATIC: + return (selected_joint,) + grasp_position_for_open_on_prismatic_joint( + robot, target_obj, selected_joint, should_open, num_waypoints=num_waypoints + ) + else: + raise ValueError("Unknown joint type encountered while generating joint position.") + + +def grasp_position_for_open_on_prismatic_joint(robot, target_obj, relevant_joint, should_open, num_waypoints="default"): + """ + Computes the grasp position for opening or closing a prismatic joint. + + Args: + robot (BaseRobot): the robot object + target_obj (USDObject): the object to open + relevant_joint (Joint): the prismatic joint to open + should_open (bool): a boolean indicating whether we are opening or closing + num_waypoints (int or str): the number of waypoints to interpolate between the start and end poses (default is "default") + + Returns: + Tuple, containing: + offset_grasp_pose_in_world_frame: the grasp pose in the world frame + waypoints: the interpolated waypoints between the start and end poses + approach_direction_in_world_frame: the approach direction in the world frame + grasp_required: a boolean indicating whether a grasp is required for the opening/closing based on which side of the joint we are + required_pos_change: the required change in position of the joint to open/close + """ + link_name = relevant_joint.body1.split("/")[-1] + + # Get the bounding box of the child link. + ( + bbox_center_in_world, + bbox_quat_in_world, + bbox_extent_in_link_frame, + _, + ) = target_obj.get_base_aligned_bbox(link_name=link_name, visual=False) + + # Match the push axis to one of the bb axes. + joint_orientation = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array( + relevant_joint.get_attribute("physics:localRot0") + )[[1, 2, 3, 0]] + push_axis = T.quat_apply(joint_orientation, th.tensor([1, 0, 0], dtype=th.float32)) + assert math.isclose(th.max(th.abs(push_axis)).item(), 1.0) # Make sure we're aligned with a bb axis. + push_axis_idx = th.argmax(th.abs(push_axis)) + canonical_push_axis = th.eye(3)[push_axis_idx] + + # TODO: Need to figure out how to get the correct push direction. + push_direction = th.sign(push_axis[push_axis_idx]) if should_open else -1 * th.sign(push_axis[push_axis_idx]) + canonical_push_direction = canonical_push_axis * push_direction + + # Pick the closer of the two faces along the push axis as our favorite. + points_along_push_axis = ( + th.tensor([canonical_push_axis, -canonical_push_axis]) * bbox_extent_in_link_frame[push_axis_idx] / 2 + ) + ( + push_axis_closer_side_idx, + center_of_selected_surface_along_push_axis, + _, + ) = _get_closest_point_to_point_in_world_frame( + points_along_push_axis, (bbox_center_in_world, bbox_quat_in_world), robot.get_position_orientation()[0] + ) + push_axis_closer_side_sign = 1 if push_axis_closer_side_idx == 0 else -1 + + # Pick the other axes. + all_axes = list(set(range(3)) - {push_axis_idx}) + x_axis_idx, y_axis_idx = tuple(sorted(all_axes)) + canonical_x_axis = th.eye(3)[x_axis_idx] + canonical_y_axis = th.eye(3)[y_axis_idx] + + # Find the correct side of the lateral axis & go some distance along that direction. + min_lateral_pos_wrt_surface_center = (canonical_x_axis + canonical_y_axis) * -bbox_extent_in_link_frame / 2 + max_lateral_pos_wrt_surface_center = (canonical_x_axis + canonical_y_axis) * bbox_extent_in_link_frame / 2 + diff_lateral_pos_wrt_surface_center = max_lateral_pos_wrt_surface_center - min_lateral_pos_wrt_surface_center + bound_lo, bound_hi = ( + m.PRISMATIC_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[0] * diff_lateral_pos_wrt_surface_center, + m.PRISMATIC_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[1] * diff_lateral_pos_wrt_surface_center, + ) + sampled_lateral_pos_wrt_min = th.rand(bound_lo.size()) * (bound_hi - bound_lo) + bound_lo + lateral_pos_wrt_surface_center = min_lateral_pos_wrt_surface_center + sampled_lateral_pos_wrt_min + grasp_position_in_bbox_frame = center_of_selected_surface_along_push_axis + lateral_pos_wrt_surface_center + grasp_quat_in_bbox_frame = T.quat_inverse(joint_orientation) + grasp_pose_in_world_frame = T.pose_transform( + bbox_center_in_world, bbox_quat_in_world, grasp_position_in_bbox_frame, grasp_quat_in_bbox_frame + ) + + # Now apply the grasp offset. + avg_finger_offset = th.mean( + th.tensor([length for length in robot.eef_to_fingertip_lengths[robot.default_arm].values()]) + ) + dist_from_grasp_pos = avg_finger_offset + 0.05 + offset_grasp_pose_in_bbox_frame = ( + grasp_position_in_bbox_frame + canonical_push_axis * push_axis_closer_side_sign * dist_from_grasp_pos, + grasp_quat_in_bbox_frame, + ) + offset_grasp_pose_in_world_frame = T.pose_transform( + bbox_center_in_world, bbox_quat_in_world, *offset_grasp_pose_in_bbox_frame + ) + + # To compute the rotation position, we want to decide how far along the rotation axis we'll go. + target_joint_pos = relevant_joint.upper_limit if should_open else relevant_joint.lower_limit + current_joint_pos = relevant_joint.get_state()[0][0] + + required_pos_change = target_joint_pos - current_joint_pos + push_vector_in_bbox_frame = canonical_push_direction * abs(required_pos_change) + target_hand_pos_in_bbox_frame = grasp_position_in_bbox_frame + push_vector_in_bbox_frame + target_hand_pose_in_world_frame = T.pose_transform( + bbox_center_in_world, bbox_quat_in_world, target_hand_pos_in_bbox_frame, grasp_quat_in_bbox_frame + ) + + # Compute the approach direction. + approach_direction_in_world_frame = T.quat_apply( + bbox_quat_in_world, canonical_push_axis * -push_axis_closer_side_sign + ) + + # Decide whether a grasp is required. If approach direction and displacement are similar, no need to grasp. + grasp_required = th.dot(push_vector_in_bbox_frame, canonical_push_axis * -push_axis_closer_side_sign) < 0 + # TODO: Need to find a better of getting the predicted position of eef for start point of interpolating waypoints. Maybe + # break this into another function that called after the grasp is executed, so we know the eef position? + waypoint_start_offset = ( + -0.05 * approach_direction_in_world_frame if should_open else 0.05 * approach_direction_in_world_frame + ) + avg_finger_offset = th.mean( + th.tensor([length for length in robot.eef_to_fingertip_lengths[robot.default_arm].values()]) + ) + waypoint_start_pose = ( + grasp_pose_in_world_frame[0] + + -1 * approach_direction_in_world_frame * (avg_finger_offset + waypoint_start_offset), + grasp_pose_in_world_frame[1], + ) + waypoint_end_pose = ( + target_hand_pose_in_world_frame[0] + -1 * approach_direction_in_world_frame * avg_finger_offset, + target_hand_pose_in_world_frame[1], + ) + waypoints = interpolate_waypoints(waypoint_start_pose, waypoint_end_pose, num_waypoints=num_waypoints) + + return ( + offset_grasp_pose_in_world_frame, + waypoints, + approach_direction_in_world_frame, + relevant_joint, + grasp_required, + required_pos_change, + ) + + +def interpolate_waypoints(start_pose, end_pose, num_waypoints="default"): + """ + Interpolates a series of waypoints between a start and end pose. + + Args: + start_pose (tuple): A tuple containing the starting position and orientation as a quaternion. + end_pose (tuple): A tuple containing the ending position and orientation as a quaternion. + num_waypoints (int, optional): The number of waypoints to interpolate. If "default", the number of waypoints is calculated based on the distance between the start and end pose. + + Returns: + list: A list of tuples representing the interpolated waypoints, where each tuple contains a position and orientation as a quaternion. + """ + start_pos, start_orn = start_pose + travel_distance = th.norm(end_pose[0] - start_pos) + + if num_waypoints == "default": + num_waypoints = th.max([2, int(travel_distance / 0.01) + 1]).item() + pos_waypoints = th.linspace(start_pos, end_pose[0], num_waypoints) + + # Also interpolate the rotations + fracs = th.linspace(0, 1, num_waypoints) + orn_waypoints = T.quat_slerp(start_orn.unsqueeze(0), end_pose[1].unsqueeze(0), fracs.unsqueeze(1)) + quat_waypoints = [x.as_quat() for x in orn_waypoints] + return [waypoint for waypoint in zip(pos_waypoints, quat_waypoints)] + + +def grasp_position_for_open_on_revolute_joint(robot, target_obj, relevant_joint, should_open): + """ + Computes the grasp position for opening or closing a revolute joint. + + Args: + robot (BaseRobot): the robot object + target_obj (USDObject): the object to open + relevant_joint (Joint): the revolute joint to open + should_open (bool): a boolean indicating whether we are opening or closing + + Returns: + Tuple, containing: + offset_grasp_pose_in_world_frame: the grasp pose in the world frame + waypoints: the interpolated waypoints between the start and end poses + approach_direction_in_world_frame: the approach direction in the world frame + grasp_required: a boolean indicating whether a grasp is required for the opening/closing based on which side of the joint we are + required_pos_change: the required change in position of the joint to open/close + """ + link_name = relevant_joint.body1.split("/")[-1] + link = target_obj.links[link_name] + + # Get the bounding box of the child link. + (bbox_center_in_world, bbox_quat_in_world, _, bbox_center_in_obj_frame) = target_obj.get_base_aligned_bbox( + link_name=link_name, visual=False + ) + + bbox_quat_in_world = link.get_position_orientation()[1] + bbox_extent_in_link_frame = th.tensor( + target_obj.native_link_bboxes[link_name]["collision"]["axis_aligned"]["extent"] + ) + bbox_wrt_origin = T.relative_pose_transform( + bbox_center_in_world, bbox_quat_in_world, *link.get_position_orientation() + ) + origin_wrt_bbox = T.invert_pose_transform(*bbox_wrt_origin) + + joint_orientation = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array( + relevant_joint.get_attribute("physics:localRot0") + )[[1, 2, 3, 0]] + joint_axis = T.quat_apply(joint_orientation, th.tensor([1, 0, 0], dtype=th.float32)) + joint_axis /= th.norm(joint_axis) + origin_towards_bbox = th.tensor(bbox_wrt_origin[0]) + open_direction = th.linalg.cross(joint_axis, origin_towards_bbox) + open_direction /= th.norm(open_direction) + lateral_axis = th.linalg.cross(open_direction, joint_axis) + + # Match the axes to the canonical axes of the link bb. + lateral_axis_idx = th.argmax(th.abs(lateral_axis)) + open_axis_idx = th.argmax(th.abs(open_direction)) + joint_axis_idx = th.argmax(th.abs(joint_axis)) + assert lateral_axis_idx != open_axis_idx + assert lateral_axis_idx != joint_axis_idx + assert open_axis_idx != joint_axis_idx + + canonical_open_direction = th.eye(3)[open_axis_idx] + points_along_open_axis = ( + th.tensor([canonical_open_direction, -canonical_open_direction]) * bbox_extent_in_link_frame[open_axis_idx] / 2 + ) + current_yaw = relevant_joint.get_state()[0][0] + closed_yaw = relevant_joint.lower_limit + points_along_open_axis_after_rotation = [ + _rotate_point_around_axis((point, [0, 0, 0, 1]), bbox_wrt_origin, joint_axis, closed_yaw - current_yaw)[0] + for point in points_along_open_axis + ] + open_axis_closer_side_idx, _, _ = _get_closest_point_to_point_in_world_frame( + points_along_open_axis_after_rotation, + (bbox_center_in_world, bbox_quat_in_world), + robot.get_position_orientation()[0], + ) + open_axis_closer_side_sign = 1 if open_axis_closer_side_idx == 0 else -1 + center_of_selected_surface_along_push_axis = points_along_open_axis[open_axis_closer_side_idx] + + # Find the correct side of the lateral axis & go some distance along that direction. + canonical_joint_axis = th.eye(3)[joint_axis_idx] + lateral_away_from_origin = th.eye(3)[lateral_axis_idx] * th.sign(origin_towards_bbox[lateral_axis_idx]) + min_lateral_pos_wrt_surface_center = ( + lateral_away_from_origin * -th.tensor(origin_wrt_bbox[0]) + - canonical_joint_axis * bbox_extent_in_link_frame[lateral_axis_idx] / 2 + ) + max_lateral_pos_wrt_surface_center = ( + lateral_away_from_origin * bbox_extent_in_link_frame[lateral_axis_idx] / 2 + + canonical_joint_axis * bbox_extent_in_link_frame[lateral_axis_idx] / 2 + ) + diff_lateral_pos_wrt_surface_center = max_lateral_pos_wrt_surface_center - min_lateral_pos_wrt_surface_center + bound_lo, bound_hi = ( + m.REVOLUTE_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[0] * diff_lateral_pos_wrt_surface_center, + m.REVOLUTE_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[1] * diff_lateral_pos_wrt_surface_center, + ) + sampled_lateral_pos_wrt_min = th.rand(bound_lo.size()) * (bound_hi - bound_lo) + bound_lo + lateral_pos_wrt_surface_center = min_lateral_pos_wrt_surface_center + sampled_lateral_pos_wrt_min + grasp_position = center_of_selected_surface_along_push_axis + lateral_pos_wrt_surface_center + # Get the appropriate rotation + + # grasp_quat_in_bbox_frame = get_quaternion_between_vectors([1, 0, 0], canonical_open_direction * open_axis_closer_side_sign * -1) + grasp_quat_in_bbox_frame = _get_orientation_facing_vector_with_random_yaw( + canonical_open_direction * open_axis_closer_side_sign * -1 + ) + + # Now apply the grasp offset. + avg_finger_offset = th.mean( + th.tensor([length for length in robot.eef_to_fingertip_lengths[robot.default_arm].values()]) + ) + dist_from_grasp_pos = avg_finger_offset + 0.05 + offset_in_bbox_frame = canonical_open_direction * open_axis_closer_side_sign * dist_from_grasp_pos + offset_grasp_pose_in_bbox_frame = (grasp_position + offset_in_bbox_frame, grasp_quat_in_bbox_frame) + offset_grasp_pose_in_world_frame = T.pose_transform( + bbox_center_in_world, bbox_quat_in_world, *offset_grasp_pose_in_bbox_frame + ) + + # To compute the rotation position, we want to decide how far along the rotation axis we'll go. + desired_yaw = relevant_joint.upper_limit if should_open else relevant_joint.lower_limit + required_yaw_change = desired_yaw - current_yaw + + # Now we'll rotate the grasp position around the origin by the desired rotation. + # Note that we use the non-offset position here since the joint can't be pulled all the way to the offset. + grasp_pose_in_bbox_frame = grasp_position, grasp_quat_in_bbox_frame + grasp_pose_in_origin_frame = T.pose_transform(*bbox_wrt_origin, *grasp_pose_in_bbox_frame) + + # Get the arc length and divide it up to 10cm segments + arc_length = abs(required_yaw_change) * th.norm(grasp_pose_in_origin_frame[0]) + turn_steps = int(math.ceil(arc_length / m.ROTATION_ARC_SEGMENT_LENGTHS)) + targets = [] + + for i in range(turn_steps): + partial_yaw_change = (i + 1) / turn_steps * required_yaw_change + rotated_grasp_pose_in_bbox_frame = _rotate_point_around_axis( + (offset_grasp_pose_in_bbox_frame[0], offset_grasp_pose_in_bbox_frame[1]), + bbox_wrt_origin, + joint_axis, + partial_yaw_change, + ) + rotated_grasp_pose_in_world_frame = T.pose_transform( + bbox_center_in_world, bbox_quat_in_world, *rotated_grasp_pose_in_bbox_frame + ) + targets.append(rotated_grasp_pose_in_world_frame) + + # Compute the approach direction. + approach_direction_in_world_frame = T.quat_apply( + bbox_quat_in_world, canonical_open_direction * -open_axis_closer_side_sign + ) + + # Decide whether a grasp is required. If approach direction and displacement are similar, no need to grasp. + movement_in_world_frame = th.tensor(targets[-1][0]) - th.tensor(offset_grasp_pose_in_world_frame[0]) + grasp_required = th.dot(movement_in_world_frame, approach_direction_in_world_frame) < 0 + + return ( + offset_grasp_pose_in_world_frame, + targets, + approach_direction_in_world_frame, + grasp_required, + required_yaw_change, + ) + + +def _get_orientation_facing_vector_with_random_yaw(vector): + """ + Get a quaternion that orients the x-axis of the object to face the given vector and the y and z + axes to be random. + + Args: + vector (th.tensor): The vector to face. + + Returns: + th.tensor: A quaternion representing the orientation. + """ + forward = vector / th.norm(vector) + rand_vec = th.rand(3) + rand_vec /= th.norm(3) + side = th.linalg.cross(rand_vec, forward) + side /= th.norm(3) + up = th.linalg.cross(forward, side) + # assert math.isclose(th.norm(up).item(), 1, abs_tol=1e-3) + rotmat = th.tensor([forward, side, up]).T + return T.mat2quat(rotmat) + + +def _rotate_point_around_axis(point_wrt_arbitrary_frame, arbitrary_frame_wrt_origin, joint_axis, yaw_change): + """ + Rotate a point around an axis, given the point in an arbitrary frame, the arbitrary frame's pose in the origin frame, + the axis to rotate around, and the amount to rotate by. This is a utility for rotating the grasp position around the + joint axis. + + Args: + point_wrt_arbitrary_frame (tuple): The point in the arbitrary frame. + arbitrary_frame_wrt_origin (tuple): The pose of the arbitrary frame in the origin frame. + joint_axis (th.tensor): The axis to rotate around. + yaw_change (float): The amount to rotate by. + + Returns: + tuple: The rotated point in the arbitrary frame. + """ + rotation = T.euler2quat(joint_axis * yaw_change) + origin_wrt_arbitrary_frame = T.invert_pose_transform(*arbitrary_frame_wrt_origin) + + pose_in_origin_frame = T.pose_transform(*arbitrary_frame_wrt_origin, *point_wrt_arbitrary_frame) + rotated_pose_in_origin_frame = T.pose_transform([0, 0, 0], rotation, *pose_in_origin_frame) + rotated_pose_in_arbitrary_frame = T.pose_transform(*origin_wrt_arbitrary_frame, *rotated_pose_in_origin_frame) + return rotated_pose_in_arbitrary_frame + + +def _get_closest_point_to_point_in_world_frame( + vectors_in_arbitrary_frame, arbitrary_frame_to_world_frame, point_in_world +): + """ + Given a set of vectors in an arbitrary frame, find the closest vector to a point in world frame. + Useful for picking between two sides of a joint for grasping. + + Args: + vectors_in_arbitrary_frame (list): A list of vectors in the arbitrary frame. + arbitrary_frame_to_world_frame (tuple): The pose of the arbitrary frame in the world frame. + point_in_world (tuple): The point in the world frame. + + Returns: + tuple: The index of the closest vector, the closest vector in the arbitrary frame, and the closest vector in the world frame. + """ + vectors_in_world = th.tensor( + [ + T.pose_transform(*arbitrary_frame_to_world_frame, vector, [0, 0, 0, 1])[0] + for vector in vectors_in_arbitrary_frame + ] + ) + + vector_distances_to_point = th.norm(vectors_in_world - th.tensor(point_in_world)[None, :], dim=1) + closer_option_idx = th.argmin(vector_distances_to_point) + vector_in_arbitrary_frame = vectors_in_arbitrary_frame[closer_option_idx] + vector_in_world_frame = vectors_in_world[closer_option_idx] + + return closer_option_idx, vector_in_arbitrary_frame, vector_in_world_frame diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/gym_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/gym_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f3ac79f9f563ae664d37ce431186f4486ee8bfae --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/gym_utils.py @@ -0,0 +1,158 @@ +from abc import ABCMeta, abstractmethod +from collections.abc import Iterable + +import gymnasium as gym +import torch as th + +from omnigibson.utils.ui_utils import create_module_logger + +# Create module logger +log = create_module_logger(module_name=__name__) + + +def recursively_generate_flat_dict(dic, prefix=None): + """ + Helper function to recursively iterate through dictionary / gym.spaces.Dict @dic and flatten any nested elements, + such that the result is a flat dictionary mapping keys to values + + Args: + dic (dict or gym.spaces.Dict): (Potentially nested) dictionary to convert into a flattened dictionary + prefix (None or str): Prefix to append to the beginning of all strings in the flattened dictionary. None results + in no prefix being applied + + Returns: + dict: Flattened version of @dic + """ + out = dict() + prefix = "" if prefix is None else f"{prefix}::" + for k, v in dic.items(): + if isinstance(v, gym.spaces.Dict) or isinstance(v, dict): + out.update(recursively_generate_flat_dict(dic=v, prefix=f"{prefix}{k}")) + elif isinstance(v, gym.spaces.Tuple) or isinstance(v, tuple): + for i, vv in enumerate(v): + # Assume no dicts are nested within tuples + out[f"{prefix}{k}::{i}"] = vv + else: + # Add to out dict + out[f"{prefix}{k}"] = v + + return out + + +def recursively_generate_compatible_dict(dic): + """ + Helper function to recursively iterate through dictionary and cast values to necessary types to be compatible with + Gym spaces -- in particular, the Sequence and Tuple types for th.tensor values in @dic + + Args: + dic (dict or gym.spaces.Dict): (Potentially nested) dictionary to convert into a flattened dictionary + + Returns: + dict: Gym-compatible version of @dic + """ + out = dict() + for k, v in dic.items(): + if isinstance(v, dict): + out[k] = recursively_generate_compatible_dict(dic=v) + elif isinstance(v, th.Tensor) and v.dim() > 1: + # Map to list of tuples + out[k] = tuple(tuple(row.tolist()) for row in v) + elif isinstance(v, Iterable): + # bounding box modalities give a list of tuples + out[k] = tuple(v) + else: + # Preserve the key-value pair + out[k] = v + + return out + + +class GymObservable(metaclass=ABCMeta): + """ + Simple class interface for observable objects. These objects should implement a way to grab observations, + (get_obs()), and should define an observation space that is created when load_observation_space() is called + + Args: + **kwargs (dict): does nothing, used to sink any extraneous arguments during initialization + """ + + def __init__(self, *args, **kwargs): + # Initialize variables that we will fill in later + self.observation_space = None + + # Call any super methods + super().__init__(*args, **kwargs) + + @abstractmethod + def get_obs(self, **kwargs): + """ + Get observations for the object. Note that the shape / nested structure should match that + of @self.observation_space! + + Args: + kwargs (dict): Any keyword args necessary for grabbing observations + + Returns: + 2-tuple: + dict: Keyword-mapped observations mapping observation names to nested observations + dict: Additional information about the observations + """ + raise NotImplementedError() + + @staticmethod + def _build_obs_box_space(shape, low, high, dtype=th.float32): + """ + Helper function that builds individual observation box spaces. + + Args: + shape (n-array): Shape of the space + low (float): Lower bound of the space + high (float): Upper bound of the space + + Returns: + gym.spaces.Box: Generated gym box observation space + """ + return gym.spaces.Box(low=low, high=high, shape=shape, dtype=dtype) + + @abstractmethod + def _load_observation_space(self): + """ + Create the observation space for this object. Should be implemented by subclass + + Returns: + dict: Keyword-mapped observation space for this object mapping observation name to observation space + """ + raise NotImplementedError() + + def load_observation_space(self): + """ + Load the observation space internally, and also return this value + + Returns: + gym.spaces.Dict: Loaded observation space for this object + """ + # Load the observation space and convert it into a gym-compatible dictionary + self.observation_space = gym.spaces.Dict(self._load_observation_space()) + log.debug(f"Loaded obs space dictionary for: {self.__class__.__name__}") + + return self.observation_space + + +def maxdim(space): + """ + Helper function to get the maximum dimension of a gym space + + Args: + space (gym.spaces.Space): Gym space to get the maximum dimension of + + Returns: + int: Maximum dimension of the gym space + """ + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple)): + return sum([maxdim(s) for s in space.spaces.values()]) + elif isinstance(space, (gym.spaces.Box, gym.spaces.Discrete, gym.spaces.MultiDiscrete, gym.spaces.MultiBinary)): + return gym.spaces.utils.flatdim(space) + elif isinstance(space, (gym.spaces.Sequence, gym.spaces.Graph)): + return float("inf") + else: + raise ValueError(f"Unsupported gym space type: {type(space)}") diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/lazy_import_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/lazy_import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3d8a5621e795680f1917e270e78dcfb22a3b5c67 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/lazy_import_utils.py @@ -0,0 +1,46 @@ +import importlib +from types import ModuleType + + +class LazyImporter(ModuleType): + """Replace a module's global namespace with me to support lazy imports of submodules and members.""" + + def __init__(self, module_name, module): + super().__init__("lazy_" + module_name) + self._module_path = module_name + self._module = module + self._not_module = set() + self._submodules = {} + + def __getattr__(self, name: str): + # First, try the argument as a module name. + if name not in self._not_module: + submodule = self._get_module(name) + if submodule: + return submodule + else: + # Record module not found so that we don't keep looking. + self._not_module.add(name) + + # If it's not a module name, try it as a member of this module. + try: + return getattr(self._module, name) + except: + raise AttributeError(f"module {self.__name__} has no attribute {name}") from None + + def _get_module(self, module_name: str): + """Recursively create and return a LazyImporter for the given module name.""" + + # Get the fully qualified module name by prepending self._module_path + if self._module_path: + module_name = f"{self._module_path}.{module_name}" + + if module_name in self._submodules: + return self._submodules[module_name] + + try: + wrapper = LazyImporter(module_name, importlib.import_module(module_name)) + self._submodules[module_name] = wrapper + return wrapper + except ModuleNotFoundError: + return None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/motion_planning_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/motion_planning_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8061a0c0bad69c353c67abe4fc532f5f44806bda --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/motion_planning_utils.py @@ -0,0 +1,638 @@ +import heapq +import math + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.utils.control_utils import IKSolver +from omnigibson.utils.geometry_utils import wrap_angle +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.utils.constants import GROUND_CATEGORIES +from omnigibson.utils.usd_utils import RigidContactAPI + +# Create module logger +logger = create_module_logger(module_name=__name__) +m = create_module_macros(module_path=__file__) +m.ANGLE_DIFF = 0.3 +m.DIST_DIFF = 0.1 + + +def plan_base_motion( + robot, + end_conf, + context, + planning_time=15.0, +): + """ + Plans a base motion to a 2d pose + + Args: + robot (omnigibson.object_states.Robot): Robot object to plan for + end_conf (Iterable): [x, y, yaw] 2d pose to plan to + context (PlanningContext): Context to plan in that includes the robot copy + planning_time (float): Time to plan for + + Returns: + Array of arrays: Array of 2d poses that the robot should navigate to + """ + from ompl import base as ob + from ompl import geometric as ompl_geo + + class CustomMotionValidator(ob.MotionValidator): + def __init__(self, si, space): + super(CustomMotionValidator, self).__init__(si) + self.si = si + self.space = space + + def checkMotion(self, s1, s2): + if not self.si.isValid(s2): + return False + + start = th.tensor([s1.getX(), s1.getY(), s1.getYaw()]) + goal = th.tensor([s2.getX(), s2.getY(), s2.getYaw()]) + segment_theta = self.get_angle_between_poses(start, goal) + + # Start rotation + if not self.is_valid_rotation(self.si, start, segment_theta): + return False + + # Navigation + dist = th.norm(goal[:2] - start[:2]) + num_points = math.ceil(dist / m.DIST_DIFF) + 1 + nav_x = th.linspace(start[0], goal[0], num_points).tolist() + nav_y = th.linspace(start[1], goal[1], num_points).tolist() + for i in range(num_points): + state = create_state(self.si, nav_x[i], nav_y[i], segment_theta) + if not self.si.isValid(state()): + return False + + # Goal rotation + if not self.is_valid_rotation(self.si, [goal[0], goal[1], segment_theta], goal[2]): + return False + + return True + + @staticmethod + def is_valid_rotation(si, start_conf, final_orientation): + diff = wrap_angle(final_orientation - start_conf[2]) + direction = th.sign(diff) + diff = abs(diff) + num_points = math.ceil(diff / m.ANGLE_DIFF) + 1 + nav_angle = th.linspace(0.0, diff, num_points) * direction + angles = nav_angle + start_conf[2] + for i in range(num_points): + state = create_state(si.getStateSpace(), start_conf[0], start_conf[1], angles[i]) + if not si.isValid(state()): + return False + return True + + @staticmethod + # Get angle between 2d robot poses + def get_angle_between_poses(p1, p2): + segment = [] + segment.append(p2[0] - p1[0]) + segment.append(p2[1] - p1[1]) + segment = th.tensor(segment, dtype=th.float32) + return th.arctan2(segment[1], segment[0]) + + def create_state(space, x, y, yaw): + x = float(x) + y = float(y) + yaw = float(yaw) + state = ob.State(space) + state().setX(x) + state().setY(y) + state().setYaw(wrap_angle(yaw)) + return state + + def state_valid_fn(q, verbose=False): + """ + returns if the input pose is in collision with any objects within the context + verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False + """ + + x = q.getX() + y = q.getY() + yaw = q.getYaw() + pose = (th.tensor([x, y, 0.0], dtype=th.float32), T.euler2quat(th.tensor([0, 0, yaw], dtype=th.float32))) + return not set_base_and_detect_collision(context, pose, verbose=verbose) + + def remove_unnecessary_rotations(path): + """ + Removes unnecessary rotations from a path when possible for the base where the yaw for each pose in the path is in the direction of the + the position of the next pose in the path + + Args: + path (Array of arrays): Array of 2d poses + + Returns: + Array of numpy arrays: Array of 2d poses with unnecessary rotations removed + """ + # Start at the same starting pose + new_path = [path[0]] + + # Process every intermediate waypoint + for i in range(1, len(path) - 1): + # compute the yaw you'd be at when arriving into path[i] and departing from it + arriving_yaw = CustomMotionValidator.get_angle_between_poses(path[i - 1], path[i]) + departing_yaw = CustomMotionValidator.get_angle_between_poses(path[i], path[i + 1]) + + # check if you are able to make that rotation directly. + arriving_state = (path[i][0], path[i][1], arriving_yaw) + if CustomMotionValidator.is_valid_rotation(si, arriving_state, departing_yaw): + # Then use the arriving yaw directly + new_path.append(arriving_state) + else: + # Otherwise, keep the waypoint + new_path.append(path[i]) + + # Don't forget to add back the same ending pose + new_path.append(path[-1]) + + return new_path + + pos, orn = robot.get_position_orientation() + yaw = T.quat2euler(orn)[2] + start_conf = (pos[0], pos[1], yaw) + + # create an SE(2) state space + space = ob.SE2StateSpace() + + # set lower and upper bounds + bbox_vals = [] + for floor in filter(lambda o: o.category == "floors", robot.scene.objects): + bbox_vals += floor.aabb[0][:2].tolist() + bbox_vals += floor.aabb[1][:2].tolist() + bounds = ob.RealVectorBounds(2) + bounds.setLow(min(bbox_vals)) + bounds.setHigh(max(bbox_vals)) + space.setBounds(bounds) + + # create a simple setup object + ss = ompl_geo.SimpleSetup(space) + ss.setStateValidityChecker(ob.StateValidityCheckerFn(state_valid_fn)) + + si = ss.getSpaceInformation() + si.setMotionValidator(CustomMotionValidator(si, space)) + # TODO: Try changing to RRTConnect in the future. Currently using RRT because movement is not direction invariant. Can change to RRTConnect + # possibly if hasSymmetricInterpolate is set to False for the state space. Doc here https://ompl.kavrakilab.org/classompl_1_1base_1_1StateSpace.html + planner = ompl_geo.RRT(si) + ss.setPlanner(planner) + + start = create_state(space, start_conf[0], start_conf[1], start_conf[2]) + goal = create_state(space, end_conf[0], end_conf[1], end_conf[2]) + + ss.setStartAndGoalStates(start, goal) + if not state_valid_fn(start(), verbose=True) or not state_valid_fn(goal(), verbose=True): + return + + solved = ss.solve(planning_time) + + if solved: + # try to shorten the path + ss.simplifySolution() + sol_path = ss.getSolutionPath() + return_path = [] + for i in range(sol_path.getStateCount()): + x = sol_path.getState(i).getX() + y = sol_path.getState(i).getY() + yaw = sol_path.getState(i).getYaw() + return_path.append([x, y, yaw]) + return remove_unnecessary_rotations(return_path) + return None + + +def plan_arm_motion(robot, end_conf, context, planning_time=15.0, torso_fixed=True): + """ + Plans an arm motion to a final joint position + + Args: + robot (BaseRobot): Robot object to plan for + end_conf (Iterable): Final joint position to plan to + context (PlanningContext): Context to plan in that includes the robot copy + planning_time (float): Time to plan for + + Returns: + Array of arrays: Array of joint positions that the robot should navigate to + """ + from ompl import base as ob + from ompl import geometric as ompl_geo + + if torso_fixed: + joint_control_idx = robot.arm_control_idx[robot.default_arm] + dim = len(joint_control_idx) + initial_joint_pos = robot.get_joint_positions()[joint_control_idx] + control_idx_in_joint_pos = th.arange(dim) + else: + joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]]) + dim = len(joint_control_idx) + if "combined" in robot.robot_arm_descriptor_yamls: + joint_combined_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx["combined"]]) + initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_combined_idx]) + control_idx_in_joint_pos = th.where(th.isin(joint_combined_idx, joint_control_idx))[0] + else: + initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_control_idx]) + control_idx_in_joint_pos = th.arange(dim) + + def state_valid_fn(q, verbose=False): + joint_pos = initial_joint_pos + joint_pos[control_idx_in_joint_pos] = th.tensor([q[i] for i in range(dim)]) + return not set_arm_and_detect_collision(context, joint_pos, verbose=verbose) + + # create an SE2 state space + space = ob.RealVectorStateSpace(dim) + + # set lower and upper bounds + bounds = ob.RealVectorBounds(dim) + all_joints = list(robot.joints.values()) + arm_joints = [all_joints[i] for i in joint_control_idx.tolist()] + for i, joint in enumerate(arm_joints): + if end_conf[i] > joint.upper_limit: + end_conf[i] = joint.upper_limit + if end_conf[i] < joint.lower_limit: + end_conf[i] = joint.lower_limit + bounds.setLow(i, float(joint.lower_limit)) + bounds.setHigh(i, float(joint.upper_limit)) + space.setBounds(bounds) + + # create a simple setup object + ss = ompl_geo.SimpleSetup(space) + ss.setStateValidityChecker(ob.StateValidityCheckerFn(state_valid_fn)) + + si = ss.getSpaceInformation() + planner = ompl_geo.BITstar(si) + ss.setPlanner(planner) + + start_conf = robot.get_joint_positions()[joint_control_idx] + start = ob.State(space) + for i in range(dim): + start[i] = float(start_conf[i]) + + goal = ob.State(space) + for i in range(dim): + goal[i] = float(end_conf[i]) + ss.setStartAndGoalStates(start, goal) + + # if the start pose or the goal pose collides, abort + if not state_valid_fn(start, verbose=True) or not state_valid_fn(goal, verbose=True): + return + + # this will automatically choose a default planner with + # default parameters + solved = ss.solve(planning_time) + + if solved: + # try to shorten the path + ss.simplifySolution() + + sol_path = ss.getSolutionPath() + return_path = [] + for i in range(sol_path.getStateCount()): + joint_pos = th.tensor([sol_path.getState(i)[j] for j in range(dim)], dtype=th.float32) + return_path.append(joint_pos) + return return_path + return None + + +def plan_arm_motion_ik(robot, end_conf, context, planning_time=15.0, torso_fixed=True): + """ + Plans an arm motion to a final end effector pose + + Args: + robot (BaseRobot): Robot object to plan for + end_conf (Iterable): Final end effector pose to plan to + context (PlanningContext): Context to plan in that includes the robot copy + planning_time (float): Time to plan for + + Returns: + th.tensor or None: Tensors of end effector pose that the robot should navigate to, if available + """ + from ompl import base as ob + from ompl import geometric as ompl_geo + + DOF = 6 + + if torso_fixed: + joint_control_idx = robot.arm_control_idx[robot.default_arm] + dim = len(joint_control_idx) + initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_control_idx]) + control_idx_in_joint_pos = th.arange(dim) + robot_description_path = robot.robot_arm_descriptor_yamls["left_fixed"] + else: + joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]]) + dim = len(joint_control_idx) + if "combined" in robot.robot_arm_descriptor_yamls: + joint_combined_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx["combined"]]) + initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_combined_idx]) + control_idx_in_joint_pos = th.where(th.isin(joint_combined_idx, joint_control_idx))[0] + else: + initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_control_idx]) + control_idx_in_joint_pos = th.arange(dim) + robot_description_path = robot.robot_arm_descriptor_yamls[robot.default_arm] + + ik_solver = IKSolver( + robot_description_path=robot_description_path, + robot_urdf_path=robot.urdf_path, + reset_joint_pos=robot.reset_joint_pos[joint_control_idx], + eef_name=robot.eef_link_names[robot.default_arm], + ) + + def state_valid_fn(q, verbose=False): + joint_pos = initial_joint_pos + eef_pose = th.tensor([q[i] for i in range(6)], dtype=th.float32) + control_joint_pos = ik_solver.solve( + target_pos=eef_pose[:3], + target_quat=T.axisangle2quat(eef_pose[3:]), + max_iterations=1000, + ) + + if control_joint_pos is None: + return False + joint_pos[control_idx_in_joint_pos] = control_joint_pos + return not set_arm_and_detect_collision(context, joint_pos, verbose=verbose) + + # create an SE2 state space + space = ob.RealVectorStateSpace(DOF) + + # set lower and upper bounds for eef position + bounds = ob.RealVectorBounds(DOF) + + EEF_X_LIM = [-0.8, 0.8] + EEF_Y_LIM = [-0.8, 0.8] + EEF_Z_LIM = [-2.0, 2.0] + bounds.setLow(0, EEF_X_LIM[0]) + bounds.setHigh(0, EEF_X_LIM[1]) + bounds.setLow(1, EEF_Y_LIM[0]) + bounds.setHigh(1, EEF_Y_LIM[1]) + bounds.setLow(2, EEF_Z_LIM[0]) + bounds.setHigh(2, EEF_Z_LIM[1]) + + # # set lower and upper bounds for eef orientation (axis angle bounds) + for i in range(3, 6): + bounds.setLow(i, -math.pi) + bounds.setHigh(i, math.pi) + space.setBounds(bounds) + + # create a simple setup object + ss = ompl_geo.SimpleSetup(space) + ss.setStateValidityChecker(ob.StateValidityCheckerFn(state_valid_fn)) + + si = ss.getSpaceInformation() + planner = ompl_geo.BITstar(si) + ss.setPlanner(planner) + + start_conf = th.cat((robot.get_relative_eef_position(), T.quat2axisangle(robot.get_relative_eef_orientation()))) + # do fk + start = ob.State(space) + for i in range(DOF): + start[i] = float(start_conf[i]) + + goal = ob.State(space) + for i in range(DOF): + goal[i] = float(end_conf[i]) + ss.setStartAndGoalStates(start, goal) + + if not state_valid_fn(start, verbose=True) or not state_valid_fn(goal, verbose=True): + return + + # this will automatically choose a default planner with + # default parameters + solved = ss.solve(planning_time) + + if solved: + # try to shorten the path + ss.simplifySolution() + + sol_path = ss.getSolutionPath() + return_path = [] + for i in range(sol_path.getStateCount()): + eef_pose = th.tensor([sol_path.getState(i)[j] for j in range(DOF)], dtype=th.float32) + return_path.append(eef_pose) + return return_path + return None + + +def set_base_and_detect_collision(context, pose, verbose=False): + """ + Moves the robot and detects robot collisions with the environment and itself + + Args: + context (PlanningContext): Context to plan in that includes the robot copy + pose (Array): Pose in the world frame to check for collisions at + verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False + + Returns: + bool: Whether the robot is in collision + """ + # make a copy of the robot, set it to the goal pose, and check for possible collision + robot_copy = context.robot_copy + robot_copy_type = context.robot_copy_type + + translation = lazy.pxr.Gf.Vec3d(pose[0].tolist()) + robot_copy.prims[robot_copy_type].GetAttribute("xformOp:translate").Set(translation) + + orientation = pose[1][[3, 0, 1, 2]] + robot_copy.prims[robot_copy_type].GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*orientation.tolist())) + return detect_robot_collision(context, verbose=verbose) + + +def set_arm_and_detect_collision(context, joint_pos, verbose=False): + """ + Sets joint positions of the robot and detects robot collisions with the environment and itself + + Args: + context (PlanningContext): Context to plan in that includes the robot copy + joint_pos (Array): Joint positions to set the robot to + verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False + + Returns: + bool: Whether the robot is in a valid state i.e. not in collision + """ + robot_copy = context.robot_copy + robot_copy_type = context.robot_copy_type + + arm_links = context.robot.manipulation_link_names + link_poses = context.fk_solver.get_link_poses(joint_pos, arm_links) + + for link in arm_links: + pose = link_poses[link] + if link in robot_copy.meshes[robot_copy_type].keys(): + for mesh_name, mesh in robot_copy.meshes[robot_copy_type][link].items(): + relative_pose = robot_copy.relative_poses[robot_copy_type][link][mesh_name] + mesh_pose = T.pose_transform(*pose, *relative_pose) + translation = lazy.pxr.Gf.Vec3d(*mesh_pose[0].tolist()) + mesh.GetAttribute("xformOp:translate").Set(translation) + orientation = mesh_pose[1][[3, 0, 1, 2]] + mesh.GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*orientation.tolist())) + + return detect_robot_collision(context, verbose=verbose) + + +def detect_robot_collision(context, verbose=False): + """ + Detects robot collisions + + Args: + context (PlanningContext): Context to plan in that includes the robot copy + verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False + + Returns: + valid_hit(bool): Whether the robot is in collision + """ + robot_copy = context.robot_copy + robot_copy_type = context.robot_copy_type + + # Define function for checking overlap + valid_hit = False + mesh_path = None + + def overlap_callback(hit): + nonlocal valid_hit + + valid_hit = hit.rigid_body not in context.disabled_collision_pairs_dict[mesh_path] + + # if verbose mode is on and overlap is detected, output a warning on the colliding object and robot mesh_path + if valid_hit and verbose: + logger.warning( + f"Could not make a plan to get to the target position, colliding objects: {hit.rigid_body} and {mesh_path}", + ) + + return not valid_hit + + for meshes in robot_copy.meshes[robot_copy_type].values(): + for mesh in meshes.values(): + if valid_hit: + return valid_hit + mesh_path = mesh.GetPrimPath().pathString + mesh_id = lazy.pxr.PhysicsSchemaTools.encodeSdfPath(mesh_path) + if mesh.GetTypeName() == "Mesh": + og.sim.psqi.overlap_mesh(*mesh_id, reportFn=overlap_callback) + else: + og.sim.psqi.overlap_shape(*mesh_id, reportFn=overlap_callback) + + return valid_hit + + +def detect_robot_collision_in_sim(robot, filter_objs=None, ignore_obj_in_hand=True): + """ + Detects robot collisions with the environment, but not with itself using the RigidContactAPI cache. + + Args: + robot (BaseRobot): Robot object to detect collisions for + filter_objs (list of DatasetObject or None): Objects to ignore collisions with + ignore_obj_in_hand (bool): Whether to ignore collisions with the object in the robot's hand + + Returns: + bool: Whether the robot is in collision + """ + if filter_objs is None: + filter_objs = [] + + if ignore_obj_in_hand: + for arm in robot.arm_names: + if robot.grasping_mode in ["sticky", "assisted"]: + if robot._ag_obj_in_hand[arm] is not None: + filter_objs.append(robot._ag_obj_in_hand[arm]) + elif robot.grasping_mode == "physical": + filter_objs.extend(robot._find_gripper_raycast_collisions(arm=arm)) + else: + raise ValueError(f"Unknown grasping mode: {robot.grasping_mode}") + + for category in GROUND_CATEGORIES: + filter_objs.extend(robot.scene.object_registry("category", category, [])) + + # Always exclude robot self-collisions (internal link-to-link contacts) + if robot not in filter_objs: + filter_objs.append(robot) + + return RigidContactAPI.is_in_contact( + scene_idx=robot.scene.idx, query_set=[robot], with_set=None, ignore_set=filter_objs, current_only=False + ) + + +def astar(search_map, start, goal, eight_connected=True): + """ + A* search algorithm for finding a path from start to goal on a grid map + + Args: + search_map (Array): 2D Grid map to search on + start (Array): Start position on the map + goal (Array): Goal position on the map + eight_connected (bool): Whether we consider the sides and diagonals of a cell as neighbors or just the sides + + Returns: + 2D numpy array or None: Array of shape (N, 2) where N is the number of steps in the path. + Each row represents the (x, y) coordinates of a step on the path. + If no path is found, returns None. + """ + + def heuristic(node): + # Calculate the Euclidean distance from node to goal + return math.sqrt((node[0] - goal[0]) ** 2 + (node[1] - goal[1]) ** 2) + + def get_neighbors(cell): + if eight_connected: + # 8-connected grid + return [ + (cell[0] + 1, cell[1]), + (cell[0] - 1, cell[1]), + (cell[0], cell[1] + 1), + (cell[0], cell[1] - 1), + (cell[0] + 1, cell[1] + 1), + (cell[0] - 1, cell[1] - 1), + (cell[0] + 1, cell[1] - 1), + (cell[0] - 1, cell[1] + 1), + ] + else: + # 4-connected grid + return [(cell[0] + 1, cell[1]), (cell[0] - 1, cell[1]), (cell[0], cell[1] + 1), (cell[0], cell[1] - 1)] + + def is_valid(cell): + # Check if cell is within the map and traversable + return 0 <= cell[0] < search_map.shape[0] and 0 <= cell[1] < search_map.shape[1] and search_map[cell] != 0 + + def cost(cell1, cell2): + # Define the cost of moving from cell1 to cell2 + # Return 1 for adjacent cells and square root of 2 for diagonal cells in an 8-connected grid. + if cell1[0] == cell2[0] or cell1[1] == cell2[1]: + return 1 + else: + return math.sqrt(2) + + open_set = [(0, start)] + came_from = {} + visited = set() + rows, cols = search_map.shape + g_score = {(i.item(), j.item()): float("inf") for i, j in th.cartesian_prod(th.arange(rows), th.arange(cols))} + g_score[start] = 0 + + while open_set: + _, current = heapq.heappop(open_set) + + visited.add(current) + + if current == goal: + # Reconstruct path + path = [] + while current in came_from: + path.insert(0, current) + current = came_from[current] + path.insert(0, start) + return th.tensor(path) + + for neighbor in get_neighbors(current): + # Skip neighbors that are not valid or have already been visited + if not is_valid(neighbor) or neighbor in visited: + continue + tentative_g_score = g_score[current] + cost(current, neighbor) + if tentative_g_score < g_score[neighbor]: + came_from[neighbor] = current + g_score[neighbor] = tentative_g_score + f_score = tentative_g_score + heuristic(neighbor) + heapq.heappush(open_set, (f_score, neighbor)) + + # Return None if no path is found + return None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/numpy_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/numpy_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f91824c6a5617ca98f8f10c35cfa5a5f911588 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/numpy_utils.py @@ -0,0 +1,37 @@ +import numpy as np +import torch as th +import omnigibson.lazy as lazy + + +class NumpyTypes: + FLOAT32 = np.float32 + INT32 = np.int32 + INT64 = np.int64 + UINT8 = np.uint8 + UINT32 = np.uint32 + + +def numpy_to_torch(np_array, dtype=th.float32, device="cpu"): + if device == "cpu": + return th.from_numpy(np_array).to(dtype) + else: + assert device.startswith("cuda") + return th.tensor(np_array, dtype=dtype, device=device) + + +def vtarray_to_torch(vtarray, dtype=th.float32, device="cpu"): + np_array = np.array(vtarray) + return numpy_to_torch(np_array, dtype=dtype, device=device) + + +def gf_quat_to_torch(gf_quat, dtype=th.float32, device="cpu"): + np_array = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array(gf_quat)[[1, 2, 3, 0]] + return numpy_to_torch(np_array, dtype=dtype, device=device) + + +def pil_to_tensor(pil_image): + return th.tensor(np.array(pil_image), dtype=th.uint8) + + +def list_to_np_array(list): + return np.array(list) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_state_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_state_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b29d3b293111ae037174e6a185cf0025099678f4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_state_utils.py @@ -0,0 +1,464 @@ +import cv2 +import math +import numpy as np +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import Dict, create_module_macros, macros +from omnigibson.utils import sampling_utils +from omnigibson.utils.constants import GROUND_CATEGORIES, PrimType +from omnigibson.utils.ui_utils import debug_breakpoint, create_module_logger +from omnigibson.utils.constants import JointType +from omnigibson.utils.usd_utils import RigidContactAPI + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +log = create_module_logger(module_name=__name__) + +m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS = 10 +m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS = 10 +m.ARM_LENGTH_XY = 0.8 +m.EEF_Z_MAX = 1.7 +m.EEF_Z_MIN = 0.3 +m.ON_TOP_RAY_CASTING_SAMPLING_PARAMS = Dict( + { + "bimodal_stdev_fraction": 1e-6, + "bimodal_mean_fraction": 1.0, + "aabb_offset_fraction": 0.02, + "max_sampling_attempts": 50, + } +) + +m.INSIDE_RAY_CASTING_SAMPLING_PARAMS = Dict( + { + "bimodal_stdev_fraction": 0.4, + "bimodal_mean_fraction": 0.5, + "aabb_offset_fraction": -0.02, + "max_sampling_attempts": 100, + } +) + +m.UNDER_RAY_CASTING_SAMPLING_PARAMS = Dict( + { + "bimodal_stdev_fraction": 1e-6, + "bimodal_mean_fraction": 0.5, + "aabb_offset_fraction": 0.02, + "max_sampling_attempts": 50, + } +) + + +def sample_cuboid_for_predicate(predicate, on_obj, bbox_extent): + if predicate == "onTop": + params = m.ON_TOP_RAY_CASTING_SAMPLING_PARAMS + elif predicate == "inside": + params = m.INSIDE_RAY_CASTING_SAMPLING_PARAMS + elif predicate == "under": + params = m.UNDER_RAY_CASTING_SAMPLING_PARAMS + else: + raise ValueError( + f"predicate must be onTop, under or inside in order to use ray casting-based " + f"kinematic sampling, but instead got: {predicate}" + ) + + if predicate == "under": + start_points, end_points = sampling_utils.sample_raytest_start_end_symmetric_bimodal_distribution( + obj=on_obj, + num_samples=1, + axis_probabilities=[0, 0, 1], + **params, + ) + return sampling_utils.sample_cuboid_on_object( + obj=None, + start_points=start_points, + end_points=end_points, + ignore_objs=[on_obj], + cuboid_dimensions=bbox_extent, + refuse_downwards=True, + undo_cuboid_bottom_padding=True, + max_angle_with_z_axis=0.17, + hit_proportion=0.0, # rays will NOT hit the object itself, but the surface below it. + ) + else: + return sampling_utils.sample_cuboid_on_object_symmetric_bimodal_distribution( + on_obj, + num_samples=1, + axis_probabilities=[0, 0, 1], + cuboid_dimensions=bbox_extent, + refuse_downwards=True, + undo_cuboid_bottom_padding=True, + max_angle_with_z_axis=0.17, + **params, + ) + + +def get_reachability_sampling_context(objB, predicate, use_trav_map=True, warn_on_scene_mismatch=False): + """ + Builds cached traversability / reachability data used for kinematic sampling checks. + + Args: + objB (StatefulObject): Reference object used for sampling. + predicate (str): Predicate being sampled, e.g. "inside", "onTop", "under". + use_trav_map (bool): Whether to enable traversability-based reachability checks. + warn_on_scene_mismatch (bool): Whether to log a warning if objB.scene is not traversable. + + Returns: + dict or None: Context dict if traversability checks are enabled, else None. + """ + if not use_trav_map: + return None + + from omnigibson.scenes.traversable_scene import TraversableScene + + if not isinstance(objB.scene, TraversableScene): + if warn_on_scene_mismatch: + log.warning( + f"Using trav_map=True requires objB.scene to be a TraversableScene, but got {type(objB.scene)} instead." + ) + return None + + trav_map = objB.scene.trav_map + trav_map_floor_map = trav_map.floor_map[0] + arm_length_pixel = int(math.ceil(m.ARM_LENGTH_XY / trav_map.map_resolution)) + + robot = objB.scene.robots[0] if len(objB.scene.robots) > 0 else None + eroded_trav_map = trav_map._erode_trav_map(trav_map_floor_map, robot=robot) + + # The eroded map pulls robot standing positions back by erosion_radius from obstacles. + # Dilating by arm_length alone would give net reach of (arm_length - erosion_radius) from + # obstacles, which is too small. Adding erosion_radius back restores the correct effective reach. + if robot is not None: + erosion_radius = th.norm(robot.reset_joint_pos_aabb_extent[:2]).item() / 2.0 + 0.2 + else: + erosion_radius = trav_map.default_erosion_radius + erosion_radius_pixel = int(math.ceil(erosion_radius / trav_map.map_resolution)) + reach_pixel = arm_length_pixel + erosion_radius_pixel + + reachability_map = th.tensor(cv2.dilate(eroded_trav_map.cpu().numpy(), np.ones((reach_pixel, reach_pixel)))) + has_prismatic_joint = any(j.joint_type == JointType.JOINT_PRISMATIC for j in objB.joints.values()) + + return { + "trav_map": trav_map, + "reachability_map": reachability_map, + "has_prismatic_joint": has_prismatic_joint, + "eroded_trav_map": eroded_trav_map, + } + + +def is_pose_reachable_for_predicate(pos, objB, predicate, reachability_context): + """ + Checks whether sampled pose @pos satisfies robot-reachability constraints. + + Args: + pos (Array[float]): Candidate world-frame position (x, y, z). + objB (StatefulObject): Reference object used for sampling. + predicate (str): Predicate being sampled, e.g. "inside", "onTop", "under". + reachability_context (dict or None): Context returned by get_reachability_sampling_context. + + Returns: + bool: True if sampled pose passes reachability checks. + """ + if reachability_context is None: + return True + + trav_map = reachability_context["trav_map"] + reachability_map = reachability_context["reachability_map"] + has_prismatic_joint = reachability_context["has_prismatic_joint"] + eroded_trav_map = reachability_context["eroded_trav_map"] + + xy_map = trav_map.world_to_map(pos[:2]) + map_x, map_y = int(xy_map[0]), int(xy_map[1]) + if pos[2] > m.EEF_Z_MAX: + # Sampled position is above the maximum z of the arm + return False + if pos[2] < m.EEF_Z_MIN and predicate == "inside" and objB.fixed_base: + # Sampling inside fixed-base object, position is below the minimum z of the arm + return False + if predicate == "onTop" and objB.category in GROUND_CATEGORIES: + # Sampling onTop of ground category, sampled position should be traversable + map_h, map_w = eroded_trav_map.shape + if map_x < 0 or map_x >= map_h or map_y < 0 or map_y >= map_w: + return False + return eroded_trav_map[map_x, map_y] == 255 + if not has_prismatic_joint: + # Sampling around object with no prismatic joints, sampled position should be reachable + map_h, map_w = reachability_map.shape + if map_x < 0 or map_x >= map_h or map_y < 0 or map_y >= map_w: + return False + return reachability_map[map_x, map_y] == 255 + + return True + + +def sample_kinematics( + predicate, + objA, + objB, + max_trials=None, + z_offset=0.05, + skip_falling=False, + use_last_ditch_effort=False, + use_trav_map=True, + reachability_context=None, +): + """ + Samples the given @predicate kinematic state for @objA with respect to @objB + + Args: + predicate (str): Name of the predicate to sample, e.g.: "onTop" + objA (StatefulObject): Object whose state should be sampled. e.g.: for sampling a microwave + on a cabinet, @objA is the microwave + objB (StatefulObject): Object who is the reference point for @objA's state. e.g.: for sampling + a microwave on a cabinet, @objB is the cabinet + max_trials (int): Number of attempts for sampling + z_offset (float): Z-offset to apply to the sampled pose + skip_falling (bool): Whether to let @objA fall after its position is sampled or not + use_last_ditch_effort (bool): Whether to use last-ditch effort to sample the kinematics if the first + sampling attempt fails. This will place @objA at the center of @objB's AABB, offset in z direction such + use_trav_map (bool): Whether to use the traversability map of the scene to check if the sampled position is traversable. + reachability_context (dict or None): Pre-computed context from get_reachability_sampling_context. If provided, + skips recomputing it (avoids repeated cv2.erode calls when sample_kinematics is called in a loop). + + Returns: + bool: True if successfully sampled, else False + """ + if reachability_context is None: + reachability_context = get_reachability_sampling_context( + objB=objB, + predicate=predicate, + use_trav_map=use_trav_map, + warn_on_scene_mismatch=True, + ) + use_trav_map = reachability_context is not None + if max_trials is None: + max_trials = m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS + assert ( + z_offset > 0.5 * 9.81 * (og.sim.get_physics_dt() ** 2) + 0.02 + ), f"z_offset {z_offset} is too small for the current physics_dt {og.sim.get_physics_dt()}" + + # Wake objects accordingly and make sure both are kept still + objA.wake() + objB.wake() + + objA.keep_still() + objB.keep_still() + + # Save the state of the simulator + state = og.sim.dump_state() + + # Attempt sampling + def _is_in_contact(): + if objA.prim_type == PrimType.RIGID: + return RigidContactAPI.is_in_contact( + scene_idx=objA.scene.idx, query_set=[objA], with_set=None, ignore_set=None, current_only=False + ) + else: + return len(objA.root_link.get_contacts()) > 0 + + for i in range(max_trials): + pos = None + if hasattr(objA, "orientations") and objA.orientations is not None: + orientation = objA.sample_orientation() + else: + orientation = th.tensor([0, 0, 0, 1.0]) + + # Orientation needs to be set for stable_z_on_aabb to work correctly + # Position needs to be set to be very far away because the object's + # original position might be blocking rays (use_ray_casting_method=True) + old_pos = th.tensor([100, 100, 10]) + objA.set_position_orientation(position=old_pos, orientation=orientation) + objA.keep_still() + # We also need to step physics to make sure the pose propagates downstream (e.g.: to Bounding Box computations) + og.sim.step_physics() + + # This would slightly change because of the step_physics call. + old_pos, orientation = objA.get_position_orientation() + + # Run import here to avoid circular imports + from omnigibson.objects.dataset_object import DatasetObject + + if isinstance(objA, DatasetObject) and objA.prim_type == PrimType.RIGID: + # Retrieve base CoM frame-aligned bounding box parallel to the XY plane + parallel_bbox_center, parallel_bbox_orn, parallel_bbox_extents, _ = objA.get_base_aligned_bbox( + xy_aligned=True + ) + else: + aabb_lower, aabb_upper = objA.aabb + parallel_bbox_center = (aabb_lower + aabb_upper) / 2.0 + parallel_bbox_orn = th.tensor([0.0, 0.0, 0.0, 1.0]) + parallel_bbox_extents = aabb_upper - aabb_lower + + sampling_results = sample_cuboid_for_predicate(predicate, objB, parallel_bbox_extents) + sampled_vector = sampling_results[0][0] + sampled_quaternion = sampling_results[0][2] + + sampling_success = sampled_vector is not None + + if sampling_success: + # Move the object from the original parallel bbox to the sampled bbox + # The additional orientation to be applied should be the delta orientation + # between the parallel bbox orientation and the sample orientation + additional_quat = T.quat_multiply(sampled_quaternion, T.quat_inverse(parallel_bbox_orn)) + combined_quat = T.quat_multiply(additional_quat, orientation) + orientation = combined_quat + + # The delta vector between the base CoM frame and the parallel bbox center needs to be rotated + # by the same additional orientation + diff = old_pos - parallel_bbox_center + rotated_diff = T.quat_apply(additional_quat, diff) + pos = sampled_vector + rotated_diff + + from omnigibson.robots.robot import Robot + + if use_trav_map and not isinstance(objA, Robot): + if not is_pose_reachable_for_predicate( + pos=pos, + objB=objB, + predicate=predicate, + reachability_context=reachability_context, + ): + pos = None + success = False + if pos is None: + success = False + else: + pos[2] += z_offset + objA.set_position_orientation(position=pos, orientation=orientation) + objA.keep_still() + + og.sim.step_physics() + objA.keep_still() + success = not _is_in_contact() + + if macros.utils.sampling_utils.DEBUG_SAMPLING: + debug_breakpoint(f"sample_kinematics: {success}") + + if success: + break + else: + og.sim.load_state(state) + + # If we didn't succeed, optionally try last-ditch effort + if not success and use_last_ditch_effort and predicate in {"onTop", "inside"}: + # Do not use last-ditch effort for onTop ground categories because it will + # break the traversability constraint (see above) + if predicate == "onTop" and objB.category in GROUND_CATEGORIES: + pass + else: + og.sim.step_physics() + # Place objA at center of objB's AABB, offset in z direction such that their AABBs are "stacked", and let fall + # until it settles + aabb_lower_a, aabb_upper_a = objA.aabb + aabb_lower_b, aabb_upper_b = objB.aabb + bbox_to_obj = objA.get_position_orientation()[0] - (aabb_lower_a + aabb_upper_a) / 2.0 + desired_bbox_pos = (aabb_lower_b + aabb_upper_b) / 2.0 + desired_bbox_pos[2] = aabb_upper_b[2] + (aabb_upper_a[2] - aabb_lower_a[2]) / 2.0 + pos = desired_bbox_pos + bbox_to_obj + success = True + + if success and not skip_falling: + objA.set_position_orientation(position=pos, orientation=orientation) + objA.keep_still() + + # Step until either (a) max steps is reached (total of 0.5 second in sim time) or (b) contact is made, then + # step until (a) max steps is reached (restarted from 0) or (b) velocity is below some threshold + n_steps_max = int(0.5 / og.sim.get_physics_dt()) + i = 0 + + while not _is_in_contact() and i < n_steps_max: + og.sim.step_physics() + i += 1 + objA.keep_still() + objB.keep_still() + # Step a few times so velocity can become non-zero if the objects are moving + for i in range(5): + og.sim.step_physics() + i = 0 + while th.norm(objA.get_linear_velocity()) > 1e-3 and i < n_steps_max: + og.sim.step_physics() + i += 1 + + return success + + +def sample_cloth_on_rigid(obj, other, max_trials=40, z_offset=0.05, randomize_xy=True): + """ + Samples the cloth object @obj on the rigid object @other + + Args: + obj (StatefulObject): Object whose state should be sampled. e.g.: for sampling a bed sheet on a rack, + @obj is the bed sheet + other (StatefulObject): Object who is the reference point for @obj's state. e.g.: for sampling a bed sheet + on a rack, @other is the rack + max_trials (int): Number of attempts for sampling + z_offset (float): Z-offset to apply to the sampled pose + randomize_xy (bool): Whether to randomize the XY position of the sampled pose. If False, the center of @other + will always be used. + + Returns: + bool: True if successfully sampled, else False + """ + assert ( + z_offset > 0.5 * 9.81 * (og.sim.get_physics_dt() ** 2) + 0.02 + ), f"z_offset {z_offset} is too small for the current physics_dt {og.sim.get_physics_dt()}" + + if not (obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): + raise ValueError("sample_cloth_on_rigid requires obj1 is cloth and obj2 is rigid.") + + state = og.sim.dump_state(serialized=False) + + # Reset the cloth to the settled configuration if available + if "settled" in obj.root_link.get_available_configurations(): + obj.root_link.reset_points_to_configuration("settled") + else: + obj.root_link.reset() + + obj_aabb_low, obj_aabb_high = obj.aabb + other_aabb_low, other_aabb_high = other.aabb + + # z value is always the same: the top-z of the other object + half the height of the object to be placed + offset + z_value = other_aabb_high[2] + (obj_aabb_high[2] - obj_aabb_low[2]) / 2.0 + z_offset + + if randomize_xy: + # Sample a random position in the x-y plane within the other object's AABB + low = th.tensor([other_aabb_low[0], other_aabb_low[1], z_value]) + high = th.tensor([other_aabb_high[0], other_aabb_high[1], z_value]) + else: + # Always sample the center of the other object's AABB + low = th.tensor( + [(other_aabb_low[0] + other_aabb_high[0]) / 2.0, (other_aabb_low[1] + other_aabb_high[1]) / 2.0, z_value] + ) + high = low + + for _ in range(max_trials): + # Sample a random position + pos = th.rand(low.size()) * (high - low) + low + # Sample a random orientation in the z-axis + z_lo, z_hi = 0, math.pi * 2 + orn = T.euler2quat(th.tensor([0.0, 0.0, (th.rand(1) * (z_hi - z_lo) + z_lo).item()])) + + obj.set_position_orientation(position=pos, orientation=orn) + obj.root_link.reset() + obj.keep_still() + + og.sim.step_physics() + success = len(obj.root_link.get_contacts()) == 0 + + if success: + break + else: + og.sim.load_state(state) + + if success: + # Let it fall for 0.2 second always to let the cloth settle + for _ in range(int(0.2 / og.sim.get_physics_dt())): + og.sim.step_physics() + + obj.keep_still() + + # Render at the end + og.sim.render() + + return success diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..340cd9a4cc54bec81578075f3cc3e287dee4ab49 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_utils.py @@ -0,0 +1,131 @@ +""" +Helper utility functions for computing relevant object information +""" + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.scenes import Scene +from omnigibson.utils.geometry_utils import get_particle_positions_from_frame + + +def sample_stable_orientations(obj, n_samples=10, drop_aabb_offset=0.1): + """ + Samples random stable orientations for obj @obj by stochastically dropping the object and recording its + resulting orientations + + Args: + obj (USDObject): Object whose orientations will be sampled + n_samples (int): How many sampled orientations will be recorded + drop_aabb_offset (float): Offset to apply in the z-direction when dropping the object + + Returns: + n-array: (N, 4) array, where each of the N rows are sampled (x,y,z,w) stable orientations + """ + og.sim.play() + assert th.all(obj.scale == 1.0) + aabb_extent = obj.aabb_extent + radius = th.norm(aabb_extent) / 2.0 + drop_pos = th.tensor([0, 0, radius + drop_aabb_offset]) + center_offset = obj.get_position_orientation()[0] - obj.aabb_center + drop_orientations = T.random_quaternion(n_samples) + stable_orientations = th.zeros_like(drop_orientations) + for i, drop_orientation in enumerate(drop_orientations): + # Sample orientation, drop, wait to stabilize, then record + pos = drop_pos + T.quat2mat(drop_orientation) @ center_offset + obj.set_position_orientation(position=pos, orientation=drop_orientation) + obj.keep_still() + for j in range(25): + og.sim.step() + stable_orientations[i] = obj.get_position_orientation()[1] + + return stable_orientations + + +def compute_bbox_offset(obj): + """ + Computes the base link offset of @obj, specifying the relative position of the object's bounding box center wrt to + its root link frame, expressed in the world frame + + Args: + obj (USDObject): Object whose bbox offset will be computed + + Returns: + n-array: (x,y,z) offset specifying the relative position from the root link to @obj's bounding box center + """ + og.sim.stop() + assert th.all(obj.scale == 1.0) + obj.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0])) + return obj.aabb_center - obj.get_position_orientation()[0] + + +def compute_native_bbox_extent(obj): + """ + Computes the native bounding box extent for @obj, which is the extent with the obj placed at (0, 0, 0) with + orientation (0, 0, 0, 1) and scale (1, 1, 1) + + Args: + obj (USDObject): Object whose native bbox extent will be computed + + Returns: + n-array: (x,y,z) native bounding box extent + """ + og.sim.stop() + assert th.all(obj.scale == 1.0) + obj.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0])) + return obj.aabb_extent + + +def compute_base_aligned_bboxes(obj): + link_bounding_boxes = {} + for link_name, link in obj.links.items(): + link_bounding_boxes[link_name] = {} + for mesh_type, mesh_list in zip(("collision", "visual"), (link.collision_meshes, link.visual_meshes)): + pts_in_link_frame = [] + for mesh_name, mesh in mesh_list.items(): + pts = mesh.get_attribute("points") + local_pos, local_orn = mesh.get_position_orientation(frame="parent") + pts_in_link_frame.append(get_particle_positions_from_frame(local_pos, local_orn, mesh.scale, pts)) + pts_in_link_frame = th.cat(pts_in_link_frame, dim=0) + max_pt = th.max(pts_in_link_frame, dim=0).values + min_pt = th.min(pts_in_link_frame, dim=0).values + extent = max_pt - min_pt + center = (max_pt + min_pt) / 2.0 + transform = T.pose2mat((center, th.tensor([0, 0, 0, 1.0]))) + print(pts_in_link_frame.shape) + link_bounding_boxes[link_name][mesh_type] = { + "extent": extent, + "transform": transform, + } + return link_bounding_boxes + + +def compute_obj_kinematic_metadata(obj): + """ + Computes relevant kinematic metadata for @obj, such as stable_orientations, bounding box offsets, + bounding box extents, and base_aligned_bboxes + + Args: + obj (USDObject): Object whose metadata will be computed + + Returns: + dict: Relevant metadata, with the following keys: + + - "stable_orientations": 2D (N, 4)-array of sampled stable (x,y,z,w) quaternion orientations + - "bbox_offset": (x,y,z) relative position from the root link to @obj's bounding box center + - "native_bbox_extent": (x,y,z) native bounding box extent + - "base_aligned_bboxes": TODO + """ + assert obj.scene is not None + assert og.sim.floor_plane is not None + assert type(obj.scene) is Scene, "An empty scene must be used in order to compute kinematic metadata!" + assert th.all(obj.scale == 1.0), "Object must have scale [1, 1, 1] in order to compute kinematic metadata!" + og.sim.stop() + + return { + "stable_orientations": sample_stable_orientations(obj=obj), + "bbox_offset": compute_bbox_offset(obj=obj), + "native_bbox_extent": compute_native_bbox_extent(obj=obj), + "base_aligned_bboxes": compute_base_aligned_bboxes(obj=obj), + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/physx_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/physx_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5822b805f77b7b532fb04f83e85e712cc1a3dc26 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/physx_utils.py @@ -0,0 +1,284 @@ +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.macros import create_module_macros +from omnigibson.utils.ui_utils import suppress_omni_log +from omnigibson.utils.usd_utils import ensure_usd_api + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.PROTOTYPE_GRAVEYARD_POS = (100.0, 100.0, 100.0) + + +def create_physx_particle_system( + prim_path, + physics_scene_path, + particle_contact_offset, + visual_only=False, + smoothing=True, + anisotropy=True, + isosurface=True, +): + """ + Creates an Omniverse physx particle system at @prim_path. For post-processing visualization effects (anisotropy, + smoothing, isosurface), see the Omniverse documentation + (https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics.html?highlight=isosurface#post-processing-for-fluid-rendering) + for more info + + Args: + prim_path (str): Stage path to where particle system should be created + physics_scene_path (str): Stage path to where active physicsScene prim is defined + particle_contact_offset (float): Distance between particles which triggers a collision (m) + visual_only (bool): If True, will disable collisions between particles and non-particles, + as well as self-collisions + smoothing (bool): Whether to smooth particle positions or not + anisotropy (bool): Whether to apply anisotropy post-processing when visualizing particles. Stretches generated + particles in order to make the particle cluster surface appear smoother. Useful for fluids + isosurface (bool): Whether to apply isosurface mesh to visualize particles. Uses a monolithic surface that + can have materials attached to it, useful for visualizing fluids + + Returns: + UsdGeom.PhysxParticleSystem: Generated particle system prim + """ + with og.sim.editing_usd(): + # TODO: Add sanity check to make sure GPU dynamics are enabled + # Create particle system + stage = lazy.isaacsim.core.utils.stage.get_current_stage() + particle_system = lazy.pxr.PhysxSchema.PhysxParticleSystem.Define(stage, prim_path) + particle_system.CreateSimulationOwnerRel().SetTargets([physics_scene_path]) + + # Use a smaller particle size for nicer fluid, and let the sim figure out the other offsets + particle_system.CreateParticleContactOffsetAttr().Set(particle_contact_offset) + + # Possibly disable collisions if we're only visual + if visual_only: + particle_system.GetGlobalSelfCollisionEnabledAttr().Set(False) + particle_system.GetNonParticleCollisionEnabledAttr().Set(False) + + if anisotropy: + # apply api and use all defaults + ani_api = ensure_usd_api(particle_system.GetPrim(), lazy.pxr.PhysxSchema.PhysxParticleAnisotropyAPI) + + if smoothing: + # apply api and use all defaults + ensure_usd_api(particle_system.GetPrim(), lazy.pxr.PhysxSchema.PhysxParticleSmoothingAPI) + + if isosurface: + # apply api and use all defaults + ensure_usd_api(particle_system.GetPrim(), lazy.pxr.PhysxSchema.PhysxParticleIsosurfaceAPI) + + with og.sim.editing_usd(): + # Make sure we're not casting shadows + primVarsApi = lazy.pxr.UsdGeom.PrimvarsAPI(particle_system.GetPrim()) + primVarsApi.CreatePrimvar("doNotCastShadows", lazy.pxr.Sdf.ValueTypeNames.Bool).Set(True) + # tweak anisotropy min, max, and scale to work better with isosurface: + if anisotropy: + ani_api.CreateScaleAttr().Set(5.0) + ani_api.CreateMinAttr().Set(1.0) # avoids gaps in surface + ani_api.CreateMaxAttr().Set(2.0) + + return particle_system + + +def bind_material(prim_path, material_path): + """ + Binds material located at @material_path to the prim located at @prim_path. + + Args: + prim_path (str): Stage path to prim to bind material to + material_path (str): Stage path to material to be bound + """ + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute( + "BindMaterialCommand", + prim_path=prim_path, + material_path=material_path, + strength=None, + ) + + +def create_physx_particleset_pointinstancer( + name, + particle_system_path, + physx_particle_system_path, + prototype_prim_paths, + particle_group, + positions, + self_collision=True, + fluid=False, + particle_mass=None, + particle_density=None, + orientations=None, + velocities=None, + angular_velocities=None, + scales=None, + prototype_indices=None, + enabled=True, +): + """ + Creates a particle set instancer based on a UsdGeom.PointInstancer at @prim_path on the current stage, with + the specified parameters. + + Args: + name (str): Name for this point instancer + particle_system_path (str): Stage path to particle system (Scope) + physx_particle_system_path (str): Stage path to physx particle system (PhysxParticleSystem) + prototype_prim_paths (list of str): Stage path(s) to the prototypes to reference for this particle set. + particle_group (int): ID for this particle set. Particles from different groups will automatically collide + with each other. Particles in the same group will have collision behavior dictated by @self_collision + positions (list of 3-tuple or th.tensor): Particle (x,y,z) positions either as a list or a (N, 3) numpy array + self_collision (bool): Whether to enable particle-particle collision within the set + (as defined by @particle_group) or not + fluid (bool): Whether to simulated the particle set as fluid or not + particle_mass (None or float): If specified, should be per-particle mass. Otherwise, will be + inferred from @density. Note: Either @particle_mass or @particle_density must be specified! + particle_density (None or float): If specified, should be per-particle density and is used to compute total + point set mass. Otherwise, will be inferred from @density. Note: Either @particle_mass or + @particle_density must be specified! + orientations (None or list of 4-array or th.tensor): Particle (x,y,z,w) quaternion orientations, either as a + list or a (N, 4) numpy array. If not specified, all will be set to canonical orientation (0, 0, 0, 1) + velocities (None or list of 3-array or th.tensor): Particle (x,y,z) velocities either as a list or a (N, 3) + numpy array. If not specified, all will be set to 0 + angular_velocities (None or list of 3-array or th.tensor): Particle (x,y,z) angular velocities either as a + list or a (N, 3) numpy array. If not specified, all will be set to 0 + scales (None or list of 3-array or th.tensor): Particle (x,y,z) scales either as a list or a (N, 3) + numpy array. If not specified, all will be set to 1.0 + prototype_indices (None or list of int): If specified, should specify which prototype should be used for + each particle. If None, will use all 0s (i.e.: the first prototype created) + enabled (bool): Whether to enable this particle instancer. If not enabled, then no physics will be used + + Returns: + UsdGeom.PointInstancer: Created point instancer prim + """ + with og.sim.editing_usd(): + stage = og.sim.stage + n_particles = len(positions) + particle_system = lazy.isaacsim.core.utils.prims.get_prim_at_path(physx_particle_system_path) + + # Create point instancer scope + prim_path = f"{particle_system_path}/{name}" + assert not stage.GetPrimAtPath( + prim_path + ), f"Cannot create an instancer scope, scope already exists at {prim_path}!" + stage.DefinePrim(prim_path, "Scope") + + # Create point instancer + instancer_prim_path = f"{prim_path}/instancer" + assert not stage.GetPrimAtPath( + instancer_prim_path + ), f"Cannot create a PointInstancer prim, prim already exists at {instancer_prim_path}!" + instancer = lazy.pxr.UsdGeom.PointInstancer.Define(stage, instancer_prim_path) + + is_isosurface = ( + particle_system.HasAPI(lazy.pxr.PhysxSchema.PhysxParticleIsosurfaceAPI) + and particle_system.GetAttribute("physxParticleIsosurface:isosurfaceEnabled").Get() + ) + + # Add prototype mesh prim paths to the prototypes relationship attribute for this point set + # We need to make copies of prototypes for each instancer currently because particles won't render properly + # if multiple instancers share the same prototypes for some reason + mesh_list = instancer.GetPrototypesRel() + prototype_prims = [] + for i, original_path in enumerate(prototype_prim_paths): + prototype_prim_path = f"{prim_path}/prototype{i}" + lazy.omni.kit.commands.execute("CopyPrim", path_from=original_path, path_to=prototype_prim_path) + prototype_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prototype_prim_path) + # Make sure this prim is invisible if we're using isosurface, and vice versa. + imageable = lazy.pxr.UsdGeom.Imageable(prototype_prim) + if is_isosurface: + imageable.MakeInvisible() + else: + imageable.MakeVisible() + + # Move the prototype to the graveyard position so that it won't be visible to the agent + # We can't directly hide the prototype because it will also hide all the generated particles (if not isosurface) + prototype_prim.GetAttribute("xformOp:translate").Set(m.PROTOTYPE_GRAVEYARD_POS) + + mesh_list.AddTarget(lazy.pxr.Sdf.Path(prototype_prim_path)) + prototype_prims.append(prototype_prim) + + # Set particle instance default data + prototype_indices = [0] * n_particles if prototype_indices is None else prototype_indices + if orientations is None: + orientations = th.zeros((n_particles, 4)) + orientations[:, -1] = 1.0 + orientations = th.tensor(orientations) if not isinstance(orientations, th.Tensor) else orientations + orientations = orientations[:, [3, 0, 1, 2]] # x,y,z,w --> w,x,y,z + velocities = th.zeros((n_particles, 3)) if velocities is None else velocities + angular_velocities = th.zeros((n_particles, 3)) if angular_velocities is None else angular_velocities + scales = th.ones((n_particles, 3)) if scales is None else scales + assert ( + particle_mass is not None or particle_density is not None + ), "Either particle mass or particle density must be specified when creating particle instancer!" + particle_mass = 0.0 if particle_mass is None else particle_mass + particle_density = 0.0 if particle_density is None else particle_density + + # Set particle states + instancer.GetProtoIndicesAttr().Set(prototype_indices) + instancer.GetPositionsAttr().Set(lazy.pxr.Vt.Vec3fArray(positions.tolist())) + instancer.GetOrientationsAttr().Set(lazy.pxr.Vt.QuathArray.FromNumpy(orientations.cpu().numpy())) + instancer.GetVelocitiesAttr().Set(lazy.pxr.Vt.Vec3fArray(velocities.tolist())) + instancer.GetAngularVelocitiesAttr().Set(lazy.pxr.Vt.Vec3fArray(angular_velocities.tolist())) + instancer.GetScalesAttr().Set(lazy.pxr.Vt.Vec3fArray(scales.tolist())) + + # Take a render step to "lock" the visuals of the prototypes at the graveyard position + # This needs to happen AFTER setting particle states + # We suppress a known warning that we have no control over where omni complains about a prototype + # not being populated yet + with suppress_omni_log(channels=["omni.hydra.scene_delegate.plugin"]): + og.sim.render() + + # Then we move the prototypes back to zero offset because otherwise all the generated particles will be offset by + # the graveyard position. At this point, the prototypes themselves no longer appear at the zero offset (locked at + # the graveyard position), which is desirable because we don't want the agent to see the prototypes themselves. + for prototype_prim in prototype_prims: + prototype_prim.GetAttribute("xformOp:translate").Set((0.0, 0.0, 0.0)) + + instancer_prim = instancer.GetPrim() + + lazy.omni.physx.scripts.particleUtils.configure_particle_set( + instancer_prim, + physx_particle_system_path, + self_collision, + fluid, + particle_group, + particle_mass * n_particles, + particle_density, + ) + + # Set whether the instancer is enabled or not + instancer_prim.GetAttribute("physxParticle:particleEnabled").Set(enabled) + + # Render three more times to fully propagate changes + # Omni always complains about a low-level USD thing we have no control over + # so we suppress the warnings + with suppress_omni_log(channels=["omni.usd"]): + for i in range(3): + og.sim.render() + + # Isosurfaces require an additional physics timestep before they're actually rendered + if is_isosurface: + og.log.warning( + f"Creating an instancer that uses isosurface {instancer_prim_path}. " + f"The rendering of these particles will have a delay of one timestep." + ) + + return instancer_prim + + +def apply_force_at_pos(prim, force, pos): + if isinstance(force, th.Tensor): + force = force.cpu().numpy() + if isinstance(pos, th.Tensor): + pos = pos.cpu().numpy() + prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(prim.prim_path) + og.sim.psi.apply_force_at_pos(og.sim.stage_id, prim_id, force, pos) + + +def apply_torque(prim, foward_vect, roll_torque_scalar): + if isinstance(foward_vect, th.Tensor): + foward_vect = foward_vect.cpu().numpy() + prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(prim.prim_path) + og.sim.psi.apply_torque(og.sim.stage_id, prim_id, foward_vect * roll_torque_scalar) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/processing_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/processing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf402da83e2b904501f79f943607560c9f72ce0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/processing_utils.py @@ -0,0 +1,386 @@ +import torch as th + +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.python_utils import Serializable + + +class Filter(Serializable): + """ + A base class for filtering a noisy data stream in an online fashion. + + Implementations store state as compute-backend arrays (``cb.arr_type``) and accept observations + as ``cb`` arrays, torch tensors, or Python sequences (converted at the call boundary). + """ + + def estimate(self, observation): + """ + Takes an observation and returns a de-noised estimate. + + Args: + observation: Current observation, cb.arr_type. + + Returns: + cb.arr_type: De-noised estimate. + """ + raise NotImplementedError + + def reset(self): + """ + Resets this filter. Default is no-op. + """ + pass + + def _dump_state(self): + # Default is no state (empty dict) + return dict() + + def _load_state(self, state): + # Default is no state (empty dict), so this is a no-op + pass + + def serialize(self, state): + # Default is no state, so do nothing + return th.empty(0, dtype=th.float32) + + def deserialize(self, state): + # Default is no state, so do nothing + return dict(), 0 + + @property + def state_size(self): + """ + Size of the serialized state of this filter + """ + raise NotImplementedError + + +class MovingAverageFilter(Filter): + """ + This class uses a moving average to de-noise a noisy data stream in an online fashion. + This is a FIR filter. + + Supports a batch of n_members independent filter rows. Each member has its own circular + buffer row; estimate() targets one member, estimate_batch() processes all rows at once + using matrix operations and broadcasting with no intermediate large allocations. + + Internal buffers are compute-backend arrays (``cb``). The per-member ``fully_filled`` row uses + ``cb.bool_zeros`` / ``cb.logical_or``. Serialized / dumped state uses torch tensors (``cb.to_torch``); + loads convert incoming torch tensors back to ``cb``. + """ + + def __init__(self, obs_dim, filter_width, n_members=1): + """ + Args: + obs_dim (int): The dimension of the points to filter. + filter_width (int): The number of past samples to take the moving average over. + n_members (int): Number of independent filter rows (one per controller member). Defaults to 1. + """ + self.obs_dim = obs_dim + assert filter_width > 0, f"MovingAverageFilter must have a non-zero size! Got: {filter_width}" + self.filter_width = filter_width + self.n_members = n_members + # (n_members, filter_width, obs_dim) — unfilled slots stay zero so sum/count gives correct mean + self.past_samples = cb.zeros((n_members, filter_width, obs_dim)) + self.current_idx = cb.int_array([0] * n_members) + # True once the circular buffer has wrapped at least once for that member + self.fully_filled = cb.bool_zeros(n_members) + # cached row indices to avoid re-allocating in estimate_batch + self._member_arange = cb.arange(n_members) + + super().__init__() + + def add_member(self, slot): + """Register a member at the given slot index. + + If slot < n_members the slot is being reused (tombstone reuse): its buffer is cleared + in-place and n_members is unchanged. If slot == n_members a new row is appended. + + Args: + slot (int): Slot index as determined by the controller's add_member (either a + previously tombstoned index or the next new index == current n_members). + """ + if slot < self.n_members: + # Reuse: clear the slot so it starts fresh + self.past_samples[slot] *= 0.0 + self.current_idx[slot] = 0 + self.fully_filled[slot] = False + # n_members and _member_arange stay the same — slot count is unchanged + return + # New slot: append a fresh row + self.past_samples = cb.cat([self.past_samples, cb.zeros((1, self.filter_width, self.obs_dim))], dim=0) + self.current_idx = cb.cat([self.current_idx, cb.int_array([0])], dim=0) + self.fully_filled = cb.cat([self.fully_filled, cb.bool_zeros(1)], dim=0) + # rebuild arange to include the new member + self._member_arange = cb.arange(self.n_members + 1) + self.n_members += 1 + + def unregister_member(self, member_idx): + """Zero a member's buffer when it is unregistered (tombstoned at the controller level). + + Args: + member_idx (int): Index of the member to unregister. + """ + self.past_samples[member_idx] *= 0.0 + self.current_idx[member_idx] = 0 + self.fully_filled[member_idx] = False + + def estimate(self, member_idx, observation): + """ + Do an online hold for state estimation given a recent observation for one member. + + Args: + member_idx (int): Index of the controller member whose row to update. + observation: New observation of shape (obs_dim,) as ``cb``, torch, or sequence. + + Returns: + cb.arr_type: New estimate of state. + """ + idx = int(cb.to_torch(self.current_idx[member_idx]).item()) + self.past_samples[member_idx, idx, :] = observation + + # Compute value based on whether we're fully filled or not + if not cb.item_bool(self.fully_filled[member_idx]): + val = cb.mean(self.past_samples[member_idx, : idx + 1, :], dim=0) + # Denote that we're fully filled if we're at the end of the buffer + if idx == self.filter_width - 1: + self.fully_filled[member_idx] = True + else: + val = cb.mean(self.past_samples[member_idx], dim=0) + + # Increment the index to write the next sample to + self.current_idx[member_idx] = (idx + 1) % self.filter_width + return val + + def estimate_batch(self, observations): + """ + Process all N member rows at once using batched matrix operations. + + Unfilled slots in past_samples are zero, so sum(dim=1) / fill_count gives the correct + per-member mean without any masking matrix. Broadcasting is used throughout to avoid + allocating intermediate large tensors. + + Args: + observations: (N, obs_dim) new observations for all members, cb.arr_type. + + Returns: + cb.arr_type: (N, obs_dim) smoothed estimates. + """ + # Write new observations in-place via advanced indexing — no new large tensor + self.past_samples[self._member_arange, self.current_idx] = observations + + fill_count = cb.where(self.fully_filled, float(self.filter_width), self.current_idx + 1.0) + + sample_sums = cb.sum(self.past_samples, dim=1) + fill_bc = cb.view(fill_count, (-1, 1)) + vals = sample_sums / fill_bc + + hit_end = self.current_idx == (self.filter_width - 1) + self.fully_filled = cb.logical_or(self.fully_filled, hit_end) + + # Advance circular buffer pointer in-place + self.current_idx = cb.as_int(self.current_idx + 1) + self.current_idx = cb.as_int(self.current_idx % self.filter_width) + + return vals + + def reset(self, member_idx=None): + """ + Reset one member's filter row, or all rows if member_idx is None. + + Args: + member_idx (int or None): Member to reset. Resets all members if None. + """ + if member_idx is None: + self.past_samples *= 0.0 + self.current_idx *= 0 + self.fully_filled = cb.bool_zeros(self.n_members) + else: + self.past_samples[member_idx] *= 0.0 + self.current_idx[member_idx] = 0 + self.fully_filled[member_idx] = False + + @property + def state_size(self): + return self.filter_width * self.obs_dim + 2 + + def dump_state(self, controller_idx, serialized=False): + state = self._dump_state(controller_idx) + return self.serialize(state, controller_idx) if serialized else state + + def _dump_state(self, controller_idx): + return { + "past_samples": cb.to_torch(self.past_samples[controller_idx]), + "current_idx": cb.item_int(self.current_idx[controller_idx]), + "fully_filled": cb.item_bool(self.fully_filled[controller_idx]), + } + + def load_state(self, controller_idx, state, serialized=False): + if serialized: + orig_state_len = len(state) + state, deserialized_items = self.deserialize(state, controller_idx) + assert deserialized_items == orig_state_len, ( + f"Invalid state deserialization occurred! Expected {orig_state_len} total " + f"values to be deserialized, only {deserialized_items} were." + ) + self._load_state(controller_idx, state) + + def _load_state(self, controller_idx, state): + self.past_samples[controller_idx] = cb.from_torch(state["past_samples"]) + self.current_idx[controller_idx] = state["current_idx"] + self.fully_filled[controller_idx] = state["fully_filled"] + + def serialize(self, state, controller_idx): + return th.cat( + [ + state["past_samples"].flatten(), + th.tensor([state["current_idx"]], dtype=th.float32), + th.tensor([state["fully_filled"]], dtype=th.float32), + ] + ) + + def deserialize(self, state, controller_idx): + samples_len = self.filter_width * self.obs_dim + state_dict = { + "past_samples": state[:samples_len].reshape(self.filter_width, self.obs_dim), + "current_idx": int(state[samples_len].item()), + "fully_filled": bool(state[samples_len + 1].item()), + } + return state_dict, samples_len + 2 + + +class ExponentialAverageFilter(Filter): + """ + This class uses an exponential average of the form y_n = alpha * x_n + (1 - alpha) * y_{n - 1}. + This is an IIR filter. + """ + + def __init__(self, obs_dim, alpha=0.9): + """ + + Args: + obs_dim (int): The dimension of the points to filter. + alpha (float): The relative weighting of new samples relative to older samples + """ + self.obs_dim = obs_dim + self.avg = cb.zeros(obs_dim) + self.num_samples = 0 + self.alpha = alpha + + super().__init__() + + def estimate(self, observation): + """ + Do an online hold for state estimation given a recent observation. + + Args: + observation: New observation, cb.arr_type. + + Returns: + cb.arr_type: New estimate of state. + """ + self.avg = self.alpha * observation + (1.0 - self.alpha) * self.avg + self.num_samples += 1 + + return cb.copy(self.avg) + + def reset(self): + # Clear internal state + self.avg *= 0.0 + self.num_samples = 0 + + @property + def state_size(self): + # This is the size of the internal value as well as a num samples + return len(self.avg) + 1 + + def _dump_state(self): + # Run super init first + state = super()._dump_state() + + # Add info from this filter + state["avg"] = cb.to_torch(self.avg) + state["num_samples"] = self.num_samples + + return state + + def _load_state(self, state): + # Run super first + super()._load_state(state=state) + + # Load relevant info for this filter + self.avg = cb.from_torch(state["avg"]) + self.num_samples = state["num_samples"] + + def serialize(self, state): + # Run super first + state_flat = super().serialize(state=state) + + # Serialize state for this filter + return th.cat( + [ + state_flat, + state["avg"], + [state["num_samples"]], + ] + ) + + def deserialize(self, state): + # Run super first + state_dict, idx = super().deserialize(state=state) + + # Deserialize state for this filter + state_dict["avg"] = state[idx : idx + self.obs_dim] + state_dict["num_samples"] = int(state[idx + self.obs_dim]) + + return state_dict, idx + self.obs_dim + 1 + + +class Subsampler: + """ + A base class for subsampling a data stream in an online fashion. + """ + + def subsample(self, observation): + """ + Takes an observation and returns the observation, or None, which + corresponds to deleting the observation. + + Args: + observation (n-array): A current observation. + + Returns: + None or n-array: No observation if subsampled, otherwise the observation + """ + raise NotImplementedError + + +class UniformSubsampler(Subsampler): + """ + A class for subsampling a data stream uniformly in time in an online fashion. + """ + + def __init__(self, T): + """ + Args: + T (int): Pick one every T observations. + """ + self.T = T + self.counter = 0 + + super(UniformSubsampler, self).__init__() + + def subsample(self, observation): + """ + Returns an observation once every T observations, None otherwise. + + Args: + observation (n-array): A current observation. + + Returns: + None or n-array: The observation, or None. + """ + self.counter += 1 + if self.counter == self.T: + self.counter = 0 + return observation + return None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/profiling_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/profiling_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e5bd299919d3ba742949c65107b861ff5e80d68 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/profiling_utils.py @@ -0,0 +1,107 @@ +import os +from cProfile import Profile as CProfile +from time import perf_counter + +import psutil + +import omnigibson.utils.pynvml_utils as pynvml + + +class Profiler: + """ + Lightweight profiler that tracks wall-clock timing across enable/disable cycles. + + Used by the Simulator's `with_profiler` decorator. Each enable/disable pair records + one timing sample. Callers can read cumulative or per-call averages at any time. + + Optionally wraps a cProfile.Profile for deep (function-level) profiling when + gm.ENABLE_DEEP_PROFILING is set. + """ + + def __init__(self, deep=False): + self._total_time = 0.0 + self._call_count = 0 + self._start = None + self._last_dt = 0.0 + self._cprofiler = CProfile() if deep else None + + def enable(self): + if self._cprofiler is not None: + self._cprofiler.enable() + self._start = perf_counter() + + def disable(self): + dt = perf_counter() - self._start + if self._cprofiler is not None: + self._cprofiler.disable() + self._last_dt = dt + self._total_time += dt + self._call_count += 1 + + @property + def last_dt(self): + """Wall-clock seconds for the most recent enable/disable pair.""" + return self._last_dt + + @property + def total_time(self): + """Cumulative wall-clock seconds across all recorded calls.""" + return self._total_time + + @property + def call_count(self): + """Number of completed enable/disable cycles.""" + return self._call_count + + @property + def average_time(self): + """Average wall-clock seconds per call, or 0 if no calls recorded.""" + return self._total_time / self._call_count if self._call_count > 0 else 0.0 + + def reset(self): + """Clear all accumulated timing data (does not affect the cProfile profiler).""" + self._total_time = 0.0 + self._call_count = 0 + self._last_dt = 0.0 + + def dump_stats(self, filename): + """Dump cProfile stats to a file (no-op if deep profiling is disabled).""" + if self._cprofiler is not None: + self._cprofiler.dump_stats(filename) + + +# Method copied from: https://github.com/wandb/wandb/blob/main/wandb/sdk/internal/system/assets/gpu.py +def gpu_in_use_by_this_process(gpu_handle, pid: int) -> bool: + if psutil is None: + return False + + try: + base_process = psutil.Process(pid=pid) + except psutil.NoSuchProcess: + return False + + our_processes = base_process.children(recursive=True) + our_processes.append(base_process) + + our_pids = {process.pid for process in our_processes} + + compute_pids = {process.pid for process in pynvml.nvmlDeviceGetComputeRunningProcesses(gpu_handle)} + graphics_pids = {process.pid for process in pynvml.nvmlDeviceGetGraphicsRunningProcesses(gpu_handle)} + + pids_using_device = compute_pids | graphics_pids + + return len(pids_using_device & our_pids) > 0 + + +def get_vram_usage(): + """Get VRAM usage in GB for the GPU used by this process.""" + pynvml.nvmlInit() + device_count = pynvml.nvmlDeviceGetCount() + vram_usage = 0.0 + for i in range(device_count): + handle = pynvml.nvmlDeviceGetHandleByIndex(i) + if gpu_in_use_by_this_process(handle, os.getpid()): + vram_usage = pynvml.nvmlDeviceGetMemoryInfo(handle).used / 1024**3 + break + pynvml.nvmlShutdown() + return vram_usage diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/pynvml_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/pynvml_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2aef4938931f727d49c3babb95715d2bde0bc7b7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/pynvml_utils.py @@ -0,0 +1,4562 @@ +# File copied from: https://github.com/wandb/wandb/blob/main/wandb/vendor/pynvml/pynvml.py + +##### +# +# Based on nvidia-ml-py version 11.515.48 +# Sourced from https://pypi.org/project/nvidia-ml-py/ +# Modifications: +# - Added `NVML_DLL_PATH` env var check to the library initialization path +# - Applied black formatting to improve readability +# - Try different versions ("_v3", "_v2", "") of the functions: +# nvmlDeviceGetComputeRunningProcesses, +# nvmlDeviceGetGraphicsRunningProcesses, and +# nvmlDeviceGetMPSComputeRunningProcesses +# +# Copyright (c) 2011-2022, NVIDIA Corporation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the NVIDIA Corporation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +# THE POSSIBILITY OF SUCH DAMAGE. +##### + +import os +import string +import sys +import threading + +## +# Python bindings for the NVML library +## +from ctypes import * +from functools import wraps + +## C Type mappings ## +## Enums +_nvmlEnableState_t = c_uint +NVML_FEATURE_DISABLED = 0 +NVML_FEATURE_ENABLED = 1 + +_nvmlBrandType_t = c_uint +NVML_BRAND_UNKNOWN = 0 +NVML_BRAND_QUADRO = 1 +NVML_BRAND_TESLA = 2 +NVML_BRAND_NVS = 3 +NVML_BRAND_GRID = 4 # Deprecated from API reporting. Keeping definition for backward compatibility. +NVML_BRAND_GEFORCE = 5 +NVML_BRAND_TITAN = 6 +NVML_BRAND_NVIDIA_VAPPS = 7 # NVIDIA Virtual Applications +NVML_BRAND_NVIDIA_VPC = 8 # NVIDIA Virtual PC +NVML_BRAND_NVIDIA_VCS = 9 # NVIDIA Virtual Compute Server +NVML_BRAND_NVIDIA_VWS = 10 # NVIDIA RTX Virtual Workstation +NVML_BRAND_NVIDIA_CLOUD_GAMING = 11 # NVIDIA Cloud Gaming +NVML_BRAND_NVIDIA_VGAMING = ( + NVML_BRAND_NVIDIA_CLOUD_GAMING # Deprecated from API reporting. Keeping definition for backward compatibility. +) +NVML_BRAND_QUADRO_RTX = 12 +NVML_BRAND_NVIDIA_RTX = 13 +NVML_BRAND_NVIDIA = 14 +NVML_BRAND_GEFORCE_RTX = 15 # Unused +NVML_BRAND_TITAN_RTX = 16 # Unused +NVML_BRAND_COUNT = 17 + +_nvmlTemperatureThresholds_t = c_uint +NVML_TEMPERATURE_THRESHOLD_SHUTDOWN = 0 +NVML_TEMPERATURE_THRESHOLD_SLOWDOWN = 1 +NVML_TEMPERATURE_THRESHOLD_MEM_MAX = 2 +NVML_TEMPERATURE_THRESHOLD_GPU_MAX = 3 +NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MIN = 4 +NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_CURR = 5 +NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MAX = 6 +NVML_TEMPERATURE_THRESHOLD_COUNT = 7 + +_nvmlTemperatureSensors_t = c_uint +NVML_TEMPERATURE_GPU = 0 +NVML_TEMPERATURE_COUNT = 1 + +_nvmlComputeMode_t = c_uint +NVML_COMPUTEMODE_DEFAULT = 0 +NVML_COMPUTEMODE_EXCLUSIVE_THREAD = 1 ## Support Removed +NVML_COMPUTEMODE_PROHIBITED = 2 +NVML_COMPUTEMODE_EXCLUSIVE_PROCESS = 3 +NVML_COMPUTEMODE_COUNT = 4 + +_nvmlMemoryLocation_t = c_uint +NVML_MEMORY_LOCATION_L1_CACHE = 0 +NVML_MEMORY_LOCATION_L2_CACHE = 1 +NVML_MEMORY_LOCATION_DEVICE_MEMORY = 2 +NVML_MEMORY_LOCATION_DRAM = 2 +NVML_MEMORY_LOCATION_REGISTER_FILE = 3 +NVML_MEMORY_LOCATION_TEXTURE_MEMORY = 4 +NVML_MEMORY_LOCATION_TEXTURE_SHM = 5 +NVML_MEMORY_LOCATION_CBU = 6 +NVML_MEMORY_LOCATION_SRAM = 7 +NVML_MEMORY_LOCATION_COUNT = 8 + +NVML_NVLINK_MAX_LINKS = 12 + +# For backwards compatibility, maintain the incorrectly-named "LANES" define +NVML_NVLINK_MAX_LANES = NVML_NVLINK_MAX_LINKS + +_nvmlNvLinkErrorCounter_t = c_uint +NVML_NVLINK_ERROR_DL_REPLAY = 0 +NVML_NVLINK_ERROR_DL_RECOVERY = 1 +NVML_NVLINK_ERROR_DL_CRC_FLIT = 2 +NVML_NVLINK_ERROR_DL_CRC_DATA = 3 +NVML_NVLINK_ERROR_DL_ECC_DATA = 4 +NVML_NVLINK_ERROR_COUNT = 5 + +_nvmlNvLinkEccLaneErrorCounter_t = c_uint +NVML_NVLINK_ERROR_DL_ECC_LANE0 = 0 +NVML_NVLINK_ERROR_DL_ECC_LANE1 = 1 +NVML_NVLINK_ERROR_DL_ECC_LANE2 = 2 +NVML_NVLINK_ERROR_DL_ECC_LANE3 = 3 +NVML_NVLINK_ERROR_DL_ECC_COUNT = 5 + +_nvmlNvLinkCapability_t = c_uint +NVML_NVLINK_CAP_P2P_SUPPORTED = 0 +NVML_NVLINK_CAP_SYSMEM_ACCESS = 1 +NVML_NVLINK_CAP_P2P_ATOMICS = 2 +NVML_NVLINK_CAP_SYSMEM_ATOMICS = 3 +NVML_NVLINK_CAP_SLI_BRIDGE = 4 +NVML_NVLINK_CAP_VALID = 5 +NVML_NVLINK_CAP_COUNT = 6 + +_nvmlNvLinkUtilizationCountPktTypes_t = c_uint +NVML_NVLINK_COUNTER_PKTFILTER_NOP = 0x1 +NVML_NVLINK_COUNTER_PKTFILTER_READ = 0x2 +NVML_NVLINK_COUNTER_PKTFILTER_WRITE = 0x4 +NVML_NVLINK_COUNTER_PKTFILTER_RATOM = 0x8 +NVML_NVLINK_COUNTER_PKTFILTER_NRATOM = 0x10 +NVML_NVLINK_COUNTER_PKTFILTER_FLUSH = 0x20 +NVML_NVLINK_COUNTER_PKTFILTER_RESPDATA = 0x40 +NVML_NVLINK_COUNTER_PKTFILTER_RESPNODATA = 0x80 +NVML_NVLINK_COUNTER_PKTFILTER_ALL = 0xFF + +_nvmlNvLinkUtilizationCountUnits_t = c_uint +NVML_NVLINK_COUNTER_UNIT_CYCLES = 0 +NVML_NVLINK_COUNTER_UNIT_PACKETS = 1 +NVML_NVLINK_COUNTER_UNIT_BYTES = 2 +NVML_NVLINK_COUNTER_UNIT_RESERVED = 3 +NVML_NVLINK_COUNTER_UNIT_COUNT = 4 + +_nvmlNvLinkDeviceType_t = c_uint +NVML_NVLINK_DEVICE_TYPE_GPU = 0x00 +NVML_NVLINK_DEVICE_TYPE_IBMNPU = 0x01 +NVML_NVLINK_DEVICE_TYPE_SWITCH = 0x02 +NVML_NVLINK_DEVICE_TYPE_UNKNOWN = 0xFF + +# These are deprecated, instead use _nvmlMemoryErrorType_t +_nvmlEccBitType_t = c_uint +NVML_SINGLE_BIT_ECC = 0 +NVML_DOUBLE_BIT_ECC = 1 +NVML_ECC_ERROR_TYPE_COUNT = 2 + +_nvmlEccCounterType_t = c_uint +NVML_VOLATILE_ECC = 0 +NVML_AGGREGATE_ECC = 1 +NVML_ECC_COUNTER_TYPE_COUNT = 2 + +_nvmlMemoryErrorType_t = c_uint +NVML_MEMORY_ERROR_TYPE_CORRECTED = 0 +NVML_MEMORY_ERROR_TYPE_UNCORRECTED = 1 +NVML_MEMORY_ERROR_TYPE_COUNT = 2 + +_nvmlClockType_t = c_uint +NVML_CLOCK_GRAPHICS = 0 +NVML_CLOCK_SM = 1 +NVML_CLOCK_MEM = 2 +NVML_CLOCK_VIDEO = 3 +NVML_CLOCK_COUNT = 4 + +_nvmlClockId_t = c_uint +NVML_CLOCK_ID_CURRENT = 0 +NVML_CLOCK_ID_APP_CLOCK_TARGET = 1 +NVML_CLOCK_ID_APP_CLOCK_DEFAULT = 2 +NVML_CLOCK_ID_CUSTOMER_BOOST_MAX = 3 +NVML_CLOCK_ID_COUNT = 4 + +_nvmlDriverModel_t = c_uint +NVML_DRIVER_WDDM = 0 +NVML_DRIVER_WDM = 1 + +NVML_MAX_GPU_PERF_PSTATES = 16 + +_nvmlPstates_t = c_uint +NVML_PSTATE_0 = 0 +NVML_PSTATE_1 = 1 +NVML_PSTATE_2 = 2 +NVML_PSTATE_3 = 3 +NVML_PSTATE_4 = 4 +NVML_PSTATE_5 = 5 +NVML_PSTATE_6 = 6 +NVML_PSTATE_7 = 7 +NVML_PSTATE_8 = 8 +NVML_PSTATE_9 = 9 +NVML_PSTATE_10 = 10 +NVML_PSTATE_11 = 11 +NVML_PSTATE_12 = 12 +NVML_PSTATE_13 = 13 +NVML_PSTATE_14 = 14 +NVML_PSTATE_15 = 15 +NVML_PSTATE_UNKNOWN = 32 + +_nvmlInforomObject_t = c_uint +NVML_INFOROM_OEM = 0 +NVML_INFOROM_ECC = 1 +NVML_INFOROM_POWER = 2 +NVML_INFOROM_COUNT = 3 + +_nvmlReturn_t = c_uint +NVML_SUCCESS = 0 +NVML_ERROR_UNINITIALIZED = 1 +NVML_ERROR_INVALID_ARGUMENT = 2 +NVML_ERROR_NOT_SUPPORTED = 3 +NVML_ERROR_NO_PERMISSION = 4 +NVML_ERROR_ALREADY_INITIALIZED = 5 +NVML_ERROR_NOT_FOUND = 6 +NVML_ERROR_INSUFFICIENT_SIZE = 7 +NVML_ERROR_INSUFFICIENT_POWER = 8 +NVML_ERROR_DRIVER_NOT_LOADED = 9 +NVML_ERROR_TIMEOUT = 10 +NVML_ERROR_IRQ_ISSUE = 11 +NVML_ERROR_LIBRARY_NOT_FOUND = 12 +NVML_ERROR_FUNCTION_NOT_FOUND = 13 +NVML_ERROR_CORRUPTED_INFOROM = 14 +NVML_ERROR_GPU_IS_LOST = 15 +NVML_ERROR_RESET_REQUIRED = 16 +NVML_ERROR_OPERATING_SYSTEM = 17 +NVML_ERROR_LIB_RM_VERSION_MISMATCH = 18 +NVML_ERROR_IN_USE = 19 +NVML_ERROR_MEMORY = 20 +NVML_ERROR_NO_DATA = 21 +NVML_ERROR_VGPU_ECC_NOT_SUPPORTED = 22 +NVML_ERROR_INSUFFICIENT_RESOURCES = 23 +NVML_ERROR_FREQ_NOT_SUPPORTED = 24 +NVML_ERROR_UNKNOWN = 999 + +_nvmlFanState_t = c_uint +NVML_FAN_NORMAL = 0 +NVML_FAN_FAILED = 1 + +_nvmlLedColor_t = c_uint +NVML_LED_COLOR_GREEN = 0 +NVML_LED_COLOR_AMBER = 1 + +_nvmlGpuOperationMode_t = c_uint +NVML_GOM_ALL_ON = 0 +NVML_GOM_COMPUTE = 1 +NVML_GOM_LOW_DP = 2 + +_nvmlPageRetirementCause_t = c_uint +NVML_PAGE_RETIREMENT_CAUSE_MULTIPLE_SINGLE_BIT_ECC_ERRORS = 0 +NVML_PAGE_RETIREMENT_CAUSE_DOUBLE_BIT_ECC_ERROR = 1 +NVML_PAGE_RETIREMENT_CAUSE_COUNT = 2 + +_nvmlRestrictedAPI_t = c_uint +NVML_RESTRICTED_API_SET_APPLICATION_CLOCKS = 0 +NVML_RESTRICTED_API_SET_AUTO_BOOSTED_CLOCKS = 1 +NVML_RESTRICTED_API_COUNT = 2 + +_nvmlBridgeChipType_t = c_uint +NVML_BRIDGE_CHIP_PLX = 0 +NVML_BRIDGE_CHIP_BRO4 = 1 +NVML_MAX_PHYSICAL_BRIDGE = 128 + +_nvmlValueType_t = c_uint +NVML_VALUE_TYPE_DOUBLE = 0 +NVML_VALUE_TYPE_UNSIGNED_INT = 1 +NVML_VALUE_TYPE_UNSIGNED_LONG = 2 +NVML_VALUE_TYPE_UNSIGNED_LONG_LONG = 3 +NVML_VALUE_TYPE_SIGNED_LONG_LONG = 4 +NVML_VALUE_TYPE_COUNT = 5 + +_nvmlPerfPolicyType_t = c_uint +NVML_PERF_POLICY_POWER = 0 +NVML_PERF_POLICY_THERMAL = 1 +NVML_PERF_POLICY_SYNC_BOOST = 2 +NVML_PERF_POLICY_BOARD_LIMIT = 3 +NVML_PERF_POLICY_LOW_UTILIZATION = 4 +NVML_PERF_POLICY_RELIABILITY = 5 +NVML_PERF_POLICY_TOTAL_APP_CLOCKS = 10 +NVML_PERF_POLICY_TOTAL_BASE_CLOCKS = 11 +NVML_PERF_POLICY_COUNT = 12 + +_nvmlEncoderQueryType_t = c_uint +NVML_ENCODER_QUERY_H264 = 0 +NVML_ENCODER_QUERY_HEVC = 1 + +_nvmlFBCSessionType_t = c_uint +NVML_FBC_SESSION_TYPE_UNKNOWN = 0 +NVML_FBC_SESSION_TYPE_TOSYS = 1 +NVML_FBC_SESSION_TYPE_CUDA = 2 +NVML_FBC_SESSION_TYPE_VID = 3 +NVML_FBC_SESSION_TYPE_HWENC = 4 + +_nvmlDetachGpuState_t = c_uint +NVML_DETACH_GPU_KEEP = 0 +NVML_DETACH_GPU_REMOVE = 1 + +_nvmlPcieLinkState_t = c_uint +NVML_PCIE_LINK_KEEP = 0 +NVML_PCIE_LINK_SHUT_DOWN = 1 + +_nvmlSamplingType_t = c_uint +NVML_TOTAL_POWER_SAMPLES = 0 +NVML_GPU_UTILIZATION_SAMPLES = 1 +NVML_MEMORY_UTILIZATION_SAMPLES = 2 +NVML_ENC_UTILIZATION_SAMPLES = 3 +NVML_DEC_UTILIZATION_SAMPLES = 4 +NVML_PROCESSOR_CLK_SAMPLES = 5 +NVML_MEMORY_CLK_SAMPLES = 6 +NVML_SAMPLINGTYPE_COUNT = 7 + +_nvmlPcieUtilCounter_t = c_uint +NVML_PCIE_UTIL_TX_BYTES = 0 +NVML_PCIE_UTIL_RX_BYTES = 1 +NVML_PCIE_UTIL_COUNT = 2 + +_nvmlGpuTopologyLevel_t = c_uint +NVML_TOPOLOGY_INTERNAL = 0 +NVML_TOPOLOGY_SINGLE = 10 +NVML_TOPOLOGY_MULTIPLE = 20 +NVML_TOPOLOGY_HOSTBRIDGE = 30 +NVML_TOPOLOGY_NODE = 40 +NVML_TOPOLOGY_CPU = NVML_TOPOLOGY_NODE +NVML_TOPOLOGY_SYSTEM = 50 + +_nvmlGpuP2PCapsIndex_t = c_uint +NVML_P2P_CAPS_INDEX_READ = (0,) +NVML_P2P_CAPS_INDEX_WRITE = 1 +NVML_P2P_CAPS_INDEX_NVLINK = 2 +NVML_P2P_CAPS_INDEX_ATOMICS = 3 +NVML_P2P_CAPS_INDEX_PROP = 4 +NVML_P2P_CAPS_INDEX_LOOPBACK = 5 +NVML_P2P_CAPS_INDEX_UNKNOWN = 6 + +_nvmlGpuP2PStatus_t = c_uint +NVML_P2P_STATUS_OK = 0 +NVML_P2P_STATUS_CHIPSET_NOT_SUPPORED = 1 +NVML_P2P_STATUS_GPU_NOT_SUPPORTED = 2 +NVML_P2P_STATUS_IOH_TOPOLOGY_NOT_SUPPORTED = 3 +NVML_P2P_STATUS_DISABLED_BY_REGKEY = 4 +NVML_P2P_STATUS_NOT_SUPPORTED = 5 +NVML_P2P_STATUS_UNKNOWN = 6 + +_nvmlDeviceArchitecture_t = c_uint +NVML_DEVICE_ARCH_KEPLER = 2 +NVML_DEVICE_ARCH_MAXWELL = 3 +NVML_DEVICE_ARCH_PASCAL = 4 +NVML_DEVICE_ARCH_VOLTA = 5 +NVML_DEVICE_ARCH_TURING = 6 +NVML_DEVICE_ARCH_AMPERE = 7 +NVML_DEVICE_ARCH_UNKNOWN = 0xFFFFFFFF + +# PCI bus Types +_nvmlBusType_t = c_uint +NVML_BUS_TYPE_UNKNOWN = 0 +NVML_BUS_TYPE_PCI = 1 +NVML_BUS_TYPE_PCIE = 2 +NVML_BUS_TYPE_FPCI = 3 +NVML_BUS_TYPE_AGP = 4 + +_nvmlPowerSource_t = c_uint +NVML_POWER_SOURCE_AC = 0x00000000 +NVML_POWER_SOURCE_BATTERY = 0x00000001 + +_nvmlAdaptiveClockInfoStatus_t = c_uint +NVML_ADAPTIVE_CLOCKING_INFO_STATUS_DISABLED = 0x00000000 +NVML_ADAPTIVE_CLOCKING_INFO_STATUS_ENABLED = 0x00000001 + +_nvmlClockLimitId_t = c_uint +NVML_CLOCK_LIMIT_ID_RANGE_START = 0xFFFFFF00 +NVML_CLOCK_LIMIT_ID_TDP = 0xFFFFFF01 +NVML_CLOCK_LIMIT_ID_UNLIMITED = 0xFFFFFF02 + +_nvmlPcieLinkMaxSpeed_t = c_uint +NVML_PCIE_LINK_MAX_SPEED_INVALID = 0x00000000 +NVML_PCIE_LINK_MAX_SPEED_2500MBPS = 0x00000001 +NVML_PCIE_LINK_MAX_SPEED_5000MBPS = 0x00000002 +NVML_PCIE_LINK_MAX_SPEED_8000MBPS = 0x00000003 +NVML_PCIE_LINK_MAX_SPEED_16000MBPS = 0x00000004 +NVML_PCIE_LINK_MAX_SPEED_32000MBPS = 0x00000005 + +_nvmlAffinityScope_t = c_uint +NVML_AFFINITY_SCOPE_NODE = 0 +NVML_AFFINITY_SCOPE_SOCKET = 1 + +# C preprocessor defined values +nvmlFlagDefault = 0 +nvmlFlagForce = 1 +NVML_INIT_FLAG_NO_GPUS = 1 +NVML_INIT_FLAG_NO_ATTACH = 2 + +NVML_MAX_GPC_COUNT = 32 + +# buffer size +NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE = 16 +NVML_DEVICE_UUID_BUFFER_SIZE = 80 +NVML_DEVICE_UUID_V2_BUFFER_SIZE = 96 +NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE = 80 +NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE = 80 +NVML_DEVICE_NAME_BUFFER_SIZE = 64 +NVML_DEVICE_NAME_V2_BUFFER_SIZE = 96 +NVML_DEVICE_SERIAL_BUFFER_SIZE = 30 +NVML_DEVICE_PART_NUMBER_BUFFER_SIZE = 80 +NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE = 32 +NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE = 32 +NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE = 16 +NVML_GRID_LICENSE_BUFFER_SIZE = 128 +NVML_VGPU_NAME_BUFFER_SIZE = 64 +NVML_GRID_LICENSE_FEATURE_MAX_COUNT = 3 +NVML_VGPU_METADATA_OPAQUE_DATA_SIZE = sizeof(c_uint) + 256 +NVML_VGPU_PGPU_METADATA_OPAQUE_DATA_SIZE = 256 + +# Format strings +NVML_DEVICE_PCI_BUS_ID_LEGACY_FMT = "%04X:%02X:%02X.0" +NVML_DEVICE_PCI_BUS_ID_FMT = "%08X:%02X:%02X.0" + +NVML_VALUE_NOT_AVAILABLE_ulonglong = c_ulonglong(-1) +NVML_VALUE_NOT_AVAILABLE_uint = c_uint(-1) + +""" + Field Identifiers. + + All Identifiers pertain to a device. Each ID is only used once and is guaranteed never to change. +""" +NVML_FI_DEV_ECC_CURRENT = 1 # Current ECC mode. 1=Active. 0=Inactive +NVML_FI_DEV_ECC_PENDING = 2 # Pending ECC mode. 1=Active. 0=Inactive + +# ECC Count Totals +NVML_FI_DEV_ECC_SBE_VOL_TOTAL = 3 # Total single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_TOTAL = 4 # Total double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_AGG_TOTAL = 5 # Total single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_TOTAL = 6 # Total double bit aggregate (persistent) ECC errors +# Individual ECC locations +NVML_FI_DEV_ECC_SBE_VOL_L1 = 7 # L1 cache single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_L1 = 8 # L1 cache double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_L2 = 9 # L2 cache single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_L2 = 10 # L2 cache double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_DEV = 11 # Device memory single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_DEV = 12 # Device memory double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_REG = 13 # Register file single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_REG = 14 # Register file double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_VOL_TEX = 15 # Texture memory single bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_TEX = 16 # Texture memory double bit volatile ECC errors +NVML_FI_DEV_ECC_DBE_VOL_CBU = 17 # CBU double bit volatile ECC errors +NVML_FI_DEV_ECC_SBE_AGG_L1 = 18 # L1 cache single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_L1 = 19 # L1 cache double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_L2 = 20 # L2 cache single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_L2 = 21 # L2 cache double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_DEV = 22 # Device memory single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_DEV = 23 # Device memory double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_REG = 24 # Register File single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_REG = 25 # Register File double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_SBE_AGG_TEX = 26 # Texture memory single bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_TEX = 27 # Texture memory double bit aggregate (persistent) ECC errors +NVML_FI_DEV_ECC_DBE_AGG_CBU = 28 # CBU double bit aggregate ECC errors + +# Page Retirement +NVML_FI_DEV_RETIRED_SBE = 29 # Number of retired pages because of single bit errors +NVML_FI_DEV_RETIRED_DBE = 30 # Number of retired pages because of double bit errors +NVML_FI_DEV_RETIRED_PENDING = 31 # If any pages are pending retirement. 1=yes. 0=no. + +# NvLink Flit Error Counters +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L0 = 32 # NVLink flow control CRC Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L1 = 33 # NVLink flow control CRC Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L2 = 34 # NVLink flow control CRC Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L3 = 35 # NVLink flow control CRC Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L4 = 36 # NVLink flow control CRC Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L5 = 37 # NVLink flow control CRC Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_TOTAL = 38 # NVLink flow control CRC Error Counter total for all Lanes + +# NvLink CRC Data Error Counters +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L0 = 39 # NVLink data CRC Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L1 = 40 # NVLink data CRC Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L2 = 41 # NVLink data CRC Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L3 = 42 # NVLink data CRC Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L4 = 43 # NVLink data CRC Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L5 = 44 # NVLink data CRC Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_TOTAL = 45 # NvLink data CRC Error Counter total for all Lanes + +# NvLink Replay Error Counters +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L0 = 46 # NVLink Replay Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L1 = 47 # NVLink Replay Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L2 = 48 # NVLink Replay Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L3 = 49 # NVLink Replay Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L4 = 50 # NVLink Replay Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L5 = 51 # NVLink Replay Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_TOTAL = 52 # NVLink Replay Error Counter total for all Lanes + +# NvLink Recovery Error Counters +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L0 = 53 # NVLink Recovery Error Counter for Lane 0 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L1 = 54 # NVLink Recovery Error Counter for Lane 1 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L2 = 55 # NVLink Recovery Error Counter for Lane 2 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L3 = 56 # NVLink Recovery Error Counter for Lane 3 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L4 = 57 # NVLink Recovery Error Counter for Lane 4 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L5 = 58 # NVLink Recovery Error Counter for Lane 5 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_TOTAL = 59 # NVLink Recovery Error Counter total for all Lanes + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L0 = 60 # NVLink Bandwidth Counter for Counter Set 0, Lane 0 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L1 = 61 # NVLink Bandwidth Counter for Counter Set 0, Lane 1 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L2 = 62 # NVLink Bandwidth Counter for Counter Set 0, Lane 2 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L3 = 63 # NVLink Bandwidth Counter for Counter Set 0, Lane 3 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L4 = 64 # NVLink Bandwidth Counter for Counter Set 0, Lane 4 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L5 = 65 # NVLink Bandwidth Counter for Counter Set 0, Lane 5 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_TOTAL = 66 # NVLink Bandwidth Counter Total for Counter Set 0, All Lanes + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L0 = 67 # NVLink Bandwidth Counter for Counter Set 1, Lane 0 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L1 = 68 # NVLink Bandwidth Counter for Counter Set 1, Lane 1 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L2 = 69 # NVLink Bandwidth Counter for Counter Set 1, Lane 2 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L3 = 70 # NVLink Bandwidth Counter for Counter Set 1, Lane 3 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L4 = 71 # NVLink Bandwidth Counter for Counter Set 1, Lane 4 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L5 = 72 # NVLink Bandwidth Counter for Counter Set 1, Lane 5 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_TOTAL = 73 # NVLink Bandwidth Counter Total for Counter Set 1, All Lanes + +# Perf Policy Counters +NVML_FI_DEV_PERF_POLICY_POWER = 74 # Perf Policy Counter for Power Policy +NVML_FI_DEV_PERF_POLICY_THERMAL = 75 # Perf Policy Counter for Thermal Policy +NVML_FI_DEV_PERF_POLICY_SYNC_BOOST = 76 # Perf Policy Counter for Sync boost Policy +NVML_FI_DEV_PERF_POLICY_BOARD_LIMIT = 77 # Perf Policy Counter for Board Limit +NVML_FI_DEV_PERF_POLICY_LOW_UTILIZATION = 78 # Perf Policy Counter for Low GPU Utilization Policy +NVML_FI_DEV_PERF_POLICY_RELIABILITY = 79 # Perf Policy Counter for Reliability Policy +NVML_FI_DEV_PERF_POLICY_TOTAL_APP_CLOCKS = 80 # Perf Policy Counter for Total App Clock Policy +NVML_FI_DEV_PERF_POLICY_TOTAL_BASE_CLOCKS = 81 # Perf Policy Counter for Total Base Clocks Policy + +# Memory temperatures +NVML_FI_DEV_MEMORY_TEMP = 82 # Memory temperature for the device + +# Energy Counter +NVML_FI_DEV_TOTAL_ENERGY_CONSUMPTION = ( + 83 # Total energy consumption for the GPU in mJ since the driver was last reloaded +) + +# NVLink Speed +NVML_FI_DEV_NVLINK_SPEED_MBPS_L0 = 84 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L1 = 85 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L2 = 86 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L3 = 87 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L4 = 88 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L5 = 89 +NVML_FI_DEV_NVLINK_SPEED_MBPS_COMMON = 90 + +# NVLink Link Count +NVML_FI_DEV_NVLINK_LINK_COUNT = 91 + +# Page Retirement pending fields +NVML_FI_DEV_RETIRED_PENDING_SBE = 92 +NVML_FI_DEV_RETIRED_PENDING_DBE = 93 + +# PCIe replay and replay rollover counters +NVML_FI_DEV_PCIE_REPLAY_COUNTER = 94 +NVML_FI_DEV_PCIE_REPLAY_ROLLOVER_COUNTER = 95 + +# NvLink Flit Error Counters +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L6 = 96 # NVLink flow control CRC Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L7 = 97 # NVLink flow control CRC Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L8 = 98 # NVLink flow control CRC Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L9 = 99 # NVLink flow control CRC Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L10 = 100 # NVLink flow control CRC Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L11 = 101 # NVLink flow control CRC Error Counter for Lane 11 + +# NvLink CRC Data Error Counters +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L6 = 102 # NVLink data CRC Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L7 = 103 # NVLink data CRC Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L8 = 104 # NVLink data CRC Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L9 = 105 # NVLink data CRC Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L10 = 106 # NVLink data CRC Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L11 = 107 # NVLink data CRC Error Counter for Lane 11 + +# NvLink Replay Error Counters +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L6 = 108 # NVLink Replay Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L7 = 109 # NVLink Replay Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L8 = 110 # NVLink Replay Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L9 = 111 # NVLink Replay Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L10 = 112 # NVLink Replay Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L11 = 113 # NVLink Replay Error Counter for Lane 11 + +# NvLink Recovery Error Counters +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L6 = 114 # NVLink Recovery Error Counter for Lane 6 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L7 = 115 # NVLink Recovery Error Counter for Lane 7 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L8 = 116 # NVLink Recovery Error Counter for Lane 8 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L9 = 117 # NVLink Recovery Error Counter for Lane 9 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L10 = 118 # NVLink Recovery Error Counter for Lane 10 +NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L11 = 119 # NVLink Recovery Error Counter for Lane 11 + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L6 = 120 # NVLink Bandwidth Counter for Counter Set 0, Lane 6 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L7 = 121 # NVLink Bandwidth Counter for Counter Set 0, Lane 7 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L8 = 122 # NVLink Bandwidth Counter for Counter Set 0, Lane 8 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L9 = 123 # NVLink Bandwidth Counter for Counter Set 0, Lane 9 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L10 = 124 # NVLink Bandwidth Counter for Counter Set 0, Lane 10 +NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L11 = 125 # NVLink Bandwidth Counter for Counter Set 0, Lane 11 + +# NvLink Bandwidth Counters +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L6 = 126 # NVLink Bandwidth Counter for Counter Set 1, Lane 6 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L7 = 127 # NVLink Bandwidth Counter for Counter Set 1, Lane 7 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L8 = 128 # NVLink Bandwidth Counter for Counter Set 1, Lane 8 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L9 = 129 # NVLink Bandwidth Counter for Counter Set 1, Lane 9 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L10 = 130 # NVLink Bandwidth Counter for Counter Set 1, Lane 10 +NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L11 = 131 # NVLink Bandwidth Counter for Counter Set 1, Lane 11 + +# NVLink Speed +NVML_FI_DEV_NVLINK_SPEED_MBPS_L6 = 132 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L7 = 133 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L8 = 134 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L9 = 135 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L10 = 136 +NVML_FI_DEV_NVLINK_SPEED_MBPS_L11 = 137 + +# NVLink Throughput Counters +NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX = 138 # NVLink TX Data throughput in KiB +NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX = 139 # NVLink RX Data throughput in KiB +NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX = 140 # NVLink TX Data + protocol overhead in KiB +NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX = 141 # NVLink RX Data + protocol overhead in KiB + +# Row Remapper +NVML_FI_DEV_REMAPPED_COR = 142 +NVML_FI_DEV_REMAPPED_UNC = 143 +NVML_FI_DEV_REMAPPED_PENDING = 144 +NVML_FI_DEV_REMAPPED_FAILURE = 145 + +# Remote device NVLink ID +NVML_FI_DEV_NVLINK_REMOTE_NVLINK_ID = 146 + +# Number of NVLinks connected to NVSwitch +NVML_FI_DEV_NVSWITCH_CONNECTED_LINK_COUNT = 147 + +# NvLink ECC Data Error Counters +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L0 = 148 # < NVLink data ECC Error Counter for Link 0 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L1 = 149 # < NVLink data ECC Error Counter for Link 1 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L2 = 150 # < NVLink data ECC Error Counter for Link 2 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L3 = 151 # < NVLink data ECC Error Counter for Link 3 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L4 = 152 # < NVLink data ECC Error Counter for Link 4 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L5 = 153 # < NVLink data ECC Error Counter for Link 5 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L6 = 154 # < NVLink data ECC Error Counter for Link 6 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L7 = 155 # < NVLink data ECC Error Counter for Link 7 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L8 = 156 # < NVLink data ECC Error Counter for Link 8 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L9 = 157 # < NVLink data ECC Error Counter for Link 9 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L10 = 158 # < NVLink data ECC Error Counter for Link 10 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L11 = 159 # < NVLink data ECC Error Counter for Link 11 +NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_TOTAL = 160 # < NvLink data ECC Error Counter total for all Links + +NVML_FI_MAX = 161 # One greater than the largest field ID defined above + +## Enums needed for the method nvmlDeviceGetVirtualizationMode and nvmlDeviceSetVirtualizationMode +NVML_GPU_VIRTUALIZATION_MODE_NONE = 0 # Represents Bare Metal GPU +NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH = 1 # Device is associated with GPU-Passthorugh +NVML_GPU_VIRTUALIZATION_MODE_VGPU = 2 # Device is associated with vGPU inside virtual machine. +NVML_GPU_VIRTUALIZATION_MODE_HOST_VGPU = 3 # Device is associated with VGX hypervisor in vGPU mode +NVML_GPU_VIRTUALIZATION_MODE_HOST_VSGA = 4 # Device is associated with VGX hypervisor in vSGA mode + +## Lib loading ## +nvmlLib = None +libLoadLock = threading.Lock() +_nvmlLib_refcount = 0 # Incremented on each nvmlInit and decremented on nvmlShutdown + +## vGPU Management +_nvmlVgpuTypeId_t = c_uint +_nvmlVgpuInstance_t = c_uint + +_nvmlVgpuVmIdType_t = c_uint +NVML_VGPU_VM_ID_DOMAIN_ID = 0 +NVML_VGPU_VM_ID_UUID = 1 + +_nvmlGridLicenseFeatureCode_t = c_uint +NVML_GRID_LICENSE_FEATURE_CODE_UNKNOWN = 0 +NVML_GRID_LICENSE_FEATURE_CODE_VGPU = 1 +NVML_GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX = 2 +NVML_GRID_LICENSE_FEATURE_CODE_VWORKSTATION = 2 # deprecated, use NVML_GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX. +NVML_GRID_LICENSE_FEATURE_CODE_GAMING = 3 +NVML_GRID_LICENSE_FEATURE_CODE_COMPUTE = 4 + +_nvmlGridLicenseExpiryStatus_t = c_uint8 +NVML_GRID_LICENSE_EXPIRY_NOT_AVAILABLE = (0,) # Expiry information not available +NVML_GRID_LICENSE_EXPIRY_INVALID = (1,) # Invalid expiry or error fetching expiry +NVML_GRID_LICENSE_EXPIRY_VALID = (2,) # Valid expiry +NVML_GRID_LICENSE_EXPIRY_NOT_APPLICABLE = (3,) # Expiry not applicable +NVML_GRID_LICENSE_EXPIRY_PERMANENT = (4,) # Permanent expiry + +_nvmlVgpuCapability_t = c_uint +NVML_VGPU_CAP_NVLINK_P2P = 0 # vGPU P2P over NVLink is supported +NVML_VGPU_CAP_GPUDIRECT = 1 # GPUDirect capability is supported +NVML_VGPU_CAP_COUNT = 2 + +_nvmlVgpuGuestInfoState_t = c_uint +NVML_VGPU_INSTANCE_GUEST_INFO_STATE_UNINITIALIZED = 0 +NVML_VGPU_INSTANCE_GUEST_INFO_STATE_INITIALIZED = 1 + +_nvmlVgpuVmCompatibility_t = c_uint +NVML_VGPU_VM_COMPATIBILITY_NONE = 0x0 +NVML_VGPU_VM_COMPATIBILITY_COLD = 0x1 +NVML_VGPU_VM_COMPATIBILITY_HIBERNATE = 0x2 +NVML_VGPU_VM_COMPATIBILITY_SLEEP = 0x4 +NVML_VGPU_VM_COMPATIBILITY_LIVE = 0x8 + +_nvmlVgpuPgpuCompatibilityLimitCode_t = c_uint +NVML_VGPU_COMPATIBILITY_LIMIT_NONE = 0x0 +NVML_VGPU_COMPATIBILITY_LIMIT_HOST_DRIVER = 0x1 +NVML_VGPU_COMPATIBILITY_LIMIT_GUEST_DRIVER = 0x2 +NVML_VGPU_COMPATIBILITY_LIMIT_GPU = 0x4 +NVML_VGPU_COMPATIBILITY_LIMIT_OTHER = 0x80000000 + +_nvmlHostVgpuMode_t = c_uint +NVML_HOST_VGPU_MODE_NON_SRIOV = 0 +NVML_HOST_VGPU_MODE_SRIOV = 1 + +# GSP firmware +NVML_GSP_FIRMWARE_VERSION_BUF_SIZE = 0x40 + + +## Error Checking ## +class NVMLError(Exception): + _valClassMapping = dict() # type: ignore + # List of currently known error codes + _errcode_to_string = { + NVML_ERROR_UNINITIALIZED: "Uninitialized", + NVML_ERROR_INVALID_ARGUMENT: "Invalid Argument", + NVML_ERROR_NOT_SUPPORTED: "Not Supported", + NVML_ERROR_NO_PERMISSION: "Insufficient Permissions", + NVML_ERROR_ALREADY_INITIALIZED: "Already Initialized", + NVML_ERROR_NOT_FOUND: "Not Found", + NVML_ERROR_INSUFFICIENT_SIZE: "Insufficient Size", + NVML_ERROR_INSUFFICIENT_POWER: "Insufficient External Power", + NVML_ERROR_DRIVER_NOT_LOADED: "Driver Not Loaded", + NVML_ERROR_TIMEOUT: "Timeout", + NVML_ERROR_IRQ_ISSUE: "Interrupt Request Issue", + NVML_ERROR_LIBRARY_NOT_FOUND: "NVML Shared Library Not Found", + NVML_ERROR_FUNCTION_NOT_FOUND: "Function Not Found", + NVML_ERROR_CORRUPTED_INFOROM: "Corrupted infoROM", + NVML_ERROR_GPU_IS_LOST: "GPU is lost", + NVML_ERROR_RESET_REQUIRED: "GPU requires restart", + NVML_ERROR_OPERATING_SYSTEM: "The operating system has blocked the request.", + NVML_ERROR_LIB_RM_VERSION_MISMATCH: "RM has detected an NVML/RM version mismatch.", + NVML_ERROR_MEMORY: "Insufficient Memory", + NVML_ERROR_UNKNOWN: "Unknown Error", + } + + def __new__(typ, value): + """ + Maps value to a proper subclass of NVMLError. + See _extractNVMLErrorsAsClasses function for more details + """ + if typ == NVMLError: + typ = NVMLError._valClassMapping.get(value, typ) + obj = Exception.__new__(typ) + obj.value = value + return obj + + def __str__(self): + try: + if self.value not in NVMLError._errcode_to_string: + NVMLError._errcode_to_string[self.value] = str(nvmlErrorString(self.value)) + return NVMLError._errcode_to_string[self.value] + except NVMLError: + return "NVML Error with code %d" % self.value + + def __eq__(self, other): + return self.value == other.value + + +def nvmlExceptionClass(nvmlErrorCode): + if nvmlErrorCode not in NVMLError._valClassMapping: + raise ValueError("nvmlErrorCode %s is not valid" % nvmlErrorCode) + return NVMLError._valClassMapping[nvmlErrorCode] + + +def _extractNVMLErrorsAsClasses(): + """ + Generates a hierarchy of classes on top of NVMLError class. + + Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate + exceptions more easily. + + NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass. + e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized + """ + this_module = sys.modules[__name__] + nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")] + for err_name in nvmlErrorsNames: + # e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized + class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "") + err_val = getattr(this_module, err_name) + + def gen_new(val): + def new(typ): + obj = NVMLError.__new__(typ, val) + return obj + + return new + + new_error_class = type(class_name, (NVMLError,), {"__new__": gen_new(err_val)}) + new_error_class.__module__ = __name__ + setattr(this_module, class_name, new_error_class) + NVMLError._valClassMapping[err_val] = new_error_class + + +_extractNVMLErrorsAsClasses() + + +def _nvmlCheckReturn(ret): + if ret != NVML_SUCCESS: + raise NVMLError(ret) + return ret + + +## Function access ## +_nvmlGetFunctionPointer_cache = ( # type: ignore + dict() +) # function pointers are cached to prevent unnecessary libLoadLock locking + + +def _nvmlGetFunctionPointer(name): + global nvmlLib + + if name in _nvmlGetFunctionPointer_cache: + return _nvmlGetFunctionPointer_cache[name] + + libLoadLock.acquire() + try: + # ensure library was loaded + if nvmlLib == None: + raise NVMLError(NVML_ERROR_UNINITIALIZED) + try: + _nvmlGetFunctionPointer_cache[name] = getattr(nvmlLib, name) + return _nvmlGetFunctionPointer_cache[name] + except AttributeError: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + finally: + # lock is always freed + libLoadLock.release() + + +## Alternative object +# Allows the object to be printed +# Allows mismatched types to be assigned +# - like None when the Structure variant requires c_uint +class nvmlFriendlyObject: + def __init__(self, dictionary): + for x in dictionary: + setattr(self, x, dictionary[x]) + + def __str__(self): + return self.__dict__.__str__() + + +def nvmlStructToFriendlyObject(struct): + d = {} + for x in struct._fields_: + key = x[0] + value = getattr(struct, key) + # only need to convert from bytes if bytes, no need to check python version. + d[key] = value.decode() if isinstance(value, bytes) else value + obj = nvmlFriendlyObject(d) + return obj + + +# pack the object so it can be passed to the NVML library +def nvmlFriendlyObjectToStruct(obj, model): + for x in model._fields_: + key = x[0] + value = obj.__dict__[key] + # any c_char_p in python3 needs to be bytes, default encoding works fine. + setattr(model, key, value.encode()) + return model + + +## Unit structures +class struct_c_nvmlUnit_t(Structure): + pass # opaque handle + + +c_nvmlUnit_t = POINTER(struct_c_nvmlUnit_t) + + +class _PrintableStructure(Structure): + """ + Abstract class that produces nicer __str__ output than ctypes.Structure. + e.g. instead of: + >>> print str(obj) + + this class will print + class_name(field_name: formatted_value, field_name: formatted_value) + + _fmt_ dictionary of -> + e.g. class that has _field_ 'hex_value', c_uint could be formatted with + _fmt_ = {"hex_value" : "%08X"} + to produce nicer output. + Default fomratting string for all fields can be set with key "" like: + _fmt_ = {"" : "%d MHz"} # e.g all values are numbers in MHz. + If not set it's assumed to be just "%s" + + Exact format of returned str from this class is subject to change in the future. + """ + + _fmt_ = {} # type: ignore + + def __str__(self): + result = [] + for x in self._fields_: + key = x[0] + value = getattr(self, key) + fmt = "%s" + if key in self._fmt_: + fmt = self._fmt_[key] + elif "" in self._fmt_: + fmt = self._fmt_[""] + result.append(("%s: " + fmt) % (key, value)) + return self.__class__.__name__ + "(" + ", ".join(result) + ")" + + def __getattribute__(self, name): + res = super().__getattribute__(name) + # need to convert bytes to unicode for python3 don't need to for python2 + # Python 2 strings are of both str and bytes + # Python 3 strings are not of type bytes + # ctypes should convert everything to the correct values otherwise + if isinstance(res, bytes): + if isinstance(res, str): + return res + return res.decode() + return res + + def __setattr__(self, name, value): + if isinstance(value, str): + # encoding a python2 string returns the same value, since python2 strings are bytes already + # bytes passed in python3 will be ignored. + value = value.encode() + super().__setattr__(name, value) + + +class c_nvmlUnitInfo_t(_PrintableStructure): + _fields_ = [ + ("name", c_char * 96), + ("id", c_char * 96), + ("serial", c_char * 96), + ("firmwareVersion", c_char * 96), + ] + + +class c_nvmlLedState_t(_PrintableStructure): + _fields_ = [ + ("cause", c_char * 256), + ("color", _nvmlLedColor_t), + ] + + +class c_nvmlPSUInfo_t(_PrintableStructure): + _fields_ = [ + ("state", c_char * 256), + ("current", c_uint), + ("voltage", c_uint), + ("power", c_uint), + ] + + +class c_nvmlUnitFanInfo_t(_PrintableStructure): + _fields_ = [ + ("speed", c_uint), + ("state", _nvmlFanState_t), + ] + + +class c_nvmlUnitFanSpeeds_t(_PrintableStructure): + _fields_ = [("fans", c_nvmlUnitFanInfo_t * 24), ("count", c_uint)] + + +## Device structures +class struct_c_nvmlDevice_t(Structure): + pass # opaque handle + + +c_nvmlDevice_t = POINTER(struct_c_nvmlDevice_t) + + +# Legacy pciInfo used for _v1 and _v2 +class nvmlPciInfo_v2_t(_PrintableStructure): + _fields_ = [ + ("busId", c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE), + ("domain", c_uint), + ("bus", c_uint), + ("device", c_uint), + ("pciDeviceId", c_uint), + # Added in 2.285 + ("pciSubSystemId", c_uint), + ("reserved0", c_uint), + ("reserved1", c_uint), + ("reserved2", c_uint), + ("reserved3", c_uint), + ] + _fmt_ = { + "domain": "0x%04X", + "bus": "0x%02X", + "device": "0x%02X", + "pciDeviceId": "0x%08X", + "pciSubSystemId": "0x%08X", + } + + +class nvmlPciInfo_t(_PrintableStructure): + _fields_ = [ + # Moved to the new busId location below + ("busIdLegacy", c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE), + ("domain", c_uint), + ("bus", c_uint), + ("device", c_uint), + ("pciDeviceId", c_uint), + # Added in 2.285 + ("pciSubSystemId", c_uint), + # New busId replaced the long deprecated and reserved fields with a + # field of the same size in 9.0 + ("busId", c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE), + ] + _fmt_ = { + "domain": "0x%08X", + "bus": "0x%02X", + "device": "0x%02X", + "pciDeviceId": "0x%08X", + "pciSubSystemId": "0x%08X", + } + + +class c_nvmlExcludedDeviceInfo_t(_PrintableStructure): + _fields_ = [("pci", nvmlPciInfo_t), ("uuid", c_char * NVML_DEVICE_UUID_BUFFER_SIZE)] + + +class nvmlNvLinkUtilizationControl_t(_PrintableStructure): + _fields_ = [ + ("units", _nvmlNvLinkUtilizationCountUnits_t), + ("pktfilter", _nvmlNvLinkUtilizationCountPktTypes_t), + ] + + +class c_nvmlMemory_t(_PrintableStructure): + _fields_ = [ + ("total", c_ulonglong), + ("free", c_ulonglong), + ("used", c_ulonglong), + ] + _fmt_ = {"": "%d B"} + + +class c_nvmlMemory_v2_t(_PrintableStructure): + _fields_ = [ + ("version", c_uint), + ("total", c_ulonglong), + ("reserved", c_ulonglong), + ("free", c_ulonglong), + ("used", c_ulonglong), + ] + _fmt_ = {"": "%d B"} + + +nvmlMemory_v2 = 0x02000028 + + +class c_nvmlBAR1Memory_t(_PrintableStructure): + _fields_ = [ + ("bar1Total", c_ulonglong), + ("bar1Free", c_ulonglong), + ("bar1Used", c_ulonglong), + ] + _fmt_ = {"": "%d B"} + + +class nvmlClkMonFaultInfo_t(Structure): + _fields_ = [("clkApiDomain", c_uint), ("clkDomainFaultMask", c_uint)] + + +class nvmlClkMonStatus_t(Structure): + _fields_ = [ + ("bGlobalStatus", c_uint), + ("clkMonListSize", c_uint), + ("clkMonList", nvmlClkMonFaultInfo_t), + ] + + +# On Windows with the WDDM driver, usedGpuMemory is reported as None +# Code that processes this structure should check for None, I.E. +# +# if (info.usedGpuMemory == None): +# # TODO handle the error +# pass +# else: +# print("Using %d MiB of memory" % (info.usedGpuMemory / 1024 / 1024)) +# endif +# +# See NVML documentation for more information +class c_nvmlProcessInfo_t(_PrintableStructure): + _fields_ = [ + ("pid", c_uint), + ("usedGpuMemory", c_ulonglong), + ("gpuInstanceId", c_uint), + ("computeInstanceId", c_uint), + ] + _fmt_ = { + "usedGpuMemory": "%d B", + } + + +class c_nvmlBridgeChipInfo_t(_PrintableStructure): + _fields_ = [ + ("type", _nvmlBridgeChipType_t), + ("fwVersion", c_uint), + ] + + +class c_nvmlBridgeChipHierarchy_t(_PrintableStructure): + _fields_ = [ + ("bridgeCount", c_uint), + ("bridgeChipInfo", c_nvmlBridgeChipInfo_t * 128), + ] + + +class c_nvmlEccErrorCounts_t(_PrintableStructure): + _fields_ = [ + ("l1Cache", c_ulonglong), + ("l2Cache", c_ulonglong), + ("deviceMemory", c_ulonglong), + ("registerFile", c_ulonglong), + ] + + +class c_nvmlUtilization_t(_PrintableStructure): + _fields_ = [ + ("gpu", c_uint), + ("memory", c_uint), + ] + _fmt_ = {"": "%d %%"} + + +# Added in 2.285 +class c_nvmlHwbcEntry_t(_PrintableStructure): + _fields_ = [ + ("hwbcId", c_uint), + ("firmwareVersion", c_char * 32), + ] + + +class c_nvmlValue_t(Union): + _fields_ = [ + ("dVal", c_double), + ("uiVal", c_uint), + ("ulVal", c_ulong), + ("ullVal", c_ulonglong), + ("sllVal", c_longlong), + ] + + +class c_nvmlSample_t(_PrintableStructure): + _fields_ = [ + ("timeStamp", c_ulonglong), + ("sampleValue", c_nvmlValue_t), + ] + + +class c_nvmlViolationTime_t(_PrintableStructure): + _fields_ = [ + ("referenceTime", c_ulonglong), + ("violationTime", c_ulonglong), + ] + + +class c_nvmlFieldValue_t(_PrintableStructure): + _fields_ = [ + ("fieldId", c_uint32), + ("scopeId", c_uint32), + ("timestamp", c_int64), + ("latencyUsec", c_int64), + ("valueType", _nvmlValueType_t), + ("nvmlReturn", _nvmlReturn_t), + ("value", c_nvmlValue_t), + ] + + +class c_nvmlVgpuInstanceUtilizationSample_t(_PrintableStructure): + _fields_ = [ + ("vgpuInstance", _nvmlVgpuInstance_t), + ("timeStamp", c_ulonglong), + ("smUtil", c_nvmlValue_t), + ("memUtil", c_nvmlValue_t), + ("encUtil", c_nvmlValue_t), + ("decUtil", c_nvmlValue_t), + ] + + +class c_nvmlVgpuProcessUtilizationSample_t(_PrintableStructure): + _fields_ = [ + ("vgpuInstance", _nvmlVgpuInstance_t), + ("pid", c_uint), + ("processName", c_char * NVML_VGPU_NAME_BUFFER_SIZE), + ("timeStamp", c_ulonglong), + ("smUtil", c_uint), + ("memUtil", c_uint), + ("encUtil", c_uint), + ("decUtil", c_uint), + ] + + +class c_nvmlVgpuLicenseExpiry_t(_PrintableStructure): + _fields_ = [ + ("year", c_uint32), + ("month", c_uint16), + ("day", c_uint16), + ("hour", c_uint16), + ("min", c_uint16), + ("sec", c_uint16), + ("status", c_uint8), + ] + + +NVML_GRID_LICENSE_STATE_UNKNOWN = 0 +NVML_GRID_LICENSE_STATE_UNINITIALIZED = 1 +NVML_GRID_LICENSE_STATE_UNLICENSED_UNRESTRICTED = 2 +NVML_GRID_LICENSE_STATE_UNLICENSED_RESTRICTED = 3 +NVML_GRID_LICENSE_STATE_UNLICENSED = 4 +NVML_GRID_LICENSE_STATE_LICENSED = 5 + + +class c_nvmlVgpuLicenseInfo_t(_PrintableStructure): + _fields_ = [ + ("isLicensed", c_uint8), + ("licenseExpiry", c_nvmlVgpuLicenseExpiry_t), + ("currentState", c_uint), + ] + + +class c_nvmlEncoderSession_t(_PrintableStructure): + _fields_ = [ + ("sessionId", c_uint), + ("pid", c_uint), + ("vgpuInstance", _nvmlVgpuInstance_t), + ("codecType", c_uint), + ("hResolution", c_uint), + ("vResolution", c_uint), + ("averageFps", c_uint), + ("encodeLatency", c_uint), + ] + + +class c_nvmlProcessUtilizationSample_t(_PrintableStructure): + _fields_ = [ + ("pid", c_uint), + ("timeStamp", c_ulonglong), + ("smUtil", c_uint), + ("memUtil", c_uint), + ("encUtil", c_uint), + ("decUtil", c_uint), + ] + + +class c_nvmlGridLicenseExpiry_t(_PrintableStructure): + _fields_ = [ + ("year", c_uint32), + ("month", c_uint16), + ("day", c_uint16), + ("hour", c_uint16), + ("min", c_uint16), + ("sec", c_uint16), + ("status", c_uint8), + ] + + +class c_nvmlGridLicensableFeature_v4_t(_PrintableStructure): + _fields_ = [ + ("featureCode", _nvmlGridLicenseFeatureCode_t), + ("featureState", c_uint), + ("licenseInfo", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ("productName", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ("featureEnabled", c_uint), + ("licenseExpiry", c_nvmlGridLicenseExpiry_t), + ] + + +class c_nvmlGridLicensableFeatures_v4_t(_PrintableStructure): + _fields_ = [ + ("isGridLicenseSupported", c_int), + ("licensableFeaturesCount", c_uint), + ( + "gridLicensableFeatures", + c_nvmlGridLicensableFeature_v4_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT, + ), + ] + + +class c_nvmlGridLicensableFeature_v3_t(_PrintableStructure): + _fields_ = [ + ("featureCode", _nvmlGridLicenseFeatureCode_t), + ("featureState", c_uint), + ("licenseInfo", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ("productName", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ("featureEnabled", c_uint), + ] + + +class c_nvmlGridLicensableFeatures_v3_t(_PrintableStructure): + _fields_ = [ + ("isGridLicenseSupported", c_int), + ("licensableFeaturesCount", c_uint), + ( + "gridLicensableFeatures", + c_nvmlGridLicensableFeature_v3_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT, + ), + ] + + +class c_nvmlGridLicensableFeature_v2_t(_PrintableStructure): + _fields_ = [ + ("featureCode", _nvmlGridLicenseFeatureCode_t), + ("featureState", c_uint), + ("licenseInfo", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ("productName", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ] + + +class c_nvmlGridLicensableFeatures_v2_t(_PrintableStructure): + _fields_ = [ + ("isGridLicenseSupported", c_int), + ("licensableFeaturesCount", c_uint), + ( + "gridLicensableFeatures", + c_nvmlGridLicensableFeature_v2_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT, + ), + ] + + +class c_nvmlGridLicensableFeature_t(_PrintableStructure): + _fields_ = [ + ("featureCode", _nvmlGridLicenseFeatureCode_t), + ("featureState", c_uint), + ("licenseInfo", c_char * NVML_GRID_LICENSE_BUFFER_SIZE), + ] + + +class c_nvmlGridLicensableFeatures_t(_PrintableStructure): + _fields_ = [ + ("isGridLicenseSupported", c_int), + ("licensableFeaturesCount", c_uint), + ( + "gridLicensableFeatures", + c_nvmlGridLicensableFeature_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT, + ), + ] + + +## Event structures +class struct_c_nvmlEventSet_t(Structure): + pass # opaque handle + + +c_nvmlEventSet_t = POINTER(struct_c_nvmlEventSet_t) + +nvmlEventTypeSingleBitEccError = 0x0000000000000001 +nvmlEventTypeDoubleBitEccError = 0x0000000000000002 +nvmlEventTypePState = 0x0000000000000004 +nvmlEventTypeXidCriticalError = 0x0000000000000008 +nvmlEventTypeClock = 0x0000000000000010 +nvmlEventTypePowerSourceChange = 0x0000000000000080 +nvmlEventMigConfigChange = 0x0000000000000100 +nvmlEventTypeNone = 0x0000000000000000 +nvmlEventTypeAll = ( + nvmlEventTypeNone + | nvmlEventTypeSingleBitEccError + | nvmlEventTypeDoubleBitEccError + | nvmlEventTypePState + | nvmlEventTypeClock + | nvmlEventTypePowerSourceChange + | nvmlEventTypeXidCriticalError + | nvmlEventMigConfigChange +) + +## Clock Throttle Reasons defines +nvmlClocksThrottleReasonGpuIdle = 0x0000000000000001 +nvmlClocksThrottleReasonApplicationsClocksSetting = 0x0000000000000002 +nvmlClocksThrottleReasonUserDefinedClocks = nvmlClocksThrottleReasonApplicationsClocksSetting # deprecated, use nvmlClocksThrottleReasonApplicationsClocksSetting +nvmlClocksThrottleReasonSwPowerCap = 0x0000000000000004 +nvmlClocksThrottleReasonHwSlowdown = 0x0000000000000008 +nvmlClocksThrottleReasonSyncBoost = 0x0000000000000010 +nvmlClocksThrottleReasonSwThermalSlowdown = 0x0000000000000020 +nvmlClocksThrottleReasonHwThermalSlowdown = 0x0000000000000040 +nvmlClocksThrottleReasonHwPowerBrakeSlowdown = 0x0000000000000080 +nvmlClocksThrottleReasonDisplayClockSetting = 0x0000000000000100 +nvmlClocksThrottleReasonNone = 0x0000000000000000 +nvmlClocksThrottleReasonAll = ( + nvmlClocksThrottleReasonNone + | nvmlClocksThrottleReasonGpuIdle + | nvmlClocksThrottleReasonApplicationsClocksSetting + | nvmlClocksThrottleReasonSwPowerCap + | nvmlClocksThrottleReasonHwSlowdown + | nvmlClocksThrottleReasonSyncBoost + | nvmlClocksThrottleReasonSwThermalSlowdown + | nvmlClocksThrottleReasonHwThermalSlowdown + | nvmlClocksThrottleReasonHwPowerBrakeSlowdown + | nvmlClocksThrottleReasonDisplayClockSetting +) + + +class c_nvmlEventData_t(_PrintableStructure): + _fields_ = [ + ("device", c_nvmlDevice_t), + ("eventType", c_ulonglong), + ("eventData", c_ulonglong), + ("gpuInstanceId", c_uint), + ("computeInstanceId", c_uint), + ] + _fmt_ = {"eventType": "0x%08X"} + + +class c_nvmlAccountingStats_t(_PrintableStructure): + _fields_ = [ + ("gpuUtilization", c_uint), + ("memoryUtilization", c_uint), + ("maxMemoryUsage", c_ulonglong), + ("time", c_ulonglong), + ("startTime", c_ulonglong), + ("isRunning", c_uint), + ("reserved", c_uint * 5), + ] + + +class c_nvmlVgpuVersion_t(Structure): + _fields_ = [("minVersion", c_uint), ("maxVersion", c_uint)] + + +class c_nvmlVgpuMetadata_t(Structure): + _fields_ = [ + ("version", c_uint), + ("revision", c_uint), + ("guestInfoState", _nvmlVgpuGuestInfoState_t), + ("guestDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ("hostDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ("reserved", c_uint * 6), + ("vgpuVirtualizationCaps", c_uint), + ("guestVgpuVersion", c_uint), + ("opaqueDataSize", c_uint), + ("opaqueData", c_char * NVML_VGPU_METADATA_OPAQUE_DATA_SIZE), + ] + + +class c_nvmlVgpuPgpuMetadata_t(Structure): + _fields_ = [ + ("version", c_uint), + ("revision", c_uint), + ("hostDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), + ("pgpuVirtualizationCaps", c_uint), + ("reserved", c_uint * 5), + ("hostSupportedVgpuRange", c_nvmlVgpuVersion_t), + ("opaqueDataSize", c_uint), + ("opaqueData", c_char * NVML_VGPU_PGPU_METADATA_OPAQUE_DATA_SIZE), + ] + + +class c_nvmlVgpuPgpuCompatibility_t(Structure): + _fields_ = [ + ("vgpuVmCompatibility", _nvmlVgpuVmCompatibility_t), + ("compatibilityLimitCode", _nvmlVgpuPgpuCompatibilityLimitCode_t), + ] + + +class c_nvmlFBCStats_t(Structure): + _fields_ = [ + ("sessionsCount", c_uint), + ("averageFPS", c_uint), + ("averageLatency", c_uint), + ] + + +class c_nvmlFBCSession_t(_PrintableStructure): + _fields_ = [ + ("sessionId", c_uint), + ("pid", c_uint), + ("vgpuInstance", _nvmlVgpuInstance_t), + ("displayOrdinal", c_uint), + ("sessionType", c_uint), + ("sessionFlags", c_uint), + ("hMaxResolution", c_uint), + ("vMaxResolution", c_uint), + ("hResolution", c_uint), + ("vResolution", c_uint), + ("averageFPS", c_uint), + ("averageLatency", c_uint), + ] + + +NVML_DEVICE_MIG_DISABLE = 0x0 +NVML_DEVICE_MIG_ENABLE = 0x1 + +NVML_GPU_INSTANCE_PROFILE_1_SLICE = 0x0 +NVML_GPU_INSTANCE_PROFILE_2_SLICE = 0x1 +NVML_GPU_INSTANCE_PROFILE_3_SLICE = 0x2 +NVML_GPU_INSTANCE_PROFILE_4_SLICE = 0x3 +NVML_GPU_INSTANCE_PROFILE_7_SLICE = 0x4 +NVML_GPU_INSTANCE_PROFILE_8_SLICE = 0x5 +NVML_GPU_INSTANCE_PROFILE_6_SLICE = 0x6 +NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV1 = 0x7 +NVML_GPU_INSTANCE_PROFILE_COUNT = 0x8 + + +class c_nvmlGpuInstancePlacement_t(Structure): + _fields_ = [("start", c_uint), ("size", c_uint)] + + +class c_nvmlGpuInstanceProfileInfo_t(Structure): + _fields_ = [ + ("id", c_uint), + ("isP2pSupported", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("copyEngineCount", c_uint), + ("decoderCount", c_uint), + ("encoderCount", c_uint), + ("jpegCount", c_uint), + ("ofaCount", c_uint), + ("memorySizeMB", c_ulonglong), + ] + + +nvmlGpuInstanceProfileInfo_v2 = 0x02000098 + + +class c_nvmlGpuInstanceProfileInfo_v2_t(Structure): + _fields_ = [ + ("version", c_uint), + ("id", c_uint), + ("isP2pSupported", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("copyEngineCount", c_uint), + ("decoderCount", c_uint), + ("encoderCount", c_uint), + ("jpegCount", c_uint), + ("ofaCount", c_uint), + ("memorySizeMB", c_ulonglong), + ("name", c_char * NVML_DEVICE_NAME_V2_BUFFER_SIZE), + ] + + def __init__(self): + super().__init__(version=nvmlGpuInstanceProfileInfo_v2) + + +class c_nvmlGpuInstanceInfo_t(Structure): + _fields_ = [ + ("device", c_nvmlDevice_t), + ("id", c_uint), + ("profileId", c_uint), + ("placement", c_nvmlGpuInstancePlacement_t), + ] + + +class struct_c_nvmlGpuInstance_t(Structure): + pass # opaque handle + + +c_nvmlGpuInstance_t = POINTER(struct_c_nvmlGpuInstance_t) + +NVML_COMPUTE_INSTANCE_PROFILE_1_SLICE = 0x0 +NVML_COMPUTE_INSTANCE_PROFILE_2_SLICE = 0x1 +NVML_COMPUTE_INSTANCE_PROFILE_3_SLICE = 0x2 +NVML_COMPUTE_INSTANCE_PROFILE_4_SLICE = 0x3 +NVML_COMPUTE_INSTANCE_PROFILE_7_SLICE = 0x4 +NVML_COMPUTE_INSTANCE_PROFILE_8_SLICE = 0x5 +NVML_COMPUTE_INSTANCE_PROFILE_6_SLICE = 0x6 +NVML_COMPUTE_INSTANCE_PROFILE_COUNT = 0x7 + +NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_SHARED = 0x0 +NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT = 0x1 + + +class c_nvmlComputeInstancePlacement_t(Structure): + _fields_ = [("start", c_uint), ("size", c_uint)] + + +class c_nvmlComputeInstanceProfileInfo_t(Structure): + _fields_ = [ + ("id", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("sharedCopyEngineCount", c_uint), + ("sharedDecoderCount", c_uint), + ("sharedEncoderCount", c_uint), + ("sharedJpegCount", c_uint), + ("sharedOfaCount", c_uint), + ] + + +nvmlComputeInstanceProfileInfo_v2 = 0x02000088 + + +class c_nvmlComputeInstanceProfileInfo_v2_t(Structure): + _fields_ = [ + ("version", c_uint), + ("id", c_uint), + ("sliceCount", c_uint), + ("instanceCount", c_uint), + ("multiprocessorCount", c_uint), + ("sharedCopyEngineCount", c_uint), + ("sharedDecoderCount", c_uint), + ("sharedEncoderCount", c_uint), + ("sharedJpegCount", c_uint), + ("sharedOfaCount", c_uint), + ("name", c_char * NVML_DEVICE_NAME_V2_BUFFER_SIZE), + ] + + def __init__(self): + super().__init__(version=nvmlComputeInstanceProfileInfo_v2) + + +class c_nvmlComputeInstanceInfo_t(Structure): + _fields_ = [ + ("device", c_nvmlDevice_t), + ("gpuInstance", c_nvmlGpuInstance_t), + ("id", c_uint), + ("profileId", c_uint), + ("placement", c_nvmlComputeInstancePlacement_t), + ] + + +NVML_MAX_GPU_UTILIZATIONS = 8 +NVML_GPU_UTILIZATION_DOMAIN_GPU = 0 +NVML_GPU_UTILIZATION_DOMAIN_FB = 1 +NVML_GPU_UTILIZATION_DOMAIN_VID = 2 +NVML_GPU_UTILIZATION_DOMAIN_BUS = 3 + + +class c_nvmlGpuDynamicPstatesUtilization_t(Structure): + _fields_ = [ + ("bIsPresent", c_uint, 1), + ("percentage", c_uint), + ("incThreshold", c_uint), + ("decThreshold", c_uint), + ] + + +class c_nvmlGpuDynamicPstatesInfo_t(Structure): + _fields_ = [ + ("flags", c_uint), + ( + "utilization", + c_nvmlGpuDynamicPstatesUtilization_t * NVML_MAX_GPU_UTILIZATIONS, + ), + ] + + +NVML_MAX_THERMAL_SENSORS_PER_GPU = 3 + +NVML_THERMAL_TARGET_NONE = 0 +NVML_THERMAL_TARGET_GPU = 1 +NVML_THERMAL_TARGET_MEMORY = 2 +NVML_THERMAL_TARGET_POWER_SUPPLY = 4 +NVML_THERMAL_TARGET_BOARD = 8 +NVML_THERMAL_TARGET_VCD_BOARD = 9 +NVML_THERMAL_TARGET_VCD_INLET = 10 +NVML_THERMAL_TARGET_VCD_OUTLET = 11 +NVML_THERMAL_TARGET_ALL = 15 +NVML_THERMAL_TARGET_UNKNOWN = -1 + +NVML_THERMAL_CONTROLLER_NONE = 0 +NVML_THERMAL_CONTROLLER_GPU_INTERNAL = 1 +NVML_THERMAL_CONTROLLER_ADM1032 = 2 +NVML_THERMAL_CONTROLLER_ADT7461 = 3 +NVML_THERMAL_CONTROLLER_MAX6649 = 4 +NVML_THERMAL_CONTROLLER_MAX1617 = 5 +NVML_THERMAL_CONTROLLER_LM99 = 6 +NVML_THERMAL_CONTROLLER_LM89 = 7 +NVML_THERMAL_CONTROLLER_LM64 = 8 +NVML_THERMAL_CONTROLLER_G781 = 9 +NVML_THERMAL_CONTROLLER_ADT7473 = 10 +NVML_THERMAL_CONTROLLER_SBMAX6649 = 11 +NVML_THERMAL_CONTROLLER_VBIOSEVT = 12 +NVML_THERMAL_CONTROLLER_OS = 13 +NVML_THERMAL_CONTROLLER_NVSYSCON_CANOAS = 14 +NVML_THERMAL_CONTROLLER_NVSYSCON_E551 = 15 +NVML_THERMAL_CONTROLLER_MAX6649R = 16 +NVML_THERMAL_CONTROLLER_ADT7473S = 17 +NVML_THERMAL_CONTROLLER_UNKNOWN = -1 + + +class c_nvmlGpuThermalSensor_t(Structure): + _fields_ = [ + ("controller", c_int), + ("defaultMinTemp", c_uint), + ("defaultMaxTemp", c_uint), + ("currentTemp", c_uint), + ("target", c_int), + ] + + +class c_nvmlGpuThermalSettings_t(Structure): + _fields_ = [ + ("count", c_uint), + ("sensor", c_nvmlGpuThermalSensor_t * NVML_MAX_THERMAL_SENSORS_PER_GPU), + ] + + +class struct_c_nvmlComputeInstance_t(Structure): + pass # opaque handle + + +c_nvmlComputeInstance_t = POINTER(struct_c_nvmlComputeInstance_t) + + +class c_nvmlDeviceAttributes(Structure): + _fields_ = [ + ("multiprocessorCount", c_uint), + ("sharedCopyEngineCount", c_uint), + ("sharedDecoderCount", c_uint), + ("sharedEncoderCount", c_uint), + ("sharedJpegCount", c_uint), + ("sharedOfaCount", c_uint), + ("gpuInstanceSliceCount", c_uint), + ("computeInstanceSliceCount", c_uint), + ("memorySizeMB", c_ulonglong), + ] + + +class c_nvmlRowRemapperHistogramValues(Structure): + _fields_ = [ + ("max", c_uint), + ("high", c_uint), + ("partial", c_uint), + ("low", c_uint), + ("none", c_uint), + ] + + +## string/bytes conversion for ease of use +def convertStrBytes(func): + """ + In python 3, strings are unicode instead of bytes, and need to be converted for ctypes + Args from caller: (1, 'string', <__main__.c_nvmlDevice_t at 0xFFFFFFFF>) + Args passed to function: (1, b'string', <__main__.c_nvmlDevice_t at 0xFFFFFFFF)> + ---- + Returned from function: b'returned string' + Returned to caller: 'returned string' + """ + + @wraps(func) + def wrapper(*args, **kwargs): + # encoding a str returns bytes in python 2 and 3 + args = [arg.encode() if isinstance(arg, str) else arg for arg in args] + res = func(*args, **kwargs) + # In python 2, str and bytes are the same + # In python 3, str is unicode and should be decoded. + # Ctypes handles most conversions, this only effects c_char and char arrays. + if isinstance(res, bytes): + if isinstance(res, str): + return res + return res.decode() + return res + + return wrapper + return func + + +## C function wrappers ## +def nvmlInitWithFlags(flags): + _LoadNvmlLibrary() + + # + # Initialize the library + # + fn = _nvmlGetFunctionPointer("nvmlInitWithFlags") + ret = fn(flags) + _nvmlCheckReturn(ret) + + # Atomically update refcount + global _nvmlLib_refcount + libLoadLock.acquire() + _nvmlLib_refcount += 1 + libLoadLock.release() + return None + + +def nvmlInit(): + nvmlInitWithFlags(0) + return None + + +def _LoadNvmlLibrary(): + """ + Load the library if it isn't loaded already + """ + global nvmlLib + + if nvmlLib is None: + # lock to ensure only one caller loads the library + libLoadLock.acquire() + + try: + # ensure the library still isn't loaded + if nvmlLib is None: + if sys.platform[:3] == "win": + # cdecl calling convention + # First, check for nvml.dll in System32 first for DCH drivers. + # If nvml.dll is not found in System32, it should be in ProgramFiles + # load nvml.dll from %ProgramFiles%/NVIDIA Corporation/NVSMI/nvml.dll + search_paths = [ + os.path.join(os.getenv("WINDIR", "C:/Windows"), "System32/nvml.dll"), + os.path.join( + os.getenv("ProgramFiles", "C:/Program Files"), + "NVIDIA Corporation/NVSMI/nvml.dll", + ), + ] + # Finally, it may be overridden by an environment variable + nvml_path = os.getenv("NVML_DLL_PATH") + if nvml_path is not None: + search_paths.append(nvml_path) + for dll_path in search_paths: + try: + nvmlLib = CDLL(dll_path) + except OSError: + continue + break + else: + # assume linux + try: + nvmlLib = CDLL("libnvidia-ml.so.1") + except OSError: + _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND) + if nvmlLib is None: + _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND) + finally: + # lock is always freed + libLoadLock.release() + + +def nvmlShutdown(): + # + # Leave the library loaded, but shutdown the interface + # + fn = _nvmlGetFunctionPointer("nvmlShutdown") + ret = fn() + _nvmlCheckReturn(ret) + + # Atomically update refcount + global _nvmlLib_refcount + libLoadLock.acquire() + if 0 < _nvmlLib_refcount: + _nvmlLib_refcount -= 1 + libLoadLock.release() + return None + + +# Added in 2.285 +@convertStrBytes +def nvmlErrorString(result): + fn = _nvmlGetFunctionPointer("nvmlErrorString") + fn.restype = c_char_p # otherwise return is an int + ret = fn(result) + return ret + + +# Added in 2.285 +@convertStrBytes +def nvmlSystemGetNVMLVersion(): + c_version = create_string_buffer(NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlSystemGetNVMLVersion") + ret = fn(c_version, c_uint(NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + + +def nvmlSystemGetCudaDriverVersion(): + c_cuda_version = c_int() + fn = _nvmlGetFunctionPointer("nvmlSystemGetCudaDriverVersion") + ret = fn(byref(c_cuda_version)) + _nvmlCheckReturn(ret) + return c_cuda_version.value + + +def nvmlSystemGetCudaDriverVersion_v2(): + c_cuda_version = c_int() + fn = _nvmlGetFunctionPointer("nvmlSystemGetCudaDriverVersion_v2") + ret = fn(byref(c_cuda_version)) + _nvmlCheckReturn(ret) + return c_cuda_version.value + + +# Added in 2.285 +@convertStrBytes +def nvmlSystemGetProcessName(pid): + c_name = create_string_buffer(1024) + fn = _nvmlGetFunctionPointer("nvmlSystemGetProcessName") + ret = fn(c_uint(pid), c_name, c_uint(1024)) + _nvmlCheckReturn(ret) + return c_name.value + + +@convertStrBytes +def nvmlSystemGetDriverVersion(): + c_version = create_string_buffer(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlSystemGetDriverVersion") + ret = fn(c_version, c_uint(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + + +# Added in 2.285 +def nvmlSystemGetHicVersion(): + c_count = c_uint(0) + hics = None + fn = _nvmlGetFunctionPointer("nvmlSystemGetHicVersion") + + # get the count + ret = fn(byref(c_count), None) + + # this should only fail with insufficient size + if (ret != NVML_SUCCESS) and (ret != NVML_ERROR_INSUFFICIENT_SIZE): + raise NVMLError(ret) + + # If there are no hics + if c_count.value == 0: + return [] + + hic_array = c_nvmlHwbcEntry_t * c_count.value + hics = hic_array() + ret = fn(byref(c_count), hics) + _nvmlCheckReturn(ret) + return hics + + +## Unit get functions +def nvmlUnitGetCount(): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlUnitGetCount") + ret = fn(byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlUnitGetHandleByIndex(index): + c_index = c_uint(index) + unit = c_nvmlUnit_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetHandleByIndex") + ret = fn(c_index, byref(unit)) + _nvmlCheckReturn(ret) + return unit + + +def nvmlUnitGetUnitInfo(unit): + c_info = c_nvmlUnitInfo_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetUnitInfo") + ret = fn(unit, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +def nvmlUnitGetLedState(unit): + c_state = c_nvmlLedState_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetLedState") + ret = fn(unit, byref(c_state)) + _nvmlCheckReturn(ret) + return c_state + + +def nvmlUnitGetPsuInfo(unit): + c_info = c_nvmlPSUInfo_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetPsuInfo") + ret = fn(unit, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +def nvmlUnitGetTemperature(unit, type): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlUnitGetTemperature") + ret = fn(unit, c_uint(type), byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.value + + +def nvmlUnitGetFanSpeedInfo(unit): + c_speeds = c_nvmlUnitFanSpeeds_t() + fn = _nvmlGetFunctionPointer("nvmlUnitGetFanSpeedInfo") + ret = fn(unit, byref(c_speeds)) + _nvmlCheckReturn(ret) + return c_speeds + + +# added to API +def nvmlUnitGetDeviceCount(unit): + c_count = c_uint(0) + # query the unit to determine device count + fn = _nvmlGetFunctionPointer("nvmlUnitGetDevices") + ret = fn(unit, byref(c_count), None) + if ret == NVML_ERROR_INSUFFICIENT_SIZE: + ret = NVML_SUCCESS + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlUnitGetDevices(unit): + c_count = c_uint(nvmlUnitGetDeviceCount(unit)) + device_array = c_nvmlDevice_t * c_count.value + c_devices = device_array() + fn = _nvmlGetFunctionPointer("nvmlUnitGetDevices") + ret = fn(unit, byref(c_count), c_devices) + _nvmlCheckReturn(ret) + return c_devices + + +## Device get functions +def nvmlDeviceGetCount(): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCount_v2") + ret = fn(byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlDeviceGetHandleByIndex(index): + c_index = c_uint(index) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByIndex_v2") + ret = fn(c_index, byref(device)) + _nvmlCheckReturn(ret) + return device + + +@convertStrBytes +def nvmlDeviceGetHandleBySerial(serial): + c_serial = c_char_p(serial) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleBySerial") + ret = fn(c_serial, byref(device)) + _nvmlCheckReturn(ret) + return device + + +@convertStrBytes +def nvmlDeviceGetHandleByUUID(uuid): + c_uuid = c_char_p(uuid) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByUUID") + ret = fn(c_uuid, byref(device)) + _nvmlCheckReturn(ret) + return device + + +@convertStrBytes +def nvmlDeviceGetHandleByPciBusId(pciBusId): + c_busId = c_char_p(pciBusId) + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHandleByPciBusId_v2") + ret = fn(c_busId, byref(device)) + _nvmlCheckReturn(ret) + return device + + +@convertStrBytes +def nvmlDeviceGetName(handle): + c_name = create_string_buffer(NVML_DEVICE_NAME_V2_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetName") + ret = fn(handle, c_name, c_uint(NVML_DEVICE_NAME_V2_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_name.value + + +def nvmlDeviceGetBoardId(handle): + c_id = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBoardId") + ret = fn(handle, byref(c_id)) + _nvmlCheckReturn(ret) + return c_id.value + + +def nvmlDeviceGetMultiGpuBoard(handle): + c_multiGpu = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMultiGpuBoard") + ret = fn(handle, byref(c_multiGpu)) + _nvmlCheckReturn(ret) + return c_multiGpu.value + + +def nvmlDeviceGetBrand(handle): + c_type = _nvmlBrandType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBrand") + ret = fn(handle, byref(c_type)) + _nvmlCheckReturn(ret) + return c_type.value + + +@convertStrBytes +def nvmlDeviceGetBoardPartNumber(handle): + c_part_number = create_string_buffer(NVML_DEVICE_PART_NUMBER_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBoardPartNumber") + ret = fn(handle, c_part_number, c_uint(NVML_DEVICE_PART_NUMBER_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_part_number.value + + +@convertStrBytes +def nvmlDeviceGetSerial(handle): + c_serial = create_string_buffer(NVML_DEVICE_SERIAL_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSerial") + ret = fn(handle, c_serial, c_uint(NVML_DEVICE_SERIAL_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_serial.value + + +def nvmlDeviceGetMemoryAffinity(handle, nodeSetSize, scope): + affinity_array = c_ulonglong * nodeSetSize + c_affinity = affinity_array() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryAffinity") + ret = fn(handle, nodeSetSize, byref(c_affinity), _nvmlAffinityScope_t(scope)) + _nvmlCheckReturn(ret) + return c_affinity + + +def nvmlDeviceGetCpuAffinityWithinScope(handle, cpuSetSize, scope): + affinity_array = c_ulonglong * cpuSetSize + c_affinity = affinity_array() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCpuAffinityWithinScope") + ret = fn(handle, cpuSetSize, byref(c_affinity), _nvmlAffinityScope_t(scope)) + _nvmlCheckReturn(ret) + return c_affinity + + +def nvmlDeviceGetCpuAffinity(handle, cpuSetSize): + affinity_array = c_ulonglong * cpuSetSize + c_affinity = affinity_array() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCpuAffinity") + ret = fn(handle, cpuSetSize, byref(c_affinity)) + _nvmlCheckReturn(ret) + return c_affinity + + +def nvmlDeviceSetCpuAffinity(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetCpuAffinity") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceClearCpuAffinity(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceClearCpuAffinity") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetMinorNumber(handle): + c_minor_number = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMinorNumber") + ret = fn(handle, byref(c_minor_number)) + _nvmlCheckReturn(ret) + return c_minor_number.value + + +@convertStrBytes +def nvmlDeviceGetUUID(handle): + c_uuid = create_string_buffer(NVML_DEVICE_UUID_V2_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetUUID") + ret = fn(handle, c_uuid, c_uint(NVML_DEVICE_UUID_V2_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_uuid.value + + +@convertStrBytes +def nvmlDeviceGetInforomVersion(handle, infoRomObject): + c_version = create_string_buffer(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomVersion") + ret = fn( + handle, + _nvmlInforomObject_t(infoRomObject), + c_version, + c_uint(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE), + ) + _nvmlCheckReturn(ret) + return c_version.value + + +# Added in 4.304 +@convertStrBytes +def nvmlDeviceGetInforomImageVersion(handle): + c_version = create_string_buffer(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomImageVersion") + ret = fn(handle, c_version, c_uint(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + + +# Added in 4.304 +def nvmlDeviceGetInforomConfigurationChecksum(handle): + c_checksum = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomConfigurationChecksum") + ret = fn(handle, byref(c_checksum)) + _nvmlCheckReturn(ret) + return c_checksum.value + + +# Added in 4.304 +def nvmlDeviceValidateInforom(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceValidateInforom") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetDisplayMode(handle): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDisplayMode") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlDeviceGetDisplayActive(handle): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDisplayActive") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlDeviceGetPersistenceMode(handle): + c_state = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPersistenceMode") + ret = fn(handle, byref(c_state)) + _nvmlCheckReturn(ret) + return c_state.value + + +def nvmlDeviceGetPciInfo_v3(handle): + c_info = nvmlPciInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPciInfo_v3") + ret = fn(handle, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +def nvmlDeviceGetPciInfo(handle): + return nvmlDeviceGetPciInfo_v3(handle) + + +def nvmlDeviceGetClockInfo(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClockInfo") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + + +# Added in 2.285 +def nvmlDeviceGetMaxClockInfo(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxClockInfo") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + + +# Added in 4.304 +def nvmlDeviceGetApplicationsClock(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetApplicationsClock") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + + +def nvmlDeviceGetMaxCustomerBoostClock(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxCustomerBoostClock") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + + +def nvmlDeviceGetClock(handle, type, id): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClock") + ret = fn(handle, _nvmlClockType_t(type), _nvmlClockId_t(id), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + + +# Added in 5.319 +def nvmlDeviceGetDefaultApplicationsClock(handle, type): + c_clock = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDefaultApplicationsClock") + ret = fn(handle, _nvmlClockType_t(type), byref(c_clock)) + _nvmlCheckReturn(ret) + return c_clock.value + + +# Added in 4.304 +def nvmlDeviceGetSupportedMemoryClocks(handle): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedMemoryClocks") + ret = fn(handle, byref(c_count), None) + + if ret == NVML_SUCCESS: + # special case, no clocks + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + clocks_array = c_uint * c_count.value + c_clocks = clocks_array() + + # make the call again + ret = fn(handle, byref(c_count), c_clocks) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + procs.append(c_clocks[i]) + + return procs + else: + # error case + raise NVMLError(ret) + + +# Added in 4.304 +def nvmlDeviceGetSupportedGraphicsClocks(handle, memoryClockMHz): + # first call to get the size + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedGraphicsClocks") + ret = fn(handle, c_uint(memoryClockMHz), byref(c_count), None) + + if ret == NVML_SUCCESS: + # special case, no clocks + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + clocks_array = c_uint * c_count.value + c_clocks = clocks_array() + + # make the call again + ret = fn(handle, c_uint(memoryClockMHz), byref(c_count), c_clocks) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + procs.append(c_clocks[i]) + + return procs + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetFanSpeed(handle): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFanSpeed") + ret = fn(handle, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + + +def nvmlDeviceGetFanSpeed_v2(handle, fan): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFanSpeed_v2") + ret = fn(handle, fan, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + + +def nvmlDeviceGetNumFans(device): + c_numFans = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNumFans") + ret = fn(device, byref(c_numFans)) + _nvmlCheckReturn(ret) + return c_numFans.value + + +def nvmlDeviceSetDefaultFanSpeed_v2(handle, index): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDefaultFanSpeed_v2") + ret = fn(handle, index) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetMinMaxFanSpeed(handle, minSpeed, maxSpeed): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMinMaxFanSpeed") + ret = fn(handle, minSpeed, maxSpeed) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetTemperature(handle, sensor): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTemperature") + ret = fn(handle, _nvmlTemperatureSensors_t(sensor), byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.value + + +def nvmlDeviceGetTemperatureThreshold(handle, threshold): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTemperatureThreshold") + ret = fn(handle, _nvmlTemperatureThresholds_t(threshold), byref(c_temp)) + _nvmlCheckReturn(ret) + return c_temp.value + + +def nvmlDeviceSetTemperatureThreshold(handle, threshold): + c_temp = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceSetTemperatureThreshold") + ret = fn(handle, _nvmlTemperatureThresholds_t(threshold), byref(c_temp)) + _nvmlCheckReturn(ret) + return None + + +# DEPRECATED use nvmlDeviceGetPerformanceState +def nvmlDeviceGetPowerState(handle): + c_pstate = _nvmlPstates_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerState") + ret = fn(handle, byref(c_pstate)) + _nvmlCheckReturn(ret) + return c_pstate.value + + +def nvmlDeviceGetPerformanceState(handle): + c_pstate = _nvmlPstates_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPerformanceState") + ret = fn(handle, byref(c_pstate)) + _nvmlCheckReturn(ret) + return c_pstate.value + + +def nvmlDeviceGetPowerManagementMode(handle): + c_pcapMode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementMode") + ret = fn(handle, byref(c_pcapMode)) + _nvmlCheckReturn(ret) + return c_pcapMode.value + + +def nvmlDeviceGetPowerManagementLimit(handle): + c_limit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementLimit") + ret = fn(handle, byref(c_limit)) + _nvmlCheckReturn(ret) + return c_limit.value + + +# Added in 4.304 +def nvmlDeviceGetPowerManagementLimitConstraints(handle): + c_minLimit = c_uint() + c_maxLimit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementLimitConstraints") + ret = fn(handle, byref(c_minLimit), byref(c_maxLimit)) + _nvmlCheckReturn(ret) + return [c_minLimit.value, c_maxLimit.value] + + +# Added in 4.304 +def nvmlDeviceGetPowerManagementDefaultLimit(handle): + c_limit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementDefaultLimit") + ret = fn(handle, byref(c_limit)) + _nvmlCheckReturn(ret) + return c_limit.value + + +# Added in 331 +def nvmlDeviceGetEnforcedPowerLimit(handle): + c_limit = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEnforcedPowerLimit") + ret = fn(handle, byref(c_limit)) + _nvmlCheckReturn(ret) + return c_limit.value + + +def nvmlDeviceGetPowerUsage(handle): + c_watts = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerUsage") + ret = fn(handle, byref(c_watts)) + _nvmlCheckReturn(ret) + return c_watts.value + + +def nvmlDeviceGetTotalEnergyConsumption(handle): + c_millijoules = c_uint64() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTotalEnergyConsumption") + ret = fn(handle, byref(c_millijoules)) + _nvmlCheckReturn(ret) + return c_millijoules.value + + +# Added in 4.304 +def nvmlDeviceGetGpuOperationMode(handle): + c_currState = _nvmlGpuOperationMode_t() + c_pendingState = _nvmlGpuOperationMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuOperationMode") + ret = fn(handle, byref(c_currState), byref(c_pendingState)) + _nvmlCheckReturn(ret) + return [c_currState.value, c_pendingState.value] + + +# Added in 4.304 +def nvmlDeviceGetCurrentGpuOperationMode(handle): + return nvmlDeviceGetGpuOperationMode(handle)[0] + + +# Added in 4.304 +def nvmlDeviceGetPendingGpuOperationMode(handle): + return nvmlDeviceGetGpuOperationMode(handle)[1] + + +def nvmlDeviceGetMemoryInfo(handle, version=None): + if not version: + c_memory = c_nvmlMemory_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo") + else: + c_memory = c_nvmlMemory_v2_t() + c_memory.version = version + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo_v2") + ret = fn(handle, byref(c_memory)) + _nvmlCheckReturn(ret) + return c_memory + + +def nvmlDeviceGetBAR1MemoryInfo(handle): + c_bar1_memory = c_nvmlBAR1Memory_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBAR1MemoryInfo") + ret = fn(handle, byref(c_bar1_memory)) + _nvmlCheckReturn(ret) + return c_bar1_memory + + +def nvmlDeviceGetComputeMode(handle): + c_mode = _nvmlComputeMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetComputeMode") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlDeviceGetCudaComputeCapability(handle): + c_major = c_int() + c_minor = c_int() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCudaComputeCapability") + ret = fn(handle, byref(c_major), byref(c_minor)) + _nvmlCheckReturn(ret) + return (c_major.value, c_minor.value) + + +def nvmlDeviceGetEccMode(handle): + c_currState = _nvmlEnableState_t() + c_pendingState = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEccMode") + ret = fn(handle, byref(c_currState), byref(c_pendingState)) + _nvmlCheckReturn(ret) + return [c_currState.value, c_pendingState.value] + + +# added to API +def nvmlDeviceGetCurrentEccMode(handle): + return nvmlDeviceGetEccMode(handle)[0] + + +# added to API +def nvmlDeviceGetPendingEccMode(handle): + return nvmlDeviceGetEccMode(handle)[1] + + +def nvmlDeviceGetDefaultEccMode(handle): + c_defaultState = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDefaultEccMode") + ret = fn(handle, byref(c_defaultState)) + _nvmlCheckReturn(ret) + return [c_defaultState.value] + + +def nvmlDeviceGetTotalEccErrors(handle, errorType, counterType): + c_count = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTotalEccErrors") + ret = fn( + handle, + _nvmlMemoryErrorType_t(errorType), + _nvmlEccCounterType_t(counterType), + byref(c_count), + ) + _nvmlCheckReturn(ret) + return c_count.value + + +# This is deprecated, instead use nvmlDeviceGetMemoryErrorCounter +def nvmlDeviceGetDetailedEccErrors(handle, errorType, counterType): + c_counts = c_nvmlEccErrorCounts_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDetailedEccErrors") + ret = fn( + handle, + _nvmlMemoryErrorType_t(errorType), + _nvmlEccCounterType_t(counterType), + byref(c_counts), + ) + _nvmlCheckReturn(ret) + return c_counts + + +# Added in 4.304 +def nvmlDeviceGetMemoryErrorCounter(handle, errorType, counterType, locationType): + c_count = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryErrorCounter") + ret = fn( + handle, + _nvmlMemoryErrorType_t(errorType), + _nvmlEccCounterType_t(counterType), + _nvmlMemoryLocation_t(locationType), + byref(c_count), + ) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlDeviceGetUtilizationRates(handle): + c_util = c_nvmlUtilization_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetUtilizationRates") + ret = fn(handle, byref(c_util)) + _nvmlCheckReturn(ret) + return c_util + + +def nvmlDeviceGetEncoderUtilization(handle): + c_util = c_uint() + c_samplingPeriod = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderUtilization") + ret = fn(handle, byref(c_util), byref(c_samplingPeriod)) + _nvmlCheckReturn(ret) + return [c_util.value, c_samplingPeriod.value] + + +def nvmlDeviceGetDecoderUtilization(handle): + c_util = c_uint() + c_samplingPeriod = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDecoderUtilization") + ret = fn(handle, byref(c_util), byref(c_samplingPeriod)) + _nvmlCheckReturn(ret) + return [c_util.value, c_samplingPeriod.value] + + +def nvmlDeviceGetPcieReplayCounter(handle): + c_replay = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieReplayCounter") + ret = fn(handle, byref(c_replay)) + _nvmlCheckReturn(ret) + return c_replay.value + + +def nvmlDeviceGetDriverModel(handle): + c_currModel = _nvmlDriverModel_t() + c_pendingModel = _nvmlDriverModel_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDriverModel") + ret = fn(handle, byref(c_currModel), byref(c_pendingModel)) + _nvmlCheckReturn(ret) + return [c_currModel.value, c_pendingModel.value] + + +# added to API +def nvmlDeviceGetCurrentDriverModel(handle): + return nvmlDeviceGetDriverModel(handle)[0] + + +# added to API +def nvmlDeviceGetPendingDriverModel(handle): + return nvmlDeviceGetDriverModel(handle)[1] + + +# Added in 2.285 +@convertStrBytes +def nvmlDeviceGetVbiosVersion(handle): + c_version = create_string_buffer(NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVbiosVersion") + ret = fn(handle, c_version, c_uint(NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE)) + _nvmlCheckReturn(ret) + return c_version.value + + +# Added in 2.285 +def nvmlDeviceGetComputeRunningProcesses_v3(handle): + # first call to get the size + c_count = c_uint(0) + fn = None + for suffix in ("_v3", "_v2", ""): + try: + fn = _nvmlGetFunctionPointer(f"nvmlDeviceGetComputeRunningProcesses{suffix}") + break + except NVMLError: + pass + if fn is None: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + ret = fn(handle, byref(c_count), None) + + if ret == NVML_SUCCESS: + # special case, no running processes + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value: + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetComputeRunningProcesses(handle): + return nvmlDeviceGetComputeRunningProcesses_v3(handle) + + +def nvmlDeviceGetGraphicsRunningProcesses_v3(handle): + # first call to get the size + c_count = c_uint(0) + fn = None + for suffix in ("_v3", "_v2", ""): + try: + fn = _nvmlGetFunctionPointer(f"nvmlDeviceGetGraphicsRunningProcesses{suffix}") + break + except NVMLError: + pass + if fn is None: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + ret = fn(handle, byref(c_count), None) + + if ret == NVML_SUCCESS: + # special case, no running processes + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value: + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetGraphicsRunningProcesses(handle): + return nvmlDeviceGetGraphicsRunningProcesses_v3(handle) + + +def nvmlDeviceGetMPSComputeRunningProcesses(handle): + return nvmlDeviceGetMPSComputeRunningProcesses_v3(handle) + + +def nvmlDeviceGetMPSComputeRunningProcesses_v3(handle): + # first call to get the size + c_count = c_uint(0) + fn = None + for suffix in ("_v3", "_v2", ""): + try: + fn = _nvmlGetFunctionPointer(f"nvmlDeviceGetMPSComputeRunningProcesses{suffix}") + break + except NVMLError: + pass + if fn is None: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + + ret = fn(handle, byref(c_count), None) + + if ret == NVML_SUCCESS: + # special case, no running processes + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + # oversize the array incase more processes are created + c_count.value = c_count.value * 2 + 5 + proc_array = c_nvmlProcessInfo_t * c_count.value + c_procs = proc_array() + + # make the call again + ret = fn(handle, byref(c_count), c_procs) + _nvmlCheckReturn(ret) + + procs = [] + for i in range(c_count.value): + # use an alternative struct for this object + obj = nvmlStructToFriendlyObject(c_procs[i]) + if obj.usedGpuMemory == NVML_VALUE_NOT_AVAILABLE_ulonglong.value: + # special case for WDDM on Windows, see comment above + obj.usedGpuMemory = None + procs.append(obj) + + return procs + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetAutoBoostedClocksEnabled(handle): + c_isEnabled = _nvmlEnableState_t() + c_defaultIsEnabled = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAutoBoostedClocksEnabled") + ret = fn(handle, byref(c_isEnabled), byref(c_defaultIsEnabled)) + _nvmlCheckReturn(ret) + return [c_isEnabled.value, c_defaultIsEnabled.value] + # Throws NVML_ERROR_NOT_SUPPORTED if hardware doesn't support setting auto boosted clocks + + +## Set functions +def nvmlUnitSetLedState(unit, color): + fn = _nvmlGetFunctionPointer("nvmlUnitSetLedState") + ret = fn(unit, _nvmlLedColor_t(color)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetPersistenceMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetPersistenceMode") + ret = fn(handle, _nvmlEnableState_t(mode)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetComputeMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetComputeMode") + ret = fn(handle, _nvmlComputeMode_t(mode)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetEccMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetEccMode") + ret = fn(handle, _nvmlEnableState_t(mode)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceClearEccErrorCounts(handle, counterType): + fn = _nvmlGetFunctionPointer("nvmlDeviceClearEccErrorCounts") + ret = fn(handle, _nvmlEccCounterType_t(counterType)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetDriverModel(handle, model): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDriverModel") + ret = fn(handle, _nvmlDriverModel_t(model)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetAutoBoostedClocksEnabled(handle, enabled): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetAutoBoostedClocksEnabled") + ret = fn(handle, _nvmlEnableState_t(enabled)) + _nvmlCheckReturn(ret) + return None + # Throws NVML_ERROR_NOT_SUPPORTED if hardware doesn't support setting auto boosted clocks + + +def nvmlDeviceSetDefaultAutoBoostedClocksEnabled(handle, enabled, flags): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetDefaultAutoBoostedClocksEnabled") + ret = fn(handle, _nvmlEnableState_t(enabled), c_uint(flags)) + _nvmlCheckReturn(ret) + return None + # Throws NVML_ERROR_NOT_SUPPORTED if hardware doesn't support setting auto boosted clocks + + +def nvmlDeviceSetGpuLockedClocks(handle, minGpuClockMHz, maxGpuClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetGpuLockedClocks") + ret = fn(handle, c_uint(minGpuClockMHz), c_uint(maxGpuClockMHz)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceResetGpuLockedClocks(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetGpuLockedClocks") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetMemoryLockedClocks(handle, minMemClockMHz, maxMemClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetMemoryLockedClocks") + ret = fn(handle, c_uint(minMemClockMHz), c_uint(maxMemClockMHz)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceResetMemoryLockedClocks(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetMemoryLockedClocks") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetClkMonStatus(handle, c_clkMonInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetClkMonStatus") + ret = fn(handle, c_clkMonInfo) + return ret + + +# Added in 4.304 +def nvmlDeviceSetApplicationsClocks(handle, maxMemClockMHz, maxGraphicsClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetApplicationsClocks") + ret = fn(handle, c_uint(maxMemClockMHz), c_uint(maxGraphicsClockMHz)) + _nvmlCheckReturn(ret) + return None + + +# Added in 4.304 +def nvmlDeviceResetApplicationsClocks(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetApplicationsClocks") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +# Added in 4.304 +def nvmlDeviceSetPowerManagementLimit(handle, limit): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetPowerManagementLimit") + ret = fn(handle, c_uint(limit)) + _nvmlCheckReturn(ret) + return None + + +# Added in 4.304 +def nvmlDeviceSetGpuOperationMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetGpuOperationMode") + ret = fn(handle, _nvmlGpuOperationMode_t(mode)) + _nvmlCheckReturn(ret) + return None + + +# Added in 2.285 +def nvmlEventSetCreate(): + fn = _nvmlGetFunctionPointer("nvmlEventSetCreate") + eventSet = c_nvmlEventSet_t() + ret = fn(byref(eventSet)) + _nvmlCheckReturn(ret) + return eventSet + + +# Added in 2.285 +def nvmlDeviceRegisterEvents(handle, eventTypes, eventSet): + fn = _nvmlGetFunctionPointer("nvmlDeviceRegisterEvents") + ret = fn(handle, c_ulonglong(eventTypes), eventSet) + _nvmlCheckReturn(ret) + return None + + +# Added in 2.285 +def nvmlDeviceGetSupportedEventTypes(handle): + c_eventTypes = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedEventTypes") + ret = fn(handle, byref(c_eventTypes)) + _nvmlCheckReturn(ret) + return c_eventTypes.value + + +# raises NVML_ERROR_TIMEOUT exception on timeout +def nvmlEventSetWait_v2(eventSet, timeoutms): + fn = _nvmlGetFunctionPointer("nvmlEventSetWait_v2") + data = c_nvmlEventData_t() + ret = fn(eventSet, byref(data), c_uint(timeoutms)) + _nvmlCheckReturn(ret) + return data + + +def nvmlEventSetWait(eventSet, timeoutms): + return nvmlEventSetWait_v2(eventSet, timeoutms) + + +# Added in 2.285 +def nvmlEventSetFree(eventSet): + fn = _nvmlGetFunctionPointer("nvmlEventSetFree") + ret = fn(eventSet) + _nvmlCheckReturn(ret) + return None + + +# Added in 3.295 +def nvmlDeviceOnSameBoard(handle1, handle2): + fn = _nvmlGetFunctionPointer("nvmlDeviceOnSameBoard") + onSameBoard = c_int() + ret = fn(handle1, handle2, byref(onSameBoard)) + _nvmlCheckReturn(ret) + return onSameBoard.value != 0 + + +# Added in 3.295 +def nvmlDeviceGetCurrPcieLinkGeneration(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrPcieLinkGeneration") + gen = c_uint() + ret = fn(handle, byref(gen)) + _nvmlCheckReturn(ret) + return gen.value + + +# Added in 3.295 +def nvmlDeviceGetMaxPcieLinkGeneration(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxPcieLinkGeneration") + gen = c_uint() + ret = fn(handle, byref(gen)) + _nvmlCheckReturn(ret) + return gen.value + + +# Added in 3.295 +def nvmlDeviceGetCurrPcieLinkWidth(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrPcieLinkWidth") + width = c_uint() + ret = fn(handle, byref(width)) + _nvmlCheckReturn(ret) + return width.value + + +# Added in 3.295 +def nvmlDeviceGetMaxPcieLinkWidth(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxPcieLinkWidth") + width = c_uint() + ret = fn(handle, byref(width)) + _nvmlCheckReturn(ret) + return width.value + + +# Added in 4.304 +def nvmlDeviceGetSupportedClocksThrottleReasons(handle): + c_reasons = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedClocksThrottleReasons") + ret = fn(handle, byref(c_reasons)) + _nvmlCheckReturn(ret) + return c_reasons.value + + +# Added in 4.304 +def nvmlDeviceGetCurrentClocksThrottleReasons(handle): + c_reasons = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrentClocksThrottleReasons") + ret = fn(handle, byref(c_reasons)) + _nvmlCheckReturn(ret) + return c_reasons.value + + +# Added in 5.319 +def nvmlDeviceGetIndex(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetIndex") + c_index = c_uint() + ret = fn(handle, byref(c_index)) + _nvmlCheckReturn(ret) + return c_index.value + + +# Added in 5.319 +def nvmlDeviceGetAccountingMode(handle): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingMode") + ret = fn(handle, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlDeviceSetAccountingMode(handle, mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetAccountingMode") + ret = fn(handle, _nvmlEnableState_t(mode)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceClearAccountingPids(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceClearAccountingPids") + ret = fn(handle) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetAccountingStats(handle, pid): + stats = c_nvmlAccountingStats_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingStats") + ret = fn(handle, c_uint(pid), byref(stats)) + _nvmlCheckReturn(ret) + if stats.maxMemoryUsage == NVML_VALUE_NOT_AVAILABLE_ulonglong.value: + # special case for WDDM on Windows, see comment above + stats.maxMemoryUsage = None + return stats + + +def nvmlDeviceGetAccountingPids(handle): + count = c_uint(nvmlDeviceGetAccountingBufferSize(handle)) + pids = (c_uint * count.value)() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingPids") + ret = fn(handle, byref(count), pids) + _nvmlCheckReturn(ret) + return list(map(int, pids[0 : count.value])) + + +def nvmlDeviceGetAccountingBufferSize(handle): + bufferSize = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAccountingBufferSize") + ret = fn(handle, byref(bufferSize)) + _nvmlCheckReturn(ret) + return int(bufferSize.value) + + +def nvmlDeviceGetRetiredPages(device, sourceFilter): + c_source = _nvmlPageRetirementCause_t(sourceFilter) + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPages") + + # First call will get the size + ret = fn(device, c_source, byref(c_count), None) + + # this should only fail with insufficient size + if (ret != NVML_SUCCESS) and (ret != NVML_ERROR_INSUFFICIENT_SIZE): + raise NVMLError(ret) + + # call again with a buffer + # oversize the array for the rare cases where additional pages + # are retired between NVML calls + c_count.value = c_count.value * 2 + 5 + page_array = c_ulonglong * c_count.value + c_pages = page_array() + ret = fn(device, c_source, byref(c_count), c_pages) + _nvmlCheckReturn(ret) + return list(map(int, c_pages[0 : c_count.value])) + + +def nvmlDeviceGetRetiredPages_v2(device, sourceFilter): + c_source = _nvmlPageRetirementCause_t(sourceFilter) + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPages_v2") + + # First call will get the size + ret = fn(device, c_source, byref(c_count), None) + + # this should only fail with insufficient size + if (ret != NVML_SUCCESS) and (ret != NVML_ERROR_INSUFFICIENT_SIZE): + raise NVMLError(ret) + + # call again with a buffer + # oversize the array for the rare cases where additional pages + # are retired between NVML calls + c_count.value = c_count.value * 2 + 5 + page_array = c_ulonglong * c_count.value + c_pages = page_array() + times_array = c_ulonglong * c_count.value + c_times = times_array() + ret = fn(device, c_source, byref(c_count), c_pages, c_times) + _nvmlCheckReturn(ret) + return [{"address": int(c_pages[i]), "timestamp": int(c_times[i])} for i in range(c_count.value)] + + +def nvmlDeviceGetRetiredPagesPendingStatus(device): + c_pending = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPagesPendingStatus") + ret = fn(device, byref(c_pending)) + _nvmlCheckReturn(ret) + return int(c_pending.value) + + +def nvmlDeviceGetAPIRestriction(device, apiType): + c_permission = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAPIRestriction") + ret = fn(device, _nvmlRestrictedAPI_t(apiType), byref(c_permission)) + _nvmlCheckReturn(ret) + return int(c_permission.value) + + +def nvmlDeviceSetAPIRestriction(handle, apiType, isRestricted): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetAPIRestriction") + ret = fn(handle, _nvmlRestrictedAPI_t(apiType), _nvmlEnableState_t(isRestricted)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetBridgeChipInfo(handle): + bridgeHierarchy = c_nvmlBridgeChipHierarchy_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBridgeChipInfo") + ret = fn(handle, byref(bridgeHierarchy)) + _nvmlCheckReturn(ret) + return bridgeHierarchy + + +def nvmlDeviceGetSamples(device, sampling_type, timeStamp): + c_sampling_type = _nvmlSamplingType_t(sampling_type) + c_time_stamp = c_ulonglong(timeStamp) + c_sample_count = c_uint(0) + c_sample_value_type = _nvmlValueType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSamples") + + ## First Call gets the size + ret = fn( + device, + c_sampling_type, + c_time_stamp, + byref(c_sample_value_type), + byref(c_sample_count), + None, + ) + + # Stop if this fails + if ret != NVML_SUCCESS: + raise NVMLError(ret) + + sampleArray = c_sample_count.value * c_nvmlSample_t + c_samples = sampleArray() + ret = fn( + device, + c_sampling_type, + c_time_stamp, + byref(c_sample_value_type), + byref(c_sample_count), + c_samples, + ) + _nvmlCheckReturn(ret) + return (c_sample_value_type.value, c_samples[0 : c_sample_count.value]) + + +def nvmlDeviceGetViolationStatus(device, perfPolicyType): + c_perfPolicy_type = _nvmlPerfPolicyType_t(perfPolicyType) + c_violTime = c_nvmlViolationTime_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetViolationStatus") + + ## Invoke the method to get violation time + ret = fn(device, c_perfPolicy_type, byref(c_violTime)) + _nvmlCheckReturn(ret) + return c_violTime + + +def nvmlDeviceGetPcieThroughput(device, counter): + c_util = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieThroughput") + ret = fn(device, _nvmlPcieUtilCounter_t(counter), byref(c_util)) + _nvmlCheckReturn(ret) + return c_util.value + + +def nvmlSystemGetTopologyGpuSet(cpuNumber): + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlSystemGetTopologyGpuSet") + + # First call will get the size + ret = fn(cpuNumber, byref(c_count), None) + + if ret != NVML_SUCCESS: + raise NVMLError(ret) + # call again with a buffer + device_array = c_nvmlDevice_t * c_count.value + c_devices = device_array() + ret = fn(cpuNumber, byref(c_count), c_devices) + _nvmlCheckReturn(ret) + return list(c_devices[0 : c_count.value]) + + +def nvmlDeviceGetTopologyNearestGpus(device, level): + c_count = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTopologyNearestGpus") + + # First call will get the size + ret = fn(device, level, byref(c_count), None) + + if ret != NVML_SUCCESS: + raise NVMLError(ret) + + # call again with a buffer + device_array = c_nvmlDevice_t * c_count.value + c_devices = device_array() + ret = fn(device, level, byref(c_count), c_devices) + _nvmlCheckReturn(ret) + return list(c_devices[0 : c_count.value]) + + +def nvmlDeviceGetTopologyCommonAncestor(device1, device2): + c_level = _nvmlGpuTopologyLevel_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetTopologyCommonAncestor") + ret = fn(device1, device2, byref(c_level)) + _nvmlCheckReturn(ret) + return c_level.value + + +def nvmlDeviceGetNvLinkUtilizationCounter(device, link, counter): + c_rxcounter = c_ulonglong() + c_txcounter = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkUtilizationCounter") + ret = fn(device, link, counter, byref(c_rxcounter), byref(c_txcounter)) + _nvmlCheckReturn(ret) + return (c_rxcounter.value, c_txcounter.value) + + +def nvmlDeviceFreezeNvLinkUtilizationCounter(device, link, counter, freeze): + fn = _nvmlGetFunctionPointer("nvmlDeviceFreezeNvLinkUtilizationCounter") + ret = fn(device, link, counter, freeze) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceResetNvLinkUtilizationCounter(device, link, counter): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetNvLinkUtilizationCounter") + ret = fn(device, link, counter) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceSetNvLinkUtilizationControl(device, link, counter, control, reset): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetNvLinkUtilizationControl") + ret = fn(device, link, counter, byref(control), reset) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetNvLinkUtilizationControl(device, link, counter): + c_control = nvmlNvLinkUtilizationControl_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkUtilizationControl") + ret = fn(device, link, counter, byref(c_control)) + _nvmlCheckReturn(ret) + return c_control + + +def nvmlDeviceGetNvLinkCapability(device, link, capability): + c_capResult = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkCapability") + ret = fn(device, link, capability, byref(c_capResult)) + _nvmlCheckReturn(ret) + return c_capResult.value + + +def nvmlDeviceGetNvLinkErrorCounter(device, link, counter): + c_result = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkErrorCounter") + ret = fn(device, link, counter, byref(c_result)) + _nvmlCheckReturn(ret) + return c_result.value + + +def nvmlDeviceResetNvLinkErrorCounters(device, link): + fn = _nvmlGetFunctionPointer("nvmlDeviceResetNvLinkErrorCounters") + ret = fn(device, link) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetNvLinkRemotePciInfo(device, link): + c_pci = nvmlPciInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkRemotePciInfo_v2") + ret = fn(device, link, byref(c_pci)) + _nvmlCheckReturn(ret) + return c_pci + + +def nvmlDeviceGetNvLinkRemoteDeviceType(handle, link): + c_type = _nvmlNvLinkDeviceType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkRemoteDeviceType") + ret = fn(handle, link, byref(c_type)) + _nvmlCheckReturn(ret) + return c_type.value + + +def nvmlDeviceGetNvLinkState(device, link): + c_isActive = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkState") + ret = fn(device, link, byref(c_isActive)) + _nvmlCheckReturn(ret) + return c_isActive.value + + +def nvmlDeviceGetNvLinkVersion(device, link): + c_version = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkVersion") + ret = fn(device, link, byref(c_version)) + _nvmlCheckReturn(ret) + return c_version.value + + +def nvmlDeviceModifyDrainState(pciInfo, newState): + fn = _nvmlGetFunctionPointer("nvmlDeviceModifyDrainState") + ret = fn(pointer(pciInfo), newState) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceQueryDrainState(pciInfo): + c_newState = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceQueryDrainState") + ret = fn(pointer(pciInfo), byref(c_newState)) + _nvmlCheckReturn(ret) + return c_newState.value + + +def nvmlDeviceRemoveGpu(pciInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceRemoveGpu") + ret = fn(pointer(pciInfo)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceDiscoverGpus(pciInfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceDiscoverGpus") + ret = fn(pointer(pciInfo)) + _nvmlCheckReturn(ret) + return None + + +def nvmlDeviceGetFieldValues(handle, fieldIds): + values_arr = c_nvmlFieldValue_t * len(fieldIds) + values = values_arr() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFieldValues") + + for i, fieldId in enumerate(fieldIds): + try: + (values[i].fieldId, values[i].scopeId) = fieldId + except TypeError: + values[i].fieldId = fieldId + + ret = fn(handle, c_int32(len(fieldIds)), byref(values)) + _nvmlCheckReturn(ret) + return values + + +def nvmlDeviceGetVirtualizationMode(handle): + c_virtualization_mode = c_ulonglong() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVirtualizationMode") + ret = fn(handle, byref(c_virtualization_mode)) + _nvmlCheckReturn(ret) + return c_virtualization_mode.value + + +def nvmlDeviceSetVirtualizationMode(handle, virtualization_mode): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetVirtualizationMode") + return fn(handle, virtualization_mode) + + +def nvmlDeviceGetSupportedVgpus(handle): + # first call to get the size + c_vgpu_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedVgpus") + ret = fn(handle, byref(c_vgpu_count), None) + + if ret == NVML_SUCCESS: + # special case, no supported vGPUs + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + vgpu_type_ids_array = _nvmlVgpuTypeId_t * c_vgpu_count.value + c_vgpu_type_ids = vgpu_type_ids_array() + + # make the call again + ret = fn(handle, byref(c_vgpu_count), c_vgpu_type_ids) + _nvmlCheckReturn(ret) + vgpus = [] + for i in range(c_vgpu_count.value): + vgpus.append(c_vgpu_type_ids[i]) + return vgpus + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetCreatableVgpus(handle): + # first call to get the size + c_vgpu_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetCreatableVgpus") + ret = fn(handle, byref(c_vgpu_count), None) + + if ret == NVML_SUCCESS: + # special case, no supported vGPUs + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + vgpu_type_ids_array = _nvmlVgpuTypeId_t * c_vgpu_count.value + c_vgpu_type_ids = vgpu_type_ids_array() + + # make the call again + ret = fn(handle, byref(c_vgpu_count), c_vgpu_type_ids) + _nvmlCheckReturn(ret) + vgpus = [] + for i in range(c_vgpu_count.value): + vgpus.append(c_vgpu_type_ids[i]) + return vgpus + else: + # error case + raise NVMLError(ret) + + +def nvmlVgpuTypeGetGpuInstanceProfileId(vgpuTypeId): + c_profile_id = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetGpuInstanceProfileId") + ret = fn(vgpuTypeId, byref(c_profile_id)) + _nvmlCheckReturn(ret) + return c_profile_id.value + + +@convertStrBytes +def nvmlVgpuTypeGetClass(vgpuTypeId): + c_class = create_string_buffer(NVML_DEVICE_NAME_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_NAME_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetClass") + ret = fn(vgpuTypeId, c_class, byref(c_buffer_size)) + _nvmlCheckReturn(ret) + return c_class.value + + +@convertStrBytes +def nvmlVgpuTypeGetName(vgpuTypeId): + c_name = create_string_buffer(NVML_DEVICE_NAME_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_NAME_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetName") + ret = fn(vgpuTypeId, c_name, byref(c_buffer_size)) + _nvmlCheckReturn(ret) + return c_name.value + + +def nvmlVgpuTypeGetDeviceID(vgpuTypeId): + c_device_id = c_ulonglong(0) + c_subsystem_id = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetDeviceID") + ret = fn(vgpuTypeId, byref(c_device_id), byref(c_subsystem_id)) + _nvmlCheckReturn(ret) + return (c_device_id.value, c_subsystem_id.value) + + +def nvmlVgpuTypeGetFramebufferSize(vgpuTypeId): + c_fb_size = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetFramebufferSize") + ret = fn(vgpuTypeId, byref(c_fb_size)) + _nvmlCheckReturn(ret) + return c_fb_size.value + + +def nvmlVgpuTypeGetNumDisplayHeads(vgpuTypeId): + c_num_heads = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetNumDisplayHeads") + ret = fn(vgpuTypeId, byref(c_num_heads)) + _nvmlCheckReturn(ret) + return c_num_heads.value + + +def nvmlVgpuTypeGetResolution(vgpuTypeId): + c_xdim = c_uint(0) + c_ydim = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetResolution") + ret = fn(vgpuTypeId, 0, byref(c_xdim), byref(c_ydim)) + _nvmlCheckReturn(ret) + return (c_xdim.value, c_ydim.value) + + +@convertStrBytes +def nvmlVgpuTypeGetLicense(vgpuTypeId): + c_license = create_string_buffer(NVML_GRID_LICENSE_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_GRID_LICENSE_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetLicense") + ret = fn(vgpuTypeId, c_license, c_buffer_size) + _nvmlCheckReturn(ret) + return c_license.value + + +def nvmlVgpuTypeGetFrameRateLimit(vgpuTypeId): + c_frl_config = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetFrameRateLimit") + ret = fn(vgpuTypeId, byref(c_frl_config)) + _nvmlCheckReturn(ret) + return c_frl_config.value + + +def nvmlVgpuTypeGetMaxInstances(handle, vgpuTypeId): + c_max_instances = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstances") + ret = fn(handle, vgpuTypeId, byref(c_max_instances)) + _nvmlCheckReturn(ret) + return c_max_instances.value + + +def nvmlVgpuTypeGetMaxInstancesPerVm(vgpuTypeId): + c_max_instances_per_vm = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetMaxInstancesPerVm") + ret = fn(vgpuTypeId, byref(c_max_instances_per_vm)) + _nvmlCheckReturn(ret) + return c_max_instances_per_vm.value + + +def nvmlDeviceGetActiveVgpus(handle): + # first call to get the size + c_vgpu_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetActiveVgpus") + ret = fn(handle, byref(c_vgpu_count), None) + + if ret == NVML_SUCCESS: + # special case, no active vGPUs + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + vgpu_instance_array = _nvmlVgpuInstance_t * c_vgpu_count.value + c_vgpu_instances = vgpu_instance_array() + + # make the call again + ret = fn(handle, byref(c_vgpu_count), c_vgpu_instances) + _nvmlCheckReturn(ret) + vgpus = [] + for i in range(c_vgpu_count.value): + vgpus.append(c_vgpu_instances[i]) + return vgpus + else: + # error case + raise NVMLError(ret) + + +@convertStrBytes +def nvmlVgpuInstanceGetVmID(vgpuInstance): + c_vm_id = create_string_buffer(NVML_DEVICE_UUID_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_GRID_LICENSE_BUFFER_SIZE) + c_vm_id_type = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetVmID") + ret = fn(vgpuInstance, byref(c_vm_id), c_buffer_size, byref(c_vm_id_type)) + _nvmlCheckReturn(ret) + return (c_vm_id.value, c_vm_id_type.value) + + +@convertStrBytes +def nvmlVgpuInstanceGetUUID(vgpuInstance): + c_uuid = create_string_buffer(NVML_DEVICE_UUID_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_UUID_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetUUID") + ret = fn(vgpuInstance, byref(c_uuid), c_buffer_size) + _nvmlCheckReturn(ret) + return c_uuid.value + + +@convertStrBytes +def nvmlVgpuInstanceGetMdevUUID(vgpuInstance): + c_uuid = create_string_buffer(NVML_DEVICE_UUID_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_DEVICE_UUID_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetMdevUUID") + ret = fn(vgpuInstance, byref(c_uuid), c_buffer_size) + _nvmlCheckReturn(ret) + return c_uuid.value + + +@convertStrBytes +def nvmlVgpuInstanceGetVmDriverVersion(vgpuInstance): + c_driver_version = create_string_buffer(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + c_buffer_size = c_uint(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetVmDriverVersion") + ret = fn(vgpuInstance, byref(c_driver_version), c_buffer_size) + _nvmlCheckReturn(ret) + return c_driver_version.value + + +def nvmlVgpuInstanceGetLicenseStatus(vgpuInstance): + c_license_status = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetLicenseStatus") + ret = fn(vgpuInstance, byref(c_license_status)) + _nvmlCheckReturn(ret) + return c_license_status.value + + +def nvmlVgpuInstanceGetLicenseInfo_v2(vgpuInstance): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetLicenseInfo_v2") + c_license_info = c_nvmlVgpuLicenseInfo_t() + ret = fn(vgpuInstance, byref(c_license_info)) + _nvmlCheckReturn(ret) + return c_license_info + + +def nvmlVgpuInstanceGetLicenseInfo(vgpuInstance): + return nvmlVgpuInstanceGetLicenseInfo_v2(vgpuInstance) + + +def nvmlVgpuInstanceGetFrameRateLimit(vgpuInstance): + c_frl = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFrameRateLimit") + ret = fn(vgpuInstance, byref(c_frl)) + _nvmlCheckReturn(ret) + return c_frl.value + + +def nvmlVgpuInstanceGetEccMode(vgpuInstance): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEccMode") + ret = fn(vgpuInstance, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlVgpuInstanceGetType(vgpuInstance): + c_vgpu_type = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetType") + ret = fn(vgpuInstance, byref(c_vgpu_type)) + _nvmlCheckReturn(ret) + return c_vgpu_type.value + + +def nvmlVgpuInstanceGetEncoderCapacity(vgpuInstance): + c_encoder_capacity = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEncoderCapacity") + ret = fn(vgpuInstance, byref(c_encoder_capacity)) + _nvmlCheckReturn(ret) + return c_encoder_capacity.value + + +def nvmlVgpuInstanceSetEncoderCapacity(vgpuInstance, encoder_capacity): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceSetEncoderCapacity") + return fn(vgpuInstance, encoder_capacity) + + +def nvmlVgpuInstanceGetFbUsage(vgpuInstance): + c_fb_usage = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFbUsage") + ret = fn(vgpuInstance, byref(c_fb_usage)) + _nvmlCheckReturn(ret) + return c_fb_usage.value + + +def nvmlVgpuTypeGetCapabilities(vgpuTypeId, capability): + c_cap_result = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuTypeGetCapabilities") + ret = fn(vgpuTypeId, _nvmlVgpuCapability_t(capability), byref(c_cap_result)) + _nvmlCheckReturn(ret) + return c_cap_result.value + + +def nvmlVgpuInstanceGetGpuInstanceId(vgpuInstance): + c_id = c_uint(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetGpuInstanceId") + ret = fn(vgpuInstance, byref(c_id)) + _nvmlCheckReturn(ret) + return c_id.value + + +def nvmlVgpuInstanceGetGpuPciId(vgpuInstance): + c_vgpuPciId = create_string_buffer(NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetGpuPciId") + ret = fn(vgpuInstance, c_vgpuPciId, byref(c_uint(NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE))) + _nvmlCheckReturn(ret) + return c_vgpuPciId.value + + +def nvmlDeviceGetVgpuUtilization(handle, timeStamp): + # first call to get the size + c_vgpu_count = c_uint(0) + c_time_stamp = c_ulonglong(timeStamp) + c_sample_value_type = _nvmlValueType_t() + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuUtilization") + ret = fn(handle, c_time_stamp, byref(c_sample_value_type), byref(c_vgpu_count), None) + + if ret == NVML_SUCCESS: + # special case, no active vGPUs + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + sampleArray = c_vgpu_count.value * c_nvmlVgpuInstanceUtilizationSample_t + c_samples = sampleArray() + + # make the call again + ret = fn( + handle, + c_time_stamp, + byref(c_sample_value_type), + byref(c_vgpu_count), + c_samples, + ) + _nvmlCheckReturn(ret) + + return c_samples[0 : c_vgpu_count.value] + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetP2PStatus(device1, device2, p2pIndex): + c_p2pstatus = _nvmlGpuP2PStatus_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetP2PStatus") + ret = fn(device1, device2, p2pIndex, byref(c_p2pstatus)) + _nvmlCheckReturn(ret) + return c_p2pstatus.value + + +def nvmlDeviceGetGridLicensableFeatures_v4(handle): + c_get_grid_licensable_features = c_nvmlGridLicensableFeatures_v4_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGridLicensableFeatures_v4") + ret = fn(handle, byref(c_get_grid_licensable_features)) + _nvmlCheckReturn(ret) + + return c_get_grid_licensable_features + + +def nvmlDeviceGetGridLicensableFeatures(handle): + return nvmlDeviceGetGridLicensableFeatures_v4(handle) + + +def nvmlDeviceGetGspFirmwareVersion(handle, version): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGspFirmwareVersion") + ret = fn(handle, version) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetGspFirmwareMode(handle, isEnabled, defaultMode): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGspFirmwareMode") + ret = fn(handle, isEnabled, defaultMode) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetEncoderCapacity(handle, encoderQueryType): + c_encoder_capacity = c_ulonglong(0) + c_encoderQuery_type = _nvmlEncoderQueryType_t(encoderQueryType) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderCapacity") + ret = fn(handle, c_encoderQuery_type, byref(c_encoder_capacity)) + _nvmlCheckReturn(ret) + return c_encoder_capacity.value + + +def nvmlDeviceGetVgpuProcessUtilization(handle, timeStamp): + # first call to get the size + c_vgpu_count = c_uint(0) + c_time_stamp = c_ulonglong(timeStamp) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuProcessUtilization") + ret = fn(handle, c_time_stamp, byref(c_vgpu_count), None) + + if ret == NVML_SUCCESS: + # special case, no active vGPUs + return [] + elif ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + sampleArray = c_vgpu_count.value * c_nvmlVgpuProcessUtilizationSample_t + c_samples = sampleArray() + + # make the call again + ret = fn(handle, c_time_stamp, byref(c_vgpu_count), c_samples) + _nvmlCheckReturn(ret) + + return c_samples[0 : c_vgpu_count.value] + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetEncoderStats(handle): + c_encoderCount = c_ulonglong(0) + c_encodeFps = c_ulonglong(0) + c_encoderLatency = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderStats") + ret = fn(handle, byref(c_encoderCount), byref(c_encodeFps), byref(c_encoderLatency)) + _nvmlCheckReturn(ret) + return (c_encoderCount.value, c_encodeFps.value, c_encoderLatency.value) + + +def nvmlDeviceGetEncoderSessions(handle): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetEncoderSessions") + ret = fn(handle, byref(c_session_count), None) + + if ret == NVML_SUCCESS: + if c_session_count.value != 0: + # typical case + session_array = c_nvmlEncoderSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(handle, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetFBCStats(handle): + c_fbcStats = c_nvmlFBCStats_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFBCStats") + ret = fn(handle, byref(c_fbcStats)) + _nvmlCheckReturn(ret) + return c_fbcStats + + +def nvmlDeviceGetFBCSessions(handle): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetFBCSessions") + ret = fn(handle, byref(c_session_count), None) + + if ret == NVML_SUCCESS: + if c_session_count.value != 0: + # typical case + session_array = c_nvmlFBCSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(handle, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + + +def nvmlVgpuInstanceGetEncoderStats(vgpuInstance): + c_encoderCount = c_ulonglong(0) + c_encodeFps = c_ulonglong(0) + c_encoderLatency = c_ulonglong(0) + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEncoderStats") + ret = fn(vgpuInstance, byref(c_encoderCount), byref(c_encodeFps), byref(c_encoderLatency)) + _nvmlCheckReturn(ret) + return (c_encoderCount.value, c_encodeFps.value, c_encoderLatency.value) + + +def nvmlVgpuInstanceGetEncoderSessions(vgpuInstance): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetEncoderSessions") + ret = fn(vgpuInstance, byref(c_session_count), None) + + if ret == NVML_SUCCESS: + if c_session_count.value != 0: + # typical case + session_array = c_nvmlEncoderSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(vgpuInstance, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + + +def nvmlVgpuInstanceGetFBCStats(vgpuInstance): + c_fbcStats = c_nvmlFBCStats_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFBCStats") + ret = fn(vgpuInstance, byref(c_fbcStats)) + _nvmlCheckReturn(ret) + return c_fbcStats + + +def nvmlVgpuInstanceGetFBCSessions(vgpuInstance): + # first call to get the size + c_session_count = c_uint(0) + + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetFBCSessions") + ret = fn(vgpuInstance, byref(c_session_count), None) + + if ret == NVML_SUCCESS: + if c_session_count.value != 0: + # typical case + session_array = c_nvmlFBCSession_t * c_session_count.value + c_sessions = session_array() + + # make the call again + ret = fn(vgpuInstance, byref(c_session_count), c_sessions) + _nvmlCheckReturn(ret) + sessions = [] + for i in range(c_session_count.value): + sessions.append(c_sessions[i]) + return sessions + else: + return [] # no active sessions + else: + # error case + raise NVMLError(ret) + + +def nvmlDeviceGetProcessUtilization(handle, timeStamp): + # first call to get the size + c_count = c_uint(0) + c_time_stamp = c_ulonglong(timeStamp) + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetProcessUtilization") + ret = fn(handle, None, byref(c_count), c_time_stamp) + + if ret == NVML_ERROR_INSUFFICIENT_SIZE: + # typical case + sampleArray = c_count.value * c_nvmlProcessUtilizationSample_t + c_samples = sampleArray() + + # make the call again + ret = fn(handle, c_samples, byref(c_count), c_time_stamp) + _nvmlCheckReturn(ret) + + return c_samples[0 : c_count.value] + else: + # error case + raise NVMLError(ret) + + +def nvmlVgpuInstanceGetMetadata(vgpuInstance): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetMetadata") + c_vgpuMetadata = c_nvmlVgpuMetadata_t() + c_bufferSize = c_uint(0) + # Make the first NVML API call to get the c_bufferSize value. + # We have already allocated required buffer above. + ret = fn(vgpuInstance, byref(c_vgpuMetadata), byref(c_bufferSize)) + if ret == NVML_ERROR_INSUFFICIENT_SIZE: + ret = fn(vgpuInstance, byref(c_vgpuMetadata), byref(c_bufferSize)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return c_vgpuMetadata + + +def nvmlDeviceGetVgpuMetadata(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetVgpuMetadata") + c_vgpuPgpuMetadata = c_nvmlVgpuPgpuMetadata_t() + c_bufferSize = c_uint(0) + # Make the first NVML API call to get the c_bufferSize value. + # We have already allocated required buffer above. + ret = fn(handle, byref(c_vgpuPgpuMetadata), byref(c_bufferSize)) + if ret == NVML_ERROR_INSUFFICIENT_SIZE: + ret = fn(handle, byref(c_vgpuPgpuMetadata), byref(c_bufferSize)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return c_vgpuPgpuMetadata + + +def nvmlGetVgpuCompatibility(vgpuMetadata, pgpuMetadata): + fn = _nvmlGetFunctionPointer("nvmlGetVgpuCompatibility") + c_vgpuPgpuCompatibility = c_nvmlVgpuPgpuCompatibility_t() + ret = fn(byref(vgpuMetadata), byref(pgpuMetadata), byref(c_vgpuPgpuCompatibility)) + _nvmlCheckReturn(ret) + return c_vgpuPgpuCompatibility + + +@convertStrBytes +def nvmlDeviceGetPgpuMetadataString(handle): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPgpuMetadataString") + c_pgpuMetadata = create_string_buffer(NVML_VGPU_PGPU_METADATA_OPAQUE_DATA_SIZE) + c_bufferSize = c_uint(0) + # Make the first NVML API call to get the c_bufferSize value. + # We have already allocated required buffer above. + ret = fn(handle, byref(c_pgpuMetadata), byref(c_bufferSize)) + if ret == NVML_ERROR_INSUFFICIENT_SIZE: + ret = fn(handle, byref(c_pgpuMetadata), byref(c_bufferSize)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return (c_pgpuMetadata.value, c_bufferSize.value) + + +def nvmlSetVgpuVersion(vgpuVersion): + fn = _nvmlGetFunctionPointer("nvmlSetVgpuVersion") + ret = fn(byref(vgpuVersion)) + _nvmlCheckReturn(ret) + return ret + + +def nvmlGetVgpuVersion(supported, current): + fn = _nvmlGetFunctionPointer("nvmlGetVgpuVersion") + ret = fn(byref(supported), byref(current)) + _nvmlCheckReturn(ret) + return ret + + +def nvmlVgpuInstanceGetAccountingMode(vgpuInstance): + c_mode = _nvmlEnableState_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetAccountingMode") + ret = fn(vgpuInstance, byref(c_mode)) + _nvmlCheckReturn(ret) + return c_mode.value + + +def nvmlVgpuInstanceGetAccountingPids(vgpuInstance): + c_pidCount = c_uint() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetAccountingPids") + ret = fn(vgpuInstance, byref(c_pidCount), None) + if ret == NVML_ERROR_INSUFFICIENT_SIZE: + sampleArray = c_pidCount.value * c_uint + c_pidArray = sampleArray() + ret = fn(vgpuInstance, byref(c_pidCount), byref(c_pidArray)) + _nvmlCheckReturn(ret) + else: + raise NVMLError(ret) + return (c_pidCount, c_pidArray) + + +def nvmlVgpuInstanceGetAccountingStats(vgpuInstance, pid): + c_accountingStats = c_nvmlAccountingStats_t() + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceGetAccountingStats") + ret = fn(vgpuInstance, pid, byref(c_accountingStats)) + _nvmlCheckReturn(ret) + return c_accountingStats + + +def nvmlVgpuInstanceClearAccountingPids(vgpuInstance): + fn = _nvmlGetFunctionPointer("nvmlVgpuInstanceClearAccountingPids") + ret = fn(vgpuInstance) + _nvmlCheckReturn(ret) + return ret + + +def nvmlGetExcludedDeviceCount(): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlGetExcludedDeviceCount") + ret = fn(byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlGetExcludedDeviceInfoByIndex(index): + c_index = c_uint(index) + info = c_nvmlExcludedDeviceInfo_t() + fn = _nvmlGetFunctionPointer("nvmlGetExcludedDeviceInfoByIndex") + ret = fn(c_index, byref(info)) + _nvmlCheckReturn(ret) + return info + + +def nvmlDeviceGetHostVgpuMode(handle): + c_host_vgpu_mode = _nvmlHostVgpuMode_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetHostVgpuMode") + ret = fn(handle, byref(c_host_vgpu_mode)) + _nvmlCheckReturn(ret) + return c_host_vgpu_mode.value + + +def nvmlDeviceSetMigMode(device, mode): + c_activationStatus = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceSetMigMode") + ret = fn(device, mode, byref(c_activationStatus)) + _nvmlCheckReturn(ret) + return c_activationStatus.value + + +def nvmlDeviceGetMigMode(device): + c_currentMode = c_uint() + c_pendingMode = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMigMode") + ret = fn(device, byref(c_currentMode), byref(c_pendingMode)) + _nvmlCheckReturn(ret) + return [c_currentMode.value, c_pendingMode.value] + + +def nvmlDeviceGetGpuInstanceProfileInfo(device, profile, version=2): + if version == 2: + c_info = c_nvmlGpuInstanceProfileInfo_v2_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceProfileInfoV") + elif version == 1: + c_info = c_nvmlGpuInstanceProfileInfo_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceProfileInfo") + else: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + ret = fn(device, profile, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +# Define function alias for the API exposed by NVML +nvmlDeviceGetGpuInstanceProfileInfoV = nvmlDeviceGetGpuInstanceProfileInfo + + +def nvmlDeviceGetGpuInstanceRemainingCapacity(device, profileId): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceRemainingCapacity") + ret = fn(device, profileId, byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlDeviceGetGpuInstancePossiblePlacements(device, profileId, placementsRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstancePossiblePlacements_v2") + ret = fn(device, profileId, placementsRef, countRef) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceCreateGpuInstance(device, profileId): + c_instance = c_nvmlGpuInstance_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceCreateGpuInstance") + ret = fn(device, profileId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + + +def nvmlDeviceCreateGpuInstanceWithPlacement(device, profileId, placement): + c_instance = c_nvmlGpuInstance_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceCreateGpuInstanceWithPlacement") + ret = fn(device, profileId, placement, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + + +def nvmlGpuInstanceDestroy(gpuInstance): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceDestroy") + ret = fn(gpuInstance) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetGpuInstances(device, profileId, gpuInstancesRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstances") + ret = fn(device, profileId, gpuInstancesRef, countRef) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetGpuInstanceById(device, gpuInstanceId): + c_instance = c_nvmlGpuInstance_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceById") + ret = fn(device, gpuInstanceId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + + +def nvmlGpuInstanceGetInfo(gpuInstance): + c_info = c_nvmlGpuInstanceInfo_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetInfo") + ret = fn(gpuInstance, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +def nvmlGpuInstanceGetComputeInstanceProfileInfo(device, profile, engProfile, version=2): + if version == 2: + c_info = c_nvmlComputeInstanceProfileInfo_v2_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceProfileInfoV") + elif version == 1: + c_info = c_nvmlComputeInstanceProfileInfo_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceProfileInfo") + else: + raise NVMLError(NVML_ERROR_FUNCTION_NOT_FOUND) + ret = fn(device, profile, engProfile, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +# Define function alias for the API exposed by NVML +nvmlGpuInstanceGetComputeInstanceProfileInfoV = nvmlGpuInstanceGetComputeInstanceProfileInfo + + +def nvmlGpuInstanceGetComputeInstanceRemainingCapacity(gpuInstance, profileId): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceRemainingCapacity") + ret = fn(gpuInstance, profileId, byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlGpuInstanceCreateComputeInstance(gpuInstance, profileId): + c_instance = c_nvmlComputeInstance_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceCreateComputeInstance") + ret = fn(gpuInstance, profileId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + + +def nvmlComputeInstanceDestroy(computeInstance): + fn = _nvmlGetFunctionPointer("nvmlComputeInstanceDestroy") + ret = fn(computeInstance) + _nvmlCheckReturn(ret) + return ret + + +def nvmlGpuInstanceGetComputeInstances(gpuInstance, profileId, computeInstancesRef, countRef): + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstances") + ret = fn(gpuInstance, profileId, computeInstancesRef, countRef) + _nvmlCheckReturn(ret) + return ret + + +def nvmlGpuInstanceGetComputeInstanceById(gpuInstance, computeInstanceId): + c_instance = c_nvmlComputeInstance_t() + fn = _nvmlGetFunctionPointer("nvmlGpuInstanceGetComputeInstanceById") + ret = fn(gpuInstance, computeInstanceId, byref(c_instance)) + _nvmlCheckReturn(ret) + return c_instance + + +def nvmlComputeInstanceGetInfo_v2(computeInstance): + c_info = c_nvmlComputeInstanceInfo_t() + fn = _nvmlGetFunctionPointer("nvmlComputeInstanceGetInfo_v2") + ret = fn(computeInstance, byref(c_info)) + _nvmlCheckReturn(ret) + return c_info + + +def nvmlComputeInstanceGetInfo(computeInstance): + return nvmlComputeInstanceGetInfo_v2(computeInstance) + + +def nvmlDeviceIsMigDeviceHandle(device): + c_isMigDevice = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceIsMigDeviceHandle") + ret = fn(device, byref(c_isMigDevice)) + _nvmlCheckReturn(ret) + return c_isMigDevice + + +def nvmlDeviceGetGpuInstanceId(device): + c_gpuInstanceId = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpuInstanceId") + ret = fn(device, byref(c_gpuInstanceId)) + _nvmlCheckReturn(ret) + return c_gpuInstanceId.value + + +def nvmlDeviceGetComputeInstanceId(device): + c_computeInstanceId = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetComputeInstanceId") + ret = fn(device, byref(c_computeInstanceId)) + _nvmlCheckReturn(ret) + return c_computeInstanceId.value + + +def nvmlDeviceGetMaxMigDeviceCount(device): + c_count = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMaxMigDeviceCount") + ret = fn(device, byref(c_count)) + _nvmlCheckReturn(ret) + return c_count.value + + +def nvmlDeviceGetMigDeviceHandleByIndex(device, index): + c_index = c_uint(index) + migDevice = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMigDeviceHandleByIndex") + ret = fn(device, c_index, byref(migDevice)) + _nvmlCheckReturn(ret) + return migDevice + + +def nvmlDeviceGetDeviceHandleFromMigDeviceHandle(migDevice): + device = c_nvmlDevice_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDeviceHandleFromMigDeviceHandle") + ret = fn(migDevice, byref(device)) + _nvmlCheckReturn(ret) + return device + + +def nvmlDeviceGetAttributes_v2(device): + c_attrs = c_nvmlDeviceAttributes() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAttributes_v2") + ret = fn(device, byref(c_attrs)) + _nvmlCheckReturn(ret) + return c_attrs + + +def nvmlDeviceGetAttributes(device): + return nvmlDeviceGetAttributes_v2(device) + + +def nvmlDeviceGetRemappedRows(device): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRemappedRows") + c_corr = c_uint() + c_unc = c_uint() + c_bpending = c_uint() + c_bfailure = c_uint() + ret = fn(device, byref(c_corr), byref(c_unc), byref(c_bpending), byref(c_bfailure)) + _nvmlCheckReturn(ret) + return (c_corr.value, c_unc.value, c_bpending.value, c_bfailure.value) + + +def nvmlDeviceGetRowRemapperHistogram(device): + c_vals = c_nvmlRowRemapperHistogramValues() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetRowRemapperHistogram") + ret = fn(device, byref(c_vals)) + _nvmlCheckReturn(ret) + return c_vals + + +def nvmlDeviceGetArchitecture(device): + arch = _nvmlDeviceArchitecture_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetArchitecture") + ret = fn(device, byref(arch)) + _nvmlCheckReturn(ret) + return arch.value + + +def nvmlDeviceGetBusType(device): + c_busType = _nvmlBusType_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetBusType") + ret = fn(device, byref(c_busType)) + _nvmlCheckReturn(ret) + return c_busType.value + + +def nvmlDeviceGetIrqNum(device): + c_irqNum = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetIrqNum") + ret = fn(device, byref(c_irqNum)) + _nvmlCheckReturn(ret) + return c_irqNum.value + + +def nvmlDeviceGetNumGpuCores(device): + c_numCores = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetNumGpuCores") + ret = fn(device, byref(c_numCores)) + _nvmlCheckReturn(ret) + return c_numCores.value + + +def nvmlDeviceGetPowerSource(device): + c_powerSource = _nvmlPowerSource_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerSource") + ret = fn(device, byref(c_powerSource)) + _nvmlCheckReturn(ret) + return c_powerSource.value + + +def nvmlDeviceGetMemoryBusWidth(device): + c_memBusWidth = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryBusWidth") + ret = fn(device, byref(c_memBusWidth)) + _nvmlCheckReturn(ret) + return c_memBusWidth.value + + +def nvmlDeviceGetPcieLinkMaxSpeed(device): + c_speed = _nvmlPcieLinkMaxSpeed_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieLinkMaxSpeed") + ret = fn(device, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + + +def nvmlDeviceGetAdaptiveClockInfoStatus(device): + c_adaptiveClockInfoStatus = _nvmlAdaptiveClockInfoStatus_t() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetAdaptiveClockInfoStatus") + ret = fn(device, byref(c_adaptiveClockInfoStatus)) + _nvmlCheckReturn(ret) + return c_adaptiveClockInfoStatus.value + + +def nvmlDeviceGetPcieSpeed(device): + c_speed = c_uint() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetPcieSpeed") + ret = fn(device, byref(c_speed)) + _nvmlCheckReturn(ret) + return c_speed.value + + +def nvmlDeviceGetDynamicPstatesInfo(device, c_dynamicpstatesinfo): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetDynamicPstatesInfo") + ret = fn(device, c_dynamicpstatesinfo) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceSetFanSpeed_v2(handle, index, speed): + fn = _nvmlGetFunctionPointer("nvmlDeviceSetFanSpeed_v2") + ret = fn(handle, index, speed) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetThermalSettings(device, sensorindex, c_thermalsettings): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetThermalSettings") + ret = fn(device, sensorindex, c_thermalsettings) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetMinMaxClockOfPState(device, type, pstate, minClockMHz, maxClockMHz): + fn = _nvmlGetFunctionPointer("nvmlDeviceGetMinMaxClockOfPState") + ret = fn( + device, + _nvmlClockType_t(type), + _nvmlClockType_t(pstate), + minClockMHz, + maxClockMHz, + ) + _nvmlCheckReturn(ret) + return ret + + +def nvmlDeviceGetSupportedPerformanceStates(device): + pstates = [] + c_count = c_uint(NVML_MAX_GPU_PERF_PSTATES) + c_size = sizeof(c_uint) * c_count.value + + # NOTE: use 'c_uint' to represent the size of the nvmlPstate_t enumeration. + pstates_array = _nvmlPstates_t * c_count.value + c_pstates = pstates_array() + + fn = _nvmlGetFunctionPointer("nvmlDeviceGetSupportedPerformanceStates") + ret = fn(device, c_pstates, c_size) + _nvmlCheckReturn(ret) + + for value in c_pstates: + if value != NVML_PSTATE_UNKNOWN: + pstates.append(value) + + return pstates + + +def nvmlDeviceGetGpcClkVfOffset(device): + offset = c_int32() + fn = _nvmlGetFunctionPointer("nvmlDeviceGetGpcClkVfOffset") + ret = fn(device, byref(offset)) + _nvmlCheckReturn(ret) + return offset.value + + +def nvmlDeviceSetGpcClkVfOffset(device, offset): + c_offset = c_int32(offset) + fn = _nvmlGetFunctionPointer("nvmlDeviceSetGpcClkVfOffset") + ret = fn(device, c_offset) + _nvmlCheckReturn(ret) + return ret diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/python_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/python_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fca11426dc8a6f4fc4213d4c1aaacaf41e857da6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/python_utils.py @@ -0,0 +1,884 @@ +""" +A set of utility functions for general python usage +""" + +import inspect +from abc import ABCMeta +from collections.abc import Iterable +from copy import deepcopy +from functools import wraps +from hashlib import md5 +from importlib import import_module +import sys + +import h5py +import torch as th + +# Global dictionary storing all unique names +NAMES = set() +CLASS_NAMES = set() + + +class classproperty: + def __init__(self, fget): + self.fget = fget + + def __get__(self, owner_self, owner_cls): + return self.fget(owner_cls) + + +def subclass_factory(name, base_classes, __init__=None, **kwargs): + """ + Programmatically generates a new class type with name @name, subclassing from base classes @base_classes, with + corresponding __init__ call @__init__. + + NOTE: If __init__ is None (default), the __init__ call from @base_classes will be used instead. + + cf. https://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class + + Args: + name (str): Generated class name + base_classes (type, or list of type): Base class(es) to use for generating the subclass + __init__ (None or function): Init call to use for the base class when it is instantiated. If None if specified, + the newly generated class will automatically inherit the __init__ call from @base_classes + **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent + the class / instance attribute to modify and the values represent the functions / value to set + """ + # Standardize base_classes + base_classes = tuple(base_classes if isinstance(base_classes, Iterable) else [base_classes]) + + # Generate the new class + if __init__ is not None: + kwargs["__init__"] = __init__ + return type(name, base_classes, kwargs) + + +def save_init_info(func): + """ + Decorator to save the init info of an object to object._init_info. + + _init_info contains class name and class constructor's input args. + """ + sig = inspect.signature(func) + + @wraps(func) # preserve func name, docstring, arguments list, etc. + def wrapper(self, *args, **kwargs): + values = sig.bind(self, *args, **kwargs) + + # Prevent args of super init from being saved. + if hasattr(self, "_init_info"): + func(*values.args, **values.kwargs) + return + + # Initialize class's self._init_info. + self._init_info = {} + self._init_info["class_module"] = self.__class__.__module__ + self._init_info["class_name"] = self.__class__.__name__ + self._init_info["args"] = {} + + # Populate class's self._init_info. + for k, p in sig.parameters.items(): + if k == "self": + continue + if k in values.arguments: + val = values.arguments[k] + if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY): + self._init_info["args"][k] = val + elif p.kind == inspect.Parameter.VAR_KEYWORD: + for kwarg_k, kwarg_val in values.arguments[k].items(): + self._init_info["args"][kwarg_k] = kwarg_val + + # Call the original function. + func(*values.args, **values.kwargs) + + return wrapper + + +class RecreatableMeta(type): + """ + Simple metaclass that automatically saves __init__ args of the instances it creates. + """ + + def __new__(cls, clsname, bases, clsdict): + if "__init__" in clsdict: + clsdict["__init__"] = save_init_info(clsdict["__init__"]) + return super().__new__(cls, clsname, bases, clsdict) + + +class RecreatableAbcMeta(RecreatableMeta, ABCMeta): + """ + A composite metaclass of both RecreatableMeta and ABCMeta. + + Adding in ABCMeta to resolve metadata conflicts. + """ + + pass + + +class Recreatable(metaclass=RecreatableAbcMeta): + """ + Simple class that provides an abstract interface automatically saving __init__ args of + the classes inheriting it. + """ + + def get_init_info(self): + """ + Grabs relevant initialization information for this class instance. Useful for directly + reloading an object from this information, using @create_object_from_init_info. + + Returns: + dict: Nested dictionary that contains this object's initialization information + """ + # Note: self._init_info is procedurally generated via @save_init_info called in metaclass + return self._init_info + + +def create_object_from_init_info(init_info): + """ + Create a new object based on given init info. + + Args: + init_info (dict): Nested dictionary that contains an object's init information. + + Returns: + any: Newly created object. + """ + module = import_module(init_info["class_module"]) + cls = getattr(module, init_info["class_name"]) + return cls(**init_info["args"], **init_info.get("kwargs", {})) + + +def safe_equal(a, b): + if isinstance(a, th.Tensor) and isinstance(b, th.Tensor): + return a.shape == b.shape and (a == b).all().item() + elif isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): + return len(a) == len(b) and all(safe_equal(a_item, b_item) for a_item, b_item in zip(a, b)) + else: + return a == b + + +def merge_nested_dicts(base_dict, extra_dict, inplace=False, verbose=False): + """ + Iteratively updates @base_dict with values from @extra_dict. Note: This generates a new dictionary! + + Args: + base_dict (dict): Nested base dictionary, which should be updated with all values from @extra_dict + extra_dict (dict): Nested extra dictionary, whose values will overwrite corresponding ones in @base_dict + inplace (bool): Whether to modify @base_dict in place or not + verbose (bool): If True, will print when keys are mismatched + + Returns: + dict: Updated dictionary + """ + # Loop through all keys in @extra_dict and update the corresponding values in @base_dict + base_dict = base_dict if inplace else deepcopy(base_dict) + for k, v in extra_dict.items(): + if k not in base_dict: + base_dict[k] = v + else: + if isinstance(v, dict) and isinstance(base_dict[k], dict): + base_dict[k] = merge_nested_dicts(base_dict[k], v) + else: + equal = safe_equal(base_dict[k], v) + if not equal and verbose: + print(f"Different values for key {k}: {base_dict[k]}, {v}\n") + base_dict[k] = v + + # Return new dict + return base_dict + + +def get_class_init_kwargs(cls): + """ + Helper function to return a list of all valid keyword arguments (excluding "self") for the given @cls class. + + Args: + cls (object): Class from which to grab __init__ kwargs + + Returns: + list: All keyword arguments (excluding "self") specified by @cls __init__ constructor method + """ + # Fall back to signature inspection for regular classes + return list(inspect.signature(cls.__init__).parameters.keys())[1:] + + +def extract_subset_dict(dic, keys, copy=False): + """ + Helper function to extract a subset of dictionary key-values from a current dictionary. Optionally (deep)copies + the values extracted from the original @dic if @copy is True. + + Args: + dic (dict): Dictionary containing multiple key-values + keys (Iterable): Specific keys to extract from @dic. If the key doesn't exist in @dic, then the key is skipped + copy (bool): If True, will deepcopy all values corresponding to the specified @keys + + Returns: + dict: Extracted subset dictionary containing only the specified @keys and their corresponding values + """ + subset = {k: dic[k] for k in keys if k in dic} + return deepcopy(subset) if copy else subset + + +def extract_class_init_kwargs_from_dict(cls, dic, copy=False): + """ + Helper function to return a dictionary of key-values that specifically correspond to @cls class's __init__ + constructor method, from @dic which may or may not contain additional, irrelevant kwargs. + Note that @dic may possibly be missing certain kwargs as specified by cls.__init__. No error will be raised. + + Args: + cls (object): Class from which to grab __init__ kwargs that will be be used as filtering keys for @dic + dic (dict): Dictionary containing multiple key-values + copy (bool): If True, will deepcopy all values corresponding to the specified @keys + + Returns: + dict: Extracted subset dictionary possibly containing only the specified keys from cls.__init__ and their + corresponding values + """ + # extract only relevant kwargs for this specific backbone + return extract_subset_dict( + dic=dic, + keys=get_class_init_kwargs(cls), + copy=copy, + ) + + +def assert_valid_key(key, valid_keys, name=None): + """ + Helper function that asserts that @key is in dictionary @valid_keys keys. If not, it will raise an error. + + Args: + key (any): key to check for in dictionary @dic's keys + valid_keys (Iterable): contains keys should be checked with @key + name (str or None): if specified, is the name associated with the key that will be printed out if the + key is not found. If None, default is "value" + """ + if name is None: + name = "value" + assert key in valid_keys, "Invalid {} received! Valid options are: {}, got: {}".format( + name, valid_keys.keys() if isinstance(valid_keys, dict) else valid_keys, key + ) + + +def create_class_from_registry_and_config(cls_name, cls_registry, cfg, cls_type_descriptor): + """ + Helper function to create a class with str type @cls_name, which should be a valid entry in @cls_registry, using + kwargs in dictionary form @cfg to pass to the constructor, with @cls_type_name specified for debugging + + Args: + cls_name (str): Name of the class to create. This should correspond to the actual class type, in string form + cls_registry (dict): Class registry. This should map string names of valid classes to create to the + actual class type itself + cfg (dict): Any keyword arguments to pass to the class constructor + cls_type_descriptor (str): Description of the class type being created. This can be any string and is used + solely for debugging purposes + + Returns: + any: Created class instance + """ + # Make sure the requested class type is valid + assert_valid_key(key=cls_name, valid_keys=cls_registry, name=f"{cls_type_descriptor} type") + + # Grab the kwargs relevant for the specific class + cls = cls_registry[cls_name] + cls_kwargs = extract_class_init_kwargs_from_dict(cls=cls, dic=cfg, copy=False) + + # Create the class + return cls(**cls_kwargs) + + +def get_uuid(name, n_digits=8, deterministic=True): + """ + Helper function to create a unique @n_digits uuid given a unique @name + + Args: + name (str): Name of the object or class + n_digits (int): Number of digits of the uuid, default is 8 + deterministic (bool): Whether the outputted UUID should be deterministic or not + + Returns: + int: uuid + """ + # Make sure the number is float32 compatible + val = int(md5(name.encode()).hexdigest(), 16) if deterministic else abs(hash(name)) + return int(th.tensor(val % (10**n_digits), dtype=th.float32).item()) + + +def meets_minimum_version(test_version, minimum_version): + """ + Verify that @test_version meets the @minimum_version + + Args: + test_version (str): Python package version. Should be, e.g., 0.26.1 + minimum_version (str): Python package version to test against. Should be, e.g., 0.27.2 + + Returns: + bool: Whether @test_version meets @minimum_version + """ + test_nums = [int(num) for num in test_version.split(".")] + minimum_nums = [int(num) for num in minimum_version.split(".")] + assert len(test_nums) == 3 + assert len(minimum_nums) == 3 + + for test_num, minimum_num in zip(test_nums, minimum_nums): + if test_num > minimum_num: + return True + elif test_num < minimum_num: + return False + # Otherwise, we continue through all sub-versions + + # If we get here, that means test_version == threshold_version, so this is a success + return True + + +class Registerable: + """ + Simple class template that provides an abstract interface for registering classes. + """ + + def __init_subclass__(cls, **kwargs): + """ + Registers all subclasses as part of this registry. This is useful to decouple internal codebase from external + user additions. This way, users can add their custom subclasses by simply extending this class, + and it will automatically be registered internally. This allows users to then specify their classes + directly in string-form in e.g., their config files, without having to manually set the str-to-class mapping + in our code. + """ + cls._register_cls() + + @classmethod + def _register_cls(cls): + """ + Register this class. Can be extended by subclass. + """ + # print(f"registering: {cls.__name__}") + # print(f"registry: {cls._cls_registry}", cls.__name__ not in cls._cls_registry) + # print(f"do not register: {cls._do_not_register_classes}", cls.__name__ not in cls._do_not_register_classes) + # input() + if cls.__name__ not in cls._cls_registry and cls.__name__ not in cls._do_not_register_classes: + cls._cls_registry[cls.__name__] = cls + + @classproperty + def _do_not_register_classes(cls): + """ + Returns: + set of str: Name(s) of classes that should not be registered. Default is empty set. + Subclasses that shouldn't be added should call super() and then add their own class name to the set + """ + return set() + + @classproperty + def _cls_registry(cls): + """ + Returns: + dict: Mapping from all registered class names to their classes. This should be a REFERENCE + to some external, global dictionary that will be filled-in at runtime. + """ + raise NotImplementedError() + + +class Serializable: + """ + Simple class that provides an abstract interface to dump / load states, optionally with serialized functionality + as well. + """ + + def _dump_state(self): + """ + Dumps the state of this object in dictionary form (can be empty). Should be implemented by subclass. + + Returns: + dict: Keyword-mapped states of this object + """ + raise NotImplementedError() + + def dump_state(self, serialized=False): + """ + Dumps the state of this object in either dictionary of flattened numerical form. + + Args: + serialized (bool): If True, will return the state of this object as a 1D numpy array. Otherewise, will return + a (potentially nested) dictionary of states for this object + + Returns: + dict or n-array: Either: + - Keyword-mapped states of this object, or + - encoded + serialized, 1D numerical th.tensor capturing this object's state + """ + state = self._dump_state() + return self.serialize(state=state) if serialized else state + + def _load_state(self, state): + """ + Load the internal state to this object as specified by @state. Should be implemented by subclass. + + Args: + state (dict): Keyword-mapped states of this object to set + """ + raise NotImplementedError() + + def load_state(self, state, serialized=False): + """ + Deserializes and loads this object's state based on @state + + Args: + state (dict or n-array): Either: + - Keyword-mapped states of this object, or + - encoded + serialized, 1D numerical th.tensor capturing this object's state. + serialized (bool): If True, will interpret @state as a 1D numpy array. Otherewise, will assume the input is + a (potentially nested) dictionary of states for this object + """ + if serialized: + orig_state_len = len(state) + state, deserialized_items = self.deserialize(state=state) + assert deserialized_items == orig_state_len, ( + f"Invalid state deserialization occurred! Expected {orig_state_len} total " + f"values to be deserialized, only {deserialized_items} were." + ) + self._load_state(state=state) + + def serialize(self, state): + """ + Serializes nested dictionary state @state into a flattened 1D numpy array for encoding efficiency. + Should be implemented by subclass. + + Args: + state (dict): Keyword-mapped states of this object to encode. Should match structure of output from + self._dump_state() + + Returns: + n-array: encoded + serialized, 1D numerical th.tensor capturing this object's state + """ + raise NotImplementedError() + + def deserialize(self, state): + """ + De-serializes flattened 1D numpy array @state into nested dictionary state. + Should be implemented by subclass. + + Args: + state (n-array): encoded + serialized, 1D numerical th.tensor capturing this object's state + + Returns: + 2-tuple: + - dict: Keyword-mapped states of this object. Should match structure of output from + self._dump_state() + - int: current index of the flattened state vector that is left off. This is helpful for subclasses + that inherit partial deserializations from parent classes, and need to know where the + deserialization left off before continuing. + """ + raise NotImplementedError + + +class SerializableNonInstance: + """ + Identical to Serializable, but intended for non-instanceable classes + """ + + @classmethod + def _dump_state(cls): + """ + Dumps the state of this object in dictionary form (can be empty). Should be implemented by subclass. + + Returns: + dict: Keyword-mapped states of this object + """ + raise NotImplementedError() + + @classmethod + def dump_state(cls, serialized=False): + """ + Dumps the state of this object in either dictionary of flattened numerical form. + + Args: + serialized (bool): If True, will return the state of this object as a 1D numpy array. Otherewise, will return + a (potentially nested) dictionary of states for this object + + Returns: + dict or n-array: Either: + - Keyword-mapped states of this object, or + - encoded + serialized, 1D numerical th.tensor capturing this object's state. + """ + state = cls._dump_state() + return cls.serialize(state=state) if serialized else state + + @classmethod + def _load_state(cls, state): + """ + Load the internal state to this object as specified by @state. Should be implemented by subclass. + + Args: + state (dict): Keyword-mapped states of this object to set + """ + raise NotImplementedError() + + @classmethod + def load_state(cls, state, serialized=False): + """ + Deserializes and loads this object's state based on @state + + Args: + state (dict or n-array): Either: + - Keyword-mapped states of this object, or + - encoded + serialized, 1D numerical th.tensor capturing this object's state. + serialized (bool): If True, will interpret @state as a 1D numpy array. Otherewise, will assume the input is + a (potentially nested) dictionary of states for this object + """ + if serialized: + orig_state_len = len(state) + state, deserialized_items = cls.deserialize(state=state) + assert deserialized_items == orig_state_len, ( + f"Invalid state deserialization occurred! Expected {orig_state_len} total " + f"values to be deserialized, only {deserialized_items} were." + ) + cls._load_state(state=state) + + @classmethod + def serialize(cls, state): + """ + Serializes nested dictionary state @state into a flattened 1D numpy array for encoding efficiency. + Should be implemented by subclass. + + Args: + state (dict): Keyword-mapped states of this object to encode. Should match structure of output from + self._dump_state() + + Returns: + n-array: encoded + serialized, 1D numerical th.tensor capturing this object's state + """ + # Simply returns self.serialize() for now. this is for future proofing + return NotImplementedError() + + @classmethod + def deserialize(cls, state): + """ + De-serializes flattened 1D numpy array @state into nested dictionary state. + Should be implemented by subclass. + + Args: + state (n-array): encoded + serialized, 1D numerical th.tensor capturing this object's state + + Returns: + 2-tuple: + - dict: Keyword-mapped states of this object. Should match structure of output from + self._dump_state() + - int: current index of the flattened state vector that is left off. This is helpful for subclasses + that inherit partial deserializations from parent classes, and need to know where the + deserialization left off before continuing. + """ + raise NotImplementedError + + +class CachedFunctions: + """ + Thin object which owns a dictionary in which each entry should be a function -- when a key is queried via get() + and it exists, it will call the function exactly once, and cache the value so that subsequent calls will refer + to the cached value. + + This allows the dictionary to be created with potentially expensive operations, but only queried up to exaclty once + as needed. + """ + + def __init__(self, **kwargs): + # Create internal dict to store functions + self._fcns = dict() + self._cache = dict() + for kwarg in kwargs: + self._fcns[kwarg] = kwargs[kwarg] + + def __getitem__(self, item): + return self.get(name=item) + + def __setitem__(self, key, value): + self.add_fcn(name=key, fcn=value) + + def get(self, name): + """ + Computes the function referenced by @name with the corresponding @args and @kwargs. Note that for a unique + set of arguments, this value will be internally cached + + Args: + name (str): The name of the function to call + + Returns: + any: Output of the function referenced by @name + """ + if name not in self._cache: + self._cache[name] = self._fcns[name]() + return self._cache[name] + + def get_fcn(self, name): + """ + Gets the raw stored function referenced by @name + + Args: + name (str): The name of the function to grab + + Returns: + function: The stored function + """ + return self._fcns[name] + + def get_fcn_names(self): + """ + Get all stored function names + + Returns: + tuple of str: Names of stored functions + """ + return tuple(self._fcns.keys()) + + def add_fcn(self, name, fcn): + """ + Adds a function to the internal registry. + + Args: + name (str): Name of the function. This is the name that should be queried with self.get() + fcn (function): Function to add. Can be an arbitrary signature + """ + assert callable(fcn), "Only functions can be added via add_fcn!" + self._fcns[name] = fcn + + +class Wrapper: + """ + Base class for all wrappers in OmniGibson + + Args: + obj (any): Arbitrary python object instance to wrap + """ + + def __init__(self, obj): + # Set the internal attributes -- store wrapped obj + self.wrapped_obj = obj + + @classmethod + def class_name(cls): + return cls.__name__ + + def _warn_double_wrap(self): + """ + Utility function that checks if we're accidentally trying to double wrap an env + Raises: + Exception: [Double wrapping env] + """ + obj = self.wrapped_obj + while True: + if isinstance(obj, Wrapper): + if obj.class_name() == self.class_name(): + raise Exception("Attempted to double wrap with Wrapper: {}".format(self.__class__.__name__)) + obj = obj.wrapped_obj + else: + break + + @property + def unwrapped(self): + """ + Grabs unwrapped object + + Returns: + any: The unwrapped object instance + """ + return self.wrapped_obj.unwrapped if hasattr(self.wrapped_obj, "unwrapped") else self.wrapped_obj + + # this method is a fallback option on any methods the original env might support + def __getattr__(self, attr): + # If we're querying wrapped_obj, raise an error + if attr == "wrapped_obj": + raise AttributeError("wrapped_obj attribute not initialized yet!") + + # Sanity check to make sure wrapped obj is not None -- if so, raise error + assert self.wrapped_obj is not None, f"Cannot access attribute {attr} since wrapped_obj is None!" + + # using getattr ensures that both __getattribute__ and __getattr__ (fallback) get called + # (see https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute) + orig_attr = getattr(self.wrapped_obj, attr) + if callable(orig_attr): + + def hooked(*args, **kwargs): + result = orig_attr(*args, **kwargs) + # prevent wrapped_class from becoming unwrapped + if id(result) == id(self.wrapped_obj): + return self + return result + + return hooked + else: + return orig_attr + + def __setattr__(self, key, value): + # Call setattr on wrapped obj if it has the attribute, otherwise, operate on this object + if hasattr(self, "wrapped_obj") and self.wrapped_obj is not None and hasattr(self.wrapped_obj, key): + setattr(self.wrapped_obj, key, value) + else: + super().__setattr__(key, value) + + +def torch_compile(func): + """ + Decorator to compile a function with torch.compile on Linux and torch.jit.script on Windows. This is because of poor support for torch.compile on Windows. + + Args: + func (function): Function to compile + + Returns: + function: Compiled function + """ + # If we're on Windows, return a jitscript option + if sys.platform == "win32": + return th.jit.script(func) + # Otherwise, return a torch.compile option + else: + return th.compile(func) + + +def nums2array(nums, dim, dtype=th.float32): + """ + Converts input @nums into numpy array of length @dim. If @nums is a single number, broadcasts input to + corresponding dimension size @dim before converting into numpy array + + Args: + nums (float or array): Numbers to map to numpy array + dim (int): Size of array to broadcast input to + + Returns: + torch.Tensor: Mapped input numbers + """ + # Make sure the inputted nums isn't a string + assert not isinstance(nums, str), "Only numeric types are supported for this operation!" + + out = th.tensor(nums, dtype=dtype) if isinstance(nums, Iterable) else th.ones(dim, dtype=dtype) * nums + + return out + + +def clear(): + """ + Clear state tied to singleton classes + """ + NAMES.clear() + CLASS_NAMES.clear() + + +def torch_delete(tensor: th.Tensor, indices: th.Tensor | int, dim: int | None = None) -> th.Tensor: + """ + Delete elements from a tensor along a specified dimension. + + Parameters: + tensor (torch.Tensor): Input tensor. + indices (int or torch.Tensor): Indices of elements to remove. + dim (int, optional): The dimension along which to delete the elements. + If None, the tensor is flattened before deletion. + + Returns: + torch.Tensor: Tensor with specified elements removed. + """ + assert tensor.dim() > 0, "Input tensor must have at least one dimension" + + if dim is None: + # Flatten the tensor if no dim is specified + tensor = tensor.flatten() + dim = 0 + + if not isinstance(indices, th.Tensor): + indices = th.tensor(indices, dtype=th.long, device=tensor.device) + + assert th.all(indices >= 0) and th.all(indices < tensor.size(dim)), "Indices out of bounds" + + # Create a mask for the indices to keep + keep_indices = th.ones(tensor.size(dim), dtype=th.bool, device=tensor.device) + keep_indices[indices] = False + + return th.index_select(tensor, dim, th.nonzero(keep_indices).squeeze(1)) + + +def recursively_convert_to_torch(state): + # For all the lists in state dict, convert to torch tensor + for key, value in state.items(): + if isinstance(value, dict): + state[key] = recursively_convert_to_torch(value) + elif isinstance(value, list): + # Convert to torch tensor if all elements are numeric and have consistent shapes + try: + state[key] = th.tensor(value, dtype=th.float32) + except: + pass + + return state + + +def recursively_convert_from_torch(state): + # For all the lists in state dict, convert from torch tensor -> numpy array + import numpy as np + + for key, value in state.items(): + if isinstance(value, dict): + state[key] = recursively_convert_from_torch(value) + elif isinstance(value, th.Tensor): + state[key] = value.cpu().numpy() + elif (isinstance(value, list) or isinstance(value, tuple)) and len(value) > 0: + if isinstance(value[0], dict): + state[key] = [recursively_convert_from_torch(val) for val in value] + elif isinstance(value[0], th.Tensor): + state[key] = [tensor.numpy() for tensor in value] + elif isinstance(value[0], int) or isinstance(value[0], float): + state[key] = np.array(value) + return state + + +def h5py_group_to_torch(group): + state = {} + for key, value in group.items(): + if isinstance(value, h5py.Group): + state[key] = h5py_group_to_torch(value) + else: + state[key] = th.from_numpy(value[()]) + return state + + +@th.jit.script +def multi_dim_linspace(start: th.Tensor, stop: th.Tensor, num: int, endpoint: bool = True) -> th.Tensor: + """ + Generate a tensor with evenly spaced values along multiple dimensions. + This function creates a tensor where each slice along the first dimension + contains values linearly interpolated between the corresponding elements + of 'start' and 'stop'. It's similar to numpy.linspace but works with + multi-dimensional inputs in PyTorch. + Args: + start (th.Tensor): Starting values for each dimension. + stop (th.Tensor): Ending values for each dimension. + num (int): Number of samples to generate along the interpolated dimension. + endpoint (bool, optional): If True, stop is the last sample. Otherwise, it is not included. + Returns: + th.Tensor: A tensor of shape (num, *start.shape) containing the interpolated values. + Example: + >>> start = th.tensor([0.0, 10.0, 100.0]) + >>> stop = th.tensor([1.0, 20.0, 200.0]) + >>> result = multi_dim_linspace(start, stop, num=5, endpoint=True) + >>> print(result.shape) + torch.Size([5, 3]) + >>> print(result) + tensor([[ 0.0000, 10.0000, 100.0000], + [ 0.2500, 12.5000, 125.0000], + [ 0.5000, 15.0000, 150.0000], + [ 0.7500, 17.5000, 175.0000], + [ 1.0000, 20.0000, 200.0000]]) + >>> result = multi_dim_linspace(start, stop, num=5, endpoint=False) + >>> print(result.shape) + torch.Size([5, 3]) + >>> print(result) + tensor([[ 0.0000, 10.0000, 100.0000], + [ 0.2000, 12.0000, 120.0000], + [ 0.4000, 14.0000, 140.0000], + [ 0.6000, 16.0000, 160.0000], + [ 0.8000, 18.0000, 180.0000]]) + """ + if endpoint: + steps = th.linspace(0, 1, num, dtype=start.dtype, device=start.device) + else: + steps = th.linspace(0, 1, num + 1, dtype=start.dtype, device=start.device)[:-1] + + # Create a new shape for broadcasting + new_shape = [num] + [1] * start.dim() + steps = steps.reshape(new_shape) + + return start + steps * (stop - start) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/registry_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/registry_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad2fa4730e69ea26d898e24ba358893085b0185 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/registry_utils.py @@ -0,0 +1,502 @@ +""" +A set of utility functions for registering and tracking objects +""" + +from collections.abc import Iterable +from inspect import isclass + +import torch as th + +from omnigibson.macros import create_module_macros +from omnigibson.utils.python_utils import Serializable, SerializableNonInstance, get_uuid +from omnigibson.utils.ui_utils import create_module_logger +from omnigibson.objects.usd_object import USDObject + +# Create module logger +log = create_module_logger(module_name=__name__) + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +# Token identifier for default values if a key doesn't exist in a given object +m.DOES_NOT_EXIST = "DOES_NOT_EXIST" + +m.STABILIZE_SKIPPED_OBJECTS = False + + +class Registry: + """ + Simple class for easily registering and tracking arbitrary objects of the same (or very similar) class types. + + Elements added are automatically organized by attributes specified by @unique_keys and @group_keys, and + can be accessed at runtime by specifying the desired key and indexing value to grab the object(s). + + Default_key is a 1-to-1 mapping: i.e.: a single indexing value will return a single object. + default: "name" -- indexing by object.name (i.e.: every object's name should be unique) + Unique_keys are other 1-to-1 mappings: i.e.: a single indexing value will return a single object. + example: indexing by object.name (every object's name should be unique) + Group_keys are 1-to-many mappings: i.e.: a single indexing value will return a set of objects. + example: indexing by object.in_rooms (many objects can be in a single room) + + Note that if a object's attribute is an array of values, then it will be stored under ALL of its values. + example: object.in_rooms = ["kitchen", "living_room"], indexing by in_rooms with a value of either kitchen OR + living room will return this object as part of its set! + + You can also easily check for membership in this registry, via either the object's name OR the object itself, + e.g.: + + > object.name in registry + > object in registry + + If the latter, note that default_key attribute will automatically be used to search for the object + """ + + def __init__( + self, + name, + class_types=object, + default_key="name", + unique_keys=None, + group_keys=None, + default_value=None, + ): + """ + Args: + name (str): name of this registry + class_types (class or list of class): class expected for all entries in this registry. Default is `object`, + meaning any object entered will be accepted. This is used to sanity check added entries using add() + to make sure their type is correct (either that the entry itself is a valid class, or that they are an + object of the valid class). Note that if a list of classes are passed, any one of the classes are + considered a valid type for added objects + default_key (str): default key by which to reference a given object. This key should be a + publically accessible attribute in a given object (e.g.: object.name) and uniquely identify + any entries + unique_keys (None or list of str or set of str): keys by which to reference a given object. Any key should be a + publically accessible attribute in a given object (e.g.: object.name) + i.e.: these keys should map to a single object + + group_keys (None or list of str): keys by which to reference a group of objects, based on the key + (e.g.: object.room) + i.e.: these keys can map to multiple objects + + e.g.: default is "name" key only, so we will store objects by their object.name attribute + + default_value (any): Default value to use if the attribute @key does not exist in the object + """ + self._name = name + self.class_types = class_types if isinstance(class_types, Iterable) else [class_types] + self.default_key = default_key + self.unique_keys = set([] if unique_keys is None else unique_keys) + self.group_keys = set([] if group_keys is None else group_keys) + self.default_value = default_value + + # We always add in the "name" attribute as well + self.unique_keys.add(self.default_key) + + # Make sure there's no overlap between the unique and group keys + assert len(self.unique_keys.intersection(self.group_keys)) == 0, ( + f"Cannot create registry with unique and group object keys that are the same! " + f"Unique keys: {self.unique_keys}, group keys: {self.group_keys}" + ) + + # Create the dicts programmatically + for k in self.unique_keys.union(self.group_keys): + self.__setattr__(f"_objects_by_{k}", dict()) + + # Run super init + super().__init__() + + @property + def name(self): + return self._name + + def add(self, obj): + """ + Adds Instance @obj to this registry + + Args: + obj (any): Instance to add to this registry + """ + # Make sure that obj is of the correct class type + assert any( + [isinstance(obj, class_type) or issubclass(obj, class_type) for class_type in self.class_types] + ), f"Added object must be either an instance or subclass of one of the following classes: {self.class_types}!" + self._add(obj=obj, keys=self.all_keys) + + def _add(self, obj, keys=None): + """ + Same as self.add, but allows for selective @keys for adding this object to. Useful for internal things, + such as internal updating of mappings + + Args: + obj (any): Instance to add to this registry + keys (None or set or list of str): Which object keys to use for adding the object to mappings. + None is default, which corresponds to all keys + """ + keys = self.all_keys if keys is None else keys + + for k in keys: + obj_attr = self._get_obj_attr(obj=obj, attr=k) + # Standardize input as a list + obj_attr = obj_attr if isinstance(obj_attr, Iterable) and not isinstance(obj_attr, str) else [obj_attr] + + # Loop over all values in this attribute and add to all mappings + for attr in obj_attr: + mapping = self.get_dict(k) + if k in self.unique_keys: + # Handle unique case + if attr in mapping: + log.warning( + f"Instance identifier '{k}' should be unique for adding to this registry mapping! Existing {k}: {attr}" + ) + # Special case for "name" attribute, which should ALWAYS be unique + assert k != "name", "For name attribute, objects MUST be unique." + mapping[attr] = obj + else: + # Not unique case + # Possibly initialize list + if attr not in mapping: + mapping[attr] = set() + mapping[attr].add(obj) + + def remove(self, obj): + """ + Removes object @object from this registry + + Args: + obj (any): Instance to remove from this registry + """ + # Iterate over all keys + for k in self.all_keys: + # Grab the attribute from the object + obj_attr = self._get_obj_attr(obj=obj, attr=k) + # Standardize input as a list + obj_attr = obj_attr if isinstance(obj_attr, Iterable) and not isinstance(obj_attr, str) else [obj_attr] + + # Loop over all values in this attribute and remove them from all mappings + for attr in obj_attr: + mapping = self.get_dict(k) + if k in self.unique_keys: + # Handle unique case -- in this case, we just directly pop the value from the dictionary + mapping.pop(attr) + else: + # Not unique case + # We remove a value from the resulting set + mapping[attr].remove(obj) + + def clear(self): + """ + Removes all owned objects from this registry + """ + # Re-create the owned dicts programmatically + for k in self.unique_keys.union(self.group_keys): + self.__setattr__(f"_objects_by_{k}", dict()) + + def update(self, keys=None): + """ + Updates this registry, refreshing all internal mappings in case an object's value was updated + + Args: + keys (None or str or set or list of str): Which object keys to update. None is default, which corresponds + to all keys + """ + objects = self.objects + keys = self.all_keys if keys is None else (keys if type(keys) in {tuple, list} else [keys]) + + # Delete and re-create all keys mappings + for k in keys: + self.__delattr__(f"_objects_by_{k}") + self.__setattr__(f"_objects_by_{k}", dict()) + + # Iterate over all objects and re-populate the mappings + for obj in objects: + self._add(obj=obj, keys=[k]) + + def object_is_registered(self, obj): + """ + Check if a given object @object is registered + + Args: + obj (any): Instance to check if it is internally registered + """ + return obj in self.objects + + def get_dict(self, key): + """ + Specific mapping dictionary within this registry corresponding to the mappings of @key. + e.g.: if key = "name", this will return the dictionary mapping object.name to objects + + Args: + key (str): Key with which to grab mapping dict from + + Returns: + dict: Mapping from identifiers to object(s) based on @key + """ + return getattr(self, f"_objects_by_{key}") + + def get_ids(self, key): + """ + All identifiers within this registry corresponding to the mappings of @key. + e.g.: if key = "name", this will return all "names" stored internally that index into a object + Args: + key (str): Key with which to grab all identifiers from + + Returns: + set: All identifiers within this registry corresponding to the mappings of @key. + """ + return set(self.get_dict(key=key).keys()) + + def _get_obj_attr(self, obj, attr): + """ + Grabs object's @obj's attribute @attr. Additionally checks to see if @obj is a class or a class instance, and + uses the correct logic + + Args: + obj (any): Object to grab attribute from + attr (str): String name of the attribute to grab + + Return: + any: Attribute @k of @obj + """ + # We try to grab the object's attribute, and if it fails we fallback to the default value + try: + val = getattr(obj, attr) + + except: + val = self.default_value if self.default_value is not None else m.DOES_NOT_EXIST + + return val + + @property + def objects(self): + """ + Get the objects in this registry + + Returns: + list of any: Instances owned by this registry + """ + return list(self.get_dict(self.default_key).values()) + + @property + def object_names(self): + """ + Get the names of the objects in this registry + + Returns: + set of str: Names of the instances owned by this registry + """ + return {obj.name for obj in self.objects} + + @property + def all_keys(self): + """ + Returns: + set of str: All object keys that are valid identification methods to index object(s) + """ + return self.unique_keys.union(self.group_keys) + + def __call__(self, key, value, default_val=None): + """ + Grab the object in this registry based on @key and @value + + Args: + key (str): What identification type to use to grab the requested object(s). + Should be one of @self.all_keys. + value (any): Value to grab. Should be the value of your requested object. attribute + default_val (any): Default value to return if @value is not found + + Returns: + any or set of any: requested unique object if @key is one of unique_keys, else a set if + @key is one of group_keys + """ + assert key in self.all_keys, f"Invalid key requested! Valid options are: {self.all_keys}, got: {key}" + + return self.get_dict(key).get(value, default_val) + + def __contains__(self, obj): + # Instance can be either a string (default key) OR the object itself + if isinstance(obj, str): + obj = self(self.default_key, obj) + return self.object_is_registered(obj=obj) + + +class SerializableRegistry(Registry, Serializable): + """ + Registry that is serializable, i.e.: entries contain states that can themselves be serialized /deserialized. + + Note that this assumes that any objects added to this registry are themselves of @Serializable type! + """ + + def __init__( + self, + name, + class_types=object, + default_key="name", + hash_key="uuid", + unique_keys=None, + group_keys=None, + default_value=None, + ): + """ + Args: + name (str): name of this registry + class_types (class or list of class): class expected for all entries in this registry. Default is `object`, + meaning any object entered will be accepted. This is used to sanity check added entries using add() + to make sure their type is correct (either that the entry itself is a valid class, or that they are an + object of the valid class). Note that if a list of classes are passed, any one of the classes are + considered a valid type for added objects + default_key (str): default key by which to reference a given object. This key should be a + publically accessible attribute in a given object (e.g.: object.name) and uniquely identify + any entries + hash_key (str): key by which to reference a given object when serializing / deserializing its state. + This key should be a publically accessible attribute in a given object (e.g.: object.name) and + uniquely identify any entries via a hash value (i.e.: integer) + unique_keys (None or list of str or set of str): keys by which to reference a given object. Any key should be a + publically accessible attribute in a given object (e.g.: object.name) + i.e.: these keys should map to a single object + + group_keys (None or list of str): keys by which to reference a group of objects, based on the key + (e.g.: object.room) + i.e.: these keys can map to multiple objects + + e.g.: default is "name" key only, so we will store objects by their object.name attribute + + default_value (any): Default value to use if the attribute @key does not exist in the object + """ + # Store hash key + self.hash_key = hash_key + + # We always add in the hash_key attribute as well + unique_keys = set() if unique_keys is None else set(unique_keys) + unique_keys.add(self.hash_key) + + # Set the default dump and load filters, which is a pass-through + self._dump_filter = lambda obj: True + self._load_filter = lambda obj: True + + # Run super + super().__init__( + name=name, + class_types=class_types, + default_key=default_key, + unique_keys=unique_keys, + group_keys=group_keys, + default_value=default_value, + ) + + def add(self, obj): + # In addition to any other class types, we make sure that the object is a serializable instance / class + validate_class = issubclass if isclass(obj) else isinstance + assert any( + [validate_class(obj, class_type) for class_type in (Serializable, SerializableNonInstance)] + ), "Added object must be either an instance or subclass of Serializable or SerializableNonInstance!" + # Run super like normal + super().add(obj=obj) + + def set_dump_filter(self, dump_filter): + """ + Sets the internal filter that determines whether an object should be dumped or not. + + Args: + dump_filter (function): Function that determines whether an object should be dumped or not. + Expected signature is: + + def dump_filter(obj) -> bool + + where it takes in a given registered object @obj and returns True if the object should have its state + dumped + """ + self._dump_filter = dump_filter + + def set_load_filter(self, load_filter): + """ + Sets the internal filter that determines whether an object's state should be loaded or not. + + Args: + load_filter (function): Function that determines whether an object should have its state loaded or not + Expected signature is: + + def load_filter(obj) -> bool + + where it takes in a given registered object @obj and returns True if the object should have its + state loaded or not + """ + self._load_filter = load_filter + + def _dump_state(self): + # Iterate over all objects and grab their states + state = dict() + for obj in self.objects: + if self._dump_filter(obj): + state[obj.name] = obj.dump_state(serialized=False) + return state + + def _load_state(self, state): + # Iterate over all objects and load their states. Currently the objects and the state don't have to match, i.e. + # there might be objects in the scene that do not appear in the state dict (a warning will be printed), or + # the state might contain additional information about objects that are NOT in the scene. For both cases, state + # loading will be skipped. + for obj in self.objects: + if self._load_filter(obj): + if obj.name not in state: + log.debug(f"Object '{obj.name}' is not in the state dict to load from. Skip loading its state.") + if m.STABILIZE_SKIPPED_OBJECTS and isinstance(obj, USDObject) and not obj.kinematic_only: + obj.keep_still() + continue + obj.load_state(state[obj.name], serialized=False) + + def serialize(self, state): + # Iterate over the entire dict and flatten + # We keep track of how many objects are being saved, as well as the unique identifier for each object so that + # the saved flattened array is agnostic to object ordering + # self("name", name) grabs the corresponding object from this registry so that we can serialize its state + # Each object's state in the flattened array is composed of [hash_key, serialized_state] + n_objs = len(state) + + if len(state) > 0: + state_flat = [] + for name in state: + obj = self("name", name) + serialized = obj.serialize(state[name]) + + # Handle the case where serialize returns an empty tensor + if serialized.numel() == 0: + hash_key_tensor = th.tensor([getattr(obj, self.hash_key)], dtype=th.float32) + state_flat.append(hash_key_tensor) + else: + hash_key_tensor = th.tensor([getattr(obj, self.hash_key)], dtype=serialized.dtype) + state_flat.append(th.cat([hash_key_tensor, serialized.flatten()])) + + state_flat = th.cat(state_flat) + else: + state_flat = th.tensor([]) + + return th.cat([th.tensor([n_objs], dtype=th.float32), state_flat]) + + def deserialize(self, state): + state_dict = dict() + # Iterate over all the objects and deserialize their individual states, incrementing the index counter + # along the way + n_objects = int(state[0]) + idx = 1 + for _ in range(n_objects): + # Infer obj based on UUID + obj = self(self.hash_key, int(state[idx])) + assert ( + obj is not None + ), f"Could not find object while deserializing with hash_key {self.hash_key}: {int(state[idx])}" + idx += 1 + log.debug(f"obj: {obj.name}, idx: {idx}, passing in state length: {len(state[idx:])}") + # We pass in the entire remaining state vector, assuming the object only parses the relevant states + # at the beginning + state_dict[obj.name], deserialized_items = obj.deserialize(state[idx:]) + idx += deserialized_items + return state_dict, idx + + @property + def uuid(self): + """ + Returns: + int: Unique hashed ID for this registry + """ + return get_uuid(self.name) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/render_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/render_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..753952a009fc816139c73c347d36c48ae1d05145 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/render_utils.py @@ -0,0 +1,83 @@ +""" +Set of rendering utility functions when working with Omni +""" + +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.utils.physx_utils import bind_material +from omnigibson.utils.ui_utils import create_module_logger + + +# Create module logger +log = create_module_logger(module_name=__name__) + + +def make_glass(prim): + """ + Links the OmniGlass material with EntityPrim, RigidPrim, or GeomPrim @obj, and procedurally generates + the necessary OmniGlass material prim if necessary. + + Args: + prim (EntityPrim or RigidPrim or GeomPrim): Desired prim to convert into glass + """ + # Do this here to avoid circular imports + from omnigibson.prims import EntityPrim, RigidPrim, GeomPrim + + # Generate the set of visual meshes we'll convert into glass + if isinstance(prim, EntityPrim): + # Grab all visual meshes from all links + visual_meshes = [vm for link in prim.links.values() for vm in link.visual_meshes.values()] + elif isinstance(prim, RigidPrim): + # Grab all visual meshes from the link + visual_meshes = [vm for vm in prim.visual_meshes.values()] + elif isinstance(prim, GeomPrim): + # Just use this visual mesh + visual_meshes = [prim] + else: + raise ValueError( + "Inputted prim must an instance of EntityPrim, RigidPrim, or GeomPrim " + "in order to be converted into glass!" + ) + + # Grab the glass material prim; if it doesn't exist, we create it on the fly + glass_prim_path = "/Looks/OmniGlass" + if not lazy.isaacsim.core.utils.prims.get_prim_at_path(glass_prim_path): + mtl_created = [] + lazy.omni.kit.commands.execute( + "CreateAndBindMdlMaterialFromLibrary", + mdl_name="OmniGlass.mdl", + mtl_name="OmniGlass", + mtl_created_list=mtl_created, + ) + + # Iterate over all meshes and bind the glass material to the mesh + for vm in visual_meshes: + bind_material(vm.prim_path, material_path=glass_prim_path) + + +def create_pbr_material(prim_path): + """ + Creates an omni pbr material prim at the specified @prim_path + + Args: + prim_path (str): Prim path where the PBR material should be generated + + Returns: + Usd.Prim: Generated PBR material prim + """ + # Use DeepWater omni present for rendering water + mtl_created = [] + with og.sim.editing_usd(): + lazy.omni.kit.commands.execute( + "CreateAndBindMdlMaterialFromLibrary", + mdl_name="OmniPBR.mdl", + mtl_name="OmniPBR", + mtl_created_list=mtl_created, + ) + material_path = mtl_created[0] + + # Move prim to desired location + lazy.omni.kit.commands.execute("MovePrim", path_from=material_path, path_to=prim_path) + + # Return generated material + return lazy.isaacsim.core.utils.prims.get_prim_at_path(material_path) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sampling_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sampling_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f6d10dd0059b6701ad0973ea97e14e2fd3b03a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sampling_utils.py @@ -0,0 +1,1227 @@ +import itertools +import math +import random +from collections import Counter, defaultdict + +import torch as th +from scipy.stats import truncnorm + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.utils.ui_utils import create_module_logger, draw_line + +# Create module logger +log = create_module_logger(module_name=__name__) + + +# Create settings for this module +m = create_module_macros(module_path=__file__) + +m.DEBUG_SAMPLING = False +m.DEFAULT_AABB_OFFSET_FRACTION = 0.02 +m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE = 1.0 # Around 60 degrees +m.DEFAULT_HIT_TO_PLANE_THRESHOLD = 0.05 +m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS = 3 * math.pi / 4 +m.DEFAULT_MAX_SAMPLING_ATTEMPTS = 10 +m.DEFAULT_CUBOID_BOTTOM_PADDING = 0.005 +# We will cast an additional parallel ray for each additional this much distance. +m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE = 0.1 +m.DEFAULT_HIT_PROPORTION = 0.8 + + +def fit_plane(points, refusal_log): + """ + Fits a plane to the given 3D points. + Copied from https://stackoverflow.com/a/18968498 + + Args: + points ((k, 3)-array): th.tensor of shape (k, 3) + refusal_log (dict): Debugging dictionary to add error messages to + + Returns: + 2-tuple: + - 3-array: (x,y,z) points' centroid + - 3-array: (x,y,z) normal of the fitted plane + """ + if points.shape[0] < points.shape[1]: + if m.DEBUG_SAMPLING: + refusal_log.append(f"insufficient points to fit a 3D plane: needs 3, has {points.shape[0]}.") + return None, None + + ctr = points.mean(dim=0) + x = points - ctr + normal = th.linalg.svd(x.T @ x).U[:, -1] + normal /= th.norm(normal) + return ctr, normal + + +def check_distance_to_plane(points, plane_centroid, plane_normal, hit_to_plane_threshold, refusal_log): + """ + Calculates whether points are within @hit_to_plane_threshold distance to plane defined by @plane_centroid + and @plane_normal + + Args: + points ((k, 3)-array): th.tensor of shape (k, 3) + plane_centroid (3-array): (x,y,z) points' centroid + plane_normal (3-array): (x,y,z) normal of the fitted plane + hit_to_plane_threshold (float): Threshold distance to check between @points and plane + refusal_log (dict): Debugging dictionary to add error messages to + + Returns: + bool: True if all points are within @hit_to_plane_threshold distance to plane, otherwise False + """ + distances = get_distance_to_plane(points, plane_centroid, plane_normal) + if th.any(distances > hit_to_plane_threshold): + if m.DEBUG_SAMPLING: + refusal_log.append("distances to plane: %r" % distances) + return False + return True + + +def get_distance_to_plane(points, plane_centroid, plane_normal): + """ + Computes distance from @points to plane defined by @plane_centroid and @plane_normal + + Args: + points ((k, 3)-array): th.tensor of shape (k, 3) + plane_centroid (3-array): (x,y,z) points' centroid + plane_normal (3-array): (x,y,z) normal of the fitted plane + + Returns: + k-array: Absolute distances from each point to the plane + """ + return th.abs((points - plane_centroid) @ plane_normal) + + +def get_projection_onto_plane(points, plane_centroid, plane_normal): + """ + Computes @points' projection onto the plane defined by @plane_centroid and @plane_normal + + Args: + points ((k, 3)-array): th.tensor of shape (k, 3) + plane_centroid (3-array): (x,y,z) points' centroid + plane_normal (3-array): (x,y,z) normal of the fitted plane + + Returns: + (k,3)-array: Points' positions projected onto the plane + """ + distances_to_plane = get_distance_to_plane(points, plane_centroid, plane_normal) + return points - th.outer(distances_to_plane, plane_normal) + + +def draw_debug_markers(hit_positions, radius=0.01): + """ + Helper method to generate and place debug markers at @hit_positions + + Args: + hit_positions ((n, 3)-array): Desired positions to place markers at + radius (float): Radius of the generated virtual marker + """ + color = th.cat([th.rand(3), [1]]) + for vec in hit_positions: + for dim in range(3): + start_point = vec + th.eye(3)[dim] * radius + end_point = vec - th.eye(3)[dim] * radius + draw_line(start_point, end_point, color) + + +def get_parallel_rays(source, destination, offset, new_ray_per_horizontal_distance): + """ + Given an input ray described by a source and a destination, sample parallel rays around it as the center. + + The parallel rays start at the corners of a square of edge length `offset` centered on `source`, with the square + orthogonal to the ray direction. That is, the cast rays are the height edges of a square-base cuboid with bases + centered on `source` and `destination`. + + Args: + source (3-array): (x,y,z) source of the ray to sample parallel rays of. + destination (3-array): Source of the ray to sample parallel rays of. + offset (float): Orthogonal distance of parallel rays from input ray. + new_ray_per_horizontal_distance (float): Step in offset beyond which an additional split will be applied in the + parallel ray grid (which at minimum is 3x3 at the AABB corners & center). + + Returns: + 3-tuple: + - list: generated sources from the original ray + - list: generated destinations from the original ray + - (W, H, 3)-array: unflattened, untransformed grid of parallel rays in object coordinates + """ + ray_direction = destination - source + + # Get an orthogonal vector using a random vector. + random_vector = th.randn(3) + random_vector /= th.norm(random_vector) + orthogonal_vector_1 = th.linalg.cross(ray_direction, random_vector) + orthogonal_vector_1 /= th.norm(orthogonal_vector_1) + + # Get a second vector orthogonal to both the ray and the first vector. + orthogonal_vector_2 = -th.linalg.cross(ray_direction, orthogonal_vector_1) + orthogonal_vector_2 /= th.norm(orthogonal_vector_2) + + orthogonal_vectors = th.stack([orthogonal_vector_1, orthogonal_vector_2]) + assert th.all(th.isfinite(orthogonal_vectors)) + + # Convert the offset into a 2-vector if it already isn't one. + offset = th.tensor([1, 1]) * offset + + # Compute the grid of rays + steps = (offset / new_ray_per_horizontal_distance).int() * 2 + 1 + steps = th.maximum(steps, th.tensor(3)) + x_range = th.linspace(-offset[0], offset[0], steps[0]) + y_range = th.linspace(-offset[1], offset[1], steps[1]) + ray_grid = th.stack(th.meshgrid(x_range, y_range, indexing="ij"), dim=-1) + ray_grid_flattened = ray_grid.reshape(-1, 2) + + # Apply the grid onto the orthogonal vectors to obtain the rays in the world frame. + sources = [source + offsets @ orthogonal_vectors for offsets in ray_grid_flattened] + destinations = [destination + offsets @ orthogonal_vectors for offsets in ray_grid_flattened] + + return sources, destinations, ray_grid + + +def sample_origin_positions(mins, maxes, count, bimodal_mean_fraction, bimodal_stdev_fraction, axis_probabilities): + """ + Sample ray casting origin positions with a given distribution. + + The way the sampling works is that for each particle, it will sample two coordinates uniformly and one + using a symmetric, bimodal truncated normal distribution. This way, the particles will mostly be close to the faces + of the AABB (given a correctly parameterized bimodal truncated normal) and will be spread across each face, + but there will still be a small number of particles spawned inside the object if it has an interior. + + Args: + mins (3-array): the minimum coordinate along each axis. + maxes (3-array): the maximum coordinate along each axis. + count (int): Number of origins to sample. + bimodal_mean_fraction (float): the mean of one side of the symmetric bimodal distribution as a fraction of the + min-max range. + bimodal_stdev_fraction (float): the standard deviation of one side of the symmetric bimodal distribution as a + fraction of the min-max range. + axis_probabilities (3-array): the probability of ray casting along each axis. + + Returns: + list: List where each element is (ray cast axis index, bool whether the axis was sampled from the top side, + [x, y, z]) tuples. + """ + assert len(mins.shape) == 1 + assert mins.shape == maxes.shape + + results = [] + for i in range(count): + # Get the uniform sample first. + position = th.rand(3) + + # Sample the bimodal normal. + bottom = (0 - bimodal_mean_fraction) / bimodal_stdev_fraction + top = (1 - bimodal_mean_fraction) / bimodal_stdev_fraction + bimodal_sample = truncnorm.rvs(bottom, top, loc=bimodal_mean_fraction, scale=bimodal_stdev_fraction) + + # Pick which axis the bimodal normal sample should go to. + bimodal_axis = th.multinomial(th.tensor(axis_probabilities, dtype=th.float32), 1).item() + + # Choose which side of the axis to sample from. We only sample from the top for the Z axis. + if bimodal_axis == 2: + bimodal_axis_top_side = True + else: + bimodal_axis_top_side = random.choice([True, False]) + + # Move sample based on chosen side. + position[bimodal_axis] = bimodal_sample if bimodal_axis_top_side else 1 - bimodal_sample + + # Scale the position from the standard normal range to the min-max range. + scaled_position = mins + (maxes - mins) * position + + # Save the result. + results.append((bimodal_axis, bimodal_axis_top_side, scaled_position)) + + return results + + +def raytest_batch( + start_points, end_points, only_closest=True, ignore_bodies=None, ignore_collisions=None, callback=None +): + """ + Computes raytest collisions for a set of rays cast from @start_points to @end_points. + + Args: + start_points (list of 3-array): Array of start locations to cast rays, where each is (x,y,z) global + start location of the ray + end_points (list of 3-array): Array of end locations to cast rays, where each is (x,y,z) global + end location of the ray + only_closest (bool): Whether we report the first (closest) hit from the ray or grab all hits + ignore_bodies (None or list of str): If specified, specifies absolute USD paths to rigid bodies + whose collisions should be ignored + ignore_collisions (None or list of str): If specified, specifies absolute USD paths to collision geoms + whose collisions should be ignored + callback (None or function): If specified and @only_closest is False, the custom callback to use per-hit. + This can be efficient if raytests are meant to terminate early. If None, no custom callback will be used. + Expected signature is callback(hit) -> bool, which returns True if the raycast should continue or not + + Returns: + list of dict or list of list of dict: Results for all rays, where each entry corresponds to the result for the + ith ray cast. If @only_closest=True, each entry in the list is the closest hit. Otherwise, each entry is + its own (unordered) list of hits for that ray. Each dict is composed of: + + "hit" (bool): Whether an object was hit or not + "position" (3-array): Location of the hit position + "normal" (3-array): normal vector of the face hit + "distance" (float): distance from @start_point the hit occurred + "collision" (str): absolute USD path to the collision body hit + "rigidBody" (str): absolute USD path to the associated rigid body hit + + Note that only "hit" = False exists in the dict if no hit was found + """ + # For now, we do a naive for loop over individual raytests until a better API comes out + results = [] + for start_point, end_point in zip(start_points, end_points): + results.append( + raytest( + start_point=start_point, + end_point=end_point, + only_closest=only_closest, + ignore_bodies=ignore_bodies, + ignore_collisions=ignore_collisions, + callback=callback, + ) + ) + + return results + + +def raytest( + start_point, + end_point, + only_closest=True, + ignore_bodies=None, + ignore_collisions=None, + callback=None, +): + """ + Computes raytest collision for ray cast from @start_point to @end_point + + Args: + start_point (3-array): (x,y,z) global start location of the ray + end_point (3-array): (x,y,z) global end location of the ray + only_closest (bool): Whether we report the first (closest) hit from the ray or grab all hits + ignore_bodies (None or list of str): If specified, specifies absolute USD paths to rigid bodies + whose collisions should be ignored + ignore_collisions (None or list of str): If specified, specifies absolute USD paths to collision geoms + whose collisions should be ignored + callback (None or function): If specified and @only_closest is False, the custom callback to use per-hit. + This can be efficient if raytests are meant to terminate early. If None, no custom callback will be used. + Expected signature is callback(hit) -> bool, which returns True if the raycast should continue or not + + Returns: + dict or list of dict: Results for this raytest. If @only_closest=True, then we only return the information from + the closest hit. Otherwise, we return an (unordered) list of information for all hits encountered. + Each dict is composed of: + + "hit" (bool): Whether an object was hit or not + "position" (3-array): Location of the hit position + "normal" (3-array): normal vector of the face hit + "distance" (float): distance from @start_point the hit occurred + "collision" (str): absolute USD path to the collision body hit + "rigidBody" (str): absolute USD path to the associated rigid body hit + + Note that only "hit" = False exists in the dict if no hit was found + """ + # Make sure start point, end point are torch tensors + start_point = th.tensor(start_point) if not isinstance(start_point, th.Tensor) else start_point + end_point = th.tensor(end_point) if not isinstance(end_point, th.Tensor) else end_point + point_diff = end_point - start_point + distance = th.norm(point_diff) + direction = point_diff / distance + + # For efficiency's sake, we handle special case of no ignore_bodies, ignore_collisions, and closest_hit + if only_closest and ignore_bodies is None and ignore_collisions is None: + result = og.sim.psqi.raycast_closest( + origin=start_point.tolist(), + dir=direction.tolist(), + distance=distance.tolist(), + ) + if result["hit"]: + result["position"] = th.tensor(result["position"]) + result["normal"] = th.tensor(result["normal"]) + return result + else: + # Compose callback function for finding raycasts + hits = [] + ignore_bodies = set() if ignore_bodies is None else set(ignore_bodies) + ignore_collisions = set() if ignore_collisions is None else set(ignore_collisions) + + def hit_callback(hit): + # Only add to hits if we're not ignoring this body or collision + if hit.rigid_body not in ignore_bodies and hit.collision not in ignore_collisions: + hits.append( + { + "hit": True, + "position": th.tensor(hit.position), + "normal": th.tensor(hit.normal), + "distance": hit.distance, + "collision": hit.collision, + "rigidBody": hit.rigid_body, + } + ) + # We always want to continue traversing to collect all hits + return True if callback is None else callback(hit) + + # Grab all collisions + og.sim.psqi.raycast_all( + origin=start_point.tolist(), + dir=direction.tolist(), + distance=distance.tolist(), + reportFn=hit_callback, + ) + + # If we only want the closest, we need to sort these hits, otherwise we return them all + if only_closest: + # Return the empty hit dictionary if our ray did not hit anything, otherwise we return the closest + return {"hit": False} if len(hits) == 0 else sorted(hits, key=lambda hit: hit["distance"])[0] + else: + # Return all hits (list) + return hits + + +def sample_raytest_start_end_symmetric_bimodal_distribution( + obj, + num_samples, + bimodal_mean_fraction, + bimodal_stdev_fraction, + axis_probabilities, + aabb_offset=None, + aabb_offset_fraction=None, + max_sampling_attempts=None, +): + """ + Sample the start points and end points around a given object by a symmetric bimodal distribution + + obj (DatasetObject): The object to sample points on. + num_samples (int): the number of points to try to sample. + bimodal_mean_fraction (float): the mean of one side of the symmetric bimodal distribution as a fraction of the + min-max range. + bimodal_stdev_fraction (float): the standard deviation of one side of the symmetric bimodal distribution as a + fraction of the min-max range. + axis_probabilities (3-array): probability of ray casting along each axis. + aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified, + will override @aabb_offset_fraction + aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB. + max_sampling_attempts (int): how many times sampling will be attempted for each requested point. + + Returns: + 2-tuple: + - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the start points for + raycasting defined in the world frame + - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the end points for + raycasting defined in the world frame + """ + aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION + max_sampling_attempts = ( + max_sampling_attempts if max_sampling_attempts is not None else m.DEFAULT_MAX_SAMPLING_ATTEMPTS + ) + bbox_center, bbox_orn, bbox_bf_extent, _ = obj.get_base_aligned_bbox(xy_aligned=True) + aabb_offset = aabb_offset_fraction * bbox_bf_extent if aabb_offset is None else aabb_offset + half_extent = bbox_bf_extent / 2 + half_extent_with_offset = half_extent + aabb_offset + + start_points = th.zeros((num_samples, max_sampling_attempts, 3)) + end_points = th.zeros((num_samples, max_sampling_attempts, 3)) + for i in range(num_samples): + # Sample the starting positions in advance. + # TODO: Narrow down the sampling domain so that we don't sample scenarios where the center is in-domain but the + # full extent isn't. Currently a lot of samples are being wasted because of this. + samples = sample_origin_positions( + -half_extent_with_offset, + half_extent_with_offset, + max_sampling_attempts, + bimodal_mean_fraction, + bimodal_stdev_fraction, + axis_probabilities, + ) + + # Try each sampled position in the AABB. + for j, (axis, is_top, start_point) in enumerate(samples): + # Compute the ray's destination using the sampling & AABB information. + end_point = compute_ray_destination( + axis, is_top, start_point, -half_extent_with_offset, half_extent_with_offset + ) + start_points[i][j] = start_point + end_points[i][j] = end_point + + # Convert the points into the world frame + orig_shape = start_points.shape + to_wf_transform = T.pose2mat((bbox_center, bbox_orn)) + start_points = T.transform_points(start_points.reshape(-1, 3), to_wf_transform).reshape(orig_shape) + end_points = T.transform_points(end_points.reshape(-1, 3), to_wf_transform).reshape(orig_shape) + + return start_points, end_points + + +def sample_raytest_start_end_full_grid_topdown( + obj, + ray_spacing, + aabb_offset=None, + aabb_offset_fraction=None, +): + """ + Sample the start points and end points around a given object by a dense grid from top down. + + Args: + obj (DatasetObject): The object to sample points on. + ray_spacing (float): spacing between the rays, or equivalently, size of the grid cell + aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified, + will override @aabb_offset_fraction + aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB. + + Returns: + 2-tuple: + - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the start points for + raycasting defined in the world frame + - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the end points for + raycasting defined in the world frame + """ + aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION + bbox_center, bbox_orn, bbox_bf_extent, _ = obj.get_base_aligned_bbox(xy_aligned=True) + aabb_offset = aabb_offset_fraction * bbox_bf_extent if aabb_offset is None else aabb_offset + + half_extent_with_offset = (bbox_bf_extent / 2) + aabb_offset + x = th.linspace( + -half_extent_with_offset[0], half_extent_with_offset[0], int(half_extent_with_offset[0] * 2 / ray_spacing) + 1 + ) + y = th.linspace( + -half_extent_with_offset[1], half_extent_with_offset[1], int(half_extent_with_offset[1] * 2 / ray_spacing) + 1 + ) + n_rays = len(x) * len(y) + + start_points = th.stack( + [ + th.tile(x, (len(y),)), + th.repeat_interleave(y, len(x)), + th.ones(n_rays) * half_extent_with_offset[2], + ] + ).T + + end_points = th.clone(start_points) + end_points[:, 2] = -half_extent_with_offset[2] + + # Convert the points into the world frame + to_wf_transform = T.pose2mat((bbox_center, bbox_orn)) + start_points = T.transform_points(start_points, to_wf_transform) + end_points = T.transform_points(end_points, to_wf_transform) + + start_points = th.unsqueeze(start_points, dim=1) + end_points = th.unsqueeze(end_points, dim=1) + + return start_points, end_points + + +def sample_cuboid_on_object_symmetric_bimodal_distribution( + obj, + num_samples, + cuboid_dimensions, + bimodal_mean_fraction, + bimodal_stdev_fraction, + axis_probabilities, + new_ray_per_horizontal_distance=None, + hit_proportion=None, + aabb_offset=None, + aabb_offset_fraction=None, + max_sampling_attempts=None, + max_angle_with_z_axis=None, + parallel_ray_normal_angle_tolerance=None, + hit_to_plane_threshold=None, + cuboid_bottom_padding=None, + undo_cuboid_bottom_padding=True, + verify_cuboid_empty=True, + refuse_downwards=False, +): + """ + Samples points on an object's surface using ray casting. + Rays are sampled with a symmetric bimodal distribution. + + Args: + obj (DatasetObject): The object to sample points on. + num_samples (int): the number of points to try to sample. + cuboid_dimensions ((n, 3)-array): Float sequence of len 3, the size of the empty cuboid we are trying to sample. + Can also provide list of cuboid dimension triplets in which case each i'th sample will be sampled using + the i'th triplet. Alternatively, cuboid_dimensions can be set to be all zeros if the user just want to + sample points (instead of cuboids) for significantly better performance. This applies when the user wants + to sample very small particles. + bimodal_mean_fraction (float): the mean of one side of the symmetric bimodal distribution as a fraction of the + min-max range. + bimodal_stdev_fraction (float): the standard deviation of one side of the symmetric bimodal distribution as a + fraction of the min-max range. + axis_probabilities (3-array): the probability of ray casting along each axis. + new_ray_per_horizontal_distance (float): per this distance of the cuboid dimension, increase the grid size of + the parallel ray-testing by 1. This controls how fine-grained the grid ray-casting should be with respect to + the size of the sampled cuboid. + hit_proportion (float): the minimum percentage of the hits required across the grid. + aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified, + will override @aabb_offset_fraction + aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB. + max_sampling_attempts (int): how many times sampling will be attempted for each requested point. + max_angle_with_z_axis (float): maximum angle between hit normal and positive Z axis allowed. Can be used to + disallow downward-facing hits when refuse_downwards=True. + parallel_ray_normal_angle_tolerance (float): maximum angle difference between the normal of the center hit + and the normal of other hits allowed. + hit_to_plane_threshold (float): how far any given hit position can be from the least-squares fit plane to + all of the hit positions before the sample is rejected. + cuboid_bottom_padding (float): additional padding applied to the bottom of the cuboid. This is needed for the + emptiness check (@check_cuboid_empty) within the cuboid. un_padding=True can be set if the user wants to remove + the padding after the emptiness check. + undo_cuboid_bottom_padding (bool): Whether the bottom padding that's applied to the cuboid should be removed before return. + Useful when the cuboid needs to be flush with the surface for whatever reason. Note that the padding will still + be applied initially (since it's not possible to do the cuboid emptiness check without doing this - otherwise + the rays will hit the sampled-on object), so the emptiness check still checks a padded cuboid. This flag will + simply make the sampler undo the padding prior to returning. + verify_cuboid_empty (bool): Whether to filter out sampled cuboid locations that are not collision-free. Note + that this check will only potentially occur if nonzero cuboid dimensions are specified. + refuse_downwards (bool): whether downward-facing hits (as defined by max_angle_with_z_axis) are allowed. + + Returns: + list of tuple: list of length num_samples elements where each element is a tuple in the form of + (cuboid_centroid, cuboid_up_vector, cuboid_rotation, {refusal_reason: [refusal_details...]}). Cuboid positions + are set to None when no successful sampling happens within the max number of attempts. Refusal details are only + filled if the m.DEBUG_SAMPLING flag is globally set to True. + """ + new_ray_per_horizontal_distance = ( + new_ray_per_horizontal_distance + if new_ray_per_horizontal_distance is not None + else m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE + ) + hit_proportion = hit_proportion if hit_proportion is not None else m.DEFAULT_HIT_PROPORTION + aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION + max_sampling_attempts = ( + max_sampling_attempts if max_sampling_attempts is not None else m.DEFAULT_MAX_SAMPLING_ATTEMPTS + ) + max_angle_with_z_axis = ( + max_angle_with_z_axis if max_angle_with_z_axis is not None else m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS + ) + parallel_ray_normal_angle_tolerance = ( + parallel_ray_normal_angle_tolerance + if parallel_ray_normal_angle_tolerance is not None + else m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE + ) + hit_to_plane_threshold = ( + hit_to_plane_threshold if hit_to_plane_threshold is not None else m.DEFAULT_HIT_TO_PLANE_THRESHOLD + ) + cuboid_bottom_padding = ( + cuboid_bottom_padding if cuboid_bottom_padding is not None else m.DEFAULT_CUBOID_BOTTOM_PADDING + ) + start_points, end_points = sample_raytest_start_end_symmetric_bimodal_distribution( + obj, + num_samples, + bimodal_mean_fraction, + bimodal_stdev_fraction, + axis_probabilities, + aabb_offset=aabb_offset, + aabb_offset_fraction=aabb_offset_fraction, + max_sampling_attempts=max_sampling_attempts, + ) + + return sample_cuboid_on_object( + obj, + start_points, + end_points, + cuboid_dimensions, + new_ray_per_horizontal_distance=new_ray_per_horizontal_distance, + hit_proportion=hit_proportion, + max_angle_with_z_axis=max_angle_with_z_axis, + parallel_ray_normal_angle_tolerance=parallel_ray_normal_angle_tolerance, + hit_to_plane_threshold=hit_to_plane_threshold, + cuboid_bottom_padding=cuboid_bottom_padding, + undo_cuboid_bottom_padding=undo_cuboid_bottom_padding, + verify_cuboid_empty=verify_cuboid_empty, + refuse_downwards=refuse_downwards, + ) + + +def sample_cuboid_on_object_full_grid_topdown( + obj, + ray_spacing, + cuboid_dimensions, + new_ray_per_horizontal_distance=None, + hit_proportion=None, + aabb_offset=None, + aabb_offset_fraction=None, + max_angle_with_z_axis=None, + parallel_ray_normal_angle_tolerance=None, + hit_to_plane_threshold=None, + cuboid_bottom_padding=None, + undo_cuboid_bottom_padding=True, + verify_cuboid_empty=True, + refuse_downwards=False, +): + """ + Samples points on an object's surface using ray casting. + Rays are sampled with a dense grid from top down. + + Args: + obj (DatasetObject): The object to sample points on. + ray_spacing (float): spacing between the rays, or equivalently, size of the grid cell, when sampling the + start and end points. This implicitly determines the number of cuboids that will be sampled. + cuboid_dimensions ((n, 3)-array): Float sequence of len 3, the size of the empty cuboid we are trying to sample. + Can also provide list of cuboid dimension triplets in which case each i'th sample will be sampled using + the i'th triplet. Alternatively, cuboid_dimensions can be set to be all zeros if the user just want to + sample points (instead of cuboids) for significantly better performance. This applies when the user wants + to sample very small particles. + new_ray_per_horizontal_distance (float): per this distance of the cuboid dimension, increase the grid size of + the parallel ray-testing by 1. This controls how fine-grained the grid ray-casting should be with respect to + the size of the sampled cuboid. + hit_proportion (float): the minimum percentage of the hits required across the grid. + aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified, + will override @aabb_offset_fraction + aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB. + max_angle_with_z_axis (float): maximum angle between hit normal and positive Z axis allowed. Can be used to + disallow downward-facing hits when refuse_downwards=True. + parallel_ray_normal_angle_tolerance (float): maximum angle difference between the normal of the center hit + and the normal of other hits allowed. + hit_to_plane_threshold (float): how far any given hit position can be from the least-squares fit plane to + all of the hit positions before the sample is rejected. + cuboid_bottom_padding (float): additional padding applied to the bottom of the cuboid. This is needed for the + emptiness check (@check_cuboid_empty) within the cuboid. un_padding=True can be set if the user wants to remove + the padding after the emptiness check. + undo_cuboid_bottom_padding (bool): Whether the bottom padding that's applied to the cuboid should be removed before return. + Useful when the cuboid needs to be flush with the surface for whatever reason. Note that the padding will still + be applied initially (since it's not possible to do the cuboid emptiness check without doing this - otherwise + the rays will hit the sampled-on object), so the emptiness check still checks a padded cuboid. This flag will + simply make the sampler undo the padding prior to returning. + verify_cuboid_empty (bool): Whether to filter out sampled cuboid locations that are not collision-free. Note + that this check will only potentially occur if nonzero cuboid dimensions are specified. + refuse_downwards (bool): whether downward-facing hits (as defined by max_angle_with_z_axis) are allowed. + + Returns: + list of tuple: list of length num_samples elements where each element is a tuple in the form of + (cuboid_centroid, cuboid_up_vector, cuboid_rotation, {refusal_reason: [refusal_details...]}). Cuboid positions + are set to None when no successful sampling happens within the max number of attempts. Refusal details are only + filled if the m.DEBUG_SAMPLING flag is globally set to True. + """ + new_ray_per_horizontal_distance = ( + new_ray_per_horizontal_distance + if new_ray_per_horizontal_distance is not None + else m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE + ) + hit_proportion = hit_proportion if hit_proportion is not None else m.DEFAULT_HIT_PROPORTION + aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION + max_angle_with_z_axis = ( + max_angle_with_z_axis if max_angle_with_z_axis is not None else m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS + ) + parallel_ray_normal_angle_tolerance = ( + parallel_ray_normal_angle_tolerance + if parallel_ray_normal_angle_tolerance is not None + else m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE + ) + hit_to_plane_threshold = ( + hit_to_plane_threshold if hit_to_plane_threshold is not None else m.DEFAULT_HIT_TO_PLANE_THRESHOLD + ) + cuboid_bottom_padding = ( + cuboid_bottom_padding if cuboid_bottom_padding is not None else m.DEFAULT_CUBOID_BOTTOM_PADDING + ) + start_points, end_points = sample_raytest_start_end_full_grid_topdown( + obj, + ray_spacing, + aabb_offset=aabb_offset, + aabb_offset_fraction=aabb_offset_fraction, + ) + return sample_cuboid_on_object( + obj, + start_points, + end_points, + cuboid_dimensions, + new_ray_per_horizontal_distance=new_ray_per_horizontal_distance, + hit_proportion=hit_proportion, + max_angle_with_z_axis=max_angle_with_z_axis, + parallel_ray_normal_angle_tolerance=parallel_ray_normal_angle_tolerance, + hit_to_plane_threshold=hit_to_plane_threshold, + cuboid_bottom_padding=cuboid_bottom_padding, + undo_cuboid_bottom_padding=undo_cuboid_bottom_padding, + verify_cuboid_empty=verify_cuboid_empty, + refuse_downwards=refuse_downwards, + ) + + +def sample_cuboid_on_object( + obj, + start_points, + end_points, + cuboid_dimensions, + ignore_objs=None, + new_ray_per_horizontal_distance=None, + hit_proportion=None, + max_angle_with_z_axis=None, + parallel_ray_normal_angle_tolerance=None, + hit_to_plane_threshold=None, + cuboid_bottom_padding=None, + undo_cuboid_bottom_padding=True, + verify_cuboid_empty=True, + refuse_downwards=False, +): + """ + Samples points on an object's surface using ray casting. + + Args: + obj (DatasetObject): The object to sample points on. + start_points ((n, s, 3)-array): (num_samples, max_sampling_attempts, 3) shaped array representing the start points for + raycasting defined in the world frame + end_points ((n, s, 3)-array): (num_samples, max_sampling_attempts, 3) shaped array representing the end points for + raycasting defined in the world frame + cuboid_dimensions ((n, 3)-array): Float sequence of len 3, the size of the empty cuboid we are trying to sample. + Can also provide list of cuboid dimension triplets in which case each i'th sample will be sampled using + the i'th triplet. Alternatively, cuboid_dimensions can be set to be all zeros if the user just want to + sample points (instead of cuboids) for significantly better performance. This applies when the user wants + to sample very small particles. + ignore_objs (None or list of EntityPrim): If @obj is None, this can be used to filter objects when checking + for valid cuboid locations. Any sampled rays that hit an object in @ignore_objs will be ignored. If None, + no filtering will be used + new_ray_per_horizontal_distance (float): per this distance of the cuboid dimension, increase the grid size of + the parallel ray-testing by 1. This controls how fine-grained the grid ray-casting should be with respect to + the size of the sampled cuboid. + hit_proportion (float): the minimum percentage of the hits required across the grid. + max_angle_with_z_axis (float): maximum angle between hit normal and positive Z axis allowed. Can be used to + disallow downward-facing hits when refuse_downwards=True. + parallel_ray_normal_angle_tolerance (float): maximum angle difference between the normal of the center hit + and the normal of other hits allowed. + hit_to_plane_threshold (float): how far any given hit position can be from the least-squares fit plane to + all of the hit positions before the sample is rejected. + cuboid_bottom_padding (float): additional padding applied to the bottom of the cuboid. This is needed for the + emptiness check (@check_cuboid_empty) within the cuboid. un_padding=True can be set if the user wants to remove + the padding after the emptiness check. + undo_cuboid_bottom_padding (bool): Whether the bottom padding that's applied to the cuboid should be removed before return. + Useful when the cuboid needs to be flush with the surface for whatever reason. Note that the padding will still + be applied initially (since it's not possible to do the cuboid emptiness check without doing this - otherwise + the rays will hit the sampled-on object), so the emptiness check still checks a padded cuboid. This flag will + simply make the sampler undo the padding prior to returning. + verify_cuboid_empty (bool): Whether to filter out sampled cuboid locations that are not collision-free. Note + that this check will only potentially occur if nonzero cuboid dimensions are specified. + refuse_downwards (bool): whether downward-facing hits (as defined by max_angle_with_z_axis) are allowed. + + Returns: + list of tuple: list of length num_samples elements where each element is a tuple in the form of + (cuboid_centroid, cuboid_up_vector, cuboid_rotation, {refusal_reason: [refusal_details...]}). Cuboid positions + are set to None when no successful sampling happens within the max number of attempts. Refusal details are only + filled if the m.DEBUG_SAMPLING flag is globally set to True. + """ + new_ray_per_horizontal_distance = ( + new_ray_per_horizontal_distance + if new_ray_per_horizontal_distance is not None + else m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE + ) + hit_proportion = hit_proportion if hit_proportion is not None else m.DEFAULT_HIT_PROPORTION + max_angle_with_z_axis = ( + max_angle_with_z_axis if max_angle_with_z_axis is not None else m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS + ) + parallel_ray_normal_angle_tolerance = ( + parallel_ray_normal_angle_tolerance + if parallel_ray_normal_angle_tolerance is not None + else m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE + ) + hit_to_plane_threshold = ( + hit_to_plane_threshold if hit_to_plane_threshold is not None else m.DEFAULT_HIT_TO_PLANE_THRESHOLD + ) + cuboid_bottom_padding = ( + cuboid_bottom_padding if cuboid_bottom_padding is not None else m.DEFAULT_CUBOID_BOTTOM_PADDING + ) + + assert ( + start_points.shape == end_points.shape + ), "the start and end points of raycasting are expected to have the same shape." + num_samples = start_points.shape[0] + + if th.any(cuboid_dimensions > 50.0): + log.warning( + "WARNING: Trying to sample for a very large cuboid (at least one dimensions > 50). " + "Terminating immediately, no hits will be registered." + ) + return [(None, None, None, None, defaultdict(list)) for _ in range(num_samples)] + + assert cuboid_dimensions.ndim <= 2 + assert cuboid_dimensions.shape[-1] == 3, "Cuboid dimensions need to contain all three dimensions." + if cuboid_dimensions.ndim == 2: + assert cuboid_dimensions.shape[0] == num_samples, "Need as many offsets as samples requested." + + results = [(None, None, None, None, defaultdict(list)) for _ in range(num_samples)] + rigid_bodies = None if obj is None else {link.prim_path for link in obj.links.values()} + ignore_rigid_bodies = ( + None + if ignore_objs is None + else {link.prim_path for ignore_obj in ignore_objs for link in ignore_obj.links.values()} + ) + + for i in range(num_samples): + refusal_reasons = results[i][4] + # Try each sampled position in the AABB. + for start_pos, end_pos in zip(start_points[i], end_points[i]): + # If we have a list of cuboid dimensions, pick the one that corresponds to this particular sample. + this_cuboid_dimensions = cuboid_dimensions if cuboid_dimensions.ndim == 1 else cuboid_dimensions[i] + + zero_cuboid_dimension = (this_cuboid_dimensions == 0.0).all() + + if not zero_cuboid_dimension: + # Make sure we have valid (nonzero) x and y values + assert ( + this_cuboid_dimensions[:-1] > 0 + ).all(), f"Cuboid x and y dimensions must not be zero if z dimension is nonzero! Got: {this_cuboid_dimensions}" + # Obtain the parallel rays using the direction sampling method. + sources, destinations, grid = get_parallel_rays( + start_pos, + end_pos, + this_cuboid_dimensions[:2] / 2.0, + new_ray_per_horizontal_distance, + ) + else: + sources = [start_pos] + destinations = [end_pos] + + # Time to cast the rays. + cast_results = raytest_batch( + start_points=sources, end_points=destinations, ignore_bodies=ignore_rigid_bodies + ) + + # Check whether sufficient number of rays hit the object + hits = check_rays_hit_object(cast_results, hit_proportion, refusal_reasons["missed_object"], rigid_bodies) + if hits is None: + continue + + center_idx = int(len(hits) / 2) + # Only consider objects whose center idx has a ray hit + if not hits[center_idx]: + continue + + filtered_cast_results = [] + filtered_center_idx = None + for idx, hit in enumerate(hits): + if hit: + filtered_cast_results.append(cast_results[idx]) + if idx == center_idx: + filtered_center_idx = len(filtered_cast_results) - 1 + + # Process the hit positions and normals. + hit_positions = th.stack([ray_res["position"] for ray_res in filtered_cast_results]) + hit_normals = th.stack([ray_res["normal"] for ray_res in filtered_cast_results]) + hit_normals /= th.norm(hit_normals, dim=1, keepdim=True) + + assert filtered_center_idx is not None + hit_link = filtered_cast_results[filtered_center_idx]["rigidBody"] + center_hit_pos = hit_positions[filtered_center_idx] + center_hit_normal = hit_normals[filtered_center_idx] + + # Reject anything facing more than 45deg downwards if requested. + if refuse_downwards: + if not check_hit_max_angle_from_z_axis( + center_hit_normal, max_angle_with_z_axis, refusal_reasons["downward_normal"] + ): + continue + + # Check that none of the parallel rays' hit normal differs from center ray by more than threshold. + if not zero_cuboid_dimension: + if not check_normal_similarity( + center_hit_normal, + hit_normals, + parallel_ray_normal_angle_tolerance, + refusal_reasons["hit_normal_similarity"], + ): + continue + + # Fit a plane to the points. + plane_centroid, plane_normal = fit_plane(hit_positions, refusal_reasons["fit_plane"]) + if plane_centroid is None: + continue + + # The fit_plane normal can be facing either direction on the normal axis, but we want it to face away from + # the object for purposes of normal checking and padding. To do this: + # We get a vector from the centroid towards the center ray source, and flip the plane normal to match it. + # The cosine has positive sign if the two vectors are similar and a negative one if not. + plane_to_source = sources[center_idx] - plane_centroid + plane_normal *= th.sign(th.dot(plane_to_source, plane_normal)) + + # Check that the plane normal is similar to the hit normal + if not check_normal_similarity( + center_hit_normal, + plane_normal[None, :], + parallel_ray_normal_angle_tolerance, + refusal_reasons["plane_normal_similarity"], + ): + continue + + # Check that the points are all within some acceptable distance of the plane. + if not check_distance_to_plane( + hit_positions, + plane_centroid, + plane_normal, + hit_to_plane_threshold, + refusal_reasons["dist_to_plane"], + ): + continue + + # Get projection of the base onto the plane, fit a rotation, and compute the new center hit / corners. + hit_positions = th.stack([ray_res.get("position", th.tensor([0.0] * 3)) for ray_res in cast_results]) + projected_hits = get_projection_onto_plane(hit_positions, plane_centroid, plane_normal) + padding = cuboid_bottom_padding * plane_normal + projected_hits += padding + center_projected_hit = projected_hits[center_idx] + cuboid_centroid = center_projected_hit + plane_normal * this_cuboid_dimensions[2] / 2.0 + + rotation = compute_rotation_from_grid_sample( + grid, + projected_hits, + cuboid_centroid, + this_cuboid_dimensions, + hits, + refusal_reasons["rotation_not_computable"], + ) + + # Make sure there are enough hit points that can be used for alignment to find the rotation + if rotation is None: + continue + + corner_vectors = ( + 0.5 + * this_cuboid_dimensions + * th.tensor([[1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]], dtype=th.float32) + ) + corner_positions = cuboid_centroid.unsqueeze(0) + T.quat_apply(rotation, corner_vectors) + + # Now we use the cuboid's diagonals to check that the cuboid is actually empty + if verify_cuboid_empty and not check_cuboid_empty( + plane_normal, + corner_positions, + this_cuboid_dimensions, + refusal_reasons["cuboid_not_empty"], + ): + continue + + if undo_cuboid_bottom_padding: + cuboid_centroid -= padding + + else: + cuboid_centroid = center_hit_pos + if not undo_cuboid_bottom_padding: + padding = cuboid_bottom_padding * center_hit_normal + cuboid_centroid += padding + plane_normal = th.zeros(3) + rotation = th.tensor([0, 0, 0, 1], dtype=th.float32) + + # We've found a nice attachment point. Continue onto next point to sample. + results[i] = (cuboid_centroid, plane_normal, rotation, hit_link, refusal_reasons) + break + + if m.DEBUG_SAMPLING: + og.log.debug("Sampling rejection reasons:") + counter = Counter() + + for instance in results: + for reason, refusals in instance[-1].items(): + counter[reason] += len(refusals) + + og.log.debug("\n".join("%s: %d" % pair for pair in counter.items())) + + return results + + +def compute_rotation_from_grid_sample( + two_d_grid, projected_hits, cuboid_centroid, this_cuboid_dimensions, hits, refusal_log +): + """ + Computes + + Args: + two_d_grid (n, 2): (x,y) raycast origin points in the local plane frame + projected_hits ((k,3)-array): Points' positions projected onto the plane generated + cuboid_centroid (3-array): (x,y,z) sampled position of the hit cuboid centroid in the global frame + this_cuboid_dimensions (3-array): (x,y,z) size of cuboid being sampled from the grid + hits (list of bool): whether each point from @two_d_grid is a valid hit or not + refusal_log (dict): Dictionary to write debugging and log information to + + Returns: + None or scipy.Rotation: If successfully hit, returns relative rotation from two_d_grid to + generated hit plane. Otherwise, returns None + """ + if sum(hits) < 3: + if m.DEBUG_SAMPLING: + refusal_log.append(f"insufficient hits to compute the rotation of the grid: needs 3, has {th.sum(hits)}") + return None + + grid_in_planar_coordinates = two_d_grid.reshape(-1, 2) + grid_in_planar_coordinates = grid_in_planar_coordinates[hits] + grid_in_object_coordinates = th.zeros((len(grid_in_planar_coordinates), 3)) + grid_in_object_coordinates[:, :2] = grid_in_planar_coordinates + grid_in_object_coordinates[:, 2] = -this_cuboid_dimensions[2] / 2.0 + + projected_hits = projected_hits[hits] + sampled_grid_relative_vectors = projected_hits - cuboid_centroid + + rotation = T.align_vector_sets(sampled_grid_relative_vectors, grid_in_object_coordinates) + + return rotation + + +def check_normal_similarity(center_hit_normal, hit_normals, tolerance, refusal_log): + """ + Check whether the normals from @hit_normals are within some @tolerance of @center_hit_normal. + + Args: + center_hit_normal (3-array): normal of the center hit point + hit_normals ((n, 3)-array): normals of all the hit points + tolerance (float): Acceptable deviation between the center hit normal and all normals + refusal_log (dict): Dictionary to write debugging and log information to + + Returns: + bool: Whether the normal similarity is acceptable or not + """ + parallel_hit_main_hit_dot_products = th.clip( + hit_normals @ center_hit_normal / (th.norm(hit_normals, dim=1) * th.norm(center_hit_normal)), + -1.0, + 1.0, + ) + parallel_hit_normal_angles_to_hit_normal = th.arccos(parallel_hit_main_hit_dot_products) + all_rays_hit_with_similar_normal = th.all(parallel_hit_normal_angles_to_hit_normal < tolerance) + if not all_rays_hit_with_similar_normal: + if m.DEBUG_SAMPLING: + refusal_log.append("angles %r" % (th.rad2deg(parallel_hit_normal_angles_to_hit_normal),)) + + return False + + return True + + +def check_rays_hit_object(cast_results, threshold, refusal_log, body_names=None): + """ + Checks whether rays hit a specific object, as specified by a list of @body_names + + Args: + cast_results (list of dict): Output from raycast_batch. + threshold (float): Relative ratio in [0, 1] specifying proportion of rays from @cast_results are + required to hit @body_names to count as the object being hit + refusal_log (list of str): Logging array for adding debug logs + body_names (None or list or set of str): absolute USD paths to rigid bodies to check for hit. If not + specified, then any valid hit will be accepted + + Returns: + None or list of bool: Individual T/F for each ray -- whether it hit the object or not + """ + body_names = None if body_names is None else set(body_names) + ray_hits = [ + ray_res["hit"] and (body_names is None or ray_res["rigidBody"] in body_names) for ray_res in cast_results + ] + if sum(ray_hits) / len(cast_results) < threshold: + if m.DEBUG_SAMPLING: + refusal_log.append( + f"{sum(ray_hits)} / {len(cast_results)} < {threshold} hits: {[ray_res['rigidBody'] for ray_res in cast_results if ray_res['hit']]}" + ) + + return None + + return ray_hits + + +def check_hit_max_angle_from_z_axis(hit_normal, max_angle_with_z_axis, refusal_log): + """ + Check whether the normal @hit_normal deviates from the global z axis by more than @max_angle_with_z_axis + + Args: + hit_normal (3-array): Normal vector to check with respect to global z-axis + max_angle_with_z_axis (float): Maximum acceptable angle between the global z-axis and @hit_normal + refusal_log (list of str): Logging array for adding debug logs + + Returns: + bool: True if the angle between @hit_normal and the global z-axis is less than @max_angle_with_z_axis, + otherwise False + """ + hit_angle_with_z = th.arccos(th.clip(th.dot(hit_normal, th.tensor([0.0, 0.0, 1.0])), -1.0, 1.0)) + if hit_angle_with_z > max_angle_with_z_axis: + if m.DEBUG_SAMPLING: + refusal_log.append("normal %r" % hit_normal) + + return False + + return True + + +def compute_ray_destination(axis, is_top, start_pos, aabb_min, aabb_max): + """ + Compute the point on the AABB defined by @aabb_min and @aabb_max from shooting a ray at @start_pos + in the direction defined by global axis @axis and @is_top + + Args: + axis (int): Which direction to compute the ray destination. Valid options are {0, 1, 2} -- the + x, y, or z axes + is_top (bool): Whether to shoot in the positive or negative @axis direction + aabb_min (3-array): (x,y,z) position defining the lower corner of the AABB + aabb_max (3-array): (x,y,z) position defining the upper corner of the AABB + + Returns: + 3-array: computed (x,y,z) point on the AABB surface + """ + # Get the ray casting direction - we want to do it parallel to the sample axis. + ray_direction = th.tensor([0, 0, 0]) + ray_direction[axis] = 1 + ray_direction *= -1 if is_top else 1 + + # We want to extend our ray until it intersects one of the AABB's faces. + # Start by getting the distances towards the min and max boundaries of the AABB on each axis. + point_to_min = aabb_min - start_pos + point_to_max = aabb_max - start_pos + + # Then choose the distance to the point in the correct direction on each axis. + closer_point_on_each_axis = th.where(ray_direction < 0, point_to_min, point_to_max) + + # For each axis, find how many times the ray direction should be multiplied to reach the AABB's boundary. + multiple_to_face_on_each_axis = closer_point_on_each_axis / ray_direction + + # Choose the minimum of these multiples, e.g. how many times the ray direction should be multiplied + # to reach the nearest boundary. + multiple_to_face = th.min(multiple_to_face_on_each_axis[th.isfinite(multiple_to_face_on_each_axis)]).item() + + # Finally, use the multiple we found to calculate the point on the AABB boundary that we want to cast our + # ray until. + point_on_face = start_pos + ray_direction * multiple_to_face + + # Make sure that we did not end up with all NaNs or infinities due to division issues. + assert not th.any(th.isnan(point_on_face)) and not th.any(th.isinf(point_on_face)) + + return point_on_face + + +def check_cuboid_empty(hit_normal, bottom_corner_positions, this_cuboid_dimensions, refusal_log): + """ + Check whether the cuboid defined by @this_cuboid_dimensions and @bottom_corner_positions contains + empty space or not + + Args: + hit_normal (3-array): (x,y,z) normal + bottom_corner_positions ((4, 3)-array): the positions defining the bottom corners of the cuboid + being sampled + this_cuboid_dimensions (3-array): (x,y,z) size of the sampled cuboid + refusal_log (list of str): Logging array for adding debug logs + + Returns: + bool: True if the cuboid is empty, else False + """ + if m.DEBUG_SAMPLING: + draw_debug_markers(bottom_corner_positions) + + # Compute top corners. + top_corner_positions = bottom_corner_positions + hit_normal * this_cuboid_dimensions[2] + + # We only generate valid rays that have nonzero distances. If the inputted cuboid is flat (i.e.: one dimension + # is zero, i.e.: it is in fact a rectangle), raise an error + assert this_cuboid_dimensions[2] != 0, "Cannot check empty cuboid for cuboid with zero height!" + + # Get all the top-to-bottom corner pairs. + # When we cast these rays, we check that the faces & volume of the cuboid are unoccupied. + top_to_bottom_pairs = list(itertools.product(top_corner_positions, bottom_corner_positions)) + + # Get all the same-height pairs. These also check that the surfaces areas are empty. + bottom_pairs = list(itertools.combinations(bottom_corner_positions, 2)) + top_pairs = list(itertools.combinations(top_corner_positions, 2)) + + # Combine all these pairs, cast the rays, and make sure the rays don't hit anything. + pairs_list = top_to_bottom_pairs + bottom_pairs + top_pairs + all_pairs = th.stack([th.cat([pair[0], pair[1]]) for pair in pairs_list]) + check_cast_results = raytest_batch(start_points=all_pairs[:, :3], end_points=all_pairs[:, 3:]) + if any(ray["hit"] for ray in check_cast_results): + if m.DEBUG_SAMPLING: + refusal_log.append("check ray info: %r" % (check_cast_results)) + + return False + + return True diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sim_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sim_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f43ebd2b4716720ca09ec95873e47739ead08a9d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sim_utils.py @@ -0,0 +1,18 @@ +import omnigibson.lazy as lazy +from omnigibson.utils import python_utils + + +def meets_minimum_isaac_version(minimum_version, current_version=None): + def _transform_isaac_version(str): + # In order to avoid issues with the version scheme change from 202X.X.X to X.X.X, + # transform Isaac Sim versions to all not be 202x-based e.g. 2021.2.3 -> 1.2.3 + return str[3:] if str.startswith("202") else str + + # If the user has not provided the current Isaac version, get it from the system. + if current_version is None: + current_version = lazy.isaacsim.core.version.get_version()[0] + + # Transform and compare. + return python_utils.meets_minimum_version( + _transform_isaac_version(current_version), _transform_isaac_version(minimum_version) + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/teleop_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/teleop_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..458081396ab6437354e8ce91e8e19ce0d4d3bf57 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/teleop_utils.py @@ -0,0 +1,693 @@ +import time +from dataclasses import dataclass, field +from typing import Iterable, Literal, Optional, Tuple + +import torch as th + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import create_module_macros +from omnigibson.prims.geom_prim import GeomPrim +from omnigibson.prims.xform_prim import XFormPrim +from omnigibson.controllers import ControllerView +from omnigibson.robots.robot import Robot +from omnigibson.sensors import VisionSensor +from omnigibson.utils.ui_utils import KeyboardEventHandler, create_module_logger +from omnigibson.utils.usd_utils import scene_relative_prim_path_to_absolute + +try: + from telemoma.configs.base_config import teleop_config + + # TODO: the imported telemoma interfaces does not work for our purposes because + # 1) dimensionality mismatch - telemoma torso action is 1 dim 2) telemoma strictly uses numpy + # from telemoma.human_interface.teleop_core import TeleopAction, TeleopObservation + from telemoma.human_interface.teleop_policy import TeleopPolicy + from telemoma.utils.general_utils import AttrDict +except ImportError as e: + raise e from ValueError("For teleoperation, install telemoma by running 'pip install telemoma'") + +# Create module logger +log = create_module_logger(module_name=__name__) + +m = create_module_macros(module_path=__file__) +m.movement_speed = 0.5 # the speed of the robot base movement +m.rotation_speed = 0.1 + + +@dataclass +class TeleopAction(AttrDict): + left: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(1)))) + right: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(1)))) + base: th.Tensor = field(default_factory=lambda: th.zeros(3)) + torso: float = field(default_factory=lambda: 0.0) + extra: dict = field(default_factory=dict) + + +@dataclass +class TeleopObservation(AttrDict): + left: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(2)))) + right: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(2)))) + base: th.Tensor = field(default_factory=lambda: th.zeros(3)) + torso: float = field(default_factory=lambda: 0.0) + extra: dict = field(default_factory=dict) + + +class TeleopSystem(TeleopPolicy): + """ + Base class for teleop policy + """ + + def __init__(self, config: AttrDict, robot: Optional[Robot] = None, show_control_marker: bool = False) -> None: + """ + Initializes the Teleoperation System + Args: + config (AttrDict): configuration dictionary + robot (Optional[Robot]): the robot that will be controlled. Can be None. + show_control_marker (bool): whether to show a visual marker that indicates the target pose of the control. + """ + super().__init__(config) + self.teleop_action = TeleopAction() + self.robot_obs = TeleopObservation() + self.robot = robot + self.robot_arms = None if not self.robot else ["left", "right"] if self.robot.n_arms == 2 else ["right"] + # robot parameters + self.movement_speed = m.movement_speed + self.rotation_speed = m.rotation_speed + self.show_control_marker = show_control_marker + + def get_obs(self) -> TeleopObservation: + """ + Retrieve observation data from robot + Returns: + TeleopObservation: dataclass containing robot observations + """ + robot_obs = TeleopObservation() + + if self.robot is None: + return robot_obs + + base_pos, base_orn = self.robot.get_position_orientation() + robot_obs.base = th.cat((base_pos[:2], th.tensor([T.quat2euler(base_orn)[2]]))) + + if self.robot_arms: + for i, arm in enumerate(self.robot_arms): + abs_cur_pos, abs_cur_orn = self.robot.eef_links[ + self.robot.arm_names[self.robot_arms.index(arm)] + ].get_position_orientation() + rel_cur_pos, rel_cur_orn = T.relative_pose_transform(abs_cur_pos, abs_cur_orn, base_pos, base_orn) + gripper_pos = th.mean( + self.robot.get_joint_positions(normalized=True)[ + self.robot.gripper_control_idx[self.robot.arm_names[i]] + ] + ).unsqueeze(0) + # if we are grasping, we manually set the gripper position to be at most 0.5 + gripper_group_key, gripper_ci = self.robot.controllers[f"gripper_{self.robot.arm_names[i]}"] + if ControllerView.is_grasping(gripper_group_key, gripper_ci): + gripper_pos = th.min(gripper_pos, th.tensor([0.5])) + robot_obs[arm] = th.cat((rel_cur_pos, rel_cur_orn, gripper_pos)) + + return robot_obs + + def get_action(self, obs: TeleopObservation) -> th.Tensor: + """ + Generate action data from VR input for robot teleoperation + Args: + robot_obs (TeleopObservation): dataclass containing robot observations + Returns: + th.Tensor: array of action data or None if robot is None + """ + if self.robot is None: + return None + + # get teleop action + self.teleop_action = super().get_action(obs) + return self.robot.teleop_data_to_action(self.teleop_action) + + def reset(self) -> None: + """ + Reset the teleop policy + """ + self.teleop_action = TeleopAction() + self.robot_obs = TeleopObservation() + for interface in self.interfaces.values(): + interface.reset_state() + + +class OVXRSystem(TeleopSystem): + """ + VR Teleoperation System build on top of Omniverse XR extension and TeleMoMa's TeleopSystem + """ + + def __init__( + self, + robot: Robot, + show_control_marker: bool = True, + system: str = "SteamVR", + disable_display_output: bool = False, + eef_tracking_mode: Literal["controller", "hand", "disabled"] = "controller", + # TODO: fix this to only take something like a prim path + align_anchor_to: Literal["camera", "base", "touchpad"] = "camera", + view_angle_limits: Optional[Iterable[float]] = None, + ) -> None: + """ + Initializes the VR system + Args: + robot (Robot): the robot that VR will control. + show_control_marker (bool): whether to show a control marker + system (str): the VR system to use, one of ["OpenXR", "SteamVR"], default is "SteamVR". + disable_display_output (bool): whether we will not display output to the VR headset (only use controller tracking), default is False. + eef_tracking_mode (Literal): whether to use controller tracking or hand tracking, one of ["controller", "hand", "disabled"], default is controller. + align_anchor_to (Literal): specify where the VR view aligns to, one of ["camera", "base", "touchpad"], defaults to robot camera. + The "touchpad" option enables free movement of the VR view (i.e. the user), while the other two constrain the VR view to the either the robot base or camera pose. + view_angle_limits (Iterable): the view angle limits for the VR system (roll, pitch, and yaw) in degrees, default is None. + """ + align_to_prim = isinstance(align_anchor_to, XFormPrim) + assert ( + align_anchor_to + in [ + "camera", + "base", + "touchpad", + ] + or align_to_prim + ), "align_anchor_to must be one of ['camera', 'base', 'touchpad'] or a XFormPrim" + self.align_anchor_to = align_anchor_to + self.anchor_prim = None + if align_to_prim: + self.set_anchor_with_prim(self.align_anchor_to) + self.raw_data = {} + self.old_raw_data = {} + # run super method + super().__init__(teleop_config, robot, show_control_marker) + # get xr core and profile + self.xr_core = lazy.omni.kit.xr.core.XRCore.get_singleton() + self.vr_profile = self.xr_core.get_profile("vr") + self.disable_display_output = disable_display_output + # visualize control markers + lazy.carb.settings.get_settings().set( + "/defaults/xr/profile/" + self.xr_core.get_current_profile_name() + "/controllers/visible", + self.show_control_marker, + ) + # set override leveled basis to be true (if this is false, headset would not track anchor pitch orientation) + allow_roll = False if align_anchor_to == "touchpad" else True + lazy.carb.settings.get_settings().set( + self.vr_profile.get_persistent_path() + "overrideLeveledBasis", allow_roll + ) + # set anchor mode to be custom anchor + lazy.carb.settings.get_settings().set( + self.vr_profile.get_scene_persistent_path() + "anchorMode", "custom_anchor" + ) + if align_anchor_to != "touchpad": + # set override leveled basis to be true (if this is false, headset would not track anchor pitch orientation) + lazy.carb.settings.get_settings().set(self.vr_profile.get_persistent_path() + "overrideLeveledBasis", True) + # set vr system + lazy.carb.settings.get_settings().set(self.vr_profile.get_persistent_path() + "system/display", system) + # set display mode + lazy.carb.settings.get_settings().set( + self.vr_profile.get_persistent_path() + "disableDisplayOutput", disable_display_output + ) + lazy.carb.settings.get_settings().set("/rtx/rendermode", "RaytracedLighting") + # devices info + self.hmd = None + self.controllers = {} + self.trackers = {} + # setup event subscriptions + self.reset() + self.eef_tracking_mode = eef_tracking_mode + if eef_tracking_mode == "hand": + self.raw_data["hand_data"] = {} + self.teleop_action.hand_data = {} + self._hand_tracking_subscription = self.xr_core.get_message_bus().create_subscription_to_pop_by_type( + lazy.omni.kit.xr.core.XRCoreEventType.hand_joints, self._update_hand_tracking_data, name="hand tracking" + ) + self.robot_cameras = ( + [s for s in self.robot.sensors.values() if isinstance(s, VisionSensor)] if self.robot else [] + ) + # TODO: this camera id is specific to R1, because it has 3 cameras, we need to make this more general + self.active_camera_id = 2 + if self.align_anchor_to == "camera" and len(self.robot_cameras) == 0: + raise ValueError("No camera found on robot, cannot align anchor to camera") + # we want to further slow down the movement speed if we are using touchpad movement + if self.align_anchor_to == "touchpad": + self.movement_speed *= 0.1 + self.rotation_speed *= 0.3 + + self.head_canonical_transformation = None + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.R, + callback_fn=self.register_head_canonical_transformation, + ) + KeyboardEventHandler.add_keyboard_callback( + key=lazy.carb.input.KeyboardInput.Q, + callback_fn=self.stop, + ) + self._update_camera_callback = self.xr_core.get_message_bus().create_subscription_to_pop_by_type( + lazy.omni.kit.xr.core.XRCoreEventType.pre_sync_update, self._update_camera_pose, name="update camera" + ) + + self._view_blackout_prim = None + self._view_angle_limits = ( + [T.deg2rad(limit) for limit in view_angle_limits] if view_angle_limits is not None else None + ) + if self._view_angle_limits is not None: + scene = self.robot.scene + blackout_relative_path = "/view_blackout" + blackout_prim_path = scene_relative_prim_path_to_absolute(scene, blackout_relative_path) + blackout_sphere = lazy.pxr.UsdGeom.Sphere.Define(og.sim.stage, blackout_prim_path) + blackout_sphere.CreateRadiusAttr().Set(0.1) + blackout_sphere.CreateDisplayColorAttr().Set(lazy.pxr.Vt.Vec3fArray([255, 255, 255])) + self._view_blackout_prim = GeomPrim( + relative_prim_path=blackout_relative_path, + name="view_blackout", + ) + self._view_blackout_prim.load(scene) + self._view_blackout_prim.initialize() + self._view_blackout_prim.visible = False + + def _update_camera_pose(self, e) -> None: + if self.align_anchor_to == "touchpad": + # we use x, y from right controller for 2d movement and y from left controller for z movement + self._move_anchor( + pos_offset=th.cat((th.tensor([self.teleop_action.torso]), self.teleop_action.base[[0, 2]])) + ) + else: + if self.anchor_prim is not None: + reference_frame = self.anchor_prim + elif self.align_anchor_to == "camera": + reference_frame = self.robot_cameras[self.active_camera_id] + elif self.align_anchor_to == "base": + reference_frame = self.robot + else: + raise ValueError(f"Invalid anchor: {self.align_anchor_to}") + + anchor_pos, anchor_orn = reference_frame.get_position_orientation() + + if self.head_canonical_transformation is not None: + current_head_physical_world_pose = self.xr2og(self.hmd.get_pose()) + # Find the orientation change from canonical to current physical orientation + _, relative_orientation = T.relative_pose_transform( + *current_head_physical_world_pose, *self.head_canonical_transformation + ) + anchor_orn = T.quat_multiply(anchor_orn, relative_orientation) + + if self._view_blackout_prim is not None: + relative_ori_in_euler = T.quat2euler(relative_orientation) + roll_limit, pitch_limit, yaw_limit = self._view_angle_limits + # OVXR has a different coordinate system than OmniGibson + if ( + abs(relative_ori_in_euler[0]) > pitch_limit + or abs(relative_ori_in_euler[1]) > yaw_limit + or abs(relative_ori_in_euler[2]) > roll_limit + ): + self._view_blackout_prim.set_position_orientation(anchor_pos, anchor_orn) + self._view_blackout_prim.visible = True + else: + self._view_blackout_prim.visible = False + anchor_pose = self.og2xr(anchor_pos, anchor_orn) + self.xr_core.schedule_set_camera(anchor_pose.numpy()) + + def register_head_canonical_transformation(self): + """ + Here's what we need to do: + 1) Let the user press a button to record head canonical orientation (GELLO and head facing forward) + 2) when the user turn their head, get orientation change from canonical to current physical orientation as R + 3) set the head in virtual world to robot head orientation + R, same position + """ + if self.hmd is None: + log.warning("No HMD found, cannot register head canonical orientation") + return + self.head_canonical_transformation = self.xr2og(self.hmd.get_pose()) + + def set_anchor_with_prim(self, prim) -> None: + """ + Set the anchor to a prim + Args: + prim (BasePrim): the prim to set the anchor to + """ + self.anchor_prim = prim + + def xr2og(self, transform: th.tensor) -> Tuple[th.tensor, th.tensor]: + """ + Apply the orientation offset from the Omniverse XR coordinate system to the OmniGibson coordinate system + Note that we have to transpose the transform matrix because Omniverse uses row-major matrices + while OmniGibson uses column-major matrices + Args: + transform (th.tensor): the transform matrix in the Omniverse XR coordinate system + Returns: + tuple(th.tensor, th.Tensor): the position and orientation in the OmniGibson coordinate system + """ + pos, orn = T.mat2pose(th.tensor(transform).T) + return pos, orn + + def og2xr(self, pos: th.tensor, orn: th.tensor) -> th.Tensor: + """ + Apply the orientation offset from the OmniGibson coordinate system to the Omniverse XR coordinate system + Args: + pos (th.tensor): the position in the OmniGibson coordinate system + orn (th.tensor): the orientation in the OmniGibson coordinate system + Returns: + th.tensor: the transform matrix in the Omniverse XR coordinate system + """ + return T.pose2mat((pos, orn)).T.double() + + def reset(self) -> None: + """ + Reset the teleop policy + """ + super().reset() + self.raw_data = {} + self.old_raw_data = {} + self.teleop_action.is_valid = {"left": False, "right": False, "head": False} + self.teleop_action.reset = {"left": False, "right": False} + self.teleop_action.head = th.zeros(6) + + @property + def is_enabled(self) -> bool: + """ + Checks whether the VR system is enabled + Returns: + bool: whether the VR system is enabled + """ + return self.vr_profile.is_enabled() + + def start(self) -> None: + """ + Enabling the VR profile + """ + self.vr_profile.request_enable_profile() + og.sim.app.update() + assert self.vr_profile.is_enabled(), "[VRSys] VR profile not enabled!" + # We want to make sure the hmd is tracking so that the whole system is ready to go + while True: + print("[VRSys] Waiting for VR headset and controllers to become active...") + og.sim.app.update() + self._update_devices() + if self.hmd is not None and "left" in self.controllers and "right" in self.controllers: + print("[VRSys] VR headset connected, put on the headset to start") + # When taking the first step, xr internally calls clear_controller_model(hand) which removes a prim from stage + # note that this does not invalidate the physics sim view but instead removes the physics view from articulation views + # og.sim.step() + # at this point we need to reinitialize the invalidated views + # og.sim.update_handles() + # for idx in range(50): + # self.update() + # # somehow, internally xr calls clear_controller_model(hand) which removes a prim from stage; + # # note that this does not invalidate the physics sim view but instead removes the physics view from articulation views + # breakpoint() + # og.sim.step() + # breakpoint() + print("[VRSys] VR system is ready") + self.register_head_canonical_transformation() + og.sim.step() + self.reset_head_transform() + og.sim.step() + break + time.sleep(1) + + def stop(self) -> None: + """ + disable VR profile + """ + self.xr_core.request_disable_profile() + og.sim.step() + assert not self.vr_profile.is_enabled(), "[VRSys] VR profile not disabled!" + + def update(self, optimized_for_tour=False) -> None: + """ + Steps the VR system and update self.teleop_action + """ + # update raw data + self.old_raw_data = self.raw_data + self.raw_data = {} + if not optimized_for_tour: + self._update_devices() + self._update_device_transforms() + self._update_button_data() + + # Fire the button callbacks + for controller_name, controller_button_datas in self.raw_data["button_data"].items(): + for button_name, button_data in controller_button_datas.items(): + print(button_data) + button_pressed = button_data["click"] + if button_pressed and not self.old_raw_data["button_data"][controller_name][button_name]["click"]: + print(f"Button {button_name} pressed on controller {controller_name}") + KeyboardEventHandler.xr_callback(controller_name, button_name) + + # Update teleop data based on controller input + if self.eef_tracking_mode == "controller": + # update eef related info + for arm_name, arm in zip(["left", "right"], self.robot_arms): + if arm in self.controllers: + controller_pose_in_robot_frame = self._pose_in_robot_frame( + self.raw_data["transforms"]["controllers"][arm][0], + self.raw_data["transforms"]["controllers"][arm][1], + ) + # When trigger is pressed, this value would be 1.0, otherwise 0.0 + # Our multi-finger gripper controller closes the gripper when the value is -1.0 and opens when > 0.0 + # So we need to negate the value here + trigger_press = ( + -self.raw_data["button_data"][arm]["trigger"]["value"] + if ( + "button_data" in self.raw_data + and arm in self.raw_data["button_data"] + and "trigger" in self.raw_data["button_data"][arm] + ) + else 0.0 + ) + self.teleop_action[arm_name] = th.cat( + ( + controller_pose_in_robot_frame[0], + T.quat2axisangle( + T.quat_multiply( + controller_pose_in_robot_frame[1], + self.robot.teleop_rotation_offset[arm_name], + ) + ), + th.tensor([trigger_press], dtype=th.float32), + ) + ) + self.teleop_action.is_valid[arm_name] = self._is_valid_transform( + self.raw_data["transforms"]["controllers"][arm] + ) + else: + self.teleop_action.is_valid[arm_name] = False + + # update base, torso, and reset info + self.teleop_action.base = th.zeros(3) + self.teleop_action.torso = 0.0 + for controller_name in self.controllers.keys(): + if "button_data" not in self.raw_data: + continue + if controller_name == "right" and "right" in self.raw_data["button_data"]: + thumbstick = self.raw_data["button_data"][controller_name]["thumbstick"] + self.teleop_action.base[2] = -thumbstick["x"] * self.rotation_speed + self.teleop_action.torso = -thumbstick["y"] * self.movement_speed + elif controller_name == "left" and "left" in self.raw_data["button_data"]: + thumbstick = self.raw_data["button_data"][controller_name]["thumbstick"] + self.teleop_action.base[0] = thumbstick["y"] * self.movement_speed + self.teleop_action.base[1] = -thumbstick["x"] * self.movement_speed + if not optimized_for_tour: + # update head related info + self.teleop_action.head = th.cat( + (self.raw_data["transforms"]["head"][0], T.quat2euler(self.raw_data["transforms"]["head"][1])) + ) + self.teleop_action.is_valid["head"] = self._is_valid_transform(self.raw_data["transforms"]["head"]) + + def get_robot_teleop_action(self) -> th.Tensor: + """ + Get the robot teleop action + Returns: + th.tensor: the robot teleop action + """ + return self.robot.teleop_data_to_action(self.teleop_action) + + def snap_controller_to_eef(self, arm: str = "right") -> None: + """ + Snap device to the robot end effector (ManipulationRobot only) + Args: + arm(str): name of the arm, one of "left" or "right". Default is "right". + """ + # TODO: fix this + pass + # robot_base_orn = self.robot.get_position_orientation()[1] + # robot_eef_pos = self.robot.eef_links[ + # self.robot.arm_names[self.robot_arms.index(arm)] + # ].get_position_orientation()[0] + # target_transform = self.og2xr(pos=robot_eef_pos, orn=robot_base_orn) + # self.vr_profile.set_physical_world_to_world_anchor_transform_to_match_xr_device( + # target_transform.numpy(), self.controllers[arm] + # ) + + def reset_head_transform(self) -> None: + """ + Function that resets the transform of the VR system (w.r.t.) head + """ + if self.align_anchor_to == "touchpad": + pos = th.tensor([0.0, 0.0, 1.0]) + orn = th.tensor([0.0, 0.0, 0.0, 1.0]) + else: + if self.anchor_prim is not None: + reference_frame = self.anchor_prim + elif self.align_anchor_to == "camera": + reference_frame = self.robot_cameras[self.active_camera_id] + elif self.align_anchor_to == "base": + reference_frame = self.robot + else: + raise ValueError(f"Invalid anchor: {self.align_anchor_to}") + pos, orn = reference_frame.get_position_orientation() + if self.robot: + self.robot.keep_still() + try: + self.xr_core.schedule_set_camera(self.og2xr(pos, orn).numpy()) + except Exception as _: + pass + + def _pose_in_robot_frame(self, pos: th.tensor, orn: th.tensor) -> Tuple[th.tensor, th.tensor]: + """ + Get the pose in the robot frame + Args: + pos (th.tensor): the position in the world frame + orn (th.tensor): the orientation in the world frame + Returns: + tuple(th.tensor, th.tensor): the position and orientation in the robot frame + """ + robot_base_pos, robot_base_orn = self.robot.get_position_orientation() + return T.relative_pose_transform(pos, orn, robot_base_pos, robot_base_orn) + + def _move_anchor( + self, pos_offset: Optional[Iterable[float]] = None, rot_offset: Optional[Iterable[float]] = None + ) -> None: + """ + Updates the anchor of the xr system in the virtual world + Args: + pos_offset (Iterable[float]): the position offset to apply to the anchor *in hmd frame*. + rot_offset (Iterable[float]): the rotation offset to apply to the anchor *in hmd frame*. + """ + if pos_offset is not None: + # note that x is forward, y is down, z is left for ovxr, but x is forward, y is left, z is up for og + pos_offset = th.tensor([-pos_offset[0], pos_offset[2], -pos_offset[1]]).double().tolist() + # self.vr_profile.add_move_physical_world_relative_to_device(pos_offset) + self.xr_core.schedule_move_space_origin_relative_to_camera(*pos_offset) + if rot_offset is not None: + return + # TODO: Fix this later + rot_offset = th.tensor(rot_offset).double().tolist() + # self.vr_profile.add_rotate_physical_world_around_device(rot_offset) + self.xr_core.schedule_rotate_space_origin_relative_to_camera(*rot_offset) # this takes yaw and pitch + + # TODO: check if this is necessary + def _is_valid_transform(self, transform: Tuple[th.tensor, th.tensor]) -> bool: + """ + Determine whether the transform is valid (ovxr plugin will return a zero position and rotation if not valid) + """ + return th.any(transform[0] != th.zeros(3)) + + def _update_devices(self) -> None: + """ + Update the VR device list + """ + # We are looking for '/user/head', '/user/hand/left', '/user/hand/right' + for device in self.xr_core.get_all_input_devices(): + device_name = str(device.get_name()) + if device_name == "/user/head" and self.hmd is None: + self.hmd = device + elif device_name == "/user/hand/left" and "left" not in self.controllers: + self.controllers["left"] = device + elif device_name == "/user/hand/right" and "right" not in self.controllers: + self.controllers["right"] = device + + def _update_device_transforms(self) -> None: + """ + Get the transform matrix of each VR device *in world frame* and store in self.raw_data + """ + assert self.hmd is not None, "VR headset device not found" + self.raw_data["transforms"] = { + "head": self.xr2og(self.hmd.get_virtual_world_pose()), + "controllers": { + name: self.xr2og(controller.get_virtual_world_pose()) for name, controller in self.controllers.items() + }, + "trackers": { + index: self.xr2og(tracker.get_virtual_world_pose()) for index, tracker in self.trackers.items() + }, + } + + def _update_button_data(self): + """ + Get the button data for each controller and store in self.raw_data + """ + if "button_data" not in self.raw_data: + self.raw_data["button_data"] = {} + + for name, controller in self.controllers.items(): + if len(controller.get_output_names()) == 0 and len(controller.get_input_names()) == 0: + continue + + # Initialize controller entry if it doesn't exist + if name not in self.raw_data["button_data"]: + self.raw_data["button_data"][name] = {} + + # Add input data + for input_name in controller.get_input_names(): + input_name = str(input_name) + # Initialize input entry if it doesn't exist + if input_name not in self.raw_data["button_data"][name]: + self.raw_data["button_data"][name][input_name] = {} + + # Add gesture data + for gesture_name in controller.get_input_gesture_names(input_name): + gesture_name = str(gesture_name) + gesture_value = controller.get_input_gesture_value(input_name, gesture_name) + self.raw_data["button_data"][name][input_name][gesture_name] = gesture_value + + def _update_hand_tracking_data(self, e) -> None: + """ + Get hand tracking data, see https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html#convention-of-hand-joints for joint indices + Args: + e (carb.events.IEvent): event that contains hand tracking data as payload + """ + e.consume() + data_dict = e.payload + for i, hand in enumerate(self.robot_arms): + robot_arm_name = self.robot.arm_names[i] + if data_dict[f"joint_count_{hand}"] != 0: + self.teleop_action.is_valid[hand] = True + self.raw_data["hand_data"][hand] = {"pos": [], "orn": []} + # hand_joint_matrices is an array of flattened 4x4 transform matrices for the 26 hand markers + hand_joint_matrices = data_dict[f"joint_matrices_{hand}"] + for j in range(26): + # extract the pose from the flattened transform matrix + pos, orn = self.xr2og(hand_joint_matrices[16 * j : 16 * (j + 1)].reshape(4, 4)) + self.raw_data["hand_data"][hand]["pos"].append(pos) + self.raw_data["hand_data"][hand]["orn"].append(orn) + self.teleop_action[hand] = th.cat( + ( + self.raw_data["hand_data"][hand]["pos"][0], + T.quat2euler( + T.quat_multiply( + self.raw_data["hand_data"][hand]["orn"][0], + self.robot.teleop_rotation_offset[robot_arm_name], + ) + ), + th.tensor([0]), + ) + ) + # Get each finger joint's rotation angle from hand tracking data + # joint_angles is a 5 x 3 array of joint rotations (from thumb to pinky, from base to tip) + joint_angles = th.zeros((5, 3)) + raw_hand_data = self.raw_data["hand_data"][hand]["pos"] + for i in range(5): + for j in range(3): + # get the 3 related joints indices + prev_joint_idx, cur_joint_idx, next_joint_idx = i * 5 + j + 1, i * 5 + j + 2, i * 5 + j + 3 + # get the 3 related joints' positions + prev_joint_pos = raw_hand_data[prev_joint_idx] + cur_joint_pos = raw_hand_data[cur_joint_idx] + next_joint_pos = raw_hand_data[next_joint_idx] + # calculate the angle formed by 3 points + v1 = cur_joint_pos - prev_joint_pos + v2 = next_joint_pos - cur_joint_pos + v1 /= th.norm(v1) + v2 /= th.norm(v2) + joint_angles[i, j] = th.arccos(v1 @ v2) + self.teleop_action.hand_data[hand] = joint_angles diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c939a9f2b72af01681164196e42a6c265203a944 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils.py @@ -0,0 +1,1612 @@ +""" +Utility functions of matrix and vector transformations. + +NOTE: This file has a 1-to-1 correspondence to transform_utils_np.py + +NOTE: convention for quaternions is (x, y, z, w) +""" + +import math +from typing import Optional, Tuple + +from omnigibson.utils.python_utils import torch_compile +import torch + +PI = math.pi + +# map axes strings to/from tuples of inner axis, parity, repetition, frame +_AXES2TUPLE = { + "sxyz": (0, 0, 0, 0), + "sxyx": (0, 0, 1, 0), + "sxzy": (0, 1, 0, 0), + "sxzx": (0, 1, 1, 0), + "syzx": (1, 0, 0, 0), + "syzy": (1, 0, 1, 0), + "syxz": (1, 1, 0, 0), + "syxy": (1, 1, 1, 0), + "szxy": (2, 0, 0, 0), + "szxz": (2, 0, 1, 0), + "szyx": (2, 1, 0, 0), + "szyz": (2, 1, 1, 0), + "rzyx": (0, 0, 0, 1), + "rxyx": (0, 0, 1, 1), + "ryzx": (0, 1, 0, 1), + "rxzx": (0, 1, 1, 1), + "rxzy": (1, 0, 0, 1), + "ryzy": (1, 0, 1, 1), + "rzxy": (1, 1, 0, 1), + "ryxy": (1, 1, 1, 1), + "ryxz": (2, 0, 0, 1), + "rzxz": (2, 0, 1, 1), + "rxyz": (2, 1, 0, 1), + "rzyz": (2, 1, 1, 1), +} + + +@torch_compile +def copysign(a, b): + # type: (float, torch.Tensor) -> torch.Tensor + a = torch.tensor(a, device=b.device, dtype=torch.float).repeat(b.shape[0]) + return torch.abs(a) * torch.sign(b) + + +@torch_compile +def anorm(x: torch.Tensor, dim: Optional[int] = None, keepdim: bool = False) -> torch.Tensor: + """Compute L2 norms along specified axes.""" + return torch.norm(x, dim=dim, keepdim=keepdim) + + +@torch_compile +def normalize(v: torch.Tensor, dim: Optional[int] = None, eps: float = 1e-10) -> torch.Tensor: + """L2 Normalize along specified axes.""" + norm = anorm(v, dim=dim, keepdim=True) + return v / torch.where(norm < eps, torch.full_like(norm, eps), norm) + + +@torch_compile +def dot(v1, v2, dim=-1, keepdim=False): + """ + Computes dot product between two vectors along the provided dim, optionally keeping the dimension + + Args: + v1 (tensor): (..., N, ...) arbitrary vector + v2 (tensor): (..., N, ...) arbitrary vector + dim (int): Dimension to sum over for dot product + keepdim (bool): Whether to keep dimension over which dot product is calculated + + Returns: + tensor: (..., [1,] ...) dot product of vectors, with optional dimension kept if @keepdim is True + """ + # type: (Tensor, Tensor, int, bool) -> Tensor + return torch.sum(v1 * v2, dim=dim, keepdim=keepdim) + + +@torch_compile +def unit_vector(data: torch.Tensor, dim: Optional[int] = None, out: Optional[torch.Tensor] = None) -> torch.Tensor: + """ + Returns tensor normalized by length, i.e. Euclidean norm, along axis. + + Args: + data (torch.Tensor): data to normalize + dim (Optional[int]): If specified, determines specific dimension along data to normalize + out (Optional[torch.Tensor]): If specified, will store computation in this variable + + Returns: + torch.Tensor: Normalized vector + """ + if out is None: + if not isinstance(data, torch.Tensor): + data = torch.tensor(data, dtype=torch.float32) + else: + data = data.clone().to(torch.float32) + + if data.ndim == 1: + return data / torch.sqrt(torch.dot(data, data)) + else: + if out is not data: + out.copy_(data) + data = out + + if dim is None: + dim = -1 + + length = torch.sum(data * data, dim=dim, keepdim=True).sqrt() + data = data / (length + 1e-8) # Add small epsilon to avoid division by zero + + return data + + +@torch_compile +def quat_apply(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor: + """ + Apply a quaternion rotation to a vector (equivalent to R.from_quat(x).apply(y)) + Args: + quat (torch.Tensor): (4,) or (N, 4) or (N, 1, 4) quaternion in (x, y, z, w) format + vec (torch.Tensor): (3,) or (M, 3) or (1, M, 3) vector to rotate + Returns: + torch.Tensor: (M, 3) or (N, M, 3) rotated vector + """ + assert quat.shape[-1] == 4, "Quaternion must have 4 components in last dimension" + assert vec.shape[-1] == 3, "Vector must have 3 components in last dimension" + + # Ensure quat is at least 2D and vec is at least 2D + if quat.dim() == 1: + quat = quat.unsqueeze(0) + if vec.dim() == 1: + vec = vec.unsqueeze(0) + + # Ensure quat is (N, 1, 4) and vec is (1, M, 3) + if quat.dim() == 2: + quat = quat.unsqueeze(1) + if vec.dim() == 2: + vec = vec.unsqueeze(0) + + # Extract quaternion components + qx, qy, qz, qw = quat.unbind(-1) + + # Compute the quaternion multiplication + t = torch.stack( + [ + 2 * (qy * vec[..., 2] - qz * vec[..., 1]), + 2 * (qz * vec[..., 0] - qx * vec[..., 2]), + 2 * (qx * vec[..., 1] - qy * vec[..., 0]), + ], + dim=-1, + ) + + # Compute the final rotated vector + result = vec + qw.unsqueeze(-1) * t + torch.cross(quat[..., :3], t, dim=-1) + + # Remove any extra dimensions + return result.squeeze() + + +@torch_compile +def convert_quat(q: torch.Tensor, to: str = "xyzw") -> torch.Tensor: + """ + Converts quaternion from one convention to another. + The convention to convert TO is specified as an optional argument. + If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa. + + Args: + q (torch.Tensor): a 4-dim array corresponding to a quaternion + to (str): either 'xyzw' or 'wxyz', determining which convention to convert to. + + Returns: + torch.Tensor: The converted quaternion + """ + if to == "xyzw": + return torch.stack([q[1], q[2], q[3], q[0]], dim=0) + elif to == "wxyz": + return torch.stack([q[3], q[0], q[1], q[2]], dim=0) + else: + raise ValueError("convert_quat: choose a valid `to` argument (xyzw or wxyz)") + + +@torch_compile +def quat_multiply(quaternion1: torch.Tensor, quaternion0: torch.Tensor) -> torch.Tensor: + """ + Return multiplication of two quaternions (q1 * q0). + + Args: + quaternion1 (torch.Tensor): (x,y,z,w) quaternion + quaternion0 (torch.Tensor): (x,y,z,w) quaternion + + Returns: + torch.Tensor: (x,y,z,w) multiplied quaternion + """ + x0, y0, z0, w0 = quaternion0[0], quaternion0[1], quaternion0[2], quaternion0[3] + x1, y1, z1, w1 = quaternion1[0], quaternion1[1], quaternion1[2], quaternion1[3] + + return torch.stack( + [ + x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0, + -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0, + x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0, + -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0, + ], + dim=0, + ) + + +@torch_compile +def quat_conjugate(quaternion: torch.Tensor) -> torch.Tensor: + """ + Return conjugate of quaternion. + + Args: + quaternion (torch.Tensor): (x,y,z,w) quaternion + + Returns: + torch.Tensor: (x,y,z,w) quaternion conjugate + """ + return torch.cat([-quaternion[:3], quaternion[3:]]) + + +@torch_compile +def quat_inverse(quaternion: torch.Tensor) -> torch.Tensor: + """ + Return inverse of quaternion. + + E.g.: + >>> q0 = random_quaternion() + >>> q1 = quat_inverse(q0) + >>> torch.allclose(quat_multiply(q0, q1), [0, 0, 0, 1]) + True + + Args: + quaternion (torch.tensor): (x,y,z,w) quaternion + + Returns: + torch.tensor: (x,y,z,w) quaternion inverse + """ + return quat_conjugate(quaternion) / torch.dot(quaternion, quaternion) + + +@torch_compile +def quat_distance(quaternion1, quaternion0): + """ + Returns distance between two quaternions, such that distance * quaternion0 = quaternion1 + Always returns the shorter rotation path. + + Args: + quaternion1 (torch.tensor): (x,y,z,w) quaternion or (..., 4) batched quaternions + quaternion0 (torch.tensor): (x,y,z,w) quaternion or (..., 4) batched quaternions + + Returns: + torch.tensor: (x,y,z,w) quaternion distance or (..., 4) batched quaternion distances + """ + # Compute dot product along the last axis (quaternion components) + d = torch.sum(quaternion0 * quaternion1, dim=-1, keepdim=True) + # If dot product is negative, negate one quaternion to get shorter path + quaternion1 = torch.where(d < 0.0, -quaternion1, quaternion1) + + return quat_multiply(quaternion1, quat_inverse(quaternion0)) + + +@torch_compile +def quat_slerp(quat0, quat1, frac, shortestpath=True, eps=1.0e-15): + """ + Return spherical linear interpolation between two quaternions. + + Args: + quat0 (tensor): (..., 4) tensor where the final dim is (x,y,z,w) initial quaternion + quat1 (tensor): (..., 4) tensor where the final dim is (x,y,z,w) final quaternion + frac (tensor): Values in [0.0, 1.0] representing fraction of interpolation + shortestpath (bool): If True, will calculate shortest path + eps (float): Value to check for singularities + Returns: + tensor: (..., 4) Interpolated + """ + # type: (Tensor, Tensor, Tensor, bool, float) -> Tensor + # reshape quaternion + quat_shape = quat0.shape + quat0 = unit_vector(quat0.reshape(-1, 4), dim=-1, out=None) + quat1 = unit_vector(quat1.reshape(-1, 4), dim=-1, out=None) + + # Check for endpoint cases + where_start = frac <= 0.0 + where_end = frac >= 1.0 + + d = dot(quat0, quat1, dim=-1, keepdim=True) + if shortestpath: + quat1 = torch.where(d < 0.0, -quat1, quat1) + d = torch.abs(d) + angle = torch.acos(torch.clip(d, -1.0, 1.0)) + + # Check for small quantities (i.e.: q0 = q1) + where_small_diff = torch.abs(torch.abs(d) - 1.0) < eps + where_small_angle = abs(angle) < eps + + isin = 1.0 / torch.sin(angle) + val = quat0 * torch.sin((1.0 - frac) * angle) * isin + quat1 * torch.sin(frac * angle) * isin + + # Filter edge cases + val = torch.where( + where_small_diff | where_small_angle | where_start, + quat0, + torch.where( + where_end, + quat1, + val, + ), + ) + + # Reshape and return values + return val.reshape(list(quat_shape)) + + +@torch_compile +def random_quaternion(num_quaternions: int = 1) -> torch.Tensor: + """ + Generate random rotation quaternions, uniformly distributed over SO(3). + + Arguments: + num_quaternions (int): number of quaternions to generate (default: 1) + + Returns: + torch.Tensor: A tensor of shape (num_quaternions, 4) containing random unit quaternions. + """ + # Generate four random numbers between 0 and 1 + rand = torch.rand(num_quaternions, 4) + + # Use the formula from Ken Shoemake's "Uniform Random Rotations" + r1 = torch.sqrt(1.0 - rand[:, 0]) + r2 = torch.sqrt(rand[:, 0]) + t1 = 2 * torch.pi * rand[:, 1] + t2 = 2 * torch.pi * rand[:, 2] + + quaternions = torch.stack([r1 * torch.sin(t1), r1 * torch.cos(t1), r2 * torch.sin(t2), r2 * torch.cos(t2)], dim=1) + + return quaternions + + +@torch_compile +def random_axis_angle(angle_limit: float = 2.0 * math.pi): + """ + Samples an axis-angle rotation by first sampling a random axis + and then sampling an angle. If @angle_limit is provided, the size + of the rotation angle is constrained. + + Args: + angle_limit (float): Determines magnitude limit of angles to generate + + Raises: + AssertionError: [Invalid RNG] + """ + # sample random axis using a normalized sample from spherical Gaussian. + # see (http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/) + # for why it works. + random_axis = torch.randn(3) + random_axis /= torch.norm(random_axis) + random_angle = torch.rand(1) * angle_limit + return random_axis, random_angle.item() + + +@torch_compile +def quat2mat(quaternion): + """ + Convert quaternions into rotation matrices. + + Args: + quaternion (torch.Tensor): A tensor of shape (..., 4) representing batches of quaternions (x, y, z, w). + + Returns: + torch.Tensor: A tensor of shape (..., 3, 3) representing batches of rotation matrices. + """ + quaternion = quaternion / torch.norm(quaternion, dim=-1, keepdim=True) + + outer = quaternion.unsqueeze(-1) * quaternion.unsqueeze(-2) + + # Extract the necessary components + xx = outer[..., 0, 0] + yy = outer[..., 1, 1] + zz = outer[..., 2, 2] + xy = outer[..., 0, 1] + xz = outer[..., 0, 2] + yz = outer[..., 1, 2] + xw = outer[..., 0, 3] + yw = outer[..., 1, 3] + zw = outer[..., 2, 3] + + rmat = torch.empty(quaternion.shape[:-1] + (3, 3), dtype=quaternion.dtype, device=quaternion.device) + + rmat[..., 0, 0] = 1 - 2 * (yy + zz) + rmat[..., 0, 1] = 2 * (xy - zw) + rmat[..., 0, 2] = 2 * (xz + yw) + + rmat[..., 1, 0] = 2 * (xy + zw) + rmat[..., 1, 1] = 1 - 2 * (xx + zz) + rmat[..., 1, 2] = 2 * (yz - xw) + + rmat[..., 2, 0] = 2 * (xz - yw) + rmat[..., 2, 1] = 2 * (yz + xw) + rmat[..., 2, 2] = 1 - 2 * (xx + yy) + + return rmat + + +@torch_compile +def mat2quat(rmat: torch.Tensor) -> torch.Tensor: + """ + Converts given rotation matrix to quaternion. + Args: + rmat (torch.Tensor): (3, 3) or (..., 3, 3) rotation matrix + Returns: + torch.Tensor: (4,) or (..., 4) (x,y,z,w) float quaternion angles + """ + assert torch.allclose(torch.linalg.det(rmat), torch.tensor(1.0)), "Rotation matrix must not be scaled" + + # Check if input is a single matrix or a batch + is_single = rmat.dim() == 2 + if is_single: + rmat = rmat.unsqueeze(0) + + batch_shape = rmat.shape[:-2] + mat_flat = rmat.reshape(-1, 3, 3) + + m00, m01, m02 = mat_flat[:, 0, 0], mat_flat[:, 0, 1], mat_flat[:, 0, 2] + m10, m11, m12 = mat_flat[:, 1, 0], mat_flat[:, 1, 1], mat_flat[:, 1, 2] + m20, m21, m22 = mat_flat[:, 2, 0], mat_flat[:, 2, 1], mat_flat[:, 2, 2] + + trace = m00 + m11 + m22 + + trace_positive = trace > 0 + cond1 = (m00 > m11) & (m00 > m22) & ~trace_positive + cond2 = (m11 > m22) & ~(trace_positive | cond1) + cond3 = ~(trace_positive | cond1 | cond2) + + # Trace positive condition + sq = torch.where(trace_positive, torch.sqrt(trace + 1.0) * 2.0, torch.zeros_like(trace)) + qw = torch.where(trace_positive, 0.25 * sq, torch.zeros_like(trace)) + qx = torch.where(trace_positive, (m21 - m12) / sq, torch.zeros_like(trace)) + qy = torch.where(trace_positive, (m02 - m20) / sq, torch.zeros_like(trace)) + qz = torch.where(trace_positive, (m10 - m01) / sq, torch.zeros_like(trace)) + + # Condition 1 + sq = torch.where(cond1, torch.sqrt(1.0 + m00 - m11 - m22) * 2.0, sq) + qw = torch.where(cond1, (m21 - m12) / sq, qw) + qx = torch.where(cond1, 0.25 * sq, qx) + qy = torch.where(cond1, (m01 + m10) / sq, qy) + qz = torch.where(cond1, (m02 + m20) / sq, qz) + + # Condition 2 + sq = torch.where(cond2, torch.sqrt(1.0 + m11 - m00 - m22) * 2.0, sq) + qw = torch.where(cond2, (m02 - m20) / sq, qw) + qx = torch.where(cond2, (m01 + m10) / sq, qx) + qy = torch.where(cond2, 0.25 * sq, qy) + qz = torch.where(cond2, (m12 + m21) / sq, qz) + + # Condition 3 + sq = torch.where(cond3, torch.sqrt(1.0 + m22 - m00 - m11) * 2.0, sq) + qw = torch.where(cond3, (m10 - m01) / sq, qw) + qx = torch.where(cond3, (m02 + m20) / sq, qx) + qy = torch.where(cond3, (m12 + m21) / sq, qy) + qz = torch.where(cond3, 0.25 * sq, qz) + + quat = torch.stack([qx, qy, qz, qw], dim=-1) + + # Normalize the quaternion + quat = quat / torch.norm(quat, dim=-1, keepdim=True) + + # Reshape to match input batch shape + quat = quat.reshape(batch_shape + (4,)) + + # If input was a single matrix, remove the batch dimension + if is_single: + quat = quat.squeeze(0) + + return quat + + +def mat2quat_batch(rmat: torch.Tensor) -> torch.Tensor: + """ + Converts given rotation matrix to quaternion. Version optimized for batch operations + + Args: + rmat (torch.Tensor): (3, 3) or (..., 3, 3) rotation matrix + + Returns: + torch.Tensor: (4,) or (..., 4) (x,y,z,w) float quaternion angles + """ + # For torch, no different than basic version + return mat2quat(rmat) + + +@torch_compile +def decompose_mat(hmat): + """Batched decompose_mat function - assumes input is already batched + + Args: + hmat (torch.Tensor): (B, 4, 4) batch of homogeneous matrices + + Returns: + scale: (B, 3) scale factors + shear: (B, 3) shear factors + quat: (B, 4) quaternions + translate: (B, 3) translations + """ + batch_size = hmat.shape[0] + M = torch.as_tensor(hmat, dtype=torch.float32).transpose(-2, -1) # (B, 4, 4) transposed + + # Check M[3, 3] for all batch items + diag_vals = M[:, 3, 3] # (B,) + + # TODO: this line might be a VRAM killer, investigate this + # if torch.any(torch.abs(diag_vals) < 1e-6): + # raise ValueError("Some M[3, 3] values are zero") + + M = M / diag_vals.unsqueeze(-1).unsqueeze(-1) # (B, 4, 4) + P = M.clone() + P[:, :, 3] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=hmat.device, dtype=hmat.dtype).expand(batch_size, 4) + + det_P = torch.linalg.det(P[:, :3, :3]) # (B,) + torch._assert(torch.all(torch.abs(det_P) >= 1e-6), "Some matrices are singular and cannot be decomposed") + + if not torch.allclose(M[:, :3, 3], torch.tensor(0.0, device=hmat.device, dtype=hmat.dtype)): + raise ValueError("Some matrices have perspective components") + + scale = torch.zeros((batch_size, 3), device=hmat.device, dtype=hmat.dtype) + shear = torch.zeros((batch_size, 3), device=hmat.device, dtype=hmat.dtype) + + translate = M[:, 3, :3].clone() # (B, 3) + M[:, 3, :3] = 0.0 + + row = M[:, :3, :3].clone() # (B, 3, 3) + + # Scale and orthogonalize rows + scale[:, 0] = torch.linalg.norm(row[:, 0], dim=-1) # (B,) + row[:, 0] = row[:, 0] / scale[:, 0].unsqueeze(-1) # (B, 3) + + shear[:, 0] = torch.sum(row[:, 0] * row[:, 1], dim=-1) # (B,) + row[:, 1] = row[:, 1] - row[:, 0] * shear[:, 0].unsqueeze(-1) # (B, 3) + + scale[:, 1] = torch.linalg.norm(row[:, 1], dim=-1) # (B,) + row[:, 1] = row[:, 1] / scale[:, 1].unsqueeze(-1) # (B, 3) + shear[:, 0] = shear[:, 0] / scale[:, 1] + + shear[:, 1] = torch.sum(row[:, 0] * row[:, 2], dim=-1) # (B,) + row[:, 2] = row[:, 2] - row[:, 0] * shear[:, 1].unsqueeze(-1) # (B, 3) + + shear[:, 2] = torch.sum(row[:, 1] * row[:, 2], dim=-1) # (B,) + row[:, 2] = row[:, 2] - row[:, 1] * shear[:, 2].unsqueeze(-1) # (B, 3) + + scale[:, 2] = torch.linalg.norm(row[:, 2], dim=-1) # (B,) + row[:, 2] = row[:, 2] / scale[:, 2].unsqueeze(-1) # (B, 3) + shear[:, 1:] = shear[:, 1:] / scale[:, 2].unsqueeze(-1) + + # Check orientation + cross_product = torch.cross(row[:, 1], row[:, 2], dim=-1) # (B, 3) + dot_product = torch.sum(row[:, 0] * cross_product, dim=-1) # (B,) + neg_mask = dot_product < 0 # (B,) + + scale = torch.where(neg_mask.unsqueeze(-1), -scale, scale) # (B, 3) + row = torch.where(neg_mask.unsqueeze(-1).unsqueeze(-1), -row, row) # (B, 3, 3) + + # Convert to quaternions - assuming mat2quat can handle batched input + quat = mat2quat(row.transpose(-2, -1)) # (B, 4) + + return scale, shear, quat, translate + + +@torch_compile +def mat2pose(hmat): + """ + Converts a homogeneous 4x4 matrix into pose. + + Args: + hmat (torch.tensor): a 4x4 homogeneous matrix + + Returns: + 2-tuple: + - (torch.tensor) (3,) position array in cartesian coordinates + - (torch.tensor) (4,) orientation array in quaternion form + """ + # Add batch dimension, process, then squeeze + hmat_batched = hmat.unsqueeze(0) # (1, 4, 4) + _, _, quat, translate = decompose_mat(hmat_batched) + return translate.squeeze(0), quat.squeeze(0) + + +@torch_compile +def mat2pose_batched(hmat): + """ + Converts batched homogeneous 4x4 matrices into poses. + + Args: + hmat (torch.tensor): (B, 4, 4) batch of homogeneous matrices + + Returns: + 2-tuple: + - (torch.tensor) (B, 3) position arrays in cartesian coordinates + - (torch.tensor) (B, 4) orientation arrays in quaternion form + """ + _, _, quat, translate = decompose_mat(hmat) + return translate, quat + + +@torch_compile +def vec2quat(vec: torch.Tensor, up: torch.Tensor = torch.tensor([0.0, 0.0, 1.0])) -> torch.Tensor: + """ + Converts given 3d-direction vector @vec to quaternion orientation with respect to another direction vector @up + + Args: + vec (torch.Tensor): (x,y,z) direction vector (possibly non-normalized) + up (torch.Tensor): (x,y,z) direction vector representing the canonical up direction (possibly non-normalized) + + Returns: + torch.Tensor: (x,y,z,w) quaternion + """ + # Ensure inputs are 2D + if vec.dim() == 1: + vec = vec.unsqueeze(0) + if up.dim() == 1: + up = up.unsqueeze(0) + + vec_n = normalize(vec, dim=-1, eps=1e-10) + up_n = normalize(up, dim=-1, eps=1e-10) + + s_n = torch.cross(up_n, vec_n, dim=-1) + u_n = torch.cross(vec_n, s_n, dim=-1) + + rmat = torch.stack([vec_n, s_n, u_n], dim=-1) + + return mat2quat(rmat) + + +@torch_compile +def euler2quat(euler: torch.Tensor) -> torch.Tensor: + """ + Converts euler angles into quaternion form + + Args: + euler (torch.Tensor): (..., 3) (r,p,y) angles + + Returns: + torch.Tensor: (..., 4) (x,y,z,w) float quaternion angles + + Raises: + AssertionError: [Invalid input shape] + """ + assert euler.shape[-1] == 3, "Invalid input shape" + + # Unpack roll, pitch, yaw + unbound_euler = euler.unbind(-1) + roll, pitch, yaw = unbound_euler[0], unbound_euler[1], unbound_euler[2] + + # Compute sines and cosines of half angles + cy = torch.cos(yaw * 0.5) + sy = torch.sin(yaw * 0.5) + cr = torch.cos(roll * 0.5) + sr = torch.sin(roll * 0.5) + cp = torch.cos(pitch * 0.5) + sp = torch.sin(pitch * 0.5) + + # Compute quaternion components + qw = cy * cr * cp + sy * sr * sp + qx = cy * sr * cp - sy * cr * sp + qy = cy * cr * sp + sy * sr * cp + qz = sy * cr * cp - cy * sr * sp + + # Stack and return + return torch.stack([qx, qy, qz, qw], dim=-1) + + +@torch_compile +def quat2euler(q): + single_dim = q.dim() == 1 + + if single_dim: + q = q.unsqueeze(0) + + qx, qy, qz, qw = 0, 1, 2, 3 + # roll (x-axis rotation) + sinr_cosp = 2.0 * (q[:, qw] * q[:, qx] + q[:, qy] * q[:, qz]) + cosr_cosp = q[:, qw] * q[:, qw] - q[:, qx] * q[:, qx] - q[:, qy] * q[:, qy] + q[:, qz] * q[:, qz] + roll = torch.atan2(sinr_cosp, cosr_cosp) + # pitch (y-axis rotation) + sinp = 2.0 * (q[:, qw] * q[:, qy] - q[:, qz] * q[:, qx]) + pitch = torch.where(torch.abs(sinp) >= 1, copysign(math.pi / 2.0, sinp), torch.asin(sinp)) + # yaw (z-axis rotation) + siny_cosp = 2.0 * (q[:, qw] * q[:, qz] + q[:, qx] * q[:, qy]) + cosy_cosp = q[:, qw] * q[:, qw] + q[:, qx] * q[:, qx] - q[:, qy] * q[:, qy] - q[:, qz] * q[:, qz] + yaw = torch.atan2(siny_cosp, cosy_cosp) + + euler = torch.stack([roll, pitch, yaw], dim=-1) % (2 * math.pi) + euler[euler > math.pi] -= 2 * math.pi + + if single_dim: + euler = euler.squeeze(0) + + return euler + + +@torch_compile +def euler2mat(euler): + """ + Converts euler angles into rotation matrix form + + Args: + euler (torch.tensor): (r,p,y) angles + + Returns: + torch.tensor: 3x3 rotation matrix + + Raises: + AssertionError: [Invalid input shape] + """ + euler = torch.as_tensor(euler, dtype=torch.float32) + assert euler.shape[-1] == 3, f"Invalid shaped euler {euler}" + + # Convert Euler angles to quaternion + quat = euler2quat(euler) + + # Convert quaternion to rotation matrix + return quat2mat(quat) + + +@torch_compile +def mat2euler(rmat): + """ + Converts given rotation matrix to euler angles in radian. + + Args: + rmat (torch.tensor): 3x3 rotation matrix + + Returns: + torch.tensor: (r,p,y) converted euler angles in radian vec3 float + """ + M = torch.as_tensor(rmat, dtype=torch.float32)[:3, :3] + assert torch.allclose(rmat.det(), torch.tensor(1.0)), "Rotation matrix must not be scaled" + + # Convert rotation matrix to quaternion + # Note: You'll need to implement mat2quat function + quat = mat2quat(M) + + # Convert quaternion to Euler angles + euler = quat2euler(quat) + roll = euler[..., 0] + pitch = euler[..., 1] + yaw = euler[..., 2] + + return torch.stack([roll, pitch, yaw], dim=-1) + + +@torch_compile +def pose2mat(pose: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor: + pos, orn = pose + + # Ensure pos and orn are the expected shape and dtype + pos = pos.to(dtype=torch.float32).reshape(-1, 3) + orn = orn.to(dtype=torch.float32).reshape(-1, 4) + + batch_size = pos.shape[0] + homo_pose_mat = torch.eye(4, dtype=torch.float32).unsqueeze(0).repeat(batch_size, 1, 1) + + homo_pose_mat[:, :3, :3] = quat2mat(orn) + homo_pose_mat[:, :3, 3] = pos + + homo_pose_mat = homo_pose_mat.squeeze(0) + + return homo_pose_mat + + +@torch_compile +def quat2axisangle(quat): + """ + Converts quaternion to axis-angle format. + Returns a unit vector direction scaled by its angle in radians. + Args: + quat (tensor): (..., 4) tensor where the final dim is (x,y,z,w) quaternion + Returns: + tensor: (..., 3) axis-angle exponential coordinates + """ + # reshape quaternion + quat_shape = quat.shape[:-1] # ignore last dim + quat = quat.reshape(-1, 4) + # clip quaternion + quat[:, 3] = torch.clip(quat[:, 3], -1.0, 1.0) + # Calculate denominator + den = torch.sqrt(1.0 - quat[:, 3] * quat[:, 3]) + # Map this into a mask + + # Create return array + ret = torch.zeros_like(quat)[:, :3] + idx = torch.nonzero(den).reshape(-1) + ret[idx, :] = (quat[idx, :3] * 2.0 * torch.acos(quat[idx, 3]).unsqueeze(-1)) / den[idx].unsqueeze(-1) + + # Reshape and return output + ret = ret.reshape( + list(quat_shape) + + [ + 3, + ] + ) + return ret + + +@torch_compile +def axisangle2quat(vec, eps=1e-6): + """ + Converts scaled axis-angle to quat. + Args: + vec (tensor): (..., 3) tensor where final dim is (ax,ay,az) axis-angle exponential coordinates + eps (float): Stability value below which small values will be mapped to 0 + + Returns: + tensor: (..., 4) tensor where final dim is (x,y,z,w) vec4 float quaternion + """ + # type: (Tensor, float) -> Tensor + # store input shape and reshape + input_shape = vec.shape[:-1] + vec = vec.reshape(-1, 3) + + # Grab angle + angle = torch.norm(vec, dim=-1, keepdim=True) + + # Create return array + quat = torch.zeros(torch.prod(torch.tensor(input_shape, dtype=torch.int)), 4, device=vec.device) + quat[:, 3] = 1.0 + + # Grab indexes where angle is not zero an convert the input to its quaternion form + idx = angle.reshape(-1) > eps # torch.nonzero(angle).reshape(-1) + quat[idx, :] = torch.cat( + [vec[idx, :] * torch.sin(angle[idx, :] / 2.0) / angle[idx, :], torch.cos(angle[idx, :] / 2.0)], dim=-1 + ) + + # Reshape and return output + quat = quat.reshape( + list(input_shape) + + [ + 4, + ] + ) + return quat + + +@torch_compile +def pose_in_A_to_pose_in_B(pose_A, pose_A_in_B): + """ + Converts a homogenous matrix corresponding to a point C in frame A + to a homogenous matrix corresponding to the same point C in frame B. + + Args: + pose_A (torch.tensor): 4x4 matrix corresponding to the pose of C in frame A + pose_A_in_B (torch.tensor): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + torch.tensor: 4x4 matrix corresponding to the pose of C in frame B + """ + + # pose of A in B takes a point in A and transforms it to a point in C. + + # pose of C in B = pose of A in B * pose of C in A + # take a point in C, transform it to A, then to B + # T_B^C = T_A^C * T_B^A + return torch.matmul(pose_A_in_B, pose_A) + + +@torch_compile +def pose_inv(pose_mat: torch.Tensor) -> torch.Tensor: + """ + Computes the inverse of a homogeneous matrix corresponding to the pose of some + frame B in frame A. The inverse is the pose of frame A in frame B. + + Args: + pose_mat (torch.tensor): 4x4 matrix for the pose to inverse + + Returns: + torch.tensor: 4x4 matrix for the inverse pose + """ + + # Note, the inverse of a pose matrix is the following + # [R t; 0 1]^-1 = [R.T -R.T*t; 0 1] + + # Intuitively, this makes sense. + # The original pose matrix translates by t, then rotates by R. + # We just invert the rotation by applying R-1 = R.T, and also translate back. + # Since we apply translation first before rotation, we need to translate by + # -t in the original frame, which is -R-1*t in the new frame, and then rotate back by + # R-1 to align the axis again. + + pose_mat = pose_mat.reshape(-1, 4, 4) + batch_size = pose_mat.shape[0] + pose_inv = torch.zeros((batch_size, 4, 4), device=pose_mat.device) + pose_inv[:, :3, :3] = pose_mat[:, :3, :3].transpose(1, 2) + pose_inv[:, :3, 3] = (-pose_inv[:, :3, :3] @ pose_mat[:, :3, 3].unsqueeze(-1)).squeeze(-1) + pose_inv[:, 3, 3] = 1.0 + pose_inv = pose_inv.squeeze(0) + return pose_inv + + +@torch_compile +def pose_transform(pos1, quat1, pos0, quat0): + """ + Conducts forward transform from pose (pos0, quat0) to pose (pos1, quat1): + + pose1 @ pose0, NOT pose0 @ pose1 + + Args: + pos1 (torch.Tensor): (x,y,z) position to transform + quat1 (torch.Tensor): (x,y,z,w) orientation to transform + pos0 (torch.Tensor): (x,y,z) initial position + quat0 (torch.Tensor): (x,y,z,w) initial orientation + + Returns: + 2-tuple: + - (torch.tensor) (x,y,z) position array in cartesian coordinates + - (torch.tensor) (x,y,z,w) orientation array in quaternion form + """ + # Get poses + mat0 = pose2mat((pos0, quat0)) + mat1 = pose2mat((pos1, quat1)) + + # Multiply and convert back to pos, quat + return mat2pose(mat1 @ mat0) + + +@torch_compile +def invert_pose_transform(pos, quat): + """ + Inverts a pose transform + + Args: + pos (torch.Tensor): (x,y,z) position to transform + quat (torch.Tensor): (x,y,z,w) orientation to transform + + Returns: + 2-tuple: + - (torch.tensor) (x,y,z) position array in cartesian coordinates + - (torch.tensor) (x,y,z,w) orientation array in quaternion form + """ + # Get pose + mat = pose2mat((pos, quat)) + + # Invert pose and convert back to pos, quat + return mat2pose(pose_inv(mat)) + + +@torch_compile +def relative_pose_transform(pos1, quat1, pos0, quat0): + """ + Computes relative forward transform from pose (pos0, quat0) to pose (pos1, quat1), i.e.: solves: + + pose1 = pose0 @ transform + + Args: + pos1 (torch.Tensor): (x,y,z) position to transform + quat1 (torch.Tensor): (x,y,z,w) orientation to transform + pos0 (torch.Tensor): (x,y,z) initial position + quat0 (torch.Tensor): (x,y,z,w) initial orientation + + Returns: + 2-tuple: + - (torch.tensor) (x,y,z) position array in cartesian coordinates + - (torch.tensor) (x,y,z,w) orientation array in quaternion form + """ + # Get poses + mat0 = pose2mat((pos0, quat0)) + mat1 = pose2mat((pos1, quat1)) + + # Invert pose0 and calculate transform + return mat2pose(pose_inv(mat0) @ mat1) + + +@torch_compile +def _skew_symmetric_translation(pos_A_in_B): + """ + Helper function to get a skew symmetric translation matrix for converting quantities + between frames. + + Args: + pos_A_in_B (torch.tensor): (x,y,z) position of A in frame B + + Returns: + torch.tensor: 3x3 skew symmetric translation matrix + """ + return torch.tensor( + [ + [0.0, -pos_A_in_B[2].item(), pos_A_in_B[1].item()], + [pos_A_in_B[2].item(), 0.0, -pos_A_in_B[0].item()], + [-pos_A_in_B[1].item(), pos_A_in_B[0].item(), 0.0], + ], + dtype=torch.float32, + device=pos_A_in_B.device, + ) + + +@torch_compile +def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B): + """ + Converts linear and angular velocity of a point in frame A to the equivalent in frame B. + + Args: + vel_A (torch.tensor): (vx,vy,vz) linear velocity in A + ang_vel_A (torch.tensor): (wx,wy,wz) angular velocity in A + pose_A_in_B (torch.tensor): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + 2-tuple: + + - (torch.tensor) (vx,vy,vz) linear velocities in frame B + - (torch.tensor) (wx,wy,wz) angular velocities in frame B + """ + pos_A_in_B = pose_A_in_B[:3, 3] + rot_A_in_B = pose_A_in_B[:3, :3] + skew_symm = _skew_symmetric_translation(pos_A_in_B) + vel_B = rot_A_in_B @ vel_A + skew_symm @ (rot_A_in_B @ ang_vel_A) + ang_vel_B = rot_A_in_B @ ang_vel_A + return vel_B, ang_vel_B + + +@torch_compile +def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B): + """ + Converts linear and rotational force at a point in frame A to the equivalent in frame B. + + Args: + force_A (torch.tensor): (fx,fy,fz) linear force in A + torque_A (torch.tensor): (tx,ty,tz) rotational force (moment) in A + pose_A_in_B (torch.tensor): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + 2-tuple: + + - (torch.tensor) (fx,fy,fz) linear forces in frame B + - (torch.tensor) (tx,ty,tz) moments in frame B + """ + pos_A_in_B = pose_A_in_B[:3, 3] + rot_A_in_B = pose_A_in_B[:3, :3] + skew_symm = _skew_symmetric_translation(pos_A_in_B) + force_B = rot_A_in_B.T @ force_A + torque_B = -(rot_A_in_B.T @ (skew_symm @ force_A)) + rot_A_in_B.T @ torque_A + return force_B, torque_B + + +@torch_compile +def rotation_matrix(angle: float, direction: torch.Tensor) -> torch.Tensor: + """ + Returns a 3x3 rotation matrix to rotate about the given axis. + + Args: + angle (float): Magnitude of rotation in radians + direction (torch.Tensor): (ax,ay,az) axis about which to rotate + + Returns: + torch.Tensor: 3x3 rotation matrix + """ + sina = torch.sin(torch.tensor(angle, dtype=torch.float32)) + cosa = torch.cos(torch.tensor(angle, dtype=torch.float32)) + + direction = direction / torch.norm(direction) # Normalize direction vector + + # Create rotation matrix + R = torch.eye(3, dtype=torch.float32, device=direction.device) + R *= cosa + R += torch.outer(direction, direction) * (1.0 - cosa) + direction *= sina + + # Create the skew-symmetric matrix + skew_matrix = torch.zeros(3, 3, dtype=torch.float32, device=direction.device) + skew_matrix[0, 1] = -direction[2] + skew_matrix[0, 2] = direction[1] + skew_matrix[1, 0] = direction[2] + skew_matrix[1, 2] = -direction[0] + skew_matrix[2, 0] = -direction[1] + skew_matrix[2, 1] = direction[0] + + R += skew_matrix + + return R + + +@torch_compile +def transformation_matrix(angle: float, direction: torch.Tensor, point: Optional[torch.Tensor] = None) -> torch.Tensor: + """ + Returns a 4x4 homogeneous transformation matrix to rotate about axis defined by point and direction. + Args: + angle (float): Magnitude of rotation in radians + direction (torch.Tensor): (ax,ay,az) axis about which to rotate + point (Optional[torch.Tensor]): If specified, is the (x,y,z) point about which the rotation will occur + Returns: + torch.Tensor: 4x4 homogeneous transformation matrix + """ + R = rotation_matrix(angle, direction) + + M = torch.eye(4, dtype=torch.float32, device=direction.device) + M[:3, :3] = R + + if point is not None: + # Rotation not about origin + point = point.to(dtype=torch.float32) + M[:3, 3] = point - R @ point + return M + + +@torch_compile +def clip_translation(dpos, limit): + """ + Limits a translation (delta position) to a specified limit + + Scales down the norm of the dpos to 'limit' if norm(dpos) > limit, else returns immediately + + Args: + dpos (n-array): n-dim Translation being clipped (e,g.: (x, y, z)) -- numpy array + limit (float): Value to limit translation by -- magnitude (scalar, in same units as input) + + Returns: + 2-tuple: + + - (torch.tensor) Clipped translation (same dimension as inputs) + - (bool) whether the value was clipped or not + """ + input_norm = torch.norm(dpos) + return (dpos * limit / input_norm, True) if input_norm > limit else (dpos, False) + + +@torch_compile +def clip_rotation(quat, limit): + """ + Limits a (delta) rotation to a specified limit + + Converts rotation to axis-angle, clips, then re-converts back into quaternion + + Args: + quat (torch.tensor): (x,y,z,w) rotation being clipped + limit (float): Value to limit rotation by -- magnitude (scalar, in radians) + + Returns: + 2-tuple: + + - (torch.tensor) Clipped rotation quaternion (x, y, z, w) + - (bool) whether the value was clipped or not + """ + clipped = False + + # First, normalize the quaternion + quat = quat / torch.norm(quat) + + den = math.sqrt(max(1 - quat[3] * quat[3], 0)) + if den == 0: + # This is a zero degree rotation, immediately return + return quat, clipped + else: + # This is all other cases + x = quat[0] / den + y = quat[1] / den + z = quat[2] / den + a = 2 * math.acos(quat[3]) + + # Clip rotation if necessary and return clipped quat + if abs(a) > limit: + a = limit * torch.sign(a) / 2 + sa = math.sin(a) + ca = math.cos(a) + quat = torch.tensor([x * sa, y * sa, z * sa, ca]) + clipped = True + + return quat, clipped + + +@torch_compile +def make_pose(translation, rotation): + """ + Makes a homogeneous pose matrix from a translation vector and a rotation matrix. + + Args: + translation (torch.tensor): (x,y,z) translation value + rotation (torch.tensor): a 3x3 matrix representing rotation + + Returns: + pose (torch.tensor): a 4x4 homogeneous matrix + """ + pose = torch.zeros((4, 4)) + pose[:3, :3] = rotation + pose[:3, 3] = translation + pose[3, 3] = 1.0 + return pose + + +@torch_compile +def get_orientation_error(desired, current): + """ + This function calculates a 3-dimensional orientation error vector, where inputs are quaternions + + Args: + desired (tensor): (..., 4) where final dim is (x,y,z,w) quaternion + current (tensor): (..., 4) where final dim is (x,y,z,w) quaternion + Returns: + tensor: (..., 3) where final dim is (ax, ay, az) axis-angle representing orientation error + """ + # convert input shapes + input_shape = desired.shape[:-1] + desired = desired.reshape(-1, 4) + current = current.reshape(-1, 4) + + cc = quat_conjugate(current) + q_r = quat_multiply(desired, cc) + return (q_r[:, 0:3] * torch.sign(q_r[:, 3]).unsqueeze(-1)).reshape(list(input_shape) + [3]) + + +@torch_compile +def get_orientation_diff_in_radian(orn0: torch.Tensor, orn1: torch.Tensor) -> torch.Tensor: + """ + Returns the difference between two quaternion orientations in radians. + + Args: + orn0 (torch.Tensor): (x, y, z, w) quaternion + orn1 (torch.Tensor): (x, y, z, w) quaternion + + Returns: + orn_diff (torch.Tensor): orientation difference in radians + """ + # Compute the difference quaternion + diff_quat = quat_distance(orn0, orn1) + + # Convert to axis-angle representation + axis_angle = quat2axisangle(diff_quat) + + # The magnitude of the axis-angle vector is the rotation angle + return torch.norm(axis_angle) + + +@torch_compile +def get_pose_error(target_pose, current_pose): + """ + Computes the error corresponding to target pose - current pose as a 6-dim vector. + The first 3 components correspond to translational error while the last 3 components + correspond to the rotational error. + + Args: + target_pose (torch.tensor): a 4x4 homogenous matrix for the target pose + current_pose (torch.tensor): a 4x4 homogenous matrix for the current pose + + Returns: + torch.tensor: 6-dim pose error. + """ + error = torch.zeros(6) + + # compute translational error + target_pos = target_pose[:3, 3] + current_pos = current_pose[:3, 3] + pos_err = target_pos - current_pos + + # compute rotational error + r1 = current_pose[:3, 0] + r2 = current_pose[:3, 1] + r3 = current_pose[:3, 2] + r1d = target_pose[:3, 0] + r2d = target_pose[:3, 1] + r3d = target_pose[:3, 2] + rot_err = 0.5 * (torch.linalg.cross(r1, r1d) + torch.linalg.cross(r2, r2d) + torch.linalg.cross(r3, r3d)) + + error[:3] = pos_err + error[3:] = rot_err + return error + + +@torch_compile +def matrix_inverse(matrix): + """ + Helper function to have an efficient matrix inversion function. + + Args: + matrix (torch.tensor): 2d-array representing a matrix + + Returns: + torch.tensor: 2d-array representing the matrix inverse + """ + return torch.linalg.inv_ex(matrix).inverse + + +@torch_compile +def vecs2axisangle(vec0, vec1): + """ + Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into an axis-angle representation of the angle + + Args: + vec0 (torch.tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized + vec1 (torch.tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized + """ + # Normalize vectors + vec0 = normalize(vec0, dim=-1, eps=1e-10) + vec1 = normalize(vec1, dim=-1, eps=1e-10) + + # Get cross product for direction of angle, and multiply by arcos of the dot product which is the angle + return torch.linalg.cross(vec0, vec1) * torch.arccos((vec0 * vec1).sum(-1, keepdim=True)) + + +@torch_compile +def vecs2quat(vec0: torch.Tensor, vec1: torch.Tensor, normalized: bool = False) -> torch.Tensor: + """ + Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into a quaternion representation of the angle + Args: + vec0 (torch.Tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized + vec1 (torch.Tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized + normalized (bool): If True, @vec0 and @vec1 are assumed to already be normalized and we will skip the + normalization step (more efficient) + Returns: + torch.Tensor: (..., 4) Normalized quaternion representing the rotation from vec0 to vec1 + """ + # Normalize vectors if requested + if not normalized: + vec0 = normalize(vec0, dim=-1, eps=1e-10) + vec1 = normalize(vec1, dim=-1, eps=1e-10) + + # Half-way Quaternion Solution -- see https://stackoverflow.com/a/11741520 + cos_theta = torch.sum(vec0 * vec1, dim=-1, keepdim=True) + + # Create a tensor for the case where cos_theta == -1 + batch_shape = vec0.shape[:-1] + fallback = torch.zeros(batch_shape + (4,), device=vec0.device, dtype=vec0.dtype) + fallback[..., 0] = 1.0 + + # Compute the quaternion + quat_unnormalized = torch.where( + cos_theta == -1, + fallback, + torch.cat([torch.linalg.cross(vec0, vec1), 1 + cos_theta], dim=-1), + ) + + return quat_unnormalized / torch.norm(quat_unnormalized, dim=-1, keepdim=True) + + +# Ref: https://github.com/scipy/scipy/blob/9974222eb58ec3eafe5d12f25ee960f3170c277a/scipy/spatial/transform/_rotation.pyx#L3249 +@torch_compile +def align_vector_sets(vec_set1: torch.Tensor, vec_set2: torch.Tensor) -> torch.Tensor: + """ + Computes a single quaternion representing the rotation that best aligns vec_set1 to vec_set2. + + Args: + vec_set1 (torch.Tensor): (N, 3) tensor of N 3D vectors + vec_set2 (torch.Tensor): (N, 3) tensor of N 3D vectors + + Returns: + torch.Tensor: (4,) Normalized quaternion representing the overall rotation + """ + B = torch.einsum("ji,jk->ik", vec_set1, vec_set2) + u, s, vh = torch.linalg.svd(B) + + # Correct improper rotation if necessary (as in Kabsch algorithm) + if torch.linalg.det(u @ vh) < 0: + s[-1] = -s[-1] + u[:, -1] = -u[:, -1] + + C = u @ vh + + # if s[1] + s[2] < 1e-16 * s[0]: + # warnings.warn("Optimal rotation is not uniquely or poorly defined " + # "for the given sets of vectors.") + + return mat2quat(C) + + +@torch_compile +def l2_distance(v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor: + """Returns the L2 distance between vector v1 and v2.""" + return torch.norm(v1 - v2) + + +@torch_compile +def cartesian_to_polar(x, y): + """Convert cartesian coordinate to polar coordinate""" + rho = torch.sqrt(x**2 + y**2) + phi = torch.arctan2(y, x) + return rho, phi + + +def deg2rad(deg): + return deg * math.pi / 180.0 + + +def rad2deg(rad): + return rad * 180.0 / math.pi + + +@torch_compile +def check_quat_right_angle(quat: torch.Tensor, atol: float = 5e-2) -> torch.Tensor: + """ + Check by making sure the quaternion is some permutation of +/- (1, 0, 0, 0), + +/- (0.707, 0.707, 0, 0), or +/- (0.5, 0.5, 0.5, 0.5) + Because orientations are all normalized (same L2-norm), every orientation should have a unique L1-norm + So we check the L1-norm of the absolute value of the orientation as a proxy for verifying these values + + Args: + quat (torch.Tensor): (x,y,z,w) quaternion orientation to check + atol (float): Absolute tolerance permitted + + Returns: + torch.Tensor: Boolean tensor indicating whether the quaternion is a right angle or not + """ + l1_norm = torch.abs(quat).sum(dim=-1) + reference_norms = torch.tensor([1.0, 1.414, 2.0], device=quat.device, dtype=quat.dtype) + return torch.any(torch.abs(l1_norm.unsqueeze(-1) - reference_norms) < atol, dim=-1) + + +@torch_compile +def z_angle_from_quat(quat): + """Get the angle around the Z axis produced by the quaternion.""" + rotated_X_axis = quat_apply(quat, torch.tensor([1, 0, 0], dtype=torch.float32)) + return torch.arctan2(rotated_X_axis[1], rotated_X_axis[0]) + + +@torch_compile +def integer_spiral_coordinates(n: int) -> Tuple[int, int]: + """A function to map integers to 2D coordinates in a spiral pattern around the origin.""" + # Map integers from Z to Z^2 in a spiral pattern around the origin. + # Sources: + # https://www.reddit.com/r/askmath/comments/18vqorf/find_the_nth_coordinate_of_a_square_spiral/ + # https://oeis.org/A174344 + m = math.floor(math.sqrt(n)) + x = ((-1) ** m) * ((n - m * (m + 1)) * (math.floor(2 * math.sqrt(n)) % 2) - math.ceil(m / 2)) + y = ((-1) ** (m + 1)) * ((n - m * (m + 1)) * (math.floor(2 * math.sqrt(n) + 1) % 2) + math.ceil(m / 2)) + return int(x), int(y) + + +@torch_compile +def transform_points(points: torch.Tensor, matrix: torch.Tensor, translate: bool = True) -> torch.Tensor: + """ + Returns points rotated by a homogeneous + transformation matrix. + If points are (n, 2) matrix must be (3, 3) + If points are (n, 3) matrix must be (4, 4) + + Arguments: + points : (n, dim) torch.Tensor + Points where `dim` is 2 or 3. + matrix : (3, 3) or (4, 4) torch.Tensor + Homogeneous rotation matrix. + translate : bool + Apply translation from matrix or not. + + Returns: + transformed : (n, dim) torch.Tensor + Transformed points. + """ + if len(points) == 0 or matrix is None: + return points.clone() + + count, dim = points.shape + # Check if the matrix is close to an identity matrix + identity = torch.eye(dim + 1, device=points.device) + if torch.abs(matrix - identity[: dim + 1, : dim + 1]).max() < 1e-8: + return points.clone().contiguous() + + if translate: + stack = torch.cat((points, torch.ones(count, 1, device=points.device)), dim=1) + return torch.mm(matrix, stack.t()).t()[:, :dim] + else: + return torch.mm(matrix[:dim, :dim], points.t()).t() + + +@torch_compile +def quaternions_close(q1: torch.Tensor, q2: torch.Tensor, atol: float = 1e-3) -> bool: + """ + Whether two quaternions represent the same rotation, + allowing for the possibility that one is the negative of the other. + + Arguments: + q1: torch.Tensor + First quaternion + q2: torch.Tensor + Second quaternion + atol: float + Absolute tolerance for comparison + + Returns: + bool + Whether the quaternions are close + """ + return torch.allclose(q1, q2, atol=atol) or torch.allclose(q1, -q2, atol=atol) + + +@torch_compile +def orientation_error(desired, current): + """ + This function calculates a 3-dimensional orientation error vector for use in the + impedance controller. It does this by computing the delta rotation between the + inputs and converting that rotation to exponential coordinates (axis-angle + representation, where the 3d vector is axis * angle). + See https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation for more information. + Optimized function to determine orientation error from matrices + + Args: + desired (tensor): (..., 3, 3) where final two dims are 2d array representing target orientation matrix + current (tensor): (..., 3, 3) where final two dims are 2d array representing current orientation matrix + Returns: + tensor: (..., 3) where final dim is (ax, ay, az) axis-angle representing orientation error + """ + # Compute batch size + batch_size = desired.numel() // 9 # Each 3x3 matrix has 9 elements + + desired_flat = desired.reshape(batch_size, 3, 3) + current_flat = current.reshape(batch_size, 3, 3) + + rc1, rc2, rc3 = current_flat[:, :, 0], current_flat[:, :, 1], current_flat[:, :, 2] + rd1, rd2, rd3 = desired_flat[:, :, 0], desired_flat[:, :, 1], desired_flat[:, :, 2] + + error = 0.5 * (torch.linalg.cross(rc1, rd1) + torch.linalg.cross(rc2, rd2) + torch.linalg.cross(rc3, rd3)) + + return error.reshape(desired.shape[:-2] + (3,)) + + +@torch_compile +def delta_rotation_matrix(omega, delta_t): + """ + Compute the delta rotation matrix given angular velocity and time elapsed. + + Arguments: + omega (torch.tensor): Angular velocity vector [omega_x, omega_y, omega_z]. + delta_t (float): Time elapsed. + + Returns: + torch.tensor: 3x3 Delta rotation matrix. + """ + # Magnitude of angular velocity (angular speed) + omega_magnitude = torch.linalg.norm(omega) + + # If angular speed is zero, return identity matrix + if omega_magnitude == 0: + return torch.eye(3) + + # Rotation angle + theta = omega_magnitude * delta_t + + # Normalized axis of rotation + axis = omega / omega_magnitude + + # Skew-symmetric matrix K + u_x, u_y, u_z = axis[0], axis[1], axis[2] + K = torch.zeros((3, 3)) + K[0, 1] = -u_z + K[0, 2] = u_y + K[1, 0] = u_z + K[1, 2] = -u_x + K[2, 0] = -u_y + K[2, 1] = u_x + + # Rodrigues' rotation formula + R = torch.eye(3) + torch.sin(theta) * K + (1 - torch.cos(theta)) * (K @ K) + + return R + + +@torch_compile +def mat2euler_intrinsic(rmat): + """ + Converts given rotation matrix to intrinsic euler angles in radian. + + Parameters: + rmat (torch.tensor): 3x3 rotation matrix + + Returns: + torch.array: (r,p,y) converted intrinsic euler angles in radian vec3 float + """ + # Check for gimbal lock (pitch = +-90 degrees) + assert torch.allclose(rmat.det(), torch.tensor(1.0)), "Rotation matrix must not be scaled" + if abs(rmat[0, 2]) != 1: + # General case + pitch = torch.arcsin(rmat[0, 2]) + roll = torch.arctan2(-rmat[1, 2], rmat[2, 2]) + yaw = torch.arctan2(-rmat[0, 1], rmat[0, 0]) + else: + # Gimbal lock case + pitch = torch.tensor(math.pi / 2 if rmat[0, 2] == 1 else -math.pi / 2) + roll = torch.arctan2(rmat[1, 0], rmat[1, 1]) + yaw = torch.tensor(0.0) # Can set yaw to 0 in gimbal lock + + return torch.stack([roll, pitch, yaw]) + + +@torch_compile +def euler_intrinsic2mat(euler): + """ + Converts intrinsic euler angles into rotation matrix form + + Parameters: + euler (torch.tensor): (r,p,y) intrinsic euler angles in radian vec3 float + + Returns: + torch.tensor: 3x3 rotation matrix + """ + roll, pitch, yaw = euler[0], euler[1], euler[2] + + # Rotation matrix around X-axis + euler_x = torch.zeros(3) + euler_x[0] = roll + Rx = euler2mat(euler_x) + + # Rotation matrix around Y-axis + euler_y = torch.zeros(3) + euler_y[1] = pitch + Ry = euler2mat(euler_y) + + # Rotation matrix around Z-axis + euler_z = torch.zeros(3) + euler_z[2] = yaw + Rz = euler2mat(euler_z) + + # Combine the rotation matrices + # Intrinsic x-y-z is the same as extrinsic z-y-x + # Multiply Rz first, then Ry, then Rx + return Rx @ Ry @ Rz diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils_np.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils_np.py new file mode 100644 index 0000000000000000000000000000000000000000..27b018aeebea4e8e9a529ded2e951f2faacaa4b9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils_np.py @@ -0,0 +1,1442 @@ +""" +Utility functions of matrix and vector transformations. + +NOTE: This file has a 1-to-1 correspondence to transform_utils.py. By default, we use scipy for most transform-related + operations, but we optionally implement numba versions for functions that are often called in "batch" mode + +NOTE: convention for quaternions is (x, y, z, w) +""" + +import math + +import numpy as np +from numba import jit, prange +from scipy.spatial.transform import Rotation as R + +PI = np.pi +EPS = np.finfo(float).eps * 4.0 + +# axis sequences for Euler angles +_NEXT_AXIS = [1, 2, 0, 1] + +# map axes strings to/from tuples of inner axis, parity, repetition, frame +_AXES2TUPLE = { + "sxyz": (0, 0, 0, 0), + "sxyx": (0, 0, 1, 0), + "sxzy": (0, 1, 0, 0), + "sxzx": (0, 1, 1, 0), + "syzx": (1, 0, 0, 0), + "syzy": (1, 0, 1, 0), + "syxz": (1, 1, 0, 0), + "syxy": (1, 1, 1, 0), + "szxy": (2, 0, 0, 0), + "szxz": (2, 0, 1, 0), + "szyx": (2, 1, 0, 0), + "szyz": (2, 1, 1, 0), + "rzyx": (0, 0, 0, 1), + "rxyx": (0, 0, 1, 1), + "ryzx": (0, 1, 0, 1), + "rxzx": (0, 1, 1, 1), + "rxzy": (1, 0, 0, 1), + "ryzy": (1, 0, 1, 1), + "rzxy": (1, 1, 0, 1), + "ryxy": (1, 1, 1, 1), + "ryxz": (2, 0, 0, 1), + "rzxz": (2, 0, 1, 1), + "rxyz": (2, 1, 0, 1), + "rzyz": (2, 1, 1, 1), +} + +_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items()) + + +def copysign(a, b): + a = np.array(a).repeat(b.shape[0]) + return np.abs(a) * np.sign(b) + + +def anorm(x, axis=None, keepdims=False): + """Compute L2 norms alogn specified axes.""" + return np.linalg.norm(x, axis=axis, keepdims=keepdims) + + +def normalize(v, axis=None, eps=1e-10): + """L2 Normalize along specified axes.""" + norm = anorm(v, axis=axis, keepdims=True) + return v / np.where(norm < eps, eps, norm) + + +def dot(v1, v2, dim=-1, keepdim=False): + return np.sum(v1 * v2, axis=dim, keepdims=keepdim) + + +def unit_vector(data, axis=None, out=None): + """ + Returns ndarray normalized by length, i.e. eucledian norm, along axis. + + E.g.: + >>> v0 = numpy.random.random(3) + >>> v1 = unit_vector(v0) + >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) + True + + >>> v0 = numpy.random.rand(5, 4, 3) + >>> v1 = unit_vector(v0, axis=-1) + >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0 * v0, axis=2)), 2) + >>> numpy.allclose(v1, v2) + True + + >>> v1 = unit_vector(v0, axis=1) + >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0 * v0, axis=1)), 1) + >>> numpy.allclose(v1, v2) + True + + >>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float32) + >>> unit_vector(v0, axis=1, out=v1) + >>> numpy.allclose(v1, v2) + True + + >>> list(unit_vector([])) + [] + + >>> list(unit_vector([1.0])) + [1.0] + + Args: + data (np.array): data to normalize + axis (None or int): If specified, determines specific axis along data to normalize + out (None or np.array): If specified, will store computation in this variable + + Returns: + None or np.array: If @out is not specified, will return normalized vector. Otherwise, stores the output in @out + """ + if out is None: + data = np.array(data, dtype=np.float32, copy=True) + if data.ndim == 1: + data /= math.sqrt(np.dot(data, data)) + return data + else: + if out is not data: + out[:] = np.array(data, copy=False) + data = out + length = np.atleast_1d(np.sum(data * data, axis)) + np.sqrt(length, length) + if axis is not None: + length = np.expand_dims(length, axis) + data /= length + if out is None: + return data + + +def quat_apply(quat, vec): + """ + Apply a quaternion rotation to a vector (equivalent to R.from_quat(x).apply(y)) + Args: + quat (np.array): (4,) or (N, 4) or (N, 1, 4) quaternion in (x, y, z, w) format + vec (np.array): (3,) or (M, 3) or (1, M, 3) vector to rotate + + Returns: + np.array: (M, 3) or (N, M, 3) rotated vector + """ + return R.from_quat(quat).apply(vec) + + +def convert_quat(q, to="xyzw"): + """ + Converts quaternion from one convention to another. + The convention to convert TO is specified as an optional argument. + If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa. + + Args: + q (np.array): a 4-dim array corresponding to a quaternion + to (str): either 'xyzw' or 'wxyz', determining which convention to convert to. + """ + if to == "xyzw": + return q[[1, 2, 3, 0]] + if to == "wxyz": + return q[[3, 0, 1, 2]] + raise Exception("convert_quat: choose a valid `to` argument (xyzw or wxyz)") + + +def quat_multiply(quaternion1, quaternion0): + if quaternion1.dtype != np.float32: + quaternion1 = quaternion1.astype(np.float32) + if quaternion0.dtype != np.float32: + quaternion0 = quaternion0.astype(np.float32) + return _quat_multiply(quaternion1, quaternion0) + + +@jit(nopython=True, cache=True) +def _quat_multiply(quaternion1, quaternion0): + """ + Return multiplication of two quaternions (q1 * q0). + + E.g.: + >>> q = quat_multiply([1, -2, 3, 4], [-5, 6, 7, 8]) + >>> np.allclose(q, [-44, -14, 48, 28]) + True + + Args: + quaternion1 (np.array): (x,y,z,w) quaternion + quaternion0 (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) multiplied quaternion + """ + x0, y0, z0, w0 = np.split(quaternion0, 4, axis=-1) + x1, y1, z1, w1 = np.split(quaternion1, 4, axis=-1) + return np.concatenate( + ( + x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0, + -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0, + x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0, + -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0, + ), + axis=-1, + ) + + +def quat_conjugate(quaternion): + """ + Return conjugate of quaternion. + + E.g.: + >>> q0 = random_quaternion() + >>> q1 = quat_conjugate(q0) + >>> q1[3] == q0[3] and all(q1[:3] == -q0[:3]) + True + + Args: + quaternion (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) quaternion conjugate + """ + n_dims = len(quaternion.shape) + # Reshape to explicitly handle batched calls + return quaternion * np.array([-1.0, -1.0, -1.0, 1.0], dtype=np.float32).reshape([1] * (n_dims - 1) + [4]) + + +def quat_inverse(quaternion): + """ + Return inverse of quaternion. + + E.g.: + >>> q0 = random_quaternion() + >>> q1 = quat_inverse(q0) + >>> np.allclose(quat_multiply(q0, q1), [0, 0, 0, 1]) + True + + Args: + quaternion (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) quaternion inverse + """ + return quat_conjugate(quaternion) / np.sum(quaternion * quaternion, axis=-1, keepdims=True) + + +def quat_distance(quaternion1, quaternion0): + """ + Returns distance between two quaternions, such that distance * quaternion0 = quaternion1 + Always returns the shorter rotation path. + + Args: + quaternion1 (np.array): (x,y,z,w) quaternion or (..., 4) batched quaternions + quaternion0 (np.array): (x,y,z,w) quaternion or (..., 4) batched quaternions + + Returns: + np.array: (x,y,z,w) quaternion distance or (..., 4) batched quaternion distances + """ + # Compute dot product along the last axis (quaternion components) + d = np.sum(quaternion0 * quaternion1, axis=-1, keepdims=True) + # If dot product is negative, negate one quaternion to get shorter path + quaternion1 = np.where(d < 0.0, -quaternion1, quaternion1) + + return quat_multiply(quaternion1, quat_inverse(quaternion0)) + + +def quat_slerp(quat0, quat1, fraction, shortestpath=True): + """ + Return spherical linear interpolation between two quaternions. + + E.g.: + >>> q0 = random_quat() + >>> q1 = random_quat() + >>> q = quat_slerp(q0, q1, 0.0) + >>> np.allclose(q, q0) + True + + >>> q = quat_slerp(q0, q1, 1.0) + >>> np.allclose(q, q1) + True + + >>> q = quat_slerp(q0, q1, 0.5) + >>> angle = math.acos(np.dot(q0, q)) + >>> np.allclose(2.0, math.acos(np.dot(q0, q1)) / angle) or \ + np.allclose(2.0, math.acos(-np.dot(q0, q1)) / angle) + True + + Args: + quat0 (np.array): (x,y,z,w) quaternion startpoint + quat1 (np.array): (x,y,z,w) quaternion endpoint + fraction (float): fraction of interpolation to calculate + shortestpath (bool): If True, will calculate the shortest path + + Returns: + np.array: (x,y,z,w) quaternion distance + """ + q0 = unit_vector(quat0[:4]) + q1 = unit_vector(quat1[:4]) + if fraction == 0.0: + return q0 + elif fraction == 1.0: + return q1 + d = np.dot(q0, q1) + if abs(abs(d) - 1.0) < EPS: + return q0 + if shortestpath and d < 0.0: + # invert rotation + d = -d + q1 *= -1.0 + angle = math.acos(np.clip(d, -1, 1)) + if abs(angle) < EPS: + return q0 + isin = 1.0 / math.sin(angle) + q0 *= math.sin((1.0 - fraction) * angle) * isin + q1 *= math.sin(fraction * angle) * isin + q0 += q1 + return q0 + + +@jit(nopython=True, cache=True) +def random_quaternion(num_quaternions=1): + """ + Generate random rotation quaternions, uniformly distributed over SO(3). + + Arguments: + num_quaternions (int): number of quaternions to generate (default: 1) + + Returns: + np.array: A tensor of shape (num_quaternions, 4) containing random unit quaternions. + """ + # Generate four random numbers between 0 and 1 + rand = np.random.rand(num_quaternions, 4) + + # Use the formula from Ken Shoemake's "Uniform Random Rotations" + r1 = np.sqrt(1.0 - rand[:, 0]) + r2 = np.sqrt(rand[:, 0]) + t1 = 2 * np.pi * rand[:, 1] + t2 = 2 * np.pi * rand[:, 2] + + quaternions = np.stack((r1 * np.sin(t1), r1 * np.cos(t1), r2 * np.sin(t2), r2 * np.cos(t2)), axis=1) + + return quaternions + + +def random_axis_angle(angle_limit=None, random_state=None): + """ + Samples an axis-angle rotation by first sampling a random axis + and then sampling an angle. If @angle_limit is provided, the size + of the rotation angle is constrained. + + If @random_state is provided (instance of np.random.RandomState), it + will be used to generate random numbers. + + Args: + angle_limit (None or float): If set, determines magnitude limit of angles to generate + random_state (None or RandomState): RNG to use if specified + + Raises: + AssertionError: [Invalid RNG] + """ + if angle_limit is None: + angle_limit = 2.0 * np.pi + + if random_state is not None: + assert isinstance(random_state, np.random.RandomState) + npr = random_state + else: + npr = np.random + + # sample random axis using a normalized sample from spherical Gaussian. + # see (http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/) + # for why it works. + random_axis = npr.randn(3) + random_axis /= np.linalg.norm(random_axis) + random_angle = npr.uniform(low=0.0, high=angle_limit) + return random_axis, random_angle + + +def quat2mat(quaternion): + if quaternion.dtype != np.float32: + quaternion = quaternion.astype(np.float32) + return _quat2mat(quaternion) + + +@jit(nopython=True, cache=True) +def _quat2mat(quaternion): + """ + Convert quaternions into rotation matrices. + + Args: + quaternion (torch.Tensor): A tensor of shape (..., 4) representing batches of quaternions (x, y, z, w). + + Returns: + torch.Tensor: A tensor of shape (..., 3, 3) representing batches of rotation matrices. + """ + # broadcast array is necessary to use numba parallel mode + q1, q2 = np.broadcast_arrays(quaternion[..., np.newaxis], quaternion[..., np.newaxis, :]) + outer = q1 * q2 + + # Extract the necessary components + xx = outer[..., 0, 0] + yy = outer[..., 1, 1] + zz = outer[..., 2, 2] + xy = outer[..., 0, 1] + xz = outer[..., 0, 2] + yz = outer[..., 1, 2] + xw = outer[..., 0, 3] + yw = outer[..., 1, 3] + zw = outer[..., 2, 3] + + rotation_matrix = np.empty(quaternion.shape[:-1] + (3, 3), dtype=np.float32) + + rotation_matrix[..., 0, 0] = 1 - 2 * (yy + zz) + rotation_matrix[..., 0, 1] = 2 * (xy - zw) + rotation_matrix[..., 0, 2] = 2 * (xz + yw) + + rotation_matrix[..., 1, 0] = 2 * (xy + zw) + rotation_matrix[..., 1, 1] = 1 - 2 * (xx + zz) + rotation_matrix[..., 1, 2] = 2 * (yz - xw) + + rotation_matrix[..., 2, 0] = 2 * (xz - yw) + rotation_matrix[..., 2, 1] = 2 * (yz + xw) + rotation_matrix[..., 2, 2] = 1 - 2 * (xx + yy) + + return rotation_matrix + + +def mat2quat(rmat): + """ + Converts given rotation matrix to quaternion. + + Args: + rmat (np.array): (..., 3, 3) rotation matrix + + Returns: + np.array: (..., 4) (x,y,z,w) float quaternion angles + """ + return R.from_matrix(rmat).as_quat() + + +@jit(nopython=True, fastmath=True, cache=True) +def _norm_2d_final_dim(mat): + n_elements = mat.shape[0] + out = np.zeros(n_elements, dtype=np.float32) + for i in prange(n_elements): + vec = mat[i] + out[i] = np.sqrt(np.sum(vec * vec)) + return out + + +@jit(nopython=True, cache=True) +def mat2quat_batch(rmat): + """ + Converts given rotation matrix to quaternion. + Args: + rmat (torch.Tensor): (3, 3) or (..., 3, 3) rotation matrix + Returns: + torch.Tensor: (4,) or (..., 4) (x,y,z,w) float quaternion angles + """ + batch_shape = rmat.shape[:-2] + mat_flat = rmat.reshape(-1, 3, 3) + + m00, m01, m02 = mat_flat[:, 0, 0], mat_flat[:, 0, 1], mat_flat[:, 0, 2] + m10, m11, m12 = mat_flat[:, 1, 0], mat_flat[:, 1, 1], mat_flat[:, 1, 2] + m20, m21, m22 = mat_flat[:, 2, 0], mat_flat[:, 2, 1], mat_flat[:, 2, 2] + + trace = m00 + m11 + m22 + + trace_positive = trace > 0 + cond1 = (m00 > m11) & (m00 > m22) & ~trace_positive + cond2 = (m11 > m22) & ~(trace_positive | cond1) + cond3 = ~(trace_positive | cond1 | cond2) + + # Trace positive condition + sq = np.where(trace_positive, np.sqrt(trace + 1.0) * 2.0, np.zeros_like(trace)) + qw = np.where(trace_positive, 0.25 * sq, np.zeros_like(trace)) + qx = np.where(trace_positive, (m21 - m12) / sq, np.zeros_like(trace)) + qy = np.where(trace_positive, (m02 - m20) / sq, np.zeros_like(trace)) + qz = np.where(trace_positive, (m10 - m01) / sq, np.zeros_like(trace)) + + # Condition 1 + sq = np.where(cond1, np.sqrt(1.0 + m00 - m11 - m22) * 2.0, sq) + qw = np.where(cond1, (m21 - m12) / sq, qw) + qx = np.where(cond1, 0.25 * sq, qx) + qy = np.where(cond1, (m01 + m10) / sq, qy) + qz = np.where(cond1, (m02 + m20) / sq, qz) + + # Condition 2 + sq = np.where(cond2, np.sqrt(1.0 + m11 - m00 - m22) * 2.0, sq) + qw = np.where(cond2, (m02 - m20) / sq, qw) + qx = np.where(cond2, (m01 + m10) / sq, qx) + qy = np.where(cond2, 0.25 * sq, qy) + qz = np.where(cond2, (m12 + m21) / sq, qz) + + # Condition 3 + sq = np.where(cond3, np.sqrt(1.0 + m22 - m00 - m11) * 2.0, sq) + qw = np.where(cond3, (m10 - m01) / sq, qw) + qx = np.where(cond3, (m02 + m20) / sq, qx) + qy = np.where(cond3, (m12 + m21) / sq, qy) + qz = np.where(cond3, 0.25 * sq, qz) + + quat = np.stack((qx, qy, qz, qw), axis=-1) + + # Normalize the quaternion + quat = quat / _norm_2d_final_dim(quat)[..., np.newaxis] + + # Reshape to match input batch shape + quat = quat.reshape(batch_shape + (4,)) + + return quat + + +def decompose_mat(hmat): + """Batched decompose_mat function - assumes input is already batched + + Args: + hmat (np.ndarray): (B, 4, 4) batch of homogeneous matrices + + Returns: + scale: (B, 3) scale factors + shear: (B, 3) shear factors + quat: (B, 4) quaternions + translate: (B, 3) translations + """ + batch_size = hmat.shape[0] + M = np.array(hmat, dtype=np.float32).transpose(0, 2, 1) # (B, 4, 4) transposed + + # Check M[3, 3] for all batch items + diag_vals = M[:, 3, 3] # (B,) + if np.any(np.abs(diag_vals) < EPS): + raise ValueError("Some M[3, 3] values are zero") + + M = M / diag_vals[:, np.newaxis, np.newaxis] # (B, 4, 4) + P = M.copy() + P[:, :, 3] = np.array([0.0, 0.0, 0.0, 1.0])[np.newaxis, :].repeat(batch_size, axis=0) + + det_P = np.linalg.det(P[:, :3, :3]) # (B,) + if np.any(np.abs(det_P) < EPS): + raise ValueError("Some matrices are singular and cannot be decomposed") + + if not np.allclose(M[:, :3, 3], 0.0): + raise ValueError("Some matrices have perspective components") + + scale = np.zeros((batch_size, 3)) + shear = np.zeros((batch_size, 3)) + + translate = M[:, 3, :3].copy() # (B, 3) + M[:, 3, :3] = 0.0 + + row = M[:, :3, :3].copy() # (B, 3, 3) + + # Scale and orthogonalize rows + scale[:, 0] = np.linalg.norm(row[:, 0], axis=-1) # (B,) + row[:, 0] = row[:, 0] / scale[:, 0, np.newaxis] # (B, 3) + + shear[:, 0] = np.sum(row[:, 0] * row[:, 1], axis=-1) # (B,) + row[:, 1] = row[:, 1] - row[:, 0] * shear[:, 0, np.newaxis] # (B, 3) + + scale[:, 1] = np.linalg.norm(row[:, 1], axis=-1) # (B,) + row[:, 1] = row[:, 1] / scale[:, 1, np.newaxis] # (B, 3) + shear[:, 0] = shear[:, 0] / scale[:, 1] + + shear[:, 1] = np.sum(row[:, 0] * row[:, 2], axis=-1) # (B,) + row[:, 2] = row[:, 2] - row[:, 0] * shear[:, 1, np.newaxis] # (B, 3) + + shear[:, 2] = np.sum(row[:, 1] * row[:, 2], axis=-1) # (B,) + row[:, 2] = row[:, 2] - row[:, 1] * shear[:, 2, np.newaxis] # (B, 3) + + scale[:, 2] = np.linalg.norm(row[:, 2], axis=-1) # (B,) + row[:, 2] = row[:, 2] / scale[:, 2, np.newaxis] # (B, 3) + shear[:, 1:] = shear[:, 1:] / scale[:, 2, np.newaxis] + + # Check orientation + cross_product = np.cross(row[:, 1], row[:, 2], axis=-1) # (B, 3) + dot_product = np.sum(row[:, 0] * cross_product, axis=-1) # (B,) + neg_mask = dot_product < 0 # (B,) + + scale = np.where(neg_mask[:, np.newaxis], -scale, scale) # (B, 3) + row = np.where(neg_mask[:, np.newaxis, np.newaxis], -row, row) # (B, 3, 3) + + # Convert to quaternions - assuming mat2quat can handle batched input + quat = mat2quat(row.transpose(0, 2, 1)) # (B, 4) + + return scale, shear, quat, translate + + +def mat2pose(hmat): + """ + Converts a homogeneous 4x4 matrix into pose. + + Args: + hmat (np.array): a 4x4 homogeneous matrix + + Returns: + 2-tuple: + - (np.array) (3,) position array in cartesian coordinates + - (np.array) (4,) orientation array in quaternion form + """ + # Add batch dimension, process, then squeeze + hmat_batched = hmat[np.newaxis, ...] # (1, 4, 4) + _, _, quat, translate = decompose_mat(hmat_batched) + return translate.squeeze(0), quat.squeeze(0) + + +def mat2pose_batched(hmat): + """ + Converts batched homogeneous 4x4 matrices into poses. + + Args: + hmat (np.array): (B, 4, 4) batch of homogeneous matrices + + Returns: + 2-tuple: + - (np.array) (B, 3) position arrays in cartesian coordinates + - (np.array) (B, 4) orientation arrays in quaternion form + """ + _, _, quat, translate = decompose_mat(hmat) + return translate, quat + + +def vec2quat(vec, up=(0, 0, 1.0)): + """ + Converts given 3d-direction vector @vec to quaternion orientation with respect to another direction vector @up + + Args: + vec (3-array): (x,y,z) direction vector (possible non-normalized) + up (3-array): (x,y,z) direction vector representing the canonical up direction (possible non-normalized) + """ + # See https://stackoverflow.com/questions/15873996/converting-a-direction-vector-to-a-quaternion-rotation + # Take cross product of @up and @vec to get @s_n, and then cross @vec and @s_n to get @u_n + # Then compose 3x3 rotation matrix and convert into quaternion + vec_n = vec / np.linalg.norm(vec) # x + up_n = up / np.linalg.norm(up) + s_n = np.cross(up_n, vec_n) # y + u_n = np.cross(vec_n, s_n) # z + return mat2quat(np.array([vec_n, s_n, u_n]).T) + + +def euler2quat(euler): + """ + Converts extrinsic euler angles into quaternion form + + Args: + euler (np.array): (r,p,y) angles + + Returns: + np.array: (x,y,z,w) float quaternion angles + + Raises: + AssertionError: [Invalid input shape] + """ + return R.from_euler("xyz", euler).as_quat() + + +def quat2euler(quat): + """ + Converts extrinsic euler angles into quaternion form + + Args: + quat (np.array): (x,y,z,w) float quaternion angles + + Returns: + np.array: (r,p,y) angles + + Raises: + AssertionError: [Invalid input shape] + """ + return R.from_quat(quat).as_euler("xyz") + + +def euler2mat(euler): + """ + Converts extrinsic euler angles into rotation matrix form + + Args: + euler (np.array): (r,p,y) angles + + Returns: + np.array: 3x3 rotation matrix + + Raises: + AssertionError: [Invalid input shape] + """ + + euler = np.asarray(euler, dtype=np.float64) + assert euler.shape[-1] == 3, "Invalid shaped euler {}".format(euler) + + return R.from_euler("xyz", euler).as_matrix() + + +def mat2euler(rmat): + """ + Converts given rotation matrix to extrinsic euler angles in radian. + + Args: + rmat (np.array): 3x3 rotation matrix + + Returns: + np.array: (r,p,y) converted extrinsic euler angles in radian vec3 float + """ + M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3] + return R.from_matrix(M).as_euler("xyz") + + +@jit(nopython=True, cache=True) +def pose2mat(pose): + """ + Converts pose to homogeneous matrix. + + Args: + pose (2-tuple): a (pos, orn) tuple where pos is vec3 float cartesian, and + orn is vec4 float quaternion. + + Returns: + np.array: 4x4 homogeneous matrix + """ + homo_pose_mat = np.zeros((4, 4), dtype=np.float32) + homo_pose_mat[:3, :3] = _quat2mat(pose[1]) + homo_pose_mat[:3, 3] = pose[0] + homo_pose_mat[3, 3] = 1.0 + return homo_pose_mat + + +def quat2axisangle(quat): + """ + Converts quaternion to axis-angle format. + Returns a unit vector direction scaled by its angle in radians. + + Args: + quat (np.array): (x,y,z,w) vec4 float angles + + Returns: + np.array: (ax,ay,az) axis-angle exponential coordinates + """ + return R.from_quat(quat).as_rotvec() + + +def axisangle2quat(vec): + """ + Converts scaled axis-angle to quat. + + Args: + vec (np.array): (ax,ay,az) axis-angle exponential coordinates + + Returns: + np.array: (x,y,z,w) vec4 float angles + """ + return R.from_rotvec(vec).as_quat() + + +def pose_in_A_to_pose_in_B(pose_A, pose_A_in_B): + """ + Converts a homogenous matrix corresponding to a point C in frame A + to a homogenous matrix corresponding to the same point C in frame B. + + Args: + pose_A (np.array): 4x4 matrix corresponding to the pose of C in frame A + pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + np.array: 4x4 matrix corresponding to the pose of C in frame B + """ + + # pose of A in B takes a point in A and transforms it to a point in C. + + # pose of C in B = pose of A in B * pose of C in A + # take a point in C, transform it to A, then to B + # T_B^C = T_A^C * T_B^A + return pose_A_in_B.dot(pose_A) + + +def pose_inv(pose_mat): + if pose_mat.dtype != np.float32: + pose_mat = pose_mat.astype(np.float32) + return _pose_inv(pose_mat) + + +@jit(nopython=True, cache=True) +def _pose_inv(pose_mat): + """ + Computes the inverse of a homogeneous matrix corresponding to the pose of some + frame B in frame A. The inverse is the pose of frame A in frame B. + + Args: + pose_mat (np.array): 4x4 matrix for the pose to inverse + + Returns: + np.array: 4x4 matrix for the inverse pose + """ + + # Note, the inverse of a pose matrix is the following + # [R t; 0 1]^-1 = [R.T -R.T*t; 0 1] + + # Intuitively, this makes sense. + # The original pose matrix translates by t, then rotates by R. + # We just invert the rotation by applying R-1 = R.T, and also translate back. + # Since we apply translation first before rotation, we need to translate by + # -t in the original frame, which is -R-1*t in the new frame, and then rotate back by + # R-1 to align the axis again. + + pose_inv = np.zeros((4, 4), dtype=np.float32) + pose_inv[:3, :3] = pose_mat[:3, :3].T + pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose_mat[:3, 3]) + pose_inv[3, 3] = 1.0 + return pose_inv + + +def pose_transform(pos1, quat1, pos0, quat0): + """ + Conducts forward transform from pose (pos0, quat0) to pose (pos1, quat1): + + pose1 @ pose0, NOT pose0 @ pose1 + + Args: + pos1 (np.ndarray): (x,y,z) position to transform + quat1 (np.ndarray): (x,y,z,w) orientation to transform + pos0 (np.ndarray): (x,y,z) initial position + quat0 (np.ndarray): (x,y,z,w) initial orientation + + Returns: + 2-tuple: + - (np.array) (x,y,z) position array in cartesian coordinates + - (np.array) (x,y,z,w) orientation array in quaternion form + """ + # Get poses + mat0 = pose2mat((pos0, quat0)) + mat1 = pose2mat((pos1, quat1)) + + # Multiply and convert back to pos, quat + return mat2pose(mat1 @ mat0) + + +def invert_pose_transform(pos, quat): + """ + Inverts a pose transform + + Args: + pos (np.ndarray): (x,y,z) position to transform + quat (np.ndarray): (x,y,z,w) orientation to transform + + Returns: + 2-tuple: + - (np.array) (x,y,z) position array in cartesian coordinates + - (np.array) (x,y,z,w) orientation array in quaternion form + """ + # Get pose + mat = pose2mat((pos, quat)) + + # Invert pose and convert back to pos, quat + return mat2pose(pose_inv(mat)) + + +def relative_pose_transform(pos1, quat1, pos0, quat0): + """ + Computes relative forward transform from pose (pos0, quat0) to pose (pos1, quat1), i.e.: solves: + + pose1 = pose0 @ transform + + Args: + pos1 (np.ndarray): (x,y,z) position to transform + quat1 (np.ndarray): (x,y,z,w) orientation to transform + pos0 (np.ndarray): (x,y,z) initial position + quat0 (np.ndarray): (x,y,z,w) initial orientation + + Returns: + 2-tuple: + - (np.array) (x,y,z) position array in cartesian coordinates + - (np.array) (x,y,z,w) orientation array in quaternion form + """ + # Get poses + mat0 = pose2mat((pos0, quat0)) + mat1 = pose2mat((pos1, quat1)) + + # Invert pose0 and calculate transform + return mat2pose(pose_inv(mat0) @ mat1) + + +def _skew_symmetric_translation(pos_A_in_B): + """ + Helper function to get a skew symmetric translation matrix for converting quantities + between frames. + + Args: + pos_A_in_B (np.array): (x,y,z) position of A in frame B + + Returns: + np.array: 3x3 skew symmetric translation matrix + """ + return np.array( + [ + 0.0, + -pos_A_in_B[2], + pos_A_in_B[1], + pos_A_in_B[2], + 0.0, + -pos_A_in_B[0], + -pos_A_in_B[1], + pos_A_in_B[0], + 0.0, + ] + ).reshape((3, 3)) + + +def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B): + """ + Converts linear and angular velocity of a point in frame A to the equivalent in frame B. + + Args: + vel_A (np.array): (vx,vy,vz) linear velocity in A + ang_vel_A (np.array): (wx,wy,wz) angular velocity in A + pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + 2-tuple: + + - (np.array) (vx,vy,vz) linear velocities in frame B + - (np.array) (wx,wy,wz) angular velocities in frame B + """ + pos_A_in_B = pose_A_in_B[:3, 3] + rot_A_in_B = pose_A_in_B[:3, :3] + skew_symm = _skew_symmetric_translation(pos_A_in_B) + vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A)) + ang_vel_B = rot_A_in_B.dot(ang_vel_A) + return vel_B, ang_vel_B + + +def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B): + """ + Converts linear and rotational force at a point in frame A to the equivalent in frame B. + + Args: + force_A (np.array): (fx,fy,fz) linear force in A + torque_A (np.array): (tx,ty,tz) rotational force (moment) in A + pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + 2-tuple: + + - (np.array) (fx,fy,fz) linear forces in frame B + - (np.array) (tx,ty,tz) moments in frame B + """ + pos_A_in_B = pose_A_in_B[:3, 3] + rot_A_in_B = pose_A_in_B[:3, :3] + skew_symm = _skew_symmetric_translation(pos_A_in_B) + force_B = rot_A_in_B.T.dot(force_A) + torque_B = -rot_A_in_B.T.dot(skew_symm.dot(force_A)) + rot_A_in_B.T.dot(torque_A) + return force_B, torque_B + + +def rotation_matrix(angle, direction, point=None): + """ + Returns matrix to rotate about axis defined by point and direction. + + E.g.: + >>> angle = (random.random() - 0.5) * (2 * math.pi) + >>> direc = numpy.random.random(3) - 0.5 + >>> point = numpy.random.random(3) - 0.5 + >>> R0 = rotation_matrix(angle, direc, point) + >>> R1 = rotation_matrix(angle - 2 * math.pi, direc, point) + >>> is_same_transform(R0, R1) + True + + >>> R0 = rotation_matrix(angle, direc, point) + >>> R1 = rotation_matrix(-angle, -direc, point) + >>> is_same_transform(R0, R1) + True + + >>> I = numpy.identity(4, numpy.float32) + >>> numpy.allclose(I, rotation_matrix(math.pi * 2, direc)) + True + + >>> numpy.allclose(2.0, numpy.trace(rotation_matrix(math.pi / 2, direc, point))) + True + + Args: + angle (float): Magnitude of rotation + direction (np.array): (ax,ay,az) axis about which to rotate + point (None or np.array): If specified, is the (x,y,z) point about which the rotation will occur + + Returns: + np.array: 4x4 homogeneous matrix that includes the desired rotation + """ + sina = math.sin(angle) + cosa = math.cos(angle) + direction = unit_vector(direction[:3]) + # rotation matrix around unit vector + R = np.array(((cosa, 0.0, 0.0), (0.0, cosa, 0.0), (0.0, 0.0, cosa)), dtype=np.float32) + R += np.outer(direction, direction) * (1.0 - cosa) + direction *= sina + R += np.array( + ( + (0.0, -direction[2], direction[1]), + (direction[2], 0.0, -direction[0]), + (-direction[1], direction[0], 0.0), + ), + dtype=np.float32, + ) + M = np.identity(4) + M[:3, :3] = R + if point is not None: + # rotation not around origin + point = np.array(point[:3], dtype=np.float32, copy=False) + M[:3, 3] = point - np.dot(R, point) + return M + + +def transformation_matrix(angle, direction, point=None): + """ + Returns a 4x4 homogeneous transformation matrix to rotate about axis defined by point and direction. + Args: + angle (float): Magnitude of rotation in radians + direction (np.array): (ax,ay,az) axis about which to rotate + point (bool): If specified, is the (x,y,z) point about which the rotation will occur + + Returns: + np.array: 4x4 homogeneous transformation matrix + """ + R = rotation_matrix(angle, direction) + + M = np.eye(4) + M[:3, :3] = R + + if point is not None: + # Rotation not about origin + M[:3, 3] = point - R @ point + return M + + +def clip_translation(dpos, limit): + """ + Limits a translation (delta position) to a specified limit + + Scales down the norm of the dpos to 'limit' if norm(dpos) > limit, else returns immediately + + Args: + dpos (n-array): n-dim Translation being clipped (e,g.: (x, y, z)) -- numpy array + limit (float): Value to limit translation by -- magnitude (scalar, in same units as input) + + Returns: + 2-tuple: + + - (np.array) Clipped translation (same dimension as inputs) + - (bool) whether the value was clipped or not + """ + input_norm = np.linalg.norm(dpos) + return (dpos * limit / input_norm, True) if input_norm > limit else (dpos, False) + + +def clip_rotation(quat, limit): + """ + Limits a (delta) rotation to a specified limit + + Converts rotation to axis-angle, clips, then re-converts back into quaternion + + Args: + quat (np.array): (x,y,z,w) rotation being clipped + limit (float): Value to limit rotation by -- magnitude (scalar, in radians) + + Returns: + 2-tuple: + + - (np.array) Clipped rotation quaternion (x, y, z, w) + - (bool) whether the value was clipped or not + """ + clipped = False + + # First, normalize the quaternion + quat = quat / np.linalg.norm(quat) + + den = np.sqrt(max(1 - quat[3] * quat[3], 0)) + if den == 0: + # This is a zero degree rotation, immediately return + return quat, clipped + else: + # This is all other cases + x = quat[0] / den + y = quat[1] / den + z = quat[2] / den + a = 2 * math.acos(quat[3]) + + # Clip rotation if necessary and return clipped quat + if abs(a) > limit: + a = limit * np.sign(a) / 2 + sa = math.sin(a) + ca = math.cos(a) + quat = np.array([x * sa, y * sa, z * sa, ca]) + clipped = True + + return quat, clipped + + +def make_pose(translation, rotation): + """ + Makes a homogeneous pose matrix from a translation vector and a rotation matrix. + + Args: + translation (np.array): (x,y,z) translation value + rotation (np.array): a 3x3 matrix representing rotation + + Returns: + pose (np.array): a 4x4 homogeneous matrix + """ + pose = np.zeros((4, 4)) + pose[:3, :3] = rotation + pose[:3, 3] = translation + pose[3, 3] = 1.0 + return pose + + +def get_orientation_error(target_orn, current_orn): + """ + Returns the difference between two quaternion orientations as a 3 DOF numpy array. + For use in an impedance controller / task-space PD controller. + + Args: + target_orn (np.array): (x, y, z, w) desired quaternion orientation + current_orn (np.array): (x, y, z, w) current quaternion orientation + + Returns: + orn_error (np.array): (ax,ay,az) current orientation error, corresponds to + (target_orn - current_orn) + """ + current_orn = np.array([current_orn[3], current_orn[0], current_orn[1], current_orn[2]]) + target_orn = np.array([target_orn[3], target_orn[0], target_orn[1], target_orn[2]]) + + pinv = np.zeros((3, 4)) + pinv[0, :] = [-current_orn[1], current_orn[0], -current_orn[3], current_orn[2]] + pinv[1, :] = [-current_orn[2], current_orn[3], current_orn[0], -current_orn[1]] + pinv[2, :] = [-current_orn[3], -current_orn[2], current_orn[1], current_orn[0]] + orn_error = 2.0 * pinv.dot(np.array(target_orn)) + return orn_error + + +def get_orientation_diff_in_radian(orn0, orn1): + """ + Returns the difference between two quaternion orientations in radian + + Args: + orn0 (np.array): (x, y, z, w) + orn1 (np.array): (x, y, z, w) + + Returns: + orn_diff (float): orientation difference in radian + """ + vec0 = quat2axisangle(orn0) + vec0 /= np.linalg.norm(vec0) + vec1 = quat2axisangle(orn1) + vec1 /= np.linalg.norm(vec1) + return np.arccos(np.dot(vec0, vec1)) + + +def get_pose_error(target_pose, current_pose): + """ + Computes the error corresponding to target pose - current pose as a 6-dim vector. + The first 3 components correspond to translational error while the last 3 components + correspond to the rotational error. + + Args: + target_pose (np.array): a 4x4 homogenous matrix for the target pose + current_pose (np.array): a 4x4 homogenous matrix for the current pose + + Returns: + np.array: 6-dim pose error. + """ + error = np.zeros(6) + + # compute translational error + target_pos = target_pose[:3, 3] + current_pos = current_pose[:3, 3] + pos_err = target_pos - current_pos + + # compute rotational error + r1 = current_pose[:3, 0] + r2 = current_pose[:3, 1] + r3 = current_pose[:3, 2] + r1d = target_pose[:3, 0] + r2d = target_pose[:3, 1] + r3d = target_pose[:3, 2] + rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d)) + + error[:3] = pos_err + error[3:] = rot_err + return error + + +def matrix_inverse(matrix): + """ + Helper function to have an efficient matrix inversion function. + + Args: + matrix (np.array): 2d-array representing a matrix + + Returns: + np.array: 2d-array representing the matrix inverse + """ + return np.linalg.inv(matrix) + + +def vecs2axisangle(vec0, vec1): + """ + Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into an axis-angle representation of the angle + + Args: + vec0 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized + vec1 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized + """ + # Normalize vectors + vec0 = normalize(vec0, axis=-1) + vec1 = normalize(vec1, axis=-1) + + # Get cross product for direction of angle, and multiply by arcos of the dot product which is the angle + return np.cross(vec0, vec1) * np.arccos((vec0 * vec1).sum(-1, keepdims=True)) + + +def vecs2quat(vec0, vec1, normalized=False): + """ + Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into a quaternion representation of the angle + + Args: + vec0 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized + vec1 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized + normalized (bool): If True, @vec0 and @vec1 are assumed to already be normalized and we will skip the + normalization step (more efficient) + """ + # Normalize vectors if requested + if not normalized: + vec0 = normalize(vec0, axis=-1) + vec1 = normalize(vec1, axis=-1) + + # Half-way Quaternion Solution -- see https://stackoverflow.com/a/11741520 + cos_theta = np.sum(vec0 * vec1, axis=-1, keepdims=True) + quat_unnormalized = np.where( + cos_theta == -1, np.array([1.0, 0, 0, 0]), np.concatenate([np.cross(vec0, vec1), 1 + cos_theta], axis=-1) + ) + return quat_unnormalized / np.linalg.norm(quat_unnormalized, axis=-1, keepdims=True) + + +def align_vector_sets(vec_set1, vec_set2): + """ + Computes a single quaternion representing the rotation that best aligns vec_set1 to vec_set2. + + Args: + vec_set1 (np.array): (N, 3) tensor of N 3D vectors + vec_set2 (np.array): (N, 3) tensor of N 3D vectors + + Returns: + np.array: (4,) Normalized quaternion representing the overall rotation + """ + rot, _ = R.align_vectors(vec_set1, vec_set2) + return rot.as_quat() + + +def l2_distance(v1, v2): + """Returns the L2 distance between vector v1 and v2.""" + return np.linalg.norm(np.array(v1) - np.array(v2)) + + +def cartesian_to_polar(x, y): + """Convert cartesian coordinate to polar coordinate""" + rho = np.sqrt(x**2 + y**2) + phi = np.arctan2(y, x) + return rho, phi + + +def deg2rad(deg): + return deg * np.pi / 180.0 + + +def rad2deg(rad): + return rad * 180.0 / np.pi + + +def check_quat_right_angle(quat, atol=5e-2): + """ + Check by making sure the quaternion is some permutation of +/- (1, 0, 0, 0), + +/- (0.707, 0.707, 0, 0), or +/- (0.5, 0.5, 0.5, 0.5) + Because orientations are all normalized (same L2-norm), every orientation should have a unique L1-norm + So we check the L1-norm of the absolute value of the orientation as a proxy for verifying these values + + Args: + quat (4-array): (x,y,z,w) quaternion orientation to check + atol (float): Absolute tolerance permitted + + Returns: + bool: Whether the quaternion is a right angle or not + """ + return np.any(np.isclose(np.abs(quat).sum(), np.array([1.0, 1.414, 2.0]), atol=atol)) + + +def z_angle_from_quat(quat): + """Get the angle around the Z axis produced by the quaternion.""" + rotated_X_axis = R.from_quat(quat).apply([1, 0, 0]) + return np.arctan2(rotated_X_axis[1], rotated_X_axis[0]) + + +def integer_spiral_coordinates(n): + """A function to map integers to 2D coordinates in a spiral pattern around the origin.""" + # Map integers from Z to Z^2 in a spiral pattern around the origin. + # Sources: + # https://www.reddit.com/r/askmath/comments/18vqorf/find_the_nth_coordinate_of_a_square_spiral/ + # https://oeis.org/A174344 + m = np.floor(np.sqrt(n)) + x = ((-1) ** m) * ((n - m * (m + 1)) * (np.floor(2 * np.sqrt(n)) % 2) - np.ceil(m / 2)) + y = ((-1) ** (m + 1)) * ((n - m * (m + 1)) * (np.floor(2 * np.sqrt(n) + 1) % 2) + np.ceil(m / 2)) + return int(x), int(y) + + +@jit(nopython=True, cache=True) +def transform_points(points, matrix, translate=True): + """ + Returns points rotated by a homogeneous + transformation matrix. + If points are (n, 2) matrix must be (3, 3) + If points are (n, 3) matrix must be (4, 4) + + Arguments: + points (np.array): (n, dim) where `dim` is 2 or 3. + matrix (np.array): (3, 3) or (4, 4) homogeneous rotation matrix. + translate (bool): whether to apply translation from matrix or not. + + Returns: + np.array: (n, dim) transformed points. + """ + if len(points) == 0 or matrix is None: + return points.copy() + + count, dim = points.shape + # Check if the matrix is close to an identity matrix + identity = np.eye(dim + 1) + if np.abs(matrix - identity[: dim + 1, : dim + 1]).max() < 1e-8: + return points.copy() + + if translate: + stack = np.ascontiguousarray(np.concatenate((points, np.ones((count, 1))), axis=1)) + return (matrix @ stack.T).T[:, :dim] + else: + return (matrix[:dim, :dim] @ points.T).T + + +def quaternions_close(q1, q2, atol=1e-3): + """ + Whether two quaternions represent the same rotation, + allowing for the possibility that one is the negative of the other. + + Arguments: + q1 (np.array): First quaternion + q2 (np.array): Second quaternion + atol (float): Absolute tolerance for comparison + + Returns: + bool: Whether the quaternions are close + """ + return np.allclose(q1, q2, atol=atol) or np.allclose(q1, -q2, atol=atol) + + +@jit(nopython=True, cache=True) +def orientation_error(desired, current): + """ + This function calculates a 3-dimensional orientation error vector for use in the + impedance controller. It does this by computing the delta rotation between the + inputs and converting that rotation to exponential coordinates (axis-angle + representation, where the 3d vector is axis * angle). + See https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation for more information. + Optimized function to determine orientation error from matrices + + Args: + desired (tensor): (..., 3, 3) where final two dims are 2d array representing target orientation matrix + current (tensor): (..., 3, 3) where final two dims are 2d array representing current orientation matrix + Returns: + tensor: (..., 3) where final dim is (ax, ay, az) axis-angle representing orientation error + """ + # convert input shapes + input_shape = desired.shape[:-2] + desired = desired.reshape(-1, 3, 3) + current = current.reshape(-1, 3, 3) + + # grab relevant info + rc1 = current[:, :, 0] + rc2 = current[:, :, 1] + rc3 = current[:, :, 2] + rd1 = desired[:, :, 0] + rd2 = desired[:, :, 1] + rd3 = desired[:, :, 2] + + error = 0.5 * (np.cross(rc1, rd1) + np.cross(rc2, rd2) + np.cross(rc3, rd3)) + + # Reshape + error = error.reshape(*input_shape, 3) + + return error + + +def delta_rotation_matrix(omega, delta_t): + """ + Compute the delta rotation matrix given angular velocity and time elapsed. + + Arguments: + omega (np.array): Angular velocity vector [omega_x, omega_y, omega_z]. + delta_t (float): Time elapsed. + + Returns: + np.array: 3x3 Delta rotation matrix. + """ + # Magnitude of angular velocity (angular speed) + omega_magnitude = np.linalg.norm(omega) + + # If angular speed is zero, return identity matrix + if omega_magnitude == 0: + return np.eye(3) + + # Rotation angle + theta = omega_magnitude * delta_t + + # Normalized axis of rotation + axis = omega / omega_magnitude + + # Skew-symmetric matrix K + u_x, u_y, u_z = axis + K = np.array([[0, -u_z, u_y], [u_z, 0, -u_x], [-u_y, u_x, 0]]) + + # Rodrigues' rotation formula + R = np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K) + + return R + + +def mat2euler_intrinsic(rmat): + """ + Converts given rotation matrix to intrinsic euler angles in radian. + + Parameters: + rmat (np.array): 3x3 rotation matrix + + Returns: + np.array: (r,p,y) converted intrinsic euler angles in radian vec3 float + """ + return R.from_matrix(rmat).as_euler("XYZ") + + +def euler_intrinsic2mat(euler): + """ + Converts intrinsic euler angles into rotation matrix form + + Parameters: + euler (np.array): (r,p,y) angles + + Returns: + np.array: 3x3 rotation matrix + """ + return R.from_euler("XYZ", euler).as_matrix() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/ui_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/ui_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..eb6e2a5cb5e5cdb3854e7a40429b92a6762a1ee3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/ui_utils.py @@ -0,0 +1,1171 @@ +""" +Helper classes and functions for streamlining user interactions +""" + +import contextlib +import datetime +import logging +import math +import random +import sys +from pathlib import Path + +import imageio +import matplotlib.path as mpath +import torch as th +from IPython import embed +from matplotlib.text import TextPath +from PIL import Image +from scipy.integrate import quad +from scipy.interpolate import CubicSpline +from scipy.spatial.transform import Rotation as R +from termcolor import colored + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.controllers import ControllerView + + +def print_icon(): + raw_texts = [ + # Lgrey, grey, lgrey, grey, red, lgrey, red + (" ___________", "", "", "", "", "", "_"), + (" / ", "", "", "", "", "", "/ \\"), + (" / ", "", "", "", "/ /", "__", ""), + (" / ", "", "", "", "", "", "/ / /\\"), + (" /", "__________", "", "", "/ /", "__", "/ \\"), + (" ", "\\ _____ ", "", "", "\\ \\", "__", "\\ /"), + (" ", "\\ \\ ", "/ ", "\\ ", "", "", "\\ \\_/ /"), + (" ", "\\ \\", "/", "___\\ ", "", "", "\\ /"), + (" ", "\\__________", "", "", "", "", "\\_/ "), + ] + for lgrey_text0, grey_text0, lgrey_text1, grey_text1, red_text0, lgrey_text2, red_text1 in raw_texts: + lgrey_text0 = colored(lgrey_text0, "light_grey", attrs=["bold"]) + grey_text0 = colored(grey_text0, "light_grey", attrs=["bold", "dark"]) + lgrey_text1 = colored(lgrey_text1, "light_grey", attrs=["bold"]) + grey_text1 = colored(grey_text1, "light_grey", attrs=["bold", "dark"]) + red_text0 = colored(red_text0, "light_red", attrs=["bold"]) + lgrey_text2 = colored(lgrey_text2, "light_grey", attrs=["bold"]) + red_text1 = colored(red_text1, "light_red", attrs=["bold"]) + print(lgrey_text0 + grey_text0 + lgrey_text1 + grey_text1 + red_text0 + lgrey_text2 + red_text1) + + +def print_logo(): + raw_texts = [ + (" ___ _", " ____ _ _ "), + (r" / _ \ _ __ ___ _ __ (_)", r"/ ___(_) |__ ___ ___ _ __ "), + (r" | | | | '_ ` _ \| '_ \| |", r" | _| | '_ \/ __|/ _ \| '_ \ "), + (r" | |_| | | | | | | | | | |", r" |_| | | |_) \__ \ (_) | | | |"), + (r" \___/|_| |_| |_|_| |_|_|", r"\____|_|_.__/|___/\___/|_| |_|"), + ] + for grey_text, red_text in raw_texts: + grey_text = colored(grey_text, "light_grey", attrs=["bold", "dark"]) + red_text = colored(red_text, "light_red", attrs=["bold"]) + print(grey_text + red_text) + + +def logo_small(): + grey_text = colored("Omni", "light_grey", attrs=["bold", "dark"]) + red_text = colored("Gibson", "light_red", attrs=["bold"]) + return grey_text + red_text + + +def dock_window(space, name, location, ratio=0.5): + """ + Method for docking a specific GUI window in a specified location within the workspace + + Args: + space (WindowHandle): Handle to the docking space to dock the window specified by @name + name (str): Name of a window to dock + location (omni.ui.DockPosition): docking position for placing the window specified by @name + ratio (float): Ratio when splitting the docking space between the pre-existing and newly added window + + Returns: + WindowHandle: Handle to the docking space that the window specified by @name was placed in + """ + window = lazy.omni.ui.Workspace.get_window(name) + if window and space: + window.dock_in(space, location, ratio=ratio) + return window + + +class KeyboardEventHandler: + """ + Simple singleton class for handing keyboard events + """ + + # Global keyboard callbacks + KEYBOARD_CALLBACKS = dict() + + # ID assigned to meta callback method for this class + _CALLBACK_ID = None + + def __init__(self): + raise ValueError("Cannot create an instance of keyboard event handler!") + + @classmethod + def initialize(cls): + """ + Hook up a meta function callback to the omni backend + """ + appwindow = lazy.omni.appwindow.get_default_app_window() + input_interface = lazy.carb.input.acquire_input_interface() + keyboard = appwindow.get_keyboard() + cls._CALLBACK_ID = input_interface.subscribe_to_keyboard_events(keyboard, cls._meta_callback) + + @classmethod + def reset(cls): + """ + Resets this callback interface by removing all current callback functions + """ + appwindow = lazy.omni.appwindow.get_default_app_window() + input_interface = lazy.carb.input.acquire_input_interface() + keyboard = appwindow.get_keyboard() + input_interface.unsubscribe_to_keyboard_events(keyboard, cls._CALLBACK_ID) + cls.KEYBOARD_CALLBACKS = dict() + cls._CALLBACK_ID = None + + @classmethod + def add_keyboard_callback(cls, key, callback_fn): + """ + Registers a keyboard callback function with omni, mapping a keypress from @key to run the callback_function + @callback_fn + + Args: + key (carb.input.KeyboardInput): key to associate with the callback + callback_fn (function): Callback function to call if the key @key is pressed or repeated. Note that this + function's signature should be: + + callback_fn() --> None + """ + # Initialize the interface if not initialized yet + if cls._CALLBACK_ID is None: + cls.initialize() + # Add the callback + cls.KEYBOARD_CALLBACKS[key] = callback_fn + + @classmethod + def _meta_callback(cls, event, *args, **kwargs): + """ + Meta callback function that is hooked up to omni's backend + """ + # Check if we've received a key press or repeat + if ( + event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS + or event.type == lazy.carb.input.KeyboardEventType.KEY_REPEAT + ): + # Run the specific callback + cls.KEYBOARD_CALLBACKS.get(event.input, lambda: None)() + + # Always return True + return True + + @classmethod + def xr_callback(cls, controller, button): + """ + Meta callback function that is hooked up to omni's backend + """ + # Check if we've received a key press or repeat + cls.KEYBOARD_CALLBACKS.get(f"{controller}_{button}", lambda: None)() + + +@contextlib.contextmanager +def suppress_omni_log(channels): + """ + A context scope for temporarily suppressing logging for certain omni channels. + + Args: + channels (None or list of str): Logging channel(s) to suppress. If None, will globally disable logger + """ + # Record the state to restore to after the context exists + log = lazy.omni.log.get_log() + + if gm.DEBUG: + # Do nothing + pass + elif channels is None: + # Globally disable log + log.enabled = False + else: + # For some reason, all enabled states always return False even if the logging is clearly enabled for the + # given channel, so we assume all channels are enabled + # We do, however, check what behavior was assigned to this channel, since we force an override during this context + channel_behavior = {channel: log.get_channel_enabled(channel)[2] for channel in channels} + + # Suppress the channels + for channel in channels: + log.set_channel_enabled(channel, False, lazy.omni.log.SettingBehavior.OVERRIDE) + + yield + + if gm.DEBUG: + # Do nothing + pass + elif channels is None: + # Globally re-enable log + log.enabled = True + else: + # Unsuppress the channels + for channel in channels: + log.set_channel_enabled(channel, True, channel_behavior[channel]) + + +@contextlib.contextmanager +def suppress_loggers(logger_names): + """ + A context scope for temporarily suppressing logging for certain omni channels. + + Args: + logger_names (list of str): Logger name(s) whose corresponding loggers should be suppressed + """ + if not gm.DEBUG: + # Store prior states so we can restore them after this context exits + logger_levels = {name: logging.getLogger(name).getEffectiveLevel() for name in logger_names} + + # Suppress the loggers (only output fatal messages) + for name in logger_names: + logging.getLogger(name).setLevel(logging.FATAL) + + yield + + if not gm.DEBUG: + # Unsuppress the loggers + for name in logger_names: + logging.getLogger(name).setLevel(logger_levels[name]) + + +def create_module_logger(module_name): + """ + Creates and returns a logger for logging statements from the module represented by @module_name + + Args: + module_name (str): Module to create the logger for. Should be the module's `__name__` variable + + Returns: + Logger: Created logger for the module + """ + return logging.getLogger(module_name) + + +def disclaimer(msg): + """ + Prints a disclaimer message, i.e.: "We know this doesn't work; it's an omni issue; we expect it to be fixed in the + next release! + """ + if gm.SHOW_DISCLAIMERS: + print("****** DISCLAIMER ******") + print("Isaac Sim / Omniverse has some significant limitations and bugs in its current release.") + print( + "This message has popped up because a potential feature in OmniGibson relies upon a feature in Omniverse that " + "is yet to be released publically. Currently, the expected behavior may not be fully functional, but " + "should be resolved by the next Isaac Sim release." + ) + print(f"Exact Limitation: {msg}") + print("************************") + + +def debug_breakpoint(msg): + og.log.error(msg) + embed() + + +def choose_from_options(options, name, random_selection=False, selected_option=None): + """ + Prints out options from a list, and returns the requested option. + + Args: + options (dict or list): options to choose from. If dict, the value entries are assumed to be docstrings + explaining the individual options + name (str): name of the options + random_selection (bool): if the selection is random (for automatic demo execution). Default False + selected_option (str or None): if specified, directly return this option without prompting. Default None + + Returns: + str: Requested option + """ + # Select robot + print("\nHere is a list of available {}s:\n".format(name)) + + for k, option in enumerate(options): + docstring = ": {}".format(options[option]) if isinstance(options, dict) else "" + print("[{}] {}{}".format(k + 1, option, docstring)) + print() + + if selected_option is not None: + assert selected_option in options, "selected_option '{}' is not a valid {}.".format(selected_option, name) + return selected_option + elif not random_selection: + try: + s = input("Choose a {} (enter a number from 1 to {}): ".format(name, len(options))) + # parse input into a number within range + k = min(max(int(s), 1), len(options)) - 1 + except ValueError: + k = 0 + print("Input is not valid. Use {} by default.".format(list(options)[k])) + else: + if "pytest" in sys.modules: + local_rng = random.Random(0) + k = local_rng.choice(range(len(options))) + else: + k = random.choice(range(len(options))) + print("Choosing {}: {} randomly".format(k, list(options)[k])) + + # Return requested option + return list(options)[k] + + +class CameraMover: + """ + A helper class for manipulating a camera via the keyboard. Utilizes carb keyboard callbacks to move + the camera around. + + Args: + cam (VisionSensor): The camera vision sensor to manipulate via the keyboard + delta (float): Change (m) per keypress when moving the camera + save_dir (str): Absolute path to where recorded images should be stored. Default is /imgs + """ + + def __init__(self, cam, delta=0.25, save_dir=None): + if save_dir is None: + save_dir = f"{og.root_path}/../images" + + self.cam = cam + self.delta = delta + self.light_val = gm.FORCE_LIGHT_INTENSITY + self.save_dir = save_dir + + self._appwindow = lazy.omni.appwindow.get_default_app_window() + self._input = lazy.carb.input.acquire_input_interface() + self._keyboard = self._appwindow.get_keyboard() + self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event) + + def clear(self): + """ + Clears this camera mover. After this is called, the camera mover cannot be used. + """ + self._input.unsubscribe_to_keyboard_events(self._keyboard, self._sub_keyboard) + + def set_save_dir(self, save_dir): + """ + Sets the absolute path corresponding to the image directory where recorded images from this CameraMover + should be saved + + Args: + save_dir (str): Absolute path to where recorded images should be stored + """ + self.save_dir = save_dir + + def change_light(self, delta): + self.light_val += delta + self.set_lights(self.light_val) + + def set_lights(self, intensity): + world = lazy.isaacsim.core.utils.prims.get_prim_at_path("/World") + for prim in world.GetChildren(): + for prim_child in prim.GetChildren(): + for prim_child_child in prim_child.GetChildren(): + if "Light" in prim_child_child.GetPrimTypeInfo().GetTypeName(): + prim_child_child.GetAttribute("inputs:intensity").Set(intensity) + + def print_info(self): + """ + Prints keyboard command info out to the user + """ + print("*" * 40) + print("CameraMover! Commands:") + print() + print("\t Right Click + Drag: Rotate camera") + print("\t W / S : Move camera forward / backward") + print("\t A / D : Move camera left / right") + print("\t T / G : Move camera up / down") + print("\t 9 / 0 : Increase / decrease the lights") + print("\t P : Print current camera pose") + print("\t O: Save the current camera view as an image") + + def print_cam_pose(self): + """ + Prints out the camera pose as (position, quaternion) in the world frame + """ + print(f"cam pose: {self.cam.get_position_orientation()}") + + def get_image(self): + """ + Helper function for quickly grabbing the currently viewed RGB image + + Returns: + th.tensor: (H, W, 3) sized RGB image array + """ + return self.cam.get_obs()[0]["rgb"][:, :, :-1] + + def record_image(self, fpath=None): + """ + Saves the currently viewed image and writes it to disk + + Args: + fpath (None or str): If specified, the absolute fpath to the image save location. Default is located in + self.save_dir + """ + og.log.info("Recording image...") + + # Use default fpath if not specified + if fpath is None: + timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + fpath = f"{self.save_dir}/og_{timestamp}.png" + + # Make sure save path directory exists, and then save the image to that location + Path(Path(fpath).parent).mkdir(parents=True, exist_ok=True) + Image.fromarray(self.get_image().cpu().numpy()).save(fpath) + og.log.info(f"Saved current viewer camera image to {fpath}.") + + def record_trajectory(self, poses, fps, steps_per_frame=1, fpath=None): + """ + Moves the viewer camera through the poses specified by @poses and records the resulting trajectory to an mp4 + video file on disk. + + Args: + poses (list of 2-tuple): List of global (position, quaternion) values to set the viewer camera to defining + this trajectory + fps (int): Frames per second when recording this video + steps_per_frame (int): How many sim steps should occur between each frame being recorded. Minimum and + default is 1. + fpath (None or str): If specified, the absolute fpath to the video save location. Default is located in + self.save_dir + """ + og.log.info("Recording trajectory...") + + # Use default fpath if not specified + if fpath is None: + timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + fpath = f"{self.save_dir}/og_{timestamp}.mp4" + + # Make sure save path directory exists, and then create the video writer + Path(Path(fpath).parent).mkdir(parents=True, exist_ok=True) + video_writer = imageio.get_writer(fpath, fps=fps) + + # Iterate through all desired poses, and record the trajectory + for i, (pos, quat) in enumerate(poses): + self.cam.set_position_orientation(position=pos, orientation=quat) + og.sim.step() + if i % steps_per_frame == 0: + video_writer.append_data(self.get_image().cpu().numpy()) + + # Close writer + video_writer.close() + og.log.info(f"Saved camera trajectory video to {fpath}.") + + def record_trajectory_from_waypoints(self, waypoints, per_step_distance, fps, steps_per_frame=1, fpath=None): + """ + Moves the viewer camera through the waypoints specified by @waypoints and records the resulting trajectory to + an mp4 video file on disk. + + Args: + waypoints (th.tensor): (n, 3) global position waypoint values to set the viewer camera to defining this trajectory + per_step_distance (float): How much distance (in m) should be approximately covered per trajectory step. + This will determine the path length between individual waypoints + fps (int): Frames per second when recording this video + steps_per_frame (int): How many sim steps should occur between each frame being recorded. Minimum and + default is 1. + fpath (None or str): If specified, the absolute fpath to the video save location. Default is located in + self.save_dir + """ + # Create splines and their derivatives + n_waypoints = len(waypoints) + if n_waypoints < 3: + og.log.error("Cannot generate trajectory from waypoints with less than 3 waypoints!") + return + + splines = [CubicSpline(range(n_waypoints), waypoints[:, i], bc_type="clamped") for i in range(3)] + dsplines = [spline.derivative() for spline in splines] + + # Function help get arc derivative + def arc_derivative(u): + return math.sqrt(sum(dspline(u) ** 2 for dspline in dsplines)) + + # Function to help get interpolated positions + def get_interpolated_positions(step): + assert step < n_waypoints - 1 + dist = quad(func=arc_derivative, a=step, b=step + 1)[0] + path_length = int(dist / per_step_distance) + interpolated_points = th.zeros((path_length, 3)) + for i in range(path_length): + curr_step = step + (i / path_length) + interpolated_points[i, :] = th.tensor([float(spline(curr_step)) for spline in splines]) + return interpolated_points + + # Iterate over all waypoints and infer the resulting trajectory, recording the resulting poses + poses = [] + for i in range(n_waypoints - 1): + positions = get_interpolated_positions(step=i) + for j in range(len(positions) - 1): + # Get direction vector from the current to the following point + direction = positions[j + 1] - positions[j] + direction = direction / th.norm(direction) + # Infer tilt and pan angles from this direction + xy_direction = direction[:2] / th.norm(direction[:2]) + z = direction[2] + pan_angle = th.arctan2(-xy_direction[0], xy_direction[1]) + tilt_angle = th.arcsin(z) + # Infer global quat orientation from these angles + quat = T.euler2quat(th.tensor([math.pi / 2 + tilt_angle.item(), 0.0, pan_angle.item()])) + poses.append([positions[j], quat]) + + # Record the generated trajectory + self.record_trajectory(poses=poses, fps=fps, steps_per_frame=steps_per_frame, fpath=fpath) + + def set_delta(self, delta): + """ + Sets the delta value (how much the camera moves with each keypress) for this CameraMover + + Args: + delta (float): Change (m) per keypress when moving the camera + """ + self.delta = delta + + def set_cam(self, cam): + """ + Sets the active camera sensor for this CameraMover + + Args: + cam (VisionSensor): The camera vision sensor to manipulate via the keyboard + """ + self.cam = cam + + @property + def input_to_function(self): + """ + Returns: + dict: Mapping from relevant keypresses to corresponding function call to use + """ + return { + lazy.carb.input.KeyboardInput.O: lambda: self.record_image(fpath=None), + lazy.carb.input.KeyboardInput.P: lambda: self.print_cam_pose(), + lazy.carb.input.KeyboardInput.KEY_9: lambda: self.change_light(delta=-2e4), + lazy.carb.input.KeyboardInput.KEY_0: lambda: self.change_light(delta=2e4), + } + + @property + def input_to_command(self): + """ + Returns: + dict: Mapping from relevant keypresses to corresponding delta command to apply to the camera pose + """ + return { + lazy.carb.input.KeyboardInput.D: th.tensor([self.delta, 0, 0]), + lazy.carb.input.KeyboardInput.A: th.tensor([-self.delta, 0, 0]), + lazy.carb.input.KeyboardInput.W: th.tensor([0, 0, -self.delta]), + lazy.carb.input.KeyboardInput.S: th.tensor([0, 0, self.delta]), + lazy.carb.input.KeyboardInput.T: th.tensor([0, self.delta, 0]), + lazy.carb.input.KeyboardInput.G: th.tensor([0, -self.delta, 0]), + } + + def _sub_keyboard_event(self, event, *args, **kwargs): + """ + Handle keyboard events. Note: The signature is pulled directly from omni. + + Args: + event (int): keyboard event type + """ + if ( + event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS + or event.type == lazy.carb.input.KeyboardEventType.KEY_REPEAT + ): + if event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS and event.input in self.input_to_function: + self.input_to_function[event.input]() + + else: + command = self.input_to_command.get(event.input, None) + + if command is not None: + # Convert to world frame to move the camera + pos, orn = self.cam.get_position_orientation() + transform = T.quat2mat(orn) + delta_pos_global = transform @ command + self.cam.set_position_orientation(position=pos + delta_pos_global) + + return True + + +class KeyboardRobotController: + """ + Simple class for controlling OmniGibson robots using keyboard commands + """ + + def __init__(self, robot): + """ + Args: + robot (BaseRobot): robot to control + """ + # Store relevant info from robot + self.robot = robot + self.action_dim = robot.action_dim + self.controller_info = dict() + self.joint_idx_to_group_key = dict() + idx = 0 + + for name, (group_key, _) in robot.controllers.items(): + self.controller_info[name] = { + "name": ControllerView.get_controller_type_str(group_key), + "start_idx": idx, + "dofs": ControllerView.get_dof_idx(group_key), + "command_dim": ControllerView.get_command_dim(group_key), + } + idx += ControllerView.get_command_dim(group_key) + for i in ControllerView.get_dof_idx(group_key).tolist(): + self.joint_idx_to_group_key[i] = group_key + + # Other persistent variables we need to keep track of + self.joint_names = [name for name in robot.joints.keys()] # Ordered list of joint names belonging to the robot + self.joint_types = [joint.joint_type for joint in robot.joints.values()] # Ordered list of joint types + self.joint_command_idx = None # Indices of joints being directly controlled in the action array + self.joint_control_idx = None # Indices of joints being directly controlled in the actual joint array + self.active_joint_command_idx_idx = ( + 0 # Which index within the joint_command_idx variable is being controlled by the user + ) + self.current_joint = -1 # Active joint being controlled for joint control + self.ik_arms = [] # List of arm controller names to be controlled by IK + self.active_arm_idx = 0 # Which index within self.ik_arms is actively being controlled (only relevant for IK) + self.binary_grippers = [] # Grippers being controlled using multi-finger binary controller + self.active_gripper_idx = 0 # Which index within self.binary_grippers is actively being controlled + self.gripper_direction = None # Flips between -1 and 1, per arm controlled by multi-finger binary control + self.persistent_gripper_action = ( + None # Persistent gripper commands, per arm controlled by multi-finger binary control + ) + # i.e.: if using binary gripper control and when no keypress is active, the gripper action should still the last executed gripper action + self.keypress_mapping = None # Maps omni keybindings to information for controlling various parts of the robot + self.current_keypress = None # Current key that is being pressed + self.active_action = None # Current action information based on the current keypress + self._pending_release_key = None # Which key has a pending release (to handle batched events) + self.toggling_gripper = False # Whether we should toggle the gripper during the next action + self.custom_keymapping = None # Dictionary mapping custom keys to custom callback functions / info + + # Populate the keypress mapping dictionary + self.populate_keypress_mapping() + + # Register the keyboard callback function + self.register_keyboard_handler() + + def register_keyboard_handler(self): + """ + Sets up the keyboard callback functionality with omniverse + """ + appwindow = lazy.omni.appwindow.get_default_app_window() + input_interface = lazy.carb.input.acquire_input_interface() + keyboard = appwindow.get_keyboard() + self._keyboard_sub = input_interface.subscribe_to_keyboard_events(keyboard, self.keyboard_event_handler) + + def register_custom_keymapping(self, key, description, callback_fn): + """ + Register a custom keymapping with corresponding callback function for this keyboard controller. + Note that this will automatically override any pre-existing callback that existed for that key. + + Args: + key (carb.input.KeyboardInput): Key to map to callback function + description (str): Description for the callback function + callback_fn (function): Callback function, should have signature: + + callback_fn() -> None + """ + self.custom_keymapping[key] = {"description": description, "callback": callback_fn} + + def generate_ik_keypress_mapping(self, controller_info): + """ + Generates a dictionary for keypress mappings for IK control, based on the inputted @controller_info + + Args: + controller_info (dict): Dictionary of controller information for the specific robot arm to control + with IK + + Returns: + dict: Populated keypress mappings for IK to control the specified controller + """ + mapping = {} + + mapping[lazy.carb.input.KeyboardInput.UP] = {"idx": controller_info["start_idx"] + 0, "val": 0.1} + mapping[lazy.carb.input.KeyboardInput.DOWN] = {"idx": controller_info["start_idx"] + 0, "val": -0.1} + mapping[lazy.carb.input.KeyboardInput.RIGHT] = {"idx": controller_info["start_idx"] + 1, "val": -0.1} + mapping[lazy.carb.input.KeyboardInput.LEFT] = {"idx": controller_info["start_idx"] + 1, "val": 0.1} + mapping[lazy.carb.input.KeyboardInput.P] = {"idx": controller_info["start_idx"] + 2, "val": 0.1} + mapping[lazy.carb.input.KeyboardInput.SEMICOLON] = {"idx": controller_info["start_idx"] + 2, "val": -0.1} + mapping[lazy.carb.input.KeyboardInput.N] = {"idx": controller_info["start_idx"] + 3, "val": 0.1} + mapping[lazy.carb.input.KeyboardInput.B] = {"idx": controller_info["start_idx"] + 3, "val": -0.1} + mapping[lazy.carb.input.KeyboardInput.O] = {"idx": controller_info["start_idx"] + 4, "val": 0.1} + mapping[lazy.carb.input.KeyboardInput.U] = {"idx": controller_info["start_idx"] + 4, "val": -0.1} + mapping[lazy.carb.input.KeyboardInput.V] = {"idx": controller_info["start_idx"] + 5, "val": 0.1} + mapping[lazy.carb.input.KeyboardInput.C] = {"idx": controller_info["start_idx"] + 5, "val": -0.1} + + return mapping + + def generate_osc_keypress_mapping(self, controller_info): + """ + Generates a dictionary for keypress mappings for OSC control, based on the inputted @controller_info + + Args: + controller_info (dict): Dictionary of controller information for the specific robot arm to control + with OSC + + Returns: + dict: Populated keypress mappings for IK to control the specified controller + """ + mapping = {} + + mapping[lazy.carb.input.KeyboardInput.UP] = {"idx": controller_info["start_idx"] + 0, "val": 0.25} + mapping[lazy.carb.input.KeyboardInput.DOWN] = {"idx": controller_info["start_idx"] + 0, "val": -0.25} + mapping[lazy.carb.input.KeyboardInput.RIGHT] = {"idx": controller_info["start_idx"] + 1, "val": -0.25} + mapping[lazy.carb.input.KeyboardInput.LEFT] = {"idx": controller_info["start_idx"] + 1, "val": 0.25} + mapping[lazy.carb.input.KeyboardInput.P] = {"idx": controller_info["start_idx"] + 2, "val": 0.25} + mapping[lazy.carb.input.KeyboardInput.SEMICOLON] = {"idx": controller_info["start_idx"] + 2, "val": -0.25} + mapping[lazy.carb.input.KeyboardInput.N] = {"idx": controller_info["start_idx"] + 3, "val": 0.25} + mapping[lazy.carb.input.KeyboardInput.B] = {"idx": controller_info["start_idx"] + 3, "val": -0.25} + mapping[lazy.carb.input.KeyboardInput.O] = {"idx": controller_info["start_idx"] + 4, "val": 0.25} + mapping[lazy.carb.input.KeyboardInput.U] = {"idx": controller_info["start_idx"] + 4, "val": -0.25} + mapping[lazy.carb.input.KeyboardInput.V] = {"idx": controller_info["start_idx"] + 5, "val": 0.25} + mapping[lazy.carb.input.KeyboardInput.C] = {"idx": controller_info["start_idx"] + 5, "val": -0.25} + + return mapping + + def populate_keypress_mapping(self): + """ + Populates the mapping @self.keypress_mapping, which maps keypresses to action info: + + keypress: + idx: + val: + """ + self.keypress_mapping = {} + self.joint_command_idx = [] + self.joint_control_idx = [] + self.gripper_direction = {} + self.persistent_gripper_action = {} + self.custom_keymapping = {} + + # Add mapping for joint control directions (no index because these are inferred at runtime) + self.keypress_mapping[lazy.carb.input.KeyboardInput.RIGHT_BRACKET] = {"idx": None, "val": 0.1} + self.keypress_mapping[lazy.carb.input.KeyboardInput.LEFT_BRACKET] = {"idx": None, "val": -0.1} + + # Iterate over all controller info and populate mapping + for component, info in self.controller_info.items(): + if info["name"] in ["JointController", "HolonomicBaseJointController"]: + for i in range(info["command_dim"]): + cmd_idx = info["start_idx"] + i + self.joint_command_idx.append(cmd_idx) + self.joint_control_idx += info["dofs"].tolist() + elif info["name"] == "DifferentialDriveController": + self.keypress_mapping[lazy.carb.input.KeyboardInput.I] = {"idx": info["start_idx"] + 0, "val": 0.4} + self.keypress_mapping[lazy.carb.input.KeyboardInput.K] = {"idx": info["start_idx"] + 0, "val": -0.4} + self.keypress_mapping[lazy.carb.input.KeyboardInput.L] = {"idx": info["start_idx"] + 1, "val": -0.2} + self.keypress_mapping[lazy.carb.input.KeyboardInput.J] = {"idx": info["start_idx"] + 1, "val": 0.2} + elif info["name"] == "InverseKinematicsController": + self.ik_arms.append(component) + self.keypress_mapping.update(self.generate_ik_keypress_mapping(controller_info=info)) + elif info["name"] == "OperationalSpaceController": + self.ik_arms.append(component) + self.keypress_mapping.update(self.generate_osc_keypress_mapping(controller_info=info)) + elif info["name"] == "MultiFingerGripperController": + if info["command_dim"] > 1: + for i in range(info["command_dim"]): + cmd_idx = info["start_idx"] + i + self.joint_command_idx.append(cmd_idx) + self.joint_control_idx += info["dofs"].tolist() + else: + self.keypress_mapping[lazy.carb.input.KeyboardInput.T] = {"idx": info["start_idx"], "val": 1.0} + self.gripper_direction[component] = 1.0 + self.persistent_gripper_action[component] = 1.0 + self.binary_grippers.append(component) + elif info["name"] == "NullJointController": + # We won't send actions if using a null gripper controller + self.keypress_mapping[lazy.carb.input.KeyboardInput.T] = {"idx": None, "val": None} + else: + raise ValueError("Unknown controller name received: {}".format(info["name"])) + + def keyboard_event_handler(self, event, *args, **kwargs): + # Check if we've received a key press or repeat + if ( + event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS + or event.type == lazy.carb.input.KeyboardEventType.KEY_REPEAT + ): + # Handle special cases + if ( + event.input in {lazy.carb.input.KeyboardInput.KEY_1, lazy.carb.input.KeyboardInput.KEY_2} + and len(self.joint_control_idx) > 1 + ): + # Update joint and print out new joint being controlled + self.active_joint_command_idx_idx = ( + max(0, self.active_joint_command_idx_idx - 1) + if event.input == lazy.carb.input.KeyboardInput.KEY_1 + else min(len(self.joint_control_idx) - 1, self.active_joint_command_idx_idx + 1) + ) + print( + f"Now controlling joint {self.joint_names[self.joint_control_idx[self.active_joint_command_idx_idx]]}" + ) + + elif ( + event.input in {lazy.carb.input.KeyboardInput.KEY_3, lazy.carb.input.KeyboardInput.KEY_4} + and len(self.ik_arms) > 1 + ): + # Update arm, update keypress mapping, and print out new arm being controlled + self.active_arm_idx = ( + max(0, self.active_arm_idx - 1) + if event.input == lazy.carb.input.KeyboardInput.KEY_3 + else min(len(self.ik_arms) - 1, self.active_arm_idx + 1) + ) + new_arm = self.ik_arms[self.active_arm_idx] + self.keypress_mapping.update(self.generate_ik_keypress_mapping(self.controller_info[new_arm])) + print(f"Now controlling arm {new_arm} EEF") + + elif ( + event.input in {lazy.carb.input.KeyboardInput.KEY_5, lazy.carb.input.KeyboardInput.KEY_6} + and len(self.binary_grippers) > 1 + ): + # Update gripper, update keypress mapping, and print out new gripper being controlled + self.active_gripper_idx = ( + max(0, self.active_gripper_idx - 1) + if event.input == lazy.carb.input.KeyboardInput.KEY_5 + else min(len(self.binary_grippers) - 1, self.active_gripper_idx + 1) + ) + print(f"Now controlling gripper {self.binary_grippers[self.active_gripper_idx]} with binary toggling") + + elif event.input == lazy.carb.input.KeyboardInput.M: + # Render the sensor modalities from the robot's camera and lidar + self.robot.visualize_sensors() + + elif event.input in self.custom_keymapping: + # Run custom press + self.custom_keymapping[event.input]["callback"]() + + elif event.input == lazy.carb.input.KeyboardInput.ESCAPE: + # Terminate immediately + og.shutdown() + + else: + # Handle all other actions and update accordingly + self.active_action = self.keypress_mapping.get(event.input, None) + + if event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS: + # Store the current keypress + self.current_keypress = event.input + + # Also store whether we pressed the key for toggling gripper actions + if event.input == lazy.carb.input.KeyboardInput.T: + self.toggling_gripper = True + + # If we release a key, mark release as pending (don't clear immediately to handle batched events) + elif event.type == lazy.carb.input.KeyboardEventType.KEY_RELEASE: + self._pending_release_key = event.input + + # Callback always needs to return True + return True + + def get_random_action(self): + """ + Returns: + n-array: Generated random action vector (normalized) + """ + action_lo, action_hi = -1, 1 + return th.rand(self.action_dim) * (action_hi - action_lo) + action_lo + + def get_teleop_action(self): + """ + Returns: + n-array: Generated action vector based on received user inputs from the keyboard + """ + action = th.zeros(self.action_dim) + + # Handle the action if any key is actively being pressed + if self.active_action is not None: + idx, val = self.active_action["idx"], self.active_action["val"] + + # Only handle the action if the value is specified + if val is not None: + # If there is no index, the user is controlling a joint with "[" and "]" + if idx is None and len(self.joint_command_idx) != 0: + idx = self.joint_command_idx[self.active_joint_command_idx_idx] + + # Also potentially modify the value being deployed in we're controlling a prismatic joint + # Lower prismatic joint values modifying delta positions since 0.1m is very different from 0.1rad! + joint_idx = self.joint_control_idx[self.active_joint_command_idx_idx] + + # Import here to avoid circular imports + from omnigibson.utils.constants import JointType + + gk = self.joint_idx_to_group_key[joint_idx] + if ( + self.joint_types[joint_idx] == JointType.JOINT_PRISMATIC + and ControllerView.get_use_delta_commands(gk) + and ControllerView.get_motor_type(gk) == "position" + ): + val *= 0.2 + + # Set the action + if idx is not None: + action[idx] = val + + # Possibly set the persistent gripper action + if len(self.binary_grippers) > 0 and self.keypress_mapping[lazy.carb.input.KeyboardInput.T]["val"] is not None: + for i, binary_gripper in enumerate(self.binary_grippers): + # Possibly update the stored value if the toggle gripper key has been pressed and + # it's the active gripper being controlled + if self.toggling_gripper and i == self.active_gripper_idx: + # We toggle the gripper direction or this gripper + self.gripper_direction[binary_gripper] *= -1.0 + self.persistent_gripper_action[binary_gripper] = ( + self.keypress_mapping[lazy.carb.input.KeyboardInput.T]["val"] + * self.gripper_direction[binary_gripper] + ) + + # Clear the toggling gripper flag + self.toggling_gripper = False + + # Set the persistent action + action[self.controller_info[binary_gripper]["start_idx"]] = self.persistent_gripper_action[ + binary_gripper + ] + + # TODO: this currently conflicts with omniverse logging and spams the window + # Print out the user what is being pressed / controlled + # sys.stdout.write("\033[K") + # keypress_str = self.current_keypress.__str__().split(".")[-1] + # print("Pressed {}. Action: {}".format(keypress_str, action.tolist())) + # sys.stdout.write("\033[F") + + # Clear action after consuming if a key release was pending for the current key + if self._pending_release_key is not None and self._pending_release_key == self.current_keypress: + self.active_action = None + self.current_keypress = None + self._pending_release_key = None + + # Return action + return action + + def print_keyboard_teleop_info(self): + """ + Prints out relevant information for teleop controlling a robot + """ + + def print_command(char, info): + char += " " * (10 - len(char)) + print("{}\t{}".format(char, info)) + + print() + print("*" * 30) + print("Controlling the Robot Using the Keyboard") + print("*" * 30) + print() + print("Joint Control") + print_command("1, 2", "decrement / increment the joint to control") + print_command("[, ]", "move the joint backwards, forwards, respectively") + print() + print("Differential Drive Control") + print_command("j, l", "turn left, right") + print_command("i, k", "move forward, backwards") + print() + print("Inverse Kinematics Control") + print_command("3, 4", "toggle between the different arm(s) to control") + print_command("\u2190, \u2192", "translate arm eef along x-axis") + print_command("\u2191, \u2193", "translate arm eef along y-axis") + print_command("p, ;", "translate arm eef along z-axis") + print_command("n, b", "rotate arm eef about x-axis") + print_command("o, u", "rotate arm eef about y-axis") + print_command("v, c", "rotate arm eef about z-axis") + print() + print("Boolean Gripper Control") + print_command("5, 6", "toggle between the different gripper(s) using binary control") + print_command("t", "toggle gripper (open/close)") + print() + print("Sensor Rendering") + print_command( + "m", "render the onboard sensor modalities (RGB, Depth, Normals, Instance Segmentation, Occupancy Map)" + ) + print() + if len(self.custom_keymapping) > 0: + print("Custom Keymappings") + for key, info in self.custom_keymapping.items(): + key_str = key.__str__().split(".")[-1].lower() + print_command(key_str, info["description"]) + print() + print("*" * 30) + print() + + +def generate_box_edges(center, extents): + """ + Generate the edges of a box given its center and extents. + + Parameters: + - center: Tuple of (x, y, z) coordinates for the box's center + - extents: Tuple of (width, height, depth) extents of the box + + Returns: + - A list of tuples, each containing two points (each a tuple of x, y, z) representing an edge of the box + """ + x_c, y_c, z_c = center + w, h, d = extents + + # Calculate the corner points of the box + corners = [ + (x_c - w, y_c - h, z_c - d), + (x_c - w, y_c - h, z_c + d), + (x_c - w, y_c + h, z_c - d), + (x_c - w, y_c + h, z_c + d), + (x_c + w, y_c - h, z_c - d), + (x_c + w, y_c - h, z_c + d), + (x_c + w, y_c + h, z_c - d), + (x_c + w, y_c + h, z_c + d), + ] + + # Define the edges by connecting the corners + edges = [ + (corners[0], corners[1]), + (corners[0], corners[2]), + (corners[1], corners[3]), + (corners[2], corners[3]), + (corners[4], corners[5]), + (corners[4], corners[6]), + (corners[5], corners[7]), + (corners[6], corners[7]), + (corners[0], corners[4]), + (corners[1], corners[5]), + (corners[2], corners[6]), + (corners[3], corners[7]), + ] + + return edges + + +def draw_text( + text, + position, + orientation=None, + color=(1.0, 0.0, 0.0, 1.0), + font_size=12, + line_size=1.0, + anchor="center", + max_height=th.inf, + max_width=th.inf, +): + """ + Draws text at a given position. + """ + + # First, get the line segments corresponding to the text + # font_family = "Ariel" + # fp = FontProperties(family=font_family) + path = TextPath((0, 0), text, size=font_size) + + def _path_to_line_segments(path): + line_segments = [] + subpath_start = None # Store the start point of the current subpath + + for points, code in zip(path.vertices, path.codes): + points = th.as_tensor(points, dtype=th.float32) # Ensure points is a tensor with float32 dtype + + if code == mpath.Path.MOVETO: + current_point = points + subpath_start = points # Remember the start of the subpath + elif code == mpath.Path.LINETO: + start_point = current_point.clone() # Create copies to avoid reference issues + end_point = points.clone() + line_segments.append( + [start_point.tolist(), end_point.tolist()] + ) # Convert to list for consistent storage + current_point = points + elif code == mpath.Path.CURVE3 or code == mpath.Path.CURVE4: + start_point = current_point.clone() + end_point = points[:2].clone() + line_segments.append([start_point.tolist(), end_point.tolist()]) + current_point = end_point + elif code == mpath.Path.CLOSEPOLY: + if not th.allclose(current_point, subpath_start): + line_segments.append([current_point.tolist(), subpath_start.tolist()]) + current_point = subpath_start + else: + raise ValueError(f"Unsupported path code: {code}") + + # Convert the entire list of segments to a tensor at once + return th.tensor(line_segments, dtype=th.float32) + + # Convert the Path to line segments + line_segments = _path_to_line_segments(path) + + # Transform the line segments to the desired position + all_verts = line_segments.reshape(-1, 2) + orig_min = th.min(all_verts, dim=0).values + orig_max = th.max(all_verts, dim=0).values + orig_ext = orig_max - orig_min + + # Figure out the necessary scaling + scale = 1.0 + max_dims = th.tensor([max_width, max_height]) + if th.any(th.isfinite(max_dims)): + scale = th.min(max_dims / orig_ext) + transformed_line_segments = line_segments * scale + + # Recompute the extents + transformed_verts = transformed_line_segments.reshape(-1, 2) + min_pt = th.min(transformed_verts, dim=0).values + max_pt = th.max(transformed_verts, dim=0).values + center = (min_pt + max_pt) / 2 + + if anchor == "center": + anchor_pt = center + elif anchor == "bottomleft": + anchor_pt = min_pt + elif anchor == "topright": + anchor_pt = max_pt + elif anchor == "topleft": + anchor_pt = th.tensor([min_pt[0], max_pt[1]]) + elif anchor == "bottomright": + anchor_pt = th.tensor([max_pt[0], min_pt[1]]) + elif anchor == "bottomcenter": + anchor_pt = th.tensor([center[0], min_pt[1]]) + elif anchor == "topcenter": + anchor_pt = th.tensor([center[0], max_pt[1]]) + else: + raise ValueError(f"Unknown anchor point {anchor}") + + rotation = R.identity() + if orientation is not None: + rotation = R.from_quat(orientation) + + def _transform_point(pt): + centered_pt = pt - anchor_pt + return rotation.apply([centered_pt[0], centered_pt[1], 0]) + position + + # Then, draw the line segments + for f, t in transformed_line_segments: + draw_line(_transform_point(f), _transform_point(t), color=color, size=line_size) + + +def draw_line(start, end, color=(1.0, 0.0, 0.0, 1.0), size=1.0): + """ + Draws a single line between two points. + """ + draw = lazy.isaacsim.util.debug_draw._debug_draw.acquire_debug_draw_interface() + draw.draw_lines([start], [end], [color], [size]) + + +def draw_box(center, extents, color=(1.0, 0.0, 0.0, 1.0), size=1.0): + """ + Draws a box defined by its center and extents. + """ + edges = generate_box_edges(center, extents) + for start, end in edges: + draw_line(start, end, color, size) + + +def draw_aabb(obj): + """ + Draws the axis-aligned bounding box of a given object. + """ + ctr = obj.aabb_center + ext = obj.aabb_extent / 2.0 + draw_box(ctr, ext) + + +def clear_debug_drawing(): + """ + Clears all debug drawings. + """ + draw = lazy.isaacsim.util.debug_draw._debug_draw.acquire_debug_draw_interface() + draw.clear_lines() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdf_preprocessing.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdf_preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a13b6bd17138bd403eccfd10bad11c3286374a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdf_preprocessing.py @@ -0,0 +1,311 @@ +from __future__ import annotations + +import os +import shutil +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Optional, Union + +PathLike = Union[str, os.PathLike] + + +def _is_ascii(text: str) -> bool: + return all(ord(ch) < 128 for ch in text) + + +def _mesh_filenames(root: ET.Element) -> list[str]: + """Return every ``filename`` referenced by a ```` element, in document order.""" + filenames = [] + for mesh in root.iter("mesh"): + fn = mesh.get("filename") + if fn is not None: + filenames.append(fn) + return filenames + + +def _strip_uri_scheme(ref: str) -> str: + """Strip a leading ``file://`` scheme if present (kept verbatim otherwise).""" + if ref.startswith("file://"): + return ref[len("file://") :] + return ref + + +def _classify_mesh_ref(ref: str, urdf_dir: Path) -> str: + """Classify a single mesh reference. + + Returns one of: ``"package"`` (package:// URI), ``"ok"`` (resolves on disk), + or ``"broken"`` (absolute/relative path that does not resolve). + """ + if ref.startswith("package://"): + return "package" + candidate = _strip_uri_scheme(ref) + path = Path(candidate) + if not path.is_absolute(): + path = urdf_dir / candidate + try: + exists = path.exists() + except OSError: + exists = False + return "ok" if exists else "broken" + + +def copy_robot_to_models(name: str, data_path: PathLike, dataset_name: str = "omnigibson-robot-assets") -> Path: + """Copy an imported robot from ``objects/robot//`` into ``models//`` (idempotent) so + ``REGISTERED_ROBOTS`` discovers it. The ``.yaml`` definition is placed there separately. + Returns the destination ``models//`` directory. + """ + src = Path(data_path) / dataset_name / "objects" / "robot" / name + dst = Path(data_path) / dataset_name / "models" / name + assert src.exists(), f"imported robot not found at {src} (run import_custom_robot.py first)" + dst.mkdir(parents=True, exist_ok=True) + for child in src.iterdir(): + target = dst / child.name + if child.is_dir(): + shutil.copytree(child, target, dirs_exist_ok=True) + else: + shutil.copy2(child, target) + return dst + + +def link_has_dedicated_collision(link_element: ET.Element) -> bool: + """True if the link ships a usable collision proxy: a ```` that is a primitive, or a + mesh whose file differs from the link's visual meshes. Such collisions are preserved on import; + otherwise (missing, or the same mesh as the visual) one must be generated. + """ + visual_mesh_files = { + mesh.get("filename") for vis in link_element.findall("visual") for mesh in vis.findall("geometry/mesh") + } + for col in link_element.findall("collision"): + geom = col.find("geometry/*") + if geom is None: + continue + if geom.tag != "mesh" or geom.get("filename") not in visual_mesh_files: + return True + return False + + +def override_joint_limits(tree: ET.ElementTree, limits: dict) -> int: + """Set ```` attributes on named joints (in place), repairing zeroed/degenerate limits that + make a joint non-drivable. ``limits`` maps ``joint_name -> {attr: value}``. Returns the count updated. + """ + root = tree.getroot() + updated = 0 + for joint in root.findall("joint"): + name = joint.get("name") + if name in limits: + limit_el = joint.find("limit") + if limit_el is None: + limit_el = ET.SubElement(joint, "limit") + for attr, value in limits[name].items(): + limit_el.set(attr, str(value)) + updated += 1 + return updated + + +def rewrite_mesh_paths(tree: ET.ElementTree, replacements) -> int: + """Apply ordered ``(old, new)`` substring replacements to every ```` (in place), + e.g. to turn ``package://`` URIs or broken relative paths into resolvable absolute paths. + Returns the count of references changed. + """ + root = tree.getroot() + updated = 0 + for mesh in root.iter("mesh"): + fn = mesh.get("filename") + if fn is None: + continue + new = fn + for old, repl in replacements: + new = new.replace(old, repl) + if new != fn: + mesh.set("filename", new) + updated += 1 + return updated + + +def strip_mimic_joints(tree: ET.ElementTree) -> int: + """Remove every ```` element (in place); returns the count removed. The importer writes no + DriveAPI on a mimic joint, leaving that finger non-drivable -- drive both fingers at runtime instead. + """ + root = tree.getroot() + removed = 0 + for joint in root.findall("joint"): + for mimic in joint.findall("mimic"): + joint.remove(mimic) + removed += 1 + return removed + + +def stage_meshes(tree: ET.ElementTree, dest_dir: PathLike, invalid_chars: str = " ()", replacement: str = "_") -> int: + """Copy every referenced mesh into ``dest_dir`` under a USD-safe basename (space/paren -> ``_``), + rewriting the references (in place); returns the number of files copied. Avoids the importer's + ill-formed-SdfPath failure on mesh filenames with spaces (it names geometry prims after the + basename). Run after `rewrite_mesh_paths` so refs resolve. Identical sources are copied + once; distinct sources colliding on a sanitized name get a numeric suffix. + """ + dest = Path(dest_dir) + dest.mkdir(parents=True, exist_ok=True) + root = tree.getroot() + + def _clean_base(name): + for ch in invalid_chars: + name = name.replace(ch, replacement) + return name + + src_to_dest: dict = {} # absolute source -> staged absolute path + used_names: dict = {} # staged basename -> source (collision detection) + copied = 0 + for mesh in root.iter("mesh"): + ref = mesh.get("filename") + if ref is None: + continue + src = Path(_strip_uri_scheme(ref)) + if str(src) in src_to_dest: + mesh.set("filename", src_to_dest[str(src)]) + continue + base = _clean_base(src.name) + # Disambiguate distinct sources that sanitize to the same basename. + if base in used_names and used_names[base] != str(src): + stem, suffix = Path(base).stem, Path(base).suffix + i = 1 + while f"{stem}_{i}{suffix}" in used_names: + i += 1 + base = f"{stem}_{i}{suffix}" + target = dest / base + if not src.exists(): + raise FileNotFoundError(f"Mesh file referenced by URDF does not exist: {src}") + shutil.copy2(src, target) + copied += 1 + used_names[base] = str(src) + src_to_dest[str(src)] = str(target) + mesh.set("filename", str(target)) + return copied + + +def sanitize_names(tree: ET.ElementTree, invalid_chars: str = " ()", replacement: str = "_") -> dict: + """Replace ``invalid_chars`` (space/paren) with ``replacement`` in every link/joint name and all + parent/child/mimic references (in place). The importer otherwise renames these silently, breaking + downstream name matching. Returns the ``{old: new}`` map so callers can update their own references. + """ + root = tree.getroot() + + def _clean(name): + if name is None: + return None + out = name + for ch in invalid_chars: + out = out.replace(ch, replacement) + return out + + renames: dict = {} + for link in root.findall("link"): + old = link.get("name") + new = _clean(old) + if new != old: + link.set("name", new) + renames[old] = new + for joint in root.findall("joint"): + old = joint.get("name") + new = _clean(old) + if new != old: + joint.set("name", new) + renames[old] = new + for tag in ("parent", "child"): + el = joint.find(tag) + if el is not None and el.get("link") is not None: + el.set("link", _clean(el.get("link"))) + mimic = joint.find("mimic") + if mimic is not None and mimic.get("joint") is not None: + mimic.set("joint", _clean(mimic.get("joint"))) + return renames + + +def set_joint_dynamics(tree: ET.ElementTree, joint_names, **attrs) -> int: + """Set ```` attributes (e.g. ``friction=0``) on named joints (in place); returns the count updated.""" + root = tree.getroot() + names = set(joint_names) + updated = 0 + for joint in root.findall("joint"): + if joint.get("name") in names: + dyn = joint.find("dynamics") + if dyn is None: + dyn = ET.SubElement(joint, "dynamics") + for attr, value in attrs.items(): + dyn.set(attr, str(value)) + updated += 1 + return updated + + +# Repair for Stretch sg3 gripper fingers shipped with zeroed limits (matches the OG stretch reference). +STRETCH_FINGER_LIMITS = { + "joint_gripper_finger_left": {"effort": 100, "lower": -0.6, "upper": 0.6, "velocity": 1.0}, + "joint_gripper_finger_right": {"effort": 100, "lower": -0.6, "upper": 0.6, "velocity": 1.0}, +} + +# Stretch wheel joints whose axle friction is zeroed to match the OG reference. +STRETCH_WHEEL_JOINTS = ["joint_left_wheel", "joint_right_wheel"] + + +def urdf_audit(urdf_path: PathLike) -> dict: + """Return a deterministic, GPU-free fact sheet for a URDF (XML-aware, so multi-line tags count + correctly). Non-resolving mesh paths are reported as ``broken`` (never raised); ``package://`` URIs + counted separately. Keys: ``n_links``, ``n_joints``, ``joint_type_counts``, ``mimic_joints``, + ``mesh_refs``, ``mesh_formats``, ``package_uris``, ``nonascii_paths``, ``broken_relative_paths``, + ``links_without_inertial``, ``root_link``. + """ + urdf_path = Path(urdf_path) + urdf_dir = urdf_path.parent + tree = ET.parse(urdf_path) + root = tree.getroot() + + links = list(root.findall("link")) + joints = list(root.findall("joint")) + + joint_type_counts: dict[str, int] = {} + mimic_joints = 0 + child_link_names: set[str] = set() + for joint in joints: + jtype = joint.get("type", "unknown") + joint_type_counts[jtype] = joint_type_counts.get(jtype, 0) + 1 + if joint.find("mimic") is not None: + mimic_joints += 1 + child_el = joint.find("child") + if child_el is not None and child_el.get("link") is not None: + child_link_names.add(child_el.get("link")) + + link_names = [link.get("name") for link in links if link.get("name") is not None] + links_without_inertial = sum(1 for link in links if link.find("inertial") is None) + + # The root link is the one never referenced as a joint's child. + root_candidates = [name for name in link_names if name not in child_link_names] + root_link: Optional[str] = root_candidates[0] if len(root_candidates) == 1 else None + + mesh_refs = _mesh_filenames(root) + mesh_formats: dict[str, int] = {} + package_uris = 0 + nonascii_paths = 0 + broken_relative_paths = 0 + for ref in mesh_refs: + ext = Path(_strip_uri_scheme(ref).split("?")[0]).suffix.lower() + if ext: + mesh_formats[ext] = mesh_formats.get(ext, 0) + 1 + if not _is_ascii(ref): + nonascii_paths += 1 + kind = _classify_mesh_ref(ref, urdf_dir) + if kind == "package": + package_uris += 1 + elif kind == "broken": + broken_relative_paths += 1 + + return { + "n_links": len(links), + "n_joints": len(joints), + "joint_type_counts": dict(sorted(joint_type_counts.items())), + "mimic_joints": mimic_joints, + "mesh_refs": len(mesh_refs), + "mesh_formats": dict(sorted(mesh_formats.items())), + "package_uris": package_uris, + "nonascii_paths": nonascii_paths, + "broken_relative_paths": broken_relative_paths, + "links_without_inertial": links_without_inertial, + "root_link": root_link, + } diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdfpy_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdfpy_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..27cf84d36dcfe6f94d7fed78f4d0df3dc7fd3cde --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdfpy_utils.py @@ -0,0 +1,4096 @@ +""" +Code directly adapted from https://github.com/mmatl/urdfpy +""" + +import copy +import os +import time +from collections import OrderedDict + +import networkx as nx +import numpy as np +import PIL +import six +import trimesh +from lxml import etree as ET + + +class URDFType(object): + """Abstract base class for all URDF types. + + This has useful class methods for automatic parsing/unparsing + of XML trees. + + There are three overridable class variables: + + - ``_ATTRIBS`` - This is a dictionary mapping attribute names to a tuple, + ``(type, required)`` where ``type`` is the Python type for the + attribute and ``required`` is a boolean stating whether the attribute + is required to be present. + - ``_ELEMENTS`` - This is a dictionary mapping element names to a tuple, + ``(type, required, multiple)`` where ``type`` is the Python type for the + element, ``required`` is a boolean stating whether the element + is required to be present, and ``multiple`` is a boolean indicating + whether multiple elements of this type could be present. + Elements are child nodes in the XML tree, and their type must be a + subclass of :class:`.URDFType`. + - ``_TAG`` - This is a string that represents the XML tag for the node + containing this type of object. + """ + + _ATTRIBS = {} # Map from attrib name to (type, required) + _ELEMENTS = {} # Map from element name to (type, required, multiple) + _TAG = "" # XML tag for this element + + def __init__(self): + pass + + @classmethod + def _parse_attrib(cls, val_type, val): + """Parse an XML attribute into a python value. + + Parameters + ---------- + val_type : :class:`type` + The type of value to create. + val : :class:`object` + The value to parse. + + Returns + ------- + val : :class:`object` + The parsed attribute. + """ + if val_type == np.ndarray: + val = np.fromstring(val, sep=" ") + else: + val = val_type(val) + return val + + @classmethod + def _parse_simple_attribs(cls, node): + """Parse all attributes in the _ATTRIBS array for this class. + + Parameters + ---------- + node : :class:`lxml.etree.Element` + The node to parse attributes for. + + Returns + ------- + kwargs : dict + Map from attribute name to value. If the attribute is not + required and is not present, that attribute's name will map to + ``None``. + """ + kwargs = {} + for a in cls._ATTRIBS: + t, r = cls._ATTRIBS[a] # t = type, r = required (bool) + if r: + try: + v = cls._parse_attrib(t, node.attrib[a]) + except Exception: + raise ValueError( + "Missing required attribute {} when parsing an object of type {}".format(a, cls.__name__) + ) + else: + v = None + if a in node.attrib: + v = cls._parse_attrib(t, node.attrib[a]) + kwargs[a] = v + return kwargs + + @classmethod + def _parse_simple_elements(cls, node, path): + """Parse all elements in the _ELEMENTS array from the children of + this node. + + Parameters + ---------- + node : :class:`lxml.etree.Element` + The node to parse children for. + path : str + The string path where the XML file is located (used for resolving + the location of mesh or image files). + + Returns + ------- + kwargs : dict + Map from element names to the :class:`URDFType` subclass (or list, + if ``multiple`` was set) created for that element. + """ + kwargs = {} + for a in cls._ELEMENTS: + t, r, m = cls._ELEMENTS[a] + if not m: + v = node.find(t._TAG) + if r or v is not None: + v = t._from_xml(v, path) + else: + vs = node.findall(t._TAG) + if len(vs) == 0 and r: + raise ValueError( + "Missing required subelement(s) of type {} when parsing an object of type {}".format( + t.__name__, cls.__name__ + ) + ) + v = [t._from_xml(n, path) for n in vs] + kwargs[a] = v + return kwargs + + @classmethod + def _parse(cls, node, path): + """Parse all elements and attributes in the _ELEMENTS and _ATTRIBS + arrays for a node. + + Parameters + ---------- + node : :class:`lxml.etree.Element` + The node to parse. + path : str + The string path where the XML file is located (used for resolving + the location of mesh or image files). + + Returns + ------- + kwargs : dict + Map from names to Python classes created from the attributes + and elements in the class arrays. + """ + kwargs = cls._parse_simple_attribs(node) + kwargs.update(cls._parse_simple_elements(node, path)) + return kwargs + + @classmethod + def _from_xml(cls, node, path): + """Create an instance of this class from an XML node. + + Parameters + ---------- + node : :class:`lxml.etree.Element` + The node to parse. + path : str + The string path where the XML file is located (used for resolving + the location of mesh or image files). + + Returns + ------- + obj : :class:`URDFType` + An instance of this class parsed from the node. + """ + return cls(**cls._parse(node, path)) + + def _unparse_attrib(self, val_type, val): + """Convert a Python value into a string for storage in an + XML attribute. + + Parameters + ---------- + val_type : :class:`type` + The type of the Python object. + val : :class:`object` + The actual value. + + Returns + ------- + s : str + The attribute string. + """ + if val_type == np.ndarray: + val = np.array2string(val)[1:-1] + else: + val = str(val) + return val + + def _unparse_simple_attribs(self, node): + """Convert all Python types from the _ATTRIBS array back into attributes + for an XML node. + + Parameters + ---------- + node : :class:`object` + The XML node to add the attributes to. + """ + for a in self._ATTRIBS: + t, r = self._ATTRIBS[a] + v = getattr(self, a, None) + if r or v is not None: + node.attrib[a] = self._unparse_attrib(t, v) + + def _unparse_simple_elements(self, node, path): + """Unparse all Python types from the _ELEMENTS array back into child + nodes of an XML node. + + Parameters + ---------- + node : :class:`object` + The XML node for this object. Elements will be added as children + of this node. + path : str + The string path where the XML file is being written to (used for + writing out meshes and image files). + """ + for a in self._ELEMENTS: + t, r, m = self._ELEMENTS[a] + v = getattr(self, a, None) + if not m: + if r or v is not None: + node.append(v._to_xml(node, path)) + else: + vs = v + for v in vs: + node.append(v._to_xml(node, path)) + + def _unparse(self, path): + """Create a node for this object and unparse all elements and + attributes in the class arrays. + + Parameters + ---------- + path : str + The string path where the XML file is being written to (used for + writing out meshes and image files). + + Returns + ------- + node : :class:`lxml.etree.Element` + The newly-created node. + """ + node = ET.Element(self._TAG) + self._unparse_simple_attribs(node) + self._unparse_simple_elements(node, path) + return node + + def _to_xml(self, parent, path): + """Create and return an XML node for this object. + + Parameters + ---------- + parent : :class:`lxml.etree.Element` + The parent node that this element will eventually be added to. + This base implementation doesn't use this information, but + classes that override this function may use it. + path : str + The string path where the XML file is being written to (used for + writing out meshes and image files). + + Returns + ------- + node : :class:`lxml.etree.Element` + The newly-created node. + """ + return self._unparse(path) + + +############################################################################### +# Link types +############################################################################### + + +class Box(URDFType): + """A rectangular prism whose center is at the local origin. + + Parameters + ---------- + size : (3,) float + The length, width, and height of the box in meters. + """ + + _ATTRIBS = {"size": (np.ndarray, True)} + _TAG = "box" + + def __init__(self, size): + self.size = size + self._meshes = [] + + @property + def size(self): + """(3,) float : The length, width, and height of the box in meters.""" + return self._size + + @size.setter + def size(self, value): + self._size = np.asanyarray(value).astype(np.float64) + self._meshes = [] + + @property + def meshes(self): + """list of :class:`~trimesh.base.Trimesh` : The triangular meshes + that represent this object. + """ + if len(self._meshes) == 0: + self._meshes = [trimesh.creation.box(extents=self.size)] + return self._meshes + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Box` + A deep copy. + """ + if scale is None: + scale = 1.0 + b = Box( + size=self.size.copy() * scale, + ) + return b + + +class Cylinder(URDFType): + """A cylinder whose center is at the local origin. + + Parameters + ---------- + radius : float + The radius of the cylinder in meters. + length : float + The length of the cylinder in meters. + """ + + _ATTRIBS = { + "radius": (float, True), + "length": (float, True), + } + _TAG = "cylinder" + + def __init__(self, radius, length): + self.radius = radius + self.length = length + self._meshes = [] + + @property + def radius(self): + """float : The radius of the cylinder in meters.""" + return self._radius + + @radius.setter + def radius(self, value): + self._radius = float(value) + self._meshes = [] + + @property + def length(self): + """float : The length of the cylinder in meters.""" + return self._length + + @length.setter + def length(self, value): + self._length = float(value) + self._meshes = [] + + @property + def meshes(self): + """list of :class:`~trimesh.base.Trimesh` : The triangular meshes + that represent this object. + """ + if len(self._meshes) == 0: + self._meshes = [trimesh.creation.cylinder(radius=self.radius, height=self.length)] + return self._meshes + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Cylinder` + A deep copy. + """ + if scale is None: + scale = 1.0 + if isinstance(scale, (list, np.ndarray)): + if scale[0] != scale[1]: + raise ValueError("Cannot rescale cylinder geometry with asymmetry in x/y") + c = Cylinder( + radius=self.radius * scale[0], + length=self.length * scale[2], + ) + else: + c = Cylinder( + radius=self.radius * scale, + length=self.length * scale, + ) + return c + + +class Sphere(URDFType): + """A sphere whose center is at the local origin. + + Parameters + ---------- + radius : float + The radius of the sphere in meters. + """ + + _ATTRIBS = { + "radius": (float, True), + } + _TAG = "sphere" + + def __init__(self, radius): + self.radius = radius + self._meshes = [] + + @property + def radius(self): + """float : The radius of the sphere in meters.""" + return self._radius + + @radius.setter + def radius(self, value): + self._radius = float(value) + self._meshes = [] + + @property + def meshes(self): + """list of :class:`~trimesh.base.Trimesh` : The triangular meshes + that represent this object. + """ + if len(self._meshes) == 0: + self._meshes = [trimesh.creation.icosphere(radius=self.radius)] + return self._meshes + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Sphere` + A deep copy. + """ + if scale is None: + scale = 1.0 + if isinstance(scale, (list, np.ndarray)): + if scale[0] != scale[1] or scale[0] != scale[2]: + raise ValueError("Spheres do not support non-uniform scaling!") + scale = scale[0] + s = Sphere( + radius=self.radius * scale, + ) + return s + + +class Mesh(URDFType): + """A triangular mesh object. + + Parameters + ---------- + filename : str + The path to the mesh that contains this object. This can be + relative to the top-level URDF or an absolute path. + scale : (3,) float, optional + The scaling value for the mesh along the XYZ axes. + If ``None``, assumes no scale is applied. + meshes : list of :class:`~trimesh.base.Trimesh` + A list of meshes that compose this mesh. + The list of meshes is useful for visual geometries that + might be composed of separate trimesh objects. + If not specified, the mesh is loaded from the file using trimesh. + """ + + _ATTRIBS = {"filename": (str, True), "scale": (np.ndarray, False)} + _TAG = "mesh" + + def __init__(self, filename, scale=None, meshes=None): + if meshes is None: + meshes = load_meshes(filename) + self.filename = filename + self.scale = scale + self.meshes = meshes + + @property + def filename(self): + """str : The path to the mesh file for this object.""" + return self._filename + + @filename.setter + def filename(self, value): + self._filename = value + + @property + def scale(self): + """(3,) float : A scaling for the mesh along its local XYZ axes.""" + return self._scale + + @scale.setter + def scale(self, value): + if value is not None: + value = np.asanyarray(value).astype(np.float64) + self._scale = value + + @property + def meshes(self): + """list of :class:`~trimesh.base.Trimesh` : The triangular meshes + that represent this object. + """ + return self._meshes + + @meshes.setter + def meshes(self, value): + if isinstance(value, six.string_types): + value = load_meshes(value) + elif isinstance(value, (list, tuple, set, np.ndarray)): + value = list(value) + if len(value) == 0: + raise ValueError("Mesh must have at least one trimesh.Trimesh") + for m in value: + if not isinstance(m, trimesh.Trimesh): + raise TypeError("Mesh requires a trimesh.Trimesh or a list of them") + elif isinstance(value, trimesh.Trimesh): + value = [value] + else: + raise TypeError("Mesh requires a trimesh.Trimesh") + self._meshes = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + + # Load the mesh, combining collision geometry meshes but keeping + # visual ones separate to preserve colors and textures + fn = get_filename(path, kwargs["filename"]) + combine = node.getparent().getparent().tag == Collision._TAG + meshes = load_meshes(fn) + if combine: + # Delete visuals for simplicity + for m in meshes: + m.visual = trimesh.visual.ColorVisuals(mesh=m) + meshes = [meshes[0] + meshes[1:]] + kwargs["meshes"] = meshes + + return Mesh(**kwargs) + + def _to_xml(self, parent, path): + # Get the filename + fn = get_filename(path, self.filename, makedirs=True) + + # Export the meshes as a single file + meshes = self.meshes + if len(meshes) == 1: + meshes = meshes[0] + elif os.path.splitext(fn)[1] == ".glb": + meshes = trimesh.scene.Scene(geometry=meshes) + trimesh.exchange.export.export_mesh(meshes, fn) + + # Unparse the node + node = self._unparse(path) + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Sphere` + A deep copy. + """ + meshes = [m.copy() for m in self.meshes] + if scale is not None: + sm = np.eye(4) + if isinstance(scale, (list, np.ndarray)): + sm[:3, :3] = np.diag(scale) + else: + sm[:3, :3] = np.diag(np.repeat(scale, 3)) + for i, m in enumerate(meshes): + meshes[i] = m.apply_transform(sm) + base, fn = os.path.split(self.filename) + fn = "{}{}".format(prefix, self.filename) + m = Mesh( + filename=os.path.join(base, fn), + scale=(self.scale.copy() if self.scale is not None else None), + meshes=meshes, + ) + return m + + +class Geometry(URDFType): + """A wrapper for all geometry types. + + Only one of the following values can be set, all others should be set + to ``None``. + + Parameters + ---------- + box : :class:`.Box`, optional + Box geometry. + cylinder : :class:`.Cylinder` + Cylindrical geometry. + sphere : :class:`.Sphere` + Spherical geometry. + mesh : :class:`.Mesh` + Mesh geometry. + """ + + _ELEMENTS = { + "box": (Box, False, False), + "cylinder": (Cylinder, False, False), + "sphere": (Sphere, False, False), + "mesh": (Mesh, False, False), + } + _TAG = "geometry" + + def __init__(self, box=None, cylinder=None, sphere=None, mesh=None): + if box is None and cylinder is None and sphere is None and mesh is None: + raise ValueError("At least one geometry element must be set") + self.box = box + self.cylinder = cylinder + self.sphere = sphere + self.mesh = mesh + + @property + def box(self): + """:class:`.Box` : Box geometry.""" + return self._box + + @box.setter + def box(self, value): + if value is not None and not isinstance(value, Box): + raise TypeError("Expected Box type") + self._box = value + + @property + def cylinder(self): + """:class:`.Cylinder` : Cylinder geometry.""" + return self._cylinder + + @cylinder.setter + def cylinder(self, value): + if value is not None and not isinstance(value, Cylinder): + raise TypeError("Expected Cylinder type") + self._cylinder = value + + @property + def sphere(self): + """:class:`.Sphere` : Spherical geometry.""" + return self._sphere + + @sphere.setter + def sphere(self, value): + if value is not None and not isinstance(value, Sphere): + raise TypeError("Expected Sphere type") + self._sphere = value + + @property + def mesh(self): + """:class:`.Mesh` : Mesh geometry.""" + return self._mesh + + @mesh.setter + def mesh(self, value): + if value is not None and not isinstance(value, Mesh): + raise TypeError("Expected Mesh type") + self._mesh = value + + @property + def geometry(self): + """:class:`.Box`, :class:`.Cylinder`, :class:`.Sphere`, or + :class:`.Mesh` : The valid geometry element. + """ + if self.box is not None: + return self.box + if self.cylinder is not None: + return self.cylinder + if self.sphere is not None: + return self.sphere + if self.mesh is not None: + return self.mesh + return None + + @property + def meshes(self): + """list of :class:`~trimesh.base.Trimesh` : The geometry's triangular + mesh representation(s). + """ + return self.geometry.meshes + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Geometry` + A deep copy. + """ + v = Geometry( + box=(self.box.copy(prefix=prefix, scale=scale) if self.box else None), + cylinder=(self.cylinder.copy(prefix=prefix, scale=scale) if self.cylinder else None), + sphere=(self.sphere.copy(prefix=prefix, scale=scale) if self.sphere else None), + mesh=(self.mesh.copy(prefix=prefix, scale=scale) if self.mesh else None), + ) + return v + + +class Texture(URDFType): + """An image-based texture. + + Parameters + ---------- + filename : str + The path to the image that contains this texture. This can be + relative to the top-level URDF or an absolute path. + image : :class:`PIL.Image.Image`, optional + The image for the texture. + If not specified, it is loaded automatically from the filename. + """ + + _ATTRIBS = {"filename": (str, True)} + _TAG = "texture" + + def __init__(self, filename, image=None): + if image is None: + image = PIL.image.open(filename) + self.filename = filename + self.image = image + + @property + def filename(self): + """str : Path to the image for this texture.""" + return self._filename + + @filename.setter + def filename(self, value): + self._filename = str(value) + + @property + def image(self): + """:class:`PIL.Image.Image` : The image for this texture.""" + return self._image + + @image.setter + def image(self, value): + if isinstance(value, str): + value = PIL.Image.open(value) + if isinstance(value, np.ndarray): + value = PIL.Image.fromarray(value) + elif not isinstance(value, PIL.Image.Image): + raise ValueError("Texture only supports numpy arrays or PIL images") + self._image = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + + # Load image + fn = get_filename(path, kwargs["filename"]) + kwargs["image"] = PIL.Image.open(fn) + + return Texture(**kwargs) + + def _to_xml(self, parent, path): + # Save the image + filepath = get_filename(path, self.filename, makedirs=True) + self.image.save(filepath) + + return self._unparse(path) + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Texture` + A deep copy. + """ + v = Texture(filename=self.filename, image=self.image.copy()) + return v + + +class Material(URDFType): + """A material for some geometry. + + Parameters + ---------- + name : str + The name of the material. + color : (4,) float, optional + The RGBA color of the material in the range [0,1]. + texture : :class:`.Texture`, optional + A texture for the material. + """ + + _ATTRIBS = {"name": (str, True)} + _ELEMENTS = { + "texture": (Texture, False, False), + } + _TAG = "material" + + def __init__(self, name, color=None, texture=None): + self.name = name + self.color = color + self.texture = texture + + @property + def name(self): + """str : The name of the material.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def color(self): + """(4,) float : The RGBA color of the material, in the range [0,1].""" + return self._color + + @color.setter + def color(self, value): + if value is not None: + value = np.asanyarray(value).astype(np.float64) + value = np.clip(value, 0.0, 1.0) + if value.shape != (4,): + raise ValueError("Color must be a (4,) float") + self._color = value + + @property + def texture(self): + """:class:`.Texture` : The texture for the material.""" + return self._texture + + @texture.setter + def texture(self, value): + if value is not None: + if isinstance(value, six.string_types): + image = PIL.Image.open(value) + value = Texture(filename=value, image=image) + elif not isinstance(value, Texture): + raise ValueError("Invalid type for texture -- expect path to image or Texture") + self._texture = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + + # Extract the color -- it's weirdly an attribute of a subelement + color = node.find("color") + if color is not None: + color = np.fromstring(color.attrib["rgba"], sep=" ", dtype=np.float64) + kwargs["color"] = color + + return Material(**kwargs) + + def _to_xml(self, parent, path): + # Simplify materials by collecting them at the top level. + + # For top-level elements, save the full material specification + if parent.tag == "robot": + node = self._unparse(path) + if self.color is not None: + color = ET.Element("color") + color.attrib["rgba"] = np.array2string(self.color)[1:-1] + node.append(color) + + # For non-top-level elements just save the material with a name + else: + node = ET.Element("material") + node.attrib["name"] = self.name + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy of the material with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.Material` + A deep copy of the material. + """ + return Material(name="{}{}".format(prefix, self.name), color=self.color, texture=self.texture) + + +class Collision(URDFType): + """Collision properties of a link. + + Parameters + ---------- + geometry : :class:`.Geometry` + The geometry of the element + name : str, optional + The name of the collision geometry. + origin : (4,4) float, optional + The pose of the collision element relative to the link frame. + Defaults to identity. + """ + + _ATTRIBS = {"name": (str, False)} + _ELEMENTS = { + "geometry": (Geometry, True, False), + } + _TAG = "collision" + + def __init__(self, name, origin, geometry): + self.geometry = geometry + self.name = name + self.origin = origin + + @property + def geometry(self): + """:class:`.Geometry` : The geometry of this element.""" + return self._geometry + + @geometry.setter + def geometry(self, value): + if not isinstance(value, Geometry): + raise TypeError("Must set geometry with Geometry object") + self._geometry = value + + @property + def name(self): + """str : The name of this collision element.""" + return self._name + + @name.setter + def name(self, value): + if value is not None: + value = str(value) + self._name = value + + @property + def origin(self): + """(4,4) float : The pose of this element relative to the link frame.""" + return self._origin + + @origin.setter + def origin(self, value): + self._origin = configure_origin(value) + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + kwargs["origin"] = parse_origin(node) + return Collision(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + node.append(unparse_origin(self.origin)) + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.Visual` + A deep copy of the visual. + """ + origin = self.origin.copy() + if scale is not None: + if not isinstance(scale, (list, np.ndarray)): + scale = np.repeat(scale, 3) + origin[:3, 3] *= scale + return Collision( + name="{}{}".format(prefix, self.name), + origin=origin, + geometry=self.geometry.copy(prefix=prefix, scale=scale), + ) + + +class Visual(URDFType): + """Visual properties of a link. + + Parameters + ---------- + geometry : :class:`.Geometry` + The geometry of the element + name : str, optional + The name of the visual geometry. + origin : (4,4) float, optional + The pose of the visual element relative to the link frame. + Defaults to identity. + material : :class:`.Material`, optional + The material of the element. + """ + + _ATTRIBS = {"name": (str, False)} + _ELEMENTS = { + "geometry": (Geometry, True, False), + "material": (Material, False, False), + } + _TAG = "visual" + + def __init__(self, geometry, name=None, origin=None, material=None): + self.geometry = geometry + self.name = name + self.origin = origin + self.material = material + + @property + def geometry(self): + """:class:`.Geometry` : The geometry of this element.""" + return self._geometry + + @geometry.setter + def geometry(self, value): + if not isinstance(value, Geometry): + raise TypeError("Must set geometry with Geometry object") + self._geometry = value + + @property + def name(self): + """str : The name of this visual element.""" + return self._name + + @name.setter + def name(self, value): + if value is not None: + value = str(value) + self._name = value + + @property + def origin(self): + """(4,4) float : The pose of this element relative to the link frame.""" + return self._origin + + @origin.setter + def origin(self, value): + self._origin = configure_origin(value) + + @property + def material(self): + """:class:`.Material` : The material for this element.""" + return self._material + + @material.setter + def material(self, value): + if value is not None: + if not isinstance(value, Material): + raise TypeError("Must set material with Material object") + self._material = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + kwargs["origin"] = parse_origin(node) + return Visual(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + node.append(unparse_origin(self.origin)) + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.Visual` + A deep copy of the visual. + """ + origin = self.origin.copy() + if scale is not None: + if not isinstance(scale, (list, np.ndarray)): + scale = np.repeat(scale, 3) + origin[:3, 3] *= scale + return Visual( + geometry=self.geometry.copy(prefix=prefix, scale=scale), + name="{}{}".format(prefix, self.name), + origin=origin, + material=(self.material.copy(prefix=prefix) if self.material else None), + ) + + +class Inertial(URDFType): + """The inertial properties of a link. + + Parameters + ---------- + mass : float + The mass of the link in kilograms. + inertia : (3,3) float + The 3x3 symmetric rotational inertia matrix. + origin : (4,4) float, optional + The pose of the inertials relative to the link frame. + Defaults to identity if not specified. + """ + + _TAG = "inertial" + + def __init__(self, mass, inertia, origin=None): + self.mass = mass + self.inertia = inertia + self.origin = origin + + @property + def mass(self): + """float : The mass of the link in kilograms.""" + return self._mass + + @mass.setter + def mass(self, value): + self._mass = float(value) + + @property + def inertia(self): + """(3,3) float : The 3x3 symmetric rotational inertia matrix.""" + return self._inertia + + @inertia.setter + def inertia(self, value): + value = np.asanyarray(value).astype(np.float64) + if not np.allclose(value, value.T): + raise ValueError("Inertia must be a symmetric matrix") + self._inertia = value + + @property + def origin(self): + """(4,4) float : The pose of the inertials relative to the link frame.""" + return self._origin + + @origin.setter + def origin(self, value): + self._origin = configure_origin(value) + + @classmethod + def _from_xml(cls, node, path): + origin = parse_origin(node) + mass = float(node.find("mass").attrib["value"]) + n = node.find("inertia") + xx = float(n.attrib["ixx"]) + xy = float(n.attrib["ixy"]) + xz = float(n.attrib["ixz"]) + yy = float(n.attrib["iyy"]) + yz = float(n.attrib["iyz"]) + zz = float(n.attrib["izz"]) + inertia = np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]], dtype=np.float64) + return Inertial(mass=mass, inertia=inertia, origin=origin) + + def _to_xml(self, parent, path): + node = ET.Element("inertial") + node.append(unparse_origin(self.origin)) + mass = ET.Element("mass") + mass.attrib["value"] = str(self.mass) + node.append(mass) + inertia = ET.Element("inertia") + inertia.attrib["ixx"] = str(self.inertia[0, 0]) + inertia.attrib["ixy"] = str(self.inertia[0, 1]) + inertia.attrib["ixz"] = str(self.inertia[0, 2]) + inertia.attrib["iyy"] = str(self.inertia[1, 1]) + inertia.attrib["iyz"] = str(self.inertia[1, 2]) + inertia.attrib["izz"] = str(self.inertia[2, 2]) + node.append(inertia) + return node + + def copy(self, prefix="", mass=None, origin=None, inertia=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.Inertial` + A deep copy of the visual. + """ + if mass is None: + mass = self.mass + if origin is None: + origin = self.origin.copy() + if inertia is None: + inertia = self.inertia.copy() + return Inertial( + mass=mass, + inertia=inertia, + origin=origin, + ) + + +############################################################################### +# Joint types +############################################################################### + + +class JointCalibration(URDFType): + """The reference positions of the joint. + + Parameters + ---------- + rising : float, optional + When the joint moves in a positive direction, this position will + trigger a rising edge. + falling : + When the joint moves in a positive direction, this position will + trigger a falling edge. + """ + + _ATTRIBS = {"rising": (float, False), "falling": (float, False)} + _TAG = "calibration" + + def __init__(self, rising=None, falling=None): + self.rising = rising + self.falling = falling + + @property + def rising(self): + """float : description.""" + return self._rising + + @rising.setter + def rising(self, value): + if value is not None: + value = float(value) + self._rising = value + + @property + def falling(self): + """float : description.""" + return self._falling + + @falling.setter + def falling(self, value): + if value is not None: + value = float(value) + self._falling = value + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.JointCalibration` + A deep copy of the visual. + """ + return JointCalibration( + rising=self.rising, + falling=self.falling, + ) + + +class JointDynamics(URDFType): + """The dynamic properties of the joint. + + Parameters + ---------- + damping : float + The damping value of the joint (Ns/m for prismatic joints, + Nms/rad for revolute). + friction : float + The static friction value of the joint (N for prismatic joints, + Nm for revolute). + """ + + _ATTRIBS = { + "damping": (float, False), + "friction": (float, False), + } + _TAG = "dynamics" + + def __init__(self, damping, friction): + self.damping = damping + self.friction = friction + + @property + def damping(self): + """float : The damping value of the joint.""" + return self._damping + + @damping.setter + def damping(self, value): + if value is not None: + value = float(value) + self._damping = value + + @property + def friction(self): + """float : The static friction value of the joint.""" + return self._friction + + @friction.setter + def friction(self, value): + if value is not None: + value = float(value) + self._friction = value + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.JointDynamics` + A deep copy of the visual. + """ + return JointDynamics( + damping=self.damping, + friction=self.friction, + ) + + +class JointLimit(URDFType): + """The limits of the joint. + + Parameters + ---------- + effort : float + The maximum joint effort (N for prismatic joints, Nm for revolute). + velocity : float + The maximum joint velocity (m/s for prismatic joints, rad/s for + revolute). + lower : float, optional + The lower joint limit (m for prismatic joints, rad for revolute). + upper : float, optional + The upper joint limit (m for prismatic joints, rad for revolute). + """ + + _ATTRIBS = { + "effort": (float, False), + "velocity": (float, False), + "lower": (float, False), + "upper": (float, False), + } + _TAG = "limit" + + def __init__(self, effort=None, velocity=None, lower=None, upper=None): + self.effort = effort + self.velocity = velocity + self.lower = lower + self.upper = upper + + @property + def effort(self): + """float : The maximum joint effort.""" + return self._effort + + @effort.setter + def effort(self, value): + self._effort = float(value) if value else 0.0 + + @property + def velocity(self): + """float : The maximum joint velocity.""" + return self._velocity + + @velocity.setter + def velocity(self, value): + self._velocity = float(value) if value else 0.0 + + @property + def lower(self): + """float : The lower joint limit.""" + return self._lower + + @lower.setter + def lower(self, value): + if value is not None: + value = float(value) + self._lower = value + + @property + def upper(self): + """float : The upper joint limit.""" + return self._upper + + @upper.setter + def upper(self, value): + if value is not None: + value = float(value) + self._upper = value + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.JointLimit` + A deep copy of the visual. + """ + return JointLimit( + effort=self.effort, + velocity=self.velocity, + lower=self.lower, + upper=self.upper, + ) + + +class JointMimic(URDFType): + """A mimicry tag for a joint, which forces its configuration to + mimic another joint's. + + This joint's configuration value is set equal to + ``multiplier * other_joint_cfg + offset``. + + Parameters + ---------- + joint : str + The name of the joint to mimic. + multiplier : float + The joint configuration multiplier. Defaults to 1.0. + offset : float, optional + The joint configuration offset. Defaults to 0.0. + """ + + _ATTRIBS = { + "joint": (str, True), + "multiplier": (float, False), + "offset": (float, False), + } + _TAG = "mimic" + + def __init__(self, joint, multiplier=None, offset=None): + self.joint = joint + self.multiplier = multiplier + self.offset = offset + + @property + def joint(self): + """float : The name of the joint to mimic.""" + return self._joint + + @joint.setter + def joint(self, value): + self._joint = str(value) + + @property + def multiplier(self): + """float : The multiplier for the joint configuration.""" + return self._multiplier + + @multiplier.setter + def multiplier(self, value): + if value is not None: + value = float(value) + else: + value = 1.0 + self._multiplier = value + + @property + def offset(self): + """float : The offset for the joint configuration""" + return self._offset + + @offset.setter + def offset(self, value): + if value is not None: + value = float(value) + else: + value = 0.0 + self._offset = value + + def copy(self, prefix="", scale=None): + """Create a deep copy of the joint mimic with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.JointMimic` + A deep copy of the joint mimic. + """ + return JointMimic(joint="{}{}".format(prefix, self.joint), multiplier=self.multiplier, offset=self.offset) + + +class SafetyController(URDFType): + """A controller for joint movement safety. + + Parameters + ---------- + k_velocity : float + An attribute specifying the relation between the effort and velocity + limits. + k_position : float, optional + An attribute specifying the relation between the position and velocity + limits. Defaults to 0.0. + soft_lower_limit : float, optional + The lower joint boundary where the safety controller kicks in. + Defaults to 0.0. + soft_upper_limit : float, optional + The upper joint boundary where the safety controller kicks in. + Defaults to 0.0. + """ + + _ATTRIBS = { + "k_velocity": (float, True), + "k_position": (float, False), + "soft_lower_limit": (float, False), + "soft_upper_limit": (float, False), + } + _TAG = "safety_controller" + + def __init__(self, k_velocity, k_position=None, soft_lower_limit=None, soft_upper_limit=None): + self.k_velocity = k_velocity + self.k_position = k_position + self.soft_lower_limit = soft_lower_limit + self.soft_upper_limit = soft_upper_limit + + @property + def soft_lower_limit(self): + """float : The soft lower limit where the safety controller kicks in.""" + return self._soft_lower_limit + + @soft_lower_limit.setter + def soft_lower_limit(self, value): + if value is not None: + value = float(value) + else: + value = 0.0 + self._soft_lower_limit = value + + @property + def soft_upper_limit(self): + """float : The soft upper limit where the safety controller kicks in.""" + return self._soft_upper_limit + + @soft_upper_limit.setter + def soft_upper_limit(self, value): + if value is not None: + value = float(value) + else: + value = 0.0 + self._soft_upper_limit = value + + @property + def k_position(self): + """float : A relation between the position and velocity limits.""" + return self._k_position + + @k_position.setter + def k_position(self, value): + if value is not None: + value = float(value) + else: + value = 0.0 + self._k_position = value + + @property + def k_velocity(self): + """float : A relation between the effort and velocity limits.""" + return self._k_velocity + + @k_velocity.setter + def k_velocity(self, value): + self._k_velocity = float(value) + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.SafetyController` + A deep copy of the visual. + """ + return SafetyController( + k_velocity=self.k_velocity, + k_position=self.k_position, + soft_lower_limit=self.soft_lower_limit, + soft_upper_limit=self.soft_upper_limit, + ) + + +############################################################################### +# Transmission types +############################################################################### + + +class Actuator(URDFType): + """An actuator. + + Parameters + ---------- + name : str + The name of this actuator. + mechanicalReduction : str, optional + A specifier for the mechanical reduction at the joint/actuator + transmission. + hardwareInterfaces : list of str, optional + The supported hardware interfaces to the actuator. + """ + + _ATTRIBS = { + "name": (str, True), + } + _TAG = "actuator" + + def __init__(self, name, mechanicalReduction=None, hardwareInterfaces=None): + self.name = name + self.mechanicalReduction = mechanicalReduction + self.hardwareInterfaces = hardwareInterfaces + + @property + def name(self): + """str : The name of this actuator.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def mechanicalReduction(self): + """str : A specifier for the type of mechanical reduction.""" + return self._mechanicalReduction + + @mechanicalReduction.setter + def mechanicalReduction(self, value): + if value is not None: + value = str(value) + self._mechanicalReduction = value + + @property + def hardwareInterfaces(self): + """list of str : The supported hardware interfaces.""" + return self._hardwareInterfaces + + @hardwareInterfaces.setter + def hardwareInterfaces(self, value): + if value is None: + value = [] + else: + value = list(value) + for i, v in enumerate(value): + value[i] = str(v) + self._hardwareInterfaces = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + mr = node.find("mechanicalReduction") + if mr is not None: + mr = float(mr.text) + kwargs["mechanicalReduction"] = mr + hi = node.findall("hardwareInterface") + if len(hi) > 0: + hi = [h.text for h in hi] + kwargs["hardwareInterfaces"] = hi + return Actuator(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + if self.mechanicalReduction is not None: + mr = ET.Element("mechanicalReduction") + mr.text = str(self.mechanicalReduction) + node.append(mr) + if len(self.hardwareInterfaces) > 0: + for hi in self.hardwareInterfaces: + h = ET.Element("hardwareInterface") + h.text = hi + node.append(h) + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy of the visual with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.Actuator` + A deep copy of the visual. + """ + return Actuator( + name="{}{}".format(prefix, self.name), + mechanicalReduction=self.mechanicalReduction, + hardwareInterfaces=self.hardwareInterfaces.copy(), + ) + + +class TransmissionJoint(URDFType): + """A transmission joint specification. + + Parameters + ---------- + name : str + The name of this actuator. + hardwareInterfaces : list of str, optional + The supported hardware interfaces to the actuator. + """ + + _ATTRIBS = { + "name": (str, True), + } + _TAG = "joint" + + def __init__(self, name, hardwareInterfaces): + self.name = name + self.hardwareInterfaces = hardwareInterfaces + + @property + def name(self): + """str : The name of this transmission joint.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def hardwareInterfaces(self): + """list of str : The supported hardware interfaces.""" + return self._hardwareInterfaces + + @hardwareInterfaces.setter + def hardwareInterfaces(self, value): + if value is None: + value = [] + else: + value = list(value) + for i, v in enumerate(value): + value[i] = str(v) + self._hardwareInterfaces = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + hi = node.findall("hardwareInterface") + if len(hi) > 0: + hi = [h.text for h in hi] + kwargs["hardwareInterfaces"] = hi + return TransmissionJoint(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + if len(self.hardwareInterfaces) > 0: + for hi in self.hardwareInterfaces: + h = ET.Element("hardwareInterface") + h.text = hi + node.append(h) + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.TransmissionJoint` + A deep copy. + """ + return TransmissionJoint( + name="{}{}".format(prefix, self.name), + hardwareInterfaces=self.hardwareInterfaces.copy(), + ) + + +############################################################################### +# Top-level types +############################################################################### + + +class Transmission(URDFType): + """An element that describes the relationship between an actuator and a + joint. + + Parameters + ---------- + name : str + The name of this transmission. + trans_type : str + The type of this transmission. + joints : list of :class:`.TransmissionJoint` + The joints connected to this transmission. + actuators : list of :class:`.Actuator` + The actuators connected to this transmission. + """ + + _ATTRIBS = { + "name": (str, True), + } + _ELEMENTS = { + "joints": (TransmissionJoint, True, True), + "actuators": (Actuator, True, True), + } + _TAG = "transmission" + + def __init__(self, name, trans_type, joints=None, actuators=None): + self.name = name + self.trans_type = trans_type + self.joints = joints + self.actuators = actuators + + @property + def name(self): + """str : The name of this transmission.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def trans_type(self): + """str : The type of this transmission.""" + return self._trans_type + + @trans_type.setter + def trans_type(self, value): + self._trans_type = str(value) + + @property + def joints(self): + """:class:`.TransmissionJoint` : The joints the transmission is + connected to. + """ + return self._joints + + @joints.setter + def joints(self, value): + if value is None: + value = [] + else: + value = list(value) + for v in value: + if not isinstance(v, TransmissionJoint): + raise TypeError("Joints expects a list of TransmissionJoint") + self._joints = value + + @property + def actuators(self): + """:class:`.Actuator` : The actuators the transmission is connected to.""" + return self._actuators + + @actuators.setter + def actuators(self, value): + if value is None: + value = [] + else: + value = list(value) + for v in value: + if not isinstance(v, Actuator): + raise TypeError("Actuators expects a list of Actuator") + self._actuators = value + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + kwargs["trans_type"] = node.find("type").text + return Transmission(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + ttype = ET.Element("type") + ttype.text = self.trans_type + node.append(ttype) + return node + + def copy(self, prefix="", scale=None): + """Create a deep copy with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all names. + + Returns + ------- + :class:`.Transmission` + A deep copy. + """ + return Transmission( + name="{}{}".format(prefix, self.name), + trans_type=self.trans_type, + joints=[j.copy(prefix) for j in self.joints], + actuators=[a.copy(prefix) for a in self.actuators], + ) + + +class Joint(URDFType): + """A connection between two links. + + There are several types of joints, including: + + - ``fixed`` - a joint that cannot move. + - ``prismatic`` - a joint that slides along the joint axis. + - ``revolute`` - a hinge joint that rotates about the axis with a limited + range of motion. + - ``continuous`` - a hinge joint that rotates about the axis with an + unlimited range of motion. + - ``planar`` - a joint that moves in the plane orthogonal to the axis. + - ``floating`` - a joint that can move in 6DoF. + + Parameters + ---------- + name : str + The name of this joint. + parent : str + The name of the parent link of this joint. + child : str + The name of the child link of this joint. + joint_type : str + The type of the joint. Must be one of :obj:`.Joint.TYPES`. + axis : (3,) float, optional + The axis of the joint specified in joint frame. Defaults to + ``[1,0,0]``. + origin : (4,4) float, optional + The pose of the child link with respect to the parent link's frame. + The joint frame is defined to be coincident with the child link's + frame, so this is also the pose of the joint frame with respect to + the parent link's frame. + limit : :class:`.JointLimit`, optional + Limit for the joint. Only required for revolute and prismatic + joints. + dynamics : :class:`.JointDynamics`, optional + Dynamics for the joint. + safety_controller : :class`.SafetyController`, optional + The safety controller for this joint. + calibration : :class:`.JointCalibration`, optional + Calibration information for the joint. + mimic : :class:`JointMimic`, optional + Joint mimicry information. + """ + + TYPES = ["fixed", "prismatic", "revolute", "continuous", "floating", "planar"] + _ATTRIBS = { + "name": (str, True), + } + _ELEMENTS = { + "dynamics": (JointDynamics, False, False), + "limit": (JointLimit, False, False), + "mimic": (JointMimic, False, False), + "safety_controller": (SafetyController, False, False), + "calibration": (JointCalibration, False, False), + } + _TAG = "joint" + + def __init__( + self, + name, + joint_type, + parent, + child, + axis=None, + origin=None, + limit=None, + dynamics=None, + safety_controller=None, + calibration=None, + mimic=None, + ): + self.name = name + self.parent = parent + self.child = child + self.joint_type = joint_type + self.axis = axis + self.origin = origin + self.limit = limit + self.dynamics = dynamics + self.safety_controller = safety_controller + self.calibration = calibration + self.mimic = mimic + + @property + def name(self): + """str : Name for this joint.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def joint_type(self): + """str : The type of this joint.""" + return self._joint_type + + @joint_type.setter + def joint_type(self, value): + value = str(value) + if value not in Joint.TYPES: + raise ValueError("Unsupported joint type {}".format(value)) + self._joint_type = value + + @property + def parent(self): + """str : The name of the parent link.""" + return self._parent + + @parent.setter + def parent(self, value): + self._parent = str(value) + + @property + def child(self): + """str : The name of the child link.""" + return self._child + + @child.setter + def child(self, value): + self._child = str(value) + + @property + def axis(self): + """(3,) float : The joint axis in the joint frame.""" + return self._axis + + @axis.setter + def axis(self, value): + if value is None: + value = np.array([1.0, 0.0, 0.0], dtype=np.float64) + elif np.linalg.norm(value) < 1e-4: + value = np.array([1.0, 0.0, 0.0], dtype=np.float64) + else: + value = np.asanyarray(value, dtype=np.float64) + if value.shape != (3,): + raise ValueError("Invalid shape for axis, should be (3,)") + value = value / np.linalg.norm(value) + self._axis = value + + @property + def origin(self): + """(4,4) float : The pose of child and joint frames relative to the + parent link's frame. + """ + return self._origin + + @origin.setter + def origin(self, value): + self._origin = configure_origin(value) + + @property + def limit(self): + """:class:`.JointLimit` : The limits for this joint.""" + return self._limit + + @limit.setter + def limit(self, value): + if value is None: + if self.joint_type in ["prismatic", "revolute"]: + raise ValueError("Require joint limit for prismatic and revolute joints") + elif not isinstance(value, JointLimit): + raise TypeError("Expected JointLimit type") + self._limit = value + + @property + def dynamics(self): + """:class:`.JointDynamics` : The dynamics for this joint.""" + return self._dynamics + + @dynamics.setter + def dynamics(self, value): + if value is not None: + if not isinstance(value, JointDynamics): + raise TypeError("Expected JointDynamics type") + self._dynamics = value + + @property + def safety_controller(self): + """:class:`.SafetyController` : The safety controller for this joint.""" + return self._safety_controller + + @safety_controller.setter + def safety_controller(self, value): + if value is not None: + if not isinstance(value, SafetyController): + raise TypeError("Expected SafetyController type") + self._safety_controller = value + + @property + def calibration(self): + """:class:`.JointCalibration` : The calibration for this joint.""" + return self._calibration + + @calibration.setter + def calibration(self, value): + if value is not None: + if not isinstance(value, JointCalibration): + raise TypeError("Expected JointCalibration type") + self._calibration = value + + @property + def mimic(self): + """:class:`.JointMimic` : The mimic for this joint.""" + return self._mimic + + @mimic.setter + def mimic(self, value): + if value is not None: + if not isinstance(value, JointMimic): + raise TypeError("Expected JointMimic type") + self._mimic = value + + def is_valid(self, cfg): + """Check if the provided configuration value is valid for this joint. + + Parameters + ---------- + cfg : float, (2,) float, (6,) float, or (4,4) float + The configuration of the joint. + + Returns + ------- + is_valid : bool + True if the configuration is valid, and False otherwise. + """ + if self.joint_type not in ["fixed", "revolute"]: + return True + if self.joint_limit is None: + return True + cfg = float(cfg) + lower = -np.infty + upper = np.infty + if self.limit.lower is not None: + lower = self.limit.lower + if self.limit.upper is not None: + upper = self.limit.upper + return cfg >= lower and cfg <= upper + + def get_child_pose(self, cfg=None): + """Computes the child pose relative to a parent pose for a given + configuration value. + + Parameters + ---------- + cfg : float, (2,) float, (6,) float, or (4,4) float + The configuration values for this joint. They are interpreted + based on the joint type as follows: + + - ``fixed`` - not used. + - ``prismatic`` - a translation along the axis in meters. + - ``revolute`` - a rotation about the axis in radians. + - ``continuous`` - a rotation about the axis in radians. + - ``planar`` - the x and y translation values in the plane. + - ``floating`` - the xyz values followed by the rpy values, + or a (4,4) matrix. + + If ``cfg`` is ``None``, then this just returns the joint pose. + + Returns + ------- + pose : (4,4) float + The pose of the child relative to the parent. + """ + if cfg is None: + return self.origin + elif self.joint_type == "fixed": + return self.origin + elif self.joint_type in ["revolute", "continuous"]: + if cfg is None: + cfg = 0.0 + else: + cfg = float(cfg) + R = trimesh.transformations.rotation_matrix(cfg, self.axis) + return self.origin.dot(R) + elif self.joint_type == "prismatic": + if cfg is None: + cfg = 0.0 + else: + cfg = float(cfg) + translation = np.eye(4, dtype=np.float64) + translation[:3, 3] = self.axis * cfg + return self.origin.dot(translation) + elif self.joint_type == "planar": + if cfg is None: + cfg = np.zeros(2, dtype=np.float64) + else: + cfg = np.asanyarray(cfg, dtype=np.float64) + if cfg.shape != (2,): + raise ValueError("(2,) float configuration required for planar joints") + translation = np.eye(4, dtype=np.float64) + translation[:3, 3] = self.origin[:3, :2].dot(cfg) + return self.origin.dot(translation) + elif self.joint_type == "floating": + if cfg is None: + cfg = np.zeros(6, dtype=np.float64) + else: + cfg = configure_origin(cfg) + if cfg is None: + raise ValueError("Invalid configuration for floating joint") + return self.origin.dot(cfg) + else: + raise ValueError("Invalid configuration") + + def get_child_poses(self, cfg, n_cfgs): + """Computes the child pose relative to a parent pose for a given set of + configuration values. + + Parameters + ---------- + cfg : (n,) float or None + The configuration values for this joint. They are interpreted + based on the joint type as follows: + + - ``fixed`` - not used. + - ``prismatic`` - a translation along the axis in meters. + - ``revolute`` - a rotation about the axis in radians. + - ``continuous`` - a rotation about the axis in radians. + - ``planar`` - Not implemented. + - ``floating`` - Not implemented. + + If ``cfg`` is ``None``, then this just returns the joint pose. + + Returns + ------- + poses : (n,4,4) float + The poses of the child relative to the parent. + """ + if cfg is None: + return np.tile(self.origin, (n_cfgs, 1, 1)) + elif self.joint_type == "fixed": + return np.tile(self.origin, (n_cfgs, 1, 1)) + elif self.joint_type in ["revolute", "continuous"]: + if cfg is None: + cfg = np.zeros(n_cfgs) + return np.matmul(self.origin, self._rotation_matrices(cfg, self.axis)) + elif self.joint_type == "prismatic": + if cfg is None: + cfg = np.zeros(n_cfgs) + translation = np.tile(np.eye(4), (n_cfgs, 1, 1)) + translation[:, :3, 3] = self.axis * cfg[:, np.newaxis] + return np.matmul(self.origin, translation) + elif self.joint_type == "planar": + raise NotImplementedError() + elif self.joint_type == "floating": + raise NotImplementedError() + else: + raise ValueError("Invalid configuration") + + @classmethod + def _from_xml(cls, node, path): + kwargs = cls._parse(node, path) + kwargs["joint_type"] = str(node.attrib["type"]) + kwargs["parent"] = node.find("parent").attrib["link"] + kwargs["child"] = node.find("child").attrib["link"] + axis = node.find("axis") + if axis is not None: + axis = np.fromstring(axis.attrib["xyz"], sep=" ") + kwargs["axis"] = axis + kwargs["origin"] = parse_origin(node) + return Joint(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + parent = ET.Element("parent") + parent.attrib["link"] = self.parent + node.append(parent) + child = ET.Element("child") + child.attrib["link"] = self.child + node.append(child) + if self.axis is not None: + axis = ET.Element("axis") + axis.attrib["xyz"] = np.array2string(self.axis)[1:-1] + node.append(axis) + node.append(unparse_origin(self.origin)) + node.attrib["type"] = self.joint_type + return node + + def _rotation_matrices(self, angles, axis): + """Compute rotation matrices from angle/axis representations. + + Parameters + ---------- + angles : (n,) float + The angles. + axis : (3,) float + The axis. + + Returns + ------- + rots : (n,4,4) + The rotation matrices + """ + axis = axis / np.linalg.norm(axis) + sina = np.sin(angles) + cosa = np.cos(angles) + M = np.tile(np.eye(4), (len(angles), 1, 1)) + M[:, 0, 0] = cosa + M[:, 1, 1] = cosa + M[:, 2, 2] = cosa + M[:, :3, :3] += np.tile(np.outer(axis, axis), (len(angles), 1, 1)) * (1.0 - cosa)[:, np.newaxis, np.newaxis] + M[:, :3, :3] += ( + np.tile( + np.array([[0.0, -axis[2], axis[1]], [axis[2], 0.0, -axis[0]], [-axis[1], axis[0], 0.0]]), + (len(angles), 1, 1), + ) + * sina[:, np.newaxis, np.newaxis] + ) + return M + + def copy(self, prefix="", scale=None): + """Create a deep copy of the joint with the prefix applied to all names. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + :class:`.Joint` + A deep copy of the joint. + """ + origin = self.origin.copy() + if scale is not None: + if not isinstance(scale, (list, np.ndarray)): + scale = np.repeat(scale, 3) + origin[:3, 3] *= scale + cpy = Joint( + name="{}{}".format(prefix, self.name), + joint_type=self.joint_type, + parent="{}{}".format(prefix, self.parent), + child="{}{}".format(prefix, self.child), + axis=self.axis.copy(), + origin=origin, + limit=(self.limit.copy(prefix, scale) if self.limit else None), + dynamics=(self.dynamics.copy(prefix, scale) if self.dynamics else None), + safety_controller=(self.safety_controller.copy(prefix, scale) if self.safety_controller else None), + calibration=(self.calibration.copy(prefix, scale) if self.calibration else None), + mimic=(self.mimic.copy(prefix=prefix, scale=scale) if self.mimic else None), + ) + return cpy + + +class Link(URDFType): + """A link of a rigid object. + + Parameters + ---------- + name : str + The name of the link. + inertial : :class:`.Inertial`, optional + The inertial properties of the link. + visuals : list of :class:`.Visual`, optional + The visual properties of the link. + collsions : list of :class:`.Collision`, optional + The collision properties of the link. + """ + + _ATTRIBS = { + "name": (str, True), + } + _ELEMENTS = { + "inertial": (Inertial, False, False), + "visuals": (Visual, False, True), + "collisions": (Collision, False, True), + } + _TAG = "link" + + def __init__(self, name, inertial, visuals, collisions): + self.name = name + self.inertial = inertial + self.visuals = visuals + self.collisions = collisions + + self._collision_mesh = None + + @property + def name(self): + """str : The name of this link.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def inertial(self): + """:class:`.Inertial` : Inertial properties of the link.""" + return self._inertial + + @inertial.setter + def inertial(self, value): + if value is not None and not isinstance(value, Inertial): + raise TypeError("Expected Inertial object") + # Set default inertial + if value is None: + value = Inertial(mass=1.0, inertia=np.eye(3)) + self._inertial = value + + @property + def visuals(self): + """list of :class:`.Visual` : The visual properties of this link.""" + return self._visuals + + @visuals.setter + def visuals(self, value): + if value is None: + value = [] + else: + value = list(value) + for v in value: + if not isinstance(v, Visual): + raise ValueError("Expected list of Visual objects") + self._visuals = value + + @property + def collisions(self): + """list of :class:`.Collision` : The collision properties of this link.""" + return self._collisions + + @collisions.setter + def collisions(self, value): + if value is None: + value = [] + else: + value = list(value) + for v in value: + if not isinstance(v, Collision): + raise ValueError("Expected list of Collision objects") + self._collisions = value + + @property + def collision_mesh(self): + """:class:`~trimesh.base.Trimesh` : A single collision mesh for + the link, specified in the link frame, or None if there isn't one. + """ + if len(self.collisions) == 0: + return None + if self._collision_mesh is None: + meshes = [] + for c in self.collisions: + for m in c.geometry.meshes: + m = m.copy() + pose = c.origin + if c.geometry.mesh is not None: + if c.geometry.mesh.scale is not None: + S = np.eye(4) + S[:3, :3] = np.diag(c.geometry.mesh.scale) + pose = pose.dot(S) + m.apply_transform(pose) + meshes.append(m) + if len(meshes) == 0: + return None + self._collision_mesh = meshes[0] + meshes[1:] + return self._collision_mesh + + def copy(self, prefix="", scale=None, collision_only=False): + """Create a deep copy of the link. + + Parameters + ---------- + prefix : str + A prefix to apply to all joint and link names. + + Returns + ------- + link : :class:`.Link` + A deep copy of the Link. + """ + inertial = self.inertial.copy() if self.inertial is not None else None + cm = self._collision_mesh + if scale is not None: + if self.collision_mesh is not None and self.inertial is not None: + sm = np.eye(4) + if not isinstance(scale, (list, np.ndarray)): + scale = np.repeat(scale, 3) + sm[:3, :3] = np.diag(scale) + cm = self.collision_mesh.copy() + cm.density = self.inertial.mass / cm.volume + cm.apply_transform(sm) + cmm = np.eye(4) + cmm[:3, 3] = cm.center_mass + inertial = Inertial(mass=cm.mass, inertia=cm.moment_inertia, origin=cmm) + + visuals = None + if not collision_only: + visuals = [v.copy(prefix=prefix, scale=scale) for v in self.visuals] + + cpy = Link( + name="{}{}".format(prefix, self.name), + inertial=inertial, + visuals=visuals, + collisions=[v.copy(prefix=prefix, scale=scale) for v in self.collisions], + ) + cpy._collision_mesh = cm + return cpy + + +class URDF(URDFType): + """The top-level URDF specification. + + The URDF encapsulates an articulated object, such as a robot or a gripper. + It is made of links and joints that tie them together and define their + relative motions. + + Parameters + ---------- + name : str + The name of the URDF. + links : list of :class:`.Link` + The links of the URDF. + joints : list of :class:`.Joint`, optional + The joints of the URDF. + transmissions : list of :class:`.Transmission`, optional + The transmissions of the URDF. + materials : list of :class:`.Material`, optional + The materials for the URDF. + other_xml : str, optional + A string containing any extra XML for extensions. + """ + + _ATTRIBS = { + "name": (str, True), + } + _ELEMENTS = { + "links": (Link, True, True), + "joints": (Joint, False, True), + "transmissions": (Transmission, False, True), + "materials": (Material, False, True), + } + _TAG = "robot" + + def __init__(self, name, links, joints=None, transmissions=None, materials=None, other_xml=None): + if joints is None: + joints = [] + if transmissions is None: + transmissions = [] + if materials is None: + materials = [] + + self.name = name + self.other_xml = other_xml + + # No setters for these + self._links = list(links) + self._joints = list(joints) + self._transmissions = list(transmissions) + self._materials = list(materials) + + # Set up private helper maps from name to value + self._link_map = {} + self._joint_map = {} + self._transmission_map = {} + self._material_map = {} + + for x in self._links: + if x.name in self._link_map: + raise ValueError("Two links with name {} found".format(x.name)) + self._link_map[x.name] = x + + for x in self._joints: + if x.name in self._joint_map: + raise ValueError("Two joints with name {} found".format(x.name)) + self._joint_map[x.name] = x + + for x in self._transmissions: + if x.name in self._transmission_map: + raise ValueError("Two transmissions with name {} found".format(x.name)) + self._transmission_map[x.name] = x + + for x in self._materials: + if x.name in self._material_map: + raise ValueError("Two materials with name {} found".format(x.name)) + self._material_map[x.name] = x + + # Synchronize materials between links and top-level set + self._merge_materials() + + # Validate the joints and transmissions + actuated_joints = self._validate_joints() + self._validate_transmissions() + + # Create the link graph and base link/end link sets + self._G = nx.DiGraph() + + # Add all links + for link in self.links: + self._G.add_node(link) + + # Add all edges from CHILDREN TO PARENTS, with joints as their object + for joint in self.joints: + parent = self._link_map[joint.parent] + child = self._link_map[joint.child] + self._G.add_edge(child, parent, joint=joint) + + # Validate the graph and get the base and end links + self._base_link, self._end_links = self._validate_graph() + + # Cache the paths to the base link + self._paths_to_base = nx.shortest_path(self._G, target=self._base_link) + + self._actuated_joints = self._sort_joints(actuated_joints) + + # Cache the reverse topological order (useful for speeding up FK, + # as we want to start at the base and work outward to cache + # computation. + self._reverse_topo = list(reversed(list(nx.topological_sort(self._G)))) + + @property + def name(self): + """str : The name of the URDF.""" + return self._name + + @name.setter + def name(self, value): + self._name = str(value) + + @property + def links(self): + """list of :class:`.Link` : The links of the URDF. + + This returns a copy of the links array which cannot be edited + directly. If you want to add or remove links, use + the appropriate functions. + """ + return copy.copy(self._links) + + @property + def link_map(self): + """dict : Map from link names to the links themselves. + + This returns a copy of the link map which cannot be edited + directly. If you want to add or remove links, use + the appropriate functions. + """ + return copy.copy(self._link_map) + + @property + def joints(self): + """list of :class:`.Joint` : The links of the URDF. + + This returns a copy of the joints array which cannot be edited + directly. If you want to add or remove joints, use + the appropriate functions. + """ + return copy.copy(self._joints) + + @property + def joint_map(self): + """dict : Map from joint names to the joints themselves. + + This returns a copy of the joint map which cannot be edited + directly. If you want to add or remove joints, use + the appropriate functions. + """ + return copy.copy(self._joint_map) + + @property + def transmissions(self): + """list of :class:`.Transmission` : The transmissions of the URDF. + + This returns a copy of the transmissions array which cannot be edited + directly. If you want to add or remove transmissions, use + the appropriate functions. + """ + return copy.copy(self._transmissions) + + @property + def transmission_map(self): + """dict : Map from transmission names to the transmissions themselves. + + This returns a copy of the transmission map which cannot be edited + directly. If you want to add or remove transmissions, use + the appropriate functions. + """ + return copy.copy(self._transmission_map) + + @property + def materials(self): + """list of :class:`.Material` : The materials of the URDF. + + This returns a copy of the materials array which cannot be edited + directly. If you want to add or remove materials, use + the appropriate functions. + """ + return copy.copy(self._materials) + + @property + def material_map(self): + """dict : Map from material names to the materials themselves. + + This returns a copy of the material map which cannot be edited + directly. If you want to add or remove materials, use + the appropriate functions. + """ + return copy.copy(self._material_map) + + @property + def other_xml(self): + """str : Any extra XML that belongs with the URDF.""" + return self._other_xml + + @other_xml.setter + def other_xml(self, value): + self._other_xml = value + + @property + def actuated_joints(self): + """list of :class:`.Joint` : The joints that are independently + actuated. + + This excludes mimic joints and fixed joints. The joints are listed + in topological order, starting from the base-most joint. + """ + return self._actuated_joints + + @property + def actuated_joint_names(self): + """list of :class:`.Joint` : The names of joints that are independently + actuated. + + This excludes mimic joints and fixed joints. The joints are listed + in topological order, starting from the base-most joint. + """ + return [j.name for j in self._actuated_joints] + + def cfg_to_vector(self, cfg): + """Convert a configuration dictionary into a configuration vector. + + Parameters + ---------- + cfg : dict or None + The configuration value. + + Returns + ------- + vec : (n,) float + The configuration vector, or None if no actuated joints present. + """ + if cfg is None: + if len(self.actuated_joints) > 0: + return np.zeros(len(self.actuated_joints)) + else: + return None + elif isinstance(cfg, (list, tuple, np.ndarray)): + return np.asanyarray(cfg) + elif isinstance(cfg, dict): + vec = np.zeros(len(self.actuated_joints)) + for i, jn in enumerate(self.actuated_joint_names): + if jn in cfg: + vec[i] = cfg[jn] + return vec + else: + raise ValueError("Invalid configuration: {}".format(cfg)) + + @property + def base_link(self): + """:class:`.Link`: The base link for the URDF. + + The base link is the single link that has no parent. + """ + return self._base_link + + @property + def end_links(self): + """list of :class:`.Link`: The end links for the URDF. + + The end links are the links that have no children. + """ + return self._end_links + + @property + def joint_limit_cfgs(self): + """tuple of dict : The lower-bound and upper-bound joint configuration + maps. + + The first map is the lower-bound map, which maps limited joints to + their lower joint limits. + The second map is the upper-bound map, which maps limited joints to + their upper joint limits. + """ + lb = {} + ub = {} + for joint in self.actuated_joints: + if joint.limit is not None: + if joint.limit.lower is not None: + lb[joint] = joint.limit.lower + if joint.limit.upper is not None: + ub[joint] = joint.limit.upper + return (lb, ub) + + @property + def joint_limits(self): + """(n,2) float : A lower and upper limit for each joint.""" + limits = [] + for joint in self.actuated_joints: + limit = [-np.infty, np.infty] + if joint.limit is not None: + if joint.limit.lower is not None: + limit[0] = joint.limit.lower + if joint.limit.upper is not None: + limit[1] = joint.limit.upper + limits.append(limit) + return np.array(limits) + + def link_fk(self, cfg=None, link=None, links=None, use_names=False): + """Computes the poses of the URDF's links via forward kinematics. + + Parameters + ---------- + cfg : dict or (n), float + A map from joints or joint names to configuration values for + each joint, or a list containing a value for each actuated joint + in sorted order from the base link. + If not specified, all joints are assumed to be in their default + configurations. + link : str or :class:`.Link` + A single link or link name to return a pose for. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only these links will be in the returned map. If neither + link nor links are specified all links are returned. + use_names : bool + If True, the returned dictionary will have keys that are string + link names rather than the links themselves. + + Returns + ------- + fk : dict or (4,4) float + A map from links to 4x4 homogenous transform matrices that + position them relative to the base link's frame, or a single + 4x4 matrix if ``link`` is specified. + """ + # Process config value + joint_cfg = self._process_cfg(cfg) + + # Process link set + link_set = set() + if link is not None: + if isinstance(link, six.string_types): + link_set.add(self._link_map[link]) + elif isinstance(link, Link): + link_set.add(link) + elif links is not None: + for lnk in links: + if isinstance(lnk, six.string_types): + link_set.add(self._link_map[lnk]) + elif isinstance(lnk, Link): + link_set.add(lnk) + else: + raise TypeError("Got object of type {} in links list".format(type(lnk))) + else: + link_set = self.links + + # Compute forward kinematics in reverse topological order + fk = OrderedDict() + for lnk in self._reverse_topo: + if lnk not in link_set: + continue + pose = np.eye(4, dtype=np.float64) + path = self._paths_to_base[lnk] + for i in range(len(path) - 1): + child = path[i] + parent = path[i + 1] + joint = self._G.get_edge_data(child, parent)["joint"] + + cfg = None + if joint.mimic is not None: + mimic_joint = self._joint_map[joint.mimic.joint] + if mimic_joint in joint_cfg: + cfg = joint_cfg[mimic_joint] + cfg = joint.mimic.multiplier * cfg + joint.mimic.offset + elif joint in joint_cfg: + cfg = joint_cfg[joint] + pose = joint.get_child_pose(cfg).dot(pose) + + # Check existing FK to see if we can exit early + if parent in fk: + pose = fk[parent].dot(pose) + break + fk[lnk] = pose + + if link: + if isinstance(link, six.string_types): + return fk[self._link_map[link]] + else: + return fk[link] + if use_names: + return {ell.name: fk[ell] for ell in fk} + return fk + + def link_fk_batch(self, cfgs=None, link=None, links=None, use_names=False): + """Computes the poses of the URDF's links via forward kinematics in a batch. + + Parameters + ---------- + cfgs : dict, list of dict, or (n,m), float + One of the following: (A) a map from joints or joint names to vectors + of joint configuration values, (B) a list of maps from joints or joint names + to single configuration values, or (C) a list of ``n`` configuration vectors, + each of which has a vector with an entry for each actuated joint. + link : str or :class:`.Link` + A single link or link name to return a pose for. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only these links will be in the returned map. If neither + link nor links are specified all links are returned. + use_names : bool + If True, the returned dictionary will have keys that are string + link names rather than the links themselves. + + Returns + ------- + fk : dict or (n,4,4) float + A map from links to a (n,4,4) vector of homogenous transform matrices that + position the links relative to the base link's frame, or a single + nx4x4 matrix if ``link`` is specified. + """ + joint_cfgs, n_cfgs = self._process_cfgs(cfgs) + + # Process link set + link_set = set() + if link is not None: + if isinstance(link, six.string_types): + link_set.add(self._link_map[link]) + elif isinstance(link, Link): + link_set.add(link) + elif links is not None: + for lnk in links: + if isinstance(lnk, six.string_types): + link_set.add(self._link_map[lnk]) + elif isinstance(lnk, Link): + link_set.add(lnk) + else: + raise TypeError("Got object of type {} in links list".format(type(lnk))) + else: + link_set = self.links + + # Compute FK mapping each link to a vector of matrices, one matrix per cfg + fk = OrderedDict() + for lnk in self._reverse_topo: + if lnk not in link_set: + continue + poses = np.tile(np.eye(4, dtype=np.float64), (n_cfgs, 1, 1)) + path = self._paths_to_base[lnk] + for i in range(len(path) - 1): + child = path[i] + parent = path[i + 1] + joint = self._G.get_edge_data(child, parent)["joint"] + + cfg_vals = None + if joint.mimic is not None: + mimic_joint = self._joint_map[joint.mimic.joint] + if mimic_joint in joint_cfgs: + cfg_vals = joint_cfgs[mimic_joint] + cfg_vals = joint.mimic.multiplier * cfg_vals + joint.mimic.offset + elif joint in joint_cfgs: + cfg_vals = joint_cfgs[joint] + poses = np.matmul(joint.get_child_poses(cfg_vals, n_cfgs), poses) + + if parent in fk: + poses = np.matmul(fk[parent], poses) + break + fk[lnk] = poses + + if link: + if isinstance(link, six.string_types): + return fk[self._link_map[link]] + else: + return fk[link] + if use_names: + return {ell.name: fk[ell] for ell in fk} + return fk + + def visual_geometry_fk(self, cfg=None, links=None): + """Computes the poses of the URDF's visual geometries using fk. + + Parameters + ---------- + cfg : dict or (n), float + A map from joints or joint names to configuration values for + each joint, or a list containing a value for each actuated joint + in sorted order from the base link. + If not specified, all joints are assumed to be in their default + configurations. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only geometries from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`Geometry` objects that are part of the visual + elements of the specified links to the 4x4 homogenous transform + matrices that position them relative to the base link's frame. + """ + lfk = self.link_fk(cfg=cfg, links=links) + + fk = OrderedDict() + for link in lfk: + for visual in link.visuals: + fk[visual.geometry] = lfk[link].dot(visual.origin) + return fk + + def visual_geometry_fk_batch(self, cfgs=None, links=None): + """Computes the poses of the URDF's visual geometries using fk. + + Parameters + ---------- + cfgs : dict, list of dict, or (n,m), float + One of the following: (A) a map from joints or joint names to vectors + of joint configuration values, (B) a list of maps from joints or joint names + to single configuration values, or (C) a list of ``n`` configuration vectors, + each of which has a vector with an entry for each actuated joint. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only geometries from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`Geometry` objects that are part of the visual + elements of the specified links to the 4x4 homogenous transform + matrices that position them relative to the base link's frame. + """ + lfk = self.link_fk_batch(cfgs=cfgs, links=links) + + fk = OrderedDict() + for link in lfk: + for visual in link.visuals: + fk[visual.geometry] = np.matmul(lfk[link], visual.origin) + return fk + + def visual_trimesh_fk(self, cfg=None, links=None): + """Computes the poses of the URDF's visual trimeshes using fk. + + Parameters + ---------- + cfg : dict or (n), float + A map from joints or joint names to configuration values for + each joint, or a list containing a value for each actuated joint + in sorted order from the base link. + If not specified, all joints are assumed to be in their default + configurations. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only trimeshes from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`~trimesh.base.Trimesh` objects that are + part of the visual geometry of the specified links to the + 4x4 homogenous transform matrices that position them relative + to the base link's frame. + """ + lfk = self.link_fk(cfg=cfg, links=links) + + fk = OrderedDict() + for link in lfk: + for visual in link.visuals: + for mesh in visual.geometry.meshes: + pose = lfk[link].dot(visual.origin) + if visual.geometry.mesh is not None: + if visual.geometry.mesh.scale is not None: + S = np.eye(4, dtype=np.float64) + S[:3, :3] = np.diag(visual.geometry.mesh.scale) + pose = pose.dot(S) + fk[mesh] = pose + return fk + + def visual_trimesh_fk_batch(self, cfgs=None, links=None): + """Computes the poses of the URDF's visual trimeshes using fk. + + Parameters + ---------- + cfgs : dict, list of dict, or (n,m), float + One of the following: (A) a map from joints or joint names to vectors + of joint configuration values, (B) a list of maps from joints or joint names + to single configuration values, or (C) a list of ``n`` configuration vectors, + each of which has a vector with an entry for each actuated joint. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only trimeshes from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`~trimesh.base.Trimesh` objects that are + part of the visual geometry of the specified links to the + 4x4 homogenous transform matrices that position them relative + to the base link's frame. + """ + lfk = self.link_fk_batch(cfgs=cfgs, links=links) + + fk = OrderedDict() + for link in lfk: + for visual in link.visuals: + for mesh in visual.geometry.meshes: + poses = np.matmul(lfk[link], visual.origin) + if visual.geometry.mesh is not None: + if visual.geometry.mesh.scale is not None: + S = np.eye(4, dtype=np.float64) + S[:3, :3] = np.diag(visual.geometry.mesh.scale) + poses = np.matmul(poses, S) + fk[mesh] = poses + return fk + + def collision_geometry_fk(self, cfg=None, links=None): + """Computes the poses of the URDF's collision geometries using fk. + + Parameters + ---------- + cfg : dict or (n), float + A map from joints or joint names to configuration values for + each joint, or a list containing a value for each actuated joint + in sorted order from the base link. + If not specified, all joints are assumed to be in their default + configurations. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only geometries from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`Geometry` objects that are part of the collision + elements of the specified links to the 4x4 homogenous transform + matrices that position them relative to the base link's frame. + """ + lfk = self.link_fk(cfg=cfg, links=links) + + fk = OrderedDict() + for link in lfk: + for collision in link.collisions: + fk[collision] = lfk[link].dot(collision.origin) + return fk + + def collision_geometry_fk_batch(self, cfgs=None, links=None): + """Computes the poses of the URDF's collision geometries using fk. + + Parameters + ---------- + cfgs : dict, list of dict, or (n,m), float + One of the following: (A) a map from joints or joint names to vectors + of joint configuration values, (B) a list of maps from joints or joint names + to single configuration values, or (C) a list of ``n`` configuration vectors, + each of which has a vector with an entry for each actuated joint. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only geometries from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`Geometry` objects that are part of the collision + elements of the specified links to the 4x4 homogenous transform + matrices that position them relative to the base link's frame. + """ + lfk = self.link_fk_batch(cfgs=cfgs, links=links) + + fk = OrderedDict() + for link in lfk: + for collision in link.collisions: + fk[collision] = np.matmul(lfk[link], collision.origin) + return fk + + def collision_trimesh_fk(self, cfg=None, links=None): + """Computes the poses of the URDF's collision trimeshes using fk. + + Parameters + ---------- + cfg : dict or (n), float + A map from joints or joint names to configuration values for + each joint, or a list containing a value for each actuated joint + in sorted order from the base link. + If not specified, all joints are assumed to be in their default + configurations. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only trimeshes from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`~trimesh.base.Trimesh` objects that are + part of the collision geometry of the specified links to the + 4x4 homogenous transform matrices that position them relative + to the base link's frame. + """ + lfk = self.link_fk(cfg=cfg, links=links) + + fk = OrderedDict() + for link in lfk: + pose = lfk[link] + cm = link.collision_mesh + if cm is not None: + fk[cm] = pose + return fk + + def collision_trimesh_fk_batch(self, cfgs=None, links=None): + """Computes the poses of the URDF's collision trimeshes using fk. + + Parameters + ---------- + cfgs : dict, list of dict, or (n,m), float + One of the following: (A) a map from joints or joint names to vectors + of joint configuration values, (B) a list of maps from joints or joint names + to single configuration values, or (C) a list of ``n`` configuration vectors, + each of which has a vector with an entry for each actuated joint. + links : list of str or list of :class:`.Link` + The links or names of links to perform forward kinematics on. + Only trimeshes from these links will be in the returned map. + If not specified, all links are returned. + + Returns + ------- + fk : dict + A map from :class:`~trimesh.base.Trimesh` objects that are + part of the collision geometry of the specified links to the + 4x4 homogenous transform matrices that position them relative + to the base link's frame. + """ + lfk = self.link_fk_batch(cfgs=cfgs, links=links) + + fk = OrderedDict() + for link in lfk: + poses = lfk[link] + cm = link.collision_mesh + if cm is not None: + fk[cm] = poses + return fk + + def animate(self, cfg_trajectory=None, loop_time=3.0, use_collision=False): + """Animate the URDF through a configuration trajectory. + + Parameters + ---------- + cfg_trajectory : dict or (m,n) float + A map from joints or joint names to lists of configuration values + for each joint along the trajectory, or a vector of + vectors where the second dimension contains a value for each joint. + If not specified, all joints will articulate from limit to limit. + The trajectory steps are assumed to be equally spaced out in time. + loop_time : float + The time to loop the animation for, in seconds. The trajectory + will play fowards and backwards during this time, ending + at the inital configuration. + use_collision : bool + If True, the collision geometry is visualized instead of + the visual geometry. + + Examples + -------- + + You can run this without specifying a ``cfg_trajectory`` to view + the full articulation of the URDF + + >>> robot = URDF.load("ur5.urdf") + >>> robot.animate() + + .. image:: /_static/ur5.gif + + >>> ct = {"shoulder_pan_joint": [0.0, 2 * np.pi]} + >>> robot.animate(cfg_trajectory=ct) + + .. image:: /_static/ur5_shoulder.gif + + >>> ct = { + ... "shoulder_pan_joint": [-np.pi / 4, np.pi / 4], + ... "shoulder_lift_joint": [0.0, -np.pi / 2.0], + ... "elbow_joint": [0.0, np.pi / 2.0], + ... } + >>> robot.animate(cfg_trajectory=ct) + + .. image:: /_static/ur5_three_joints.gif + + """ + import pyrender # Save pyrender import for here for CI + + ct = cfg_trajectory + + traj_len = None # Length of the trajectory in steps + ct_np = {} # Numpyified trajectory + + # If trajectory not specified, articulate between the limits. + if ct is None: + lb, ub = self.joint_limit_cfgs + if len(lb) > 0: + traj_len = 2 + ct_np = {k: np.array([lb[k], ub[k]]) for k in lb} + + # If it is specified, parse it and extract the trajectory length. + elif isinstance(ct, dict): + if len(ct) > 0: + for k in ct: + val = np.asanyarray(ct[k]).astype(np.float64) + if traj_len is None: + traj_len = len(val) + elif traj_len != len(val): + raise ValueError("Trajectories must be same length") + ct_np[k] = val + elif isinstance(ct, (list, tuple, np.ndarray)): + ct = np.asanyarray(ct).astype(np.float64) + if ct.ndim == 1: + ct = ct.reshape(-1, 1) + if ct.ndim != 2 or ct.shape[1] != len(self.actuated_joints): + raise ValueError("Cfg trajectory must have entry for each joint") + ct_np = {j: ct[:, i] for i, j in enumerate(self.actuated_joints)} + else: + raise TypeError("Invalid type for cfg_trajectory: {}".format(type(cfg_trajectory))) + + # If there isn't a trajectory to render, just show the model and exit + if len(ct_np) == 0 or traj_len < 2: + self.show(use_collision=use_collision) + return + + # Create an array of times that loops from 0 to 1 and back to 0 + fps = 30.0 + n_steps = int(loop_time * fps / 2.0) + times = np.linspace(0.0, 1.0, n_steps) + times = np.hstack((times, np.flip(times))) + + # Create bin edges in the range [0, 1] for each trajectory step + bins = np.arange(traj_len) / (float(traj_len) - 1.0) + + # Compute alphas for each time + right_inds = np.digitize(times, bins, right=True) + right_inds[right_inds == 0] = 1 + alphas = (bins[right_inds] - times) / (bins[right_inds] - bins[right_inds - 1]) + + # Create the new interpolated trajectory + new_ct = {} + for k in ct_np: + new_ct[k] = alphas * ct_np[k][right_inds - 1] + (1.0 - alphas) * ct_np[k][right_inds] + + # Create the scene + if use_collision: + fk = self.collision_trimesh_fk() + else: + fk = self.visual_trimesh_fk() + + node_map = {} + scene = pyrender.Scene() + for tm in fk: + pose = fk[tm] + mesh = pyrender.Mesh.from_trimesh(tm, smooth=False) + node = scene.add(mesh, pose=pose) + node_map[tm] = node + + # Get base pose to focus on + blp = self.link_fk(links=[self.base_link])[self.base_link] + + # Pop the visualizer asynchronously + v = pyrender.Viewer(scene, run_in_thread=True, use_raymond_lighting=True, view_center=blp[:3, 3]) + + # Now, run our loop + i = 0 + while v.is_active: + cfg = {k: new_ct[k][i] for k in new_ct} + i = (i + 1) % len(times) + + if use_collision: + fk = self.collision_trimesh_fk(cfg=cfg) + else: + fk = self.visual_trimesh_fk(cfg=cfg) + + v.render_lock.acquire() + for mesh in fk: + pose = fk[mesh] + node_map[mesh].matrix = pose + v.render_lock.release() + + time.sleep(1.0 / fps) + + def show(self, cfg=None, use_collision=False): + """Visualize the URDF in a given configuration. + + Parameters + ---------- + cfg : dict or (n), float + A map from joints or joint names to configuration values for + each joint, or a list containing a value for each actuated joint + in sorted order from the base link. + If not specified, all joints are assumed to be in their default + configurations. + use_collision : bool + If True, the collision geometry is visualized instead of + the visual geometry. + """ + import pyrender # Save pyrender import for here for CI + + if use_collision: + fk = self.collision_trimesh_fk(cfg=cfg) + else: + fk = self.visual_trimesh_fk(cfg=cfg) + + scene = pyrender.Scene() + for tm in fk: + pose = fk[tm] + mesh = pyrender.Mesh.from_trimesh(tm, smooth=False) + scene.add(mesh, pose=pose) + pyrender.Viewer(scene, use_raymond_lighting=True) + + def copy(self, name=None, prefix="", scale=None, collision_only=False): + """Make a deep copy of the URDF. + + Parameters + ---------- + name : str, optional + A name for the new URDF. If not specified, ``self.name`` is used. + prefix : str, optional + A prefix to apply to all names except for the base URDF name. + scale : float or (3,) float, optional + A scale to apply to the URDF. + collision_only : bool, optional + If True, all visual geometry is redirected to the collision geometry. + + Returns + ------- + copy : :class:`.URDF` + The copied URDF. + """ + return URDF( + name=(name if name else self.name), + links=[v.copy(prefix, scale, collision_only) for v in self.links], + joints=[v.copy(prefix, scale) for v in self.joints], + transmissions=[v.copy(prefix, scale) for v in self.transmissions], + materials=[v.copy(prefix, scale) for v in self.materials], + other_xml=self.other_xml, + ) + + def save(self, file_obj): + """Save this URDF to a file. + + Parameters + ---------- + file_obj : str or file-like object + The file to save the URDF to. Should be the path to the + ``.urdf`` XML file. Any paths in the URDF should be specified + as relative paths to the ``.urdf`` file instead of as ROS + resources. + + Returns + ------- + urdf : :class:`.URDF` + The parsed URDF. + """ + if isinstance(file_obj, six.string_types): + path, _ = os.path.split(file_obj) + else: + path, _ = os.path.split(os.path.realpath(file_obj.name)) + + node = self._to_xml(None, path) + tree = ET.ElementTree(node) + tree.write(file_obj, pretty_print=True, xml_declaration=True, encoding="utf-8") + + def join(self, other, link, origin=None, name=None, prefix=""): + """Join another URDF to this one by rigidly fixturing the two at a link. + + Parameters + ---------- + other : :class:.`URDF` + Another URDF to fuze to this one. + link : :class:`.Link` or str + The link of this URDF to attach the other URDF to. + origin : (4,4) float, optional + The location in this URDF's link frame to attach the base link of the other + URDF at. + name : str, optional + A name for the new URDF. + prefix : str, optional + If specified, all joints and links from the (other) mesh will be pre-fixed + with this value to avoid name clashes. + + Returns + ------- + :class:`.URDF` + The new URDF. + """ + myself = self.copy() + other = other.copy(prefix=prefix) + + # Validate + link_names = set(myself.link_map.keys()) + other_link_names = set(other.link_map.keys()) + if len(link_names.intersection(other_link_names)) > 0: + raise ValueError("Cannot merge two URDFs with shared link names") + + joint_names = set(myself.joint_map.keys()) + other_joint_names = set(other.joint_map.keys()) + if len(joint_names.intersection(other_joint_names)) > 0: + raise ValueError("Cannot merge two URDFs with shared joint names") + + links = myself.links + other.links + joints = myself.joints + other.joints + transmissions = myself.transmissions + other.transmissions + materials = myself.materials + other.materials + + if name is None: + name = self.name + + # Create joint that links the two rigidly + joints.append( + Joint( + name="{}_join_{}{}_joint".format(self.name, prefix, other.name), + joint_type="fixed", + parent=link if isinstance(link, str) else link.name, + child=other.base_link.name, + origin=origin, + ) + ) + + return URDF(name=name, links=links, joints=joints, transmissions=transmissions, materials=materials) + + def _merge_materials(self): + """Merge the top-level material set with the link materials.""" + for link in self.links: + for v in link.visuals: + if v.material is None: + continue + if v.material.name in self.material_map: + v.material = self._material_map[v.material.name] + else: + self._materials.append(v.material) + self._material_map[v.material.name] = v.material + + @staticmethod + def load(file_obj): + """Load a URDF from a file. + + Parameters + ---------- + file_obj : str or file-like object + The file to load the URDF from. Should be the path to the + ``.urdf`` XML file. Any paths in the URDF should be specified + as relative paths to the ``.urdf`` file instead of as ROS + resources. + + Returns + ------- + urdf : :class:`.URDF` + The parsed URDF. + """ + if isinstance(file_obj, six.string_types): + if os.path.isfile(file_obj): + parser = ET.XMLParser(remove_comments=True, remove_blank_text=True) + tree = ET.parse(file_obj, parser=parser) + path, _ = os.path.split(file_obj) + else: + raise ValueError("{} is not a file".format(file_obj)) + else: + parser = ET.XMLParser(remove_comments=True, remove_blank_text=True) + tree = ET.parse(file_obj, parser=parser) + path, _ = os.path.split(file_obj.name) + + node = tree.getroot() + return URDF._from_xml(node, path) + + def _validate_joints(self): + """Raise an exception of any joints are invalidly specified. + + Checks for the following: + + - Joint parents are valid link names. + - Joint children are valid link names that aren't the same as parent. + - Joint mimics have valid joint names that aren't the same joint. + + Returns + ------- + actuated_joints : list of :class:`.Joint` + The joints in the model that are independently controllable. + """ + actuated_joints = [] + for joint in self.joints: + if joint.parent not in self._link_map: + raise ValueError("Joint {} has invalid parent link name {}".format(joint.name, joint.parent)) + if joint.child not in self._link_map: + raise ValueError("Joint {} has invalid child link name {}".format(joint.name, joint.child)) + if joint.child == joint.parent: + raise ValueError("Joint {} has matching parent and child".format(joint.name)) + if joint.mimic is not None: + if joint.mimic.joint not in self._joint_map: + raise ValueError( + "Joint {} has an invalid mimic joint name {}".format(joint.name, joint.mimic.joint) + ) + if joint.mimic.joint == joint.name: + raise ValueError("Joint {} set up to mimic itself".format(joint.mimic.joint)) + elif joint.joint_type != "fixed": + actuated_joints.append(joint) + + # Do a depth-first search + return actuated_joints + + def _sort_joints(self, joints): + """Sort joints by ascending distance from the base link (topologically). + + Parameters + ---------- + joints : list of :class:`.Joint` + The joints to sort. + + Returns + ------- + joints : list of :class:`.Joint` + The sorted joints. + """ + lens = [] + for joint in joints: + child_link = self._link_map[joint.child] + lens.append(len(self._paths_to_base[child_link])) + order = np.argsort(lens) + return np.array(joints)[order].tolist() + + def _validate_transmissions(self): + """Raise an exception of any transmissions are invalidly specified. + + Checks for the following: + + - Transmission joints have valid joint names. + """ + for t in self.transmissions: + for joint in t.joints: + if joint.name not in self._joint_map: + raise ValueError("Transmission {} has invalid joint name {}".format(t.name, joint.name)) + + def _validate_graph(self): + """Raise an exception if the link-joint structure is invalid. + + Checks for the following: + + - The graph is connected in the undirected sense. + - The graph is acyclic in the directed sense. + - The graph has only one base link. + + Returns + ------- + base_link : :class:`.Link` + The base link of the URDF. + end_links : list of :class:`.Link` + The end links of the URDF. + """ + + # Check that the link graph is weakly connected + if not nx.is_weakly_connected(self._G): + link_clusters = [] + for cc in nx.weakly_connected_components(self._G): + cluster = [] + for n in cc: + cluster.append(n.name) + link_clusters.append(cluster) + message = "Links are not all connected. Connected components are:" + for lc in link_clusters: + message += "\n\t" + for n in lc: + message += " {}".format(n) + raise ValueError(message) + + # Check that link graph is acyclic + if not nx.is_directed_acyclic_graph(self._G): + raise ValueError("There are cycles in the link graph") + + # Ensure that there is exactly one base link, which has no parent + base_link = None + end_links = [] + for n in self._G: + if len(nx.descendants(self._G, n)) == 0: + if base_link is None: + base_link = n + else: + raise ValueError("Links {} and {} are both base links!".format(n.name, base_link.name)) + if len(nx.ancestors(self._G, n)) == 0: + end_links.append(n) + return base_link, end_links + + def _process_cfg(self, cfg): + """Process a joint configuration spec into a dictionary mapping + joints to configuration values. + """ + joint_cfg = {} + if cfg is None: + return joint_cfg + if isinstance(cfg, dict): + for joint in cfg: + if isinstance(joint, six.string_types): + joint_cfg[self._joint_map[joint]] = cfg[joint] + elif isinstance(joint, Joint): + joint_cfg[joint] = cfg[joint] + elif isinstance(cfg, (list, tuple, np.ndarray)): + if len(cfg) != len(self.actuated_joints): + raise ValueError("Cfg must have same length as actuated joints if specified as a numerical array") + for joint, value in zip(self.actuated_joints, cfg): + joint_cfg[joint] = value + else: + raise TypeError("Invalid type for config") + return joint_cfg + + def _process_cfgs(self, cfgs): + """Process a list of joint configurations into a dictionary mapping joints to + configuration values. + + This should result in a dict mapping each joint to a list of cfg values, one + per joint. + """ + joint_cfg = {j: [] for j in self.actuated_joints} + n_cfgs = None + if isinstance(cfgs, dict): + for joint in cfgs: + if isinstance(joint, six.string_types): + joint_cfg[self._joint_map[joint]] = cfgs[joint] + else: + joint_cfg[joint] = cfgs[joint] + if n_cfgs is None: + n_cfgs = len(cfgs[joint]) + elif isinstance(cfgs, (list, tuple, np.ndarray)): + n_cfgs = len(cfgs) + if isinstance(cfgs[0], dict): + for cfg in cfgs: + for joint in cfg: + if isinstance(joint, six.string_types): + joint_cfg[self._joint_map[joint]].append(cfg[joint]) + else: + joint_cfg[joint].append(cfg[joint]) + elif cfgs[0] is None: + pass + else: + cfgs = np.asanyarray(cfgs, dtype=np.float64) + for i, j in enumerate(self.actuated_joints): + joint_cfg[j] = cfgs[:, i] + else: + raise ValueError("Incorrectly formatted config array") + + for j in joint_cfg: + if len(joint_cfg[j]) == 0: + joint_cfg[j] = None + elif len(joint_cfg[j]) != n_cfgs: + raise ValueError("Inconsistent number of configurations for joints") + + return joint_cfg, n_cfgs + + @classmethod + def _from_xml(cls, node, path): + valid_tags = set(["joint", "link", "transmission", "material"]) + kwargs = cls._parse(node, path) + + extra_xml_node = ET.Element("extra") + for child in node: + if child.tag not in valid_tags: + extra_xml_node.append(child) + + data = ET.tostring(extra_xml_node) + kwargs["other_xml"] = data + return URDF(**kwargs) + + def _to_xml(self, parent, path): + node = self._unparse(path) + if self.other_xml: + extra_tree = ET.fromstring(self.other_xml) + for child in extra_tree: + node.append(child) + return node + + +def rpy_to_matrix(coords): + """Convert roll-pitch-yaw coordinates to a 3x3 homogenous rotation matrix. + + The roll-pitch-yaw axes in a typical URDF are defined as a + rotation of ``r`` radians around the x-axis followed by a rotation of + ``p`` radians around the y-axis followed by a rotation of ``y`` radians + around the z-axis. These are the Z1-Y2-X3 Tait-Bryan angles. See + Wikipedia_ for more information. + + .. _Wikipedia: https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + + Parameters + ---------- + coords : (3,) float + The roll-pitch-yaw coordinates in order (x-rot, y-rot, z-rot). + + Returns + ------- + R : (3,3) float + The corresponding homogenous 3x3 rotation matrix. + """ + coords = np.asanyarray(coords, dtype=np.float64) + c3, c2, c1 = np.cos(coords) + s3, s2, s1 = np.sin(coords) + + return np.array( + [ + [c1 * c2, (c1 * s2 * s3) - (c3 * s1), (s1 * s3) + (c1 * c3 * s2)], + [c2 * s1, (c1 * c3) + (s1 * s2 * s3), (c3 * s1 * s2) - (c1 * s3)], + [-s2, c2 * s3, c2 * c3], + ], + dtype=np.float64, + ) + + +def matrix_to_rpy(R, solution=1): + """Convert a 3x3 transform matrix to roll-pitch-yaw coordinates. + + The roll-pitchRyaw axes in a typical URDF are defined as a + rotation of ``r`` radians around the x-axis followed by a rotation of + ``p`` radians around the y-axis followed by a rotation of ``y`` radians + around the z-axis. These are the Z1-Y2-X3 Tait-Bryan angles. See + Wikipedia_ for more information. + + .. _Wikipedia: https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix + + There are typically two possible roll-pitch-yaw coordinates that could have + created a given rotation matrix. Specify ``solution=1`` for the first one + and ``solution=2`` for the second one. + + Parameters + ---------- + R : (3,3) float + A 3x3 homogenous rotation matrix. + solution : int + Either 1 or 2, indicating which solution to return. + + Returns + ------- + coords : (3,) float + The roll-pitch-yaw coordinates in order (x-rot, y-rot, z-rot). + """ + R = np.asanyarray(R, dtype=np.float64) + r = 0.0 + p = 0.0 + y = 0.0 + + if np.abs(R[2, 0]) >= 1.0 - 1e-12: + y = 0.0 + if R[2, 0] < 0: + p = np.pi / 2 + r = np.arctan2(R[0, 1], R[0, 2]) + else: + p = -np.pi / 2 + r = np.arctan2(-R[0, 1], -R[0, 2]) + else: + if solution == 1: + p = -np.arcsin(R[2, 0]) + else: + p = np.pi + np.arcsin(R[2, 0]) + r = np.arctan2(R[2, 1] / np.cos(p), R[2, 2] / np.cos(p)) + y = np.arctan2(R[1, 0] / np.cos(p), R[0, 0] / np.cos(p)) + + return np.array([r, p, y], dtype=np.float64) + + +def matrix_to_xyz_rpy(matrix): + """Convert a 4x4 homogenous matrix to xyzrpy coordinates. + + Parameters + ---------- + matrix : (4,4) float + The homogenous transform matrix. + + Returns + ------- + xyz_rpy : (6,) float + The xyz_rpy vector. + """ + xyz = matrix[:3, 3] + rpy = matrix_to_rpy(matrix[:3, :3]) + return np.hstack((xyz, rpy)) + + +def xyz_rpy_to_matrix(xyz_rpy): + """Convert xyz_rpy coordinates to a 4x4 homogenous matrix. + + Parameters + ---------- + xyz_rpy : (6,) float + The xyz_rpy vector. + + Returns + ------- + matrix : (4,4) float + The homogenous transform matrix. + """ + matrix = np.eye(4, dtype=np.float64) + matrix[:3, 3] = xyz_rpy[:3] + matrix[:3, :3] = rpy_to_matrix(xyz_rpy[3:]) + return matrix + + +def parse_origin(node): + """Find the ``origin`` subelement of an XML node and convert it + into a 4x4 homogenous transformation matrix. + + Parameters + ---------- + node : :class`lxml.etree.Element` + An XML node which (optionally) has a child node with the ``origin`` + tag. + + Returns + ------- + matrix : (4,4) float + The 4x4 homogneous transform matrix that corresponds to this node's + ``origin`` child. Defaults to the identity matrix if no ``origin`` + child was found. + """ + matrix = np.eye(4, dtype=np.float64) + origin_node = node.find("origin") + if origin_node is not None: + if "xyz" in origin_node.attrib: + matrix[:3, 3] = np.fromstring(origin_node.attrib["xyz"], sep=" ") + if "rpy" in origin_node.attrib: + rpy = np.fromstring(origin_node.attrib["rpy"], sep=" ") + matrix[:3, :3] = rpy_to_matrix(rpy) + return matrix + + +def unparse_origin(matrix): + """Turn a 4x4 homogenous matrix into an ``origin`` XML node. + + Parameters + ---------- + matrix : (4,4) float + The 4x4 homogneous transform matrix to convert into an ``origin`` + XML node. + + Returns + ------- + node : :class`lxml.etree.Element` + An XML node whose tag is ``origin``. The node has two attributes: + + - ``xyz`` - A string with three space-delimited floats representing + the translation of the origin. + - ``rpy`` - A string with three space-delimited floats representing + the rotation of the origin. + """ + node = ET.Element("origin") + node.attrib["xyz"] = "{} {} {}".format(*matrix[:3, 3]) + node.attrib["rpy"] = "{} {} {}".format(*matrix_to_rpy(matrix[:3, :3])) + return node + + +def get_filename(base_path, file_path, makedirs=False): + """Formats a file path correctly for URDF loading. + + Parameters + ---------- + base_path : str + The base path to the URDF's folder. + file_path : str + The path to the file. + makedirs : bool, optional + If ``True``, the directories leading to the file will be created + if needed. + + Returns + ------- + resolved : str + The resolved filepath -- just the normal ``file_path`` if it was an + absolute path, otherwise that path joined to ``base_path``. + """ + fn = file_path + if not os.path.isabs(file_path): + fn = os.path.join(base_path, file_path) + if makedirs: + d, _ = os.path.split(fn) + if not os.path.exists(d): + os.makedirs(d) + return fn + + +def load_meshes(filename): + """Loads triangular meshes from a file. + + Parameters + ---------- + filename : str + Path to the mesh file. + + Returns + ------- + meshes : list of :class:`~trimesh.base.Trimesh` + The meshes loaded from the file. + """ + meshes = trimesh.load(filename) + + # If we got a scene, dump the meshes + if isinstance(meshes, trimesh.Scene): + meshes = list(meshes.dump()) + meshes = [g for g in meshes if isinstance(g, trimesh.Trimesh)] + + if isinstance(meshes, (list, tuple, set)): + meshes = list(meshes) + if len(meshes) == 0: + raise ValueError("At least one mesh must be pmeshesent in file") + for r in meshes: + if not isinstance(r, trimesh.Trimesh): + raise TypeError("Could not load meshes from file") + elif isinstance(meshes, trimesh.Trimesh): + meshes = [meshes] + else: + raise ValueError("Unable to load mesh from file") + + return meshes + + +def configure_origin(value): + """Convert a value into a 4x4 transform matrix. + + Parameters + ---------- + value : None, (6,) float, or (4,4) float + The value to turn into the matrix. + If (6,), interpreted as xyzrpy coordinates. + + Returns + ------- + matrix : (4,4) float or None + The created matrix. + """ + if value is None: + value = np.eye(4, dtype=np.float64) + elif isinstance(value, (list, tuple, np.ndarray)): + value = np.asanyarray(value, dtype=np.float64) + if value.shape == (6,): + value = xyz_rpy_to_matrix(value) + elif value.shape != (4, 4): + raise ValueError("Origin must be specified as a 4x4 homogenous transformation matrix") + else: + raise TypeError("Invalid type for origin, expect 4x4 matrix") + return value diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/usd_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/usd_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..46d825b70fe1e1672c9c4d46f84b0af04debef8c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/usd_utils.py @@ -0,0 +1,3859 @@ +import collections +import os +import re +from collections.abc import Iterable +from typing import Tuple + +import numpy as np +import torch as th +import trimesh +import warp as wp +from numba import jit, prange + +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as TT +import omnigibson.utils.transform_utils_np as NT +from omnigibson.utils.backend_utils import _compute_backend as cb +from omnigibson.utils.backend_utils import add_compute_function +from omnigibson.macros import gm +from omnigibson.utils.constants import PRIMITIVE_MESH_TYPES, JointType, PrimType +from omnigibson.utils.numpy_utils import vtarray_to_torch +from omnigibson.utils.python_utils import assert_valid_key, torch_compile +from omnigibson.utils.ui_utils import create_module_logger, suppress_omni_log + +# Create module logger +log = create_module_logger(module_name=__name__) + + +@wp.func +def rigid_inverse_mat44(T: wp.mat44) -> wp.mat44: + """ + Inverse of a rigid transform `T = [R | t; 0 | 1]` with R orthogonal. + Result: `[R^T | -R^T t; 0 | 1]`. Cheap to compute (transpose + dot products), + avoids a general 4x4 inverse and works correctly under wp.graph capture. + + Used by _toggle_overlap_kernel (and any future kernel that needs to transform a world-space point into a link's + local frame). + """ + R = wp.mat33( + T[0, 0], + T[0, 1], + T[0, 2], + T[1, 0], + T[1, 1], + T[1, 2], + T[2, 0], + T[2, 1], + T[2, 2], + ) + t = wp.vec3(T[0, 3], T[1, 3], T[2, 3]) + Rt = wp.transpose(R) + nt = -wp.mul(Rt, t) + return wp.mat44( + Rt[0, 0], + Rt[0, 1], + Rt[0, 2], + nt[0], + Rt[1, 0], + Rt[1, 1], + Rt[1, 2], + nt[1], + Rt[2, 0], + Rt[2, 1], + Rt[2, 2], + nt[2], + 0.0, + 0.0, + 0.0, + 1.0, + ) + + +@wp.kernel +def _is_in_contact_batch_kernel( + query_masks: wp.array2d(dtype=wp.uint8), # (N, R) + contact_matrix: wp.array2d(dtype=wp.uint8), # (R, C) + col_filter: wp.array2d(dtype=wp.uint8), # (N, C) — with-mask if mode=0, ignore-mask if mode=1, ignored if mode=2 + mode: wp.int32, # 0 = with_masks, 1 = ignore_masks, 2 = no filter + out: wp.array(dtype=wp.int32), # (N,) — atomic-OR'd, int32 because uint8 atomics aren't supported +): + """ + Per (query, row, col) thread: full N*R*C parallelism. Each thread checks one cell: + if query_masks[i, r] AND contact_matrix[r, c] AND col_filter passes: + atomic-set out[i] to 1. + + Output is int32 because Warp's atomic_max requires [u]int32, [u]int64, float32, or + float64 (CUDA doesn't expose 8-bit atomics natively). Same-value atomic_max writes + short-circuit on Pascal+ hardware, so contention on out[i] is bounded — only the + first hitting thread per query actually does meaningful work; subsequent writes are + NOPs at the memory subsystem. + + Caller must zero `out` before launch (see is_in_contact_batch_warp). The atomic only + sets-to-1 on hits; cells with no hits remain at their initial value. + """ + i, r, c = wp.tid() + + # If query_masks or col_filter has a single row, it is shared across all N output queries. + query_row = i + if query_masks.shape[0] == 1: + query_row = 0 + filter_row = i + if col_filter.shape[0] == 1: + filter_row = 0 + + # Column filter — early exit before touching query_masks/contact_matrix. + if mode == wp.int32(0): # with-mask: only count if filter is True + if col_filter[filter_row, c] == wp.uint8(0): + return + elif mode == wp.int32(1): # ignore-mask: only count if filter is False + if col_filter[filter_row, c] != wp.uint8(0): + return + + # Row mask — does query query_row include row r? + if query_masks[query_row, r] == wp.uint8(0): + return + + # Contact lookup. + if contact_matrix[r, c] == wp.uint8(0): + return + + # Hit. Set out[i] = 1. atomic_max because multiple (i, *, *) threads may converge + # on the same out[i]. Same-value short-circuit keeps contention cheap. + wp.atomic_max(out, i, wp.int32(1)) + + +@wp.func +def _body_awake_at_step( + i: wp.int32, + b: wp.int32, + all_transforms: wp.array3d(dtype=wp.float32), + prev_transforms: wp.array2d(dtype=wp.float32), + body_to_row: wp.array(dtype=wp.int32), + net_forces: wp.array3d(dtype=wp.float32), + pos_eps: wp.float32, + ori_eps: wp.float32, +) -> wp.bool: + """ + Returns True iff body ``b`` was awake at physics-step ``i``. + + A body is awake if either its position/orientation changed since the previous step, + or — for bodies that map to a contact-matrix row — its net contact force is nonzero. + For step ``i == 0`` the predecessor is the cached ``prev_transforms`` (the + ``_BODY_TRANSFORMS`` snapshot from the previous update), otherwise it's + ``all_transforms[i-1, b]``. + + Shared by ``_update_contact_matrices_kernel`` and ``_update_body_transforms_kernel`` + so both kernels see the exact same awakeness predicate. + """ + if i == 0: + px0 = prev_transforms[b, 0] + py0 = prev_transforms[b, 1] + pz0 = prev_transforms[b, 2] + qx0 = prev_transforms[b, 3] + qy0 = prev_transforms[b, 4] + qz0 = prev_transforms[b, 5] + qw0 = prev_transforms[b, 6] + else: + px0 = all_transforms[i - 1, b, 0] + py0 = all_transforms[i - 1, b, 1] + pz0 = all_transforms[i - 1, b, 2] + qx0 = all_transforms[i - 1, b, 3] + qy0 = all_transforms[i - 1, b, 4] + qz0 = all_transforms[i - 1, b, 5] + qw0 = all_transforms[i - 1, b, 6] + px1 = all_transforms[i, b, 0] + py1 = all_transforms[i, b, 1] + pz1 = all_transforms[i, b, 2] + qx1 = all_transforms[i, b, 3] + qy1 = all_transforms[i, b, 4] + qz1 = all_transforms[i, b, 5] + qw1 = all_transforms[i, b, 6] + + pos_changed = wp.abs(px1 - px0) > pos_eps or wp.abs(py1 - py0) > pos_eps or wp.abs(pz1 - pz0) > pos_eps + qdot = qx0 * qx1 + qy0 * qy1 + qz0 * qz1 + qw0 * qw1 + ori_changed = wp.abs(qdot) < (wp.float32(1.0) - ori_eps) + awake = pos_changed or ori_changed + + r = body_to_row[b] + if r >= 0: + fx = net_forces[i, r, 0] + fy = net_forces[i, r, 1] + fz = net_forces[i, r, 2] + if fx != 0.0 or fy != 0.0 or fz != 0.0: + awake = True + return awake + + +@wp.kernel +def _update_contact_matrices_kernel( + all_transforms: wp.array3d(dtype=wp.float32), # (N, B, 7) + prev_transforms: wp.array2d(dtype=wp.float32), # (B, 7) — cached BODY_TRANSFORMS + net_forces: wp.array3d(dtype=wp.float32), # (N, R, 3) + body_to_row: wp.array(dtype=wp.int32), # (B,) -1 if body is not a row body + impulses: wp.array4d(dtype=wp.float32), # (N, R, C, 3) + row_to_rigid: wp.array(dtype=wp.int32), # (R,) row index → body index + col_to_rigid: wp.array(dtype=wp.int32), # (C,) col index → body index, -1 = kinematic + n_steps_arr: wp.array(dtype=wp.int32), # (1,) read at runtime, NOT a captured constant + pos_eps: wp.float32, + ori_eps: wp.float32, + contact_matrix: wp.array2d(dtype=wp.uint8), # (R, C) in/out — "any contact during recent steps" + current_contact_matrix: wp.array2d(dtype=wp.uint8), # (R, C) in/out — "contact at most recent awake step" +): + """ + Per (r, c) thread: walks ``n_steps_arr[0]`` physics sub-steps, evaluating pair awakeness + inline via ``_body_awake_at_step``. Replaces the entire torch pipeline in the old + ``RigidContactAPIImpl.update()``: + + - ``th.cat`` of prev+all_transforms → folded into the i==0 base case in _body_awake_at_step. + - ``th.where(per_step_awake, idx, -1).max(dim=0)`` → tracked as a scalar ``last_awake`` per thread. + - ``th.any(impulses != 0, dim=-1)`` and the masked indexed writes → + scalar OR over the awake sub-steps, single write at the end. + + ``n_steps`` comes from ``n_steps_arr[0]`` (a 1-element GPU array refreshed from Python + before each graph launch) rather than a captured constant. This matches the old code's + ``all_impulses[:self._PENDING_STEPS]`` slicing — when ``og.sim.step_physics()`` is used + (e.g. inside ``sample_kinematics``), only 1 < n_physics_timesteps_per_render sub-step + has actually run, and the remaining pending slots hold stale data from previous frames. + + Pairs that were never awake retain ``current_contact_matrix[r, c]`` and copy it into + ``contact_matrix[r, c]``, matching the torch behavior at the end of the original update(). + """ + r, c = wp.tid() + n_steps = n_steps_arr[0] + row_b = row_to_rigid[r] + col_b = col_to_rigid[c] + has_col_b = col_b >= 0 + + last_awake = wp.int32(-1) + any_contact = wp.uint8(0) + for i in range(n_steps): + row_awake = _body_awake_at_step( + i, row_b, all_transforms, prev_transforms, body_to_row, net_forces, pos_eps, ori_eps + ) + col_awake = False + if has_col_b: + col_awake = _body_awake_at_step( + i, col_b, all_transforms, prev_transforms, body_to_row, net_forces, pos_eps, ori_eps + ) + if row_awake or col_awake: + last_awake = i + if impulses[i, r, c, 0] != 0.0 or impulses[i, r, c, 1] != 0.0 or impulses[i, r, c, 2] != 0.0: + any_contact = wp.uint8(1) + + if last_awake >= 0: + cur = wp.uint8(0) + if ( + impulses[last_awake, r, c, 0] != 0.0 + or impulses[last_awake, r, c, 1] != 0.0 + or impulses[last_awake, r, c, 2] != 0.0 + ): + cur = wp.uint8(1) + current_contact_matrix[r, c] = cur + contact_matrix[r, c] = any_contact + else: + # Pair was never awake — both matrices collapse to the (carried-over) current value. + contact_matrix[r, c] = current_contact_matrix[r, c] + + +@wp.kernel +def _update_body_transforms_kernel( + all_transforms: wp.array3d(dtype=wp.float32), # (N, B, 7) + prev_transforms: wp.array2d(dtype=wp.float32), # (B, 7) — same buffer as body_transforms below + net_forces: wp.array3d(dtype=wp.float32), # (N, R, 3) + body_to_row: wp.array(dtype=wp.int32), # (B,) + n_steps_arr: wp.array(dtype=wp.int32), # (1,) read at runtime, shared with the contact kernel + pos_eps: wp.float32, + ori_eps: wp.float32, + body_transforms: wp.array2d(dtype=wp.float32), # (B, 7) in/out — snapshot of last awake step per body +): + """ + Per (b,) thread: snapshots each body's transform from its last awake step. + + MUST be launched *after* ``_update_contact_matrices_kernel`` because both kernels + use ``body_transforms`` as the ``prev_transforms`` ``_body_awake_at_step`` reads for + ``i == 0``, and this kernel writes to it in-place. Same-stream ordering inside the + captured graph guarantees this. + """ + b = wp.tid() + n_steps = n_steps_arr[0] + last_awake = wp.int32(-1) + for i in range(n_steps): + if _body_awake_at_step(i, b, all_transforms, prev_transforms, body_to_row, net_forces, pos_eps, ori_eps): + last_awake = i + if last_awake >= 0: + for k in range(7): + body_transforms[b, k] = all_transforms[last_awake, b, k] + + +def ensure_usd_api(prim, api): + """ + Ensures that a USD API schema is applied to a prim. If the prim already has the API, + returns the existing wrapper. Otherwise, applies the API inside an editing_usd() context + (triggering a USD-to-Fabric sync) and returns the newly applied wrapper. + + Args: + prim (Usd.Prim): The prim to check / apply the API on + api: The USD API class (e.g. lazy.pxr.UsdPhysics.RigidBodyAPI) + + Returns: + The API wrapper for the prim + """ + if prim.HasAPI(api): + return api(prim) + with og.sim.editing_usd(): + return api.Apply(prim) + + +def array_to_vtarray(arr, element_type): + """ + Converts array @arr into a Vt-typed array, where each individual element of type @element_type. + + Args: + arr (n-array): An array of values. Can be, e.g., a list, or numpy array + element_type (type): Per-element type to convert the elements from @arr into. + Valid options are keys of GF_TO_VT_MAPPING + + Returns: + Vt.Array: Vt-typed array, of specified type corresponding to @element_type + """ + GF_TO_VT_MAPPING = { + lazy.pxr.Gf.Vec3d: lazy.pxr.Vt.Vec3dArray, + lazy.pxr.Gf.Vec3f: lazy.pxr.Vt.Vec3fArray, + lazy.pxr.Gf.Vec3h: lazy.pxr.Vt.Vec3hArray, + lazy.pxr.Gf.Quatd: lazy.pxr.Vt.QuatdArray, + lazy.pxr.Gf.Quatf: lazy.pxr.Vt.QuatfArray, + lazy.pxr.Gf.Quath: lazy.pxr.Vt.QuathArray, + int: lazy.pxr.Vt.IntArray, + float: lazy.pxr.Vt.FloatArray, + bool: lazy.pxr.Vt.BoolArray, + str: lazy.pxr.Vt.StringArray, + chr: lazy.pxr.Vt.CharArray, + } + + # Make sure array type is valid + assert_valid_key(key=element_type, valid_keys=GF_TO_VT_MAPPING, name="array element type") + + # Construct list of values + arr_list = [] + + # Check first to see if elements are vectors or not. If this is an iterable value that is not a string, + # then this is a vector and we have to map it to the correct type via * + is_vec_element = (isinstance(arr[0], Iterable)) and (not isinstance(arr[0], str)) + + # Loop over array and set values + for ele in arr: + arr_list.append(element_type(*ele) if is_vec_element else ele) + + return GF_TO_VT_MAPPING[element_type](arr_list) + + +def get_prim_nested_children(prim): + """ + Grabs all nested prims starting from root @prim via depth-first-search + + Args: + prim (Usd.Prim): root prim from which to search for nested children prims + + Returns: + list of Usd.Prim: nested prims + """ + prims = [] + for child in lazy.isaacsim.core.utils.prims.get_prim_children(prim): + prims.append(child) + prims += get_prim_nested_children(prim=child) + + return prims + + +def create_joint( + prim_path, + joint_type, + body0=None, + body1=None, + enabled=True, + exclude_from_articulation=False, + joint_frame_in_parent_frame_pos=None, + joint_frame_in_parent_frame_quat=None, + joint_frame_in_child_frame_pos=None, + joint_frame_in_child_frame_quat=None, + break_force=None, + break_torque=None, + stage=None, +): + """ + Creates a joint between @body0 and @body1 of specified type @joint_type + + Args: + prim_path (str): absolute path to where the joint will be created + joint_type (str or JointType): type of joint to create. Valid options are: + "FixedJoint", "Joint", "PrismaticJoint", "RevoluteJoint", "SphericalJoint" + (equivalently, one of JointType) + body0 (str or None): absolute path to the first body's prim. At least @body0 or @body1 must be specified. + body1 (str or None): absolute path to the second body's prim. At least @body0 or @body1 must be specified. + enabled (bool): whether to enable this joint or not. + exclude_from_articulation (bool): whether to exclude this joint from the articulation or not. + joint_frame_in_parent_frame_pos (th.tensor or None): relative position of the joint frame to the parent frame (body0). + joint_frame_in_parent_frame_quat (th.tensor or None): relative orientation of the joint frame to the parent frame (body0). + joint_frame_in_child_frame_pos (th.tensor or None): relative position of the joint frame to the child frame (body1). + joint_frame_in_child_frame_quat (th.tensor or None): relative orientation of the joint frame to the child frame (body1). + break_force (float or None): break force for linear dofs, unit is Newton. + break_torque (float or None): break torque for angular dofs, unit is Newton-meter. + stage (None or Usd.Stage): If specified, stage on which the joint should be created. If None, will use og.sim.stage + + Returns: + Usd.Prim: Created joint prim + """ + with og.sim.editing_usd(stage=stage): + current_stage = stage or og.sim.stage + # Make sure we have valid joint_type + assert JointType.is_valid(joint_type=joint_type), f"Invalid joint specified for creation: {joint_type}" + + # Make sure at least body0 or body1 is specified + assert ( + body0 is not None or body1 is not None + ), "At least either body0 or body1 must be specified when creating a joint!" + + # Create the joint + joint = getattr(lazy.pxr.UsdPhysics, joint_type).Define(current_stage, prim_path) + + # Possibly add body0, body1 targets + if body0 is not None: + assert current_stage.GetPrimAtPath(body0).IsValid(), f"Invalid body0 path specified: {body0}" + joint.GetBody0Rel().SetTargets([lazy.pxr.Sdf.Path(body0)]) + if body1 is not None: + assert current_stage.GetPrimAtPath(body1).IsValid(), f"Invalid body1 path specified: {body1}" + joint.GetBody1Rel().SetTargets([lazy.pxr.Sdf.Path(body1)]) + + # Get the prim pointed to at this path + joint_prim = current_stage.GetPrimAtPath(prim_path) + + # Apply joint API interface + ensure_usd_api(joint_prim, lazy.pxr.PhysxSchema.PhysxJointAPI) + + # We need to step rendering once to auto-fill the local pose before overwriting it. + # Note that for some reason, if multi_gpu is used, this line will crash if create_joint is called during on_contact + # callback, e.g. when an attachment joint is being created due to contacts. + # TODO(#2082): Is this necessary? Can it be removed altogether or replaced with a refresh? + if stage is None: + og.sim.render() + + with og.sim.editing_usd(stage=stage): + if joint_frame_in_parent_frame_pos is not None: + joint_prim.GetAttribute("physics:localPos0").Set( + lazy.pxr.Gf.Vec3f(*joint_frame_in_parent_frame_pos.tolist()) + ) + if joint_frame_in_parent_frame_quat is not None: + joint_prim.GetAttribute("physics:localRot0").Set( + lazy.pxr.Gf.Quatf(*joint_frame_in_parent_frame_quat[[3, 0, 1, 2]].tolist()) + ) + if joint_frame_in_child_frame_pos is not None: + joint_prim.GetAttribute("physics:localPos1").Set( + lazy.pxr.Gf.Vec3f(*joint_frame_in_child_frame_pos.tolist()) + ) + if joint_frame_in_child_frame_quat is not None: + joint_prim.GetAttribute("physics:localRot1").Set( + lazy.pxr.Gf.Quatf(*joint_frame_in_child_frame_quat[[3, 0, 1, 2]].tolist()) + ) + + if break_force is not None: + joint_prim.GetAttribute("physics:breakForce").Set(break_force) + if break_torque is not None: + joint_prim.GetAttribute("physics:breakTorque").Set(break_torque) + + # Possibly (un-/)enable this joint + joint_prim.GetAttribute("physics:jointEnabled").Set(enabled) + + # Possibly exclude this joint from the articulation + joint_prim.GetAttribute("physics:excludeFromArticulation").Set(exclude_from_articulation) + + # Update handles to include the new joint + og.sim.update_handles() + + # Return this joint + return joint_prim + + +@wp.kernel +def _aabb_reduce_kernel( + pose_matrices: wp.array(dtype=wp.mat44), # (N_links_total,) + mesh_ids: wp.array(dtype=wp.uint64), # (N_links_total,) — 0 if link has no mesh + aabb_links: wp.array(dtype=wp.int32), # (K,) k → which link this thread belongs to + aabb_vertices: wp.array(dtype=wp.int32), # (K,) k → which vertex within that link's mesh + aabb_objs: wp.array(dtype=wp.int32), # (K,) k → output row (= s*O + obj_idx) + out_values: wp.array2d(dtype=wp.float32), # (S*O, 6) +): + # K = total number of link vertices that have AABB state = total number of threads. + # Each thread processes ONE (link, vertex) pair. Three K-length lookup tables tell + # thread k where to read the point from and where to write its contribution. + # + # Example with K = 5, two tracked links A (3 verts → object 5) and B (2 verts → object 7): + # + # thread index k: 0 1 2 3 4 + # ───────────────────────── + # aabb_links: [ A , A , A , B , B ] ← which link I belong to + # aabb_vertices: [ 0 , 1 , 2 , 0 , 1 ] ← which vertex within that link + # aabb_objs: [ 5 , 5 , 5 , 7 , 7 ] ← which object's AABB I write to + k = wp.tid() + body = aabb_links[k] + # NOTE: wp.mesh_get_point(id, i) is a *face-vertex* lookup (returns mesh.points[mesh.indices[i]]), + # not a vertex lookup. We want vertex i directly, so we read mesh.points[i] via wp.mesh_get(id). + mesh = wp.mesh_get(mesh_ids[body]) + pt3 = mesh.points[aabb_vertices[k]] + pt4 = wp.vec4(pt3[0], pt3[1], pt3[2], 1.0) + world = wp.mul(pose_matrices[body], pt4) + obj = aabb_objs[k] + wp.atomic_min(out_values, obj, 0, world[0]) + wp.atomic_min(out_values, obj, 1, world[1]) + wp.atomic_min(out_values, obj, 2, world[2]) + wp.atomic_max(out_values, obj, 3, world[0]) + wp.atomic_max(out_values, obj, 4, world[1]) + wp.atomic_max(out_values, obj, 5, world[2]) + + +@wp.kernel +def _aabb_baselink_fallback_kernel( + poses: wp.array2d(dtype=wp.float32), # POSES_GPU as (N_links_total, 7) + base_link_links: wp.array(dtype=wp.int32), # (N_rigid,) flat body idx of each rigid obj's base link + base_link_objs: wp.array(dtype=wp.int32), # (N_rigid,) output row in out_values + out_values: wp.array2d(dtype=wp.float32), # (S*O, 6) — populated by _aabb_reduce_kernel +): + # Each thread = one rigid object's base link. If the main kernel never touched this + # obj's row (still +inf at lo_x), no link had collision geometry — write a point AABB + # at the base link's world position. Each rigid object has exactly one base link, so + # threads never share an obj — non-atomic writes are safe. + n = wp.tid() + obj = base_link_objs[n] + if wp.isinf(out_values[obj, 0]): + body = base_link_links[n] + x = poses[body, 0] + y = poses[body, 1] + z = poses[body, 2] + out_values[obj, 0] = x + out_values[obj, 1] = y + out_values[obj, 2] = z + out_values[obj, 3] = x + out_values[obj, 4] = y + out_values[obj, 5] = z + + +@wp.kernel +def _poses_to_matrices_kernel( + poses: wp.array2d(dtype=wp.float32), # (N, 7) — [px, py, pz, qx, qy, qz, qw] + matrices: wp.array(dtype=wp.mat44), # (N,) +): + """Convert (N, 7) pose tensor (xyz + xyzw quat) into (N,) wp.mat44 rigid transforms.""" + i = wp.tid() + px = poses[i, 0] + py = poses[i, 1] + pz = poses[i, 2] + qx = poses[i, 3] + qy = poses[i, 4] + qz = poses[i, 5] + qw = poses[i, 6] + + # Normalize the quaternion defensively (PhysX usually returns unit quats, but matching + # transform_utils.quat2mat behavior keeps results bit-for-bit consistent with the legacy CPU path). + n = wp.sqrt(qx * qx + qy * qy + qz * qz + qw * qw) + inv_n = wp.float32(1.0) / n + qx = qx * inv_n + qy = qy * inv_n + qz = qz * inv_n + qw = qw * inv_n + + xx = qx * qx + yy = qy * qy + zz = qz * qz + xy = qx * qy + xz = qx * qz + yz = qy * qz + xw = qx * qw + yw = qy * qw + zw = qz * qw + + matrices[i] = wp.mat44( + wp.float32(1.0) - wp.float32(2.0) * (yy + zz), + wp.float32(2.0) * (xy - zw), + wp.float32(2.0) * (xz + yw), + px, + wp.float32(2.0) * (xy + zw), + wp.float32(1.0) - wp.float32(2.0) * (xx + zz), + wp.float32(2.0) * (yz - xw), + py, + wp.float32(2.0) * (xz - yw), + wp.float32(2.0) * (yz + xw), + wp.float32(1.0) - wp.float32(2.0) * (xx + yy), + pz, + wp.float32(0.0), + wp.float32(0.0), + wp.float32(0.0), + wp.float32(1.0), + ) + + +class RigidBodyViewAPI: + """ + Batched rigid-body pose cache for all rigid bodies across all scenes. + + Poses are stored in a flat layout keyed by absolute prim path, so each scene can + have an independent link count (different object models are supported). + + Two categories of links are tracked: + - physx_tracked: rigid body links included in create_rigid_body_view. + Poses updated every step from PhysX. + - physx_untracked: kinematic-only articulated objects' links not tracked by physx's rigid body view. + Poses seeded once at initialize_view() and refreshed only by invalidate_kinematic(). + + Flat index layout in POSE_MATRICES (N_links_total, 4, 4): + [scene_0 physx_tracked] [scene_1 physx_tracked] ... [physx_untracked links across all scenes] + + Also exposes LINK_MESH_IDS / LINK_VERTEX_COUNTS so the _aabb_reduce_kernel can read each + link's collision mesh via wp.mesh_get_point. Each link's wp.Mesh is owned by this view + (built once in initialize_view from link.collision_mesh_cpu_data with batched H2D copies), + and stored in cls._link_meshes alongside the GPU-resident points/faces backing tensors. + """ + + # Rigid body view for batched pose reads (one per scene) + _RIGID_BODY_VIEW = None + + # Flat path index across all scenes keyed by absolute prim path. + _PATH_TO_IDX = {} # {link_absolute_prim_path: int} + _IDX_TO_PATH = [] # list[link_absolute_prim_path] + + # Position + quaternion pose of all links in the scene, indexed by flat index. + # POSES (CPU pinned): where read_from_physx() copies PhysX output; + # POSES_GPU: GPU mirror; + # POSE_MATRICES: the derived (N,) wp.mat44 transform table. + # All three are populated inside the captured wp.graph each step via update(). + POSES = None # wp.array, device="cpu", pinned=True, shape=(N_links_total, 7), float32 + POSES_GPU = None # wp.array, device="cuda", shape=(N_links_total, 7), float32 + POSE_MATRICES = None # wp.array, device="cuda", shape=(N_links_total,), wp.mat44 + + # Per-link wp.Mesh ids (0 if link has no collision geometry), kernel input for + # wp.mesh_get_point(mesh_ids[body], v). Built in initialize_view via batched H2D copies of + # link.collision_mesh_cpu_data, with each per-link wp.Mesh viewing a slice of the shared + # GPU points/faces tensors. + LINK_MESH_IDS = None # wp.array(dtype=wp.uint64) on CUDA, shape (N_links_total,) + + # Per-link vertex count. Used by prepare_aabb_kernel_inputs to vectorize the K-length + # thread-table expansion. CPU is fine (small, no transfer needed during expansion). + LINK_VERTEX_COUNTS = None # th.Tensor on CPU, shape (N_links_total,) int32 + + # Per-link wp.Mesh cache, keyed by absolute prim path. Keeps wp.Mesh objects (and their + # backing GPU points/faces tensors) alive across initialize_view() calls so re-init only + # rebuilds meshes for newly-registered links. Reuse is gated by Python id(link), so a + # rebuild also happens if a path is registered to a different RigidPrim instance. + # Each entry: {"link_id": int, "mesh": wp.Mesh, "n_pts": int, + # "pts_buffer": th.Tensor, "faces_buffer": th.Tensor}. + _link_mesh_cache = {} + + # K = total number links' vertices of objects with AABB states + # Cached K-length kernel inputs for the main AABB kernel. Built by + # prepare_aabb_kernel_inputs from the (PRIM_BODY_IDX, LINK_IDX) pair AABB.initialize_view + # provides. Reset to None on every initialize_view(). + _aabb_links = None # wp.array(dtype=wp.int32) on CUDA, shape (K,) + _aabb_vertices = None # wp.array(dtype=wp.int32) on CUDA, shape (K,) + _aabb_objs = None # wp.array(dtype=wp.int32) on CUDA, shape (K,) + + # Cached fallback-kernel inputs for meshes without boundry points (one entry per rigid object's base link). + _aabb_base_link_links = None # wp.array(dtype=wp.int32) on CUDA, shape (N_rigid,) + _aabb_base_link_objs = None # wp.array(dtype=wp.int32) on CUDA, shape (N_rigid,) + + # Tolerances for change detection + _POS_EPS = 1e-4 + _ORI_EPS = 1e-4 + + @classmethod + def initialize_view(cls): + """ + Initializes the rigid body view. Note: Can only be done when sim is playing! + + Builds a flat layout keyed by absolute prim path so each scene can have an + independent link count. Layout of POSE_MATRICES (N_links_total, 4, 4): + [scene_0 physx_tracked] [scene_1 physx_tracked] ... [physx_untracked across all scenes] + + Also collects each registered link's wp.Mesh id and vertex count into + LINK_MESH_IDS / LINK_VERTEX_COUNTS for the AABB Warp kernel. + """ + assert og.sim.is_playing(), "Cannot create rigid body view while sim is not playing!" + + # Ensure Warp's runtime is up before any kernel launches in get_aabb. Idempotent — + # subsequent calls are no-ops once the runtime has been constructed. + wp.init() + + # Snapshot existing kinematic-link poses ton reuse them below. + # cls.POSES is now a wp.array, convert to a torch view for the per-row + # indexing/unsqueeze below. + prev_path_to_idx = dict(cls._PATH_TO_IDX) # snapshot before clear() + prev_poses = wp.to_torch(cls.POSES) if cls.POSES is not None else None + + # Reset + cls.clear() + + if len(og.sim.scenes) == 0: + return + + # If there are no rigid bodies in any scene, return early (view creation would fail) + has_rigid_bodies = any( + obj.prim_type == PrimType.RIGID and len(obj.links) > 0 for scene in og.sim.scenes for obj in scene.objects + ) + if not has_rigid_bodies: + cls.clear() + return + + # Create a PhysX view for all scenes, build _PATH_TO_IDX, collect poses + poses_list = [] + + with suppress_omni_log(channels=["omni.physx.tensors.plugin"]): + cls._RIGID_BODY_VIEW = og.sim.physics_sim_view.create_rigid_body_view(pattern="/World/scene_*/*/*") + for abs_path in list(cls._RIGID_BODY_VIEW.prim_paths): + cls._PATH_TO_IDX[abs_path] = len(cls._PATH_TO_IDX) + cls._IDX_TO_PATH.append(abs_path) + poses_list.append(cls._RIGID_BODY_VIEW.get_transforms().clone()) + + # Add physx_untracked kinematic links and remember each registered link object so + # we can pull its wp.Mesh after _PATH_TO_IDX is finalized below. + link_by_idx = {} # {flat_idx: link object} + + for _, scene in enumerate(og.sim.scenes): + for obj in scene.objects: + is_untracked = obj.kinematic_only and obj.prim_type != PrimType.CLOTH + for link in obj.links.values(): + abs_path = link.prim_path + + # Kinematic objects' child links (e.g. fillable meta links) may be dynamic + # and already tracked by PhysX even though the parent is kinematic_only=True. + # Only manually register links that PhysX did not track. + if is_untracked and abs_path not in cls._PATH_TO_IDX: + idx = len(cls._PATH_TO_IDX) + cls._PATH_TO_IDX[abs_path] = idx + cls._IDX_TO_PATH.append(abs_path) + + if abs_path in prev_path_to_idx and prev_poses is not None: + # Reuse the cached pose + pose = prev_poses[prev_path_to_idx[abs_path]].unsqueeze(0) + elif og.sim.currently_stepping: + # New kinematic link appearing mid-step, cannot read Fabric. + # Use zero placeholder. + # Corrected by the next out-of-step initialize_view() or update_handles(). + pose = th.zeros(1, 7) + else: + pos, quat_xyzw = link.get_position_orientation() + pose = th.cat([pos, quat_xyzw]).unsqueeze(0) + poses_list.append(pose) + + if abs_path in cls._PATH_TO_IDX: + link_by_idx[cls._PATH_TO_IDX[abs_path]] = link + + initial_poses = th.cat(poses_list, dim=0).contiguous() # (N, 7) torch CPU, used only to seed + N = initial_poses.shape[0] + cls.POSES = wp.empty(shape=(N, 7), dtype=wp.float32, device="cpu", pinned=True) + cls.POSES_GPU = wp.zeros(shape=(N, 7), dtype=wp.float32, device="cuda") + cls.POSE_MATRICES = wp.zeros(shape=(N,), dtype=wp.mat44, device="cuda") + # Seed POSES via the zero-copy torch view (same memory as the wp.array). + wp.to_torch(cls.POSES)[:] = initial_poses + + # Build / reuse per-link wp.Mesh objects. Cached entries (same prim path + same RigidPrim + # instance) are reused as-is; only newly-registered links flow through a single batched + # H2D copy + BVH-build pass. Drop cache entries for paths no longer registered. + N_total = len(cls._PATH_TO_IDX) + mesh_id_list = [0] * N_total + vertex_count_list = [0] * N_total + + new_cache = {} + new_links = [] # (idx, abs_path, link, pts_cpu, faces_cpu) for paths needing a rebuild + for idx, link in link_by_idx.items(): + abs_path = link.prim_path + cached = cls._link_mesh_cache.get(abs_path) + if cached is not None and cached["link_id"] == id(link): + mesh_id_list[idx] = cached["mesh"].id + vertex_count_list[idx] = cached["n_pts"] + new_cache[abs_path] = cached + continue + data = link.collision_mesh_cpu_data + if data is None: + continue + pts_cpu, faces_cpu = data + new_links.append((idx, abs_path, link, pts_cpu, faces_cpu)) + + if new_links: + pts_segments = [item[3] for item in new_links] + faces_segments = [item[4] for item in new_links] + pts_offsets = [0] + faces_offsets = [0] + for p, f in zip(pts_segments, faces_segments): + pts_offsets.append(pts_offsets[-1] + p.shape[0]) + faces_offsets.append(faces_offsets[-1] + f.shape[0]) + + pts_gpu_buf = th.cat(pts_segments, dim=0).cuda() + faces_gpu_buf = th.cat(faces_segments, dim=0).cuda() + + for i, (idx, abs_path, link, pts_cpu, _) in enumerate(new_links): + p0, p1 = pts_offsets[i], pts_offsets[i + 1] + f0, f1 = faces_offsets[i], faces_offsets[i + 1] + pts_view = pts_gpu_buf[p0:p1] + faces_view = faces_gpu_buf[f0:f1] + mesh = wp.Mesh( + points=wp.from_torch(pts_view, dtype=wp.vec3), + indices=wp.from_torch(faces_view), + ) + mesh_id_list[idx] = mesh.id + vertex_count_list[idx] = pts_cpu.shape[0] + # Hold strong refs to the batch buffers in the cache entry so the wp.array + # views into them stay valid for the lifetime of `mesh`. + new_cache[abs_path] = { + "link_id": id(link), + "mesh": mesh, + "n_pts": pts_cpu.shape[0], + "pts_buffer": pts_gpu_buf, + "faces_buffer": faces_gpu_buf, + } + + cls._link_mesh_cache = new_cache + cls.LINK_MESH_IDS = wp.array(mesh_id_list, dtype=wp.uint64, device="cuda") + cls.LINK_VERTEX_COUNTS = th.tensor(vertex_count_list, dtype=th.int32) + + # Invalidate any previously cached AABB kernel inputs — AABB.initialize_view() must + # call prepare_aabb_kernel_inputs() again before the next get_aabb() call. + cls._aabb_links = None + cls._aabb_vertices = None + cls._aabb_objs = None + cls._aabb_base_link_links = None + cls._aabb_base_link_objs = None + + @classmethod + def read_from_physx(cls): + """ + Read the latest PhysX transforms into the pinned-CPU staging buffer (cls.POSES). + Stays on the host: PhysX returns a CPU torch tensor, and graph capture freezes the + call (see scripts/test_physx_in_warp_graph.py). The H2D copy + pose2mat kernel run + inside the captured wp.graph via update(). + + physx_untracked links are never touched here; they are updated only by invalidate_kinematic(). + """ + if not cls._RIGID_BODY_VIEW: + return + try: + transforms = cls._RIGID_BODY_VIEW.get_transforms() # torch CPU tensor + except Exception: + log.warning( + "RigidBodyViewAPI cannot fetch transforms because the physics sim view is invalid. " + "This is expected during initial scene loading." + ) + return + + # Copy PhysX output into the fixed pinned wp.array via a torch view + N_physx_tracked = transforms.shape[0] + wp.to_torch(cls.POSES)[:N_physx_tracked] = transforms + wp.copy(cls.POSES_GPU, cls.POSES) + + @classmethod + def get_flat_idx(cls, abs_prim_path): + """ + Return the flat index into POSE_MATRICES for a link's absolute prim path, or None. + + Args: + abs_prim_path (str): Absolute prim path of the link (e.g. /World/scene_0/obj/link). + + Returns: + int or None + """ + return cls._PATH_TO_IDX.get(abs_prim_path) + + @classmethod + def prepare_aabb_kernel_inputs(cls, prim_body_idx, link_idx, base_link_body_idx, base_link_values_idx): + """ + Build and cache the K-length kernel input tables for the AABB kernel and the + N_rigid-length tables for the base-link fallback kernel. Called once by + AABB.initialize_view() after it builds its (PRIM_BODY_IDX, LINK_IDX, + BASE_LINK_BODY_IDX, BASE_LINK_VALUES_IDX) tensors. + + Args: + prim_body_idx (th.Tensor): (n_tracked_links,) int32 CPU — flat idx per AABB-tracked link + link_idx (th.Tensor): (n_tracked_links,) int32 CPU — output row (s*O + obj_idx) per tracked link + base_link_body_idx (th.Tensor): (n_rigid_objs,) int32 CPU — flat idx of each rigid object's base link + base_link_values_idx (th.Tensor):(n_rigid_objs,) int32 CPU — output row per rigid object + """ + # Always reset the cache; we rebuild what we can below. + cls._aabb_links = None + cls._aabb_vertices = None + cls._aabb_objs = None + cls._aabb_base_link_links = None + cls._aabb_base_link_objs = None + + # Nothing to prepare if no rigid bodies are registered. + if cls.LINK_VERTEX_COUNTS is None: + return + + if prim_body_idx.numel() > 0: + # Goal: expand from "one entry per tracked link" (length = n_tracked_links) to + # "one entry per (link, vertex) pair" (length K = sum of vertex counts). The + # K-length tables are what the AABB kernel reads, one per thread. + # + # All ops on CPU; n_tracked_links is small. + # + # TODO(vector): reconsider this approach. K = sum(vertex_counts) can be large, and we + # keep three K-length device arrays (_aabb_links, _aabb_vertices, _aabb_objs) + # resident for the lifetime of the view. A more memory-efficient alternative is + # to launch the AABB kernel over (n_tracked_links, max_verts) and have each + # thread derive (link, vertex) from its tid + a small per-link cumsum table. + + verts_per_link = cls.LINK_VERTEX_COUNTS[prim_body_idx] # (n_tracked_links,) + K = int(verts_per_link.sum().item()) + + # Repeat each link's body / obj index by its vertex count so each thread that + # belongs to that link sees the same body and obj. + aabb_links = th.repeat_interleave(prim_body_idx, verts_per_link) # (K,) + aabb_objs = th.repeat_interleave(link_idx, verts_per_link) # (K,) + + # Compute for each link, the index of the first thread that run the link's vertex + link_thread_starts = th.cat([th.zeros(1, dtype=verts_per_link.dtype), verts_per_link.cumsum(0)]) + thread_idx = th.arange(K, dtype=verts_per_link.dtype) + # for thread k, find the smallest i such that k < link_thread_starts[1:][i] + tracked_link_per_thread = th.searchsorted(link_thread_starts[1:], thread_idx, right=True) + aabb_vertices = (thread_idx - link_thread_starts[tracked_link_per_thread]).to(th.int32) + + cls._aabb_links = wp.from_torch(aabb_links.cuda()) + cls._aabb_vertices = wp.from_torch(aabb_vertices.cuda()) + cls._aabb_objs = wp.from_torch(aabb_objs.cuda()) + + if base_link_body_idx.numel() > 0: + cls._aabb_base_link_links = wp.from_torch(base_link_body_idx.cuda()) + cls._aabb_base_link_objs = wp.from_torch(base_link_values_idx.cuda()) + + @classmethod + def get_aabb(cls, out_values): + """ + Compute per-object world-space AABBs by launching two Warp kernels back-to-back on + torch's current CUDA stream: + 1. _aabb_reduce_kernel: per-(link, vertex) thread, transforms one local point and + atomically narrows the owning object's (lo, hi) row of out_values. + 2. _aabb_baselink_fallback_kernel: per-rigid-object thread, writes base-link + position as a point AABB for any object whose row was untouched (still +inf). + + Args: + out_values (th.Tensor): (S*O, 6) float32 CUDA — caller pre-fills with +/-inf, + written in-place. + """ + has_reduce = cls._aabb_links is not None and cls._aabb_links.shape[0] > 0 + has_fallback = cls._aabb_base_link_links is not None and cls._aabb_base_link_links.shape[0] > 0 + if not has_reduce and not has_fallback: + return + out_arr = wp.from_torch(out_values) + + if has_reduce: + wp.launch( + kernel=_aabb_reduce_kernel, + dim=cls._aabb_links.shape[0], + inputs=[ + cls.POSE_MATRICES, + cls.LINK_MESH_IDS, + cls._aabb_links, + cls._aabb_vertices, + cls._aabb_objs, + out_arr, + ], + device="cuda", + ) + # use base-link pose for meshes without boundry points + if has_fallback: + wp.launch( + kernel=_aabb_baselink_fallback_kernel, + dim=cls._aabb_base_link_links.shape[0], + inputs=[ + cls.POSES_GPU, + cls._aabb_base_link_links, + cls._aabb_base_link_objs, + out_arr, + ], + device="cuda", + ) + + @classmethod + def invalidate_kinematic(cls, links): + """ + Refresh the CPU pose staging buffer for kinematic links after an explicit move. + + For physx_untracked links (no physics:RigidBodyAPI) this is the only update path. + For physx_tracked kinematic links this write is harmless — read_from_physx() will + re-read from PhysX on the next step. + + Only POSES (pinned CPU) is touched here. POSES_GPU and POSE_MATRICES are + refreshed by the next captured-graph replay — every consumer reads them inside the + graph (or post-synchronize via UpdateStateMixin), so no eager H2D / kernel is needed. + + Args: + links: iterable of RigidPrim link objects whose poses should be refreshed. + """ + if cls.POSES is None: + return + # Zero-copy torch view over the pinned wp.array — same memory. + poses_torch = wp.to_torch(cls.POSES) + for link in links: + idx = cls._PATH_TO_IDX.get(link.prim_path) + if idx is None: + continue # not registered (e.g. particle templates not in scene.objects) + pos, quat_xyzw = link.get_position_orientation() + poses_torch[idx, :3] = pos + poses_torch[idx, 3:] = quat_xyzw + + @classmethod + def update(cls): + """ + Enqueue the per-step H2D + pose-to-mat work onto the current Warp stream. Called + inside wp.ScopedCapture so the captured graph replays the H2D + kernel together with + the tensorized-state global_updates each step. + """ + if cls.POSES is None or cls.POSES_GPU is None or cls.POSE_MATRICES is None: + return + N = cls.POSES_GPU.shape[0] + if N == 0: + return + wp.launch( + _poses_to_matrices_kernel, + dim=N, + inputs=[cls.POSES_GPU, cls.POSE_MATRICES], + device="cuda", + ) + + @classmethod + def clear(cls): + """Reset all cached state.""" + cls._RIGID_BODY_VIEW = None + cls._PATH_TO_IDX = {} + cls._IDX_TO_PATH = [] + cls.POSES = None + cls.POSES_GPU = None + cls.POSE_MATRICES = None + cls.LINK_MESH_IDS = None + cls.LINK_VERTEX_COUNTS = None + cls._link_mesh_cache = {} + cls._aabb_links = None + cls._aabb_vertices = None + cls._aabb_objs = None + cls._aabb_base_link_links = None + cls._aabb_base_link_objs = None + + +class ArticulatedObjectViewAPI: + """ + Batched DOF position cache for non-robot articulated objects across all scenes. + + We exclude robots because they have a lot more DOFs than other objects, which would inflate the + size of this view drastically. However, this view is mainly used for Open state checking, which + does not apply to robots. As a result, robots are excluded for optimization purposes. + + Creates a single ArticulationView covering all non-robot articulated objects across all scenes + using the pattern "/World/scene_\\d+/articulated_.*" (objects are placed under articulated_ + by _preapply_articulation_root in usd_object.py). + + Data layout: + _VIEW ArticulationView single view for all non-robot articulated objects + _OBJ_TO_VIEW_IDX {abs_art_root_path: int} row index in _JOINT_POSITIONS + _JOINT_POSITIONS (N_objects_all_scenes, max_dof) one row per object per scene, PhysX row order + """ + + _VIEW = None + _OBJ_TO_VIEW_IDX = {} + _JOINT_POSITIONS = None # wp.array, device="cuda", shape=(N_art, max_dof), float32 + + @classmethod + def initialize_view(cls): + cls.clear() + + if len(og.sim.scenes) == 0: + return + + from omnigibson.robots import Robot + + articulation_objs = [ + obj + for scene in og.sim.scenes + for obj in scene.objects + if obj.relative_prim_path.startswith("/articulated__") and not isinstance(obj, Robot) + ] + if not articulation_objs: + return + + # Build the view from the exact articulation root paths of the registered objects. + # If directly use "/World/scene_*/articulated__*/*" it will also include visual-only + # articulations which have register=False (such as the JoyLo teleop "ghost" robot). + expected_paths = [obj.articulation_root_path for obj in articulation_objs] + cls._VIEW = og.sim.physics_sim_view.create_articulation_view(expected_paths) + cls._OBJ_TO_VIEW_IDX = {abs_path: row for row, abs_path in enumerate(cls._VIEW.prim_paths)} + # Allocate fixed pinned-CPU and CUDA wp.arrays of the right shape. + seed_positions = cls._VIEW.get_dof_positions().contiguous() # torch CPU, used only to seed + N, max_dof = seed_positions.shape + cls._JOINT_POSITIONS = wp.zeros(shape=(N, max_dof), dtype=wp.float32, device="cuda") + wp.copy(cls._JOINT_POSITIONS, wp.from_torch(seed_positions)) + + @classmethod + def read_from_physx(cls): + """Pull latest DOF positions from PhysX into the pinned CPU staging buffer. + Stays on the host (PhysX returns CPU torch tensor). H2D happens inside the captured + wp.graph via update().""" + if cls._VIEW is None or cls._JOINT_POSITIONS is None: + return + positions = cls._VIEW.get_dof_positions() # torch CPU + wp.copy(cls._JOINT_POSITIONS, wp.from_torch(positions.contiguous())) + + @classmethod + def get_view_row(cls, abs_prim_path): + """Return row index in _JOINT_POSITIONS for a given absolute articulation root path, or None.""" + return cls._OBJ_TO_VIEW_IDX.get(abs_prim_path) + + @classmethod + def get_max_dof(cls): + """Return the padded DOF width of _JOINT_POSITIONS; 0 if not initialized.""" + return cls._JOINT_POSITIONS.shape[1] if cls._JOINT_POSITIONS is not None else 0 + + @classmethod + def clear(cls): + cls._VIEW = None + cls._OBJ_TO_VIEW_IDX = {} + cls._JOINT_POSITIONS = None + + +class RigidContactAPIImpl: + """ + Class containing class methods to aggregate rigid body contacts across all rigid bodies in the simulator. + + This API checks for contacts on every physics step, and then aggregates this into a boolean contact matrix + on every non-physics step. Callers can then use this API to query either for contacts that are still ongoing, + or contacts that occurred at any point since the last non-physics step (e.g. for checking for contact events). + Contact information is cached per-physics-step and only updated for body pairs who have at least one side + not asleep, which allows this API to bypass the limitations of the view (which returns contacts only for awake bodies). + + Since there is no direct tensorized way to check for object sleep state, this API approximates this by checking for + the net contact force on an object (only reported for awake bodies) and also the position change since the last step. + """ + + def __init__(self): + # Dictionary mapping rigid body prim path to corresponding row / col index in the contact view matrix + self._PATH_TO_ROW_IDX = dict() + self._PATH_TO_COL_IDX = dict() + + # Arrays of rigid body prim paths where each array index maps directly to the contact matrix row / col + self._ROW_IDX_TO_PATH = dict() + self._COL_IDX_TO_PATH = dict() + + # Contact view for generating contact matrices at each timestep + self._CONTACT_VIEW = dict() + + # Rigid body view for batched body transform reads used by persistence logic + self._RIGID_BODY_VIEW = dict() + + # Precomputed tensors mapping row/col indices to rigid body view indices + self._CONTACT_MATRIX_ROWS_TO_RIGID_BODY_ROWS = dict() + self._CONTACT_MATRIX_COLS_TO_RIGID_BODY_ROWS = dict() + self._CONTACT_MATRIX_COLS_HAS_RIGID_BODY = dict() + + # int32 wp.array mirrors of the row/col→rigid-body index maps, consumed by + # the warp kernels in update(). Kept alongside the torch versions to avoid + # type-casting inside the captured graph. + self._ROW_TO_RIGID_WP = dict() + self._COL_TO_RIGID_WP = dict() + + # Body → row index map (B,), -1 if body is not a contact-matrix row body. + # Inverse of _CONTACT_MATRIX_ROWS_TO_RIGID_BODY_ROWS. Used by _body_awake_at_step + # to apply net-force-awake inline, eliminating the separate per-step OR pass. + self._BODY_TO_ROW = dict() + self._BODY_TO_ROW_WP = dict() + + # Contact matrix tracking contacts that occurred at any point during the last N physics steps + # (between consecutive update calls). Shape: (R, C) + self._CONTACT_MATRIX = dict() + self._CONTACT_MATRIX_GPU = dict() # GPU primary — updated directly in update() + # wp.array views over _CONTACT_MATRIX_GPU per scene; wrapped once after each (re-)allocation + # for use inside Warp kernels and graph capture. + self._CONTACT_MATRIX_GPU_WP = dict() + + # Contact matrix tracking contacts at only the most recent physics step. Shape: (R, C) + self._CURRENT_CONTACT_MATRIX = dict() + self._CURRENT_CONTACT_MATRIX_GPU = dict() # GPU primary — updated directly in update() + self._CURRENT_CONTACT_MATRIX_GPU_WP = dict() + + # A matrix of indices for the contact matrix. This can be indexed the same way as the contact matrix + # to obtain row and column indices to map back to prim paths. Shape: (R, C, 2) + self._INDEX_MATRIX = dict() + + # Cached body transforms used for change detection. Shape: (N, 7) [pos(3), quat(4)] + self._BODY_TRANSFORMS = dict() + # wp.array view over _BODY_TRANSFORMS for the contact-matrix and body-transform kernels. + self._BODY_TRANSFORMS_WP = dict() + + # Accumulated impulse matrices and transforms from individual physics steps, + # collected between consecutive update calls. + self._PENDING_STEPS = 0 + self._PENDING_IMPULSES = dict() + self._PENDING_TRANSFORMS = dict() + self._PENDING_NET_FORCES = dict() + + # wp.array views over _PENDING_* for use inside the captured warp graph. + # Re-wrapped on every initialize_view because the underlying torch storage is + # (re-)allocated there. + self._PENDING_IMPULSES_WP = dict() + self._PENDING_TRANSFORMS_WP = dict() + self._PENDING_NET_FORCES_WP = dict() + + # Pinned-CPU wp.array views over the pinned torch CPU mirrors. The captured + # update() does `wp.copy(host_wp, gpu_wp)` after the kernels to refresh them + # each replay — replaces the old sync_cpu_mirrors method that ran outside the + # captured region. + self._CONTACT_MATRIX_HOST_WP = dict() + self._CURRENT_CONTACT_MATRIX_HOST_WP = dict() + + # 1-element GPU buffer holding _PENDING_STEPS — the number of physics sub-steps + # the captured contact kernels should iterate via `n_steps_arr[0]`. + # Must be a wp.array (not a scalar kernel arg) because scalar args get baked into + # the captured graph at capture time, but this count varies between replays + # (``og.sim.step()`` = N sub-steps, ``og.sim.step_physics()`` = 1). + self._N_STEPS_TORCH = None # torch.Tensor on cuda, shape (1,), int32 + self._N_STEPS_GPU = None # wp.array view over _N_STEPS_TORCH + + # Position / orientation tolerances for deciding whether a pair should be updated + self._POS_EPS = 1e-6 + self._ORI_EPS = 1e-4 + + @classmethod + def get_body_filters(cls): + filters = dict() + for scene_idx, scene in enumerate(og.sim.scenes): + filters[scene_idx] = [] + + # Add the (global) floor plane if there is one + if og.sim.floor_plane is not None: + filters[scene_idx].append(og.sim.floor_plane.prim_path + "/collisionPlane") + + for obj in scene.objects: + if obj.prim_type == PrimType.RIGID: + for link in obj.links.values(): + from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim + from omnigibson.prims.rigid_kinematic_prim import RigidKinematicPrim + + if isinstance(link, (RigidDynamicPrim, RigidKinematicPrim)) and link.contact_reporting_enabled: + filters[scene_idx].append(link.prim_path) + + return filters + + @classmethod + def get_max_contact_data_count(cls, n_bodies): + return 256 + + def initialize_view(self): + """ + Initializes the rigid contact view. Note: Can only be done when sim is playing! + """ + assert og.sim.is_playing(), "Cannot create rigid contact view while sim is not playing!" + + # Snapshot the old contact matrices and path mappings so we can carry over + # cached contact state for pairs of bodies that already existed. + prev_contact_matrix = dict(self._CONTACT_MATRIX) + prev_current_contact_matrix = dict(self._CURRENT_CONTACT_MATRIX) + prev_path_to_row_idx = dict(self._PATH_TO_ROW_IDX) + prev_path_to_col_idx = dict(self._PATH_TO_COL_IDX) + + # Rebuild views from scratch to pick up any new/removed bodies. + self.clear() + + self._N_STEPS_TORCH = th.zeros(1, dtype=th.int32, device="cuda") + self._N_STEPS_GPU = wp.from_torch(self._N_STEPS_TORCH, dtype=wp.int32) + + body_filters = self.get_body_filters() + + # If there are no valid bodies, clear all views / mappings and terminate early + if not any(len(filters) > 0 for filters in body_filters.values()): + self.clear() + return + + # Generate views, making sure to update simulation first so the physx backend is synchronized. + with suppress_omni_log(channels=["omni.physx.tensors.plugin"]): + for scene_idx, _ in enumerate(og.sim.scenes): + scene_body_filters = body_filters[scene_idx] + if len(scene_body_filters) == 0: + continue + + # Rows correspond to dynamic rigid prims only, while columns correspond to all rigid prims. + scene_dynamic_body_filters = [] + for obj in og.sim.scenes[scene_idx].objects: + if obj.prim_type == PrimType.RIGID: + for link in obj.links.values(): + from omnigibson.prims.rigid_dynamic_prim import RigidDynamicPrim + + if isinstance(link, RigidDynamicPrim) and link.contact_reporting_enabled: + scene_dynamic_body_filters.append(link.prim_path) + + # If there are only kinematic/static bodies, skip view creation for this scene. + if len(scene_dynamic_body_filters) == 0: + continue + + self._CONTACT_VIEW[scene_idx] = og.sim.physics_sim_view.create_rigid_contact_view( + pattern=f"/World/scene_{scene_idx}/*/*", + filter_patterns=scene_body_filters, + max_contact_data_count=self.get_max_contact_data_count(len(scene_body_filters)), + ) + row_paths = list(self._CONTACT_VIEW[scene_idx].sensor_paths) + col_paths = list(getattr(self._CONTACT_VIEW[scene_idx], "filter_patterns", scene_body_filters)) + + if set(row_paths) != set(scene_dynamic_body_filters): + missing_rows = sorted(set(scene_dynamic_body_filters) - set(row_paths)) + extra_rows = sorted(set(row_paths) - set(scene_dynamic_body_filters)) + raise AssertionError( + "RigidContactAPI contact-view row mismatch. " + f"Expected {len(scene_dynamic_body_filters)} dynamic rows, got {len(row_paths)} rows. " + f"Missing rows ({len(missing_rows)}): {missing_rows}. " + f"Extra rows ({len(extra_rows)}): {extra_rows}." + ) + + if set(col_paths) != set(scene_body_filters): + missing_cols = sorted(set(scene_body_filters) - set(col_paths)) + extra_cols = sorted(set(col_paths) - set(scene_body_filters)) + raise AssertionError( + "RigidContactAPI contact-view column mismatch. " + f"Expected {len(scene_body_filters)} rigid columns, got {len(col_paths)} columns. " + f"Missing columns ({len(missing_cols)}): {missing_cols}. " + f"Extra columns ({len(extra_cols)}): {extra_cols}." + ) + + # Create the lookup tables + self._ROW_IDX_TO_PATH[scene_idx] = row_paths + self._COL_IDX_TO_PATH[scene_idx] = col_paths + self._PATH_TO_ROW_IDX[scene_idx] = {path: i for i, path in enumerate(row_paths)} + self._PATH_TO_COL_IDX[scene_idx] = {path: i for i, path in enumerate(col_paths)} + + # Create the rigid body view, and create some indexing tensors that allow for fast lookups + # between the contact matrix rows and the rigid body view indices. + self._RIGID_BODY_VIEW[scene_idx] = og.sim.physics_sim_view.create_rigid_body_view( + pattern=f"/World/scene_{scene_idx}/*/*" + ) + path_to_view_idx = {path: i for i, path in enumerate(list(self._RIGID_BODY_VIEW[scene_idx].prim_paths))} + self._CONTACT_MATRIX_ROWS_TO_RIGID_BODY_ROWS[scene_idx] = th.tensor( + [path_to_view_idx[path] for path in row_paths], dtype=th.long, device="cuda" + ) + + # Some contact-matrix columns can correspond to kinematic-only links that do not appear + # in the rigid-body view. We encode those as -1 and track a validity mask. + col_to_rigid_rows = [path_to_view_idx.get(path, -1) for path in col_paths] + self._CONTACT_MATRIX_COLS_TO_RIGID_BODY_ROWS[scene_idx] = th.tensor( + col_to_rigid_rows, dtype=th.long, device="cuda" + ) + self._CONTACT_MATRIX_COLS_HAS_RIGID_BODY[scene_idx] = ( + self._CONTACT_MATRIX_COLS_TO_RIGID_BODY_ROWS[scene_idx] >= 0 + ) + ii, jj = th.meshgrid(th.arange(len(row_paths)), th.arange(len(col_paths)), indexing="ij") + self._INDEX_MATRIX[scene_idx] = th.stack([ii, jj], dim=-1) + self._BODY_TRANSFORMS[scene_idx] = self._RIGID_BODY_VIEW[scene_idx].get_transforms().cuda() + + # int32 mirrors of the row/col→rigid-body maps for the warp kernels (wp.tid() + # returns int32; keeping these as int32 avoids per-launch casts inside the captured graph). + row_to_rigid_int32 = self._CONTACT_MATRIX_ROWS_TO_RIGID_BODY_ROWS[scene_idx].to(th.int32) + col_to_rigid_int32 = self._CONTACT_MATRIX_COLS_TO_RIGID_BODY_ROWS[scene_idx].to(th.int32) + self._ROW_TO_RIGID_WP[scene_idx] = wp.from_torch(row_to_rigid_int32, dtype=wp.int32) + self._COL_TO_RIGID_WP[scene_idx] = wp.from_torch(col_to_rigid_int32, dtype=wp.int32) + + # Body → row map (B,), -1 if body is not a row body. Inverse scatter is safe + # without atomics because rows correspond to unique bodies (see initialize_view's + # dynamic-body iteration above). + num_bodies = self._BODY_TRANSFORMS[scene_idx].shape[0] + body_to_row = th.full((num_bodies,), -1, dtype=th.int32, device="cuda") + row_idxs = th.arange(len(row_paths), dtype=th.int32, device="cuda") + body_to_row[self._CONTACT_MATRIX_ROWS_TO_RIGID_BODY_ROWS[scene_idx]] = row_idxs + self._BODY_TO_ROW[scene_idx] = body_to_row + self._BODY_TO_ROW_WP[scene_idx] = wp.from_torch(body_to_row, dtype=wp.int32) + + # wp.array view over _BODY_TRANSFORMS for the contact kernels. + self._BODY_TRANSFORMS_WP[scene_idx] = wp.from_torch(self._BODY_TRANSFORMS[scene_idx], dtype=wp.float32) + + # Build the new contact matrices. Start from current impulses (captures contacts + # for newly added bodies), then overwrite with previously cached values for + # every pair of bodies that already existed before the rebuild. + initial_impulses = self._CONTACT_VIEW[scene_idx].get_contact_force_matrix(dt=1.0) + initial_contacts = th.any(initial_impulses != 0, dim=-1) + self._CONTACT_MATRIX[scene_idx] = initial_contacts.clone().pin_memory() + self._CURRENT_CONTACT_MATRIX[scene_idx] = initial_contacts.clone().pin_memory() + self._CONTACT_MATRIX_GPU[scene_idx] = initial_contacts.cuda() + self._CURRENT_CONTACT_MATRIX_GPU[scene_idx] = initial_contacts.cuda() + + # Finally, remap data from the old matrices into the new ones. This lets us avoid losing our + # cached data when new bodies are added or removed. + old_matrix = prev_contact_matrix.get(scene_idx) + old_current_matrix = prev_current_contact_matrix.get(scene_idx) + old_row_map = prev_path_to_row_idx.get(scene_idx) + old_col_map = prev_path_to_col_idx.get(scene_idx) + if old_matrix is not None and old_row_map is not None and old_col_map is not None: + # Find rows and columns that existed in both the old and new views + surviving_row_paths = [p for p in row_paths if p in old_row_map] + surviving_col_paths = [p for p in col_paths if p in old_col_map] + if surviving_row_paths and surviving_col_paths: + old_row_idxs = th.tensor([old_row_map[p] for p in surviving_row_paths], dtype=th.long) + old_col_idxs = th.tensor([old_col_map[p] for p in surviving_col_paths], dtype=th.long) + new_row_idxs = th.tensor( + [self._PATH_TO_ROW_IDX[scene_idx][p] for p in surviving_row_paths], dtype=th.long + ) + new_col_idxs = th.tensor( + [self._PATH_TO_COL_IDX[scene_idx][p] for p in surviving_col_paths], dtype=th.long + ) + self._CONTACT_MATRIX[scene_idx][new_row_idxs[:, None], new_col_idxs[None, :]] = old_matrix[ + old_row_idxs[:, None], old_col_idxs[None, :] + ] + self._CURRENT_CONTACT_MATRIX[scene_idx][new_row_idxs[:, None], new_col_idxs[None, :]] = ( + old_current_matrix[old_row_idxs[:, None], old_col_idxs[None, :]] + ) + + # Sync GPU mirrors from CPU matrices — carry-over may have updated the CPU tensors above. + self._CONTACT_MATRIX_GPU[scene_idx].copy_(self._CONTACT_MATRIX[scene_idx]) + self._CURRENT_CONTACT_MATRIX_GPU[scene_idx].copy_(self._CURRENT_CONTACT_MATRIX[scene_idx]) + + # Wrap the GPU contact matrices as wp.array views for use inside Warp kernels and + # graph capture. Re-wrap on every initialize_view because the underlying torch + # storage was just (re-)allocated above. Bool tensors → wp.uint8 (byte-per-bool). + self._CONTACT_MATRIX_GPU_WP[scene_idx] = wp.from_torch( + self._CONTACT_MATRIX_GPU[scene_idx].view(th.uint8), dtype=wp.uint8 + ) + self._CURRENT_CONTACT_MATRIX_GPU_WP[scene_idx] = wp.from_torch( + self._CURRENT_CONTACT_MATRIX_GPU[scene_idx].view(th.uint8), dtype=wp.uint8 + ) + # Pinned-host wp.array views over the pinned torch CPU mirrors. The captured + # ``wp.copy`` in update() refreshes these from the GPU each replay, so callers + # of is_in_contact / get_contact_pairs (which read the torch CPU tensors) see + # fresh data without a separate sync method. + self._CONTACT_MATRIX_HOST_WP[scene_idx] = wp.from_torch( + self._CONTACT_MATRIX[scene_idx].view(th.uint8), dtype=wp.uint8 + ) + self._CURRENT_CONTACT_MATRIX_HOST_WP[scene_idx] = wp.from_torch( + self._CURRENT_CONTACT_MATRIX[scene_idx].view(th.uint8), dtype=wp.uint8 + ) + + # Initialize pending accumulation lists for this scene + # Note that existing data in these lists will be lost when the view is rebuilt. + # TODO: Assert here that this is not happening during a physics step, and that these buffers are empty. + # This TODO can be accomplished after the follow-up PR removes RigidContactAPI use in assisted grasping. + n_physics_steps = og.sim.n_physics_timesteps_per_render + self._PENDING_STEPS = 0 + self._PENDING_IMPULSES[scene_idx] = th.zeros( + n_physics_steps, + self._CONTACT_MATRIX[scene_idx].shape[0], + self._CONTACT_MATRIX[scene_idx].shape[1], + 3, + device="cuda", + ) + self._PENDING_TRANSFORMS[scene_idx] = th.zeros( + n_physics_steps, self._BODY_TRANSFORMS[scene_idx].shape[0], 7, device="cuda" + ) + self._PENDING_NET_FORCES[scene_idx] = th.zeros( + n_physics_steps, + self._CONTACT_MATRIX[scene_idx].shape[0], + 3, + device="cuda", + ) + + # wp.array views over the pending GPU buffers, consumed by the captured + # update() kernels. Re-wrap on every initialize_view because the underlying + # torch storage was just (re-)allocated above. + self._PENDING_IMPULSES_WP[scene_idx] = wp.from_torch( + self._PENDING_IMPULSES[scene_idx], dtype=wp.float32 + ) + self._PENDING_TRANSFORMS_WP[scene_idx] = wp.from_torch( + self._PENDING_TRANSFORMS[scene_idx], dtype=wp.float32 + ) + self._PENDING_NET_FORCES_WP[scene_idx] = wp.from_torch( + self._PENDING_NET_FORCES[scene_idx], dtype=wp.float32 + ) + + def read_from_physx(self): + """ + Fetches contact impulse matrices and body transforms from the current physics step + and appends them to pending lists. Should be called by the simulator after every + individual physics step. The accumulated data is later processed in bulk by + update(). + """ + assert og.sim.currently_stepping, "read_from_physx must be called during a physics step" + assert self._PENDING_STEPS < og.sim.n_physics_timesteps_per_render, "Pending steps buffer is full" + + scene_idx_list = list(self._CONTACT_VIEW.keys()) + dt = og.sim.get_physics_dt() + for scene_idx in scene_idx_list: + try: + # Fetch source tensors from PhysX views. + src_impulses = self._CONTACT_VIEW[scene_idx].get_contact_force_matrix(dt=dt) + src_net_forces = self._CONTACT_VIEW[scene_idx].get_net_contact_forces(dt=dt) + src_transforms = self._RIGID_BODY_VIEW[scene_idx].get_transforms() + except Exception: + log.warning( + "RigidContactAPI cannot compute contacts because the physics sim view is invalid. " + "This is expected if the physics sim view is not yet initialized, e.g. you are loading " + "a scene for the first time." + ) + continue + + # Copy via wp.copy so the writes land on warp's default stream — the same + # stream the captured graph consumes them from — so every sync point on this + # path can stay stream-scoped instead of device-wide. + wp.copy( + self._PENDING_IMPULSES_WP[scene_idx][self._PENDING_STEPS], + wp.from_torch(src_impulses, dtype=wp.float32), + ) + wp.copy( + self._PENDING_NET_FORCES_WP[scene_idx][self._PENDING_STEPS], + wp.from_torch(src_net_forces, dtype=wp.float32), + ) + wp.copy( + self._PENDING_TRANSFORMS_WP[scene_idx][self._PENDING_STEPS], + wp.from_torch(src_transforms, dtype=wp.float32), + ) + + # Increment once per physics step and push the new count to GPU so the captured + # contact kernels see the right `n_steps` at replay time. + if scene_idx_list: + self._PENDING_STEPS += 1 + self._N_STEPS_TORCH.fill_(self._PENDING_STEPS) + + def update(self): + """ + Issue the per-step warp kernels that bring the GPU contact matrices and body-transform + snapshot up to date from the pending physics-step data ``read_from_physx`` staged. + Also issues the D2H ``wp.copy``s that mirror the GPU matrices into the pinned CPU + tensors ``is_in_contact`` / ``get_contact_pairs`` read — captured into the graph so + they replay each frame without a separate sync hook. + + Algorithm: + 1. Per (r, c): walk the N physics sub-steps, marking each step's pair-awakeness + via ``_body_awake_at_step`` for both row and column bodies. Track the last awake + step + whether any awake step had a nonzero impulse. Write + ``current_contact_matrix`` from the last-awake-step impulse and + ``contact_matrix`` from the OR over all awake-step impulses. Pairs that were + never awake collapse both matrices to the carried-over current value. + 2. Per (b,): snapshot each body's transform from its own last awake step into + ``_BODY_TRANSFORMS`` (also the ``prev_transforms`` next-frame baseline). + 3. ``wp.copy`` GPU → pinned CPU for both contact matrices. + """ + for scene_idx in self._CONTACT_VIEW.keys(): + R, C = self._CONTACT_MATRIX_GPU[scene_idx].shape + B = self._BODY_TRANSFORMS[scene_idx].shape[0] + + # need to launch first because _update_body_transforms_kernel + # overwrites _BODY_TRANSFORMS, which read by both kernels + wp.launch( + kernel=_update_contact_matrices_kernel, + dim=(R, C), + inputs=[ + self._PENDING_TRANSFORMS_WP[scene_idx], + self._BODY_TRANSFORMS_WP[scene_idx], + self._PENDING_NET_FORCES_WP[scene_idx], + self._BODY_TO_ROW_WP[scene_idx], + self._PENDING_IMPULSES_WP[scene_idx], + self._ROW_TO_RIGID_WP[scene_idx], + self._COL_TO_RIGID_WP[scene_idx], + self._N_STEPS_GPU, + wp.float32(self._POS_EPS), + wp.float32(self._ORI_EPS), + self._CONTACT_MATRIX_GPU_WP[scene_idx], + self._CURRENT_CONTACT_MATRIX_GPU_WP[scene_idx], + ], + device="cuda", + ) + + wp.launch( + kernel=_update_body_transforms_kernel, + dim=B, + inputs=[ + self._PENDING_TRANSFORMS_WP[scene_idx], + self._BODY_TRANSFORMS_WP[scene_idx], + self._PENDING_NET_FORCES_WP[scene_idx], + self._BODY_TO_ROW_WP[scene_idx], + self._N_STEPS_GPU, + wp.float32(self._POS_EPS), + wp.float32(self._ORI_EPS), + self._BODY_TRANSFORMS_WP[scene_idx], + ], + device="cuda", + ) + + # so `is_in_contact` reads stay fresh each replay. + wp.copy(self._CONTACT_MATRIX_HOST_WP[scene_idx], self._CONTACT_MATRIX_GPU_WP[scene_idx]) + wp.copy(self._CURRENT_CONTACT_MATRIX_HOST_WP[scene_idx], self._CURRENT_CONTACT_MATRIX_GPU_WP[scene_idx]) + + def _get_prim_paths(self, objects_links_or_prim_paths): + """ + Converts a set of objects, links, or prim paths to a list of prim paths for contact matrix lookups. + + Args: + objects_links_or_prim_paths (set of EntityPrim, RigidPrim, str, or USDObject): Objects, links, or prim paths to convert to prim paths. + + Returns: + list[str]: List of prim paths. + """ + # Avoid circular imports + from omnigibson.prims.entity_prim import EntityPrim + from omnigibson.prims.rigid_prim import RigidPrim + + outputs = [] + for inp in objects_links_or_prim_paths: + if isinstance(inp, EntityPrim): + outputs.extend([link.prim_path for link in inp.links.values()]) + elif isinstance(inp, RigidPrim): + outputs.append(inp.prim_path) + elif isinstance(inp, str): + outputs.append(inp) + else: + raise ValueError(f"Input set must be a set of EntityPrim, RigidPrim, or str, found {type(inp)}") + return outputs + + def get_contact_row_indices(self, scene_idx, objects_links_or_prim_paths): + """ + Gets the row indices of the contact matrix for a given set of objects, links, or prim paths. + This is the index of the rigid body in the contact matrix. This can be used by external callers to + pre-cache the indices they care about for faster lookups later (e.g. avoiding a lookup on every call to is_in_contact). + + Args: + scene_idx (int): Scene index to get the contact row indices for. + objects_links_or_prim_paths (set of EntityPrim, RigidPrim, str, or USDObject): Objects, links, or prim paths to get the contact row indices for. + + Returns: + th.Tensor: Tensor of row indices. + """ + # If the input is already a tensor just return it + if isinstance(objects_links_or_prim_paths, th.Tensor): + return objects_links_or_prim_paths + + # Otherwise, convert to prim paths, filtering out kinematic-only bodies that are not rows. + # dtype=long so an empty result (all paths kinematic-only) is still safe to use as an index. + prim_paths = self._get_prim_paths(objects_links_or_prim_paths) + row_map = self._PATH_TO_ROW_IDX.get(scene_idx, {}) + return th.tensor([row_map[path] for path in prim_paths if path in row_map], dtype=th.long) + + def get_contact_col_indices(self, scene_idx, objects_links_or_prim_paths): + """ + Gets the column indices of the contact matrix for a given set of objects, links, or prim paths. + This is the index of the rigid body in the contact matrix. This can be used by external callers to + pre-cache the indices they care about for faster lookups later (e.g. avoiding a lookup on every call to is_in_contact). + + Args: + scene_idx (int): Scene index to get the contact column indices for. + objects_links_or_prim_paths (set of EntityPrim, RigidPrim, str, or USDObject): Objects, links, or prim paths to get the contact column indices for. + + Returns: + th.Tensor: Tensor of column indices. + """ + # If the input is already a tensor just return it + if isinstance(objects_links_or_prim_paths, th.Tensor): + return objects_links_or_prim_paths + + # Otherwise, convert to prim paths, filtering out bodies without contact reporting + # (e.g. visual-only links) that are not columns. dtype=long so an empty result is safe + # to use as an index. + prim_paths = self._get_prim_paths(objects_links_or_prim_paths) + col_map = self._PATH_TO_COL_IDX.get(scene_idx, {}) + return th.tensor([col_map[path] for path in prim_paths if path in col_map], dtype=th.long) + + def get_contact_pairs(self, scene_idx, query_set, with_set, current_only): + """ + Get pairs of prim paths that are in contact. + + Args: + scene_idx (int): Scene index to get the contact pairs for. + query_set (set of RigidPrim, str, or USDObject): Prims, prim paths, or objects for contact sensor objects to check. Must be specified. + with_set (set of RigidPrim, str, or USDObject): Prims, prim paths, or objects to filter the contact pairs by. Only these objects will be considered for contact. Can be None to check for contact with any object. + current_only (bool): If True, only checks the most recent physics step. If False, checks whether contact occurred at any physics step since the last non-physics step. + The True mode is recommended for use cases like Touching state etc. where a contact at the current position of the object is important. + The False mode is recommended for use cases like transition rules etc. where a contact at any point during the last N physics steps is enough (e.g. as a trigger event). + + Returns: + set of tuples: Set of tuples of (query_prim_path, filter_prim_path) pairs that are in contact. + """ + if scene_idx not in self._CONTACT_MATRIX or scene_idx not in self._PATH_TO_COL_IDX: + return set() + contact_matrix = self._CURRENT_CONTACT_MATRIX[scene_idx] if current_only else self._CONTACT_MATRIX[scene_idx] + assert contact_matrix.ndim == 2, f"Contact matrix should be 2D, found shape {contact_matrix.shape}" + + # Get the row indices corresponding to the sensor prim paths + row_idxs = self.get_contact_row_indices(scene_idx, query_set) + + # Slice the contact matrix and the index matrix with the same indexing so that + # nonzero positions in the submatrix can be mapped back to original row/col indices. + idx_matrix = self._INDEX_MATRIX[scene_idx] + if with_set is not None: + col_idxs = self.get_contact_col_indices(scene_idx, with_set) + in_contact = contact_matrix[row_idxs[:, None], col_idxs[None, :]] + idx_matrix = idx_matrix[row_idxs[:, None], col_idxs[None, :]] + else: + in_contact = contact_matrix[row_idxs, :] + idx_matrix = idx_matrix[row_idxs, :] + + # Early return if not in contact. + if not th.any(in_contact).item(): + return set() + + original_indices = idx_matrix[in_contact].cpu().tolist() + + return { + (self._ROW_IDX_TO_PATH[scene_idx][row], self._COL_IDX_TO_PATH[scene_idx][col]) + for row, col in original_indices + } + + def is_in_contact(self, scene_idx, query_set, with_set, ignore_set, current_only): + """ + Check if any of the prims in @query_set are in contact with any of the prims in @with_set, or not in contact with any of the prims in @ignore_set. + + Returns CPU tensors. + + Args: + scene_idx (int): Scene index to check for contact. + query_set (set of RigidPrim, str, or USDObject): Prims, prim paths, or objects to check for contact. + with_set (set of RigidPrim, str, or USDObject): Prims, prim paths, or objects to check for contact with. Can be None to check for contact with any object. + ignore_set (set of RigidPrim, str, or USDObject): Prims, prim paths, or objects to ignore contact with. Can be None to not ignore any objects. + current_only (bool): If True, only checks the most recent physics step. If False, checks whether contact occurred at any physics step since the last non-physics step. + The True mode is recommended for use cases like Touching state etc. where a contact at the current position of the object is important. + The False mode is recommended for use cases like transition rules etc. where a contact at any point during the last N physics steps is enough (e.g. as a trigger event). + + Returns: + bool: True if any of the prims in @query_set are in contact with any of the prims in @with_set, or not in contact with any of the prims in @ignore_set, else False. + """ + if with_set is not None and ignore_set is not None: + raise ValueError("At most one of with_set or ignore_set may be specified.") + + if scene_idx not in self._CONTACT_MATRIX or scene_idx not in self._PATH_TO_COL_IDX: + return False + + contact_matrix = self._CURRENT_CONTACT_MATRIX[scene_idx] if current_only else self._CONTACT_MATRIX[scene_idx] + rows = self.get_contact_row_indices(scene_idx, query_set) + if rows.numel() == 0: + return False + if with_set is not None: + cols = self.get_contact_col_indices(scene_idx, with_set) + return th.any(contact_matrix[rows, :][:, cols]).item() + elif ignore_set is not None: + ignore_mask = th.ones(contact_matrix.shape[1], dtype=th.bool) + ignore_mask[self.get_contact_col_indices(scene_idx, ignore_set)] = False + return th.any(contact_matrix[rows, :][:, ignore_mask]).item() + + # Base case, return any collisions with any other prim + return th.any(contact_matrix[rows]).item() + + def get_contact_row_mask(self, scene_idx, objects_links_or_prim_paths): + """ + Gets a boolean mask over contact matrix rows for a given set of objects, links, or prim paths. + Useful for building batch query masks for :meth:`is_in_contact_batch`. + + Args: + scene_idx (int): Scene index. + objects_links_or_prim_paths: Objects, links, or prim paths (or a pre-cached index tensor). + + Returns: + th.Tensor: (R,) boolean tensor where R is the number of contact matrix rows. + """ + R = self._CONTACT_MATRIX[scene_idx].shape[0] + idxs = self.get_contact_row_indices(scene_idx, objects_links_or_prim_paths) + mask = th.zeros(R, dtype=th.bool) + mask[idxs] = True + return mask + + def get_contact_col_mask(self, scene_idx, objects_links_or_prim_paths): + """ + Gets a boolean mask over contact matrix columns for a given set of objects, links, or prim paths. + Useful for building batch with/ignore masks for :meth:`is_in_contact_batch`. + + Args: + scene_idx (int): Scene index. + objects_links_or_prim_paths: Objects, links, or prim paths (or a pre-cached index tensor). + + Returns: + th.Tensor: (C,) boolean tensor where C is the number of contact matrix columns. + """ + C = self._CONTACT_MATRIX[scene_idx].shape[1] + idxs = self.get_contact_col_indices(scene_idx, objects_links_or_prim_paths) + mask = th.zeros(C, dtype=th.bool) + mask[idxs] = True + return mask + + def is_in_contact_batch(self, scene_idx, query_masks, with_masks, ignore_masks, current_only): + """ + Batch contact check for N queries, fully tensorized. Returns GPU tensors. + + Each row ``i`` of the input masks defines one independent contact query. The method + returns an ``(N,)`` boolean tensor where entry ``i`` is ``True`` iff any row selected + by ``query_masks[i]`` is in contact with any column selected by ``with_masks[i]`` + (or any column *not* in ``ignore_masks[i]``). + + Provide either ``with_masks`` for all N queries or ``ignore_masks`` for all N queries, + but not both (and not a per-query mix). + + Use :meth:`get_contact_row_mask` / :meth:`get_contact_col_mask` to build individual + masks, then ``torch.stack`` them into the ``(N, R)`` / ``(N, C)`` tensors expected here. + + Args: + scene_idx (int): Scene index to check for contact. + query_masks (th.Tensor): ``(N, R)`` boolean tensor. ``query_masks[i, j]`` is True + if contact-matrix row ``j`` belongs to query set ``i``. + with_masks (th.Tensor or None): ``(N, C)`` boolean tensor. ``with_masks[i, j]`` is + True if contact-matrix column ``j`` belongs to the with-set for query ``i``. Can be None to check for contact with any object. + ignore_masks (th.Tensor or None): ``(N, C)`` boolean tensor. ``ignore_masks[i, j]`` + is True if contact-matrix column ``j`` should be *ignored* for query ``i``. Can be None to not ignore any objects. + current_only (bool): If True, only checks the most recent physics step. If False, checks whether contact occurred at any physics step since the last non-physics step. + The True mode is recommended for use cases like Touching state etc. where a contact at the current position of the object is important. + The False mode is recommended for use cases like transition rules etc. where a contact at any point during the last N physics steps is enough (e.g. as a trigger event). + + Returns: + th.Tensor: ``(N,)`` boolean tensor of contact results. + """ + assert with_masks is None or ignore_masks is None, "Provide either with_masks or ignore_masks, not both." + + if scene_idx not in self._CONTACT_MATRIX_GPU or scene_idx not in self._PATH_TO_COL_IDX: + return th.zeros(query_masks.shape[0], dtype=th.bool, device="cuda") + + contact_matrix = ( + self._CURRENT_CONTACT_MATRIX_GPU[scene_idx] if current_only else self._CONTACT_MATRIX_GPU[scene_idx] + ) + + # query_contacts[i, c] = True iff any row in query set i is in contact with column c. + # We use float matmul for speed: (N, R) @ (R, C) -> (N, C), then threshold. + query_contacts = (query_masks.float() @ contact_matrix.float()) > 0 + + if with_masks is not None: + return (query_contacts & with_masks).any(dim=1) + elif ignore_masks is not None: + return (query_contacts & ~ignore_masks).any(dim=1) + + return query_contacts.any(dim=1) + + def is_in_contact_batch_warp(self, scene_idx, query_masks_wp, with_masks_wp, ignore_masks_wp, current_only, out_wp): + """ + Warp-kernel variant of is_in_contact_batch. Same semantics, but takes pre-cached + wp.array inputs (uint8 masks) and writes to a caller-allocated output wp.array. + Designed to be safe to call inside wp.graph capture. + + out_wp must be int32, NOT uint8. + + Args: + scene_idx (int): Scene index. + query_masks_wp (wp.array): (N, R) uint8 — wp.from_torch wrapper of bool query masks. + with_masks_wp (wp.array | None): (N, C) uint8 — with-mask, mutually exclusive with ignore_masks_wp. + ignore_masks_wp (wp.array | None): (N, C) uint8 — ignore-mask. + current_only (bool): True → use _CURRENT_CONTACT_MATRIX_GPU_WP, else _CONTACT_MATRIX_GPU_WP. + out_wp (wp.array): (N,) **int32** — caller-allocated, must be pre-zeroed. + + If the scene has no contact view yet (e.g. only kinematic bodies), no kernel is + launched and out_wp is left as-is. + """ + assert ( + with_masks_wp is None or ignore_masks_wp is None + ), "Provide either with_masks_wp or ignore_masks_wp, not both." + # Scene without a contact view: nothing to do; caller's out_wp is left as-is. + if scene_idx not in self._CONTACT_MATRIX_GPU_WP: + return + + contact_matrix_wp = ( + self._CURRENT_CONTACT_MATRIX_GPU_WP[scene_idx] if current_only else self._CONTACT_MATRIX_GPU_WP[scene_idx] + ) + + # Decide kernel mode + col_filter argument. The kernel always reads from col_filter, + # so when there's no real filter we substitute query_masks_wp as a dummy of compatible + # shape — mode=2 means the kernel ignores it. + if with_masks_wp is not None: + col_filter = with_masks_wp + mode = 0 + elif ignore_masks_wp is not None: + col_filter = ignore_masks_wp + mode = 1 + else: + # Dummy placeholder; kernel ignores when mode=2. Use query_masks_wp for matching device. + col_filter = query_masks_wp + mode = 2 + + # Output count is the broadcast of the query-mask rows and the filter-mask rows, + # whichever has >1 row drives N; a 1-row operand + # is shared across all N. mode==2 has no real filter, so N follows the query rows. + n_query_rows = query_masks_wp.shape[0] + n_filter_rows = 1 if mode == 2 else col_filter.shape[0] + N = max(n_query_rows, n_filter_rows) + R = contact_matrix_wp.shape[0] + C = contact_matrix_wp.shape[1] + + # 3D launch: one thread per (query, row, col) cell. Each thread does at most a few + # reads + 1 atomic_max on hit. Maximum parallelism, no serial loops. + wp.launch( + kernel=_is_in_contact_batch_kernel, + dim=(N, R, C), + inputs=[ + query_masks_wp, + contact_matrix_wp, + col_filter, + wp.int32(mode), + out_wp, + ], + device="cuda", + ) + + def has_contact_view(self, scene_idx): + """Returns True if a valid contact view has been initialized for @scene_idx.""" + return scene_idx in self._CONTACT_MATRIX + + def get_contact_matrix_shape(self, scene_idx): + """ + Returns: + tuple(int, int) | None: (R, C) shape of the contact matrix for @scene_idx, or None + if no contact view exists for that scene. + """ + if scene_idx not in self._CONTACT_MATRIX: + return None + return tuple(self._CONTACT_MATRIX[scene_idx].shape) + + def get_contact_matrix_wp(self, scene_idx, current_only): + """ + Get the wp.array view of the GPU contact matrix for use inside Warp kernels (e.g. inside + a captured wp.graph). Same view that ``is_in_contact_batch_warp`` consumes internally. + + Args: + scene_idx (int): Scene index. + current_only (bool): True → "current step only" matrix, False → "any recent step" matrix. + + Returns: + wp.array(uint8) | None: (R, C) uint8 view, or None if no contact view exists for @scene_idx. + """ + if scene_idx not in self._CONTACT_MATRIX_GPU_WP: + return None + return ( + self._CURRENT_CONTACT_MATRIX_GPU_WP[scene_idx] if current_only else self._CONTACT_MATRIX_GPU_WP[scene_idx] + ) + + def clear(self): + """ + Clears internal contact views, mappings, and caches. + """ + self._PATH_TO_ROW_IDX = dict() + self._PATH_TO_COL_IDX = dict() + self._ROW_IDX_TO_PATH = dict() + self._COL_IDX_TO_PATH = dict() + self._CONTACT_VIEW = dict() + self._RIGID_BODY_VIEW = dict() + self._CONTACT_MATRIX_ROWS_TO_RIGID_BODY_ROWS = dict() + self._CONTACT_MATRIX_COLS_TO_RIGID_BODY_ROWS = dict() + self._CONTACT_MATRIX_COLS_HAS_RIGID_BODY = dict() + self._ROW_TO_RIGID_WP = dict() + self._COL_TO_RIGID_WP = dict() + self._BODY_TO_ROW = dict() + self._BODY_TO_ROW_WP = dict() + self._CONTACT_MATRIX = dict() + self._CONTACT_MATRIX_GPU = dict() + self._CONTACT_MATRIX_GPU_WP = dict() + self._CONTACT_MATRIX_HOST_WP = dict() + self._CURRENT_CONTACT_MATRIX = dict() + self._CURRENT_CONTACT_MATRIX_GPU = dict() + self._CURRENT_CONTACT_MATRIX_GPU_WP = dict() + self._CURRENT_CONTACT_MATRIX_HOST_WP = dict() + self._INDEX_MATRIX = dict() + self._BODY_TRANSFORMS = dict() + self._BODY_TRANSFORMS_WP = dict() + self._PENDING_STEPS = 0 + self._PENDING_IMPULSES = dict() + self._PENDING_TRANSFORMS = dict() + self._PENDING_NET_FORCES = dict() + self._PENDING_IMPULSES_WP = dict() + self._PENDING_TRANSFORMS_WP = dict() + self._PENDING_NET_FORCES_WP = dict() + + +# Instantiate the RigidContactAPI +RigidContactAPI = RigidContactAPIImpl() + + +class CollisionAPI: + """ + Class containing class methods to facilitate collision handling, e.g. collision groups + """ + + ACTIVE_COLLISION_GROUPS = dict() + + @classmethod + def create_collision_group(cls, col_group, filter_self_collisions=False): + """ + Creates a new collision group with name @col_group + + Args: + col_group (str): Name of the collision group to create + filter_self_collisions (bool): Whether to ignore self-collisions within the group. Default is False + """ + with og.sim.editing_usd(): + # Can only be done when sim is stopped + assert og.sim is None or og.sim.is_stopped(), "Cannot create a collision group unless og.sim is stopped!" + + # Make sure the group doesn't already exist + assert ( + col_group not in cls.ACTIVE_COLLISION_GROUPS + ), f"Cannot create collision group {col_group} because it already exists!" + + # Create the group + col_group_prim_path = f"/World/collision_groups/{col_group}" + group = lazy.pxr.UsdPhysics.CollisionGroup.Define(og.sim.stage, col_group_prim_path) + if filter_self_collisions: + # Do not collide with self + group.GetFilteredGroupsRel().AddTarget(col_group_prim_path) + cls.ACTIVE_COLLISION_GROUPS[col_group] = group + + @classmethod + def add_to_collision_group(cls, col_group, prim_path): + """ + Adds the prim and all nested prims specified by @prim_path to the global collision group @col_group. If @col_group + does not exist, then it will either be created if @create_if_not_exist is True, otherwise will raise an Error. + Args: + col_group (str): Name of the collision group to assign the prim at @prim_path to + prim_path (str): Prim (and all nested prims) to assign to this @col_group + """ + with og.sim.editing_usd(): + # Make sure collision group exists + assert ( + col_group in cls.ACTIVE_COLLISION_GROUPS + ), f"Cannot add to collision group {col_group} because it does not exist!" + + # Add this prim to the collision group + cls.ACTIVE_COLLISION_GROUPS[col_group].GetCollidersCollectionAPI().GetIncludesRel().AddTarget(prim_path) + + @classmethod + def add_group_filter(cls, col_group, filter_group): + """ + Adds a new group filter for group @col_group, filtering all collision with group @filter_group + Args: + col_group (str): Name of the collision group which will have a new filter group added + filter_group (str): Name of the group that should be filtered + """ + with og.sim.editing_usd(): + # Make sure the group doesn't already exist + for group_name in (col_group, filter_group): + assert group_name in cls.ACTIVE_COLLISION_GROUPS, ( + f"Cannot add group filter {filter_group} to collision group {col_group} because at least one group " + f"does not exist!" + ) + + # Grab the group, and add the filter + filter_group_prim_path = f"/World/collision_groups/{filter_group}" + group = cls.ACTIVE_COLLISION_GROUPS[col_group] + group.GetFilteredGroupsRel().AddTarget(filter_group_prim_path) + + @classmethod + def clear(cls): + """ + Clears the internal state of this CollisionAPI + """ + # Remove all the collision group prims + for col_group_prim in cls.ACTIVE_COLLISION_GROUPS.values(): + delete_or_deactivate_prim(col_group_prim.GetPath().pathString) + + # Remove the collision groups tree + delete_or_deactivate_prim("/World/collision_groups") + + # Clear the dictionary + cls.ACTIVE_COLLISION_GROUPS = {} + + +def setup_collision_apis(prim): + """ + Apply collision-related physics APIs to a USD prim. This should be called for prims + that are identified as collision meshes (e.g. those appearing under a "collisions" scope prim). + + This applies the CollisionAPI, PhysxCollisionAPI, and (for meshes) MeshCollisionAPI to the prim, + sets a default convex hull collision approximation for mesh types, and enables/disables collisions + based on the global VISUAL_ONLY setting. + + Note: This does NOT set the prim's purpose. The caller should set purpose as appropriate + (e.g. "guide" for collision-only meshes, "default" for collision+visual meshes). + + Args: + prim: The USD prim to set up collision APIs on. + + Returns: + tuple: (collision_api, physx_collision_api, mesh_collision_api) where mesh_collision_api + may be None for non-mesh prims. + """ + # Create / get CollisionAPI reference + collision_api = ensure_usd_api(prim, lazy.pxr.UsdPhysics.CollisionAPI) + physx_collision_api = ensure_usd_api(prim, lazy.pxr.PhysxSchema.PhysxCollisionAPI) + mesh_collision_api = ( + ensure_usd_api(prim, lazy.pxr.UsdPhysics.MeshCollisionAPI) + if prim.GetPrimTypeInfo().GetTypeName() == "Mesh" + else None + ) + + # Optionally add mesh collision API if this is a mesh + if mesh_collision_api is not None: + # Set the approximation to be convex hull by default + apply_collision_approximation(prim, mesh_collision_api, "convexHull") + + with og.sim.editing_usd(): + # Set collision enabled based on global setting + collision_api.GetCollisionEnabledAttr().Set(not gm.VISUAL_ONLY) + + return collision_api, physx_collision_api, mesh_collision_api + + +def apply_collision_approximation(prim, mesh_collision_api, approximation_type): + """ + Apply a collision approximation type to a single collision mesh prim. + + Args: + prim: The USD prim to apply the collision approximation to. + mesh_collision_api: The UsdPhysics.MeshCollisionAPI for this prim. + approximation_type (str): Approximation type to use. One of: + {"none", "convexHull", "convexDecomposition", "meshSimplification", "sdf", + "boundingSphere", "boundingCube"} + """ + assert mesh_collision_api is not None, "collision_approximation only applicable for meshes!" + assert_valid_key( + key=approximation_type, + valid_keys={ + "none", + "convexHull", + "convexDecomposition", + "meshSimplification", + "sdf", + "boundingSphere", + "boundingCube", + }, + name="collision approximation type", + ) + + # Make sure to add the appropriate API if we're setting certain values + if approximation_type == "convexHull": + ensure_usd_api(prim, lazy.pxr.PhysxSchema.PhysxConvexHullCollisionAPI) + elif approximation_type == "convexDecomposition": + ensure_usd_api(prim, lazy.pxr.PhysxSchema.PhysxConvexDecompositionCollisionAPI) + elif approximation_type == "meshSimplification": + ensure_usd_api(prim, lazy.pxr.PhysxSchema.PhysxTriangleMeshSimplificationCollisionAPI) + elif approximation_type == "sdf": + ensure_usd_api(prim, lazy.pxr.PhysxSchema.PhysxSDFMeshCollisionAPI) + elif approximation_type == "none": + ensure_usd_api(prim, lazy.pxr.PhysxSchema.PhysxTriangleMeshCollisionAPI) + + with og.sim.editing_usd(): + if approximation_type == "convexHull": + pch_api = lazy.pxr.PhysxSchema.PhysxConvexHullCollisionAPI(prim) + # Also make sure the maximum vertex count is 60 (max number compatible with GPU) + # https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics/rigid-bodies.html#collision-settings + if pch_api.GetHullVertexLimitAttr().Get() is None: + pch_api.CreateHullVertexLimitAttr() + pch_api.GetHullVertexLimitAttr().Set(60) + + mesh_collision_api.GetApproximationAttr().Set(approximation_type) + + +def get_world_pose(prim_path): + """ + Gets pose of the prim object with respect to the world frame + Args: + Prim_path: the path of the prim object + Returns: + 2-tuple: + - torch.Tensor: (x,y,z) position in the world frame + - torch.Tensor: (x,y,z,w) quaternion orientation in the world frame + """ + matrix = _get_world_pose_with_scale_from_fabric_hierarchy(prim_path) + quaternion = matrix.RemoveScaleShear().ExtractRotationQuat() + position = th.tensor(matrix.ExtractTranslation(), dtype=th.float32) + orientation = th.tensor([*quaternion.GetImaginary(), quaternion.GetReal()], dtype=th.float32) + return position, orientation + + +def _get_world_pose_with_scale_from_fabric_hierarchy(prim_path): + # Check that no reads from Fabric are happening during a physics step. + assert not og.sim.currently_stepping, "Do not read poses from Fabric during a physics step, this is quite slow!" + + return og.sim.fabric_hierarchy.get_world_xform(lazy.usdrt.Sdf.Path(prim_path)) + + +def get_world_pose_with_scale(prim_path): + """ + This is used when information about the prim's global scale is needed, + e.g. when converting points in the prim frame to the world frame. + """ + + return th.tensor(_get_world_pose_with_scale_from_fabric_hierarchy(prim_path), dtype=th.float32).T + + +def get_local_pose(prim_path): + """ + Gets pose of the prim with respect to its parent prim's frame (local / parent-relative transform). + + Args: + prim_path: the path of the prim object + + Returns: + 2-tuple: + - torch.Tensor: (x,y,z) position in the parent frame + - torch.Tensor: (x,y,z,w) quaternion orientation in the parent frame + """ + matrix = _get_local_pose_with_scale_from_fabric_hierarchy(prim_path) + quaternion = matrix.RemoveScaleShear().ExtractRotationQuat() + position = th.tensor(matrix.ExtractTranslation(), dtype=th.float32) + orientation = th.tensor([*quaternion.GetImaginary(), quaternion.GetReal()], dtype=th.float32) + return position, orientation + + +def _get_local_pose_with_scale_from_fabric_hierarchy(prim_path): + assert not og.sim.currently_stepping, "Do not read poses from Fabric during a physics step, this is quite slow!" + + return og.sim.fabric_hierarchy.get_local_xform(lazy.usdrt.Sdf.Path(prim_path)) + + +def get_local_pose_with_scale(prim_path): + """ + Like get_local_pose, but returns the full 4x4 local transform matrix (with scale), + for converting points between the prim frame and the parent frame. + """ + + return th.tensor(_get_local_pose_with_scale_from_fabric_hierarchy(prim_path), dtype=th.float32).T + + +class BatchControlViewAPIImpl: + """ + A centralized view that allows for reading and writing to an ArticulationView that covers multiple + controllable objects in the scene. This is used to avoid the overhead of reading from many views + for each robot in each physics step, a source of significant overhead. + + **Compute backend:** Isaac's physics sim articulation view APIs return **torch** tensors. This layer + caches **compute-backend arrays** (``cb.arr_type``). All public getters on this class therefore + return ``cb`` arrays (positions, quaternions, Jacobians, etc.). Batched writes from controllers + expect ``cb`` arrays as well. ``flush_control`` converts cached targets back to torch for the PhysX backend. + """ + + def __init__(self, pattern): + # The prim path pattern that will be passed into the view + self._pattern = pattern + + # The unified ArticulationView used to access all of the controllable objects in the scene. + self._view = None + + # Cache for all of the view functions' return values within the same simulation step. + # Keyed by function name without get_, the value is the return value of the function. + self._read_cache = {} + + # Cache for all of the view functions' write values within the same simulation step. + # Keyed by the function name without set_, the value is the set of indices that need to be updated. + self._write_idx_cache = collections.defaultdict(set) + + # Mapping from prim path to index in the view. + self._idx = {} + + # Mapping from prim idx to a dict that maps link name to link index in the view. + self._link_idx = {} + + # Mapping from prim path to base footprint link name if one exists, None if the root is the base link. + self._base_footprint_link_names = {} + + # Prior link transforms / dof positions for estimating velocities since Omni gives inaccurate values + self._last_state = None + + def post_physics_step(self): + # Should be called every sim physics step, right after a new physics step occurs + # The current poses (if it exists) are now the former poses from the previous timestep + # These values are needed to compute velocity estimates + if ( + "root_transforms" in self._read_cache + and "link_transforms" in self._read_cache + and "dof_positions" in self._read_cache + ): + self._last_state = { + "root_transforms": cb.copy(self._read_cache["root_transforms"]), + "link_transforms": cb.copy(self._read_cache["link_transforms"]), + "dof_positions": cb.copy(self._read_cache["dof_positions"]), + } + else: + # We don't have enough info to populate the history, so simply clear it instead + self._last_state = None + + # Clear the internal data since everything is outdated + self.clear(keep_last_pose=True) + + def clear(self, keep_last_pose=False): + self._read_cache = {} + self._write_idx_cache = collections.defaultdict(set) + + # Clear our last timestep's cached values by default + if not keep_last_pose: + self._last_state = None + + # Cache the (now current) transforms so that they're guaranteed to exist throughout the duration of this + # timestep, and available for caching during the next timestep's post_physics_step() call + if og.sim.is_playing(): + self._read_cache["root_transforms"] = cb.from_torch(self._view.get_root_transforms()) + self._read_cache["link_transforms"] = cb.from_torch(self._view.get_link_transforms()) + self._read_cache["dof_positions"] = cb.from_torch(self._view.get_dof_positions()) + + def _set_dof_position_targets(self, data, indices, cast=True): + # No casting results in better efficiency + if cast: + data = self._view._frontend.as_contiguous_float32(data) + indices = self._view._frontend.as_contiguous_uint32(indices) + data_desc = self._view._frontend.get_tensor_desc(data) + indices_desc = self._view._frontend.get_tensor_desc(indices) + + if not self._view._backend.set_dof_position_targets(data_desc, indices_desc): + raise Exception("Failed to set DOF positions in backend") + + def _set_dof_velocity_targets(self, data, indices, cast=True): + # No casting results in better efficiency + if cast: + data = self._view._frontend.as_contiguous_float32(data) + indices = self._view._frontend.as_contiguous_uint32(indices) + data_desc = self._view._frontend.get_tensor_desc(data) + indices_desc = self._view._frontend.get_tensor_desc(indices) + + if not self._view._backend.set_dof_velocity_targets(data_desc, indices_desc): + raise Exception("Failed to set DOF velocities in backend") + + def _set_dof_actuation_forces(self, data, indices, cast=True): + # No casting results in better efficiency + if cast: + data = self._view._frontend.as_contiguous_float32(data) + indices = self._view._frontend.as_contiguous_uint32(indices) + data_desc = self._view._frontend.get_tensor_desc(data) + indices_desc = self._view._frontend.get_tensor_desc(indices) + + if not self._view._backend.set_dof_actuation_forces(data_desc, indices_desc): + raise Exception("Failed to set DOF actuation forces in backend") + + def flush_control(self): + if "dof_position_targets" in self._write_idx_cache: + pos_indices = cb.int_array(sorted(self._write_idx_cache["dof_position_targets"])) + pos_targets = self._read_cache["dof_position_targets"] + self._set_dof_position_targets(cb.to_torch(pos_targets), cb.to_torch(pos_indices), cast=False) + + if "dof_velocity_targets" in self._write_idx_cache: + vel_indices = cb.int_array(sorted(self._write_idx_cache["dof_velocity_targets"])) + vel_targets = self._read_cache["dof_velocity_targets"] + self._set_dof_velocity_targets(cb.to_torch(vel_targets), cb.to_torch(vel_indices), cast=False) + + if "dof_actuation_forces" in self._write_idx_cache: + eff_indices = cb.int_array(sorted(self._write_idx_cache["dof_actuation_forces"])) + eff_targets = self._read_cache["dof_actuation_forces"] + self._set_dof_actuation_forces(cb.to_torch(eff_targets), cb.to_torch(eff_indices), cast=False) + + def initialize_view(self): + # First, get all of the controllable objects in the scene (avoiding circular import) + from omnigibson.robots import Robot + + controllable_objects = [obj for scene in og.sim.scenes for obj in scene.objects if isinstance(obj, Robot)] + + # Get their corresponding prim paths + expected_prim_paths = {obj.articulation_root_path for obj in controllable_objects} + + # Apply the pattern to find the expected prim paths + expected_prim_paths = { + prim_path for prim_path in expected_prim_paths if re.fullmatch(self._pattern.replace("*", ".*"), prim_path) + } + + # Make sure we have at least one controllable object + if len(expected_prim_paths) == 0: + return + + # Create the actual articulation view. Note that even though we search for base_link here, + # the returned things will not necessarily be the base_link prim paths, but the appropriate + # articulation root path for every object (base_link for non-fixed, parent for fixed objects) + self._view = og.sim.physics_sim_view.create_articulation_view(self._pattern) + view_prim_paths = self._view.prim_paths + assert ( + set(view_prim_paths) == expected_prim_paths + ), f"ControllableObjectViewAPI expected prim paths {expected_prim_paths} but got {view_prim_paths}" + + # Create the mapping from prim path to index + self._idx = {prim_path: i for i, prim_path in enumerate(view_prim_paths)} + self._link_idx = [ + {link_path.split("/")[-1]: j for j, link_path in enumerate(articulation_link_paths)} + for articulation_link_paths in self._view.link_paths + ] + self._base_footprint_link_names = { + obj.articulation_root_path: ( + obj.base_footprint_link_name if obj.base_footprint_link_name != obj.root_link_name else None + ) + for obj in controllable_objects + if obj.articulation_root_path in expected_prim_paths + } + + def set_joint_position_targets(self, prim_path, positions, indices): + assert len(indices) == len(positions), "Indices and values must have the same length" + idx = self._idx[prim_path] + + # Load the current targets. + if "dof_position_targets" not in self._read_cache: + self._read_cache["dof_position_targets"] = cb.from_torch(self._view.get_dof_position_targets()) + + # Update the target + self._read_cache["dof_position_targets"][idx, indices] = positions + + # Add this index to the write cache + self._write_idx_cache["dof_position_targets"].add(idx) + + def set_joint_velocity_targets(self, prim_path, velocities, indices): + assert len(indices) == len(velocities), "Indices and values must have the same length" + idx = self._idx[prim_path] + + # Load the current targets. + if "dof_velocity_targets" not in self._read_cache: + self._read_cache["dof_velocity_targets"] = cb.from_torch(self._view.get_dof_velocity_targets()) + + # Update the target + self._read_cache["dof_velocity_targets"][idx, indices] = velocities + + # Add this index to the write cache + self._write_idx_cache["dof_velocity_targets"].add(idx) + + def set_joint_efforts(self, prim_path, efforts, indices): + assert len(indices) == len(efforts), "Indices and values must have the same length" + idx = self._idx[prim_path] + + # Load the current targets. + if "dof_actuation_forces" not in self._read_cache: + self._read_cache["dof_actuation_forces"] = cb.from_torch(self._view.get_dof_actuation_forces()) + + # Update the target + self._read_cache["dof_actuation_forces"][idx, indices] = efforts + + # Add this index to the write cache + self._write_idx_cache["dof_actuation_forces"].add(idx) + + def get_member_view_indices(self, prim_paths): + """Return view row index for each prim_path (in input order).""" + return [self._idx[p] for p in prim_paths] + + def set_all_joint_position_targets(self, enabled_rows, controls, dof_idx): + """ + Args: + enabled_rows: list[int] — view row indices for enabled members (pre-filtered) + controls: (N_enabled, len(dof_idx)) compute-backend array — pre-stacked by controller + dof_idx: DOF column indices (cb.arr_type) + """ + if "dof_position_targets" not in self._read_cache: + self._read_cache["dof_position_targets"] = cb.from_torch(self._view.get_dof_position_targets()) + targets = self._read_cache["dof_position_targets"] + row_idx = cb.int_array(enabled_rows).reshape(-1, 1) + targets[row_idx, dof_idx] = controls + self._write_idx_cache["dof_position_targets"].update(enabled_rows) + + def set_all_joint_velocity_targets(self, enabled_rows, velocities, dof_idx): + if "dof_velocity_targets" not in self._read_cache: + self._read_cache["dof_velocity_targets"] = cb.from_torch(self._view.get_dof_velocity_targets()) + targets = self._read_cache["dof_velocity_targets"] + row_idx = cb.int_array(enabled_rows).reshape(-1, 1) + targets[row_idx, dof_idx] = velocities + self._write_idx_cache["dof_velocity_targets"].update(enabled_rows) + + def set_all_joint_efforts(self, enabled_rows, efforts, dof_idx): + if "dof_actuation_forces" not in self._read_cache: + self._read_cache["dof_actuation_forces"] = cb.from_torch(self._view.get_dof_actuation_forces()) + targets = self._read_cache["dof_actuation_forces"] + row_idx = cb.int_array(enabled_rows).reshape(-1, 1) + targets[row_idx, dof_idx] = efforts + self._write_idx_cache["dof_actuation_forces"].update(enabled_rows) + + def get_all_root_transform(self): + if "root_transforms" not in self._read_cache: + self._read_cache["root_transforms"] = cb.from_torch(self._view.get_root_transforms()) + pose = self._read_cache["root_transforms"] + return pose[:, :3], pose[:, 3:] + + def get_root_transform(self, prim_path): + idx = self._idx[prim_path] + pos, quat = self.get_all_root_transform() + return pos[idx], quat[idx] + + def get_all_position_orientation(self): + # Here we want to return the position of the base footprint link. + # If the base footprint link is None, we return the position of the root link. + + # we assume that in a view, all base link_name is the same + link_name = next(iter(self._base_footprint_link_names.values())) + if link_name is None: + return self.get_all_root_transform() + else: + return self.get_all_link_transform(link_name) + + def get_position_orientation(self, prim_path): + # Here we want to return the position of the base footprint link. If the base footprint link is None, + # we return the position of the root link. + if self._base_footprint_link_names[prim_path] is not None: + link_name = self._base_footprint_link_names[prim_path] + return self.get_link_transform(prim_path, link_name) + else: + return self.get_root_transform(prim_path) + + def _get_all_velocities(self, estimate=False): + link_name = next(iter(self._base_footprint_link_names.values())) + if link_name is not None: + return self._get_all_link_velocities(link_name, estimate=estimate) + else: + return self._get_all_root_velocities(estimate=estimate) + + def _get_velocities(self, prim_path, estimate=False): + """World-frame linear + angular velocity for one articulation (6,) from the batched cache.""" + idx = self._idx[prim_path] + return self._get_all_velocities(estimate=estimate)[idx] + + def _get_all_relative_velocities(self, estimate=False): + """Returns (N, n_links+1, 6) relative velocities for all robots; final slot [-1] is the base.""" + vel_str = "velocities_estimate" if estimate else "velocities" + + if f"all_relative_{vel_str}" not in self._read_cache: + # Warm the (N, L, 6) link velocity cache and fetch it + any_link_name = next(iter(self._link_idx[0])) + self._get_all_link_velocities(any_link_name, estimate=estimate) + link_vels = cb.to_torch(self._read_cache[f"link_{vel_str}"]) # (N, L, 6) + + # Get base velocities (N, 6): reuse link cache if a base footprint link is configured + # (all robots in a view share the same base footprint link name) + base_footprint_link_name = next(iter(self._base_footprint_link_names.values())) + if base_footprint_link_name is not None: + base_link_idx = self._link_idx[0][base_footprint_link_name] + base_vels = link_vels[:, base_link_idx, :] # (N, 6) — already in cache, no extra fetch + else: + # Warm root velocities cache and get (N, 6) + self._get_all_root_velocities(estimate=estimate) + base_vels = cb.to_torch(self._read_cache[f"root_{vel_str}"]) # (N, 6) + + # Build (N, L+1, 6): link vels followed by base vel (base at final index, matching _get_relative_velocities) + all_vels = th.cat([link_vels, base_vels.unsqueeze(1)], dim=1) # (N, L+1, 6) + + # Build block-diagonal rotation transform per robot: (N, 6, 6) + all_quats = cb.to_torch(self.get_all_position_orientation()[1]) # (N, 4) + ori_t_batch = TT.quat2mat(all_quats).transpose(-2, -1) # (N, 3, 3) + tf = th.zeros(all_vels.shape[0], 6, 6, dtype=all_vels.dtype) + tf[:, :3, :3] = ori_t_batch + tf[:, 3:, 3:] = ori_t_batch + + # Batched matmul: (N, 1, 6, 6) @ (N, L+1, 6, 1) → (N, L+1, 6) + rel_vels = (tf.unsqueeze(1) @ all_vels.unsqueeze(-1)).squeeze(-1) + self._read_cache[f"all_relative_{vel_str}"] = cb.from_torch(rel_vels) + + return self._read_cache[f"all_relative_{vel_str}"] + + def _get_relative_velocities(self, prim_path, estimate=False): + idx = self._idx[prim_path] + return self._get_all_relative_velocities(estimate=estimate)[idx] + + def get_linear_velocity(self, prim_path, estimate=False): + return self._get_velocities(prim_path, estimate=estimate)[:3] + + def get_angular_velocity(self, prim_path, estimate=False): + return self._get_velocities(prim_path, estimate=estimate)[3:] + + def _get_all_root_velocities(self, estimate=False): + vel_str = "velocities_estimate" if estimate else "velocities" + + # Use estimated calculation if requested and we have prior history info + if f"root_{vel_str}" not in self._read_cache: + if estimate and self._last_state is not None: + # Compute root velocities estimate as delta between prior timestep and current timestep + vels = cb.zeros((self._last_state["root_transforms"].shape[0], 6)) + + if "root_transforms" not in self._read_cache: + self._read_cache["root_transforms"] = cb.from_torch(self._view.get_root_transforms()) + + vels[:, :3] = self._read_cache["root_transforms"][:, :3] - self._last_state["root_transforms"][:, :3] + vels[:, 3:] = cb.T.quat2axisangle( + cb.T.quat_distance( + self._read_cache["root_transforms"][:, 3:], self._last_state["root_transforms"][:, 3:] + ) + ) + self._read_cache[f"root_{vel_str}"] = vels / og.sim.get_physics_dt() + else: + self._read_cache[f"root_{vel_str}"] = cb.from_torch(self._view.get_root_velocities()) + + return self._read_cache[f"root_{vel_str}"] + + def get_relative_linear_velocity(self, prim_path, estimate=False): + # base corresponds to final index + return self._get_relative_velocities(prim_path, estimate=estimate)[-1, :3] + + def get_relative_angular_velocity(self, prim_path, estimate=False): + # base corresponds to final index + return self._get_relative_velocities(prim_path, estimate=estimate)[-1, 3:] + + def get_link_index(self, link_name): + """Returns the integer body index for the named link in the articulation view's link_paths.""" + return self._link_idx[0][link_name] + + def get_all_link_relative_position_orientation(self, link_name): + """Returns (N, 3) positions and (N, 4) quaternions for the given link across all robots.""" + cache_key = f"all_link_rel_pose_{link_name}" + if cache_key not in self._read_cache: + link_idx = self._link_idx[0][link_name] + # _get_all_relative_poses returns (N, n_links, 7); slice the desired link: (N, 7) + poses = self._get_all_relative_poses()[:, link_idx, :] + self._read_cache[cache_key] = poses + poses = self._read_cache[cache_key] + return poses[:, :3], poses[:, 3:] + + def get_all_link_relative_linear_velocity(self, link_name, estimate=False): + """Returns (N, 3) link linear velocities for all robots.""" + cache_key = f"all_link_rel_lin_vel{'_est' if estimate else ''}_{link_name}" + if cache_key not in self._read_cache: + link_idx = self._link_idx[0][link_name] + self._read_cache[cache_key] = self._get_all_relative_velocities(estimate=estimate)[:, link_idx, :3] + return self._read_cache[cache_key] + + def get_all_link_relative_angular_velocity(self, link_name, estimate=False): + """Returns (N, 3) link angular velocities for all robots.""" + cache_key = f"all_link_rel_ang_vel{'_est' if estimate else ''}_{link_name}" + if cache_key not in self._read_cache: + link_idx = self._link_idx[0][link_name] + self._read_cache[cache_key] = self._get_all_relative_velocities(estimate=estimate)[:, link_idx, 3:] + return self._read_cache[cache_key] + + def get_all_relative_linear_velocity(self, estimate=False): + """Returns (N, 3) base linear velocities for all robots in this view.""" + cache_key = f"all_relative_lin_vel{'_est' if estimate else ''}" + if cache_key not in self._read_cache: + # Base is appended at the final index in _get_all_relative_velocities + self._read_cache[cache_key] = self._get_all_relative_velocities(estimate=estimate)[:, -1, :3] + return self._read_cache[cache_key] + + def get_all_relative_angular_velocity(self, estimate=False): + """Returns (N, 3) base angular velocities for all robots in this view.""" + cache_key = f"all_relative_ang_vel{'_est' if estimate else ''}" + if cache_key not in self._read_cache: + # Base is appended at the final index in _get_all_relative_velocities + self._read_cache[cache_key] = self._get_all_relative_velocities(estimate=estimate)[:, -1, 3:] + return self._read_cache[cache_key] + + def get_all_joint_positions(self): + """Returns (N, n_dof) joint positions for all robots in this view.""" + if "dof_positions" not in self._read_cache: + self._read_cache["dof_positions"] = cb.from_torch(self._view.get_dof_positions()) + return self._read_cache["dof_positions"] + + def get_joint_positions(self, prim_path): + return self.get_all_joint_positions()[self._idx[prim_path]] + + def get_all_joint_velocities(self, estimate=False): + """Returns (N, n_dof) joint velocities for all robots in this view.""" + vel_str = "velocities_estimate" if estimate else "velocities" + if f"dof_{vel_str}" not in self._read_cache: + if estimate and self._last_state is not None: + if "dof_positions" not in self._read_cache: + self._read_cache["dof_positions"] = cb.from_torch(self._view.get_dof_positions()) + self._read_cache[f"dof_{vel_str}"] = ( + self._read_cache["dof_positions"] - self._last_state["dof_positions"] + ) / og.sim.get_physics_dt() + else: + self._read_cache[f"dof_{vel_str}"] = cb.from_torch(self._view.get_dof_velocities()) + return self._read_cache[f"dof_{vel_str}"] + + def get_joint_velocities(self, prim_path, estimate=False): + return self.get_all_joint_velocities(estimate=estimate)[self._idx[prim_path]] + + def get_all_joint_efforts(self): + """Returns (N, n_dof) joint efforts for all robots in this view.""" + if "dof_projected_joint_forces" not in self._read_cache: + self._read_cache["dof_projected_joint_forces"] = cb.from_torch(self._view.get_dof_projected_joint_forces()) + return self._read_cache["dof_projected_joint_forces"] + + def get_joint_efforts(self, prim_path): + return self.get_all_joint_efforts()[self._idx[prim_path]] + + def get_all_generalized_mass_matrices(self): + """Returns (N, n_dof, n_dof) mass matrices for all robots in this view.""" + if "mass_matrices" not in self._read_cache: + self._read_cache["mass_matrices"] = cb.from_torch(self._view.get_generalized_mass_matrices()) + return self._read_cache["mass_matrices"] + + def get_generalized_mass_matrices(self, prim_path): + return self.get_all_generalized_mass_matrices()[self._idx[prim_path]] + + def get_all_gravity_compensation_forces(self): + """Returns (N, n_dof) gravity compensation forces for all robots in this view.""" + if "generalized_gravity_forces" not in self._read_cache: + self._read_cache["generalized_gravity_forces"] = cb.from_torch(self._view.get_gravity_compensation_forces()) + return self._read_cache["generalized_gravity_forces"] + + def get_gravity_compensation_forces(self, prim_path): + return self.get_all_gravity_compensation_forces()[self._idx[prim_path]] + + def get_all_coriolis_and_centrifugal_compensation_forces(self): + """Returns (N, n_dof) Coriolis/centrifugal forces for all robots in this view.""" + if "coriolis_and_centrifugal_forces" not in self._read_cache: + self._read_cache["coriolis_and_centrifugal_forces"] = cb.from_torch( + self._view.get_coriolis_and_centrifugal_compensation_forces() + ) + return self._read_cache["coriolis_and_centrifugal_forces"] + + def get_coriolis_and_centrifugal_compensation_forces(self, prim_path): + return self.get_all_coriolis_and_centrifugal_compensation_forces()[self._idx[prim_path]] + + def get_link_transform(self, prim_path, link_name): + idx = self._idx[prim_path] + pos, quat = self.get_all_link_transform(link_name) + return pos[idx], quat[idx] + + def get_all_link_transform(self, link_name): + if "link_transforms" not in self._read_cache: + self._read_cache["link_transforms"] = cb.from_torch(self._view.get_link_transforms()) + + # We assume that in a view, link_idx for the same link_name is the same across all members + link_idx = self._link_idx[0][link_name] + pose = self._read_cache["link_transforms"][:, link_idx] + return pose[:, :3], pose[:, 3:] + + def _get_relative_poses(self, prim_path): + idx = self._idx[prim_path] + return self._get_all_relative_poses()[idx] + + def get_link_relative_position_orientation(self, prim_path, link_name): + idx = self._idx[prim_path] + pos, quat = self.get_all_link_relative_position_orientation(link_name) + return pos[idx], quat[idx] + + def _get_all_link_velocities(self, link_name, estimate=False): + """Returns (N, 6) velocities (linear + angular) for the given link across all robots.""" + vel_str = "velocities_estimate" if estimate else "velocities" + + # Build and cache the full (N, L, 6) tensor for all robots and all links + if f"link_{vel_str}" not in self._read_cache: + if estimate and self._last_state is not None: + # Compute link velocities estimate as delta between prior timestep and current timestep + N, L, _ = self._last_state["link_transforms"].shape + vels = cb.zeros((N, L, 6)) + + if "link_transforms" not in self._read_cache: + self._read_cache["link_transforms"] = cb.from_torch(self._view.get_link_transforms()) + + vels[:, :, :3] = ( + self._read_cache["link_transforms"][:, :, :3] - self._last_state["link_transforms"][:, :, :3] + ) + vels[:, :, 3:] = cb.view( + cb.T.quat2axisangle( + cb.T.quat_distance( + cb.view(self._read_cache["link_transforms"][:, :, 3:], (-1, 4)), + cb.view(self._last_state["link_transforms"][:, :, 3:], (-1, 4)), + ) + ), + (N, L, 3), + ) + self._read_cache[f"link_{vel_str}"] = vels / og.sim.get_physics_dt() + + # Otherwise, directly grab velocities + else: + self._read_cache[f"link_{vel_str}"] = cb.from_torch(self._view.get_link_velocities()) + + link_idx = self._link_idx[0][link_name] + return self._read_cache[f"link_{vel_str}"][:, link_idx, :] # (N, 6) + + def _get_link_velocities(self, prim_path, link_name, estimate=False): + idx = self._idx[prim_path] + return self._get_all_link_velocities(link_name, estimate=estimate)[idx] + + def get_link_linear_velocity(self, prim_path, link_name, estimate=False): + return self._get_link_velocities(prim_path, link_name, estimate=estimate)[:3] + + def get_all_link_linear_velocity(self, link_name, estimate=False): + return self._get_all_link_velocities(link_name, estimate=estimate)[:, :3] + + def get_link_relative_linear_velocity(self, prim_path, link_name, estimate=False): + idx = self._idx[prim_path] + link_idx = self._link_idx[idx][link_name] + return self._get_relative_velocities(prim_path, estimate=estimate)[link_idx, :3] + + def get_all_link_angular_velocity(self, link_name, estimate=False): + return self._get_all_link_velocities(link_name, estimate=estimate)[:, 3:] + + def get_link_relative_angular_velocity(self, prim_path, link_name, estimate=False): + idx = self._idx[prim_path] + link_idx = self._link_idx[idx][link_name] + return self._get_relative_velocities(prim_path, estimate=estimate)[link_idx, 3:] + + def get_all_jacobian(self): + if "jacobians" not in self._read_cache: + self._read_cache["jacobians"] = cb.from_torch(self._view.get_jacobians()) + return self._read_cache["jacobians"] + + def get_jacobian(self, prim_path): + idx = self._idx[prim_path] + return self.get_all_jacobian()[idx] + + def _get_all_relative_poses(self): + """Returns (N, n_links, 7) relative poses (pos + quat) for all robots in this view, batched.""" + if "relative_poses" not in self._read_cache: + # All link world transforms: (N, n_links, 7) + if "link_transforms" not in self._read_cache: + self._read_cache["link_transforms"] = cb.from_torch(self._view.get_link_transforms()) + all_link_tfs = cb.to_torch(self._read_cache["link_transforms"]) # (N, n_links, 7) + + # All base poses + all_pos, all_quat = self.get_all_position_orientation() # (N, 3), (N, 4) + all_pos = cb.to_torch(all_pos) + all_quat = cb.to_torch(all_quat) + + N, n_links = all_link_tfs.shape[:2] + + # Build link homogeneous transform matrices: (N, n_links, 4, 4) + tfs = th.zeros(N, n_links, 4, 4, dtype=th.float32) + tfs[:, :, 3, 3] = 1.0 + tfs[:, :, :3, 3] = all_link_tfs[:, :, :3] + # quat2mat doesn't handle rank-3 input; flatten the N*n_links batch dimension + tfs[:, :, :3, :3] = TT.quat2mat(all_link_tfs[:, :, 3:].reshape(-1, 4)).reshape(N, n_links, 3, 3) + + # Build batched base pose inverses: (N, 4, 4) + # For a rigid transform [R, t; 0, 1], the inverse is [R^T, -R^T t; 0, 1] + base_rot_T = TT.quat2mat(all_quat).transpose(-2, -1) # (N, 3, 3) + base_tf_inv = th.zeros(N, 4, 4, dtype=th.float32) + base_tf_inv[:, 3, 3] = 1.0 + base_tf_inv[:, :3, :3] = base_rot_T + base_tf_inv[:, :3, 3] = -(base_rot_T @ all_pos.unsqueeze(-1)).squeeze(-1) + + # Batched matmul: (N, 1, 4, 4) @ (N, n_links, 4, 4) → (N, n_links, 4, 4) + rel_tfs = base_tf_inv.unsqueeze(1) @ tfs + + # Convert back to (N, n_links, 7) pos + quat + rel_poses = th.zeros(N, n_links, 7, dtype=th.float32) + rel_poses[:, :, :3] = rel_tfs[:, :, :3, 3] + rel_poses[:, :, 3:] = TT.mat2quat(rel_tfs[:, :, :3, :3].reshape(-1, 3, 3)).reshape(N, n_links, 4) + + self._read_cache["relative_poses"] = cb.from_torch(rel_poses) + return self._read_cache["relative_poses"] + + def get_all_relative_jacobians(self): + """Returns (N, n_links, 6, n_dof_total) relative jacobians for all robots in this view.""" + if "relative_jacobians" not in self._read_cache: + # All raw jacobians: (N, n_links, 6, n_dof_total) + all_jacobians = cb.to_torch(self.get_all_jacobian()) + # Base orientation quaternions for all robots: (N, 4) + all_quats = cb.to_torch(self.get_all_position_orientation()[1]) + N = all_quats.shape[0] + + # Rotation matrices transposed per robot: (N, 3, 3) + ori_t_batch = TT.quat2mat(all_quats).transpose(-2, -1) + + # Build block-diagonal transform tf = [[ori_t, 0], [0, ori_t]]: (N, 6, 6) + tf = th.zeros(N, 6, 6, dtype=all_jacobians.dtype) + tf[:, :3, :3] = ori_t_batch + tf[:, 3:, 3:] = ori_t_batch + + # Batched matmul: (N, 1, 6, 6) @ (N, n_links, 6, n_dof_total) → (N, n_links, 6, n_dof_total) + # Run in pytorch since it's order of magnitude faster than numpy! + self._read_cache["relative_jacobians"] = cb.from_torch(tf.unsqueeze(1) @ all_jacobians) + return self._read_cache["relative_jacobians"] + + def get_relative_jacobian(self, prim_path): + idx = self._idx[prim_path] + return self.get_all_relative_jacobians()[idx] + + +def get_robot_kinematic_tree_pattern(articulation_root_path: str) -> str: + """ + Returns a glob pattern that matches all robots of the same type and fixedness as the + given articulation root path. + + The pattern generalizes over scene index and robot instance name, preserving the + robot-type component and any path suffix (e.g. base link name for floating-base robots). + + Examples: + "/World/scene_0/controllable__fetch__robot0" + -> "/World/scene_*/controllable__fetch__*" + "/World/scene_0/controllable__fetch__robot0/base_link" + -> "/World/scene_*/controllable__fetch__*/base_link" + """ + scene_id, robot_name = articulation_root_path.split("/")[2:4] + assert scene_id.startswith("scene_"), f"Prim path 2nd component {articulation_root_path} does not start with scene_" + components = robot_name.split("__") + assert len(components) == 3, ( + f"Robot prim path's 3rd component {robot_name} does not match " + "expected format of prefix__robottype__robotname." + ) + assert ( + components[0] == "controllable" + ), f"Prim path {articulation_root_path} 3rd component does not start with 'controllable__'" + return articulation_root_path.replace(f"/{scene_id}/", "/scene_*/").replace( + f"/{robot_name}", f"/{components[0]}__{components[1]}__*" + ) + + +class ControllableObjectViewAPI: + """ + An interface that creates BatchControlViewAPIImpl instances for each robot type in the scene. + + This is done to avoid the overhead of reading from many views for each robot in each physics step, + providing major speed improvements in vector env use cases. + + This class is a singleton, and should be used to access the BatchControlViewAPIImpl instances. + + The pattern used to group the robots is based on the robot prim paths, which is assumed to be in the format + /World/scene_*/controllable__robottype__robotname. + + The patterns used by the subviews are generated by replacing the robot name with a wildcard, so that all robots + of the same type are grouped together. If there are fixed base robots, they will be grouped separately from + non-fixed base robots even within the same robot type, by virtue of their different articulation root paths. + + **Return types:** All kinematic / dynamic getters delegate to :class:`BatchControlViewAPIImpl` and return + **compute-backend arrays** (``cb.arr_type`` from :mod:`omnigibson.utils.backend_utils`), after converting + Isaac articulation-view **torch** tensors with ``cb.from_torch``. Batched joint commands from controllers + should be **compute-backend arrays** (``cb.arr_type``). + """ + + # Dictionary mapping from pattern to BatchControlViewAPIImpl + _VIEWS_BY_PATTERN = {} + + @classmethod + def post_physics_step(cls): + for view in cls._VIEWS_BY_PATTERN.values(): + view.post_physics_step() + + @classmethod + def clear(cls): + for view in cls._VIEWS_BY_PATTERN.values(): + view.clear() + + @classmethod + def clear_object(cls, prim_path): + if get_robot_kinematic_tree_pattern(prim_path) in cls._VIEWS_BY_PATTERN: + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].clear() + + @classmethod + def flush_control(cls): + for view in cls._VIEWS_BY_PATTERN.values(): + view.flush_control() + + @classmethod + def initialize_view(cls): + cls._VIEWS_BY_PATTERN = {} + + # First, get all of the controllable objects in the scene (avoiding circular import) + from omnigibson.robots import Robot + + controllable_objects = [obj for scene in og.sim.scenes for obj in scene.objects if isinstance(obj, Robot)] + + # Get their corresponding prim paths + expected_prim_paths = {obj.articulation_root_path for obj in controllable_objects} + + # Group the prim paths by robot type + patterns = {get_robot_kinematic_tree_pattern(prim_path) for prim_path in expected_prim_paths} + + # Create the view for each robot type / fixedness combo + for pattern in patterns: + if pattern not in cls._VIEWS_BY_PATTERN: + cls._VIEWS_BY_PATTERN[pattern] = BatchControlViewAPIImpl(pattern) + + # Initialize the views + for view in cls._VIEWS_BY_PATTERN.values(): + view.initialize_view() + + # Assert that the views' prim paths are disjoint + all_prim_paths = [] + for view in cls._VIEWS_BY_PATTERN.values(): + all_prim_paths.extend(view._idx.keys()) + counts = collections.Counter(all_prim_paths) + + missing = set(expected_prim_paths) - set(all_prim_paths) + assert len(missing) == 0, f"Prim paths {missing} are missing from the views!" + + more_than_once = {prim_path: count for prim_path, count in counts.items() if count > 1} + assert len(more_than_once) == 0, f"Prim paths {more_than_once} are present in multiple views!" + + @classmethod + def set_joint_position_targets(cls, prim_path, positions, indices): + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].set_joint_position_targets( + prim_path, positions, indices + ) + + @classmethod + def set_joint_velocity_targets(cls, prim_path, velocities, indices): + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].set_joint_velocity_targets( + prim_path, velocities, indices + ) + + @classmethod + def set_joint_efforts(cls, prim_path, efforts, indices): + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].set_joint_efforts( + prim_path, efforts, indices + ) + + @classmethod + def get_member_view_indices(cls, routing_path, prim_paths): + """Return view row indices for prim_paths (all in same view as routing_path).""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(routing_path)].get_member_view_indices(prim_paths) + + @classmethod + def set_all_joint_position_targets(cls, routing_path, enabled_rows, controls, dof_idx): + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(routing_path)].set_all_joint_position_targets( + enabled_rows, controls, dof_idx + ) + + @classmethod + def set_all_joint_velocity_targets(cls, routing_path, enabled_rows, velocities, dof_idx): + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(routing_path)].set_all_joint_velocity_targets( + enabled_rows, velocities, dof_idx + ) + + @classmethod + def set_all_joint_efforts(cls, routing_path, enabled_rows, efforts, dof_idx): + cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(routing_path)].set_all_joint_efforts( + enabled_rows, efforts, dof_idx + ) + + @classmethod + def get_position_orientation(cls, prim_path): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_position_orientation(prim_path) + + @classmethod + def get_root_position_orientation(cls, prim_path): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_root_transform(prim_path) + + @classmethod + def get_linear_velocity(cls, prim_path, estimate=False): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_linear_velocity( + prim_path, estimate=estimate + ) + + @classmethod + def get_angular_velocity(cls, prim_path, estimate=False): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_angular_velocity( + prim_path, estimate=estimate + ) + + @classmethod + def get_all_joint_positions(cls, prim_path): + """Returns (N, n_dof) joint positions for all robots of the same type as @prim_path.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_joint_positions() + + @classmethod + def get_joint_positions(cls, prim_path): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_joint_positions(prim_path) + + @classmethod + def get_all_joint_velocities(cls, prim_path, estimate=False): + """Returns (N, n_dof) joint velocities for all robots of the same type as @prim_path.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_joint_velocities( + estimate=estimate + ) + + @classmethod + def get_joint_velocities(cls, prim_path, estimate=False): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_joint_velocities( + prim_path, estimate=estimate + ) + + @classmethod + def get_all_joint_efforts(cls, prim_path): + """Returns (N, n_dof) joint efforts for all robots of the same type as @prim_path.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_joint_efforts() + + @classmethod + def get_joint_efforts(cls, prim_path): + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_joint_efforts(prim_path) + + @classmethod + def get_all_generalized_mass_matrices(cls, prim_path): + """Returns (N, n_dof, n_dof) mass matrices for all robots of the same type as @prim_path.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_generalized_mass_matrices() + + @classmethod + def get_all_gravity_compensation_forces(cls, prim_path): + """Returns (N, n_dof) gravity compensation forces for all robots of the same type as @prim_path.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_gravity_compensation_forces() + + @classmethod + def get_all_coriolis_and_centrifugal_compensation_forces(cls, prim_path): + """Returns (N, n_dof) Coriolis/centrifugal forces for all robots of the same type as @prim_path.""" + return cls._VIEWS_BY_PATTERN[ + get_robot_kinematic_tree_pattern(prim_path) + ].get_all_coriolis_and_centrifugal_compensation_forces() + + @classmethod + def get_link_relative_position_orientation(cls, prim_path, link_name): + return cls._VIEWS_BY_PATTERN[ + get_robot_kinematic_tree_pattern(prim_path) + ].get_link_relative_position_orientation(prim_path, link_name) + + @classmethod + def get_link_index(cls, prim_path, link_name): + """Returns the integer body index for the named link in the articulation view's link_paths.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_link_index(link_name) + + @classmethod + def get_all_relative_jacobians(cls, prim_path): + """Returns (N, n_links, 6, n_dof_total) relative jacobians for all robots of the same type.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_relative_jacobians() + + @classmethod + def get_all_link_relative_position_orientation(cls, prim_path, link_name): + """Returns (N, 3) positions and (N, 4) quaternions for the given link across all robots.""" + return cls._VIEWS_BY_PATTERN[ + get_robot_kinematic_tree_pattern(prim_path) + ].get_all_link_relative_position_orientation(link_name) + + @classmethod + def get_all_link_relative_linear_velocity(cls, prim_path, link_name, estimate=False): + """Returns (N, 3) link linear velocities for all robots of the same type.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_link_relative_linear_velocity( + link_name, estimate=estimate + ) + + @classmethod + def get_all_link_relative_angular_velocity(cls, prim_path, link_name, estimate=False): + """Returns (N, 3) link angular velocities for all robots of the same type.""" + return cls._VIEWS_BY_PATTERN[ + get_robot_kinematic_tree_pattern(prim_path) + ].get_all_link_relative_angular_velocity(link_name, estimate=estimate) + + @classmethod + def get_all_relative_linear_velocity(cls, prim_path, estimate=False): + """Returns (N, 3) base linear velocities for all robots of the same type.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_relative_linear_velocity( + estimate=estimate + ) + + @classmethod + def get_all_relative_angular_velocity(cls, prim_path, estimate=False): + """Returns (N, 3) base angular velocities for all robots of the same type.""" + return cls._VIEWS_BY_PATTERN[get_robot_kinematic_tree_pattern(prim_path)].get_all_relative_angular_velocity( + estimate=estimate + ) + + +def clear(): + """ + Clear state tied to singleton classes + """ + CollisionAPI.clear() + RigidBodyViewAPI.clear() + RigidContactAPI.clear() + ArticulatedObjectViewAPI.clear() + ControllableObjectViewAPI.clear() + + +def create_mesh_prim_with_default_xform(primitive_type, prim_path, u_patches=None, v_patches=None, stage=None): + """ + Creates a mesh prim of the specified @primitive_type at the specified @prim_path + + Args: + primitive_type (str): Primitive mesh type, should be one of PRIMITIVE_MESH_TYPES to be valid + prim_path (str): Destination prim path to store the mesh prim + u_patches (int or None): If specified, should be an integer that represents how many segments to create in the + u-direction. E.g. 10 means 10 segments (and therefore 11 vertices) will be created. + v_patches (int or None): If specified, should be an integer that represents how many segments to create in the + v-direction. E.g. 10 means 10 segments (and therefore 11 vertices) will be created. + Both u_patches and v_patches need to be specified for them to be effective. + stage (None or Usd.Stage): If specified, stage on which the primitive mesh should be generated. If None, will + use og.sim.stage + """ + with og.sim.editing_usd(stage=stage): + MESH_PRIM_TYPE_TO_EVALUATOR_MAPPING = { + "Sphere": lazy.omni.kit.primitive.mesh.evaluators.sphere.SphereEvaluator, + "Disk": lazy.omni.kit.primitive.mesh.evaluators.disk.DiskEvaluator, + "Plane": lazy.omni.kit.primitive.mesh.evaluators.plane.PlaneEvaluator, + "Cylinder": lazy.omni.kit.primitive.mesh.evaluators.cylinder.CylinderEvaluator, + "Torus": lazy.omni.kit.primitive.mesh.evaluators.torus.TorusEvaluator, + "Cone": lazy.omni.kit.primitive.mesh.evaluators.cone.ConeEvaluator, + "Cube": lazy.omni.kit.primitive.mesh.evaluators.cube.CubeEvaluator, + } + + assert primitive_type in PRIMITIVE_MESH_TYPES, "Invalid primitive mesh type: {primitive_type}" + evaluator = MESH_PRIM_TYPE_TO_EVALUATOR_MAPPING[primitive_type] + u_backup = lazy.carb.settings.get_settings().get(evaluator.SETTING_U_SCALE) + v_backup = lazy.carb.settings.get_settings().get(evaluator.SETTING_V_SCALE) + hs_backup = lazy.carb.settings.get_settings().get(evaluator.SETTING_OBJECT_HALF_SCALE) + lazy.carb.settings.get_settings().set(evaluator.SETTING_U_SCALE, 1) + lazy.carb.settings.get_settings().set(evaluator.SETTING_V_SCALE, 1) + stage = og.sim.stage if stage is None else stage + + # Default half_scale (i.e. half-extent, half_height, radius) is 1. + # TODO (eric): change it to 0.5 once the mesh generator API accepts floating-number HALF_SCALE + # (currently it only accepts integer-number and floors 0.5 into 0). + lazy.carb.settings.get_settings().set(evaluator.SETTING_OBJECT_HALF_SCALE, 1) + kwargs = dict(prim_type=primitive_type, prim_path=prim_path, stage=stage) + if u_patches is not None and v_patches is not None: + kwargs["u_patches"] = u_patches + kwargs["v_patches"] = v_patches + + # Import now to avoid too-eager load of Omni classes due to inheritance + from omnigibson.utils.deprecated_utils import CreateMeshPrimWithDefaultXformCommand + + CreateMeshPrimWithDefaultXformCommand(**kwargs).do() + + lazy.carb.settings.get_settings().set(evaluator.SETTING_U_SCALE, u_backup) + lazy.carb.settings.get_settings().set(evaluator.SETTING_V_SCALE, v_backup) + lazy.carb.settings.get_settings().set(evaluator.SETTING_OBJECT_HALF_SCALE, hs_backup) + + +def mesh_prim_mesh_to_trimesh_mesh(mesh_prim, include_normals=True, include_texcoord=True): + """ + Generates trimesh mesh from @mesh_prim if mesh_type is "Mesh" + + Args: + mesh_prim (Usd.Prim): Mesh prim to convert into trimesh mesh + include_normals (bool): Whether to include the normals in the resulting trimesh or not + include_texcoord (bool): Whether to include the corresponding 2D-texture coordinates in the resulting + trimesh or not + + Returns: + trimesh.Trimesh: Generated trimesh mesh + """ + mesh_type = mesh_prim.GetPrimTypeInfo().GetTypeName() + assert mesh_type == "Mesh", f"Expected mesh prim to have type Mesh, got {mesh_type}" + face_vertex_counts = vtarray_to_torch(mesh_prim.GetAttribute("faceVertexCounts").Get(), dtype=th.int) + vertices = vtarray_to_torch(mesh_prim.GetAttribute("points").Get()) + face_indices = vtarray_to_torch(mesh_prim.GetAttribute("faceVertexIndices").Get(), dtype=th.int) + + faces = [] + i = 0 + for count in face_vertex_counts: + for j in range(count - 2): + faces.append([face_indices[i], face_indices[i + j + 1], face_indices[i + j + 2]]) + i += count + + kwargs = dict(vertices=vertices, faces=faces) + + if include_normals: + kwargs["vertex_normals"] = vtarray_to_torch(mesh_prim.GetAttribute("normals").Get()) + + if include_texcoord: + raw_texture = mesh_prim.GetAttribute("primvars:st").Get() + if raw_texture is not None: + kwargs["visual"] = trimesh.visual.TextureVisuals(uv=vtarray_to_torch(raw_texture)) + + return trimesh.Trimesh(**kwargs) + + +def mesh_prim_shape_to_trimesh_mesh(mesh_prim): + """ + Generates trimesh mesh from @mesh_prim if mesh_type is "Sphere", "Cube", "Cone" or "Cylinder" + + Args: + mesh_prim (Usd.Prim): Mesh prim to convert into trimesh mesh + + Returns: + trimesh.Trimesh: Generated trimesh mesh + """ + mesh_type = mesh_prim.GetPrimTypeInfo().GetTypeName() + if mesh_type == "Sphere": + radius = mesh_prim.GetAttribute("radius").Get() + trimesh_mesh = trimesh.creation.icosphere(subdivision=3, radius=radius) + elif mesh_type == "Cube": + extent = mesh_prim.GetAttribute("size").Get() + trimesh_mesh = trimesh.creation.box([extent] * 3) + elif mesh_type == "Cone": + radius = mesh_prim.GetAttribute("radius").Get() + height = mesh_prim.GetAttribute("height").Get() + trimesh_mesh = trimesh.creation.cone(radius=radius, height=height) + # Trimesh cones are centered at the base. We'll move them down by half the height. + transform = trimesh.transformations.translation_matrix([0, 0, -height / 2]) + trimesh_mesh.apply_transform(transform) + elif mesh_type == "Cylinder": + radius = mesh_prim.GetAttribute("radius").Get() + height = mesh_prim.GetAttribute("height").Get() + trimesh_mesh = trimesh.creation.cylinder(radius=radius, height=height) + else: + raise ValueError(f"Expected mesh prim to have type Sphere, Cube, Cone or Cylinder, got {mesh_type}") + + return trimesh_mesh + + +def mesh_prim_to_trimesh_mesh(mesh_prim, include_normals=True, include_texcoord=True, world_frame=False): + """ + Generates trimesh mesh from @mesh_prim + + Args: + mesh_prim (Usd.Prim): Mesh prim to convert into trimesh mesh + include_normals (bool): Whether to include the normals in the resulting trimesh or not + include_texcoord (bool): Whether to include the corresponding 2D-texture coordinates in the resulting + trimesh or not + world_frame (bool): Whether to convert the mesh to the world frame or not + + Returns: + trimesh.Trimesh: Generated trimesh mesh + """ + mesh_type = mesh_prim.GetTypeName() + if mesh_type == "Mesh": + trimesh_mesh = mesh_prim_mesh_to_trimesh_mesh(mesh_prim, include_normals, include_texcoord) + else: + trimesh_mesh = mesh_prim_shape_to_trimesh_mesh(mesh_prim) + + if world_frame: + trimesh_mesh.apply_transform(get_world_pose_with_scale(mesh_prim.GetPath().pathString)) + + return trimesh_mesh + + +def sample_mesh_keypoints(mesh_prim, n_keypoints, n_keyfaces, seed=None): + """ + Samples keypoints and keyfaces for mesh @mesh_prim + + Args: + mesh_prim (Usd.Prim): Mesh prim to be sampled from + n_keypoints (int): number of (unique) keypoints to randomly sample from @mesh_prim + n_keyfaces (int): number of (unique) keyfaces to randomly sample from @mesh_prim + seed (None or int): If set, sets the random seed for deterministic results + + Returns: + 2-tuple: + - n-array: (n,) 1D int array representing the randomly sampled point idxs from @mesh_prim. + Note that since this is without replacement, the total length of the array may be less than + @n_keypoints + - None or n-array: 1D int array representing the randomly sampled face idxs from @mesh_prim. + Note that since this is without replacement, the total length of the array may be less than + @n_keyfaces + """ + # Set seed if deterministic + if seed is not None: + th.manual_seed(seed) + + # Generate trimesh mesh from which to aggregate points + tm = mesh_prim_mesh_to_trimesh_mesh(mesh_prim=mesh_prim, include_normals=False, include_texcoord=False) + n_unique_vertices, n_unique_faces = len(tm.vertices), len(tm.faces) + faces_flat = th.tensor(tm.faces.flatten(), dtype=th.int32) + + # Sample vertices + unique_vertices = th.unique(faces_flat) + assert len(unique_vertices) == n_unique_vertices + keypoint_idx = ( + th.randperm(len(unique_vertices))[:n_keypoints] if n_unique_vertices > n_keypoints else unique_vertices + ) + + # Sample faces + keyface_idx = th.randperm(n_unique_faces)[:n_keyfaces] if n_unique_faces > n_keyfaces else th.arange(n_unique_faces) + + return keypoint_idx, keyface_idx + + +def get_mesh_volume_and_com(mesh_prim, world_frame=False): + """ + Computes the volume and center of mass for @mesh_prim + + Args: + mesh_prim (Usd.Prim): Mesh prim to compute volume and center of mass for + world_frame (bool): Whether to return the volume and CoM in the world frame + + Returns: + Tuple[float, th.tensor]: Tuple containing the (volume, center_of_mass) in the mesh frame or the world frame + """ + + trimesh_mesh = mesh_prim_to_trimesh_mesh( + mesh_prim, include_normals=False, include_texcoord=False, world_frame=world_frame + ) + if trimesh_mesh.is_volume: + volume = trimesh_mesh.volume + com = th.tensor(trimesh_mesh.center_mass) + else: + # If the mesh is not a volume, we compute its convex hull and use that instead + try: + trimesh_mesh_convex = trimesh_mesh.convex_hull + volume = trimesh_mesh_convex.volume + com = th.tensor(trimesh_mesh_convex.center_mass) + except: + # if convex hull computation fails, it usually means the mesh is degenerated: use trivial values. + volume = 0.0 + com = th.zeros(3) + + return volume, com.to(dtype=th.float32) + + +def check_extent_radius_ratio(geom_prim, com): + """ + Checks if the min extent in world frame and the extent radius ratio in local frame of @geom_prim is within the + acceptable range for PhysX GPU acceleration (not too thin, and not too oblong) + + Ref: https://github.com/NVIDIA-Omniverse/PhysX/blob/561a0df858d7e48879cdf7eeb54cfe208f660f18/physx/source/geomutils/src/convex/GuConvexMeshData.h#L183-L190 + + Args: + geom_prim (GeomPrim): Geom prim to check + com (th.tensor): Center of mass of the mesh. Obtained from get_mesh_volume_and_com + + Returns: + bool: True if the min extent (world) and the extent radius ratio (local frame) is acceptable, False otherwise + """ + mesh_type = geom_prim.prim.GetPrimTypeInfo().GetTypeName() + # Non-mesh prims are always considered to be within the acceptable range + if mesh_type != "Mesh": + return True + + extent = geom_prim.extent + min_extent = extent.min() + # If the mesh is too flat in the world frame, omniverse cannot create convex mesh for it + if min_extent < 1e-5: + return False + + max_radius = extent.max() / 2.0 + min_radius = th.min(th.norm(geom_prim.points - com, dim=-1), dim=0).values + ratio = max_radius / min_radius + + # PhysX requires ratio to be < 100.0. We use 95.0 to be safe. + return ratio < 95.0 + + +def create_primitive_mesh(prim_path, primitive_type, extents=1.0, u_patches=None, v_patches=None, stage=None): + """ + Helper function that generates a UsdGeom.Mesh prim at specified @prim_path of type @primitive_type. + + NOTE: Generated mesh prim will, by default, have extents equaling [1, 1, 1] + + Args: + prim_path (str): Where the loaded mesh should exist on the stage + primitive_type (str): Type of primitive mesh to create. Should be one of: + {"Cone", "Cube", "Cylinder", "Disk", "Plane", "Sphere", "Torus"} + extents (float or 3-array): Specifies the extents of the generated mesh. Default is 1.0, i.e.: + generated mesh will be in be contained in a [1,1,1] sized bounding box + u_patches (int or None): If specified, should be an integer that represents how many segments to create in the + u-direction. E.g. 10 means 10 segments (and therefore 11 vertices) will be created. + v_patches (int or None): If specified, should be an integer that represents how many segments to create in the + v-direction. E.g. 10 means 10 segments (and therefore 11 vertices) will be created. + Both u_patches and v_patches need to be specified for them to be effective. + stage (None or Usd.Stage): If specified, stage on which the primitive mesh should be generated. If None, will + use og.sim.stage + + Returns: + UsdGeom.Mesh: Generated primitive mesh as a prim on the active stage + """ + assert_valid_key(key=primitive_type, valid_keys=PRIMITIVE_MESH_TYPES, name="primitive mesh type") + create_mesh_prim_with_default_xform( + primitive_type, prim_path, u_patches=u_patches, v_patches=v_patches, stage=stage + ) + + with og.sim.editing_usd(stage=stage): + mesh = lazy.pxr.UsdGeom.Mesh.Define(og.sim.stage if stage is None else stage, prim_path) + + # Modify the points and normals attributes so that total extents is the desired + # This means multiplying omni's default by extents * 50.0, as the native mesh generated has extents [-0.01, 0.01] + # -- i.e.: 2cm-wide mesh + extents = th.ones(3) * extents if isinstance(extents, float) else th.tensor(extents) + for attr in (mesh.GetPointsAttr(), mesh.GetNormalsAttr()): + vals = th.tensor(attr.Get()).double() + attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*(val * extents * 50.0).tolist()) for val in vals])) + mesh.GetExtentAttr().Set( + lazy.pxr.Vt.Vec3fArray( + [lazy.pxr.Gf.Vec3f(*(-extents / 2.0).tolist()), lazy.pxr.Gf.Vec3f(*(extents / 2.0).tolist())] + ) + ) + + return triangularize_mesh(mesh) + + +def create_usd_stage(usd_path): + stage = lazy.pxr.Usd.Stage.CreateNew(usd_path) + lazy.pxr.UsdGeom.SetStageMetersPerUnit(stage, 1.0) + lazy.pxr.UsdGeom.SetStageUpAxis(stage, "Z") + return stage + + +def triangularize_mesh(mesh): + """ + Triangulates the mesh @mesh, modification in-place + """ + with og.sim.editing_usd(): + tm = mesh_prim_to_trimesh_mesh(mesh.GetPrim()) + + face_vertex_counts = np.array([len(face) for face in tm.faces], dtype=int) + mesh.GetFaceVertexCountsAttr().Set(face_vertex_counts) + mesh.GetFaceVertexIndicesAttr().Set(tm.faces.flatten()) + mesh.GetNormalsAttr().Set(lazy.pxr.Vt.Vec3fArray.FromNumpy(tm.vertex_normals[tm.faces.flatten()])) + + # Modify the UV mapping if it exists + if isinstance(tm.visual, trimesh.visual.TextureVisuals): + mesh.GetPrim().GetAttribute("primvars:st").Set( + lazy.pxr.Vt.Vec2fArray.FromNumpy(tm.visual.uv[tm.faces.flatten()]) + ) + + return mesh + + +def add_asset_to_stage(asset_path, prim_path): + """ + Adds asset file (either USD or OBJ) at @asset_path at the location @prim_path + + Args: + asset_path (str): Absolute or relative path to the asset file to load + prim_path (str): Where loaded asset should exist on the stage + + Returns: + Usd.Prim: Loaded prim as a USD prim + """ + with og.sim.editing_usd(): + # Make sure this is actually a supported asset type + asset_type = asset_path.split(".")[-1] + assert asset_type in {"usd", "usda", "obj", "usdz"}, "Cannot load a non-USD or non-OBJ file as a USD prim!" + + # Make sure the path exists + assert os.path.exists( + asset_path + ), f"Cannot load {asset_type.upper()} file {asset_path} because it does not exist!" + + # Add reference to stage and grab prim + lazy.isaacsim.core.utils.stage.add_reference_to_stage(usd_path=asset_path, prim_path=prim_path) + prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path) + + # Make sure prim was loaded correctly + assert prim, f"Failed to load {asset_type.upper()} object from path: {asset_path}" + + return prim + + +def get_world_prim(): + """ + Returns: + Usd.Prim: Active world prim in the current stage + """ + return lazy.isaacsim.core.utils.prims.get_prim_at_path("/World") + + +def scene_relative_prim_path_to_absolute(scene, relative_prim_path): + """ + Converts a scene-relative prim path to an absolute prim path. + + Args: + scene (Scene or None): Scene object that the prim is in. None if it's global. + relative_prim_path (str): Relative prim path in the scene + + Returns: + str: Absolute prim path in the stage + """ + # Special case for OmniGraph prims + if relative_prim_path.startswith("/OmniGraph"): + return relative_prim_path + + # Special case for global floor plane collision prim — already an absolute path + if ( + og.sim.floor_plane is not None + and relative_prim_path == og.sim.floor_plane.relative_prim_path + "/collisionPlane" + ): + return relative_prim_path + + # Make sure the relative path is actually relative + assert not relative_prim_path.startswith("/World"), f"Expected relative prim path, got {relative_prim_path}" + + # When the scene is set to None, this prim is not in a scene but is global e.g. like the + # viewer camera or one of the scene prims. + if scene is None: + return "/World" + relative_prim_path + + return scene.prim_path + relative_prim_path + + +def absolute_prim_path_to_scene_relative(scene, absolute_prim_path): + """ + Converts an absolute prim path to a scene-relative prim path. + + Args: + scene (Scene): Scene object that the prim is in. None if it's global. + absolute_prim_path (str): Absolute prim path in the stage + + Returns: + str: Relative prim path in the scene + """ + # Special case for OmniGraph prims + if absolute_prim_path.startswith("/OmniGraph"): + return absolute_prim_path + + # Special case for global floor plane collision prim — not scene-scoped, return unchanged + if ( + og.sim.floor_plane is not None + and absolute_prim_path == og.sim.floor_plane.relative_prim_path + "/collisionPlane" + ): + return absolute_prim_path + + assert absolute_prim_path.startswith("/World"), f"Expected absolute prim path, got {absolute_prim_path}" + + # When the scene is set to None, this prim is not in a scene but is global e.g. like the + # viewer camera or one of the scene prims. + if scene is None: + assert not absolute_prim_path.startswith( + "/World/scene_" + ), f"Expected global prim path, got {absolute_prim_path}" + return absolute_prim_path[len("/World") :] + + return absolute_prim_path[len(scene.prim_path) :] + + +def delete_or_deactivate_prim(prim_path): + """ + Attept to delete or deactivate the prim defined at @prim_path. + + Note that the removal of prims usually has an impact on the PhysX state and needs to be followed + by a call to og.sim.update_handles() to update tensor views etc. - we do not do here to avoid + performance overhead when lots of prims are removed at once in clear() etc. and instead we + delegate this to the caller. + + Args: + prim_path (str): Path defining which prim should be deleted or deactivated + + Returns: + bool: Whether the operation was successful or not + """ + + # TODO: Replace the weird delete-or-deactivate mechanism here with a concrete deletion + # using the Sdf layer deletion API. + with og.sim.editing_usd(): + if not lazy.isaacsim.core.utils.prims.is_prim_path_valid(prim_path): + return False + if lazy.isaacsim.core.utils.prims.is_prim_no_delete(prim_path): + return False + if lazy.isaacsim.core.utils.prims.get_prim_type_name(prim_path=prim_path) == "PhysicsScene": + return False + if prim_path == "/World": + return False + if prim_path == "/": + return False + # Don't remove any /Render prims as that can cause crashes + if prim_path.startswith("/Render"): + return False + + # If the prim is not ancestral, we can delete it. + if not lazy.isaacsim.core.utils.prims.is_prim_ancestral(prim_path): + lazy.omni.usd.commands.DeletePrimsCommand([prim_path], destructive=True).do() + + # Otherwise, we can only deactivate it, which essentially serves the same purpose. + # All objects that are originally in the scene are ancestral because we add the pre-build scene to the stage. + else: + # Clear all default attributes before deactivating the prim to ensure clean reactivation. + # Note: Prim deactivation preserves attribute values, so we must explicitly clear defaults + # to prevent stale custom values from persisting when the prim is reactivated later. + prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prim_path) + for attr in prim.GetAttributes(): + assert attr.ClearDefault() + lazy.omni.usd.commands.DeletePrimsCommand([prim_path], destructive=False).do() + + return True + + +def activate_prim_and_children(prim_path): + """ + Recursively activates the prim at @prim_path and all of its children. + + Args: + prim_path (str): Path to the prim to activate + """ + + def _activate(path): + current_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(path) + current_prim.SetActive(True) + for child in current_prim.GetAllChildren(): + _activate(child.GetPath().pathString) + + with og.sim.editing_usd(): + _activate(prim_path) + + +def get_sdf_value_type_name(val): + """ + Determines the appropriate Sdf value type based on the input value. + Args: + val: The input value to determine the type for. + Returns: + lazy.pxr.Sdf.ValueTypeName: The corresponding Sdf value type. + Raises: + ValueError: If the input value type is not supported. + """ + SDF_TYPE_MAPPING = { + lazy.pxr.Gf.Vec3f: lazy.pxr.Sdf.ValueTypeNames.Float3, + lazy.pxr.Gf.Vec2f: lazy.pxr.Sdf.ValueTypeNames.Float2, + lazy.pxr.Sdf.AssetPath: lazy.pxr.Sdf.ValueTypeNames.Asset, + bool: lazy.pxr.Sdf.ValueTypeNames.Bool, + int: lazy.pxr.Sdf.ValueTypeNames.Int, + float: lazy.pxr.Sdf.ValueTypeNames.Float, + str: lazy.pxr.Sdf.ValueTypeNames.String, + } + for type_, usd_type in SDF_TYPE_MAPPING.items(): + if isinstance(val, type_): + return usd_type + raise ValueError(f"Unsupported input type: {type(val)}") + + +def replace_collision_blocks(old_usd_path: str, new_usd_path: str, output_usd_path: str): + """ + Replace all collisions blocks in new_usd_path with those from old_usd_path. + """ + + def extract_collision_blocks(text): + """ + Extract all top-level 'def [Mesh] "collisions"' blocks using brace matching. + Returns a list of (start_idx, end_idx, block_text) + """ + blocks = [] + lines = text.splitlines(keepends=True) + i = 0 + while i < len(lines): + line = lines[i].strip() + if line.startswith("def") and '"collisions"' in line: + start = i + brace_count = 0 + # Find the opening brace + while "{" not in lines[i]: + i += 1 + if i >= len(lines): + break + if i >= len(lines): + break + brace_count += lines[i].count("{") - lines[i].count("}") + i += 1 + # Count braces to find block end + while brace_count > 0 and i < len(lines): + brace_count += lines[i].count("{") - lines[i].count("}") + i += 1 + end = i + block_text = "".join(lines[start:end]) + blocks.append((start, end, block_text)) + else: + i += 1 + return blocks + + # Load USDA files + with open(old_usd_path, "r") as f: + source_usda = f.read() + with open(new_usd_path, "r") as f: + target_usda = f.read() + + # Extract collision blocks + source_collision_blocks = extract_collision_blocks(source_usda) + target_blocks = extract_collision_blocks(target_usda) + + # Replace in target + if len(target_blocks) != len(source_collision_blocks): + print(f"Warning: Replacing {min(len(target_blocks), len(source_collision_blocks))} blocks due to mismatch.") + + new_lines = [] + last_idx = 0 + target_lines = target_usda.splitlines(keepends=True) + for (start, end, _), (_, _, new_block) in zip(target_blocks, source_collision_blocks): + new_lines.extend(target_lines[last_idx:start]) + new_lines.append(new_block) + last_idx = end + new_lines.extend(target_lines[last_idx:]) + + new_usda_text = "".join(new_lines) + + # Save result + with open(output_usd_path, "w") as f: + f.write(new_usda_text) + + print(f"Finished replacing all {len(source_collision_blocks)} collision blocks.") + + +@torch_compile +def _compute_relative_poses_torch( + idx: int, + n_links: int, + all_tfs: th.Tensor, + base_pose: Tuple[th.Tensor, th.Tensor], +): + tfs = th.zeros((n_links, 4, 4), dtype=th.float32) + # base vel is the final -1 index + link_tfs = all_tfs[idx, :] + tfs[:, 3, 3] = 1.0 + tfs[:, :3, 3] = link_tfs[:, :3] + tfs[:, :3, :3] = TT.quat2mat(link_tfs[:, 3:]) + base_tf_inv = th.zeros((1, 4, 4), dtype=th.float32) + base_tf_inv[0, :, :] = TT.pose_inv(TT.pose2mat(base_pose)) + + # (1, 4, 4) @ (n_links, 4, 4) -> (n_links, 4, 4) + rel_tfs = base_tf_inv @ tfs + + # Re-convert to quat form + rel_poses = th.zeros((n_links, 7), dtype=th.float32) + rel_poses[:, :3] = rel_tfs[:, :3, 3] + rel_poses[:, 3:] = TT.mat2quat(rel_tfs[:, :3, :3]) + + return rel_poses + + +@jit(nopython=True, cache=True) +def _compute_relative_poses_numpy(idx, n_links, all_tfs, base_pose): + tfs = np.zeros((n_links, 4, 4), dtype=np.float32) + # base vel is the final -1 index + link_tfs = all_tfs[idx, :] + tfs[:, 3, 3] = 1.0 + tfs[:, :3, 3] = link_tfs[:, :3] + tfs[:, :3, :3] = NT._quat2mat(link_tfs[:, 3:]) + # base_tf_inv = np.zeros((1, 4, 4), dtype=np.float32) + # base_tf_inv[0, :, :] = NT._pose_inv(NT.pose2mat(base_pose)) + base_tf_inv = NT._pose_inv(NT.pose2mat(base_pose)) + + # (1, 4, 4) @ (n_links, 4, 4) -> (n_links, 4, 4) + rel_tfs = np.zeros((n_links, 4, 4), dtype=np.float32) + for i in prange(n_links): + rel_tfs[i, :, :] = base_tf_inv @ tfs[i, :, :] + # rel_tfs = base_tf_inv @ tfs + + # Re-convert to quat form + rel_poses = np.zeros((n_links, 7), dtype=np.float32) + rel_poses[:, :3] = rel_tfs[:, :3, 3] + rel_poses[:, 3:] = NT.mat2quat_batch(rel_tfs[:, :3, :3].copy()) + + return rel_poses + + +# Set these as part of the backend values +add_compute_function( + name="compute_relative_poses", np_function=_compute_relative_poses_numpy, th_function=_compute_relative_poses_torch +) + + +def count_joints(prim): + """ + Search from @prim to count movable joints, fixed joints, and attachment points. + + Args: + prim (Usd.Prim): Root prim to search from. + + Returns: + tuple: (n_joints, n_fixed_joints, has_attachment) where + n_joints (int): number of non-fixed physics joints, + n_fixed_joints (int): number of fixed physics joints, + has_attachment (bool): whether any prim name contains "attachment". + """ + n_joints = 0 + n_fixed_joints = 0 + has_attachment = False + children = list(prim.GetChildren()) + while children: + child_prim = children.pop() + children.extend(child_prim.GetChildren()) + prim_type = child_prim.GetPrimTypeInfo().GetTypeName().lower() + if "joint" in prim_type: + if "fixed" in prim_type: + n_fixed_joints += 1 + else: + n_joints += 1 + if "attachment" in child_prim.GetName().lower(): + has_attachment = True + return n_joints, n_fixed_joints, has_attachment + + +def find_joint_prims(root_prim): + """ + Recursively search under @root_prim and yield every physics joint prim found. + + Recent Isaac Sim USD exports place joints in a flat scope rather than nested under their body0 + link prim, so any code that needs to enumerate an object's joints must traverse the whole subtree + rather than just the children of each link. + + Args: + root_prim (Usd.Prim): Root prim to search under. + + Yields: + Usd.Prim: Each physics joint prim found anywhere under @root_prim. + """ + children = list(root_prim.GetChildren()) + while children: + child = children.pop() + children.extend(child.GetChildren()) + if "joint" in child.GetPrimTypeInfo().GetTypeName().lower(): + yield child + + +def compute_kinematic_only(fixed_base, scale, n_joints, n_fixed_joints, kinematic_only_config, has_attachment): + """ + Determine whether an object should be kinematic-only based on its properties. + + Args: + fixed_base (bool): Whether the object has a fixed base. + scale (th.Tensor): 3-element scale tensor. + n_joints (int): Number of non-fixed joints. + n_fixed_joints (int): Number of fixed joints. + kinematic_only_config: Value of the kinematic_only load config key (True, False, or None). + has_attachment (bool): Whether the object has attachment points. + + Returns: + bool: True if the object should be kinematic only. + """ + if not fixed_base: + return False + if kinematic_only_config is False: + return False + return ( + n_joints == 0 + and (th.all(th.isclose(scale, th.ones_like(scale), atol=1e-3)).item() or n_fixed_joints == 0) + and not has_attachment + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/vision_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/vision_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cd28d2c60aa0060e33bc7d520a14e357edd973ec --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/vision_utils.py @@ -0,0 +1,372 @@ +import colorsys + +import torch as th +from PIL import Image, ImageDraw +import omnigibson as og +import omnigibson.utils.transform_utils as T +import omnigibson.lazy as lazy + + +def add_semantic_label(prim, label, instance_name="class"): + """ + Helper function to add semantic labels to a prim. + This upgrades the prim semantics to labels and adds the specified label. + + Args: + prim: The prim to add labels to + label (str): The semantic label to add (will be converted to a list internally) + instance_name (str): The instance name for the label. Defaults to "class" + """ + with og.sim.editing_usd(): + lazy.isaacsim.core.utils.semantics.upgrade_prim_semantics_to_labels(prim=prim) + lazy.isaacsim.core.utils.semantics.add_labels(prim=prim, labels=[label], instance_name=instance_name) + + +class RandomScale: + """Rescale the input PIL.Image to the given size. + Args: + minsize (sequence or int): Desired min output size. If size is a sequence like + (w, h), output size will be matched to this. If size is an int, + smaller edge of the image will be matched to this number. + i.e, if height > width, then image will be rescaled to + (size * height / width, size) + maxsize (sequence or int): Desired max output size. If size is a sequence like + (w, h), output size will be matched to this. If size is an int, + smaller edge of the image will be matched to this number. + i.e, if height > width, then image will be rescaled to + (size * height / width, size) + interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` + """ + + def __init__(self, minsize, maxsize, interpolation=Image.BILINEAR): + assert isinstance(minsize, int) + assert isinstance(maxsize, int) + self.minsize = minsize + self.maxsize = maxsize + self.interpolation = interpolation + + def __call__(self, img): + """ + Args: + img (PIL.Image): Image to be scaled. + + Returns: + PIL.Image: Rescaled image. + """ + + size = th.randint(self.minsize, self.maxsize + 1) + + if isinstance(size, int): + w, h = img.size + if (w <= h and w == size) or (h <= w and h == size): + return img + if w < h: + ow = size + oh = int(size * h / w) + return img.resize((ow, oh), self.interpolation) + else: + oh = size + ow = int(size * w / h) + return img.resize((ow, oh), self.interpolation) + else: + raise NotImplementedError() + + +class Remapper: + """ + Remaps values in an image from old_mapping to new_mapping using an efficient key_array. + See more details in the remap method. + """ + + def __init__(self): + self.key_array = None # Will be initialized with the correct device on first use + self.known_ids = set() + self.unlabelled_ids = set() + self.warning_printed = set() + + def clear(self): + """Resets the key_array to empty.""" + self.key_array = None # Will be reinitialized with the correct device on next use + self.known_ids = set() + self.unlabelled_ids = set() + + def remap(self, old_mapping, new_mapping, image, image_keys=None): + """ + Remaps values in the given image from old_mapping to new_mapping using an efficient key_array. + If the image contains values that are not in old_mapping, they are remapped to the value in new_mapping + that corresponds to 'unlabelled'. + + Args: + old_mapping (dict): The old mapping dictionary that maps a set of image values to labels + e.g. {1: 'desk', 2: 'chair'}. + new_mapping (dict): The new mapping dictionary that maps another set of image values to labels, + e.g. {5: 'desk', 7: 'chair', 100: 'unlabelled'}. + image (th.tensor): The 2D image to remap, e.g. [[1, 3], [1, 2]]. + image_keys (th.tensor): The unique keys in the image, e.g. [1, 2, 3]. + + Returns: + th.tensor: The remapped image, e.g. [[5,100],[5,7]]. + dict: The remapped labels dictionary, e.g. {5: 'desk', 7: 'chair', 100: 'unlabelled'}. + """ + # Make sure that max int32 doesn't match any value in the new mapping + assert th.all( + th.tensor(list(new_mapping.keys())) != th.iinfo(th.int32).max + ), "New mapping contains default unmapped value!" + image_max_key = max(th.max(image).item(), max(old_mapping.keys())) + + if self.key_array is None: + # First time initialization + self.key_array = th.full((image_max_key + 1,), th.iinfo(th.int32).max, dtype=th.int32, device=image.device) + else: + key_array_max_key = len(self.key_array) - 1 + if image_max_key > key_array_max_key: + prev_key_array = self.key_array.clone() + # We build a new key array and use max int32 as the default value. + self.key_array = th.full( + (image_max_key + 1,), th.iinfo(th.int32).max, dtype=th.int32, device=image.device + ) + # Copy the previous key array into the new key array + self.key_array[: len(prev_key_array)] = prev_key_array + + # Retrospectively inspect our cached ids against the old mapping and update the key array + updated_ids = set() + for unlabelled_id in self.unlabelled_ids: + if unlabelled_id in old_mapping and old_mapping[unlabelled_id] != "unlabelled": + # If an object was previously unlabelled but now has a label, we need to update the key array + updated_ids.add(unlabelled_id) + self.unlabelled_ids -= updated_ids + + # For updated ids, we need to update their key_array entries and then mark them as known + for updated_id in updated_ids: + label = old_mapping[updated_id] + new_key = next((k for k, v in new_mapping.items() if v == label), None) + assert new_key is not None, f"Could not find a new key for label {label} in new_mapping!" + self.key_array[updated_id] = new_key + + # Add updated ids to known_ids since they now have valid mappings + self.known_ids.update(updated_ids) + + # Check if any objects in known_ids have changed their labels and need updating + changed_known_ids = set() + for known_id in self.known_ids: + if known_id in old_mapping: + # Get the current label from old_mapping + current_label = old_mapping[known_id] + # Get the currently mapped value from key_array + current_mapped_value = self.key_array[known_id].item() + # Find what label this mapped value corresponds to + current_mapped_label = None + for k, v in new_mapping.items(): + if k == current_mapped_value: + current_mapped_label = v + break + + # If the labels don't match, we need to update this known_id + if current_mapped_label != current_label: + changed_known_ids.add(known_id) + + # Update the key_array for changed known_ids + for changed_id in changed_known_ids: + label = old_mapping[changed_id] + new_key = next((k for k, v in new_mapping.items() if v == label), None) + assert new_key is not None, f"Could not find a new key for label {label} in new_mapping!" + self.key_array[changed_id] = new_key + + new_keys = old_mapping.keys() - self.known_ids + + if new_keys: + self.known_ids.update(new_keys) + # Populate key_array with new keys + for key in new_keys: + label = old_mapping[key] + new_key = next((k for k, v in new_mapping.items() if v == label), None) + assert new_key is not None, f"Could not find a new key for label {label} in new_mapping!" + self.key_array[key] = new_key + if label == "unlabelled": + # Some objects in the image might be unlabelled first but later get a valid label later, so we keep track of them + self.unlabelled_ids.add(key) + + # For all the values that exist in the image but not in old_mapping.keys(), we map them to whichever key in + # new_mapping that equals to 'unlabelled'. This is needed because some values in the image don't necessarily + # show up in the old_mapping, i.e. particle systems. + for key in th.unique(image) if image_keys is None else image_keys: + if key.item() not in old_mapping.keys(): + new_key = next((k for k, v in new_mapping.items() if v == "unlabelled"), None) + assert new_key is not None, "Could not find a new key for label 'unlabelled' in new_mapping!" + self.key_array[key] = new_key + + # Apply remapping + remapped_img = self.key_array[image] + # Make sure all values are correctly remapped and not equal to the default value + assert th.all(remapped_img != th.iinfo(th.int32).max), "Not all keys in the image are in the key array!" + remapped_labels = {} + for key in th.unique(remapped_img): + remapped_labels[key.item()] = new_mapping[key.item()] + + return remapped_img, remapped_labels + + +def randomize_colors(N, bright=True): + """ + Modified from https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/visualize.py#L59 + Generate random colors. + To get visually distinct colors, generate them in HSV space then + convert to RGB. + + Args: + N (int): Number of colors to generate + + Returns: + bright (bool): whether to increase the brightness of the colors or not + """ + brightness = 1.0 if bright else 0.5 + hsv = [(1.0 * i / N, 1, brightness) for i in range(N)] + colors = th.tensor(list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))) + colors = colors[th.randperm(colors.size(0))] + colors[0] = th.tensor([0, 0, 0], dtype=th.float32) # First color is black + return colors + + +def segmentation_to_rgb(seg_im, N, colors=None): + """ + Helper function to visualize segmentations as RGB frames. + NOTE: assumes that geom IDs go up to N at most - if not, + multiple geoms might be assigned to the same color. + + Args: + seg_im ((W, H)-array): Segmentation image + N (int): Maximum segmentation ID from @seg_im + colors (None or list of 3-array): If specified, colors to apply + to different segmentation IDs. Otherwise, will be generated randomly + """ + # ensure all values lie within [0, N] + seg_im = th.fmod(seg_im, N).cpu() + + if colors is None: + use_colors = randomize_colors(N=N, bright=True) + else: + use_colors = colors + + if N <= 256: + return (255.0 * use_colors[seg_im]).to(th.uint8) + else: + return use_colors[seg_im] + + +def colorize_bboxes_3d(bbox_3d_data, rgb_image, camera_params): + """ + Project 3D bounding box data onto 2D and colorize the bounding boxes for visualization. + Reference: https://forums.developer.nvidia.com/t/mathematical-definition-of-3d-bounding-boxes-annotator-nvidia-omniverse-isaac-sim/223416 + + Args: + bbox_3d_data (th.tensor): 3D bounding box data + rgb_image (th.tensor): RGB image + camera_params (dict): Camera parameters + + Returns: + th.tensor: RGB image with 3D bounding boxes drawn + """ + + def world_to_image_pinhole(world_points, camera_params): + # Project corners to image space (assumes pinhole camera model) + proj_mat = camera_params["cameraProjection"].reshape(4, 4) + view_mat = camera_params["cameraViewTransform"].reshape(4, 4) + view_proj_mat = view_mat @ proj_mat + world_points_homo = th.nn.functional.pad(world_points, (0, 1, 0, 0), value=1.0) + tf_points = th.dot(world_points_homo, view_proj_mat) + tf_points = tf_points / (tf_points[..., -1:]) + return 0.5 * (tf_points[..., :2] + 1) + + def draw_lines_and_points_for_boxes(img, all_image_points): + width, height = img.size + draw = ImageDraw.Draw(img) + + # Define connections between the corners of the bounding box + connections = [ + (0, 1), + (1, 3), + (3, 2), + (2, 0), # Front face + (4, 5), + (5, 7), + (7, 6), + (6, 4), # Back face + (0, 4), + (1, 5), + (2, 6), + (3, 7), # Side edges connecting front and back faces + ] + + # Calculate the number of bounding boxes + num_boxes = len(all_image_points) // 8 + + # Generate random colors for each bounding box + from omni.replicator.core import random_colours + + box_colors = random_colours(num_boxes, enable_random=True, num_channels=3) + + # Ensure colors are in the correct format for drawing (255 scale) + box_colors = [(int(r), int(g), int(b)) for r, g, b in box_colors] + + # Iterate over each set of 8 points (each bounding box) + for i in range(0, len(all_image_points), 8): + image_points = all_image_points[i : i + 8] + image_points[:, 1] = height - image_points[:, 1] # Flip Y-axis to match image coordinates + + # Use a distinct color for each bounding box + line_color = box_colors[i // 8] + + # Draw lines for each connection + for start, end in connections: + draw.line( + (image_points[start][0], image_points[start][1], image_points[end][0], image_points[end][1]), + fill=line_color, + width=2, + ) + + rgb = Image.fromarray(rgb_image) + + # Get 3D corners + from omni.syntheticdata.scripts.helpers import get_bbox_3d_corners + + corners_3d = get_bbox_3d_corners(bbox_3d_data) + corners_3d = corners_3d.reshape(-1, 3) + + # Project to image space + corners_2d = world_to_image_pinhole(corners_3d, camera_params) + width, height = rgb.size + corners_2d *= th.tensor([[width, height]]) + + # Now, draw all bounding boxes + draw_lines_and_points_for_boxes(rgb, corners_2d) + + return th.tensor(rgb) + + +def change_pcd_frame(pcd: th.Tensor, rel_pose: th.Tensor) -> th.Tensor: + """ + Transform point cloud from one frame to another frame. + + Args: + pcd: (N, 6) point cloud tensor in world frame + rel_pose: (7) relative pose tensor [pos, quat] from current to target frame + Returns: + th.Tensor: (B, N, 6) point cloud tensor in target frame + """ + rel_pos = rel_pose[:3] + rel_quat = rel_pose[3:] + rel_rot = T.quat2mat(rel_quat) + + # Create transformation matrix + tf = th.eye(4) + tf[:3, :3] = rel_rot + tf[:3, 3] = rel_pos + + # Add homogeneous coordinate to point cloud + xyz = pcd[..., 3:] # (N, 3) + xyz_homo = th.cat([xyz, th.ones_like(xyz[..., :1])], dim=-1) # (N, 4) + + # Transform point cloud from camera frame to base frame + new_xyz = th.matmul(xyz_homo, th.inverse(tf).T) # (N, 4) + pcd[..., 3:] = new_xyz[..., :3] + return pcd diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/pyproject.toml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..709cc9b7ca805b904c92c859c06e9510d0a471b5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/pyproject.toml @@ -0,0 +1,38 @@ +[tool.pyright] +exclude = [ + 'omnigibson/data', + 'omnigibson/docs', + 'omnigibson/docker' +] + +[tool.pytest.ini_options] +testpaths = [ + "tests", +] + +[tool.ruff] +# Exclude a variety of commonly ignored directories. +extend-exclude = ["omnigibson/utils/pynvml_utils.py", "omnigibson/data"] + +# Same as Black. +line-length = 120 +indent-width = 4 + +# Assume Python 3.10 +target-version = "py310" + +[tool.ruff.lint] +# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. +# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or +# McCabe complexity (`C901`) by default. +select = ["E4", "E7", "E9", "F"] +ignore = [ + "E731", # lambda expressions assigned to variables. this keeps some files short. + "E722", # bare except. We don't want to dig deep to find what exception is being raised. + "E741", # ambiguous variable name for the character 'l', but we use it a lot for length. +] + +[tool.ruff.format] +# Enable auto-formatting of code examples in docstrings. Markdown, +# reStructuredText code/literal blocks and doctests are all supported. +docstring-code-format = true diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/build_docs.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/build_docs.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c6913f8ab374987e0b7054c6c6349ed586f707d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/build_docs.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# Remove source directory and copy over source files to docs folder +rm -rf docs/src +mkdir docs/src +cp -r omnigibson/* docs/src + +# Update code source references +rm -rf docs/reference +python docs/gen_ref_pages.py + +# Build the docs (written to ./site) +mkdocs build diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/aggregate_lerobot_task_shards.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/aggregate_lerobot_task_shards.py new file mode 100644 index 0000000000000000000000000000000000000000..6b375cc2657f75f0eec9027bfd915141faf675a5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/aggregate_lerobot_task_shards.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +"""Aggregate completed LeRobot v3 replay shards into one dataset per task.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import shutil +from pathlib import Path + +import pandas as pd +from lerobot.datasets.aggregate import aggregate_datasets + + +def ensure_shared_permissions(path: Path) -> None: + resolved = path.resolve() + try: + resolved.relative_to("/vision/group/behavior") + except ValueError: + return + + shutil.chown(resolved, group="behavior") + for child in resolved.rglob("*"): + shutil.chown(child, group="behavior") + mode = child.stat().st_mode + if child.is_dir(): + child.chmod(mode | 0o2770) + else: + child.chmod(mode | 0o660) + resolved.chmod(resolved.stat().st_mode | 0o2770) + + +def load_task_mapping(data_root: Path) -> dict[str, int]: + task_mapping = {} + task_misc_path = data_root / "2026-challenge-task-instances" / "metadata" / "B100_task_misc.csv" + with task_misc_path.open(newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + task_mapping[row["Task"]] = int(row["Task ID"]) + + return task_mapping + + +def parse_task_names(args: argparse.Namespace, task_mapping: dict[str, int]) -> list[str]: + if args.task_names_file: + names = [ + line.strip() + for line in Path(args.task_names_file).read_text().splitlines() + if line.strip() and not line.strip().startswith("#") + ] + elif args.tasks: + names = [name.strip() for name in args.tasks.split(",") if name.strip()] + else: + names = [name for name, _ in sorted(task_mapping.items(), key=lambda item: item[1])] + + unknown = sorted(set(names) - set(task_mapping)) + if task_mapping and unknown: + raise ValueError(f"Unknown task names: {unknown}") + if not task_mapping and not names: + raise RuntimeError("No task names provided and no challenge task metadata found") + return names + + +def shard_repo_id(task_name: str, shard_index: int) -> str: + return f"b1k_shards/{task_name}/shard-{shard_index:03d}" + + +def shard_complete(lerobot_shards_root: Path, task_name: str, shard_index: int) -> bool: + return (lerobot_shards_root / ".replay_status" / task_name / f"shard-{shard_index:03d}" / "complete").exists() + + +def episode_complete(lerobot_shards_root: Path, task_name: str, episode_root: Path) -> bool: + demo_id = episode_root.name.removeprefix("episode_") + return (lerobot_shards_root / ".replay_status" / task_name / f"shard-ep-{demo_id}" / "complete").exists() + + +def discover_inputs(args: argparse.Namespace, task_name: str) -> tuple[list[str], list[Path], list[str]]: + lerobot_shards_root = Path(args.lerobot_shards_root).resolve() + + if args.per_episode: + shard_root = lerobot_shards_root / "b1k_shards" / task_name + roots = sorted(shard_root.glob("episode_*")) + missing = [ + root.name + for root in roots + if args.require_complete and not episode_complete(lerobot_shards_root, task_name, root) + ] + repo_ids = [f"b1k_shards/{task_name}/{root.name}" for root in roots] + else: + repo_ids = [shard_repo_id(task_name, shard_index) for shard_index in range(args.num_shards)] + roots = [lerobot_shards_root / repo_id for repo_id in repo_ids] + missing = [ + str(shard_index) + for shard_index, root in enumerate(roots) + if not root.exists() + or (args.require_complete and not shard_complete(lerobot_shards_root, task_name, shard_index)) + ] + + if args.expected_episodes is not None and len(roots) != args.expected_episodes: + missing.append(f"expected {args.expected_episodes} inputs, found {len(roots)}") + + missing.extend(str(root) for root in roots if not root.exists()) + return repo_ids, roots, missing + + +def verify_aggregate(output_root: Path, expected_episodes: int | None, require_packed: bool) -> None: + info_path = output_root / "meta" / "info.json" + if not info_path.exists(): + raise FileNotFoundError(f"Missing {info_path}") + + info = json.loads(info_path.read_text()) + total_episodes = int(info.get("total_episodes", -1)) + if expected_episodes is not None and total_episodes != expected_episodes: + raise RuntimeError(f"Expected {expected_episodes} episodes, got {total_episodes}") + + episodes_path = output_root / "meta" / "episodes" / "chunk-000" / "file-000.parquet" + if not episodes_path.exists(): + raise FileNotFoundError(f"Missing {episodes_path}") + episodes = pd.read_parquet(episodes_path) + if expected_episodes is not None and len(episodes) != expected_episodes: + raise RuntimeError(f"Expected {expected_episodes} episode rows, got {len(episodes)}") + + data_files = list((output_root / "data").rglob("*.parquet")) + video_files = list((output_root / "videos").rglob("*.mp4")) + if not data_files: + raise RuntimeError("Aggregate has no data parquet files") + video_keys = sorted( + { + column.removeprefix("videos/").removesuffix("/chunk_index") + for column in episodes.columns + if column.startswith("videos/") and column.endswith("/chunk_index") + } + ) + if video_keys and not video_files: + raise RuntimeError("Aggregate has video keys but no video files") + + def format_ref(pattern: str, **values: int | str) -> str: + return pattern.format(**values) + + data_refs = set() + if "data/file_path" in episodes.columns: + data_refs = set(episodes["data/file_path"].dropna().astype(str)) + elif {"data/chunk_index", "data/file_index"}.issubset(episodes.columns): + data_pattern = info.get("data_path") or "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet" + for _, row in episodes[["data/chunk_index", "data/file_index"]].drop_duplicates().iterrows(): + data_refs.add( + format_ref( + data_pattern, + chunk_index=int(row["data/chunk_index"]), + file_index=int(row["data/file_index"]), + ) + ) + else: + raise RuntimeError("Episode metadata does not contain data file references") + + missing_refs = [ref for ref in sorted(data_refs) if not (output_root / ref).exists()] + + video_refs = set() + file_path_cols = [col for col in episodes.columns if col.startswith("videos/") and col.endswith("/file_path")] + for col in file_path_cols: + video_refs.update(episodes[col].dropna().astype(str)) + + video_pattern = info.get("video_path") or "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4" + for video_key in video_keys: + chunk_col = f"videos/{video_key}/chunk_index" + file_col = f"videos/{video_key}/file_index" + if not {chunk_col, file_col}.issubset(episodes.columns): + continue + for _, row in episodes[[chunk_col, file_col]].dropna().drop_duplicates().iterrows(): + video_refs.add( + format_ref( + video_pattern, + video_key=video_key, + chunk_index=int(row[chunk_col]), + file_index=int(row[file_col]), + ) + ) + + missing_refs.extend(ref for ref in sorted(video_refs) if not (output_root / ref).exists()) + if missing_refs: + raise RuntimeError(f"Missing {len(missing_refs)} referenced files, examples: {missing_refs[:5]}") + + if require_packed and expected_episodes is not None: + if len(data_files) >= expected_episodes: + raise RuntimeError(f"Data files are not packed: {len(data_files)} files for {expected_episodes} episodes") + if video_keys and len(video_files) >= expected_episodes * len(video_keys): + raise RuntimeError( + f"Video files are not packed: {len(video_files)} files for {expected_episodes} episodes " + f"and {len(video_keys)} video keys" + ) + + +def aggregate_task(args: argparse.Namespace, task_name: str) -> None: + output_root = Path(args.output_root).resolve() / "b1k" / task_name + repo_ids, roots, missing = discover_inputs(args, task_name) + if missing: + print(f"skip {task_name}: missing/incomplete shards {missing}") + return + + print(f"{'aggregate' if args.run else 'dry-run aggregate'} {task_name}: {len(repo_ids)} shards -> {output_root}") + if not args.run: + return + + if output_root.exists(): + if not args.overwrite: + raise FileExistsError(f"Output dataset already exists: {output_root}") + shutil.rmtree(output_root) + + aggregate_datasets( + repo_ids=repo_ids, + roots=roots, + aggr_repo_id=f"b1k/{task_name}", + aggr_root=output_root, + data_files_size_in_mb=args.data_files_size_in_mb, + video_files_size_in_mb=args.video_files_size_in_mb, + ) + if args.verify: + verify_aggregate(output_root, args.expected_episodes, args.require_packed) + ensure_shared_permissions(output_root) + + +def main() -> None: + os.umask(0o002) + default_repo_root = Path(__file__).resolve().parents[3] + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo_root", default=str(default_repo_root)) + parser.add_argument("--data_root", default=os.environ.get("OMNIGIBSON_DATA_PATH", "/vision/group/behavior")) + parser.add_argument("--lerobot_shards_root", required=True) + parser.add_argument("--output_root", required=True) + parser.add_argument("--tasks", default="", help="Comma-separated task names. Defaults to all tasks.") + parser.add_argument("--task_names_file", default="") + parser.add_argument("--num_shards", type=int, default=20) + parser.add_argument("--per_episode", action="store_true", help="Aggregate b1k_shards//episode_* roots.") + parser.add_argument("--expected_episodes", type=int, default=None) + parser.add_argument("--data_files_size_in_mb", type=int, default=None) + parser.add_argument("--video_files_size_in_mb", type=int, default=None) + parser.add_argument("--verify", action="store_true", help="Verify metadata references after aggregation.") + parser.add_argument( + "--require_packed", action="store_true", help="Fail verification if output remains one-file-per-episode." + ) + parser.add_argument("--require_complete", action="store_true", default=True) + parser.add_argument("--allow_incomplete", action="store_false", dest="require_complete") + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--run", action="store_true", help="Actually aggregate. Default is dry-run.") + args = parser.parse_args() + + task_mapping = load_task_mapping(Path(args.data_root).resolve()) + for task_name in parse_task_names(args, task_mapping): + aggregate_task(args, task_name) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/benchmark.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..905f2116cafa25b5592d402b03e296ca00365cd4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/benchmark.py @@ -0,0 +1,279 @@ +""" +B1K LeRobot benchmark for the current upstream-depth integration path. + +This is a focused counterpart to ``outputs/benchmark.py``. The original script +benchmarks many historical encoding variants laid out in the challenge-demo +``videos/task-*`` tree. This script targets the current B1K integration combo: + +- RGB: LeRobotDataset video features encoded by ``VideoEncoderConfig`` +- Depth: LeRobotDataset depth video features encoded by ``DepthEncoderConfig`` + +It uses the official ``lerobot.datasets.LeRobotDataset`` read path for random +access speed and compares decoded depth frames against the original replay HDF5 +observations for reconstruction error. +""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import h5py +import numpy as np +from lerobot.datasets import LeRobotDataset +from tqdm import tqdm + + +CAMERA_PREFIXES: dict[str, str] = { + "observation.depth_linear.left_realsense_link_camera_0": "robot_r1::robot_r1:left_realsense_link:Camera:0", + "observation.depth_linear.right_realsense_link_camera_0": "robot_r1::robot_r1:right_realsense_link:Camera:0", + "observation.depth_linear.zed_link_camera_0": "robot_r1::robot_r1:zed_link:Camera:0", +} + +STAT_KEYS = ("mean", "median", "std", "min", "max", "p01", "p05", "p25", "p75", "p95", "p99") + + +def _stats(values: np.ndarray) -> dict[str, float]: + return { + "mean": float(np.mean(values)), + "median": float(np.median(values)), + "std": float(np.std(values)), + "min": float(np.min(values)), + "max": float(np.max(values)), + "p01": float(np.percentile(values, 1)), + "p05": float(np.percentile(values, 5)), + "p25": float(np.percentile(values, 25)), + "p75": float(np.percentile(values, 75)), + "p95": float(np.percentile(values, 95)), + "p99": float(np.percentile(values, 99)), + } + + +def _as_numpy_frame(value) -> np.ndarray: + if hasattr(value, "detach"): + value = value.detach().cpu().numpy() + else: + value = np.asarray(value) + if value.ndim == 3 and value.shape[0] == 1: + value = value[0] + return value.astype(np.float32, copy=False) + + +def _depth_unit(dataset: LeRobotDataset, depth_key: str) -> str: + feature_info = dataset.meta.features[depth_key].get("info") or {} + unit = feature_info.get("video.output_unit") + if unit is None: + raise ValueError(f"Depth feature {depth_key} is missing info['video.output_unit']") + if unit not in {"m", "mm"}: + raise ValueError(f"Unsupported depth unit for {depth_key}: {unit!r}") + return unit + + +def _to_meters(depth: np.ndarray, unit: str) -> np.ndarray: + if unit == "m": + return depth + return depth / 1000.0 + + +def _resolve_hdf5_path(args: argparse.Namespace) -> Path: + if args.hdf5_path is not None: + return Path(args.hdf5_path).expanduser() + + data_root = Path(args.data_folder).expanduser() + replayed = data_root / "replayed" / f"episode_{args.demo_id:08d}.hdf5" + if replayed.exists(): + return replayed + + raw_root = data_root / "2026-challenge-rawdata" + if args.task_id is not None: + return raw_root / f"task-{args.task_id:04d}" / f"episode_{args.demo_id:08d}.hdf5" + + matches = sorted(raw_root.glob(f"task-*/episode_{args.demo_id:08d}.hdf5")) + if not matches: + raise FileNotFoundError(f"No episode_{args.demo_id:08d}.hdf5 found under {raw_root}/task-*") + if len(matches) > 1: + task_hint = args.task_name.replace("_", " ") if args.task_name else None + raise ValueError( + f"Found multiple HDF5 matches for demo_id={args.demo_id}: {matches}. " + f"Pass --task_id or --hdf5_path explicitly. task_name hint was {task_hint!r}." + ) + return matches[0] + + +def _select_hdf5_demo(f: h5py.File) -> str: + demos = list(f["data"].keys()) + return max(demos, key=lambda key: f["data"][key].attrs.get("num_samples", 0)) + + +def _valid_depth_indices(obs: h5py.Group, hdf5_keys: list[str], max_len: int) -> np.ndarray: + valid_indices = [] + for idx in range(max_len): + valid = True + for hdf5_key in hdf5_keys: + frame = np.asarray(obs[hdf5_key][idx]) + if not np.isfinite(frame).all() or float(np.abs(frame).max()) == 0.0: + valid = False + break + if valid: + valid_indices.append(idx) + + if not valid_indices: + raise ValueError("No valid nonzero HDF5 depth frames found for reconstruction benchmark.") + return np.asarray(valid_indices, dtype=np.int64) + + +def _dataset_summary(dataset: LeRobotDataset) -> None: + print("=" * 100) + print("Dataset") + print("=" * 100) + print(f"root : {dataset.root}") + print(f"frames : {dataset.num_frames}") + print(f"episodes : {dataset.num_episodes}") + print(f"video keys : {len(dataset.meta.video_keys)}") + print(f"depth keys : {dataset.meta.depth_keys}") + print(f"git hash : {dataset.meta.info.get('omnigibson_git_hash')}") + print(f"intrinsics : {sorted((dataset.meta.info.get('cam_intrinsics') or {}).keys())}") + + print("\nVideo feature metadata:") + for key in dataset.meta.video_keys: + info = dataset.meta.features[key].get("info") or {} + print( + f" {key}: codec={info.get('video.codec')} pix_fmt={info.get('video.pix_fmt')} " + f"g={info.get('video.g')} crf={info.get('video.crf')} depth={info.get('is_depth_map', False)} " + f"output_unit={info.get('video.output_unit')}" + ) + + +def benchmark_random_access_speed(dataset: LeRobotDataset, sample_count: int, seed: int) -> dict[str, float]: + print("\n" + "=" * 100) + print("Benchmark 1: LeRobotDataset Random-Access Decode Speed") + print("=" * 100) + rng = np.random.default_rng(seed) + n = min(sample_count, len(dataset)) + indices = rng.permutation(len(dataset))[:n] + + # Warm one item so any lazy decoder state is initialized outside the timed loop. + _ = dataset[int(indices[0])] + + t0 = time.perf_counter() + for idx in tqdm(indices, desc="LeRobotDataset __getitem__", leave=False): + _ = dataset[int(idx)] + elapsed = time.perf_counter() - t0 + fps = n / elapsed + print(f"samples : {n}") + print(f"elapsed_s : {elapsed:.3f}") + print(f"samples/s : {fps:.2f}") + return {"samples": float(n), "elapsed_s": elapsed, "samples_per_s": fps} + + +def benchmark_depth_reconstruction( + dataset: LeRobotDataset, + hdf5_path: Path, + sample_count: int, + seed: int, +) -> dict[str, dict[str, float]]: + print("\n" + "=" * 130) + print("Benchmark 2: Depth Reconstruction Error vs HDF5 Ground Truth") + print("=" * 130) + print(f"hdf5 : {hdf5_path}") + + rng = np.random.default_rng(seed) + results: dict[str, dict[str, float]] = {} + with h5py.File(hdf5_path, "r") as f: + demo_key = _select_hdf5_demo(f) + if "obs" not in f["data"][demo_key]: + raise KeyError( + f"{hdf5_path} has no data/{demo_key}/obs group. " + "Use a replayed observation HDF5, e.g. data_folder/replayed/episode_*.hdf5." + ) + obs = f["data"][demo_key]["obs"] + print(f"demo : {demo_key}") + + depth_to_hdf5_key = {} + for depth_key in dataset.meta.depth_keys: + prefix = CAMERA_PREFIXES.get(depth_key) + if prefix is None: + print(f"[WARN] No HDF5 camera mapping for {depth_key}; skipping") + continue + hdf5_key = f"{prefix}::depth_linear" + if hdf5_key not in obs: + print(f"[WARN] Missing HDF5 key {hdf5_key}; skipping") + continue + depth_to_hdf5_key[depth_key] = hdf5_key + + valid_indices = _valid_depth_indices(obs, list(depth_to_hdf5_key.values()), len(dataset)) + n = min(sample_count, len(valid_indices)) + indices = rng.permutation(valid_indices)[:n] + print(f"valid frames: {len(valid_indices)} / {len(dataset)}") + print(f"samples : {n}") + results["_summary"] = { + "valid_frames": float(len(valid_indices)), + "total_frames": float(len(dataset)), + "samples": float(n), + } + + header = f"{'depth_key':<58} {'samples':>8}" + for stat in STAT_KEYS: + header += f" {stat:>10}" + print(header) + print("-" * len(header)) + + for depth_key, hdf5_key in depth_to_hdf5_key.items(): + errors: list[np.ndarray] = [] + for idx in tqdm(indices, desc=depth_key, leave=False): + idx = int(idx) + item = dataset[idx] + decoded = _to_meters(_as_numpy_frame(item[depth_key]), _depth_unit(dataset, depth_key)) + gt = np.asarray(obs[hdf5_key][idx], dtype=np.float32) + errors.append(np.abs(decoded - gt).ravel()) + + err = np.concatenate(errors) + stats = _stats(err) + results[depth_key] = stats + row = f"{depth_key:<58} {n:>8}" + for stat in STAT_KEYS: + row += f" {stats[stat]:>10.6f}" + print(row) + + return results + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Benchmark current B1K LeRobot streaming decode and depth reconstruction." + ) + parser.add_argument("--root", default="/home/wsai/Documents/Files/behavior/lerobot/b1k/turning_on_radio") + parser.add_argument("--repo_id", default="b1k/turning_on_radio") + parser.add_argument("--data_folder", default="/home/wsai/Documents/Files/behavior") + parser.add_argument("--task_name", default="turning_on_radio") + parser.add_argument("--task_id", type=int, default=None) + parser.add_argument("--demo_id", type=int, default=10) + parser.add_argument("--hdf5_path", default=None) + parser.add_argument("--video_backend", default="pyav") + parser.add_argument("--speed_samples", type=int, default=256) + parser.add_argument("--error_samples", type=int, default=128) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--json", default=None, help="Optional path to write machine-readable results.") + args = parser.parse_args() + + dataset = LeRobotDataset(repo_id=args.repo_id, root=Path(args.root).expanduser(), video_backend=args.video_backend) + hdf5_path = _resolve_hdf5_path(args) + if not hdf5_path.exists(): + raise FileNotFoundError(hdf5_path) + + _dataset_summary(dataset) + speed = benchmark_random_access_speed(dataset, args.speed_samples, args.seed) + depth = benchmark_depth_reconstruction(dataset, hdf5_path, args.error_samples, args.seed) + + result = {"speed": speed, "depth_reconstruction": depth} + if args.json is not None: + out = Path(args.json).expanduser() + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(result, indent=2)) + print(f"\nWrote JSON results to {out}") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.py new file mode 100644 index 0000000000000000000000000000000000000000..654a2fe99042983830d8d55b3b8f2e0b235db81d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Download BEHAVIOR raw HDF5 demos from GCS into the challenge raw-data layout.""" + +from __future__ import annotations + +import argparse +import csv +import os +import shutil +import signal +import subprocess +import urllib.parse +import urllib.request +import uuid +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path + + +DEFAULT_BUCKET_URI = "gs://behavior-demos" +DEFAULT_TARGET_ROOT = "/vision/group/behavior/2026-challenge-rawdata" +DEFAULT_SOURCE_TEMPLATE = "{bucket_uri}/task-{task_id:04d}/episode_{episode_id}.hdf5" + + +def format_episode_id(task_id: int, instance_id: int) -> str: + if task_id >= 50: + return f"{task_id:04d}{instance_id:03d}0" + return f"{task_id:04d}{instance_id:04d}" + + +def parse_ids(value: str) -> list[int]: + ids = [] + for item in value.split(","): + item = item.strip() + if not item: + continue + ids.append(int(item)) + return ids + + +def load_instance_ids(args: argparse.Namespace) -> list[int]: + if args.instance_ids: + return parse_ids(args.instance_ids) + if args.instance_ids_file: + ids = [] + for line in Path(args.instance_ids_file).read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + ids.append(int(line.split(",")[0])) + return ids + return [args.first_instance_id + i * args.instance_stride for i in range(args.num_instances)] + + +def load_manifest_jobs(args: argparse.Namespace) -> list[tuple[int, str, str, Path]]: + jobs = [] + bucket_uri = args.bucket_uri.rstrip("/") + task_dir = Path(args.target_root) / f"task-{args.task_id:04d}" + with Path(args.gcs_manifest_csv).open(newline="") as f: + reader = csv.DictReader(f) + for row in reader: + task_id = int(row["task_id"]) + if task_id != args.task_id: + continue + instance_id = int(row["instance_id"]) + episode_id = row.get("episode_id") or format_episode_id(task_id, instance_id) + object_name = row.get("object") or row.get("source") + if object_name is None: + raise ValueError(f"Manifest row lacks object/source column: {row}") + source = object_name if object_name.startswith("gs://") else f"{bucket_uri}/{object_name}" + dest = task_dir / f"episode_{episode_id}.hdf5" + jobs.append((instance_id, episode_id, source, dest)) + return jobs + + +def resolve_tool(tool: str) -> str: + if tool in {"python", "python-gcs", "gcs-python"}: + return "python-gcs" + if tool != "auto": + return tool + for candidate in ("gcloud", "gsutil"): + path = shutil.which(candidate) + if path: + return path + return "python-gcs" + + +def parse_gs_uri(uri: str) -> tuple[str, str]: + if not uri.startswith("gs://"): + raise ValueError(f"Expected gs:// URI, got: {uri}") + bucket_and_object = uri[len("gs://") :] + bucket, _, object_name = bucket_and_object.partition("/") + if not bucket or not object_name: + raise ValueError(f"Expected gs://bucket/object URI, got: {uri}") + return bucket, object_name + + +class PythonGCSClient: + def __init__(self, credentials_path: str = "") -> None: + import google.auth + from google.auth.transport.requests import Request + + scopes = ["https://www.googleapis.com/auth/devstorage.read_only"] + if credentials_path: + from google.auth import load_credentials_from_file + + self.credentials, _ = load_credentials_from_file(credentials_path, scopes=scopes) + else: + self.credentials, _ = google.auth.default(scopes=scopes) + self.request = Request() + + def _headers(self) -> dict[str, str]: + if not self.credentials.valid: + self.credentials.refresh(self.request) + return {"Authorization": f"Bearer {self.credentials.token}"} + + def download(self, source: str, dest: Path) -> None: + bucket, object_name = parse_gs_uri(source) + encoded_object = urllib.parse.quote(object_name, safe="") + url = f"https://storage.googleapis.com/download/storage/v1/b/{bucket}/o/{encoded_object}?alt=media" + req = urllib.request.Request(url, headers=self._headers()) + with urllib.request.urlopen(req, timeout=120) as response, dest.open("wb") as f: + shutil.copyfileobj(response, f, length=1024 * 1024) + + +def build_copy_command(tool: str, source: str, dest: Path) -> list[str]: + name = Path(tool).name + if name == "gsutil": + return [tool, "-q", "cp", source, str(dest)] + return [tool, "storage", "cp", "--quiet", source, str(dest)] + + +def chmod_group_writable(path: Path) -> None: + try: + path.chmod(0o664) + except PermissionError: + pass + + +def download_one( + tool: str, + client: PythonGCSClient | None, + source: str, + dest: Path, + dry_run: bool, +) -> tuple[str, str, str]: + if dest.exists() and dest.stat().st_size > 0: + return ("exists", source, str(dest)) + + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(f".{dest.name}.part-{os.getpid()}-{uuid.uuid4().hex}") + + if dry_run: + return ("dry-run", source, str(dest)) + + if tool == "python-gcs": + try: + assert client is not None + client.download(source, tmp) + except Exception as e: + if tmp.exists(): + tmp.unlink() + return ("failed", source, f"{type(e).__name__}: {e}") + else: + cmd = build_copy_command(tool, source, tmp) + result = subprocess.run(cmd, text=True, capture_output=True) + if result.returncode != 0: + if tmp.exists(): + tmp.unlink() + message = result.stderr.strip() or result.stdout.strip() or f"exit {result.returncode}" + return ("failed", source, message) + + if not tmp.exists() or tmp.stat().st_size == 0: + if tmp.exists(): + tmp.unlink() + return ("failed", source, "download produced an empty/missing file") + + if dest.exists() and dest.stat().st_size > 0: + tmp.unlink() + return ("exists-after-download", source, str(dest)) + + tmp.replace(dest) + chmod_group_writable(dest) + return ("downloaded", source, str(dest)) + + +def write_manifest_row(path: Path | None, row: dict[str, str]) -> None: + if path is None: + return + path.parent.mkdir(parents=True, exist_ok=True) + exists = path.exists() + with path.open("a", newline="") as f: + writer = csv.DictWriter(f, fieldnames=["task_id", "instance_id", "episode_id", "status", "source", "dest"]) + if not exists: + writer.writeheader() + writer.writerow(row) + + +def main() -> None: + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--task_id", type=int, required=True) + parser.add_argument("--bucket_uri", default=DEFAULT_BUCKET_URI) + parser.add_argument("--target_root", default=DEFAULT_TARGET_ROOT) + parser.add_argument( + "--source_template", + default=DEFAULT_SOURCE_TEMPLATE, + help=( + "Python format template for source URI. Available fields: bucket_uri, " "task_id, instance_id, episode_id." + ), + ) + parser.add_argument("--instance_ids", default="", help="Comma-separated instance ids.") + parser.add_argument("--instance_ids_file", default="", help="One instance id per line, or CSV with id first.") + parser.add_argument( + "--gcs_manifest_csv", + default="", + help="CSV with task_id, instance_id, episode_id, object columns from generate_gcs_rawdata_manifest.py.", + ) + parser.add_argument("--first_instance_id", type=int, default=0) + parser.add_argument("--num_instances", type=int, default=200) + parser.add_argument("--instance_stride", type=int, default=1) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--tool", default="auto", help="auto, python-gcs, gcloud, gsutil, or full path.") + parser.add_argument( + "--credentials", + default="", + help="Path to a Google credentials JSON file for --tool python-gcs. Defaults to ADC env/config.", + ) + parser.add_argument("--manifest", default="", help="CSV status manifest path.") + parser.add_argument("--dry_run", action="store_true") + args = parser.parse_args() + + tool = "python-gcs" if args.dry_run and args.tool == "auto" else resolve_tool(args.tool) + client = None if args.dry_run or tool != "python-gcs" else PythonGCSClient(args.credentials) + manifest = Path(args.manifest) if args.manifest else None + + if args.gcs_manifest_csv: + jobs = load_manifest_jobs(args) + else: + bucket_uri = args.bucket_uri.rstrip("/") + task_dir = Path(args.target_root) / f"task-{args.task_id:04d}" + jobs = [] + for instance_id in load_instance_ids(args): + episode_id = format_episode_id(args.task_id, instance_id) + source = args.source_template.format( + bucket_uri=bucket_uri, + task_id=args.task_id, + instance_id=instance_id, + episode_id=episode_id, + ) + dest = task_dir / f"episode_{episode_id}.hdf5" + jobs.append((instance_id, episode_id, source, dest)) + + counts: dict[str, int] = {} + with ThreadPoolExecutor(max_workers=max(args.workers, 1)) as executor: + futures = { + executor.submit(download_one, tool, client, source, dest, args.dry_run): ( + instance_id, + episode_id, + source, + dest, + ) + for instance_id, episode_id, source, dest in jobs + } + for future in as_completed(futures): + instance_id, episode_id, source, dest = futures[future] + status, resolved_source, resolved_dest = future.result() + counts[status] = counts.get(status, 0) + 1 + print( + f"{status}: task={args.task_id:04d} instance={instance_id:04d} {resolved_source} -> {resolved_dest}", + flush=True, + ) + write_manifest_row( + manifest, + { + "task_id": f"{args.task_id:04d}", + "instance_id": f"{instance_id:04d}", + "episode_id": episode_id, + "status": status, + "source": source, + "dest": str(dest), + }, + ) + + failed = counts.get("failed", 0) + print(f"summary task={args.task_id:04d} " + " ".join(f"{k}={v}" for k, v in sorted(counts.items()))) + if failed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.sbatch.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.sbatch.sh new file mode 100644 index 0000000000000000000000000000000000000000..4232751d89f538703684194c824a5ead4c003076 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.sbatch.sh @@ -0,0 +1,209 @@ +#!/bin/bash +#SBATCH --job-name=download_gcs_rawdata +#SBATCH --account=vision +#SBATCH --partition=svl +#SBATCH --nodes=1 +#SBATCH --mem=16G +#SBATCH --cpus-per-task=8 +#SBATCH --time=1-00:00:00 +#SBATCH --output=/vision/u/%u/BEHAVIOR-1K/outputs/sc/download_gcs_rawdata/%x-%A_%a.out +#SBATCH --error=/vision/u/%u/BEHAVIOR-1K/outputs/sc/download_gcs_rawdata/%x-%A_%a.err + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: + sbatch --array=0-99 download_gcs_rawdata.sbatch [options] + sbatch download_gcs_rawdata.sbatch --task_id 16 [options] + +Options: + --task_id ID Overrides SLURM_ARRAY_TASK_ID. + --bucket_uri URI Default: gs://behavior-demos + --target_root PATH Default: /vision/group/behavior/2026-challenge-rawdata + --source_template TEMPLATE Default: {bucket_uri}/task-{task_id:04d}/episode_{episode_id}.hdf5 + --instance_ids IDS Comma-separated instance ids. + --instance_ids_file PATH One instance id per line, or CSV with id first. + --instance_ids_file_template PATH + Template with {task_id}, e.g. /path/task-{task_id}.txt. + --gcs_manifest_csv PATH CSV from generate_gcs_rawdata_manifest.py. + --first_instance_id ID Default: 0 + --num_instances N Default: 200 + --instance_stride N Default: 1 + --workers N Default: 4 + --tool TOOL auto, python-gcs, gcloud, gsutil, or full path. + --credentials PATH Google credentials JSON for --tool python-gcs. + --repo_root PATH BEHAVIOR-1K checkout. + --dry_run Print planned downloads only. +EOF +} + +TASK_ID="${SLURM_ARRAY_TASK_ID:-}" +BUCKET_URI="gs://behavior-demos" +TARGET_ROOT="/vision/group/behavior/2026-challenge-rawdata" +SOURCE_TEMPLATE="{bucket_uri}/task-{task_id:04d}/episode_{episode_id}.hdf5" +INSTANCE_IDS="" +INSTANCE_IDS_FILE="" +INSTANCE_IDS_FILE_TEMPLATE="" +GCS_MANIFEST_CSV="" +FIRST_INSTANCE_ID="0" +NUM_INSTANCES="200" +INSTANCE_STRIDE="1" +WORKERS="4" +TOOL="auto" +CREDENTIALS="" +REPO_ROOT="" +DRY_RUN=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --task_id) + TASK_ID="$2" + shift 2 + ;; + --bucket_uri) + BUCKET_URI="$2" + shift 2 + ;; + --target_root) + TARGET_ROOT="$2" + shift 2 + ;; + --source_template) + SOURCE_TEMPLATE="$2" + shift 2 + ;; + --instance_ids) + INSTANCE_IDS="$2" + shift 2 + ;; + --instance_ids_file) + INSTANCE_IDS_FILE="$2" + shift 2 + ;; + --instance_ids_file_template) + INSTANCE_IDS_FILE_TEMPLATE="$2" + shift 2 + ;; + --gcs_manifest_csv) + GCS_MANIFEST_CSV="$2" + shift 2 + ;; + --first_instance_id) + FIRST_INSTANCE_ID="$2" + shift 2 + ;; + --num_instances) + NUM_INSTANCES="$2" + shift 2 + ;; + --instance_stride) + INSTANCE_STRIDE="$2" + shift 2 + ;; + --workers) + WORKERS="$2" + shift 2 + ;; + --tool) + TOOL="$2" + shift 2 + ;; + --credentials) + CREDENTIALS="$2" + shift 2 + ;; + --repo_root) + REPO_ROOT="$2" + shift 2 + ;; + --dry_run) + DRY_RUN=1 + shift + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [[ -z "$TASK_ID" ]]; then + echo "Missing --task_id or SLURM_ARRAY_TASK_ID." >&2 + usage >&2 + exit 2 +fi + +if [[ -z "$REPO_ROOT" ]]; then + if [[ -d "/vision/u/${USER}/BEHAVIOR-1K" ]]; then + REPO_ROOT="/vision/u/${USER}/BEHAVIOR-1K" + else + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" + fi +fi + +TASK_ID_PADDED="$(printf '%04d' "$TASK_ID")" +if [[ -z "$INSTANCE_IDS_FILE" && -n "$INSTANCE_IDS_FILE_TEMPLATE" ]]; then + INSTANCE_IDS_FILE="${INSTANCE_IDS_FILE_TEMPLATE//\{task_id\}/$TASK_ID_PADDED}" +fi + +mkdir -p "/vision/u/${USER}/BEHAVIOR-1K/outputs/sc/download_gcs_rawdata" +mkdir -p "$TARGET_ROOT" + +echo "SLURM_JOBID=${SLURM_JOB_ID:-}" +echo "SLURM_ARRAY_TASK_ID=${SLURM_ARRAY_TASK_ID:-}" +echo "SLURM_JOB_NODELIST=${SLURM_JOB_NODELIST:-}" +echo "task_id=${TASK_ID}" +echo "bucket_uri=${BUCKET_URI}" +echo "target_root=${TARGET_ROOT}" +echo "source_template=${SOURCE_TEMPLATE}" +echo "repo_root=${REPO_ROOT}" +echo "Current time: $(date)" + +CONDA_SH="/vision/u/${USER}/miniconda3/etc/profile.d/conda.sh" +if [[ ! -f "$CONDA_SH" ]]; then + CONDA_SH="${HOME}/miniconda3/etc/profile.d/conda.sh" +fi +set +u +source "$CONDA_SH" +conda activate behavior +set -u + +cd "$REPO_ROOT" + +ARGS=( + --task_id "$TASK_ID" + --bucket_uri "$BUCKET_URI" + --target_root "$TARGET_ROOT" + --source_template "$SOURCE_TEMPLATE" + --first_instance_id "$FIRST_INSTANCE_ID" + --num_instances "$NUM_INSTANCES" + --instance_stride "$INSTANCE_STRIDE" + --workers "$WORKERS" + --tool "$TOOL" + --manifest "$TARGET_ROOT/download_manifests/task-$(printf '%04d' "$TASK_ID").csv" +) + +if [[ -n "$INSTANCE_IDS" ]]; then + ARGS+=(--instance_ids "$INSTANCE_IDS") +fi +if [[ -n "$INSTANCE_IDS_FILE" ]]; then + ARGS+=(--instance_ids_file "$INSTANCE_IDS_FILE") +fi +if [[ -n "$GCS_MANIFEST_CSV" ]]; then + ARGS+=(--gcs_manifest_csv "$GCS_MANIFEST_CSV") +fi +if [[ "$DRY_RUN" -eq 1 ]]; then + ARGS+=(--dry_run) +fi +if [[ -n "$CREDENTIALS" ]]; then + ARGS+=(--credentials "$CREDENTIALS") +fi + +python OmniGibson/scripts/learning/download_gcs_rawdata.py "${ARGS[@]}" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/generate_gcs_rawdata_manifest.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/generate_gcs_rawdata_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..b72b65b663dc64ac560acc007d7e7e49cb8ded5f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/generate_gcs_rawdata_manifest.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""List GCS raw-data objects and generate per-task instance-id files.""" + +from __future__ import annotations + +import argparse +import csv +import json +import re +import urllib.parse +import urllib.request +from pathlib import Path + + +DEFAULT_PATTERN = ( + r"(?:^|/)task-?(?P\d+)[^/]*/" r"(?:episode_(?P\d{8})|task\d+_(?P\d+))\.hdf5$" +) + + +def parse_bucket_uri(uri: str) -> tuple[str, str]: + if not uri.startswith("gs://"): + raise ValueError(f"Expected gs:// URI, got: {uri}") + bucket_and_prefix = uri[len("gs://") :] + bucket, _, prefix = bucket_and_prefix.partition("/") + return bucket, prefix + + +class PythonGCSLister: + def __init__(self, credentials_path: str = "") -> None: + import google.auth + from google.auth.transport.requests import Request + + scopes = ["https://www.googleapis.com/auth/devstorage.read_only"] + if credentials_path: + from google.auth import load_credentials_from_file + + self.credentials, _ = load_credentials_from_file(credentials_path, scopes=scopes) + else: + self.credentials, _ = google.auth.default(scopes=scopes) + self.request = Request() + + def _headers(self) -> dict[str, str]: + if not self.credentials.valid: + self.credentials.refresh(self.request) + return {"Authorization": f"Bearer {self.credentials.token}"} + + def list_objects(self, bucket: str, prefix: str) -> list[dict[str, str]]: + objects = [] + page_token = "" + while True: + query = { + "prefix": prefix, + "fields": "items(name,size),nextPageToken", + "maxResults": "1000", + } + if page_token: + query["pageToken"] = page_token + url = f"https://storage.googleapis.com/storage/v1/b/{bucket}/o?{urllib.parse.urlencode(query)}" + req = urllib.request.Request(url, headers=self._headers()) + with urllib.request.urlopen(req, timeout=120) as response: + payload = json.loads(response.read().decode("utf-8")) + objects.extend(payload.get("items", [])) + page_token = payload.get("nextPageToken", "") + if not page_token: + return objects + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bucket_uri", default="gs://behavior-demos") + parser.add_argument("--prefix", default="", help="Optional prefix inside the bucket.") + parser.add_argument("--credentials", default="", help="Google credentials JSON path. Defaults to ADC.") + parser.add_argument("--output_dir", required=True) + parser.add_argument("--manifest_csv", default="") + parser.add_argument("--pattern", default=DEFAULT_PATTERN) + args = parser.parse_args() + + bucket, uri_prefix = parse_bucket_uri(args.bucket_uri.rstrip("/")) + prefix = args.prefix or uri_prefix + if prefix and not prefix.endswith("/"): + prefix += "/" + + matcher = re.compile(args.pattern) + client = PythonGCSLister(args.credentials) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + task_to_instances: dict[str, set[str]] = {} + rows = [] + total_size = 0 + for obj in client.list_objects(bucket, prefix): + name = obj["name"] + match = matcher.search(name) + if not match: + continue + size = int(obj.get("size", 0)) + total_size += size + task_id = f"{int(match.group('task_id')):04d}" + instance_id_match = match.groupdict().get("instance_id") + if instance_id_match is None: + episode_id = match.group("episode_id") + instance_id = episode_id[4:] + else: + instance_id = f"{int(instance_id_match):03d}" + episode_id = f"{task_id}{instance_id}0" + task_to_instances.setdefault(task_id, set()).add(instance_id) + rows.append( + { + "task_id": task_id, + "instance_id": instance_id, + "episode_id": episode_id, + "object": name, + "size": str(size), + } + ) + + for task_id, instance_ids in sorted(task_to_instances.items()): + path = output_dir / f"task-{task_id}.txt" + path.write_text("\n".join(sorted(instance_ids)) + "\n") + print(f"{path}: {len(instance_ids)} instances") + + if args.manifest_csv: + manifest_path = Path(args.manifest_csv) + manifest_path.parent.mkdir(parents=True, exist_ok=True) + with manifest_path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=["task_id", "instance_id", "episode_id", "object", "size"]) + writer.writeheader() + writer.writerows(sorted(rows, key=lambda row: (row["task_id"], row["instance_id"], row["object"]))) + print(f"{manifest_path}: {len(rows)} objects") + + print(f"summary tasks={len(task_to_instances)} objects={len(rows)} bytes={total_size}") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/replay_data_sc.sbatch b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/replay_data_sc.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..ec61858a24721970c396500ad41236cc3f2753f8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/replay_data_sc.sbatch @@ -0,0 +1,251 @@ +#!/bin/bash +#SBATCH --job-name=replay_data_sc +#SBATCH --account=svl +#SBATCH --partition=svl,sc-loprio +#SBATCH --nodes=1 +#SBATCH --gres=gpu:titanrtx:1 +#SBATCH --mem=80G +#SBATCH --cpus-per-task=12 +#SBATCH --time=1-00:00:00 +#SBATCH --requeue +#SBATCH --output=/vision/u/%u/BEHAVIOR-1K/outputs/sc/replay_data/%x-%j.out +#SBATCH --error=/vision/u/%u/BEHAVIOR-1K/outputs/sc/replay_data/%x-%j.err + +set -euo pipefail +umask 0002 + +ensure_shared_permissions() { + local path + local resolved + for path in "$@"; do + [[ -e "$path" ]] || continue + resolved="$(realpath -m "$path")" + case "$resolved" in + /vision/group/behavior|/vision/group/behavior/*) + chgrp -R behavior "$resolved" || true + chmod -R g+rwX "$resolved" || true + find "$resolved" -type d -exec chmod g+s {} + || true + ;; + esac + done +} + +usage() { + cat <<'EOF' +Usage: + sbatch replay_data_sc.sbatch --data_folder PATH --task_name TASK --shard_id ID --demo_ids 00000000,00000010,00000020 + +Required: + --data_folder Root containing 2026-challenge-rawdata/ + --task_name BEHAVIOR task name (used for shard output paths / markers) + --shard_id Stable shard id, e.g. 0007 + --demo_ids Comma-separated *episode demo ids* (8-digit: task_id + instance_id + traj_id) to replay serially in this shard + +Optional: + --lerobot_root_dir LeRobot shard root. Defaults to /lerobot_shards + --lerobot_repo_id LeRobot repo id. Defaults to b1k_shards//shard- + --flush_every_n_steps Defaults to 1000 + --repo_root BEHAVIOR-1K checkout. Defaults to this script's repository root +EOF +} + +DATA_FOLDER="" +TASK_NAME="" +SHARD_ID="" +DEMO_IDS="" +LEROBOT_ROOT_DIR="" +LEROBOT_REPO_ID="" +FLUSH_EVERY_N_STEPS="1000" +REPO_ROOT="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --data_folder) + DATA_FOLDER="$2" + shift 2 + ;; + --task_name) + TASK_NAME="$2" + shift 2 + ;; + --shard_id) + SHARD_ID="$2" + shift 2 + ;; + --demo_ids) + DEMO_IDS="$2" + shift 2 + ;; + --lerobot_root_dir) + LEROBOT_ROOT_DIR="$2" + shift 2 + ;; + --lerobot_repo_id) + LEROBOT_REPO_ID="$2" + shift 2 + ;; + --flush_every_n_steps) + FLUSH_EVERY_N_STEPS="$2" + shift 2 + ;; + --repo_root) + REPO_ROOT="$2" + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [[ -z "$DATA_FOLDER" || -z "$TASK_NAME" || -z "$SHARD_ID" || -z "$DEMO_IDS" ]]; then + usage >&2 + exit 2 +fi + +if [[ -z "$REPO_ROOT" ]]; then + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +fi + +if [[ -z "$LEROBOT_ROOT_DIR" ]]; then + LEROBOT_ROOT_DIR="${DATA_FOLDER}/lerobot_shards" +fi + +if [[ -z "$LEROBOT_REPO_ID" ]]; then + LEROBOT_REPO_ID="b1k_shards/${TASK_NAME}/shard-${SHARD_ID}" +fi + +MARKER_DIR="${LEROBOT_ROOT_DIR}/.replay_status/${TASK_NAME}/shard-${SHARD_ID}" +RUNNING_MARKER="${MARKER_DIR}/running" +COMPLETE_MARKER="${MARKER_DIR}/complete" +FAILED_MARKER="${MARKER_DIR}/failed" +LEROBOT_OUTPUT_DIR="${LEROBOT_ROOT_DIR}/${LEROBOT_REPO_ID}" + +cleanup_shared_permissions() { + ensure_shared_permissions "$MARKER_DIR" "$LEROBOT_OUTPUT_DIR" +} + +mkdir -p "/vision/u/${USER}/BEHAVIOR-1K/outputs/sc/replay_data" +mkdir -p "$MARKER_DIR" +ensure_shared_permissions "$MARKER_DIR" + +echo "SLURM_JOBID=${SLURM_JOB_ID:-}" +echo "SLURM_JOB_NAME=${SLURM_JOB_NAME:-}" +echo "SLURM_JOB_NODELIST=${SLURM_JOB_NODELIST:-}" +echo "SLURM_NNODES=${SLURM_NNODES:-}" +echo "SLURMTMPDIR=${SLURMTMPDIR:-}" +echo "working directory=${SLURM_SUBMIT_DIR:-$(pwd)}" +echo "repo root=${REPO_ROOT}" +echo "task=${TASK_NAME}" +echo "shard=${SHARD_ID}" +echo "demo_ids=${DEMO_IDS}" +echo "lerobot_root_dir=${LEROBOT_ROOT_DIR}" +echo "lerobot_repo_id=${LEROBOT_REPO_ID}" +echo "Current time: $(date)" + +if [[ -f "$COMPLETE_MARKER" ]]; then + echo "Shard already complete: ${COMPLETE_MARKER}" + exit 0 +fi + +mark_failed() { + local exit_code="$?" + mkdir -p "$MARKER_DIR" + { + echo "exit_code=${exit_code}" + echo "job_id=${SLURM_JOB_ID:-}" + echo "host=$(hostname)" + echo "time=$(date --iso-8601=seconds)" + } > "$FAILED_MARKER" + rm -f "$RUNNING_MARKER" + cleanup_shared_permissions + exit "$exit_code" + } +trap cleanup_shared_permissions EXIT +trap mark_failed ERR TERM INT + +GPU_INFO="$(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits | head -n 1 || true)" +GPU_NAME="$(echo "$GPU_INFO" | cut -d',' -f1 | xargs)" +GPU_MEM_MB="$(echo "$GPU_INFO" | cut -d',' -f2 | xargs)" +GPU_NAME_LOWER="$(echo "$GPU_NAME" | tr '[:upper:]' '[:lower:]')" + +if [[ -z "$GPU_NAME" || -z "$GPU_MEM_MB" ]]; then + echo "Could not read GPU information from nvidia-smi." >&2 + exit 42 +fi + +if (( GPU_MEM_MB < 24000 )); then + echo "GPU has less than 24GB VRAM: ${GPU_NAME} (${GPU_MEM_MB} MB)." >&2 + exit 42 +fi + +if [[ ! "$GPU_NAME_LOWER" =~ (titan[[:space:]]*rtx|3090|4090|5090|a6000|a5000|a40|l40s|rtx.*6000) ]]; then + echo "GPU is not in the allowed RTX-class replay set: ${GPU_NAME}." >&2 + exit 42 +fi + +echo "Using GPU: ${GPU_NAME} (${GPU_MEM_MB} MB)" + +CONDA_SH="/vision/u/${USER}/miniconda3/etc/profile.d/conda.sh" +if [[ ! -f "$CONDA_SH" ]]; then + CONDA_SH="${HOME}/miniconda3/etc/profile.d/conda.sh" +fi +set +u +source "$CONDA_SH" +conda activate behavior +set -u + +cd "$REPO_ROOT" + +{ + echo "job_id=${SLURM_JOB_ID:-}" + echo "host=$(hostname)" + echo "time=$(date --iso-8601=seconds)" + echo "demo_ids=${DEMO_IDS}" +} > "$RUNNING_MARKER" +rm -f "$FAILED_MARKER" +ensure_shared_permissions "$MARKER_DIR" + +IFS=',' read -r -a DEMO_ID_ARRAY <<< "$DEMO_IDS" +FIRST_DEMO=1 +for DEMO_ID in "${DEMO_ID_ARRAY[@]}"; do + DEMO_ID="$(echo "$DEMO_ID" | xargs)" + if [[ -z "$DEMO_ID" ]]; then + continue + fi + + RESUME_ARGS=() + if [[ "$FIRST_DEMO" -eq 0 ]]; then + RESUME_ARGS=(--resume_lerobot) + fi + + echo "Replaying task=${TASK_NAME} demo_id=${DEMO_ID} shard=${SHARD_ID} resume=${RESUME_ARGS[*]:-false}" + OMNIGIBSON_HEADLESS=1 python OmniGibson/scripts/learning/replay_obs.py \ + --data_folder "$DATA_FOLDER" \ + --demo_id "$DEMO_ID" \ + --output_format lerobot \ + --flush_every_n_steps "$FLUSH_EVERY_N_STEPS" \ + --lerobot_root_dir "$LEROBOT_ROOT_DIR" \ + --lerobot_repo_id "$LEROBOT_REPO_ID" \ + "${RESUME_ARGS[@]}" + + FIRST_DEMO=0 +done + +{ + echo "job_id=${SLURM_JOB_ID:-}" + echo "host=$(hostname)" + echo "time=$(date --iso-8601=seconds)" + echo "demo_ids=${DEMO_IDS}" +} > "$COMPLETE_MARKER" +rm -f "$RUNNING_MARKER" "$FAILED_MARKER" +cleanup_shared_permissions + +echo "Shard finished successfully." diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/replay_obs.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/replay_obs.py new file mode 100644 index 0000000000000000000000000000000000000000..134eba86e71dec4195c37dba52805234c2781d2a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/replay_obs.py @@ -0,0 +1,260 @@ +import argparse +import csv +import omnigibson as og +import os +import yaml +from omnigibson.envs import HDF5PlaybackWrapper, LeRobotPlaybackWrapper +from omnigibson.eval.utils.dataset_utils import makedirs_with_mode +from omnigibson.eval.utils.eval_utils import PROPRIOCEPTION_INDICES +from omnigibson.macros import gm +from omnigibson.eval.utils.light_utils import LightToggleSynchronizer +from omnigibson.utils.ui_utils import create_module_logger + + +log = create_module_logger(module_name="replay_obs") +log.setLevel(20) + +gm.RENDER_VIEWER_CAMERA = False +gm.DEFAULT_VIEWER_WIDTH = 128 +gm.DEFAULT_VIEWER_HEIGHT = 128 + +LIGHT_REPLAY_TASKS = {"turning_out_all_lights_before_sleep"} + + +def _load_challenge_available_tasks() -> dict: + task_cfg_path = os.path.join(gm.DATA_PATH, "2026-challenge-task-instances", "metadata", "available_tasks.yaml") + with open(task_cfg_path, "r") as f: + return yaml.safe_load(f) + + +def _load_challenge_task_ids() -> dict[str, int]: + task_ids = {} + task_misc_path = os.path.join(gm.DATA_PATH, "2026-challenge-task-instances", "metadata", "B100_task_misc.csv") + with open(task_misc_path, newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + task_ids[row["Task"]] = int(row["Task ID"]) + return task_ids + + +def _infer_task_id_from_demo_id(demo_id: int) -> int: + return demo_id // 10000 + + +def _get_task_name_from_task_id(task_id: int) -> str: + task_names_by_id = {task_id: task_name for task_name, task_id in _load_challenge_task_ids().items()} + if task_id not in task_names_by_id: + raise KeyError(f"Task ID {task_id} inferred from demo_id was not found in challenge task metadata") + return task_names_by_id[task_id] + + +def _find_full_scene_file(task_name: str, scene_model: str) -> str: + task_scene_file_folder = os.path.join(gm.DATA_PATH, "2026-challenge-task-instances", "scenes", scene_model, "json") + if os.path.isdir(task_scene_file_folder): + for file in os.listdir(task_scene_file_folder): + if task_name in file and file.endswith(".json") and "partial_rooms" not in file: + return os.path.join(task_scene_file_folder, file) + raise FileNotFoundError(f"No full scene file found for task '{task_name}' and scene '{scene_model}'") + + +def _load_room_instances(task_name: str) -> list[str]: + task_misc_path = os.path.join(gm.DATA_PATH, "2026-challenge-task-instances", "metadata", "B100_task_misc.csv") + with open(task_misc_path, newline="", encoding="utf-8") as f: + task_misc_csv = csv.reader(f, delimiter=",", quotechar='"') + for row in task_misc_csv: + if task_name in row[1]: + return row[2].strip().split("\n") + raise FileNotFoundError(f"No task misc room instances found for task '{task_name}'") + + +def replay_hdf5_file( + data_folder: str, + task_id: int, + demo_id: int, + output_format: str, + flush_every_n_steps: int, + lerobot_repo_id: str | None = None, + lerobot_root_dir: str | None = None, + overwrite_lerobot: bool = True, + use_longest_demo: bool = False, +) -> int: + """ + Replays a single HDF5 file and saves data to the specified format. + + Args: + data_folder: data folder + task_id: ID of the task to replay + demo_id: ID of the demo to replay + output_format: Output format, "hdf5" or "lerobot" + flush_every_n_steps: Number of steps to flush the data after + use_longest_demo: If True, replay the demo with the most steps instead of the last demo group + + Returns: + episode_id: ID of the episode + """ + task_name = _get_task_name_from_task_id(task_id) + replay_dir = os.path.join(data_folder, "replayed") + makedirs_with_mode(replay_dir) + + gm.ENABLE_TRANSITION_RULES = False + + robot_sensor_config = { + "VisionSensor": { + "sensor_kwargs": { + "image_height": 480, + "image_width": 480, + }, + }, + "zed_link:Camera:0": { + "sensor_kwargs": { + "horizontal_aperture": 40.0, + "image_height": 720, + "image_width": 720, + }, + }, + } + available_tasks = _load_challenge_available_tasks() + if task_name not in available_tasks: + raise KeyError(f"Task '{task_name}' not found in available challenge task metadata") + scene_model = available_tasks[task_name][0]["scene_model"] + full_scene_file = _find_full_scene_file(task_name=task_name, scene_model=scene_model) + load_room_instances = _load_room_instances(task_name=task_name) + + input_path = f"{data_folder}/2026-challenge-rawdata/task-{task_id:04d}/episode_{demo_id:08d}.hdf5" + + common_kwargs = dict( + input_path=input_path, + full_scene_file=full_scene_file, + load_room_instances=load_room_instances, + robot_sensor_config=robot_sensor_config, + n_render_iterations=1, + flush_every_n_steps=flush_every_n_steps, + flush_every_n_traj=1, + include_robot_control=False, + robot_proprio_keys=list(PROPRIOCEPTION_INDICES["R1Pro"].keys()), + robot_obs_modalities=["proprio", "rgb", "depth_linear"], + include_contacts=False, + ) + + if output_format == "hdf5": + output_path = os.path.join(replay_dir, f"episode_{demo_id:08d}.hdf5") + kwargs = dict( + **common_kwargs, + output_path=output_path, + compression={"compression": "lzf"}, + ) + env = HDF5PlaybackWrapper.create_from_hdf5(**kwargs) + else: + output_path = f"b1k/{task_name}" + if lerobot_repo_id is not None: + output_path = lerobot_repo_id + root_dir = lerobot_root_dir or os.path.join(data_folder, "lerobot") + makedirs_with_mode(root_dir) + kwargs = dict( + **common_kwargs, + output_path=output_path, + root_dir=root_dir, + overwrite=overwrite_lerobot, + robot_type="R1Pro", + task_name=task_name, + include_task_obs=False, + ) + env = LeRobotPlaybackWrapper.create_from_hdf5(**kwargs) + + env.load_observation_space() + + demo_ids = sorted(int(key.split("_", 1)[1]) for key in env.input_hdf5["data"].keys() if key.startswith("demo_")) + if not demo_ids: + raise ValueError(f"No demo groups found in {input_path}") + + if use_longest_demo: + episode_id = max( + demo_ids, + key=lambda cur_episode_id: env.input_hdf5["data"][f"demo_{cur_episode_id}"].attrs["num_samples"], + ) + selection_reason = "most steps" + else: + episode_id = demo_ids[-1] + selection_reason = "last demo" + num_samples = env.input_hdf5["data"][f"demo_{episode_id}"].attrs["num_samples"] + log.info(f" >>> Replaying episode {episode_id} ({selection_reason}) with {num_samples} steps") + + post_state_update_callback = None + if task_name in LIGHT_REPLAY_TASKS: + light_synchronizer = LightToggleSynchronizer(env.scene) + post_state_update_callback = light_synchronizer.sync_from_current_state + + env.playback_episode( + episode_id=episode_id, + record_data=True, + post_state_update_callback=post_state_update_callback, + ) + + log.info("Playback complete. Saving data...") + env.save_data() + + log.info(f"Successfully processed episode_{demo_id:08d}") + return episode_id + + +def main(): + parser = argparse.ArgumentParser(description="Replay HDF5 files and save data") + parser.add_argument("--data_folder", type=str, required=True, help="Path to the data folder") + parser.add_argument("--demo_id", type=int, required=True, help="Demo ID to process") + parser.add_argument( + "--output_format", + type=str, + choices=["hdf5", "lerobot"], + default="hdf5", + help="Output format: hdf5, lerobot", + ) + parser.add_argument("--flush_every_n_steps", type=int, default=1000, help="Flush data every N steps") + parser.add_argument( + "--lerobot_repo_id", + type=str, + default=None, + help="LeRobot repo id / relative output path. Defaults to b1k/.", + ) + parser.add_argument( + "--lerobot_root_dir", + type=str, + default=None, + help="Root directory for LeRobot output. Defaults to /lerobot.", + ) + parser.add_argument( + "--resume_lerobot", + action="store_true", + help="Append to an existing LeRobot dataset instead of overwriting it.", + ) + parser.add_argument( + "--use_longest_demo", + "--use-longest-demo", + action="store_true", + help="Replay the demo with the most steps instead of the last demo group.", + ) + + args = parser.parse_args() + task_id = _infer_task_id_from_demo_id(args.demo_id) + + if not os.path.exists( + f"{args.data_folder}/2026-challenge-rawdata/task-{task_id:04d}/episode_{args.demo_id:08d}.hdf5" + ): + raise FileNotFoundError(f"Error: File episode_{args.demo_id:08d}.hdf5 does not exist under {args.data_folder}") + + _ = replay_hdf5_file( + data_folder=args.data_folder, + task_id=task_id, + demo_id=args.demo_id, + output_format=args.output_format, + flush_every_n_steps=args.flush_every_n_steps, + lerobot_repo_id=args.lerobot_repo_id, + lerobot_root_dir=args.lerobot_root_dir, + overwrite_lerobot=not args.resume_lerobot, + use_longest_demo=args.use_longest_demo, + ) + + log.info("All done!") + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/update_lerobot_base_qvel.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/update_lerobot_base_qvel.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb7a4e008adc6b3cf22f478777679ea3f7a5fa4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/update_lerobot_base_qvel.py @@ -0,0 +1,586 @@ +#!/usr/bin/env python3 +"""Recover robot-local base qvel from raw HDF5 demos and patch LeRobot parquets. + +This script is intended for repairing LeRobot datasets that were generated from +replay observations before holonomic ``base_qvel`` was recorded in the robot +base frame. + +It is intentionally non-destructive: + +- ``validate`` reads raw HDF5 + LeRobot parquet files and writes JSONL reports. +- ``write-staging`` writes updated data parquets and metadata under a separate + staging root. It does not copy videos. + +The recovered value is direct simulator state. For each raw HDF5 state frame, it +reads holonomic base joint velocities ``[x, y, rz]`` and rotates x/y by the base +yaw into the robot-local frame. For correspondence checks, ``action[t]`` is +compared to recovered ``base_qvel[t + 1]``. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import tempfile +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import h5py +import numpy as np +import pandas as pd +import pyarrow as pa +import pyarrow.parquet as pq + +from omnigibson.eval.utils.eval_utils import holonomic_base_qvel_to_robot_frame + + +BASE_QPOS_INDICES = np.asarray([0, 1, 5], dtype=np.int64) +QUANTILES = {"q01": 0.01, "q10": 0.10, "q50": 0.50, "q90": 0.90, "q99": 0.99} + + +@dataclass(frozen=True) +class EpisodeMeta: + episode_index: int + task_index: int + raw_episode_id: int + length: int + data_chunk_index: int + data_file_index: int + + +@dataclass +class EpisodeResult: + episode: EpisodeMeta + demo_name: str | None = None + robot_name: str | None = None + ok: bool = False + hard_fail: bool = False + warnings: list[str] | None = None + error: str | None = None + frames: int = 0 + state_frames: int = 0 + action_max_abs_diff: float | None = None + corr: list[float | None] | None = None + mae: list[float] | None = None + rmse: list[float] | None = None + action_std: list[float] | None = None + slope: list[float | None] | None = None + + def to_json(self) -> str: + rec = { + "episode_index": self.episode.episode_index, + "task_index": self.episode.task_index, + "raw_episode_id": self.episode.raw_episode_id, + "length": self.episode.length, + "data_chunk_index": self.episode.data_chunk_index, + "data_file_index": self.episode.data_file_index, + "demo_name": self.demo_name, + "robot_name": self.robot_name, + "ok": self.ok, + "hard_fail": self.hard_fail, + "warnings": self.warnings or [], + "error": self.error, + "frames": self.frames, + "state_frames": self.state_frames, + "action_max_abs_diff": self.action_max_abs_diff, + "corr": self.corr, + "mae": self.mae, + "rmse": self.rmse, + "action_std": self.action_std, + "slope": self.slope, + } + return json.dumps(rec, sort_keys=True) + + +def get_uuid(name: str) -> int: + val = int(hashlib.md5(name.encode()).hexdigest(), 16) % (10**8) + return int(np.float32(val).item()) + + +def find_robot_offsets(states: np.ndarray, uuid: np.float32, n_joints: int) -> np.ndarray: + rows, cols = np.where(states == uuid) + if len(rows) == 0: + raise ValueError(f"robot uuid not found in state frames={states.shape[0]}") + + order = np.argsort(rows, kind="stable") + rows = rows[order] + cols = cols[order] + if len(rows) == states.shape[0] and np.array_equal(rows, np.arange(states.shape[0])): + return cols + + offsets = np.empty(states.shape[0], dtype=np.int64) + out_row = 0 + i = 0 + min_width = 15 + 2 * n_joints + + while i < len(rows): + row = int(rows[i]) + if row != out_row: + raise ValueError(f"robot uuid missing at state row {out_row}") + + j = i + 1 + while j < len(rows) and rows[j] == row: + j += 1 + + valid_cols = [] + for col in cols[i:j]: + col = int(col) + if col + min_width > states.shape[1]: + continue + is_asleep = states[row, col + 1] + if is_asleep not in (0, 1): + continue + root_ori = states[row, col + 5 : col + 9] + if not np.all(np.isfinite(root_ori)): + continue + ori_norm = float(np.linalg.norm(root_ori)) + if 0.95 <= ori_norm <= 1.05: + valid_cols.append(col) + + if len(valid_cols) != 1: + raise ValueError(f"robot uuid row={row} candidates={cols[i:j].tolist()} valid={valid_cols}") + + offsets[row] = valid_cols[0] + out_row += 1 + i = j + + if out_row != states.shape[0]: + raise ValueError(f"robot uuid missing after row {out_row - 1}; state_frames={states.shape[0]}") + + return offsets + + +def natural_demo_key(name: str) -> tuple[int, str]: + match = re.fullmatch(r"demo_(\d+)", name) + return (int(match.group(1)) if match else -1, name) + + +def select_last_demo(data_group: h5py.Group) -> str: + demos = sorted((name for name in data_group.keys() if name.startswith("demo_")), key=natural_demo_key) + if not demos: + raise ValueError("raw HDF5 has no data/demo_* groups") + return demos[-1] + + +def find_robot_name(scene: dict) -> str: + init_info = scene.get("objects_info", {}).get("init_info", {}) + candidates = [ + name + for name, info in init_info.items() + if isinstance(info, dict) + and ("robot" in info.get("class_module", "") or info.get("class_name", "").lower().startswith("r1")) + ] + if not candidates: + candidates = [ + name for name in scene["state"]["registry"].get("object_registry", {}) if name.startswith("robot") + ] + if len(candidates) != 1: + raise ValueError(f"expected exactly one robot candidate, got {candidates}") + return candidates[0] + + +def list_column_to_matrix(column: pa.ChunkedArray, expected_width: int | None = None) -> np.ndarray: + arr = column.combine_chunks() + if not pa.types.is_list(arr.type) and not pa.types.is_large_list(arr.type): + raise TypeError(f"expected list column, got {arr.type}") + offsets = arr.offsets.to_numpy(zero_copy_only=False) + lengths = np.diff(offsets) + if len(lengths) == 0: + width = expected_width or 0 + else: + width = int(lengths[0]) + if not np.all(lengths == width): + raise ValueError("ragged list column is not supported") + if expected_width is not None and width != expected_width: + raise ValueError(f"expected list width {expected_width}, got {width}") + values = arr.values.to_numpy(zero_copy_only=False) + return values.reshape(len(lengths), width) + + +def replace_state_first3(table: pa.Table, first3: np.ndarray) -> pa.Table: + col_idx = table.schema.get_field_index("observation.state") + if col_idx < 0: + raise KeyError("observation.state column missing") + state_col = table.column(col_idx).combine_chunks() + offsets = state_col.offsets + offsets_np = offsets.to_numpy(zero_copy_only=False) + lengths = np.diff(offsets_np) + if len(lengths) != len(first3): + raise ValueError(f"state rows {len(lengths)} != replacement rows {len(first3)}") + if not np.all(lengths >= 3): + raise ValueError("some observation.state rows have fewer than 3 values") + + values = state_col.values.to_numpy(zero_copy_only=False).copy() + positions = offsets_np[:-1, None] + np.asarray([0, 1, 2], dtype=offsets_np.dtype)[None, :] + values[positions] = first3.astype(values.dtype, copy=False) + new_values = pa.array(values, type=state_col.type.value_type) + new_state = pa.ListArray.from_arrays(offsets, new_values) + return table.set_column(col_idx, table.schema.field(col_idx), new_state) + + +def corr_1d(x: np.ndarray, y: np.ndarray) -> float | None: + mask = np.isfinite(x) & np.isfinite(y) + if mask.sum() < 4 or np.std(x[mask]) == 0 or np.std(y[mask]) == 0: + return None + return float(np.corrcoef(x[mask], y[mask])[0, 1]) + + +def slope_1d(x: np.ndarray, y: np.ndarray) -> float | None: + mask = np.isfinite(x) & np.isfinite(y) & (np.abs(x) > 1e-6) + if mask.sum() < 10 or np.std(x[mask]) == 0: + return None + return float(np.polyfit(x[mask], y[mask], 1)[0]) + + +def validate_correspondence( + action: np.ndarray, + qvel: np.ndarray, +) -> tuple[list[float | None], list[float], list[float], list[float], list[float | None], list[str]]: + """Compare qvel[t + 1] against action[t].""" + if len(action) < 2 or len(qvel) < 2: + raise ValueError("episode too short for t+1 correspondence check") + lhs = action[:-1, :3].astype(np.float64, copy=False) + rhs = qvel[1 : len(lhs) + 1, :3].astype(np.float64, copy=False) + err = rhs - lhs + corr = [corr_1d(lhs[:, axis], rhs[:, axis]) for axis in range(3)] + mae = np.mean(np.abs(err), axis=0).tolist() + rmse = np.sqrt(np.mean(err * err, axis=0)).tolist() + action_std = np.std(lhs, axis=0).tolist() + slopes = [slope_1d(lhs[:, axis], rhs[:, axis]) for axis in range(3)] + + warnings = [] + for axis, name in enumerate(("x", "y", "yaw")): + if action_std[axis] >= 0.02: + axis_corr = corr[axis] + if axis_corr is None: + warnings.append(f"{name}: active axis has undefined correlation") + elif axis_corr < 0.80 and mae[axis] > 0.03: + warnings.append(f"{name}: low corr {axis_corr:.4f} with mae {mae[axis]:.5f}") + elif axis_corr < 0.90: + warnings.append(f"{name}: marginal corr {axis_corr:.4f}") + return corr, mae, rmse, action_std, slopes, warnings + + +def format_raw_path(raw_root: Path, pattern: str, episode: EpisodeMeta) -> Path: + return raw_root / pattern.format( + task_index=episode.task_index, + raw_episode_id=episode.raw_episode_id, + episode_index=episode.episode_index, + ) + + +def decode_raw_episode( + raw_root: Path, + raw_path_pattern: str, + episode: EpisodeMeta, +) -> tuple[str, str, np.ndarray, np.ndarray, int]: + raw_path = format_raw_path(raw_root, raw_path_pattern, episode) + if not raw_path.exists(): + raise FileNotFoundError(raw_path) + + with h5py.File(raw_path, "r") as f: + scene = json.loads(f["data"].attrs["scene_file"]) + demo_name = select_last_demo(f["data"]) + demo = f["data"][demo_name] + action = demo["action"][:] + states = demo["state"][:] + + if action.shape[0] != episode.length: + raise ValueError(f"last demo {demo_name} action length {action.shape[0]} != meta length {episode.length}") + if states.shape[0] < episode.length: + raise ValueError(f"state length {states.shape[0]} < meta length {episode.length}") + + robot_name = find_robot_name(scene) + robot_state = scene["state"]["registry"]["object_registry"][robot_name] + n_joints = len(robot_state["joint_pos"]) + uuid = np.float32(get_uuid(robot_name)) + offsets = find_robot_offsets(states, uuid, n_joints) + row_idx = np.arange(states.shape[0])[:, None] + base_qpos_cols = offsets[:, None] + 15 + BASE_QPOS_INDICES[None, :] + base_qvel_cols = offsets[:, None] + 15 + n_joints + BASE_QPOS_INDICES[None, :] + base_qpos = states[row_idx, base_qpos_cols].astype(np.float64) + base_qvel = states[row_idx, base_qvel_cols].astype(np.float64) + qvel_local = holonomic_base_qvel_to_robot_frame(base_qpos, base_qvel).astype(np.float32) + + return demo_name, robot_name, action.astype(np.float32, copy=False), qvel_local[: episode.length], states.shape[0] + + +def parse_task_ids(value: str | None) -> list[int] | None: + if not value: + return None + task_ids = [] + for part in value.split(","): + part = part.strip() + if not part: + continue + if "-" in part: + start, end = part.split("-", 1) + task_ids.extend(range(int(start), int(end) + 1)) + else: + task_ids.append(int(part)) + return sorted(set(task_ids)) + + +def load_episode_metadata(dataset_root: Path, task_ids: Iterable[int] | None = None) -> list[EpisodeMeta]: + selected = set(task_ids) if task_ids is not None else None + episodes = [] + for ep_path in sorted((dataset_root / "meta" / "episodes").glob("chunk-*/file-*.parquet")): + df = pd.read_parquet(ep_path) + if selected is not None: + df = df[df["task_index"].isin(selected)] + for _, row in df.iterrows(): + episodes.append( + EpisodeMeta( + episode_index=int(row["episode_index"]), + task_index=int(row["task_index"]), + raw_episode_id=int(row["raw_episode_id"]), + length=int(row["length"]), + data_chunk_index=int(row["data/chunk_index"]), + data_file_index=int(row["data/file_index"]), + ) + ) + episodes.sort(key=lambda ep: ep.episode_index) + return episodes + + +def data_path(root: Path, chunk_index: int, file_index: int) -> Path: + return root / "data" / f"chunk-{chunk_index:03d}" / f"file-{file_index:03d}.parquet" + + +def atomic_write_table(table: pa.Table, output_path: Path) -> None: + output_path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=output_path.parent, suffix=".tmp", delete=False) as tmp: + tmp_path = Path(tmp.name) + try: + pq.write_table(table, tmp_path, compression="zstd") + os.replace(tmp_path, output_path) + finally: + if tmp_path.exists(): + tmp_path.unlink() + + +def update_stats_json(source_stats: Path, output_stats: Path, memmap_path: Path, total_frames: int) -> None: + stats = json.loads(source_stats.read_text()) + arr = np.memmap(memmap_path, dtype=np.float32, mode="r", shape=(total_frames, 3)) + obs_stats = stats["observation.state"] + obs_stats["count"] = [int(total_frames)] + for axis in range(3): + col = np.asarray(arr[:, axis], dtype=np.float64) + obs_stats["min"][axis] = float(np.min(col)) + obs_stats["max"][axis] = float(np.max(col)) + mean = float(np.mean(col)) + obs_stats["mean"][axis] = mean + obs_stats["std"][axis] = float(np.std(col)) + for key, q in QUANTILES.items(): + obs_stats[key][axis] = float(np.quantile(col, q)) + output_stats.parent.mkdir(parents=True, exist_ok=True) + output_stats.write_text(json.dumps(stats, indent=2, sort_keys=True) + "\n") + + +def copy_metadata(dataset_root: Path, staging_root: Path) -> None: + for rel in [".gitattributes", "LICENSE", "README.md", "meta/info.json", "meta/tasks.parquet", "meta/tasks.jsonl"]: + src = dataset_root / rel + if src.exists(): + dst = staging_root / rel + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + + src_episodes = dataset_root / "meta" / "episodes" + dst_episodes = staging_root / "meta" / "episodes" + if dst_episodes.exists(): + shutil.rmtree(dst_episodes) + shutil.copytree(src_episodes, dst_episodes) + + +def summarize_results(results: list[EpisodeResult]) -> dict: + hard_failures = [r for r in results if r.hard_fail] + warnings = [r for r in results if r.warnings] + ok = [r for r in results if r.ok] + summary = { + "episodes": len(results), + "ok": len(ok), + "hard_failures": len(hard_failures), + "warnings": len(warnings), + "total_frames": int(sum(r.frames for r in results if r.ok)), + } + for axis, name in enumerate(("x", "y", "yaw")): + corr_vals = [r.corr[axis] for r in ok if r.corr and r.corr[axis] is not None] + if corr_vals: + summary[f"corr_{name}_mean"] = float(np.mean(corr_vals)) + summary[f"corr_{name}_median"] = float(np.median(corr_vals)) + summary[f"corr_{name}_min"] = float(np.min(corr_vals)) + mae_vals = [r.mae[axis] for r in ok if r.mae] + if mae_vals: + summary[f"mae_{name}_mean"] = float(np.mean(mae_vals)) + summary[f"mae_{name}_median"] = float(np.median(mae_vals)) + summary[f"mae_{name}_max"] = float(np.max(mae_vals)) + return summary + + +def run(args: argparse.Namespace) -> None: + dataset_root = Path(args.dataset_root) + raw_root = Path(args.raw_root) + output_root = Path(args.output_root) + report_dir = output_root / args.run_name + report_dir.mkdir(parents=True, exist_ok=True) + + task_ids = parse_task_ids(args.tasks) + if args.mode == "write-staging" and task_ids is not None: + raise ValueError("--tasks is only supported for validate; write-staging must process the full dataset") + + episodes = load_episode_metadata(dataset_root, task_ids=task_ids) + if not episodes: + raise RuntimeError("no episodes selected") + if args.expected_episodes is not None and len(episodes) != args.expected_episodes: + raise RuntimeError(f"expected {args.expected_episodes} episodes, found {len(episodes)}") + + by_file: dict[tuple[int, int], list[EpisodeMeta]] = {} + for ep in episodes: + by_file.setdefault((ep.data_chunk_index, ep.data_file_index), []).append(ep) + + staging_root = Path(args.staging_root) if args.staging_root else None + total_frames = sum(ep.length for ep in episodes) + memmap = None + memmap_pos = 0 + if args.mode == "write-staging": + if staging_root is None: + raise ValueError("--staging-root is required for write-staging") + staging_root.mkdir(parents=True, exist_ok=True) + memmap = np.memmap( + report_dir / "base_qvel_first3.float32.memmap", + dtype=np.float32, + mode="w+", + shape=(total_frames, 3), + ) + + results = [] + report_path = report_dir / f"{args.mode}_episodes.jsonl" + with report_path.open("w") as report: + for file_idx, ((chunk_idx, part_idx), file_episodes) in enumerate(sorted(by_file.items()), start=1): + src_data_path = data_path(dataset_root, chunk_idx, part_idx) + if not src_data_path.exists(): + raise FileNotFoundError(src_data_path) + + read_columns = ["episode_index", "frame_index", "action"] + if args.mode == "write-staging": + table = pq.read_table(src_data_path) + action_table = table.select(read_columns) + else: + table = None + action_table = pq.read_table(src_data_path, columns=read_columns) + + ep_indices = action_table["episode_index"].combine_chunks().to_numpy(zero_copy_only=False) + frame_indices = action_table["frame_index"].combine_chunks().to_numpy(zero_copy_only=False) + action_matrix = list_column_to_matrix(action_table["action"], expected_width=args.action_width) + replacements = np.empty((len(ep_indices), 3), dtype=np.float32) if args.mode == "write-staging" else None + + for ep in sorted(file_episodes, key=lambda item: item.episode_index): + result = EpisodeResult(episode=ep, warnings=[]) + try: + positions = np.flatnonzero(ep_indices == ep.episode_index) + if len(positions) != ep.length: + raise ValueError(f"parquet row count {len(positions)} != meta length {ep.length}") + if not np.array_equal(frame_indices[positions], np.arange(ep.length)): + raise ValueError("parquet frame_index is not contiguous 0..length-1") + + demo_name, robot_name, raw_action, qvel_local, state_frames = decode_raw_episode( + raw_root, + args.raw_path_pattern, + ep, + ) + result.demo_name = demo_name + result.robot_name = robot_name + result.frames = ep.length + result.state_frames = state_frames + + parquet_action = action_matrix[positions] + max_abs_diff = float(np.max(np.abs(raw_action[:, : args.action_width] - parquet_action))) + result.action_max_abs_diff = max_abs_diff + if max_abs_diff > args.action_atol: + raise ValueError(f"raw action and parquet action differ: max_abs={max_abs_diff}") + + corr, mae, rmse, action_std, slopes, warnings_ = validate_correspondence( + parquet_action[:, :3], + qvel_local, + ) + result.corr = corr + result.mae = mae + result.rmse = rmse + result.action_std = action_std + result.slope = slopes + result.warnings = warnings_ + result.ok = True + + if replacements is not None: + replacements[positions] = qvel_local[: ep.length] + assert memmap is not None + memmap[memmap_pos : memmap_pos + ep.length] = qvel_local[: ep.length] + memmap_pos += ep.length + except Exception as exc: + result.error = repr(exc) + result.hard_fail = True + results.append(result) + report.write(result.to_json() + "\n") + + if args.mode == "write-staging": + assert table is not None and replacements is not None and staging_root is not None + atomic_write_table( + replace_state_first3(table, replacements), + data_path(staging_root, chunk_idx, part_idx), + ) + + if file_idx % args.progress_every == 0 or file_idx == len(by_file): + summary = summarize_results(results) + print( + f"processed_files={file_idx}/{len(by_file)} episodes={summary['episodes']} " + f"ok={summary['ok']} hard_failures={summary['hard_failures']} warnings={summary['warnings']}", + flush=True, + ) + + summary = summarize_results(results) + (report_dir / f"{args.mode}_summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n") + + hard_failures = [r for r in results if r.hard_fail] + if hard_failures: + print(json.dumps(summary, indent=2, sort_keys=True)) + raise RuntimeError(f"{len(hard_failures)} hard failures; see {report_path}") + + if args.mode == "write-staging": + assert staging_root is not None and memmap is not None + memmap.flush() + copy_metadata(dataset_root, staging_root) + update_stats_json( + dataset_root / "meta" / "stats.json", + staging_root / "meta" / "stats.json", + report_dir / "base_qvel_first3.float32.memmap", + total_frames, + ) + + print(json.dumps(summary, indent=2, sort_keys=True)) + print(f"report_dir={report_dir}") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("mode", choices=["validate", "write-staging"]) + parser.add_argument("--dataset-root", required=True, help="LeRobot dataset root containing data/ and meta/") + parser.add_argument("--raw-root", required=True, help="Root containing raw HDF5 files") + parser.add_argument("--output-root", required=True, help="Directory for reports and temporary memmaps") + parser.add_argument("--staging-root", help="Output LeRobot staging root for write-staging mode") + parser.add_argument("--run-name", default="base_qvel_update") + parser.add_argument("--tasks", help="Comma-separated task IDs or ranges, e.g. 0-9,20") + parser.add_argument("--expected-episodes", type=int) + parser.add_argument("--raw-path-pattern", default="task-{task_index:04d}/episode_{raw_episode_id:08d}.hdf5") + parser.add_argument("--action-width", type=int, default=23) + parser.add_argument("--action-atol", type=float, default=1e-5) + parser.add_argument("--progress-every", type=int, default=1) + return parser.parse_args() + + +if __name__ == "__main__": + run(parse_args()) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/upload_to_hf.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/upload_to_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..52085dafd542d0485285a7978b79805ae9190b08 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/upload_to_hf.py @@ -0,0 +1,42 @@ +import argparse +import json +import os +from huggingface_hub import HfApi, login + +print(os.cpu_count()) + +home = os.environ.get("HOME") +with open(f"{home}/Documents/credentials/hf_credentials.json") as f: + credentials = json.load(f) +login(token=credentials["token"]) + + +parser = argparse.ArgumentParser() +parser.add_argument("--folder_path", type=str, default="/scr/behavior/2025-challenge-demos") +parser.add_argument("--task_id", type=int, required=True) +args = parser.parse_args() + +hub_api = HfApi() + + +hub_api.create_branch( + repo_id="behavior-1k/B50", + branch=f"task-{args.task_id:04d}", + repo_type="dataset", + exist_ok=True, +) + +print(f"Branch task-{args.task_id:04d} created.") + +hub_api.upload_large_folder( + repo_id="behavior-1k/2025-challenge-demos", + folder_path=args.folder_path, + repo_type="dataset", + revision=f"task-{args.task_id:04d}", + private=True, + num_workers=os.cpu_count() - 2, + allow_patterns=[f"**/task-{args.task_id:04d}/**"], + ignore_patterns=["raw/**", "meta/**"], +) + +print(f"Upload complete for task {args.task_id}!") diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/upload_to_hf.sbatch.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/upload_to_hf.sbatch.sh new file mode 100644 index 0000000000000000000000000000000000000000..15efc86416d10f8173cd29e2d05fd0201b794db0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/upload_to_hf.sbatch.sh @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name="replay_data" +#SBATCH --account=cvgl +#SBATCH --partition=svl,napoli-gpu +#SBATCH --exclude=svl4 +#SBATCH --nodes=1 +#SBATCH --gres=gpu:1 +#SBATCH --mem=480G +#SBATCH --cpus-per-task=72 +#SBATCH --time=2-00:00:00 +#SBATCH --output=outputs/sc/upload_to_hf_%j.out +#SBATCH --error=outputs/sc/upload_to_hf_%j.err + +# list out some useful information +echo "SLURM_JOBID="$SLURM_JOBID +echo "SLURM_JOB_NAME="$SLURM_JOB_NAME +echo "SLURM_JOB_NODELIST"=$SLURM_JOB_NODELIST +echo "SLURM_NNODES"=$SLURM_NNODES +echo "SLURMTMPDIR="$SLURMTMPDIR +echo "working directory = "$SLURM_SUBMIT_DIR + +source /vision/u/$(whoami)/miniconda3/bin/activate behavior + +python OmniGibson/omnigibson/learning/scripts/upload_to_hf.py $@ + +echo "Job finished." +exit 0 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/visualize_lerobot_pointcloud.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/visualize_lerobot_pointcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..d00acae85bd942b94ea36677ea028e877c6486ae --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/visualize_lerobot_pointcloud.py @@ -0,0 +1,349 @@ +"""Visualize RGB-D point clouds from a B1K LeRobot dataset. + +The script reads decoded RGB/depth frames and robot-relative camera poses via +``LeRobotDataset``, projects depth with ``obs_utils.depth_to_pcd``, then writes +or displays a colored point cloud in the robot base frame. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +import open3d as o3d +import torch as th +from lerobot.datasets import LeRobotDataset + +from omnigibson.eval.utils.eval_utils import CAMERA_INTRINSICS +from omnigibson.eval.utils.obs_utils import depth_to_pcd, color_pcd_vis + + +CAMERA_KEY_TO_INTRINSIC_NAME = { + "left_realsense_link_camera_0": "left_wrist", + "right_realsense_link_camera_0": "right_wrist", + "zed_link_camera_0": "head", +} + + +def _infer_repo_id(root: Path) -> str: + if root.parent.name: + return f"{root.parent.name}/{root.name}" + raise ValueError("Could not infer repo_id from --root. Please pass --repo_id explicitly.") + + +def _as_hwc_rgb(value) -> th.Tensor: + rgb = value.detach().cpu() if isinstance(value, th.Tensor) else th.as_tensor(value) + if rgb.ndim == 3 and rgb.shape[0] in {3, 4}: + rgb = rgb[:3].permute(1, 2, 0) + elif rgb.ndim == 3 and rgb.shape[-1] in {3, 4}: + rgb = rgb[..., :3] + else: + raise ValueError(f"Expected RGB frame with shape CxHxW or HxWxC, got {tuple(rgb.shape)}") + return rgb.float() + + +def _as_hw_depth(value, unit: str) -> th.Tensor: + depth = value.detach().cpu() if isinstance(value, th.Tensor) else th.as_tensor(value) + if depth.ndim == 3 and depth.shape[0] == 1: + depth = depth[0] + elif depth.ndim == 3 and depth.shape[-1] == 1: + depth = depth[..., 0] + elif depth.ndim != 2: + raise ValueError(f"Expected depth frame with shape 1xHxW, HxWx1, or HxW, got {tuple(depth.shape)}") + + depth = depth.float() + if unit == "mm": + depth = depth / 1000.0 + elif unit != "m": + raise ValueError(f"Unsupported depth unit {unit!r}; expected 'm' or 'mm'") + return depth + + +def _depth_unit(dataset: LeRobotDataset, key: str) -> str: + info = dataset.meta.features[key].get("info") or {} + unit = info.get("video.output_unit") + if unit is None: + raise ValueError(f"Depth feature {key} is missing info['video.output_unit']") + return unit + + +def _load_intrinsics(args: argparse.Namespace, dataset: LeRobotDataset) -> dict[str, np.ndarray]: + if args.intrinsics_json is not None: + with Path(args.intrinsics_json).expanduser().open("r") as f: + raw_intrinsics = json.load(f) + return {name: np.asarray(K, dtype=np.float32) for name, K in raw_intrinsics.items()} + + meta_intrinsics = dataset.meta.info.get("cam_intrinsics") or {} + if meta_intrinsics: + return {name: np.asarray(K, dtype=np.float32) for name, K in meta_intrinsics.items()} + + return CAMERA_INTRINSICS[args.robot_type] + + +def _camera_names(dataset: LeRobotDataset, requested: list[str] | None) -> list[str]: + names = [] + for key in dataset.meta.depth_keys: + prefix = "observation.depth_linear." + if not key.startswith(prefix): + continue + camera_name = key[len(prefix) :] + if f"observation.rgb.{camera_name}" in dataset.meta.video_keys: + names.append(camera_name) + + if requested is not None: + requested_set = set(requested) + names = [name for name in names if name in requested_set] + + if not names: + raise ValueError("No cameras with matching RGB and depth features were found.") + return names + + +def _build_camera_pcd( + item: dict, + dataset: LeRobotDataset, + camera_name: str, + K: np.ndarray, + max_depth: float, +) -> np.ndarray: + rgb_key = f"observation.rgb.{camera_name}" + depth_key = f"observation.depth_linear.{camera_name}" + pose_key = f"observation.robot2cam_pose.{camera_name}" + + rgb = _as_hwc_rgb(item[rgb_key]) + if rgb.max() > 1.0: + rgb = rgb / 255.0 + depth = _as_hw_depth(item[depth_key], unit=_depth_unit(dataset, depth_key)) + rel_pose_value = item[pose_key] + rel_pose = ( + rel_pose_value.detach().cpu().float() + if isinstance(rel_pose_value, th.Tensor) + else th.as_tensor(rel_pose_value).float() + ) + + xyz = depth_to_pcd( + depth.unsqueeze(0), + rel_pose.unsqueeze(0), + th.as_tensor(K, dtype=th.float32), + )[0] + + mask = th.isfinite(depth) & th.isfinite(xyz).all(dim=-1) & (depth > 0.0) & (depth <= max_depth) + color_xyz = th.cat([rgb, xyz], dim=-1)[mask] + return color_xyz.numpy() + + +def _filter_range(color_pcd: np.ndarray, pcd_range: list[float] | None) -> np.ndarray: + if pcd_range is None: + return color_pcd + + x_min, x_max, y_min, y_max, z_min, z_max = pcd_range + xyz = color_pcd[:, 3:6] + mask = ( + (xyz[:, 0] >= x_min) + & (xyz[:, 0] <= x_max) + & (xyz[:, 1] >= y_min) + & (xyz[:, 1] <= y_max) + & (xyz[:, 2] >= z_min) + & (xyz[:, 2] <= z_max) + ) + return color_pcd[mask] + + +def _downsample(color_pcd: np.ndarray, num_points: int | None, seed: int) -> np.ndarray: + if num_points is None or len(color_pcd) <= num_points: + return color_pcd + rng = np.random.default_rng(seed) + indices = rng.choice(len(color_pcd), size=num_points, replace=False) + return color_pcd[indices] + + +def _sample_fixed(color_pcd: np.ndarray, num_points: int, seed: int) -> np.ndarray: + if len(color_pcd) == 0: + raise ValueError("Point cloud is empty after filtering; loosen --pcd_range or --max_depth.") + + rng = np.random.default_rng(seed) + replace = len(color_pcd) < num_points + indices = rng.choice(len(color_pcd), size=num_points, replace=replace) + return color_pcd[indices] + + +def _build_frame_pcd( + item: dict, + dataset: LeRobotDataset, + camera_names: list[str], + intrinsics: dict[str, np.ndarray], + max_depth: float, + pcd_range: list[float] | None, +) -> np.ndarray: + color_pcds = [] + for camera_name in camera_names: + intrinsic_name = CAMERA_KEY_TO_INTRINSIC_NAME.get(camera_name, camera_name) + if camera_name in intrinsics: + K = intrinsics[camera_name] + elif intrinsic_name in intrinsics: + K = intrinsics[intrinsic_name] + else: + raise KeyError( + f"No intrinsics found for camera {camera_name!r}. " f"Available keys: {sorted(intrinsics.keys())}" + ) + color_pcds.append(_build_camera_pcd(item, dataset, camera_name, K, max_depth=max_depth)) + + color_pcd = np.concatenate(color_pcds, axis=0) + return _filter_range(color_pcd, pcd_range) + + +def _write_ply(color_pcd: np.ndarray, output: Path) -> None: + output.parent.mkdir(parents=True, exist_ok=True) + pcd = o3d.geometry.PointCloud() + pcd.colors = o3d.utility.Vector3dVector(color_pcd[:, :3]) + pcd.points = o3d.utility.Vector3dVector(color_pcd[:, 3:6]) + o3d.io.write_point_cloud(str(output), pcd) + + +def _iter_video_pcds( + dataset: LeRobotDataset, + start_frame: int, + first_item: dict, + camera_names: list[str], + intrinsics: dict[str, np.ndarray], + max_depth: float, + pcd_range: list[float] | None, + num_points: int, + seed: int, + stride: int, + max_frames: int | None, +): + episode_index = int(first_item["episode_index"]) + frame_idx = start_frame + frame_count = 0 + while frame_idx < len(dataset) and (max_frames is None or frame_count < max_frames): + item = first_item if frame_idx == start_frame else dataset[frame_idx] + if int(item["episode_index"]) != episode_index: + break + + color_pcd = _build_frame_pcd( + item=item, + dataset=dataset, + camera_names=camera_names, + intrinsics=intrinsics, + max_depth=max_depth, + pcd_range=pcd_range, + ) + yield _sample_fixed(color_pcd, num_points, seed=seed + frame_idx) + + frame_count += 1 + frame_idx += stride + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", + type=Path, + default=Path("~/Downloads/2026-challenge-demos/b1k/turning_on_radio"), + help="Path to one LeRobot dataset root, e.g. .../b1k/turning_on_radio.", + ) + parser.add_argument("--repo_id", default=None, help="LeRobot repo id. Defaults to '/'.") + parser.add_argument("--frame", type=int, default=0, help="Global dataset frame index to visualize.") + parser.add_argument( + "--cameras", + nargs="+", + default=None, + help="Camera names to fuse. Defaults to all RGB-D cameras in the dataset.", + ) + parser.add_argument("--robot_type", default="R1Pro", help="Robot type for default intrinsics.") + parser.add_argument( + "--intrinsics_json", + default=None, + help="Optional JSON mapping camera or intrinsic names to 3x3 matrices.", + ) + parser.add_argument("--max_depth", type=float, default=10.0, help="Drop pixels beyond this depth in meters.") + parser.add_argument( + "--pcd_range", + nargs=6, + type=float, + default=None, + metavar=("X_MIN", "X_MAX", "Y_MIN", "Y_MAX", "Z_MIN", "Z_MAX"), + help="Optional robot-frame crop box.", + ) + parser.add_argument("--num_points", type=int, default=200000, help="Randomly downsample to this many points.") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--output", type=Path, default=Path("/tmp/lerobot_pointcloud.ply")) + parser.add_argument("--visualize", action="store_true", help="Open an interactive Open3D visualizer.") + parser.add_argument( + "--visualize_video", + action="store_true", + help="Stream consecutive frames from the current episode through color_pcd_vis.", + ) + parser.add_argument( + "--max_frames", + type=int, + default=300, + help="Maximum frames for --visualize_video. Use 0 to stream until the episode ends.", + ) + parser.add_argument("--stride", type=int, default=1, help="Frame stride for --visualize_video.") + args = parser.parse_args() + + root = args.root.expanduser() + repo_id = args.repo_id or _infer_repo_id(root) + dataset = LeRobotDataset(repo_id=repo_id, root=root, video_backend="pyav") + intrinsics = _load_intrinsics(args, dataset) + camera_names = _camera_names(dataset, args.cameras) + + if args.visualize_video: + if args.num_points is None: + raise ValueError("--visualize_video requires --num_points so every frame has the same shape.") + if args.stride <= 0: + raise ValueError("--stride must be positive.") + + first_item = dataset[args.frame] + max_frames = None if args.max_frames == 0 else args.max_frames + video_pcds = list( + _iter_video_pcds( + dataset=dataset, + start_frame=args.frame, + first_item=first_item, + camera_names=camera_names, + intrinsics=intrinsics, + max_depth=args.max_depth, + pcd_range=args.pcd_range, + num_points=args.num_points, + seed=args.seed, + stride=args.stride, + max_frames=max_frames, + ) + ) + if not video_pcds: + raise ValueError("No frames were collected for video visualization.") + + color_pcd_video = np.stack(video_pcds, axis=0) + _write_ply(color_pcd_video[0], args.output.expanduser()) + print( + f"Streaming {len(color_pcd_video)} frames with {color_pcd_video.shape[1]} points each. " + f"Wrote first frame to {args.output.expanduser()}" + ) + color_pcd_vis(color_pcd_video) + return + + item = dataset[args.frame] + color_pcd = _build_frame_pcd( + item=item, + dataset=dataset, + camera_names=camera_names, + intrinsics=intrinsics, + max_depth=args.max_depth, + pcd_range=args.pcd_range, + ) + color_pcd = _downsample(color_pcd, args.num_points, args.seed) + + _write_ply(color_pcd, args.output.expanduser()) + print(f"Wrote {len(color_pcd)} points to {args.output.expanduser()}") + + if args.visualize: + color_pcd_vis(color_pcd) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.css b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.css new file mode 100644 index 0000000000000000000000000000000000000000..62cfdb442acb61dcbecced1b4f688204b68dd7e9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.css @@ -0,0 +1,71 @@ +h1 { + display: flex; + align-items: center; + justify-content: center; + padding: 10vh 0 3vh 0; + width: 100vw; +} + +h2 { + display: flex; + align-items: center; + justify-content: center; + padding: 20vh 0 0 0; +} + +h5 { + display: flex; + align-items: center; + justify-content: center; + padding: 1vh 0 9vh 0; + font-size: small; + font-weight: normal; +} + +.list-group { + display: inline-block; + position: relative; + left: 7vw; + width: 13vw; + text-align: center; +} + +.tab-content { + display: inline-block; + width: 60vw; +} + +.row { + width: 100vw; +} + +#dl-button { + color: #fff; + background-color: #3298dc; + border-color: transparent; + cursor: pointer; + text-align: center; + width: 10vw; + border-radius: 3px; +} + +button:hover { + background-color: #2793da; + flex: none; +} + +.spacer { + flex: auto; +} + +header { + margin-bottom: 8px; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.header-item { + margin-top: 2vh; +} \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.html b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.html new file mode 100644 index 0000000000000000000000000000000000000000..b2578a33f57262f84edf7932a025cb4187d1e409 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.html @@ -0,0 +1,167 @@ + + + + OmniGibson Profiling + + + + + + + + +
+ +

Baselines

+
*Ran with GPU dynamics on
+
+ +
+ +
+
+ + +

Scenes

+
* Ran with GPU dynamics off
+
+ +
+ +
+
+ + +

Non-physics Features

+
* Ran with GPU dynamics on
+
+ +
+ +
+
+
+
+
+
+
+ + + + \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.js b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.js new file mode 100644 index 0000000000000000000000000000000000000000..ac403be57321f1f47a2dd7aebb840025cd617ae0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.js @@ -0,0 +1,163 @@ +const canvasDict = { + 'baseline_total_canvas': ["FPS", ["Empty scene", "Rs_int", "Rs_int, with 1 Fetch", "Rs_int, with 3 Fetch"]], + 'baseline_loading_canvas': ["Loading time", ["Empty scene", "Rs_int", "Rs_int, with 1 Fetch", "Rs_int, with 3 Fetch"]], + 'baseline_omni_canvas': ["Omni step time", ["Empty scene", "Rs_int", "Rs_int, with 1 Fetch", "Rs_int, with 3 Fetch"]], + 'baseline_non_omni_canvas': ["Non-omni step time", ["Empty scene", "Rs_int", "Rs_int, with 1 Fetch", "Rs_int, with 3 Fetch"]], + 'baseline_mem_canvas': ["Memory usage", ["Empty scene", "Rs_int", "Rs_int, with 1 Fetch", "Rs_int, with 3 Fetch"]], + 'baseline_vram_canvas': ["Vram usage", ["Empty scene", "Rs_int", "Rs_int, with 1 Fetch", "Rs_int, with 3 Fetch"]], + 'np_total_canvas': ["FPS", ["Empty scene, with 1 Fetch, fluids", "Empty scene, with 1 Fetch, cloth", "Empty scene, with 1 Fetch, macro particles", "Empty scene, with 1 Fetch, cloth, fluids, macro particles"]], + 'np_loading_canvas': ["Loading time", ["Empty scene, with 1 Fetch, fluids", "Empty scene, with 1 Fetch, cloth", "Empty scene, with 1 Fetch, macro particles", "Empty scene, with 1 Fetch, cloth, fluids, macro particles"]], + 'np_omni_canvas': ["Omni step time", ["Empty scene, with 1 Fetch, fluids", "Empty scene, with 1 Fetch, cloth", "Empty scene, with 1 Fetch, macro particles", "Empty scene, with 1 Fetch, cloth, fluids, macro particles"]], + 'np_non_omni_canvas': ["Non-omni step time", ["Empty scene, with 1 Fetch, fluids", "Empty scene, with 1 Fetch, cloth", "Empty scene, with 1 Fetch, macro particles", "Empty scene, with 1 Fetch, cloth, fluids, macro particles"]], + 'np_mem_canvas': ["Memory usage", ["Empty scene, with 1 Fetch, fluids", "Empty scene, with 1 Fetch, cloth", "Empty scene, with 1 Fetch, macro particles", "Empty scene, with 1 Fetch, cloth, fluids, macro particles"]], + 'np_vram_canvas': ["Vram usage", ["Empty scene, with 1 Fetch, fluids", "Empty scene, with 1 Fetch, cloth", "Empty scene, with 1 Fetch, macro particles", "Empty scene, with 1 Fetch, cloth, fluids, macro particles"]], + 'scene_total_canvas': ["FPS", ["Ihlen_0_int, with 1 Fetch", "Pomaria_0_garden, with 1 Fetch", "house_single_floor, with 1 Fetch", "grocery_store_cafe, with 1 Fetch"]], + 'scene_loading_canvas': ["Loading time", ["Ihlen_0_int, with 1 Fetch", "Pomaria_0_garden, with 1 Fetch", "house_single_floor, with 1 Fetch", "grocery_store_cafe, with 1 Fetch"]], + 'scene_omni_canvas': ["Omni step time", ["Ihlen_0_int, with 1 Fetch", "Pomaria_0_garden, with 1 Fetch", "house_single_floor, with 1 Fetch", "grocery_store_cafe, with 1 Fetch"]], + 'scene_non_omni_canvas': ["Non-omni step time", ["Ihlen_0_int, with 1 Fetch", "Pomaria_0_garden, with 1 Fetch", "house_single_floor, with 1 Fetch", "grocery_store_cafe, with 1 Fetch"]], + 'scene_mem_canvas': ["Memory usage", ["Ihlen_0_int, with 1 Fetch", "Pomaria_0_garden, with 1 Fetch", "house_single_floor, with 1 Fetch", "grocery_store_cafe, with 1 Fetch"]], + 'scene_vram_canvas': ["Vram usage", ["Ihlen_0_int, with 1 Fetch", "Pomaria_0_garden, with 1 Fetch", "house_single_floor, with 1 Fetch", "grocery_store_cafe, with 1 Fetch"]], +} + + + +$('#baseline_tab a').on('click', function (e) { + e.preventDefault() + $(this).tab('show') +}) + +$('#np_tab a').on('click', function (e) { + e.preventDefault() + $(this).tab('show') +}) + +$('#scene_tab a').on('click', function (e) { + e.preventDefault() + $(this).tab('show') +}) + +function init() { + function collectBenchesPerTestCase(entries) { + const map = new Map(); + for (const entry of entries) { + const {commit, date, tool, benches} = entry; + for (const bench of benches) { + const result = { commit, date, tool, bench }; + const title_map = map.get(bench.extra[0]); + if (title_map === undefined) { + const temp_map = new Map(); + temp_map.set(bench.name, [result]); + map.set(bench.extra[0], temp_map); + } else { + const name_map = title_map.get(bench.name); + if (name_map === undefined) { + title_map.set(bench.name, [result]); + } else { + name_map.push(result); + } + } + } + } + return map; + } + + const data = window.BENCHMARK_DATA; + + // Render header + document.getElementById('last-update').textContent = new Date(data.lastUpdate).toString(); + const repoLink = document.getElementById('repository-link'); + repoLink.href = data.repoUrl; + repoLink.textContent = data.repoUrl; + + // Render footer + document.getElementById('dl-button').onclick = () => { + const a = document.createElement('a'); + a.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], {type: "application/json"})); + a.download = 'OmniGibson Profiling.json'; + a.click(); + }; + + // Prepare data points for charts + return collectBenchesPerTestCase(data.entries['Benchmark']); +} + + +function renderGraph(canvasName, fieldName, runNames) { + // get filtered data + let filteredData = new Map(Array.from(allData.get(fieldName)).filter(([key, _value]) => { + return runNames.includes(key); + })); + const canvas = document.getElementById(canvasName); + const color = ['#178600', '#00add8', '#ffa500', '#ff3838']; + const data = { + labels: Array.from(filteredData.values())[0].map(value => value.commit.id.slice(0, 7)), + datasets: Array.from(filteredData).map(([name, value], index) => { + return { + label: name, + data: value.map(d => ({ + 'x': d.commit.id.slice(0, 7), + 'y': d.bench.value + } + )), + borderColor: color[index], + backgroundColor: 'rgba(0, 0, 0, 0.01)' + }; + }) + }; + const options = { + tooltips: { + callbacks: { + afterTitle: items => { + const {datasetIndex, index} = items[0]; + const data = Array.from(filteredData.values())[datasetIndex][index]; + return '\n' + data.commit.message + '\n\n' + data.commit.timestamp + ' committed by @' + data.commit.committer.username + '\n'; + }, + label: item => { + let label = item.value; + const { range, unit } = filteredData.values().next().value[item.index].bench; + label += ' ' + unit; + if (range) { + label += ' (' + range + ')'; + } + return label; + }, + afterLabel: item => { + const { extra } = filteredData.values().next().value[item.index].bench; + return extra ? '\n' + extra[0] : ''; + } + } + }, + onClick: (_mouseEvent) => { + const points = myChart.getElementsAtEventForMode(_mouseEvent, 'nearest', { intersect: true }, true); + if (points.length === 0) { + return; + } + const url = Array.from(filteredData.values())[points[0]._datasetIndex][points[0]._index].commit.url; + window.open(url, '_blank'); + }, + title: { + display: true, + text: fieldName, + }, + layout: { + padding: 0 + }, + responsive: true, + maintainAspectRatio: true + }; + + const myChart = new Chart(canvas, { + type: 'line', + data, + options, + }); + return myChart; +} + + + +const allData = init() +for (const [canvasName, [fieldName, runNames]] of Object.entries(canvasDict)) { + renderGraph(canvasName, fieldName, runNames); +} + diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e14326726d29f80c640934fc8e088a9b61b9224 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/profiling.sh @@ -0,0 +1,20 @@ +# warm up isaac sim +python tests/benchmark/profiling.py -s Rs_int -g +rm output.json +# 1st batch: baselines +python tests/benchmark/profiling.py -g # baseline +python tests/benchmark/profiling.py -g -s Rs_int # for vision research +python tests/benchmark/profiling.py -g -s Rs_int -r 1 # for robotics research +python tests/benchmark/profiling.py -g -s Rs_int -r 3 # for multi-agent research + +# 2nd batch: compare different scenes +python tests/benchmark/profiling.py -r 1 -s Ihlen_0_int +python tests/benchmark/profiling.py -r 1 -s Pomaria_0_garden +python tests/benchmark/profiling.py -r 1 -s house_single_floor +python tests/benchmark/profiling.py -r 1 -s grocery_store_cafe + +# 3rd batch: OG non-physics features +python tests/benchmark/profiling.py -g -r 1 -w # fluids (water) +python tests/benchmark/profiling.py -g -r 1 -c # soft body (cloth) +python tests/benchmark/profiling.py -g -r 1 -p # macro particle system (diced objects) +python tests/benchmark/profiling.py -g -r 1 -w -c -p # everything \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/autogenerate_task_custom_list_template.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/autogenerate_task_custom_list_template.py new file mode 100644 index 0000000000000000000000000000000000000000..36e95ea976a1a24bae77674c266918f8fbb09805 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/autogenerate_task_custom_list_template.py @@ -0,0 +1,522 @@ +import json +import argparse +import csv +import glob +import os +import textwrap +from collections import defaultdict +import numpy as np +from omnigibson.utils.bddl_utils import get_knowledge_base, GOOD_MODELS, BAD_CLOTH_MODELS +from omnigibson.utils.asset_utils import get_all_object_category_models, get_scene_path +from constants import DATASET_2026_PATH, TASK_CUSTOM_LIST_PATH +from floor_plan_visualization import get_floor_plan_data + + +SYNSET_BASE_URL = "https://behavior.stanford.edu/knowledgebase/synsets" +TASK_MISC_HEADER = ["Task ID", "Task", "Rooms to include"] + +parser = argparse.ArgumentParser() +parser.add_argument("-t", "--activity", type=str, required=True) +parser.add_argument("--no-room-gui", action="store_true", help="Skip the floor-plan room picker GUI.") +parser.add_argument("--floor", type=int, default=0, help="Floor index to show in the room picker.") + + +def get_existing_models_for_task(activity_name): + """Return {synset: {category: [model_id, ...]}} for a task found in the dataset.""" + pattern = os.path.join(DATASET_2026_PATH, "scenes", "*", "json", f"*_task_{activity_name}_0_0_template.json") + results = {} + for template_path in glob.glob(pattern): + try: + with open(template_path) as f: + d = json.load(f) + inst_to_name = d["metadata"]["task"]["inst_to_name"] + objs_info = d["objects_info"]["init_info"] + for bddl_inst, obj_name in inst_to_name.items(): + if "agent" in bddl_inst or obj_name not in objs_info: + continue + args = objs_info[obj_name]["args"] + synset = "_".join(bddl_inst.split("_")[:-1]) + category = args["category"] + model = args["model"] + results.setdefault(synset, {}).setdefault(category, set()).add(model) + except Exception: + pass + return results + + +def prompt_choice(prompt, options, multi=False): + print(f"\n{prompt}") + for i, opt in enumerate(options): + print(f" [{i}] {opt}") + while True: + raw = input("Enter index or name" + (" (comma-separated for multiple)" if multi else "") + ": ").strip() + chosen = [] + for part in raw.split(","): + part = part.strip() + if part.isdigit() and int(part) < len(options): + chosen.append(options[int(part)]) + elif part in options: + chosen.append(part) + else: + print(f" Invalid choice: {part!r}") + chosen = [] + break + if chosen: + return chosen if multi else chosen[0] + + +def _iter_predicates(conds): + if isinstance(conds, str): + return + assert isinstance(conds, list) + if not conds: + return + if any(isinstance(ele, list) for ele in conds): + for ele in conds: + yield from _iter_predicates(ele) + else: + yield conds + + +def _synset_from_bddl_name(name, kb): + for i in range(len(name.split("_")), 0, -1): + candidate = "_".join(name.split("_")[:i]) + if kb.get_synset(candidate) is not None: + return candidate + return None + + +def _get_leaf_categories(synset_obj): + leaf_synsets = [synset_obj] if synset_obj.is_leaf else [d for d in synset_obj.descendants if d.is_leaf] + return sorted({cat.name for s in leaf_synsets for cat in s.categories}) + + +def _load_scene_object_locations(scene, category_to_synsets): + stable_path = os.path.join(DATASET_2026_PATH, "scenes", scene, "json", f"{scene}_stable.json") + if not os.path.exists(stable_path): + return {} + + with open(stable_path, "r") as f: + scene_dict = json.load(f) + + locations = defaultdict(lambda: defaultdict(int)) + for obj_info in scene_dict.get("objects_info", {}).get("init_info", {}).values(): + args = obj_info.get("args", {}) + category = args.get("category") + if category not in category_to_synsets: + continue + in_rooms = args.get("in_rooms") or [] + in_rooms = [in_rooms] if isinstance(in_rooms, str) else in_rooms + for room in in_rooms: + for synset in category_to_synsets[category]: + locations[room][synset] += 1 + return {room: dict(counts) for room, counts in locations.items()} + + +def _write_task_misc_rooms(activity_name, room_instances): + if not room_instances: + raise ValueError("At least one room must be selected before writing B100_task_misc.csv.") + + task_misc_path = os.path.join(DATASET_2026_PATH, "metadata", "B100_task_misc.csv") + rows = [] + if os.path.exists(task_misc_path): + with open(task_misc_path, newline="", encoding="utf-8") as f: + rows = list(csv.reader(f, delimiter=",", quotechar='"')) + + if not rows: + rows = [TASK_MISC_HEADER] + + room_cell = "\n".join(room_instances) + max_task_id = -1 + updated = False + for row in rows[1:]: + if len(row) >= 1 and row[0].isdigit(): + max_task_id = max(max_task_id, int(row[0])) + if len(row) >= 2 and row[1] == activity_name: + row[:] = [row[0], activity_name, room_cell] + updated = True + + if not updated: + rows.append([str(max_task_id + 1), activity_name, room_cell]) + + with open(task_misc_path, "w", newline="", encoding="utf-8") as f: + writer = csv.writer(f, delimiter=",", quotechar='"') + writer.writerows(rows) + print(f"Wrote selected rooms for '{activity_name}' to {task_misc_path}") + + +def _room_type_from_instance(room_instance): + return "_".join(room_instance.split("_")[:-1]) + + +def _get_room_reasons(room, bddl_room_types, object_locations): + reasons = [] + if _room_type_from_instance(room) in bddl_room_types: + reasons.append("Task requires this room type") + if room in object_locations: + for synset, count in sorted(object_locations[room].items()): + suffix = f" x{count}" if count > 1 else "" + reasons.append(f"{synset}{suffix}") + return reasons + + +def _format_room_label(room, bddl_room_types, object_locations): + lines = [room] + for reason in _get_room_reasons(room, bddl_room_types, object_locations): + wrapped = textwrap.wrap(reason, width=28) or [reason] + lines.append(f" - {wrapped[0]}") + lines.extend(f" {line}" for line in wrapped[1:]) + return "\n".join(lines) + + +def _format_predicate(predicate): + return f"{predicate[0]}({', '.join(str(arg) for arg in predicate[1:])})" + + +def _format_column_items(items, width=24, max_lines=7): + if not items: + return "none" + + lines = [] + consumed_items = 0 + for item in items: + wrapped = textwrap.wrap(str(item), width=width) or [str(item)] + next_lines = [wrapped[0], *[f" {line}" for line in wrapped[1:]]] + if len(lines) + len(next_lines) > max_lines: + break + lines.extend(next_lines) + consumed_items += 1 + + remaining = len(items) - consumed_items + if remaining > 0: + lines = lines[: max_lines - 1] + lines.append(f"... (+{remaining} more)") + + return "\n".join(lines) + + +def _add_metadata_panel(fig, required_rooms, required_objects, goal_conditions): + info_ax = fig.add_axes([0.03, 0.83, 0.66, 0.11]) + info_ax.set_axis_off() + + columns = [ + ("Required rooms", sorted(required_rooms), 16, 0.00), + ("Required objects", sorted(required_objects), 22, 0.18), + ("Goal conditions", goal_conditions, 52, 0.45), + ] + for title, items, width, x in columns: + info_ax.text(x, 0.98, title, va="top", fontsize=10, fontweight="bold", transform=info_ax.transAxes) + info_ax.text( + x, + 0.74, + _format_column_items(items, width=width), + va="top", + fontsize=8, + transform=info_ax.transAxes, + ) + + +def _select_room_instances_with_gui( + scene, + bddl_room_types, + object_locations, + floor=0, + activity_name=None, + required_objects=None, + goal_conditions=None, +): + scene_dir = get_scene_path(scene) + plan = get_floor_plan_data(scene_dir, floor=floor) + room_names = sorted(plan["ins_id_to_name"].values()) + name_to_ins_id = {name: ins_id for ins_id, name in plan["ins_id_to_name"].items()} + bddl_rooms = {room for room in room_names if _room_type_from_instance(room) in bddl_room_types} + default_rooms = bddl_rooms + + try: + import matplotlib.pyplot as plt + from matplotlib.widgets import Button, CheckButtons + except Exception as e: + print(f"\nCould not open room picker GUI ({e}); using default rooms: {sorted(default_rooms)}") + return sorted(default_rooms) + + if plt.get_backend().lower() == "agg": + print(f"\nMatplotlib is using a non-interactive backend; using default rooms: {sorted(default_rooms)}") + return sorted(default_rooms) + + selected = set(default_rooms) + ins = plan["ins"] + + def make_overlay(): + overlay_data = np.zeros((*ins.shape, 4), dtype=np.float32) + for room in selected: + ins_id = name_to_ins_id.get(room) + if ins_id is None: + continue + overlay_data[ins == ins_id] = [1.0, 0.95, 0.0, 0.42] + return overlay_data + + fig = plt.figure(figsize=(16, 10)) + fig.suptitle(activity_name or scene, fontsize=14, fontweight="bold", y=0.99) + _add_metadata_panel( + fig=fig, + required_rooms=bddl_room_types, + required_objects=required_objects or [], + goal_conditions=goal_conditions or [], + ) + + ax = fig.add_axes([0.03, 0.21, 0.66, 0.57]) + ax.imshow(plan["canvas"], interpolation="nearest") + overlay = ax.imshow(make_overlay(), interpolation="nearest") + + for ins_id, name in plan["ins_id_to_name"].items(): + ys, xs = (ins == ins_id).nonzero() + if len(xs) == 0: + continue + cx, cy = float(xs.mean()), float(ys.mean()) + ax.text( + cx, + cy, + name, + ha="center", + va="center", + fontsize=8, + color="black", + bbox=dict(boxstyle="round,pad=0.15", facecolor="white", edgecolor="black", alpha=0.82, linewidth=0.5), + ) + if name in bddl_rooms: + ax.scatter( + [cx], + [cy - 22], + marker="*", + s=260, + c="#d62728", + edgecolors="white", + linewidths=1.2, + zorder=5, + ) + ax.set_title(f"{scene}: select rooms to load for task sampling") + ax.set_axis_off() + + selected_ax = fig.add_axes([0.03, 0.05, 0.66, 0.12]) + selected_ax.set_axis_off() + + def format_selected_rooms(): + selected_rooms = sorted(selected) + if not selected_rooms: + return "Selected rooms: none" + wrapped = textwrap.wrap(", ".join(selected_rooms), width=95) + return "Selected rooms:\n" + "\n".join(wrapped) + + selected_text = selected_ax.text( + 0, + 0.95, + format_selected_rooms(), + va="top", + fontsize=11, + wrap=True, + ) + + room_labels = [] + label_to_room = {} + for room in room_names: + label = _format_room_label(room, bddl_room_types, object_locations) + room_labels.append(label) + label_to_room[label] = room + + check_height = min(0.76, max(0.16, 0.085 * len(room_names))) + check_ax = fig.add_axes([0.71, 0.88 - check_height, 0.28, check_height]) + checks = CheckButtons(check_ax, room_labels, [room in selected for room in room_names]) + check_ax.set_title("Rooms") + for label in checks.labels: + label.set_fontsize(10) + + note_ax = fig.add_axes([0.71, 0.89, 0.28, 0.09]) + note_ax.set_axis_off() + note_ax.text( + 0, + 0.5, + "Yellow rooms are selected. Defaults come from task-required room types. Red stars mark those task-required room types.", + va="center", + wrap=True, + fontsize=10, + ) + + button_ax = fig.add_axes([0.80, 0.05, 0.12, 0.06]) + done_button = Button(button_ax, "Done") + + def refresh(): + overlay.set_data(make_overlay()) + selected_text.set_text(format_selected_rooms()) + fig.canvas.draw_idle() + + def toggle_room(room): + if room in selected: + selected.remove(room) + else: + selected.add(room) + refresh() + + def on_check(label): + toggle_room(label_to_room[label]) + + def on_click(event): + if event.inaxes != ax or event.xdata is None or event.ydata is None: + return + y = int(round(event.ydata)) + x = int(round(event.xdata)) + if not (0 <= y < ins.shape[0] and 0 <= x < ins.shape[1]): + return + room = plan["ins_id_to_name"].get(int(ins[y, x])) + if room not in room_names: + return + checks.set_active(room_names.index(room)) + + checks.on_clicked(on_check) + fig.canvas.mpl_connect("button_press_event", on_click) + done_button.on_clicked(lambda _: plt.close(fig)) + plt.show() + + if not selected: + if default_rooms: + print(f"\nNo rooms selected; using default rooms: {', '.join(sorted(default_rooms))}") + return sorted(default_rooms) + raise ValueError("At least one room must be selected.") + + return sorted(selected) + + +def autogenerate_task_custom_list(activity_name, use_room_gui=True, floor=0): + assert os.path.exists(DATASET_2026_PATH), f"2026 dataset not found: {DATASET_2026_PATH}" + assert os.path.exists(TASK_CUSTOM_LIST_PATH), f"task_custom_lists.json not found: {TASK_CUSTOM_LIST_PATH}" + + kb = get_knowledge_base() + task = kb.get_task(f"{activity_name}-0") + conditions = task.parse_base_scope()[0] + init_conds = conditions.parsed_initial_conditions + goal_conds = conditions.parsed_goal_conditions + synsets = set() + room_types = set() + task_synsets = set() + for cond in _iter_predicates(init_conds): + if len(cond) == 3 and cond[0] == "inroom": + room_types.add(cond[2]) + for arg in cond[1:]: + synset = _synset_from_bddl_name(arg, kb) + if synset is None or "agent" in synset: + continue + task_synsets.add(synset) + synset_obj = kb.get_synset(synset) + if synset_obj is not None and "sceneObject" in synset_obj.abilities: + continue + synsets.add(synset) + + for cond in _iter_predicates(goal_conds): + for arg in cond[1:]: + synset = _synset_from_bddl_name(arg, kb) + if synset is not None and "agent" not in synset: + task_synsets.add(synset) + + # Prompt for scene — only offer scenes that match the task per the knowledge base + matched_scene_names = sorted(s.name for s in task.matched_scenes) + print(f"\nSelect scene for activity '{activity_name}' ({len(matched_scene_names)} matching):") + for i, s in enumerate(matched_scene_names): + print(f" [{i}] {s}") + while True: + raw = input("Enter index, name, or custom string: ").strip() + if raw.isdigit() and int(raw) < len(matched_scene_names): + scene = matched_scene_names[int(raw)] + break + elif raw: + scene = raw + break + + scene_object_category_to_synsets = defaultdict(set) + for synset in sorted(task_synsets): + synset_obj = kb.get_synset(synset) + if synset_obj is None or "sceneObject" not in synset_obj.abilities: + continue + for category in _get_leaf_categories(synset_obj): + scene_object_category_to_synsets[category].add(synset) + object_locations = _load_scene_object_locations(scene, scene_object_category_to_synsets) + room_instances = None + if use_room_gui: + try: + room_instances = _select_room_instances_with_gui( + scene=scene, + bddl_room_types=room_types, + object_locations=object_locations, + floor=floor, + activity_name=activity_name, + required_objects=sorted(synsets), + goal_conditions=[_format_predicate(cond) for cond in _iter_predicates(goal_conds)], + ) + except Exception as e: + print(f"\nCould not open room picker GUI ({e}); using BDDL room types: {', '.join(sorted(room_types))}") + if room_instances is not None: + room_types = {_room_type_from_instance(room) for room in room_instances} + selected_rooms_msg = ", ".join(room_instances) if room_instances else "none" + print(f"\nSelected room instances: {selected_rooms_msg}") + print(f"Saved room types for compatibility: {', '.join(sorted(room_types))}") + + # Prompt for models per synset/category + existing_models = get_existing_models_for_task(activity_name) + whitelist = {} + for synset in sorted(synsets): + synset_obj = get_knowledge_base().get_synset(synset) + if synset_obj is None: + continue + whitelist[synset] = {} + # Non-leaf synsets have no direct categories; walk to leaf descendants + leaf_synsets = [synset_obj] if synset_obj.is_leaf else [d for d in synset_obj.descendants if d.is_leaf] + all_cats = [cat for s in leaf_synsets for cat in s.categories] + for cat in all_cats: + cat_name = cat.name + available_models = set(get_all_object_category_models(cat_name)) + available_models = ( + available_models + if cat_name not in GOOD_MODELS + else available_models.intersection(GOOD_MODELS[cat_name]) + ) + available_models = sorted(available_models - BAD_CLOTH_MODELS.get(cat_name, set())) + if not available_models: + print(f"\n No models found for category '{cat_name}', skipping.") + continue + used_models = sorted(existing_models.get(synset, {}).get(cat_name, [])) + hint = ( + f" (used in existing templates: {', '.join(used_models)})" + if used_models + else " (not found in existing templates)" + ) + models = prompt_choice( + f"Select model(s) for {synset} / {cat_name} ({SYNSET_BASE_URL}/{synset}.html):\n{hint}", + available_models, + multi=True, + ) + whitelist[synset][cat_name] = {m: None for m in models} + + task_entry = { + activity_name: { + "room_types": sorted(room_types), + scene: { + "whitelist": whitelist, + "blacklist": {}, + }, + } + } + # Load, update, and write back + with open(TASK_CUSTOM_LIST_PATH, "r") as f: + existing = json.load(f) + + existing.update(task_entry) + + with open(TASK_CUSTOM_LIST_PATH, "w") as f: + json.dump(existing, f, indent=4) + + print(f"\nWrote entry for '{activity_name}' to {TASK_CUSTOM_LIST_PATH}") + if room_instances is not None: + _write_task_misc_rooms(activity_name, room_instances) + + +if __name__ == "__main__": + args = parser.parse_args() + autogenerate_task_custom_list(args.activity, use_room_gui=not args.no_room_gui, floor=args.floor) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/challenge_instance_qc_gui.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/challenge_instance_qc_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..c63b241cf818066e0a96b2e8dfbfcf14572086fc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/challenge_instance_qc_gui.py @@ -0,0 +1,1291 @@ +"""Validate 2026 challenge task instances and show sampled poses on floor plans.""" + +import argparse +import base64 +import csv +import json +import math +import re +import webbrowser +from collections import Counter, defaultdict +from dataclasses import dataclass, field +from pathlib import Path + +import cv2 +import numpy as np +import yaml + +from constants import DATASET_2026_PATH +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.utils import transform_utils_np as T + + +SCRIPT_DESCRIPTION = "Validate 2026 challenge task instances and show sampled poses on floor plans." +REPO_ROOT = Path(__file__).resolve().parents[3] +DEFAULT_DATASET_DIR = Path(DATASET_2026_PATH) +DEFAULT_ASSET_DATASET_DIR = Path(get_dataset_path("behavior-1k-assets")) +DEFAULT_ASSET_SCENES_DIR = DEFAULT_ASSET_DATASET_DIR / "scenes" +ROOM_CATEGORIES_PATH = DEFAULT_ASSET_DATASET_DIR / "metadata" / "room_categories.txt" +TEMPLATE_DIR = Path(__file__).resolve().parent / "templates" + +METADATA_FILENAMES = {"B100_task_misc.csv", "available_tasks.yaml", "task_custom_lists.json"} +INSTANCE_SUFFIX = "_template-tro_state.json" +MAP_RESOLUTION = 0.01 +UNKNOWN_TASK_ID_SORT_KEY = 10_000 +QUATERNION_NORM_TOLERANCE = 1e-3 +POSE_KEYS_TO_SKIP = {"robot_poses"} +STATIC_OBJECT_PREFIXES = ("floor.", "wall.", "ceiling.") +DEFAULT_PALETTE = [ + "#1577d8", + "#f59e0b", + "#1f7a4d", + "#8b5cf6", + "#ef4444", + "#14b8a6", + "#64748b", + "#e11d48", + "#0ea5e9", + "#84cc16", + "#f97316", + "#7c3aed", + "#06b6d4", + "#be123c", + "#475569", + "#b45309", +] + +# Data models + + +@dataclass +class CheckLine: + text: str + ok: bool + detail: str = "" + + +@dataclass +class TaskPaths: + task_name: str + scene: str | None = None + instance_dir: Path | None = None + prefix: str | None = None + template_path: Path | None = None + partial_rooms_path: Path | None = None + stable_path: Path | None = None + + +@dataclass +class PoseStats: + count: int = 0 + std_x: float = 0.0 + std_y: float = 0.0 + std_xy: float = 0.0 + + +@dataclass +class TaskReport: + task_name: str + task_id: int | None = None + scene: str | None = None + rooms: list[str] = field(default_factory=list) + checks: list[CheckLine] = field(default_factory=list) + robot_stats: PoseStats = field(default_factory=PoseStats) + object_stats: dict[str, PoseStats] = field(default_factory=dict) + robot_points: list[dict] = field(default_factory=list) + object_points: dict[str, list[dict]] = field(default_factory=dict) + missing_instance_ids: list[int] = field(default_factory=list) + extra_instance_files: list[str] = field(default_factory=list) + invalid_json_files: list[str] = field(default_factory=list) + map_payload: dict | None = None + + @property + def ok(self): + return all(check.ok for check in self.checks) + + +# Loading helpers + + +def yes_no(value): + return "Yes" if value else "No" + + +def read_json(path): + with path.open("r") as f: + return json.load(f) + + +def load_json_file(path, duplicate_keys=None): + if duplicate_keys is None: + return read_json(path) + + def hook(pairs): + seen = set() + data = {} + for key, value in pairs: + if key in seen: + duplicate_keys.append(key) + seen.add(key) + data[key] = value + return data + + with path.open("r") as f: + return json.load(f, object_pairs_hook=hook) + + +def load_yaml(path): + with path.open("r") as f: + return yaml.safe_load(f) or {} + + +def load_or_report(load_fn, path, default, errors): + if not path.exists(): + errors.append(f"{path.parent.name}/{path.name}: missing") + return default + try: + return load_fn(path) + except Exception as exc: + errors.append(f"{path.parent.name}/{path.name}: {exc}") + return default + + +def require_mapping(value, label, errors): + if isinstance(value, dict): + return value + errors.append(f"{label}: root should be an object") + return {} + + +def find_top_level_yaml_duplicates(path): + keys = [] + pattern = re.compile(r"^([A-Za-z0-9_][^:#]*):\s*$") + for line in path.read_text().splitlines(): + if not line or line[0].isspace() or line.lstrip().startswith("#"): + continue + match = pattern.match(line) + if match: + keys.append(match.group(1).strip()) + counts = Counter(keys) + return sorted(key for key, count in counts.items() if count > 1) + + +def load_b100_rows(path): + rows = [] + duplicate_tasks = [] + seen = set() + with path.open(newline="") as f: + for row in csv.DictReader(f): + task_name = (row.get("Task") or "").strip() + if not task_name: + continue + if task_name in seen: + duplicate_tasks.append(task_name) + seen.add(task_name) + raw_rooms = row.get("Rooms to include") or row.get("Rooms to inlcude") or "" + rooms = [room.strip() for room in raw_rooms.splitlines() if room.strip()] + try: + task_id = int(row.get("Task ID", "")) + except (TypeError, ValueError): + task_id = None + rows.append({"task_id": task_id, "task_name": task_name, "rooms": rooms}) + return rows, sorted(duplicate_tasks) + + +def discover_task_paths(dataset_dir): + task_paths = {} + extra_instance_dirs = [] + for instance_dir in sorted((dataset_dir / "scenes").glob("*/json/*_instances")): + scene = instance_dir.parents[1].name + expected_start = f"{scene}_task_" + if not instance_dir.name.startswith(expected_start): + extra_instance_dirs.append(instance_dir) + continue + task_name = instance_dir.name.removeprefix(expected_start).removesuffix("_instances") + prefix = f"{scene}_task_{task_name}" + task_paths[task_name] = TaskPaths( + task_name=task_name, + scene=scene, + instance_dir=instance_dir, + prefix=prefix, + template_path=instance_dir.parent / f"{prefix}_0_0_template.json", + partial_rooms_path=instance_dir.parent / f"{prefix}_0_0_template-partial_rooms.json", + stable_path=instance_dir.parent / f"{scene}_stable.json", + ) + return task_paths, extra_instance_dirs + + +def task_order_from_b100(task_names, b100_rows): + id_by_task = {row["task_name"]: row["task_id"] for row in b100_rows} + return sorted( + task_names, + key=lambda name: ( + id_by_task.get(name) is None, + id_by_task.get(name, UNKNOWN_TASK_ID_SORT_KEY), + name, + ), + ) + + +def choose_tasks(available_tasks, b100_rows): + return task_order_from_b100(available_tasks.keys(), b100_rows) + + +def parse_instance_id(path, prefix): + match = re.match(rf"^{re.escape(prefix)}_0_(\d+)_template-tro_state\.json$", path.name) + return int(match.group(1)) if match else None + + +# Pose helpers + + +def instance_state_path(paths, instance_id): + return paths.instance_dir / f"{paths.prefix}_0_{instance_id}_template-tro_state.json" + + +def template_task_metadata(data): + if not isinstance(data, dict): + raise ValueError("template JSON root should be an object") + metadata = data.get("metadata") + if not isinstance(metadata, dict): + raise ValueError("metadata should be an object") + task_metadata = metadata.get("task") + if not isinstance(task_metadata, dict): + raise ValueError("metadata.task should be an object") + return task_metadata + + +def safe_template_task_metadata(data): + try: + return template_task_metadata(data) + except ValueError: + return {} + + +def is_number_sequence(value, min_length): + return ( + isinstance(value, list) + and len(value) >= min_length + and all( + isinstance(component, (int, float)) and not isinstance(component, bool) and math.isfinite(component) + for component in value[:min_length] + ) + ) + + +def is_valid_position(value, min_length=2): + return is_number_sequence(value, min_length) + + +def is_valid_unit_quaternion(value): + if not is_number_sequence(value, 4): + return False + norm = math.sqrt(sum(component * component for component in value[:4])) + return abs(norm - 1.0) <= QUATERNION_NORM_TOLERANCE + + +def require_dict_field(data, key, context): + value = data.get(key) if isinstance(data, dict) else None + if not isinstance(value, dict): + raise ValueError(f"{context}.{key} should be an object") + return value + + +def check_robot_pose_dict(value): + if not isinstance(value, dict) or not value: + return False + for poses in value.values(): + if not isinstance(poses, list) or not poses: + return False + for pose in poses: + if not isinstance(pose, dict): + return False + position = pose.get("position") + orientation = pose.get("orientation") + if not is_valid_position(position): + return False + if not is_valid_unit_quaternion(orientation): + return False + return True + + +def nested_template_robot_poses(data): + return safe_template_task_metadata(data).get("robot_poses") + + +def first_position_from_robot_poses(robot_poses): + if not isinstance(robot_poses, dict): + return None + for poses in robot_poses.values(): + if not isinstance(poses, list) or not poses: + continue + position = poses[0].get("position") if isinstance(poses[0], dict) else None + if is_valid_position(position): + return position + return None + + +def first_robot_position(data): + robot_poses = data.get("robot_poses") if isinstance(data, dict) else None + return first_position_from_robot_poses(robot_poses) + + +def first_template_robot_position(data): + return first_position_from_robot_poses(nested_template_robot_poses(data)) + + +def object_root_position(value): + if not isinstance(value, dict): + return None + root_link = value.get("root_link") + if not isinstance(root_link, dict): + return None + position = root_link.get("pos") + return position if is_valid_position(position) else None + + +def object_root_pose(value): + if not isinstance(value, dict): + return None + root_link = value.get("root_link") + if not isinstance(root_link, dict): + return None + position = root_link.get("pos") + orientation = root_link.get("ori") + if not is_valid_position(position, min_length=3): + return None + if not is_valid_unit_quaternion(orientation): + return None + return position, orientation + + +def transform_local_position(position, parent_state): + pose = object_root_pose(parent_state) + if pose is None or not is_valid_position(position, min_length=3): + return position + parent_position, parent_orientation = pose + world, _ = T.pose_transform( + np.asarray(parent_position[:3], dtype=np.float32), + np.asarray(parent_orientation[:4], dtype=np.float32), + np.asarray(position[:3], dtype=np.float32), + np.asarray([0, 0, 0, 1], dtype=np.float32), + ) + return world.tolist() + + +def template_scene_to_bddl_names(data): + task_metadata = safe_template_task_metadata(data) + inst_to_name = task_metadata.get("inst_to_name") if isinstance(task_metadata, dict) else None + if not isinstance(inst_to_name, dict): + return {} + return {scene_name: bddl_name for bddl_name, scene_name in inst_to_name.items()} + + +def attached_object_state(group_name, object_states, scene_to_bddl_name): + if not isinstance(object_states, dict): + return None + return object_states.get(group_name) or object_states.get(scene_to_bddl_name.get(group_name)) + + +def particle_positions(value): + if not isinstance(value, dict): + return [] + positions = value.get("positions") + if not isinstance(positions, list): + return [] + return [position for position in positions if is_valid_position(position)] + + +def particle_world_positions(value, object_states, scene_to_bddl_name=None): + positions = particle_positions(value) + if not positions: + return [] + + groups = value.get("groups") if isinstance(value, dict) else None + if not isinstance(groups, dict) or not groups: + return positions + + if scene_to_bddl_name is None: + scene_to_bddl_name = {} + transformed = {} + single_group = len(groups) == 1 + for group_name, group_info in groups.items(): + if not isinstance(group_info, dict): + continue + indices = group_info.get("particle_indices") + if not isinstance(indices, list): + indices = list(range(len(positions))) if single_group else [] + parent_state = attached_object_state(group_name, object_states, scene_to_bddl_name) + for index in indices: + if isinstance(index, int) and 0 <= index < len(positions): + transformed[index] = transform_local_position(positions[index], parent_state) + + return [transformed.get(index, position) for index, position in enumerate(positions)] + + +def should_collect_object_pose(object_name): + return object_name not in POSE_KEYS_TO_SKIP and not object_name.startswith(STATIC_OBJECT_PREFIXES) + + +def object_world_positions(object_name, object_data, state_data, scene_to_bddl_name): + if not should_collect_object_pose(object_name): + return [] + position = object_root_position(object_data) + if position is not None: + return [position] + return particle_world_positions(object_data, state_data, scene_to_bddl_name) + + +def template_object_positions(data): + task_metadata = safe_template_task_metadata(data) + inst_to_name = task_metadata.get("inst_to_name") if isinstance(task_metadata, dict) else None + if not isinstance(inst_to_name, dict): + return {} + state = require_dict_field(data, "state", "template") + registry = require_dict_field(state, "registry", "template.state") + object_registry = require_dict_field(registry, "object_registry", "template.state.registry") + system_registry = require_dict_field(registry, "system_registry", "template.state.registry") + + positions_by_name = defaultdict(list) + for bddl_name, scene_name in inst_to_name.items(): + if "agent" in bddl_name or not should_collect_object_pose(bddl_name): + continue + object_data = object_registry.get(scene_name) + position = object_root_position(object_data) + if position is not None: + positions_by_name[bddl_name].append(position) + continue + for particle_position in particle_world_positions(system_registry.get(scene_name), object_registry): + positions_by_name[bddl_name].append(particle_position) + return dict(positions_by_name) + + +def compute_pose_stats(points): + if len(points) < 2: + return PoseStats(count=len(points)) + arr = np.asarray(points, dtype=np.float64) + std_x = float(np.std(arr[:, 0])) + std_y = float(np.std(arr[:, 1])) + return PoseStats(count=len(points), std_x=std_x, std_y=std_y, std_xy=float(math.hypot(std_x, std_y))) + + +def short_object_label(name): + synset = name.rsplit("_", 1)[0] + suffix = name.rsplit("_", 1)[1] if "_" in name else "" + base = synset.split(".")[0].replace("__", " ").replace("_", " ") + return f"{base} {suffix}".strip() + + +def load_room_categories(): + return [line.strip() for line in ROOM_CATEGORIES_PATH.read_text().splitlines() if line.strip()] + + +# Floor plan helpers + + +@dataclass +class FloorPlan: + image_uri: str + width: int + height: int + rooms: list[dict] + existing_room_names: set[str] + transform: dict + + +def parse_room_maps(scene, floor=0): + layout_dir = DEFAULT_ASSET_SCENES_DIR / scene / "layout" + ins_path = layout_dir / f"floor_insseg_{floor}.png" + sem_path = layout_dir / f"floor_semseg_{floor}.png" + trav_path = layout_dir / f"floor_trav_{floor}.png" + ins = cv2.imread(str(ins_path), cv2.IMREAD_GRAYSCALE) + sem = cv2.imread(str(sem_path), cv2.IMREAD_GRAYSCALE) + trav = cv2.imread(str(trav_path), cv2.IMREAD_GRAYSCALE) + if ins is None or sem is None or trav is None: + missing = [str(path) for path, img in [(ins_path, ins), (sem_path, sem), (trav_path, trav)] if img is None] + raise FileNotFoundError("Missing floor map files: " + ", ".join(missing)) + if ins.shape != sem.shape or ins.shape != trav.shape: + raise ValueError(f"Floor map shapes do not match for {scene}") + if ins.shape[0] != ins.shape[1]: + raise ValueError(f"Floor maps must be square for {scene}, got shape {ins.shape} for floor {floor}") + + room_cats = load_room_categories() + sem_id_to_ins_ids = defaultdict(list) + for ins_id in sorted(int(value) for value in np.unique(ins) if value != 0): + ys, xs = np.where(ins == ins_id) + sem_id = int(sem[ys[0], xs[0]]) + sem_id_to_ins_ids[sem_id].append(ins_id) + + ins_id_to_name = {} + for sem_id, ins_ids in sem_id_to_ins_ids.items(): + sem_name = room_cats[sem_id - 1] + for index, ins_id in enumerate(sorted(ins_ids)): + ins_id_to_name[ins_id] = f"{sem_name}_{index}" + + return ins, trav, ins_id_to_name + + +def transform_map_point(raw_row, raw_col, transform): + row = (raw_row - transform["crop_y0"]) * transform["scale_y"] + col = (raw_col - transform["crop_x0"]) * transform["scale_x"] + row = transform["scaled_h"] - 1 - row + if transform["rotated"]: + x = row + y = transform["scaled_w"] - 1 - col + else: + x = col + y = row + return float(x), float(y) + + +def world_to_display_point(position, transform): + raw_size = transform["raw_size"] + raw_row = position[1] / MAP_RESOLUTION + raw_size / 2.0 + raw_col = position[0] / MAP_RESOLUTION + raw_size / 2.0 + x, y = transform_map_point(raw_row, raw_col, transform) + visible = 0 <= x < transform["display_w"] and 0 <= y < transform["display_h"] + return {"x": x, "y": y, "visible": visible} + + +def make_floor_plan(scene, chosen_rooms, floor=0, target_size=1200, crop_margin_px=80): + ins, trav, ins_id_to_name = parse_room_maps(scene, floor=floor) + ys, xs = np.where(ins > 0) + if len(xs): + y0 = max(int(ys.min()) - crop_margin_px, 0) + y1 = min(int(ys.max()) + crop_margin_px + 1, ins.shape[0]) + x0 = max(int(xs.min()) - crop_margin_px, 0) + x1 = min(int(xs.max()) + crop_margin_px + 1, ins.shape[1]) + else: + y0, y1, x0, x1 = 0, ins.shape[0], 0, ins.shape[1] + + ins_crop = ins[y0:y1, x0:x1] + trav_crop = trav[y0:y1, x0:x1] + crop_h, crop_w = ins_crop.shape[:2] + scale = min(1.0, target_size / max(crop_h, crop_w)) + scaled_w = max(1, int(round(crop_w * scale))) + scaled_h = max(1, int(round(crop_h * scale))) + scale_x = scaled_w / crop_w + scale_y = scaled_h / crop_h + ins_scaled = cv2.resize(ins_crop, (scaled_w, scaled_h), interpolation=cv2.INTER_NEAREST) + trav_scaled = cv2.resize(trav_crop, (scaled_w, scaled_h), interpolation=cv2.INTER_NEAREST) + ins_display = ins_scaled[::-1, :] + trav_display = trav_scaled[::-1, :] + rotated = ins_display.shape[0] > ins_display.shape[1] + if rotated: + ins_display = np.rot90(ins_display, k=1) + trav_display = np.rot90(trav_display, k=1) + + chosen_rooms = set(chosen_rooms) + canvas = np.full((*ins_display.shape, 3), 244, dtype=np.uint8) + for ins_id, room_name in ins_id_to_name.items(): + room_mask = ins_display == ins_id + if room_name in chosen_rooms: + canvas[room_mask] = np.array([255, 218, 121], dtype=np.uint8) + else: + canvas[room_mask] = np.array([221, 228, 226], dtype=np.uint8) + + obstacle_mask = (trav_display == 0) & (ins_display > 0) + canvas[obstacle_mask] = (canvas[obstacle_mask] * 0.45).astype(np.uint8) + canvas[(trav_display == 0) & (ins_display == 0)] = np.array([38, 38, 38], dtype=np.uint8) + + success, encoded = cv2.imencode(".png", cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR)) + if not success: + raise RuntimeError(f"Could not encode floor plan PNG for {scene}") + image_uri = "data:image/png;base64," + base64.b64encode(encoded.tobytes()).decode("ascii") + + transform = { + "raw_size": ins.shape[0], + "crop_x0": x0, + "crop_y0": y0, + "scale_x": scale_x, + "scale_y": scale_y, + "scaled_w": scaled_w, + "scaled_h": scaled_h, + "rotated": rotated, + "display_w": int(ins_display.shape[1]), + "display_h": int(ins_display.shape[0]), + } + + rooms = [] + for ins_id, name in ins_id_to_name.items(): + room_ys, room_xs = np.where(ins == ins_id) + if len(room_xs) == 0: + continue + raw_row = float(np.mean(room_ys)) + raw_col = float(np.mean(room_xs)) + x, y = transform_map_point(raw_row, raw_col, transform) + rooms.append( + { + "name": name, + "x": x, + "y": y, + "chosen": name in chosen_rooms, + } + ) + + return FloorPlan( + image_uri=image_uri, + width=int(ins_display.shape[1]), + height=int(ins_display.shape[0]), + rooms=rooms, + existing_room_names=set(ins_id_to_name.values()), + transform=transform, + ) + + +# Report checks + + +def validate_templates(paths): + issues = [] + for path, label in [(paths.template_path, "template"), (paths.partial_rooms_path, "partial rooms")]: + if path is None or not path.exists(): + issues.append(f"missing {label}") + continue + try: + data = read_json(path) + except Exception as exc: + issues.append(f"{label} JSON does not open: {exc}") + continue + try: + task_metadata = template_task_metadata(data) + except ValueError as exc: + issues.append(f"{label} metadata is invalid: {exc}") + continue + if not check_robot_pose_dict(task_metadata.get("robot_poses")): + issues.append(f"{label} robot pose is missing or invalid") + return issues + + +def analyze_task(paths, task_id, rooms, args): + report = TaskReport(task_name=paths.task_name, task_id=task_id, scene=paths.scene, rooms=rooms) + if paths.instance_dir is None or not paths.instance_dir.exists(): + report.checks.append(CheckLine("Task folder exists", False, "missing instance folder")) + return report + + report.checks.append(CheckLine("Task folder exists", True)) + template_issues = validate_templates(paths) + report.checks.append( + CheckLine("Template and partial rooms are there", not template_issues, "; ".join(template_issues)) + ) + report.checks.append( + CheckLine("Scene stable file is there", paths.stable_path is not None and paths.stable_path.exists()) + ) + + instance_pattern = f"*{INSTANCE_SUFFIX}" + actual_files = sorted(paths.instance_dir.glob(instance_pattern)) + expected_ids = set(range(1, args.expected_instances + 1)) + actual_ids = {} + report.extra_instance_files = [] + for path in actual_files: + instance_id = parse_instance_id(path, paths.prefix) + if instance_id in expected_ids: + actual_ids[instance_id] = path + else: + report.extra_instance_files.append(str(path.relative_to(args.dataset_dir))) + report.missing_instance_ids = sorted(expected_ids - set(actual_ids)) + report.checks.append( + CheckLine( + f"Task has {args.expected_instances} instances", + not report.missing_instance_ids and not report.extra_instance_files, + format_instance_detail(report.missing_instance_ids, report.extra_instance_files), + ) + ) + + robot_positions = [] + object_positions = defaultdict(list) + invalid_robot_pose_ids = [] + valid_json_count = 0 + try: + template_data = ( + read_json(paths.template_path) if paths.template_path is not None and paths.template_path.exists() else {} + ) + except Exception: + template_data = {} + scene_to_bddl_name = template_scene_to_bddl_names(template_data) + for instance_id in range(1, args.expected_instances + 1): + path = instance_state_path(paths, instance_id) + if not path.exists(): + invalid_robot_pose_ids.append(instance_id) + continue + try: + data = read_json(path) + valid_json_count += 1 + except Exception as exc: + invalid_robot_pose_ids.append(instance_id) + report.invalid_json_files.append(f"{path.relative_to(args.dataset_dir)}: {exc}") + continue + + if not isinstance(data, dict): + invalid_robot_pose_ids.append(instance_id) + report.invalid_json_files.append( + f"{path.relative_to(args.dataset_dir)}: root should be an object, got {type(data).__name__}" + ) + continue + + robot_poses = data.get("robot_poses") + if not check_robot_pose_dict(robot_poses): + invalid_robot_pose_ids.append(instance_id) + else: + position = first_robot_position(data) + if position is not None: + robot_positions.append(position[:2]) + + for object_name, object_data in data.items(): + for particle_position in object_world_positions(object_name, object_data, data, scene_to_bddl_name): + object_positions[object_name].append(particle_position[:2]) + + report.checks.append( + CheckLine("JSONs open cleanly", not report.invalid_json_files, format_list(report.invalid_json_files)) + ) + report.checks.append( + CheckLine( + "Every instance has a robot pose", + not invalid_robot_pose_ids, + format_robot_pose_detail(report.missing_instance_ids, invalid_robot_pose_ids), + ) + ) + report.robot_stats = compute_pose_stats(robot_positions) + report.object_stats = {name: compute_pose_stats(points) for name, points in sorted(object_positions.items())} + robot_std_ok = report.robot_stats.std_xy >= args.min_xy_std + object_std_values = [stats.std_xy for stats in report.object_stats.values() if stats.count >= 2] + object_std_ok = bool(object_std_values) and max(object_std_values) >= args.min_xy_std + report.checks.append( + CheckLine( + f"Robot pose std is over {args.min_xy_std:g} m", + robot_std_ok, + f"xy std {report.robot_stats.std_xy:.3f} m from {report.robot_stats.count} poses", + ) + ) + report.checks.append( + CheckLine( + f"Object pose std is over {args.min_xy_std:g} m", + object_std_ok, + format_object_std_detail(report.object_stats, args.min_xy_std), + ) + ) + report.checks.append( + CheckLine("Valid instance JSON count is readable", valid_json_count == args.expected_instances) + ) + return report + + +def format_instance_detail(missing_ids, extra_files): + parts = [] + if missing_ids: + parts.append("missing " + summarize_ints(missing_ids)) + if extra_files: + parts.append("extra " + format_list(extra_files, max_items=5)) + return "; ".join(parts) + + +def format_robot_pose_detail(missing_ids, invalid_pose_ids): + parts = [] + if missing_ids: + parts.append("missing instance files " + summarize_ints(missing_ids)) + invalid_ids = sorted(set(invalid_pose_ids) - set(missing_ids)) + if invalid_ids: + parts.append("invalid robot pose " + summarize_ints(invalid_ids)) + return "; ".join(parts) + + +def summarize_ints(values, max_items=12): + values = list(values) + if len(values) <= max_items: + return ", ".join(str(value) for value in values) + head = ", ".join(str(value) for value in values[:max_items]) + return f"{head}, ... (+{len(values) - max_items} more)" + + +def format_list(values, max_items=8): + values = [str(value) for value in values] + if not values: + return "" + if len(values) <= max_items: + return ", ".join(values) + return ", ".join(values[:max_items]) + f", ... (+{len(values) - max_items} more)" + + +def format_object_std_detail(object_stats, min_xy_std): + if not object_stats: + return "no object poses found" + values = [stats.std_xy for stats in object_stats.values() if stats.count >= 2] + if not values: + return "not enough repeated object poses" + low = [name for name, stats in object_stats.items() if stats.count >= 2 and stats.std_xy < min_xy_std] + return f"min {min(values):.3f} m, median {float(np.median(values)):.3f} m, max {max(values):.3f} m" + ( + f"; low: {format_list([short_object_label(name) for name in low], max_items=5)}" if low else "" + ) + + +def scan_all_json(dataset_dir): + invalid = [] + count = 0 + for path in sorted(dataset_dir.rglob("*.json")): + if ".git" in path.parts: + continue + count += 1 + try: + read_json(path) + except Exception as exc: + invalid.append(f"{path.relative_to(dataset_dir)}: {exc}") + return count, invalid + + +def validate_dataset_shape(dataset_dir, discovered_paths, expected_instances): + allowed_files = { + Path("README.md"), + *(Path("metadata") / name for name in METADATA_FILENAMES), + } + allowed_dirs = { + Path("."), + Path("metadata"), + Path("scenes"), + } + + for scene_json_dir in sorted((dataset_dir / "scenes").glob("*/json")): + scene_dir = scene_json_dir.parent + scene = scene_dir.name + allowed_dirs.add(scene_dir.relative_to(dataset_dir)) + allowed_dirs.add(scene_json_dir.relative_to(dataset_dir)) + stable = scene_json_dir / f"{scene}_stable.json" + allowed_files.add(stable.relative_to(dataset_dir)) + + for paths in discovered_paths.values(): + if not paths.instance_dir or not paths.prefix: + continue + allowed_dirs.add(paths.instance_dir.relative_to(dataset_dir)) + allowed_files.add(paths.template_path.relative_to(dataset_dir)) + allowed_files.add(paths.partial_rooms_path.relative_to(dataset_dir)) + for instance_id in range(1, expected_instances + 1): + allowed_files.add(instance_state_path(paths, instance_id).relative_to(dataset_dir)) + + extras = [] + for path in sorted(dataset_dir.rglob("*")): + if ".git" in path.parts: + continue + rel = path.relative_to(dataset_dir) + if path.is_dir(): + if rel not in allowed_dirs: + extras.append(f"{rel}/") + elif rel not in allowed_files: + extras.append(str(rel)) + return extras + + +def available_scene_for_task(available_tasks, task_name): + task_entry = available_tasks.get(task_name) + if not isinstance(task_entry, dict): + return None + for instance_entry in task_entry.values(): + if isinstance(instance_entry, dict) and instance_entry.get("scene_model"): + return instance_entry["scene_model"] + return None + + +def custom_scenes_for_task(custom_lists, task_name): + task_entry = custom_lists.get(task_name) + if not isinstance(task_entry, dict): + return [] + return sorted(key for key, value in task_entry.items() if key != "room_types" and isinstance(value, dict)) + + +def add_metadata_scene_check(report, available_tasks, custom_lists, paths): + available_scene = available_scene_for_task(available_tasks, report.task_name) + custom_scenes = custom_scenes_for_task(custom_lists, report.task_name) + expected = set(filter(None, [available_scene, *custom_scenes])) + if not expected: + report.checks.append(CheckLine("Metadata scene matches folder", False, "no scene in metadata")) + return + ok = paths.scene in expected if paths.scene is not None else False + detail = "" if ok else f"folder scene {paths.scene}; metadata scenes {format_list(sorted(expected))}" + report.checks.append(CheckLine("Metadata scene matches folder", ok, detail)) + + +def build_reports(args): + dataset_dir = args.dataset_dir.expanduser().resolve() + args.dataset_dir = dataset_dir + metadata_dir = dataset_dir / "metadata" + available_path = metadata_dir / "available_tasks.yaml" + custom_lists_path = metadata_dir / "task_custom_lists.json" + b100_path = metadata_dir / "B100_task_misc.csv" + + metadata_load_errors = [] + available_tasks = load_or_report(load_yaml, available_path, {}, metadata_load_errors) + available_tasks = require_mapping(available_tasks, "available_tasks.yaml", metadata_load_errors) + available_duplicates = find_top_level_yaml_duplicates(available_path) if available_path.exists() else [] + custom_duplicate_keys = [] + custom_lists = load_or_report( + lambda path: load_json_file(path, duplicate_keys=custom_duplicate_keys), + custom_lists_path, + {}, + metadata_load_errors, + ) + custom_lists = require_mapping(custom_lists, "task_custom_lists.json", metadata_load_errors) + b100_rows, b100_duplicates = load_or_report(load_b100_rows, b100_path, ([], []), metadata_load_errors) + discovered_paths, extra_instance_dirs = discover_task_paths(dataset_dir) + selected_tasks = choose_tasks(available_tasks, b100_rows) + + b100_by_task = {row["task_name"]: row for row in b100_rows} + reports = [] + for task_name in selected_tasks: + paths = discovered_paths.get(task_name, TaskPaths(task_name=task_name)) + b100_row = b100_by_task.get(task_name, {}) + reports.append( + analyze_task( + paths=paths, + task_id=b100_row.get("task_id"), + rooms=b100_row.get("rooms", []), + args=args, + ) + ) + add_metadata_scene_check(reports[-1], available_tasks, custom_lists, paths) + + global_json_count, global_invalid_json = scan_all_json(dataset_dir) + readable_errors = sorted(set(global_invalid_json + metadata_load_errors)) + discovered_task_names = set(discovered_paths) + selected_set = set(selected_tasks) + available_set = set(available_tasks) + custom_set = set(custom_lists) + b100_set = set(b100_by_task) + metadata_selected_ok = selected_set <= available_set and selected_set <= custom_set and selected_set <= b100_set + discovered_selected_ok = selected_set <= discovered_task_names + metadata_sets_match = available_set == custom_set + extra_discovered_tasks = sorted(discovered_task_names - available_set) + readme_text = (dataset_dir / "README.md").read_text(errors="ignore") if (dataset_dir / "README.md").exists() else "" + readme_missing = sorted(task for task in selected_tasks if task not in readme_text) + dataset_extras = validate_dataset_shape(dataset_dir, discovered_paths, args.expected_instances) + duplicate_ok = not (available_duplicates or custom_duplicate_keys or b100_duplicates) + + global_checks = [ + CheckLine("Metadata and JSON files open cleanly", not readable_errors, format_list(readable_errors)), + CheckLine( + "Selected tasks are in every metadata file", + metadata_selected_ok, + metadata_detail(selected_set, available_set, custom_set, b100_set), + ), + CheckLine( + "2026 available_tasks and task_custom_lists match", + metadata_sets_match, + metadata_set_diff_detail(available_set, custom_set), + ), + CheckLine( + "No duplicates", + duplicate_ok, + "" if duplicate_ok else duplicate_detail(available_duplicates, custom_duplicate_keys, b100_duplicates), + ), + CheckLine("README mentions every selected task", not readme_missing, format_list(readme_missing)), + CheckLine( + "Selected tasks have folders", + discovered_selected_ok, + format_list(sorted(selected_set - discovered_task_names)), + ), + CheckLine( + "No incomplete task folders", + not (extra_discovered_tasks or extra_instance_dirs), + format_list(extra_discovered_tasks + [str(path.relative_to(dataset_dir)) for path in extra_instance_dirs]), + ), + CheckLine("No extra file/folder than required", not dataset_extras, format_list(dataset_extras, max_items=12)), + ] + return { + "dataset_dir": dataset_dir, + "selected_tasks": selected_tasks, + "reports": reports, + "global_checks": global_checks, + "global_json_count": global_json_count, + } + + +def metadata_detail(selected, available, custom, b100): + parts = [] + for label, source in [("available_tasks", available), ("task_custom_lists", custom), ("B100_task_misc", b100)]: + missing = sorted(selected - source) + if missing: + parts.append(f"{label} missing {format_list(missing)}") + return "; ".join(parts) + + +def metadata_set_diff_detail(available, custom): + parts = [] + missing_custom = sorted(available - custom) + missing_available = sorted(custom - available) + if missing_custom: + parts.append("custom missing " + format_list(missing_custom)) + if missing_available: + parts.append("available missing " + format_list(missing_available)) + return "; ".join(parts) + + +def duplicate_detail(available_duplicates, custom_duplicate_keys, b100_duplicates): + parts = [] + if available_duplicates: + parts.append("available_tasks " + format_list(available_duplicates)) + if custom_duplicate_keys: + parts.append("task_custom_lists " + format_list(sorted(set(custom_duplicate_keys)))) + if b100_duplicates: + parts.append("B100 CSV " + format_list(b100_duplicates)) + return "; ".join(parts) + + +def append_visible_point(points, position, transform, instance_id): + point = world_to_display_point(position, transform) + point["instance"] = instance_id + if point["visible"]: + points.append(point) + + +def attach_gui_payloads(reports, args): + cache = {} + task_paths = discover_task_paths(args.dataset_dir)[0] + for report in reports: + if report.scene is None: + continue + cache_key = (report.scene, tuple(sorted(set(report.rooms)))) + if cache_key not in cache: + try: + cache[cache_key] = make_floor_plan( + scene=report.scene, + chosen_rooms=report.rooms, + floor=args.floor, + target_size=args.target_size, + crop_margin_px=args.crop_margin_px, + ) + except Exception as exc: + report.checks.append(CheckLine("Floor map opens", False, str(exc))) + continue + floor_plan = cache[cache_key] + missing_rooms = sorted(set(report.rooms) - floor_plan.existing_room_names) + report.checks.append( + CheckLine("CSV rooms exist in the floor map", not missing_rooms, format_list(missing_rooms)) + ) + + transform = floor_plan.transform + report.map_payload = { + "image": floor_plan.image_uri, + "width": floor_plan.width, + "height": floor_plan.height, + "rooms": floor_plan.rooms, + } + + paths = task_paths.get(report.task_name) + if paths is None or paths.instance_dir is None: + continue + scene_to_bddl_name = {} + if paths.template_path is not None and paths.template_path.exists(): + try: + template_data = read_json(paths.template_path) + except Exception: + template_data = None + scene_to_bddl_name = template_scene_to_bddl_names(template_data) if template_data is not None else {} + if template_data is not None: + template_robot_position = first_template_robot_position(template_data) + if template_robot_position is not None: + append_visible_point(report.robot_points, template_robot_position, transform, instance_id=0) + try: + template_positions = template_object_positions(template_data) + except ValueError as exc: + report.checks.append(CheckLine("Template object registry is valid", False, str(exc))) + else: + for object_name, positions in template_positions.items(): + for object_position in positions: + append_visible_point( + report.object_points.setdefault(object_name, []), + object_position, + transform, + instance_id=0, + ) + for instance_id in range(1, args.expected_instances + 1): + path = instance_state_path(paths, instance_id) + if not path.exists(): + continue + try: + data = read_json(path) + except Exception: + continue + robot_position = first_robot_position(data) + if robot_position is not None: + append_visible_point(report.robot_points, robot_position, transform, instance_id) + for object_name, object_data in data.items(): + for object_position in object_world_positions(object_name, object_data, data, scene_to_bddl_name): + append_visible_point( + report.object_points.setdefault(object_name, []), + object_position, + transform, + instance_id, + ) + + +def print_report(result, min_xy_std, expected_instances, max_details): + reports = result["reports"] + global_checks = result["global_checks"] + print(f"Dataset: {result['dataset_dir']}") + print(f"Tasks checked: {len(reports)}") + print(f"JSON files seen: {result['global_json_count']}") + print() + + for check in global_checks: + print(f"{check.text}: {yes_no(check.ok)}") + task_all_checks = [ + ( + "Every task has the required files", + lambda report: ( + check_by_text(report, "Template and partial rooms are there") + and check_by_text(report, "Scene stable file is there") + ), + ), + ( + f"Every task has {expected_instances} instances", + lambda report: check_by_text(report, f"Task has {expected_instances} instances"), + ), + ("Every instance has a robot pose", lambda report: check_by_text(report, "Every instance has a robot pose")), + (f"Robot pose std is over {min_xy_std:g} m", lambda report: report.robot_stats.std_xy >= min_xy_std), + ( + f"Object pose std is over {min_xy_std:g} m", + lambda report: ( + bool(report.object_stats) + and max((stats.std_xy for stats in report.object_stats.values()), default=0.0) >= min_xy_std + ), + ), + ] + for label, predicate in task_all_checks: + print(f"{label}: {yes_no(bool(reports) and all(predicate(report) for report in reports))}") + + print("\nStd by task:") + for report in reports: + object_values = [stats.std_xy for stats in report.object_stats.values() if stats.count >= 2] + object_summary = "none" + if object_values: + object_summary = ( + f"min {min(object_values):.3f}, median {float(np.median(object_values)):.3f}, " + f"max {max(object_values):.3f}" + ) + print(f"- {report.task_name}: robot {report.robot_stats.std_xy:.3f} m; objects {object_summary} m") + + details = [] + for check in global_checks: + if not check.ok and check.detail: + details.append(f"{check.text}: {check.detail}") + for report in reports: + for check in report.checks: + if not check.ok and check.detail: + details.append(f"{report.task_name} - {check.text}: {check.detail}") + if details: + print("\nDetails:") + for detail in details[:max_details]: + print(f"- {detail}") + if len(details) > max_details: + print(f"- ... {len(details) - max_details} more") + + +def check_by_text(report, text): + return any(check.text == text and check.ok for check in report.checks) + + +def task_to_gui(report, index): + object_names = sorted(report.object_points) + object_colors = {name: DEFAULT_PALETTE[i % len(DEFAULT_PALETTE)] for i, name in enumerate(object_names)} + checks = [{"text": check.text, "ok": check.ok, "detail": check.detail} for check in report.checks] + object_stats = { + name: { + "label": short_object_label(name), + "std_xy": stats.std_xy, + "count": stats.count, + "color": object_colors.get(name, "#666666"), + } + for name, stats in report.object_stats.items() + } + return { + "index": index, + "task": report.task_name, + "task_id": report.task_id, + "scene": report.scene, + "ok": report.ok, + "rooms": report.rooms, + "checks": checks, + "robotStats": { + "count": report.robot_stats.count, + "stdX": report.robot_stats.std_x, + "stdY": report.robot_stats.std_y, + "stdXY": report.robot_stats.std_xy, + }, + "objectStats": object_stats, + "map": report.map_payload, + "robotPoints": report.robot_points, + "objectPoints": report.object_points, + "objectColors": object_colors, + "objectLabels": {name: short_object_label(name) for name in object_names}, + } + + +def image_data_uri(path, mime_type="image/png"): + try: + encoded = base64.b64encode(path.read_bytes()).decode("ascii") + except OSError: + return "" + return f"data:{mime_type};base64,{encoded}" + + +def browser_url(host, port): + browser_host = "127.0.0.1" if host in {"0.0.0.0", "::", ""} else host + return f"http://{browser_host}:{port}" + + +def run_gui(result, args): + try: + from flask import Flask, render_template + except ImportError as exc: + raise RuntimeError("Flask is needed to show the QC GUI. Install it with `pip install flask`.") from exc + + gui_data = { + "datasetDir": str(result["dataset_dir"]), + "expectedInstances": args.expected_instances, + "globalChecks": [ + {"text": check.text, "ok": check.ok, "detail": check.detail} for check in result["global_checks"] + ], + "tasks": [task_to_gui(report, index) for index, report in enumerate(result["reports"])], + } + logo_uri = image_data_uri(REPO_ROOT / "docs" / "assets" / "behavior_logo3.png") + app = Flask(__name__, template_folder=str(TEMPLATE_DIR)) + + @app.route("/") + def index(): + return render_template("challenge_instance_qc_gui.html", gui_data=gui_data, logo_uri=logo_uri) + + url = browser_url(args.host, args.port) + print(f"\nGUI: {url}", flush=True) + if args.open_browser: + webbrowser.open(url) + app.run(host=args.host, port=args.port, debug=False, use_reloader=False) + + +def parse_args(): + parser = argparse.ArgumentParser(description=SCRIPT_DESCRIPTION) + parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR) + parser.add_argument("--expected-instances", type=int, default=300) + parser.add_argument("--min-xy-std", type=float, default=0.05) + parser.add_argument("--floor", type=int, default=0) + parser.add_argument("--target-size", type=int, default=1200) + parser.add_argument("--crop-margin-px", type=int, default=80) + parser.add_argument("--max-details", type=int, default=40) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8765) + parser.add_argument("--open-browser", action="store_true") + return parser.parse_args() + + +def main(): + args = parse_args() + print("Building QC report for all tasks...", flush=True) + result = build_reports(args) + attach_gui_payloads(result["reports"], args) + print_report( + result, + min_xy_std=args.min_xy_std, + expected_instances=args.expected_instances, + max_details=args.max_details, + ) + run_gui(result, args) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/constants.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..37aa2114d0f336dd5ee86c19abc6c3d30ae3708e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/constants.py @@ -0,0 +1,5 @@ +import os +from omnigibson.macros import gm + +DATASET_2026_PATH = os.path.join(gm.DATA_PATH, "2026-challenge-task-instances") +TASK_CUSTOM_LIST_PATH = os.path.join(DATASET_2026_PATH, "metadata", "task_custom_lists.json") diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/extract_task_information.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/extract_task_information.py new file mode 100644 index 0000000000000000000000000000000000000000..8ffeea6c8bf39ab8e47b7566fb1bdb5dfe063a06 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/extract_task_information.py @@ -0,0 +1,105 @@ +import os +import json +import yaml +import torch as th +import omnigibson.utils.transform_utils as T +from constants import DATASET_2026_PATH + + +ROBOT_NAME = "robot" +ROBOT_TYPE = "R1Pro" + + +def get_pose_from_robot_poses(robot_poses): + if ROBOT_NAME in robot_poses: + pose = robot_poses[ROBOT_NAME][0] + return pose["position"], pose["orientation"] + + if ROBOT_TYPE in robot_poses: + pose = robot_poses[ROBOT_TYPE][0] + return pose["position"], pose["orientation"] + + return None + + +def get_robot_start_pose(tmpl): + pose = get_pose_from_robot_poses(tmpl["metadata"]["task"].get("robot_poses", {})) + if pose is not None: + return pose + + # 2025 compatibility: older template JSONs stored robot_poses under metadata, + # outside metadata.task, and keyed poses by robot type. + pose = get_pose_from_robot_poses(tmpl["metadata"].get("robot_poses", {})) + if pose is not None: + return pose + + robot_name = tmpl["metadata"]["task"]["inst_to_name"]["agent.n.01_1"] + object_registry = tmpl["state"]["registry"]["object_registry"] + if robot_name not in object_registry: + raise KeyError(f"Could not find robot pose for {robot_name} in template JSON") + obj_state = object_registry[robot_name] + root_pos = obj_state["root_link"]["pos"] + base_joints = obj_state["joint_pos"] + robot_start_position = [root_pos[i] + base_joints[i] for i in range(3)] + robot_start_orientation = T.euler2quat(th.tensor(base_joints[3:6])).tolist() + return robot_start_position, robot_start_orientation + + +def main(): + scenes_dir = os.path.join(DATASET_2026_PATH, "scenes") + + # Create a new empty dictionary to store tasks + tasks_data = {} + + # Traverse scenes//json + for scene_model in os.listdir(scenes_dir): + json_dir = os.path.join(scenes_dir, scene_model, "json") + if not os.path.isdir(json_dir): + continue + + for task_instances_dir in os.listdir(json_dir): + task_path = os.path.join(json_dir, task_instances_dir) + if not os.path.isdir(task_path): + continue + + # Dir name format: {scene_model}_task_{task_name}_instances + prefix = f"{scene_model}_task_" + suffix = "_instances" + if not (task_instances_dir.startswith(prefix) and task_instances_dir.endswith(suffix)): + continue + task_name = task_instances_dir[len(prefix) : -len(suffix)] + + # Instance 0 lives in the parent json/ folder as _0_0_template.json + template_file = os.path.join(json_dir, f"{scene_model}_task_{task_name}_0_0_template.json") + if os.path.exists(template_file): + with open(template_file, "r") as f: + tmpl = json.load(f) + robot_start_position, robot_start_orientation = get_robot_start_pose(tmpl) + tasks_data[task_name] = { + 0: { + "scene_model": scene_model, + "robot_start_position": robot_start_position, + "robot_start_orientation": robot_start_orientation, + } + } + print(f"Processed instance 0 from: {os.path.basename(template_file)}") + print(f" Robot start position: {robot_start_position}") + print(f" Robot start orientation: {robot_start_orientation}") + print("-" * 50) + else: + print(f"Warning: no instance 0 template found for {task_name} in {scene_model}") + + # Write the data to the YAML file (completely overwriting it) + yaml_file = os.path.join(DATASET_2026_PATH, "metadata", "available_tasks.yaml") + with open(yaml_file, "w") as f: + yaml.dump(tasks_data, f, default_flow_style=False) + + # Count total instances + total_instances = sum(len(instances) for instances in tasks_data.values()) + print( + f"Created new {yaml_file} with information from {len(tasks_data)} tasks and {total_instances} total instances" + ) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/floor_plan_visualization.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/floor_plan_visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..edfa45d557bf128b51ba224809b500e11b70794a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/floor_plan_visualization.py @@ -0,0 +1,199 @@ +"""Render a labeled, color-coded floor plan PNG for a BEHAVIOR-1K scene. + +The image shows every room instance in a distinct color with its instance name +drawn at the room centroid, and overlays the traversability map so that walls +and obstacles (furniture, fixtures) are visible against the room colors. + +Run as a script: + + python scripts/sampling/floor_plan_visualization.py \\ + --scene house_single_floor --output house_single_floor_floorplan.png +""" + +import argparse +import os + +import cv2 +import matplotlib.patches as mpatches +import matplotlib.pyplot as plt +import numpy as np + +from omnigibson.utils.asset_utils import get_dataset_path, get_scene_path + + +def _load_room_categories(): + path = os.path.join(get_dataset_path("behavior-1k-assets"), "metadata", "room_categories.txt") + with open(path, "r") as fp: + return [line.rstrip() for line in fp.readlines()] + + +def _parse_segmentation(scene_dir, floor): + """Parse instance/semantic segmentation the same way SegmentationMap does. + + Returns the raw instance map, semantic map, and an ins_id -> ins_name dict. + """ + layout_dir = os.path.join(scene_dir, "layout") + img_ins = cv2.imread(os.path.join(layout_dir, f"floor_insseg_{floor}.png"), cv2.IMREAD_GRAYSCALE) + img_sem = cv2.imread(os.path.join(layout_dir, f"floor_semseg_{floor}.png"), cv2.IMREAD_GRAYSCALE) + assert img_ins is not None and img_sem is not None, f"Missing segmentation maps in {layout_dir}" + assert img_ins.shape == img_sem.shape, "Instance and semantic maps have different sizes" + + room_cats = _load_room_categories() + + # For each semantic id, enumerate its instance ids (in sorted order, matching SegmentationMap). + sem_id_to_ins_ids = {} + for ins_id in np.unique(img_ins): + if ins_id == 0: + continue + ys, xs = np.where(img_ins == ins_id) + sem_id = int(img_sem[ys[0], xs[0]]) + sem_id_to_ins_ids.setdefault(sem_id, []).append(int(ins_id)) + + ins_id_to_name = {} + for sem_id, ins_ids in sem_id_to_ins_ids.items(): + sem_name = room_cats[sem_id - 1] + for i, ins_id in enumerate(sorted(ins_ids)): + ins_id_to_name[ins_id] = f"{sem_name}_{i}" + + return img_ins, img_sem, ins_id_to_name + + +def _load_trav(scene_dir, floor): + path = os.path.join(scene_dir, "layout", f"floor_trav_{floor}.png") + trav = cv2.imread(path, cv2.IMREAD_GRAYSCALE) + assert trav is not None, f"Missing traversability map: {path}" + return trav + + +def _downsample_to(img, target_size, interpolation): + """Resize so the largest dimension is target_size, preserving aspect.""" + h, w = img.shape[:2] + scale = target_size / max(h, w) + if scale >= 1.0: + return img + new_w, new_h = max(1, int(round(w * scale))), max(1, int(round(h * scale))) + return cv2.resize(img, (new_w, new_h), interpolation=interpolation) + + +def get_floor_plan_data(scene_dir, floor=0, target_size=1500, crop_margin_px=80): + ins, _, ins_id_to_name = _parse_segmentation(scene_dir, floor) + trav = _load_trav(scene_dir, floor) + + # Crop the full-scene maps to the tight bounding box around the rooms so + # the rendered image isn't dominated by empty exterior pixels. + ys, xs = np.where(ins > 0) + if len(xs): + y0 = max(int(ys.min()) - crop_margin_px, 0) + y1 = min(int(ys.max()) + crop_margin_px + 1, ins.shape[0]) + x0 = max(int(xs.min()) - crop_margin_px, 0) + x1 = min(int(xs.max()) + crop_margin_px + 1, ins.shape[1]) + ins = ins[y0:y1, x0:x1] + trav = trav[y0:y1, x0:x1] + + # Keep the two maps pixel-aligned while downsampling for a manageable figure. + ins = _downsample_to(ins, target_size, cv2.INTER_NEAREST) + trav = _downsample_to(trav, target_size, cv2.INTER_NEAREST) + + # Image rows run top-to-bottom while world y runs bottom-to-top, so flip rows. + ins = ins[::-1, :] + trav = trav[::-1, :] + + # Prefer landscape output: if the cropped map is taller than wide, rotate 90 CCW. + if ins.shape[0] > ins.shape[1]: + ins = np.rot90(ins, k=1) + trav = np.rot90(trav, k=1) + + ins_ids = sorted(ins_id_to_name.keys()) + cmap = plt.get_cmap("tab20", max(len(ins_ids), 1)) + ins_id_to_color = {ins_id: cmap(i)[:3] for i, ins_id in enumerate(ins_ids)} + + # Build an RGB canvas: white background, colored per-room fill, dark obstacles. + canvas = np.ones((*ins.shape, 3), dtype=np.float32) + for ins_id, color in ins_id_to_color.items(): + canvas[ins == ins_id] = color + + # Obstacle overlay: where the traversability map is black inside any room, + # darken that pixel so furniture / fixtures stand out against the room color. + obstacle_mask = (trav == 0) & (ins > 0) + canvas[obstacle_mask] *= 0.35 + + # Walls (black in trav, outside any room) render as solid black for contrast. + wall_mask = (trav == 0) & (ins == 0) + canvas[wall_mask] = 0.0 + + return { + "canvas": canvas, + "ins": ins, + "trav": trav, + "ins_id_to_name": ins_id_to_name, + "ins_id_to_color": ins_id_to_color, + } + + +def render_floor_plan(scene_dir, output_path, floor=0, target_size=1500, dpi=200, crop_margin_px=80): + plan = get_floor_plan_data( + scene_dir=scene_dir, + floor=floor, + target_size=target_size, + crop_margin_px=crop_margin_px, + ) + canvas = plan["canvas"] + ins = plan["ins"] + ins_id_to_name = plan["ins_id_to_name"] + ins_id_to_color = plan["ins_id_to_color"] + ins_ids = sorted(ins_id_to_name.keys()) + + fig, ax = plt.subplots(figsize=(14, 14)) + ax.imshow(canvas, interpolation="nearest") + + # Label each room at its centroid. Use a bbox so labels stay readable on any color. + for ins_id, name in ins_id_to_name.items(): + ys, xs = np.where(ins == ins_id) + if len(xs) == 0: + continue + cx, cy = float(np.mean(xs)), float(np.mean(ys)) + ax.text( + cx, + cy, + f"{name}\n(id={ins_id})", + ha="center", + va="center", + fontsize=7, + color="black", + bbox=dict(boxstyle="round,pad=0.15", facecolor="white", edgecolor="black", alpha=0.8, linewidth=0.5), + ) + + # Legend keyed by instance name, sorted for stable output. + handles = [mpatches.Patch(color=ins_id_to_color[i], label=f"{ins_id_to_name[i]} (id={i})") for i in ins_ids] + ax.legend(handles=handles, loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=8, frameon=False) + + scene_name = os.path.basename(os.path.normpath(scene_dir)) + ax.set_title(f"{scene_name} — floor {floor} room segmentation with obstacles") + ax.set_axis_off() + + fig.tight_layout() + fig.savefig(output_path, dpi=dpi, bbox_inches="tight") + plt.close(fig) + return output_path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--scene", default="house_single_floor", help="Scene name under behavior-1k-assets/scenes") + parser.add_argument( + "--scene-dir", default=None, help="Override scene directory directly (takes precedence over --scene)" + ) + parser.add_argument("--floor", type=int, default=0) + parser.add_argument("--output", default=None, help="Output PNG path (default: _floorplan.png)") + parser.add_argument("--target-size", type=int, default=1500, help="Max pixels per side before rendering") + parser.add_argument("--dpi", type=int, default=200) + args = parser.parse_args() + + scene_dir = args.scene_dir or get_scene_path(args.scene) + output = args.output or f"{args.scene}_floorplan.png" + out = render_floor_plan(scene_dir, output, floor=args.floor, target_size=args.target_size, dpi=args.dpi) + print(f"Wrote {out}") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/multiply_b1k_tasks.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/multiply_b1k_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..3e95b7436c8f0b6ae5417d977d357fd4708509ba --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/multiply_b1k_tasks.py @@ -0,0 +1,191 @@ +import os +import argparse +import omnigibson as og +from omnigibson.macros import gm, macros +import json +from omnigibson.objects import DatasetObject +import numpy as np +from utils import validate_task, get_scene_model, resolve_scene_model +from constants import DATASET_2026_PATH, TASK_CUSTOM_LIST_PATH + +parser = argparse.ArgumentParser() +parser.add_argument( + "-t", + "--activity", + type=str, + default=None, + required=True, + help="Activity to be sampled.", +) +parser.add_argument( + "--seed", + type=int, + default=0, + help="Instance ID to use as seed", +) +parser.add_argument( + "--start_idx", + type=int, + default=1, + help="Instance ID to start (inclusive)", +) +parser.add_argument( + "--end_idx", + type=int, + default=300, + help="Instance ID to end (inclusive)", +) +parser.add_argument( + "--partial_save", + action="store_true", + help="Whether to only save the task-relevant object scope states instead of the entire scene json", +) +parser.add_argument( + "-o", + "--output_dir", + type=str, + default=None, + help="Output directory for sampled tasks (default: gm.DATA_PATH/2026-challenge-task-instances/)", +) + +assert os.path.exists(TASK_CUSTOM_LIST_PATH), f"task_custom_lists.json not found: {TASK_CUSTOM_LIST_PATH}" +with open(TASK_CUSTOM_LIST_PATH, "r") as f: + TASK_CUSTOM_LISTS = json.load(f) + +gm.HEADLESS = False +gm.USE_GPU_DYNAMICS = False +gm.ENABLE_OBJECT_STATES = True +gm.ENABLE_TRANSITION_RULES = True + +macros.systems.micro_particle_system.MICRO_PARTICLE_SYSTEM_MAX_VELOCITY = 0.5 +macros.systems.macro_particle_system.MACRO_PARTICLE_SYSTEM_MAX_DENSITY = 200.0 +# macros.prims.entity_prim.DEFAULT_SLEEP_THRESHOLD = 0.0 +macros.utils.object_state_utils.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS = 5 +macros.utils.object_state_utils.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS = 5 + + +def main(): + args = parser.parse_args() + + scene_model = get_scene_model(TASK_CUSTOM_LISTS[args.activity]) + scene_model = resolve_scene_model(scene_model, os.path.join(DATASET_2026_PATH, "scenes")) + + if args.output_dir is None: + args.output_dir = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json") + + task_scene_file = os.path.join(args.output_dir, f"{scene_model}_task_{args.activity}_0_0_template.json") + assert os.path.exists(task_scene_file), "Did not find task scene template json at expected path: {}".format( + task_scene_file + ) + # Define the configuration to load -- we'll use a Fetch + cfg = { + # Use default frequency + "env": { + "action_frequency": 30, + "physics_frequency": 120, + }, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": scene_model, + "scene_file": task_scene_file, + "seg_map_resolution": 0.1, + "load_room_types": TASK_CUSTOM_LISTS[args.activity]["room_types"], + }, + "robots": [ + { + "type": "R1Pro", + "obs_modalities": [], + "default_reset_mode": "tuck", + "position": np.ones(3) * -50.0, + }, + ], + "task": { + "type": "BehaviorTask", + "online_object_sampling": False, + "activity_name": args.activity, + "activity_instance_id": args.seed, + "use_presampled_robot_pose": False, + }, + } + env = og.Environment(cfg) + + # Define where to save instances + save_dir = os.path.join(args.output_dir, f"{env.task.scene_name}_task_{args.activity}_instances") + + # If we want to create a stable scene config, do that now + default_scene_fpath = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json", f"{scene_model}_stable.json") + # Get the default scene instance + assert os.path.exists(default_scene_fpath), "Did not find default stable scene json!" + with open(default_scene_fpath, "r") as f: + default_scene_dict = json.load(f) + + # Needed for _sample_initial_conditions_final() + env.task.sampler._compiled_task = env.task.compiled_task + env.task.sampler._parse_inroom_object_room_assignment() + env.task.sampler._build_sampling_order() + + # Clear all the system particles + for system in env.scene.active_systems.values(): + system.remove_all_particles() + + og.sim.step() + + # Store the state without any particles + initial_state = og.sim.dump_state() + + num_trials = 50 + for activity_instance_id in range(args.start_idx, args.end_idx + 1): + success = False + for i in range(num_trials): + og.sim.load_state(initial_state) + og.sim.step() + + # Will sample new particles to satisfy states like Filled + error_msg = env.task.sampler._sample_initial_conditions_final() + + if error_msg is not None: + print(f"instance {activity_instance_id} trial {i} sampling failed: {error_msg}") + continue + + for _ in range(10): + og.sim.step() + + # object_scopes is indexed per env; this sampling script always runs a single env + for obj in env.task.object_scopes[0].values(): + if isinstance(obj, DatasetObject): + obj.keep_still() + + for _ in range(10): + og.sim.step() + + task_final_state = env.scene.dump_state() + task_scene_dict = {"state": task_final_state} + try: + validate_task( + env.task, + task_scene_dict, + default_scene_dict, + active_room_instances=env.scene.load_room_instances, + ) + except ValueError as e: + print(f"instance {activity_instance_id} trial {i} validation failed: {e}") + continue + + env.scene.load_state(task_final_state) + env.scene.update_initial_file() + print(f"instance {activity_instance_id} trial {i} succeeded.") + + env.task.activity_instance_id = activity_instance_id + env.task.save_task(env=env, save_dir=save_dir, override=True, task_relevant_only=args.partial_save) + print(f"instance {activity_instance_id} trial {i} saved") + success = True + break + if not success: + raise ValueError(f"instance {activity_instance_id} failed all {num_trials} trials") + + print(f"\n\nMultiply task for {args.activity} successful! Saved to {save_dir}.\n\n") + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/postprocess_sampled_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/postprocess_sampled_task.py new file mode 100644 index 0000000000000000000000000000000000000000..b060f634659c9c0d142d69a2b3b66079baa4ecfd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/postprocess_sampled_task.py @@ -0,0 +1,69 @@ +import argparse +import json +import os +from omnigibson.utils.data_utils import merge_scene_files +from omnigibson.tasks import BehaviorTask +from constants import DATASET_2026_PATH, TASK_CUSTOM_LIST_PATH +from utils import get_scene_model + +parser = argparse.ArgumentParser() +parser.add_argument( + "-t", + "--activity", + type=str, + default=None, + required=True, + help="Activity to be postprocessed.", +) +parser.add_argument( + "-w", + "--overwrite", + action="store_true", + help="Whether to forcibly overwrite any pre-existing files", +) +parser.add_argument( + "-o", + "--output_dir", + type=str, + default=None, + help="Output directory for sampled tasks (default: gm.DATA_PATH/2026-challenge-task-instances)", +) + + +def postprocess_task(output_dir, scene_model, activity_name, overwrite=False): + task_name = BehaviorTask.get_cached_activity_scene_filename( + scene_model=scene_model, + activity_name=activity_name, + activity_definition_id=0, + activity_instance_id=0, + ) + sampled_scene_partial_json = os.path.join(output_dir, f"{task_name}-partial_rooms.json") + full_scene_full_json = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json", f"{scene_model}_stable.json") + with open(full_scene_full_json, "r") as f: + scene_a = json.load(f) + with open(sampled_scene_partial_json, "r") as f: + scene_b = json.load(f) + sampled_scene_full_dict = merge_scene_files(scene_a, scene_b, keep_robot_from="b") + out_path = sampled_scene_partial_json.replace("-partial_rooms.json", ".json") + if os.path.exists(out_path) and not overwrite: + raise ValueError(f"File already exists at {out_path}, use --overwrite to overwrite.") + with open(out_path, "w+") as f: + json.dump(sampled_scene_full_dict, f, indent=4) + print(f"Postprocessed sampled scene saved to: {out_path}") + + +def main(): + args = parser.parse_args() + + with open(TASK_CUSTOM_LIST_PATH) as f: + task_custom_lists = json.load(f) + scene_model = get_scene_model(task_custom_lists[args.activity]) + + if args.output_dir is None: + args.output_dir = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json") + + postprocess_task(args.output_dir, scene_model, args.activity, overwrite=args.overwrite) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/sample_b1k_tasks.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/sample_b1k_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..71ed308f5acd873914661f71495d79dde299c235 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/sample_b1k_tasks.py @@ -0,0 +1,353 @@ +import logging +import os +import copy +import argparse +import omnigibson as og +from omnigibson.macros import gm, macros +import json +from omnigibson.objects import DatasetObject +from omnigibson.object_states import Contains +from omnigibson.tasks import BehaviorTask +from omnigibson.utils.python_utils import clear as clear_pu +from omnigibson.utils.constants import PrimType +from omnigibson.utils.bddl_utils import get_knowledge_base +from omnigibson.utils.ui_utils import create_module_logger +from utils import ( + get_predicates, + get_valid_tasks, + hide_all_lights, + UNSUPPORTED_PREDICATES, + validate_task, + get_scene_model, + resolve_scene_model, +) +from constants import DATASET_2026_PATH, TASK_CUSTOM_LIST_PATH +from postprocess_sampled_task import postprocess_task +import numpy as np + +log = create_module_logger(module_name="sample_b1k_tasks") +log.setLevel(logging.INFO) + + +# task_custom_lists.json always takes precedence. +assert os.path.exists(TASK_CUSTOM_LIST_PATH), f"task_custom_lists.json not found: {TASK_CUSTOM_LIST_PATH}" +with open(TASK_CUSTOM_LIST_PATH, "r") as f: + TASK_CUSTOM_LISTS = json.load(f) + + +parser = argparse.ArgumentParser() +parser.add_argument( + "-t", + "--activity", + type=str, + required=True, + help="Activity to be sampled", +) +parser.add_argument( + "-r", + "--room_types", + type=str, + default=None, + help="room types to be loaded, if specified. This should be a comma-delimited list of desired room types. Otherwise, will try to load all room types in this scene", +) +parser.add_argument( + "-w", + "--overwrite", + action="store_true", + help="If set, will overwrite any existing tasks that are found. Otherwise, will skip.", +) +parser.add_argument( + "-o", + "--output_dir", + type=str, + default=None, + help="Output directory for sampled tasks (default: gm.DATA_PATH/2026-challenge-task-instances)", +) + +# gm.HEADLESS = False +gm.USE_GPU_DYNAMICS = False +gm.ENABLE_OBJECT_STATES = True +gm.ENABLE_TRANSITION_RULES = False # Must be False! We permute this later + +macros.systems.micro_particle_system.MICRO_PARTICLE_SYSTEM_MAX_VELOCITY = 0.5 +macros.systems.macro_particle_system.MACRO_PARTICLE_SYSTEM_MAX_DENSITY = 200.0 +# macros.prims.entity_prim.DEFAULT_SLEEP_THRESHOLD = 0.0 +macros.utils.object_state_utils.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS = 5 +macros.utils.object_state_utils.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS = 5 + +logging.getLogger().setLevel(logging.INFO) + + +def main(random_selection=False, headless=False, short_exec=False): + args = parser.parse_args() + + scene_model_key = get_scene_model(TASK_CUSTOM_LISTS[args.activity]) + scene_model = resolve_scene_model(scene_model_key, os.path.join(DATASET_2026_PATH, "scenes")) + + if args.output_dir is None: + args.output_dir = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json") + + # If we want to create a stable scene config, do that now + default_scene_fpath = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json", f"{scene_model}_stable.json") + # Get the default scene instance + assert os.path.exists(default_scene_fpath), "Did not find default stable scene json!" + with open(default_scene_fpath, "r") as f: + default_scene_dict = json.load(f) + + # Define the configuration to load -- we'll use a Fetch + cfg = { + # Use default frequency + "env": { + "action_frequency": 30, + "physics_frequency": 120, + }, + "scene": { + "type": "InteractiveTraversableScene", + "scene_file": default_scene_fpath, + "scene_model": scene_model, + "seg_map_resolution": 0.1, + }, + "robots": [ + { + "type": "R1Pro", + "obs_modalities": [], + "default_reset_mode": "tuck", + "position": np.ones(3) * -50.0, + }, + ], + } + + activity = args.activity + + # Check if activity is valid + valid_tasks = get_valid_tasks() + if activity not in valid_tasks: + log.error(f"Activity {activity} not in valid tasks!") + return + + log.info(f"Sampling activity: {activity}...") + + # Currently our sampling script always samples partial rooms so we specify there to delineate between full + # scene templates + task_suffix = "partial_rooms" + if args.room_types is not None: + cfg["scene"]["load_room_types"] = args.room_types.split(",") + else: + cfg["scene"]["load_room_types"] = TASK_CUSTOM_LISTS[activity]["room_types"] + + # Create the environment + # Attempt to sample the activity + # env = create_env_with_stable_objects(cfg) + with gm.unlocked(): + gm.ENABLE_TRANSITION_RULES = True + env = og.Environment(configs=copy.deepcopy(cfg)) + gm.ENABLE_TRANSITION_RULES = False + if gm.HEADLESS: + hide_all_lights() + else: + og.sim.enable_viewer_camera_teleoperation() + + # After we load the robot, we do self.scene.reset() (one physics step) and then self.scene.update_initial_file(). + # We need to set all velocities to zero after this. Otherwise, the visual only objects will drift. + for obj in env.scene.objects: + obj.keep_still() + env.scene.update_initial_file() + + # Store the initial state -- this is the safeguard to reset to! + scene_initial_file = copy.deepcopy(env.scene._initial_file) + og.sim.stop() + + n_scene_objects = len(env.scene.objects) + + # Set environment configuration after environment is loaded, because we will load the task + env.task_config["type"] = "BehaviorTask" + env.task_config["online_object_sampling"] = True + + should_sample, success, reason = True, False, "" + + # Skip any with unsupported predicates, but still record the reason why we can't sample + task_obj = get_knowledge_base().get_task(f"{activity}-0") + conditions, object_scope, inroom_assignments = task_obj.parse_base_scope() + all_predicates = set( + get_predicates(conditions.parsed_initial_conditions) + get_predicates(conditions.parsed_goal_conditions) + ) + unsupported_predicates = set.intersection(all_predicates, UNSUPPORTED_PREDICATES) + if len(unsupported_predicates) > 0: + should_sample = False + reason = f"Unsupported predicate(s): {unsupported_predicates}" + + env.task_config["activity_name"] = activity + if activity in TASK_CUSTOM_LISTS and scene_model_key in TASK_CUSTOM_LISTS[activity]: + whitelist = TASK_CUSTOM_LISTS[activity][scene_model_key]["whitelist"] + blacklist = TASK_CUSTOM_LISTS[activity][scene_model_key]["blacklist"] + else: + whitelist, blacklist = None, None + env.task_config["sampling_whitelist"] = whitelist + env.task_config["sampling_blacklist"] = blacklist + log.info(f"white_list: {whitelist}") + log.info(f"black_list: {blacklist}") + assert whitelist is not None, "whitelist should not be None for manual sampling" + BehaviorTask.get_cached_activity_scene_filename( + scene_model=scene_model, + activity_name=activity, + activity_definition_id=0, + activity_instance_id=0, + ) + + # Make sure sim is stopped + assert og.sim.is_stopped() + + # Attempt to sample + if should_sample: + active_room_instances = env.scene.load_room_instances + log.info(f"relevant room instances: {active_room_instances}") + relevant_room_instances = set(active_room_instances) if active_room_instances is not None else None + for obj in env.scene.objects: + if isinstance(obj, DatasetObject): + active = ( + relevant_room_instances is None + or len(relevant_room_instances.intersection(obj.in_rooms)) > 0 + or obj.category in {"floors", "walls"} + ) + obj.visual_only = not active + obj.visible = active + + og.log.info(f"Sampling task: {activity}") + original_task_cfg = env.task_config + original_task_cfg["use_presampled_robot_pose"] = False + env._load_task(original_task_cfg) + assert og.sim.is_stopped() + success, feedback = env.task.feedback is None, env.task.feedback + + if not success: + raise ValueError(f"Initial task feedback not None: {feedback}") + + # Set masses of all task-relevant objects to be very high + # This is to avoid particles from causing instabilities + # Don't use this on cloth since these may be unstable at high masses + for obj in env.scene.objects[n_scene_objects:]: + if obj.prim_type != PrimType.CLOTH and Contains in obj.states: + obj.root_link.mass = max(1.0, obj.root_link.mass) + + # Sampling success + og.sim.play() + # This will actually reset the objects to their sample poses + env.task.reset(env) + + for i in range(300): + og.sim.step() + + # Remove any particles that fell out of the world + for system in env.scene.active_systems.values(): + if system.n_particles > 0: + particle_positions, _ = system.get_particles_position_orientation() + remove_idxs = np.where(particle_positions[:, -1] < -1.0)[0] + if len(remove_idxs) > 0: + system.remove_particles(remove_idxs) + + # Make sure objects are settled + for _ in range(10): + og.sim.step() + + task_final_state = env.scene.dump_state() + task_scene_dict = {"state": task_final_state} + # from IPython import embed; print("validate_task"); embed() + for obj in env.task.object_scopes[0].values(): + if isinstance(obj, DatasetObject): + obj.wake() + assert validate_task( + env.task, + task_scene_dict, + default_scene_dict, + active_room_instances=active_room_instances, + ) + # BREAKPOINT: Validation failed - inspect the task state to understand why + # At this breakpoint, you can: + # - Run: for _ in range(1000): og.sim.render() + # - Move the camera around to inspect objects and their states + # - Check env.task for task details + # - Examine feedback variable for the validation error message + + env.scene.load_state(task_final_state) + env.scene.update_initial_file() + log.info("\n\nsampling succeed! Please continue to save task and scene reload...\n\n") + # BREAKPOINT: Sampling succeeded - inspect the final task state before saving + # At this breakpoint, you can: + # - Run: for _ in range(1000): og.sim.render() + # - Move the camera around to visually verify the sampled task looks correct + # After inspection, continue to save the task to disk + breakpoint() + save_dir = os.path.join(args.output_dir) + os.makedirs(save_dir, exist_ok=True) + env.task.save_task( + env=env, + save_dir=save_dir, + override=args.overwrite, + task_relevant_only=False, + suffix=task_suffix, + ) + postprocess_task(save_dir, scene_model, activity, overwrite=args.overwrite) + og.sim.stop() + + assert og.sim.is_stopped() + + # Clear task callbacks if sampled + if should_sample: + callback_name = f"{activity}_refresh" + og.sim.remove_callback_on_add_obj(name=callback_name) + og.sim.remove_callback_on_remove_obj(name=callback_name) + og.sim.remove_callback_on_system_init(name=callback_name) + og.sim.remove_callback_on_system_clear(name=callback_name) + + # Remove all the additionally added objects + objs_to_remove = tuple(env.scene.objects[n_scene_objects:]) + og.sim.batch_remove_objects(objs_to_remove) + + # Clear all systems + for system in env.scene.active_systems.values(): + env.scene.clear_system(system_name=system.name) + clear_pu() + og.sim.play() + og.sim.step() + + # Update the scene initial state to the original state + env.scene.update_initial_file(scene_initial_file) + + # Stop sim, clear simulator + og.sim.stop() + og.clear() + + # env = create_env_with_stable_objects(cfg) + # Make sure transition rules are loaded properly + with gm.unlocked(): + gm.ENABLE_TRANSITION_RULES = True + env = og.Environment(configs=copy.deepcopy(cfg)) + gm.ENABLE_TRANSITION_RULES = False + + if gm.HEADLESS: + hide_all_lights() + + # After we load the robot, we do self.scene.reset() (one physics step) and then self.scene.update_initial_file(). + # We need to set all velocities to zero after this. Otherwise, the visual only objects will drift. + for obj in env.scene.objects: + obj.keep_still() + env.scene.update_initial_file() + + # Store the initial state -- this is the safeguard to reset to! + scene_initial_file = copy.deepcopy(env.scene._initial_file) + og.sim.stop() + + n_scene_objects = len(env.scene.objects) + + # Set environment configuration after environment is loaded, because we will load the task + env.task_config["type"] = "BehaviorTask" + env.task_config["online_object_sampling"] = True + + log.info(f"Finished sampling activity: {activity} with success: {success} and reason: {reason}") + + +if __name__ == "__main__": + main() + + # Shutdown at the end + og.shutdown() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/sample_robot_pose.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/sample_robot_pose.py new file mode 100644 index 0000000000000000000000000000000000000000..3de30c976b563779d7179ed8993f106fe20147cf --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/sample_robot_pose.py @@ -0,0 +1,305 @@ +import argparse +import copy +import json +import os +import sys +import omnigibson as og +import torch as th +from pathlib import Path +from typing import Dict, List +from omnigibson.macros import gm +from omnigibson.objects.primitive_object import PrimitiveObject +from constants import DATASET_2026_PATH, TASK_CUSTOM_LIST_PATH +from gello.utils.og_teleop_utils import generate_robot_config +from utils import get_scene_model, resolve_scene_model +from omnigibson.object_states import OnTop +import omnigibson.utils.transform_utils as T +from omnigibson.utils.bddl_utils import is_system_bddl_inst +from omnigibson.utils.python_utils import recursively_convert_to_torch + +sys.path.append(str(Path(__file__).parent.parent)) + +parser = argparse.ArgumentParser() +parser.add_argument( + "-t", + "--activity", + type=str, + default=None, + required=True, + help="Activity to be sampled", +) +parser.add_argument( + "-o", + "--output_dir", + type=str, + default=None, + help="Output directory for sampled tasks (default: gm.DATA_PATH/2026-challenge-task-instances)", +) +# Constants +MAX_ATTEMPTS = 10 +MAX_UPRIGHT_TILT = 0.1 + +gm.ENABLE_TRANSITION_RULES = False + + +def find_given_tasks(data_dir, activities: List[str] = []) -> List[Dict]: + """ + Find all instance files, partial json and full template json of the given task under folder data_dir. + + Returns: + List of dictionaries containing task info: name, path, template files, instance dir + """ + instance_dirs = list(data_dir.glob("*_instances")) + template_files = list(data_dir.glob("*_template.json")) + partial_files = list(data_dir.glob("*_template-partial_rooms.json")) + + tasks = [] + for activity in activities: + instance_dirs = [d for d in instance_dirs if activity in d.name] + template_files = [f for f in template_files if activity in f.name] + partial_files = [f for f in partial_files if activity in f.name] + # assert all threes are not empty list + assert len(instance_dirs) > 0, f"No instance directories found in {data_dir} for activity {activity}" + assert len(template_files) > 0, f"No template files found in {data_dir} for activity {activity}" + assert len(partial_files) > 0, f"No partial template files found in {data_dir} for activity {activity}" + tasks.append( + { + "name": activity, + "path": data_dir, + "template_file": template_files[0], + "partial_file": partial_files[0] if partial_files else None, + "instance_dir": instance_dirs[0], + "tro_files": sorted(list(instance_dirs[0].glob("*-tro_state.json"))), + } + ) + print("tasks ", tasks) + return tasks + + +def is_robot_pose_upright(quat): + """ + Test if the given quaternion orientation is approximately upright (i.e. z-axis aligned) within a certain tilt threshold. + """ + z_angle = T.z_angle_from_quat(quat) + upright_euler = th.stack([quat.new_tensor(0.0), quat.new_tensor(0.0), z_angle]) + upright_quat = T.euler2quat(upright_euler) + tilt_quat = T.quat_distance(quat, upright_quat) + tilt_angle = 2.0 * th.atan2(th.norm(tilt_quat[:3]), th.abs(tilt_quat[3])) + return tilt_angle <= MAX_UPRIGHT_TILT + + +def sample_robot_poses(env) -> Dict[str, List[Dict]]: + """ + Sample a valid pose for the generic cylinder robot in the current environment state. + + Args: + env: The OmniGibson environment already loaded and potentially reset to a specific state + + Returns: + Dictionary mapping "robot" to list of pose dicts + """ + # This script samples a single template instance at a time, so everything below indexes scene 0. + # (env.scene further down enforces this too, but only after the object_scopes lookups.) + assert env.num_envs == 1, f"sample_robot_poses only supports single-env environments, got num_envs={env.num_envs}" + + # Find the reference object from initial conditions + reference_object_name = None + for cond in env.task.activity_initial_conditions: + object_list = [] + for bddl_name in cond.get_relevant_objects(): + obj = env.task.object_scopes[0].get(bddl_name, None) + if obj is not None: + object_list.append(obj.name) + + # Check if this condition involves a robot + robot_objects = [obj_name for obj_name in object_list if "robot" in obj_name] + if robot_objects: + # Get the non-robot object from this condition + non_robot_objects = [obj_name for obj_name in object_list if "robot" not in obj_name] + reference_object_name = non_robot_objects[0] # Take the first non-robot object + print(f" Found reference object for robot positioning: {reference_object_name}") + break + + assert reference_object_name is not None, "No reference object found in initial conditions for robot pose sampling" + reference_object = env.scene.object_registry("name", reference_object_name) + + # Create the generic cylinder object + + cylinder = PrimitiveObject( + name="generic_cylinder", + primitive_type="Cylinder", + height=2.0, + radius=0.5, + fixed_base=False, + ) + + # Add cylinder to scene. Stopping the scene and playing it again causes a reset, so dump the state first. + state = og.sim.dump_state() + og.sim.stop() + env.scene.add_object(cylinder) + og.sim.play() + og.sim.load_state(state) + + # Sample pose using OnTop state + sampled_cylinder_pose = None + for _ in range(MAX_ATTEMPTS): + trial_success = cylinder.states[OnTop].set_value(reference_object, True) + if trial_success: + # Settle cylinder + for _ in range(10): + og.sim.step() + sampled_cylinder_pose = cylinder.get_position_orientation() + if not is_robot_pose_upright(sampled_cylinder_pose[1]): + sampled_cylinder_pose = None + continue + break + + assert sampled_cylinder_pose is not None, "Failed to sample valid upright cylinder pose" + # set z to the cylinder base + sampled_cylinder_pose[0][2] -= cylinder.height / 2 + robot_poses = { + "robot": [{"position": sampled_cylinder_pose[0].tolist(), "orientation": sampled_cylinder_pose[1].tolist()}] + } + + # Remove cylinder from scene + env.scene.remove_object(cylinder) + + return robot_poses + + +def process_task(task_info: Dict): + """ + Process a single task: sample cylinder pose and update all files. + + Args: + task_info: Dictionary containing task information + """ + print(f"Processing task: {task_info['name']}") + + # Load template file + with open(task_info["template_file"], "r") as f: + template_data = json.load(f) + + # Create environment configuration using template file as scene + cfg = { + "env": { + "action_frequency": 30, + "rendering_frequency": 30, + "physics_frequency": 120, + }, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": template_data["init_info"]["args"]["scene_model"], + "scene_file": str(task_info["template_file"]), + "include_robots": False, + }, + "task": { + "type": "BehaviorTask", + "activity_name": task_info["name"], + "activity_definition_id": 0, + "activity_instance_id": 0, + "online_object_sampling": False, + "debug_object_sampling": False, + "highlight_task_relevant_objects": False, + "termination_config": { + "max_steps": 50000, + }, + "reward_config": { + "r_potential": 1.0, + }, + "include_obs": False, + "use_presampled_robot_pose": False, + }, + "robots": generate_robot_config( + robot_type="r1pro", + robot_name="robot", + ), + } + # Create environment once for this task + env = og.Environment(configs=cfg) + + # Sample cylinder pose for the template instance + template_robot_poses = sample_robot_poses(env) + + # 2. Update template file + template_data["metadata"]["task"]["robot_poses"] = template_robot_poses + + # Save updated template + with open(task_info["template_file"], "w") as f: + json.dump(template_data, f, indent=4) + + # 3. Update partial template file if it exists + if task_info["partial_file"] is not None: + with open(task_info["partial_file"], "r") as f: + partial_data = json.load(f) + + partial_data["metadata"]["task"]["robot_poses"] = template_robot_poses + + with open(task_info["partial_file"], "w") as f: + json.dump(partial_data, f, indent=4) + + # 4. Update all TRO files - each needs its own cylinder pose sampling + for i, tro_file in enumerate(task_info["tro_files"]): + print(f" Processing TRO {i + 1}/{len(task_info['tro_files'])}: {tro_file.name}") + + env.scene.reset() + with open(tro_file, "r") as f: + tro_data = json.load(f) + tro_torch_state = recursively_convert_to_torch(copy.deepcopy(tro_data)) + + # Reset environment to this TRO instance state + for bddl_name, obj_state in tro_torch_state.items(): + if "agent" in bddl_name or "robot_poses" in bddl_name: + continue + env.task.object_scopes[0][bddl_name].load_state(obj_state, serialized=False) + for _ in range(25): + og.sim.step_physics() + for bddl_name, entity in env.task.object_scopes[0].items(): + if not is_system_bddl_inst(bddl_name) and entity is not None: + entity.keep_still() + + # Sample cylinder pose for this specific TRO instance + tro_robot_poses = sample_robot_poses(env) + + tro_data["robot_poses"] = tro_robot_poses + + with open(tro_file, "w") as f: + json.dump(tro_data, f, indent=4) + + print(f" Added pose for: {list(template_robot_poses.keys())}") + print(f" Updated template, partial template, and {len(task_info['tro_files'])} TRO files") + + +def main(): + """ + Main function to process all tasks with instance directories. + """ + args = parser.parse_args() + + with open(TASK_CUSTOM_LIST_PATH) as f: + task_custom_lists = json.load(f) + scene_model = get_scene_model(task_custom_lists[args.activity]) + scene_model = resolve_scene_model(scene_model, os.path.join(DATASET_2026_PATH, "scenes")) + + if args.output_dir is None: + args.output_dir = os.path.join(DATASET_2026_PATH, "scenes", scene_model, "json") + + # Find tasks in output_dir + tasks = find_given_tasks(Path(args.output_dir), [args.activity]) + + print(f"Found {len(tasks)} tasks with instance directories") + + # Process each task + for i, task_info in enumerate(tasks): + print(f"\n[{i + 1}/{len(tasks)}] ", end="") + process_task(task_info) + if i < len(tasks) - 1: + og.clear() + + og.shutdown() + + print("\nProcessing complete!") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/task_custom_lists.json b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/task_custom_lists.json new file mode 100644 index 0000000000000000000000000000000000000000..c4ecb92628acb56915e637c89bbcf2733ddddb5c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/task_custom_lists.json @@ -0,0 +1,2156 @@ +{ + "picking_up_trash": { + "room_types": [ + "living_room", + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "can__of__soda.n.01": { + "can_of_soda": { + "itolcg": null, + "lugwcz": null, + "opivig": null + } + }, + "ashcan.n.01": { + "trash_can": { + "wkxtxh": null + } + } + }, + "blacklist": {} + } + }, + "putting_away_Halloween_decorations": { + "room_types": [ + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "pumpkin.n.02": { + "pumpkin": { + "apitmi": null + } + }, + "caldron.n.01": { + "cauldron": { + "zndohl": null + } + }, + "candle.n.01": { + "pillar_candle": { + "bhaqam": null, + "cxswbc": null, + "omdnwg": null + } + } + }, + "blacklist": {} + } + }, + "picking_up_toys": { + "room_types": [ + "childs_room" + ], + "house_single_floor": { + "whitelist": { + "board_game.n.01": { + "board_game": { + "eoywpy": null, + "vbamua": null, + "rgvkmy": null, + "gcfkqa": null, + "ovttum": null + } + }, + "jigsaw_puzzle.n.01": { + "jigsaw_puzzle": { + "antykn": [0.19, 0.15, 0.01] + } + }, + "tennis_ball.n.01": { + "tennis_ball": { + "rgekxe": null + } + }, + "toy_box.n.01": { + "toy_box": { + "aviadj": [0.3160, 0.4553, 0.1384] + } + } + }, + "blacklist": {} + } + }, + "carrying_in_groceries": { + "room_types": [ + "garage", + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "beefsteak_tomato.n.01": { + "beefsteak_tomato": { + "altlfz": null + } + }, + "carton__of__milk.n.01": { + "carton_of_milk": { + "xmugpm": null + } + }, + "sack.n.01": { + "paper_bag": { + "bzsxgw": [0.20, 0.30, 0.48] + } + } + }, + "blacklist": {} + } + }, + "setting_mousetraps": { + "room_types": [ + "bathroom" + ], + "house_double_floor_upper": { + "whitelist": { + "mousetrap.n.01": { + "mousetrap": { + "mwfwsv": null + } + } + }, + "blacklist": {} + } + }, + "hiding_Easter_eggs": { + "room_types": [ + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "easter_egg.n.01": { + "easter_egg": { + "rxwfse": [0.1549, 0.1451, 0.1305] + } + }, + "wicker_basket.n.01": { + "wicker_basket": { + "drxfmr": null + } + }, + "lawn.n.01": { + "lawn": { + "aztwla": null + } + } + }, + "blacklist": {} + } + }, + "rearranging_kitchen_furniture": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "food_processor.n.01": { + "food_processor": { + "gamkbo": [0.2469, 0.2367, 0.3468] + } + }, + "french_press.n.01": { + "french_press": { + "zidmyo": null + } + }, + "toaster.n.02": { + "toaster": { + "kjwqav": null + } + } + }, + "blacklist": {} + } + }, + "loading_the_dishwasher": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "bowl.n.01": { + "bowl": { + "jblalf": null + } + }, + "mug.n.04": { + "mug": { + "yxaapv": null + } + }, + "plate.n.04": { + "plate": { + "luhkiz": null + } + } + }, + "blacklist": {} + } + }, + "cleaning_up_plates_and_food": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "plate.n.04": { + "plate": { + "itoeew": [0.408, 0.408, 0.024] + } + }, + "pizza.n.01": { + "pizza": { + "vyfhkm": [0.3, 0.3, 0.04] + } + }, + "bowl.n.01": { + "bowl": { + "adciys": null + } + } + }, + "blacklist": {} + } + }, + "can_meat": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "hinged_jar.n.01": { + "hinged_jar": { + "vzwhbg": null + } + }, + "bratwurst.n.01": { + "bratwurst": { + "pqfrrn": [0.1148, 0.0570, 0.0203] + } + }, + "chopping_board.n.01": { + "cutting_board": { + "jfrbuz": [0.5141, 0.3012, 0.0254] + } + }, + "cabinet.n.01": { + "top_cabinet": { + "lkxmne": null + } + + } + }, + "blacklist": {} + } + }, + "putting_away_toys": { + "room_types": [ + "living_room", + "dining_room" + ], + "house_single_floor": { + "whitelist": { + "toy_box.n.01": { + "toy_box": { + "qgfbdj": null + } + }, + "toy_figure.n.01": { + "toy_figure": { + "fnueyn": null, + "dgphap": null, + "fekpjq": null, + "gnofgv": null, + "lfxygp": null, + "orunry": null, + "psfkaj": null, + "tjchdg": null, + "usnnxe": null, + "vcmcoi": null, + "zltgeo": null, + "zuntus": null + } + } + }, + "blacklist": {} + } + }, + "assembling_gift_baskets": { + "room_types": [ + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "wicker_basket.n.01": { + "wicker_basket": { + "dgkhyn": null + } + }, + "candle.n.01": { + "pillar_candle": { + "bhaqam": null + } + }, + "butter_cookie.n.01": { + "butter_cookie": { + "kukrla": [0.08, 0.08, 0.02] + } + }, + "swiss_cheese.n.01": { + "swiss_cheese": { + "hwxeto": null + } + }, + "bow.n.08": { + "bow": { + "fhchql": [0.08, 0.08, 0.02] + } + } + }, + "blacklist": {} + } + }, + "clean_up_broken_glass": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "broken__glass.n.01": { + "broken_glass": { + "beltgg": null, + "rvpgpt": null + } + }, + "broom.n.01": { + "broom": { + "tpyvbt": [0.81, 0.27, 0.06] + } + }, + "ashcan.n.01": { + "trash_can": { + "wklill": null + } + } + }, + "blacklist": {} + } + }, + "sorting_mail": { + "room_types": [ + "living_room" + ], + "house_double_floor_upper": { + "whitelist": { + "mail.n.04": { + "mail": { + "azunex": [0.13, 0.2, 0.01] + } + }, + "newspaper.n.03": { + "newspaper": { + "ukamcl": null + } + }, + "table.n.02": { + "desk": { + "iotfzl": null + } + } + }, + "blacklist": {} + } + }, + "putting_up_Christmas_decorations_inside": { + "room_types": [ + "living_room", + "dining_room" + ], + "house_single_floor": { + "whitelist": { + "candy_cane.n.01": { + "candy_cane": { + "qfomjj": [0.12 , 0.045, 0.015] + } + }, + "pillar_candle.n.01": { + "pillar_candle": { + "cxswbc": [0.05, 0.05, 0.07] + } + }, + "wicker_basket.n.01": { + "wicker_basket": { + "dgkhyn": null + } + }, + "christmas_tree.n.05": { + "christmas_tree": { + "eadukw": null + } + }, + "gift_box.n.01": { + "gift_box": { + "mfalrc": null + } + }, + "wreath.n.01": { + "wreath": { + "rkrxno": null + } + } + }, + "blacklist": {} + } + }, + "hanging_pictures": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "poster.n.01": { + "poster": { + "dsrcyt": [0.01, 0.31 , 0.445] + } + } + }, + "blacklist": {} + } + }, + "can_beans": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "canister.n.02": { + "canister": { + "gqwnfv": null + } + }, + "stockpot.n.01": { + "stockpot": { + "dcleem": null + } + }, + "soup_ladle.n.01": { + "soup_ladle": { + "cfzneb": null + } + } + }, + "blacklist": {} + } + }, + "canning_food": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "carving_knife.n.01": { + "carving_knife": { + "usqmjc": null + } + }, + "chopping_board.n.01": { + "cutting_board": { + "aibvew": [0.35, 0.25, 0.02] + } + }, + "bowl.n.01": { + "bowl": { + "belcml": [0.255, 0.255, 0.15] + } + }, + "pineapple.n.02": { + "pineapple": { + "wfaybl": null + } + }, + "steak.n.01": { + "steak": { + "ppykkp": [0.13, 0.19, 0.05] + } + }, + "cabinet.n.01": { + "bottom_cabinet": { + "fancyy": null + } + }, + "countertop.n.01": { + "countertop": { + "kelzer": null + } + } + }, + "blacklist": {} + } + }, + "cook_cabbage": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "carving_knife.n.01": { + "carving_knife": { + "awvoox": null + } + }, + "chili.n.02": { + "chili": { + "xhbpqh": 6.0 + } + }, + "chopping_board.n.01": { + "cutting_board": { + "tcdrzs": null + } + }, + "frying_pan.n.01": { + "frying_pan": { + "cprjvq": null + } + }, + "plate.n.04": { + "plate": { + "zpddxu": null + } + }, + "head_cabbage.n.02": { + "head_cabbage": { + "tqohvs": null + } + }, + "countertop.n.01": { + "countertop": { + "kelker": null + } + } + }, + "blacklist": {} + } + }, + "spraying_for_bugs": { + "room_types": [ + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "insectifuge__atomizer.n.01": { + "insectifuge_atomizer": { + "qnroki": null + } + }, + "floor.n.01": { + "floors": { + "ghetev": null + } + }, + "pot_plant.n.01": { + "pot_plant": { + "arwvvc": null + } + } + }, + "blacklist": {} + } + }, + "spraying_fruit_trees": { + "room_types": [ + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "pesticide__atomizer.n.01": { + "pesticide_atomizer": { + "eisckl": null + } + }, + "floor.n.01": { + "floors": { + "ghetev": null + } + }, + "tree.n.01": { + "tree": { + "dyymaq": null + } + } + }, + "blacklist": {} + } + }, + "cook_bacon": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "bacon.n.01": { + "bacon": { + "eclhdh": null + } + }, + "frying_pan.n.01": { + "frying_pan": { + "mhndon": null + } + }, + "tray.n.01": { + "tray": { + "gsxbym": null + } + } + }, + "blacklist": {} + } + }, + "cook_a_brisket": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "brisket.n.01": { + "brisket": { + "nnnnqw": null + } + }, + "chopping_board.n.01": { + "cutting_board": { + "tcdrzs": null + } + }, + "frying_pan.n.01": { + "frying_pan": { + "cprjvq": null + } + } + }, + "blacklist": {} + } + }, + "cool_cakes": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "cookie_sheet.n.01": { + "baking_sheet": { + "yhurut": null + } + }, + "fruitcake.n.02": { + "fruitcake": { + "kxckts": null + } + } + }, + "blacklist": {} + } + }, + "freeze_pies": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "apple_pie.n.01": { + "apple_pie": { + "rpdhbr": null + } + }, + "plate.n.04": { + "plate": { + "bgxzec": null + } + }, + "tupperware.n.01": { + "tupperware": { + "mkstwr": [0.25, 0.25, 0.10] + } + } + }, + "blacklist": {} + } + }, + "freeze_fruit": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "apple.n.01": { + "apple": { + "agveuv": null, + "omzprq": null + } + }, + "bowl.n.01": { + "bowl": { + "byzaxy": null + } + }, + "strawberry.n.01": { + "strawberry": { + "xcnzxh": [0.06, 0.05, 0.05] + } + }, + "tray.n.01": { + "tray": { + "vxbtax": null + } + }, + "tupperware.n.01": { + "tupperware": { + "mkstwr": null + } + } + }, + "blacklist": {} + } + }, + "freeze_vegetables": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "bell_pepper.n.02": { + "bell_pepper": { + "wszvwc": null, + "ggurxn": null, + "ihctxa": null + } + }, + "carrot.n.03": { + "carrot": { + "nktmff": null, + "aucrah": null + } + }, + "chopping_board.n.01": { + "cutting_board": { + "tcdrzs": null + } + }, + "half__zucchini.n.01": { + "half_zucchini": { + "career": null, + "uzezze": null + } + }, + "tupperware.n.01": { + "tupperware": { + "mkstwr": null + } + } + }, + "blacklist": {} + } + }, + "freeze_meat": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "chicken.n.01": { + "chicken": { + "nppsmz": [0.2, 0.16, 0.096] + } + }, + "plate.n.04": { + "plate": { + "dnqekb": null + } + }, + "steak.n.01": { + "steak": { + "ppykkp": null + } + }, + "tupperware.n.01": { + "tupperware": { + "mkstwr": [0.25, 0.25, 0.15] + } + } + }, + "blacklist": {} + } + }, + "thawing_frozen_food": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "date.n.08": { + "date": { + "kdfasq": null + } + }, + "lobster.n.01": { + "lobster": { + "fhvrtx": null + } + }, + "olive.n.04": { + "olive": { + "ghjddf": null + } + } + }, + "blacklist": {} + } + }, + "turning_on_radio": { + "room_types": [ + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "radio_receiver.n.01": { + "radio": { + "wxnicr": null + } + } + }, + "blacklist": {} + } + }, + "chop_an_onion": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "parer.n.02": { + "parer": { + "lwpdhi": null + } + }, + "chopping_board.n.01": { + "cutting_board": { + "aibvew": [0.3, 0.2 , 0.02] + } + }, + "bowl.n.01": { + "bowl": { + "aspeds": [0.225, 0.225, 0.075] + } + }, + "vidalia_onion.n.01": { + "vidalia_onion": { + "buyxll": null + } + }, + "countertop.n.01": { + "bar": { + "egwapq": null + } + } + }, + "blacklist": {} + } + }, + "slicing_vegetables": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "beet.n.02": { + "beet": { + "wantjv": null + } + }, + "bell_pepper.n.02": { + "bell_pepper": { + "wszvwc": null + } + }, + "chopping_board.n.01": { + "cutting_board": { + "tcdrzs": null + } + }, + "parer.n.02": { + "parer": { + "lwpdhi": null + } + }, + "zucchini.n.02": { + "zucchini": { + "udvfaz": null + } + }, + "countertop.n.01": { + "countertop": { + "kelzer": null + } + } + }, + "blacklist": {} + } + }, + "chopping_wood": { + "room_types": [ + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "ax.n.01": { + "axe": { + "plqyos": null + } + }, + "chopping_block.n.01": { + "chopping_block": { + "ekowsj":[0.30, 0.27, 0.10] + } + }, + "log.n.01": { + "log": { + "pepele": 0.67 + } + }, + "driveway.n.01": { + "driveway": { + "umalys": null + } + } + }, + "blacklist": {} + } + }, + "cook_eggplant": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "chopping_board.n.01": { + "cutting_board": { + "tcdrzs": null + } + }, + "cookie_sheet.n.01": { + "baking_sheet": { + "yhurut": null + } + }, + "eggplant.n.01": { + "eggplant": { + "gfytkk": null + } + }, + "feta.n.01": { + "feta": { + "gkaitc": [0.09, 0.055, 0.05] + } + }, + "feta__box.n.01": { + "feta_box": { + "qxnzpx": null + } + }, + "parer.n.02": { + "parer": { + "lwpdhi": null + } + } + }, + "blacklist": {} + } + }, + "bringing_in_wood": { + "room_types": [ + "corridor", + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "plywood.n.01": { + "plywood": { + "fkmkqa": [0.07, 0.47, 0.02] + } + }, + "floor.n.01": { + "floors": { + "qadhjb": null, + "xorxro": null + } + } + }, + "blacklist": {} + } + }, + "bringing_water": { + "room_types": [ + "kitchen", + "living_room" + ], + "house_single_floor": { + "whitelist": { + "bottle.n.01": { + "beer_bottle": { + "nigfha": null + } + } + }, + "blacklist": {} + } + }, + "bringing_in_kindling": { + "room_types": [ + "garden", + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "firewood.n.01": { + "firewood": { + "agntyc": null, + "bfalqo": null, + "fpqlgh": null, + "soubgn": null, + "gmwelp": null + } + } + }, + "blacklist": {} + } + }, + "bringing_newspaper_in": { + "room_types": [ + "garden", + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "newspaper.n.03": { + "newspaper": { + "omsont": null + } + } + }, + "blacklist": {} + } + }, + "clean_up_your_desk": { + "room_types": [ + "childs_room" + ], + "house_single_floor": { + "whitelist": { + "folder.n.02": { + "folder": { + "lktggf": null + } + }, + "laptop.n.01": { + "laptop": { + "izydvb": null + } + }, + "paperback_book.n.01": { + "paperback_book": { + "yxujzs": [0.25, 0.19, 0.02] + } + }, + "pen.n.01": { + "pen": { + "gqwdor": [0.15, 0.01, 0.01] + } + }, + "pencil.n.01": { + "pencil": { + "lamaxq": [0.13, 0.01, 0.01] + } + }, + "pencil_box.n.01": { + "pencil_case": { + "otcmih": [0.105, 0.3 , 0.105] + } + }, + "stapler.n.01": { + "stapler": { + "kgnsas": [0.18, 0.04, 0.1] + } + } + }, + "blacklist": {} + } + }, + "moving_boxes_to_storage": { + "room_types": [ + "living_room", + "garage" + ], + "house_double_floor_lower": { + "whitelist": { + "storage_container.n.01": { + "storage_box": { + "izcglf": null + } + } + }, + "blacklist": {} + } + }, + "outfit_a_basic_toolbox": { + "room_types": [ + "utility_room" + ], + "house_single_floor": { + "whitelist": { + "allen_wrench.n.01": { + "allen_wrench": { + "neqlcn": [0.3 , 0.06, 0.02] + } + }, + "drill.n.01": { + "drill": { + "nzgmza": null + } + }, + "flashlight.n.01": { + "flashlight": { + "jtrbkc": null + } + }, + "pliers.n.01": { + "plier": { + "zwzncq": [0.3 , 0.08, 0.02] + } + }, + "screwdriver.n.01": { + "screwdriver": { + "irtslw": null + } + }, + "toolbox.n.01": { + "toolbox": { + "redmtl": null + } + }, + "tabletop.n.01": { + "countertop": { + "fjkase": null + } + } + }, + "blacklist": {} + } + }, + "re_shelving_library_books": { + "room_types": [ + "living_room" + ], + "house_double_floor_upper": { + "whitelist": { + "book.n.02": { + "hardback": { + "okcflv": null, + "acbrnv": null, + "dichmv": null, + "mekfxk": null, + "wfjsog": null, + "rdqqum": null, + "eaktib": null, + "hrxujh": null + } + } + }, + "blacklist": { + "table.n.02": { + "coffee_table": { + "osroux": null + } + } + } + } + }, + "putting_dishes_away_after_cleaning": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "plate.n.04": { + "plate": { + "luhkiz": null, + "ntedfx": null, + "pkkgzc": null, + "lkomhp": null, + "xfjmld": null + } + } + }, + "blacklist": {} + } + }, + "dispose_of_a_pizza_box": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "ashcan.n.01": { + "trash_can": { + "cdzyew": [0.58, 0.48, 0.78] + } + }, + "half__pizza.n.01": { + "half_pizza": { + "frlqiv": [0.235, 0.12 , 0.02] + } + }, + "pizza_box.n.01": { + "pizza_box": { + "hvaucj": [0.39, 0.40, 0.05] + } + } + }, + "blacklist": {} + } + }, + "preparing_lunch_box": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "bottle__of__tea.n.01": { + "bottle_of_tea": { + "iladfg": null + } + }, + "chocolate_chip_cookie.n.01": { + "chocolate_chip_cookie": { + "xprsse": [0.13, 0.13, 0.04] + } + }, + "chopping_board.n.01": { + "chopping_board": { + "afwefw": [0.5 , 0.74, 0.04] + } + }, + "club_sandwich.n.01": { + "club_sandwich": { + "ablfyd": [0.1575, 0.15 , 0.06] + } + }, + "half__apple.n.01": { + "half_apple": { + "qusmpx": null + } + }, + "packing_box.n.02": { + "packing_box": { + "cjhskr": [0.228, 0.282, 0.132] + } + }, + "countertop.n.01": { + "countertop": { + "kelker": null + } + } + }, + "blacklist": {} + } + }, + "loading_the_car": { + "room_types": [ + "living_room", + "garage" + ], + "house_double_floor_lower": { + "whitelist": { + "container.n.01": { + "toy_box": { + "uvhflb": [0.3 , 0.45, 0.15] + } + }, + "digital_camera.n.01": { + "digital_camera": { + "wbzzjl": null + } + }, + "tennis_racket.n.01": { + "tennis_racket": { + "rmvafy": null + } + } + }, + "blacklist": {} + } + }, + "carrying_out_garden_furniture": { + "room_types": [ + "garden", + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "barrow.n.03": { + "wheelbarrow": { + "msaevo": null + } + }, + "lawn_chair.n.01": { + "garden_chair": { + "cottya": null + } + } + }, + "blacklist": {} + } + }, + "tidying_bedroom": { + "room_types": [ + "bedroom" + ], + "house_single_floor": { + "whitelist": { + "book.n.02": { + "hardback": { + "dmqfqx": null + } + }, + "sandal.n.01": { + "sandal": { + "tkfdsk": null, + "txkidl": null + } + } + }, + "blacklist": {} + } + }, + "set_up_a_coffee_station_in_your_kitchen": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "bottle__of__coffee.n.01": { + "bottle_of_coffee": { + "zywanc": [0.078, 0.078, 0.168] + } + }, + "coffee_cup.n.01": { + "coffee_cup": { + "nbhcgu": null + } + }, + "coffee_maker.n.01": { + "coffee_maker": { + "fwlabx": null + } + }, + "electric_kettle.n.01": { + "electric_kettle": { + "hkdsla": null + } + }, + "paper_coffee_filter.n.01": { + "paper_coffee_filter": { + "kizndy": null + } + }, + "saucer.n.02": { + "saucer": { + "vghfkh": null + } + }, + "countertop.n.01": { + "countertop": { + "kelzer": null + } + }, + "shelf.n.01": { + "shelf": { + "pfusrd": null + } + } + }, + "blacklist": {} + } + }, + "collecting_childrens_toys": { + "room_types": [ + "living_room", + "childs_room" + ], + "house_single_floor": { + "whitelist": { + "board_game.n.01": { + "board_game": { + "eoywpy": null, + "gcfkqa": null, + "lzslbu": null + } + }, + "die.n.01": { + "dice": { + "iswudu": [0.04, 0.04, 0.04], + "jommvx": [0.04, 0.04, 0.04] + } + }, + "teddy.n.01": { + "teddy_bear": { + "dgagea": null, + "ecvxmu": null + } + }, + "train_set.n.01": { + "toy_train": { + "zdfhbw": null + } + } + }, + "blacklist": {} + } + }, + "delivering_groceries_to_doorstep": { + "room_types": [ + "corridor", + "garden" + ], + "house_single_floor": { + "whitelist": { + "bread_slice.n.01": { + "bread_slice": { + "yedlgq": null + } + }, + "carton__of__milk.n.01": { + "carton_of_milk": { + "znqqft": null + } + }, + "sack.n.01": { + "paper_bag": { + "bzsxgw": [0.20, 0.30, 0.40] + } + } + }, + "blacklist": {} + } + }, + "gathering_nuts": { + "room_types": [ + "garden" + ], + "house_single_floor": { + "whitelist": { + "bucket.n.01": { + "bucket": { + "bdhvnt": null + } + }, + "walnut.n.01": { + "walnut": { + "fbswir": null, + "rmwtdh": [0.6, 0.6, 0.4] + } + } + }, + "blacklist": {} + } + }, + "put_together_a_basic_pruning_kit": { + "room_types": [ + "garage" + ], + "house_single_floor": { + "whitelist": { + "pruner.n.02": { + "pruner": { + "lucqrs": null + } + }, + "shears.n.01": { + "shears": { + "iizidc": [0.208, 0.08, 0.02] + } + }, + "toolbox.n.01": { + "toolbox": { + "redmtl": null + } + } + }, + "blacklist": {} + } + }, + "sorting_vegetables": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "broccoli.n.02": { + "broccoli": { + "wsxavx": [0.09, 0.09, 0.06] + } + }, + "bok_choy.n.02": { + "bok_choy": { + "bbvcji": null + } + }, + "vidalia_onion.n.01": { + "vidalia_onion": { + "buyxll": null + } + }, + "leek.n.02": { + "leek": { + "fyihsq": null + } + }, + "mixing_bowl.n.01": { + "mixing_bowl": { + "bsgybx": [0.36 , 0.315, 0.165] + } + }, + "sweet_corn.n.02": { + "sweet_corn": { + "qtesku": null + } + }, + "wicker_basket.n.01": { + "wicker_basket": { + "dgkhyn": [0.3, 0.45, 0.19] + } + }, + "countertop.n.01": { + "countertop": { + "kelzer": null + } + } + }, + "blacklist": {} + } + }, + "boxing_books_up_for_storage": { + "room_types": [ + "living_room" + ], + "house_double_floor_upper": { + "whitelist": { + "book.n.02": { + "hardback": { + "okcflv": null, + "acbrnv": null, + "dichmv": null, + "mekfxk": null, + "wfjsog": null, + "rdqqum": null, + "eaktib": null, + "hrxujh": null, + "xkjctf": null, + "yomcyv": null, + "poanfs": null, + "tvydcv": null, + "znlewl": null + } + }, + "box.n.01": { + "storage_box": { + "bwbpvg": [0.48, 0.5 , 0.12] + } + } + }, + "blacklist": {} + } + }, + "putting_shoes_on_rack": { + "room_types": [ + "corridor" + ], + "house_double_floor_lower": { + "whitelist": { + "gym_shoe.n.01": { + "gym_shoe": { + "kmcbym": null, + "mcfcwq": null + } + }, + "sandal.n.01": { + "sandal": { + "dfkzbd": null, + "vwbomj": null + } + }, + "hallstand.n.01": { + "hall_tree": { + "daxzaw": null + } + }, + "floor.n.01": { + "floors": { + "xorxro": null + } + } + }, + "blacklist": {} + } + }, + "clearing_food_from_table_into_fridge": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "half__chicken.n.01": { + "half_chicken": { + "hkcqlq": null + } + }, + "half__apple_pie.n.01": { + "half_apple_pie": { + "grcock": null + } + }, + "plate.n.04": { + "plate": { + "fhdyrj": null + } + }, + "tupperware.n.01": { + "tupperware": { + "mkstwr": null + } + }, + "countertop.n.01": { + "bar": { + "egwapq": null + } + } + }, + "blacklist": {} + } + }, + "storing_food": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "bag__of__chips.n.01": { + "bag_of_chips": { + "bryahw": null + } + }, + "bottle__of__olive_oil.n.01": { + "bottle_of_olive_oil": { + "ajswsh": null + } + }, + "box__of__oatmeal.n.01": { + "box_of_oatmeal": { + "zkggxm": null + } + }, + "jar__of__sugar.n.01": { + "jar_of_sugar": { + "pnbbfb": null + } + }, + "countertop.n.01": { + "countertop": { + "kelzer": null + } + } + }, + "blacklist": {} + } + }, + "getting_organized_for_work": { + "room_types": [ + "bedroom" + ], + "house_double_floor_upper": { + "whitelist": { + "computer.n.01": { + "desktop_computer": { + "eantds": null + } + }, + "monitor.n.04": { + "monitor": { + "qvpbge": null + } + }, + "folder.n.02": { + "folder": { + "guhatz": null + } + }, + "keyboard.n.01": { + "keyboard": { + "injrgc": null + } + }, + "mouse.n.04": { + "mouse": { + "oydobn": [0.09, 0.06, 0.03] + } + }, + "notebook.n.01": { + "notebook": { + "eijrqw": null + } + }, + "pen.n.01": { + "pen": { + "enfumt": null + } + } + }, + "blacklist": {} + } + }, + "setting_the_table": { + "room_types": [ + "kitchen", + "dining_room" + ], + "house_single_floor": { + "whitelist": { + "cupcake.n.01": { + "cupcake": { + "mbhweg": null + } + }, + "plate.n.04": { + "plate": { + "spppps": null + } + }, + "table_knife.n.01": { + "table_knife": { + "jxdfyy": null + } + }, + "tablefork.n.01": { + "tablefork": { + "hktwlm": null + } + } + }, + "blacklist": {} + } + }, + "wash_dog_toys": { + "room_types": [ + "utility_room" + ], + "house_single_floor": { + "whitelist": { + "softball.n.01": { + "softball": { + "erhbze": null + } + }, + "teddy.n.01": { + "teddy_bear": { + "mvwvlv": null + } + }, + "tennis_ball.n.01": { + "tennis_ball": { + "rgekxe": null + } + } + }, + "blacklist": {} + } + }, + "wash_a_baseball_cap": { + "room_types": [ + "utility_room" + ], + "house_single_floor": { + "whitelist": { + "baseball_cap.n.01": { + "baseball_cap": { + "ogptul": null + } + } + }, + "blacklist": {} + } + }, + "clean_boxing_gloves": { + "room_types": [ + "utility_room" + ], + "house_single_floor": { + "whitelist": { + "boxing_glove.n.01": { + "boxing_gloves": { + "jlfuaf": [0.259, 0.175, 0.126] + } + }, + "countertop.n.01": { + "countertop": { + "sjxber": null + } + } + }, + "blacklist": {} + } + }, + "make_pizza": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "carving_knife.n.01": { + "carving_knife": { + "fqqbop": null + } + }, + "chopping_board.n.01": { + "chopping_board": { + "sygezm": [0.22, 0.33, 0.015] + } + }, + "cookie_sheet.n.01": { + "baking_sheet": { + "yhurut": [0.27, 0.30, 0.03] + } + }, + "mushroom.n.05": { + "mushroom": { + "zlukhz": null + } + }, + "pepperoni.n.01": { + "pepperoni": { + "xcurfr": [0.03, 0.03, 0.005] + } + }, + "pizza_dough.n.01": { + "pizza_dough": { + "jguwbv": [0.23, 0.23, 0.005] + } + }, + "tupperware.n.01": { + "tupperware": { + "mkstwr": null + } + }, + "bowl.n.01": { + "bowl": { + "szgdpc": 1.5 + } + }, + "vidalia_onion.n.01": { + "vidalia_onion": { + "buyxll": null + } + } + }, + "blacklist": {} + } + }, + "make_microwave_popcorn": { + "room_types": [ + "kitchen" + ], + "house_double_floor_lower": { + "whitelist": { + "popcorn__bag.n.01": { + "popcorn_bag": { + "hdcpqg": [0.2025, 0.2775, 0.18] + } + } + }, + "blacklist": {} + } + }, + "scrubbing_bathroom_floor": { + "room_types": [ + "bathroom" + ], + "house_double_floor_upper": { + "whitelist": { + "scrub_brush.n.01": { + "scrub_brush": { + "hsejyi": null + } + } + }, + "blacklist": {} + } + }, + "clean_a_felt_pool_table_top": { + "room_types": [ + "living_room" + ], + "house_single_floor": { + "whitelist": { + "scrub_brush.n.01": { + "scrub_brush": { + "hsejyi": null + } + }, + "pool_table.n.01": { + "pool_table": { + "atjfhn": null + } + } + }, + "blacklist": {} + } + }, + "clean_a_rug": { + "room_types": [ + "utility_room" + ], + "house_single_floor": { + "whitelist": { + "rug.n.01": { + "carpet": { + "sehjcp": null + } + }, + "vacuum.n.04": { + "vacuum": { + "bdmsbr": null + } + } + }, + "blacklist": {} + } + }, + "clean_a_patio": { + "room_types": [ + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "broom.n.01": { + "broom": { + "tpyvbt": [0.81, 0.27, 0.06] + } + }, + "floor.n.01": { + "floors": { + "ghetev": null + } + } + }, + "blacklist": {} + } + }, + "attach_a_camera_to_a_tripod": { + "room_types": [ + "bedroom" + ], + "house_double_floor_upper": { + "whitelist": { + "camera_tripod.n.01": { + "camera_tripod": { + "hnpofr": null + } + }, + "digital_camera.n.01": { + "digital_camera": { + "zcnxuz": null + } + } + }, + "blacklist": {} + } + }, + "putting_on_license_plates": { + "room_types": [ + "garden" + ], + "house_single_floor": { + "whitelist": { + "license_plate.n.01": { + "license_plate": { + "nuqnlr": null + } + } + }, + "blacklist": {} + } + }, + "installing_a_fence": { + "room_types": [ + "garden" + ], + "house_double_floor_lower": { + "whitelist": { + "spray_paint__can.n.01": { + "spray_paint_can": { + "pgbbbb": null + } + } + }, + "blacklist": {} + } + }, + "setting_the_fire": { + "room_types": [ + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "cigar_lighter.n.01": { + "lighter": { + "zsxfjz": null + } + }, + "firewood.n.01": { + "firewood": { + "agntyc": null + } + }, + "newspaper.n.03": { + "newspaper": { + "omsont": null + } + } + }, + "blacklist": {} + } + }, + "clean_gas_logs": { + "room_types": [ + "living_room" + ], + "house_double_floor_lower": { + "whitelist": { + "log.n.01": { + "log": { + "pepele": [0.3, 0.1, 0.1] + } + }, + "scrub_brush.n.01": { + "scrub_brush": { + "hsejyi": [0.195, 0.06 , 0.03] + } + } + }, + "blacklist": {} + } + }, + "clean_a_trumpet": { + "room_types": [ + "bedroom" + ], + "house_double_floor_upper": { + "whitelist": { + "cornet.n.01": { + "trumpet": { + "bafgow": null + } + }, + "scrub_brush.n.01": { + "scrub_brush": { + "hsejyi": null + } + }, + "desk.n.01": { + "desk": { + "aduafr": null + } + } + }, + "blacklist": {} + } + }, + "sorting_household_items": { + "room_types": [ + "bathroom", + "bedroom" + ], + "house_single_floor": { + "whitelist": { + "basket.n.01": { + "hamper": { + "drgdfh": null + } + }, + "bottle__of__detergent.n.01": { + "bottle_of_detergent": { + "gkpmii": null, + "qjkmhq": null + } + }, + "box__of__sanitary_napkin.n.01": { + "box_of_sanitary_napkins": { + "zqinib": null + } + }, + "cup.n.01": { + "coffee_cup": { + "ykuftq": [0.135, 0.09 , 0.15] + } + }, + "soap_dispenser.n.01": { + "soap_dispenser": { + "jmulpc": null + } + }, + "soap_dish.n.01": { + "soap_dish": { + "ownvqj": null + } + }, + "toothbrush.n.01": { + "toothbrush": { + "vkrjps": 1.5 + } + }, + "tube__of__toothpaste.n.01": { + "tube_of_toothpaste": { + "vsclsj": null + } + } + }, + "blacklist": {} + } + }, + "cook_hot_dogs": { + "room_types": [ + "kitchen" + ], + "house_single_floor": { + "whitelist": { + "hotdog.n.02": { + "hotdog": { + "lsajfg": null + } + } + }, + "blacklist": {} + } + } +} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/templates/challenge_instance_qc_gui.html b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/templates/challenge_instance_qc_gui.html new file mode 100644 index 0000000000000000000000000000000000000000..fc1fd4cbbb30ece13089cb33a98a40e15c3fc68d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/templates/challenge_instance_qc_gui.html @@ -0,0 +1,871 @@ + + + + + + Challenge Instance QC + + + +
+ +
+
+
+ + +
+
+ + +
+
+
+
+
+ Task floor map + +
+
+ + +
+
+
+
+
+
Did you update the sheet?
+
+ + +
+
+
+
+ +
+
+
+ +
+
+
+
+
+
+
+ + + diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f55deabb26270417f19a2efc7557ea761878f4d6 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/sampling/utils.py @@ -0,0 +1,465 @@ +import torch as th +import csv +import json +import os +import copy +import omnigibson as og +import omnigibson.lazy as lazy +import omnigibson.utils.transform_utils as T +from bddl.knowledge_base import CompiledTask +from omnigibson.objects import DatasetObject +from omnigibson.systems import MicroPhysicalParticleSystem +from omnigibson.utils.asset_utils import get_dataset_path +from omnigibson.macros import gm, macros + + +folder_path = os.path.dirname(os.path.abspath(__file__)) + +SCENE_INFO_FPATH = os.path.join(folder_path, "BEHAVIOR-1K Scenes.csv") + +UNSUPPORTED_PREDICATES = {"broken", "assembled"} + + +def get_scene_model(activity_entry): + """Return the scene model name from a task_custom_lists activity entry.""" + return next(k for k in activity_entry if k != "room_types") + + +def resolve_scene_model(scene_model, scenes_dir): + """Return the actual directory name for scene_model, resolving case mismatches (e.g. rs_int → Rs_int).""" + if os.path.isdir(os.path.join(scenes_dir, scene_model)): + return scene_model + for entry in os.listdir(scenes_dir): + if entry.lower() == scene_model.lower() and os.path.isdir(os.path.join(scenes_dir, entry)): + return entry + return scene_model + + +def prune_unevaluatable_predicates(init_conditions): + pruned_conditions = [] + for condition in init_conditions: + if condition.body[0] in {"insource", "future", "real"}: + continue + pruned_conditions.append(condition) + + return pruned_conditions + + +def get_predicates(conds): + preds = [] + if isinstance(conds, str): + return preds + assert isinstance(conds, list) + contains_list = any(isinstance(ele, list) for ele in conds) + if contains_list: + for ele in conds: + preds += get_predicates(ele) + else: + preds.append(conds[0]) + return preds + + +def get_subjects(conds): + subjs = [] + if isinstance(conds, str): + return subjs + assert isinstance(conds, list) + contains_list = any(isinstance(ele, list) for ele in conds) + if contains_list: + for ele in conds: + subjs += get_subjects(ele) + else: + subjs.append(conds[1]) + return subjs + + +def get_rooms(conds): + rooms = [] + if isinstance(conds, str): + return rooms + assert isinstance(conds, list) + contains_list = any(isinstance(ele, list) for ele in conds) + if contains_list: + for ele in conds: + rooms += get_rooms(ele) + elif conds[0] == "inroom": + rooms.append(conds[2]) + return rooms + + +def get_scenes(): + scenes = set() + with open(SCENE_INFO_FPATH) as csvfile: + reader = csv.reader(csvfile, delimiter=",", quotechar='"') + for i, row in enumerate(reader): + # Skip first row since it's the header + if i == 0: + continue + scenes.add(row[0]) + + return tuple(sorted(scenes)) + + +def get_valid_tasks(): + from omnigibson.utils.bddl_utils import get_behavior_activities + + return set(get_behavior_activities()) + + +def get_all_lights(prim): + prims = [] + for child in prim.GetChildren(): + if "Light" in child.GetPrimTypeInfo().GetTypeName(): + prims.append(child) + prims += get_all_lights(child) + + return prims + + +def hide_all_lights(): + with og.sim.editing_usd(): + lights = get_all_lights(prim=og.sim.world_prim) + for light in lights: + imageable = lazy.pxr.UsdGeom.Imageable(light) + imageable.MakeInvisible() + + +def parse_task_mapping_new(): + if os.path.exists("task_mapping.json"): + with open("task_mapping.json", "r") as f: + mapping = json.load(f) + return mapping + + from omnigibson.utils.bddl_utils import get_knowledge_base + + tasks = get_knowledge_base().all_tasks() + mapping = dict() + for task in tasks: + task_name = task.name[:-2] + scenes = [] + for scene, status in task.scene_matching_dict.items(): + if status["matched"]: + scenes.append(scene.name) + mapping[task_name] = scenes + with open("task_mapping.json", "w") as f: + json.dump(mapping, f, indent=4) + return mapping + + +def get_scene_compatible_activities(scene_model, mapping): + return [activity for activity, scenes in mapping.items() if scene_model in scenes] + + +def _validate_object_state_stability(obj_name, obj_dict, strict=False): + lin_vel_threshold = 0.001 if strict else 1.0 + ang_vel_threshold = 0.005 if strict else th.pi + joint_vel_threshold = 0.01 if strict else 1.0 + # Check close to zero root link velocity + for key, atol in zip(("lin_vel", "ang_vel"), (lin_vel_threshold, ang_vel_threshold)): + val = obj_dict["root_link"].get(key, th.tensor(0.0)) + if not isinstance(val, th.Tensor): + val = th.tensor(val) + if not th.all(th.isclose(val, th.tensor(0.0), atol=atol, rtol=0.0)).item(): + raise ValueError(f"{obj_name} root link {key} is not close to 0: {val}") + + # Check close to zero joint velocities + if "joint_vel" in obj_dict.keys(): + val = obj_dict["joint_vel"] + if not isinstance(val, th.Tensor): + val = th.tensor(val) + if not th.all(th.isclose(val, th.tensor(0.0), atol=joint_vel_threshold, rtol=0.0)).item(): + raise ValueError(f"{obj_name} joint velocity is not close to 0: {val}") + + # If all passes, return True + return True + + +def create_stable_scene_json(scene_model): + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": scene_model, + }, + } + + # Disable sleeping + macros.prims.entity_prim.DEFAULT_SLEEP_THRESHOLD = 0.0 + + # Create the environment + env = og.Environment(configs=copy.deepcopy(cfg)) + + # Take a few steps to let objects settle, then update the scene initial state + for _ in range(300): + og.sim.step() + + # Sanity check for zero velocities for all objects + stable_state = og.sim.dump_state()[0] + if "registry" in stable_state: + stable_state = stable_state["registry"] + for obj_name, obj_info in stable_state["object_registry"].items(): + _validate_object_state_stability(obj_name, obj_info, strict=False) + for obj in env.scene.objects: + obj.keep_still() + env.scene.update_initial_file() + + # Save this as a stable file + path = os.path.join( + get_dataset_path("behavior-1k-assets"), "scenes", env.scene.scene_model, "json", f"{scene_model}_stable.json" + ) + og.sim.save(json_paths=[path]) + + og.sim.stop() + og.clear() + + +def validate_task(task, task_scene_dict, default_scene_dict, active_room_instances=None): + assert og.sim.is_playing() + + if active_room_instances is None: + conditions = task._base_conditions + relevant_rooms = set(get_rooms(conditions.parsed_initial_conditions)) + relevant_room_instances = None + else: + relevant_rooms = None + relevant_room_instances = set(active_room_instances) + active_obj_names = set() + for obj in og.sim.scenes[0].objects: + if isinstance(obj, DatasetObject): + if relevant_room_instances is None: + obj_rooms = {"_".join(room.split("_")[:-1]) for room in obj.in_rooms} + active = len(relevant_rooms.intersection(obj_rooms)) > 0 or obj.category in {"floors", "walls"} + else: + active = len(relevant_room_instances.intersection(obj.in_rooms)) > 0 or obj.category in { + "floors", + "walls", + } + if active: + active_obj_names.add(obj.name) + + # 1. Sanity check all object poses wrt their original pre-loaded poses + print("Step 1: Checking loaded task environment...") + + def _validate_identical_object_kinematic_state(obj_name, default_obj_dict, obj_dict, check_vel=True): + # Check root link state + for key, val in default_obj_dict["root_link"].items(): + # Skip velocities if requested + if not check_vel and "vel" in key: + continue + obj_val = obj_dict["root_link"][key] + val = th.tensor(val) if not isinstance(val, th.Tensor) else val + obj_val = th.tensor(obj_val) if not isinstance(obj_val, th.Tensor) else obj_val + atol = 1.0 if "vel" in key else 0.05 + # # TODO: Update ori value to be larger tolerance + # tol = 0.15 if "ori" in key else 0.05 + # If particle positions are being checked, only check the min / max + if "particle" in key: + # Only check particle position + if "position" in key: + pos_min, pos_max = th.min(val, dim=0), th.max(val, dim=0) + curr_pos_min, curr_pos_max = ( + th.min(obj_val, dim=0), + th.max(obj_val, dim=0), + ) + for name, pos, curr_pos in zip(("min", "max"), (pos_min, pos_max), (curr_pos_min, curr_pos_max)): + if not th.all(th.isclose(pos, curr_pos, atol=0.05)).item(): + raise ValueError( + f"Got mismatch in cloth {obj_name} particle positions range: {name} min {pos_min} max {pos_max} vs. min {curr_pos_min} max {curr_pos_max}" + ) + else: + continue + else: + if key == "ori": + if not th.all( + th.isclose(T.quat_distance(val, obj_val), th.tensor([0.0, 0.0, 0.0, 1.0]), atol=atol) + ).item(): + raise ValueError( + f"{obj_name} root link mismatch in {key}: default_obj_dict has: {val}, obj_dict has: {obj_val}" + ) + else: + if not th.all(th.isclose(val, obj_val, atol=atol, rtol=0.0)).item(): + raise ValueError( + f"{obj_name} root link mismatch in {key}: default_obj_dict has: {val}, obj_dict has: {obj_val}" + ) + + # Check any non-robot joint values + # This is because the controller can cause the robot to drift over time + if "robot" not in obj_name: + # Check joint states + if "joint_pos" in default_obj_dict.keys(): + for key in ("pos", "vel"): + val = default_obj_dict[f"joint_{key}"] + obj_val = obj_dict[f"joint_{key}"] + atol = 1.0 if key == "vel" else 0.05 + if not isinstance(val, th.Tensor): + val = th.tensor(val) + if not isinstance(obj_val, th.Tensor): + obj_val = th.tensor(obj_val) + if not th.all(th.isclose(val, obj_val, atol=atol, rtol=0.0)).item(): + raise ValueError( + f"{obj_name} joint mismatch in {key}: default_obj_dict has: {val}, obj_dict has: {obj_val}" + ) + + # If all passes, return True + return True + + task_state_t0 = og.sim.dump_state(serialized=False)[0] + if "registry" in task_state_t0: + task_state_t0 = task_state_t0["registry"] + for obj_name, obj_info in task_scene_dict["state"]["registry"]["object_registry"].items(): + current_obj_info = task_state_t0["object_registry"][obj_name] + _validate_identical_object_kinematic_state(obj_name, obj_info, current_obj_info, check_vel=True) + + # We should never use this after + task_scene_dict = None + + # 2. Validate the native USDs jsons are stable and similar -- compare all object kinematics (poses, joint + # states) with respect to the native scene file + print("Step 2: Checking poses and joint states for non-task-relevant objects and velocities for all objects...") + + # Sanity check all non-task-relevant object poses + for obj_name, default_obj_info in default_scene_dict["state"]["registry"]["object_registry"].items(): + # Skip any active objects since they may have changed + if obj_name in active_obj_names: + continue + # HACK: need to skip objects in default scene when partial loading during sampling + if obj_name not in task_state_t0["object_registry"]: + continue + obj_info = task_state_t0["object_registry"][obj_name] + _validate_identical_object_kinematic_state(obj_name, default_obj_info, obj_info, check_vel=True) + + # Sanity check for zero velocities for all objects + for obj_name, obj_info in task_state_t0["object_registry"].items(): + _validate_object_state_stability(obj_name, obj_info, strict=False) + + # Need to enable transition rules before running step 3 and 4 + original_transition_rule_flag = gm.ENABLE_TRANSITION_RULES + with gm.unlocked(): + gm.ENABLE_TRANSITION_RULES = True + + # 3. Validate object set is consistent (no faulty transition rules occurring) -- we expect the number + # of active systems (and number of active particles) and the number of objects to be the same after + # taking a physics step, and also make sure init state is True + print("Step 3: Checking BehaviorTask initial conditions and scene stability...") + # Take a single physics step + og.sim.step() + task_state_t1 = og.sim.dump_state(serialized=False)[0] + if "registry" in task_state_t1: + task_state_t1 = task_state_t1["registry"] + + def _validate_scene_stability(task, task_state, current_state, check_particle_positions=True): + def _validate_particle_system_consistency( + system_name, system_state, current_system_state, check_particle_positions=True + ): + is_micro_physical = isinstance(og.sim.scenes[0].get_system(system_name), MicroPhysicalParticleSystem) + n_particles_key = "instancer_particle_counts" if is_micro_physical else "n_particles" + if ( + is_micro_physical + and not ( + th.isclose( + th.tensor(system_state[n_particles_key]), + th.tensor(current_system_state[n_particles_key]), + ).all() + ) + ) or (not is_micro_physical and system_state[n_particles_key] != current_system_state[n_particles_key]): + raise ValueError( + f"Got inconsistent number of system {system_name} particles: {system_state[n_particles_key]} vs. {current_system_state[n_particles_key]}" + ) + + # Validate that no particles went flying -- maximum ranges of positions should be roughly close + n_particles = ( + th.tensor(system_state[n_particles_key]).sum().item() + if is_micro_physical + else system_state[n_particles_key] + ) + if n_particles > 0 and check_particle_positions: + if is_micro_physical: + particle_positions = th.concatenate( + [inst_state["particle_positions"] for inst_state in system_state["particle_states"].values()], + dim=0, + ) + current_particle_positions = th.concatenate( + [ + inst_state["particle_positions"] + for inst_state in current_system_state["particle_states"].values() + ], + dim=0, + ) + else: + particle_positions = system_state["positions"].detach().clone() + current_particle_positions = current_system_state["positions"].detach().clone() + pos_min, pos_max = th.min(particle_positions, dim=0).values, th.max(particle_positions, dim=0).values + curr_pos_min, curr_pos_max = ( + th.min(current_particle_positions, dim=0).values, + th.max(current_particle_positions, dim=0).values, + ) + for name, pos, curr_pos in zip(("min", "max"), (pos_min, pos_max), (curr_pos_min, curr_pos_max)): + if not th.all(th.isclose(pos, curr_pos, atol=0.05)).item(): + raise ValueError( + f"Got mismatch in system {system_name} particle positions range: {name} {pos} vs. {curr_pos}" + ) + + return True + + # Sanity check consistent objects + task_objects = {obj_name for obj_name in task_state["object_registry"].keys()} + curr_objects = {obj_name for obj_name in current_state["object_registry"].keys()} + mismatched_objs = set.union(task_objects, curr_objects) - set.intersection(task_objects, curr_objects) + if len(mismatched_objs) > 0: + raise ValueError(f"Got mismatch in active objects: {mismatched_objs}") + + for obj_name, obj_info in task_state["object_registry"].items(): + current_obj_info = current_state["object_registry"][obj_name] + _validate_identical_object_kinematic_state(obj_name, obj_info, current_obj_info, check_vel=True) + + # Sanity check consistent particle systems + task_systems = {system_name for system_name in task_state["system_registry"].keys() if system_name != "cloth"} + curr_systems = { + system_name for system_name in current_state["system_registry"].keys() if system_name != "cloth" + } + mismatched_systems = set.union(task_systems, curr_systems) - set.intersection(task_systems, curr_systems) + if len(mismatched_systems) > 0: + raise ValueError(f"Got mismatch in active systems: {mismatched_systems}") + + for system_name in task_systems: + system_state = task_state["system_registry"][system_name] + curr_system_state = current_state["system_registry"][system_name] + _validate_particle_system_consistency( + system_name, system_state, curr_system_state, check_particle_positions=check_particle_positions + ) + + # Sanity check initial state + valid_init_state, results = CompiledTask.evaluate_conditions( + prune_unevaluatable_predicates(task.activity_initial_conditions), task._evaluate_predicate + ) + if not valid_init_state: + raise ValueError(f"BDDL Task init conditions were invalid. Results: {results}") + + return True + + # Sanity check scene + _validate_scene_stability( + task=task, task_state=task_state_t0, current_state=task_state_t1, check_particle_positions=True + ) + + # 4. Validate longer-term stability -- take N=10 timesteps, and make sure all object positions and velocities + # are still stable (positions don't drift too much, and velocities are close to 0), as well as verifying + # that all BDDL conditions are satisfied + print("Step 4: Checking longer-term BehaviorTask initial conditions and scene stability...") + + # Take 10 steps + for _ in range(10): + og.sim.step() + + # Sanity check scene + # Don't check particle positions since some particles may be falling + # TODO: Tighten this constraint once we figure out a way to stably sample particles + task_state_t11 = og.sim.dump_state(serialized=False)[0] + if "registry" in task_state_t11: + task_state_t11 = task_state_t11["registry"] + _validate_scene_stability( + task=task, task_state=task_state_t0, current_state=task_state_t11, check_particle_positions=False + ) + with gm.unlocked(): + gm.ENABLE_TRANSITION_RULES = original_transition_rule_flag + + return True diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/setup.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..220517f5f02317ec71a33e77f841915d7683cc83 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/setup.py @@ -0,0 +1,95 @@ +# read the contents of your README file +from os import path + +from setuptools import find_packages, setup + +this_directory = path.abspath(path.dirname(__file__)) +with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: + lines = f.readlines() + +# remove images from README +lines = [x for x in lines if ".png" not in x] +long_description = "".join(lines) + +setup( + name="omnigibson", + version="3.9.3", + author="Stanford University", + long_description_content_type="text/markdown", + long_description=long_description, + url="https://github.com/StanfordVL/BEHAVIOR-1K", + zip_safe=False, + packages=find_packages(), + install_requires=[ + "huggingface-hub[cli]>=0.34.4", + "gymnasium>=0.28.1", + "numpy<2.0.0,>=1.23.5", + "scipy>=1.10.1", + "GitPython>=3.1.40", + "transforms3d>=0.4.1", + "networkx>=3.2.1", + "PyYAML>=6.0.1", + "addict>=2.4.0", + "ipython>=8.20.0", + "future>=0.18.3", + "trimesh>=4.0.8", + "h5py>=3.10.0", + "cryptography>=41.0.7", + "bddl~=3.7.0", + "opencv-python>=4.8.1", + "nest_asyncio>=1.5.6", + "imageio>=2.33.1", + "imageio-ffmpeg>=0.4.9", + "termcolor>=2.4.0", + "progressbar>=2.5", + "pymeshlab~=2022.2; platform_machine!='aarch64'", + "pymeshlab>=2022.2; platform_machine=='aarch64'", + "click>=8.1.3", + "aenum>=3.1.15", + "rtree>=1.2.0", + "graphviz>=0.20", + "matplotlib>=3.0.0", + "lxml>=5.2.2", + "numba>=0.59.1", + "cffi==1.17.1", + "pillow~=11.0.0", + "websockets>=15.0.1", + "omegaconf>=2.3.0", + "lerobot[dataset] @ git+https://github.com/wensi-ai/lerobot@release/b1k", + ], + extras_require={ + "dev": [ + "pytest>=6.2.3", + "pytest-cov>=3.0.0", + "pytest_rerunfailures", + "pyright>=1.1.390", + "mkdocs", + "mkdocs-autorefs", + "mkdocs-gen-files", + "mkdocs-material", + "mkdocs-material-extensions", + "mkdocstrings[python]", + "mkdocs-section-index", + "mkdocs-literate-nav", + "mkdocs-redirects", + "mkdocs-include-markdown-plugin", + "telemoma~=0.3.0", + "gspread>=6.2.1", + ], + "primitives": [ + "ninja~=1.13.0", + "warp-lang==1.12.0", + "nvidia-curobo @ git+https://github.com/StanfordVL/curobo@78612f45cef52c3fa0298de243a54cd7ca614414", + ], + "eval": [ + "dm_tree>=0.1.9", + "hydra-core>=1.3.2", + "msgpack>=1.1.0", + "gspread>=6.2.1", + "open3d>=0.19.0", + ] + }, + tests_require=[], + python_requires=">=3", + include_package_data=True, +) # yapf: disable diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/benchmark_interactive_scene.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/benchmark_interactive_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..4daa0140e0efcb45bcd5f79f567692aec12fa4a3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/benchmark_interactive_scene.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python + +import os +import time + +import matplotlib.pyplot as plt +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.objects import DatasetObject +from omnigibson.robots.robot import Robot +from omnigibson.scenes.interactive_traversable_scene import InteractiveTraversableScene +from omnigibson.utils.asset_utils import get_behavior_1k_assets_version +from omnigibson.utils.constants import PrimType + +# Params to be set as needed. +SCENES = ["Rs_int"] # house_single_floor +OUTPUT_DIR = os.path.join(os.path.expanduser("~"), "Desktop") +NUM_STEPS = 2000 + +gm.HEADLESS = False +gm.GUI_VIEWPORT_ONLY = True +gm.RENDER_VIEWER_CAMERA = False +gm.USE_GPU_DYNAMICS = False +gm.ENABLE_OBJECT_STATES = False +gm.ENABLE_TRANSITION_RULES = False +gm.DEFAULT_VIEWER_WIDTH = 128 +gm.DEFAULT_VIEWER_HEIGHT = 128 + + +# Launch the simulator +og.launch(physics_dt=1 / 60.0, rendering_dt=1 / 60.0) + + +def benchmark_scene(scene_name, non_rigid_simulation=False, import_robot=True): + assets_version = get_behavior_1k_assets_version() + print("dataset version", assets_version) + scene = InteractiveTraversableScene(scene_name) + start = time.time() + og.sim.import_scene(scene) + + if gm.RENDER_VIEWER_CAMERA: + og.sim.viewer_camera.set_position_orientation(position=[0, 0, 0.2], orientation=[0.5, -0.5, -0.5, 0.5]) + print(time.time() - start) + + if import_robot: + turtlebot = Robot(model="turtlebot", relative_prim_path="/robot", name="agent", obs_modalities=["rgb"]) + scene.add_object(turtlebot) + og.sim.step() + + if non_rigid_simulation: + cloth = DatasetObject( + name="cloth", + relative_prim_path="/cloth", + category="t_shirt", + model="kvidcx", + prim_type=PrimType.CLOTH, + abilities={"cloth": {}}, + bounding_box=[0.3, 0.5, 0.7], + ) + scene.add_object(cloth) + og.sim.step() + water_system = scene.get_system("water") + for i in range(100): + water_system.generate_particles(positions=[th.tensor([0.5, 0, 0.5]) + th.randn(3) * 0.1]) + og.sim.step() + + og.sim.play() + if non_rigid_simulation: + cloth.set_position_orientation(position=[1, 0, 1]) + og.sim.step() + fps = [] + physics_fps = [] + render_fps = [] + print(len(scene.objects)) + for i in range(NUM_STEPS): + start = time.time() + if import_robot: + # Apply random actions. + turtlebot.apply_action(th.zeros(2)) + og.sim.step(render=False) + physics_end = time.time() + + og.sim.render() + end = time.time() + + if i % 100 == 0: + print("Elapsed time: ", end - start) + print("Render Frequency: ", 1 / (end - physics_end)) + print("Physics Frequency: ", 1 / (physics_end - start)) + print("Step Frequency: ", 1 / (end - start)) + fps.append(1 / (end - start)) + physics_fps.append(1 / (physics_end - start)) + render_fps.append(1 / (end - physics_end)) + + plt.figure(figsize=(7, 25)) + ax = plt.subplot(6, 1, 1) + plt.hist(render_fps) + ax.set_xlabel("Render fps") + ax.set_title( + "Scene {} version {}\nnon_physics {} num_obj {}\n import_robot {}".format( + scene_name, assets_version, non_rigid_simulation, scene.n_objects, import_robot + ) + ) + ax = plt.subplot(6, 1, 2) + plt.hist(physics_fps) + ax.set_xlabel("Physics fps") + ax = plt.subplot(6, 1, 3) + plt.hist(fps) + ax.set_xlabel("Step fps") + ax = plt.subplot(6, 1, 4) + plt.plot(render_fps) + ax.set_xlabel("Render fps with time, converge to {}".format(th.mean(render_fps[-100:]))) + ax.set_ylabel("fps") + ax = plt.subplot(6, 1, 5) + plt.plot(physics_fps) + ax.set_xlabel("Physics fps with time, converge to {}".format(th.mean(physics_fps[-100:]))) + ax.set_ylabel("fps") + ax = plt.subplot(6, 1, 6) + plt.plot(fps) + ax.set_xlabel("Overall fps with time, converge to {}".format(th.mean(fps[-100:]))) + ax.set_ylabel("fps") + plt.tight_layout() + plt.savefig( + os.path.join( + OUTPUT_DIR, "scene_benchmark_{}_np_{}_r_{}.pdf".format(scene_name, non_rigid_simulation, import_robot) + ) + ) + + +def main(): + for scene in SCENES: + benchmark_scene(scene, non_rigid_simulation=False, import_robot=True) + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/benchmark_object_count.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/benchmark_object_count.py new file mode 100644 index 0000000000000000000000000000000000000000..98e5d34a53e5c11ab8e476d57d853eb1b534f0dd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/benchmark_object_count.py @@ -0,0 +1,104 @@ +""" +Script to benchmark speed vs. no. of objects in the scene. +""" + +import math +import os +import time + +import matplotlib.pyplot as plt +import torch as th + +from omnigibson import app, launch +from omnigibson.objects.primitive_object import PrimitiveObject +from omnigibson.scenes.scene_base import Scene +from omnigibson.utils.asset_utils import get_behavior_1k_assets_version + +# Params to be set as needed. +MAX_NUM_OBJS = 400 # Maximum no. of objects to add. +NUM_OBJS_PER_ITER = 20 # No. of objects to add per iteration. +NUM_STEPS_PER_ITER = 30 # No. of steps to take for each n of objects. +OBJ_SCALE = 0.05 # Object scale to be set appropriately to sim collisions. +RAND_POSITION = True # True to randomize positions. +OUTPUT_DIR = os.path.join(os.path.expanduser("~"), "Desktop") + +# Internal constants. +_N_PER_ROW = int(math.sqrt(MAX_NUM_OBJS)) +_MIN_VAL = -2.0 +_MAX_VAL = 2.0 +_STEP_SIZE = (_MAX_VAL - _MIN_VAL) / _N_PER_ROW + + +def _get_position(obj_idx, is_random=False): + if is_random: + pos_arange = th.arange(_MIN_VAL, _MAX_VAL, step=0.1, dtype=th.float32) + x, y, z = pos_arange[th.randint(len(pos_arange), (3,))] + return x, y, z + x = _MIN_VAL + _STEP_SIZE * (obj_idx % _N_PER_ROW) + y = _MIN_VAL + _STEP_SIZE * (obj_idx // _N_PER_ROW) + return x, y, 0.1 + + +def benchmark_scene(sim): + assets_version = get_behavior_1k_assets_version() + print("dataset version", assets_version) + + scene = Scene() + sim.import_scene(scene) + sim.play() + + xs = [] + ys = [] + yerrs = [] + for i in range(MAX_NUM_OBJS // NUM_OBJS_PER_ITER): + new_objs = [] + for j in range(NUM_OBJS_PER_ITER): + obj_idx = i * NUM_OBJS_PER_ITER + j + obj = PrimitiveObject( + relative_prim_path=f"/obj{obj_idx}", + primitive_type="Sphere", + name=f"obj{obj_idx}", + scale=OBJ_SCALE, + visual_only=False, + ) + scene.add_object(obj=obj, auto_initialize=False) + # x, y, z = _get_position(obj_idx, RAND_POSITION) + x, y = 0, 0 + z = 0.5 + j * OBJ_SCALE * 2.25 + obj.set_position_orientation(position=th.tensor([x, y, z])) + new_objs.append(obj) + + # Take a step to initialize the new objects (done in _non_physics_step()). + sim.step() + step_freqs = [] + for _ in range(NUM_STEPS_PER_ITER): + start = time.time() + sim.step() + end = time.time() + step_freqs.append(1 / (end - start)) + + xs.append(i * NUM_OBJS_PER_ITER) + max_freq, min_freq = th.max(step_freqs).item(), th.min(step_freqs).item() + ys.append(th.mean((max_freq, min_freq))) + yerrs.append(max_freq - ys[-1]) + + plt.figure(figsize=(9, 6)) + ax = plt.subplot(1, 1, 1) + plt.errorbar(xs, ys, yerr=yerrs, elinewidth=0.75) + ax.set_xlabel("No. of objects") + ax.set_ylabel("Step fps") + ax.set_title(f"Version {assets_version}") + plt.tight_layout() + plt.savefig(os.path.join(OUTPUT_DIR, f"scene_objs_benchmark_{MAX_NUM_OBJS}_{OBJ_SCALE}.png")) + + +def main(): + assert MAX_NUM_OBJS <= 1000 + + sim = launch() + benchmark_scene(sim) + app.close() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/profiling.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..6030a5ea168b7ebb15c14a5096f56d426d720d6d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/profiling.py @@ -0,0 +1,259 @@ +import argparse +import cProfile +import json +import math +import os +import time + +import psutil +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.object_states import Covered +from omnigibson.utils.constants import PrimType +from omnigibson.utils.profiling_utils import get_vram_usage + +parser = argparse.ArgumentParser() + +parser.add_argument("-r", "--robot", type=int, default=0) +parser.add_argument("-s", "--scene", default="") +parser.add_argument("-c", "--cloth", action="store_true") +parser.add_argument("-w", "--fluids", action="store_true") +parser.add_argument("-g", "--gpu_dynamics", action="store_true") +parser.add_argument("-p", "--macro_particle_system", action="store_true") +parser.add_argument("-d", "--deep-profiling", action="store_true") + +PROFILING_FIELDS = ["FPS", "Isaac step time", "Non-Isaac step time", "Memory usage", "Vram usage"] +NUM_CLOTH = 5 +NUM_SLICE_OBJECT = 3 + +SCENE_OFFSET = { + "": [0, 0], + "Rs_int": [0, 0], + "Pomaria_0_garden": [0.3, 0], + "grocery_store_cafe": [-3.5, 3.5], + "house_single_floor": [-3, -1], + "Ihlen_0_int": [-1, 2], +} + + +def main(): + args = parser.parse_args() + # Modify macros settings + # gm.ENABLE_HQ_RENDERING = args.fluids # Temporarily disabled, since it requires >= 60 FPS + gm.ENABLE_OBJECT_STATES = True + gm.ENABLE_TRANSITION_RULES = True + gm.USE_GPU_DYNAMICS = args.gpu_dynamics + gm.ENABLE_DEEP_PROFILING = args.deep_profiling + + cfg = { + "env": { + "action_frequency": 30, + "physics_frequency": 120, + } + } + if args.robot > 0: + cfg["robots"] = [] + for i in range(args.robot): + cfg["robots"].append( + { + "model": "r1pro", + "obs_modalities": ["rgb"], + "position": [-1.3 + 0.75 * i + SCENE_OFFSET[args.scene][0], 0.5 + SCENE_OFFSET[args.scene][1], 0], + "orientation": [0.0, 0.0, 0.7071, -0.7071], + } + ) + + if args.scene: + assert args.scene in SCENE_OFFSET, f"Scene {args.scene} not found in SCENE_OFFSET" + cfg["scene"] = { + "type": "InteractiveTraversableScene", + "scene_model": args.scene, + } + else: + cfg["scene"] = {"type": "Scene"} + + cfg["objects"] = [ + { + "type": "DatasetObject", + "name": "table", + "category": "breakfast_table", + "model": "rjgmmy", + "fixed_base": True, + "scale": [0.75] * 3, + "position": [0.5 + SCENE_OFFSET[args.scene][0], -1 + SCENE_OFFSET[args.scene][1], 0.3], + "orientation": [0.0, 0.0, 0.7071, -0.7071], + } + ] + + if args.cloth: + cfg["objects"].extend( + [ + { + "type": "DatasetObject", + "name": f"cloth_{n}", + "category": "t_shirt", + "model": "kvidcx", + "prim_type": PrimType.CLOTH, + "abilities": {"cloth": {}}, + "bounding_box": [0.3, 0.5, 0.7], + "position": [-0.4, -1, 0.7 + n * 0.4], + "orientation": [0.7071, 0.0, 0.7071, 0.0], + } + for n in range(NUM_CLOTH) + ] + ) + + cfg["objects"].extend( + [ + { + "type": "DatasetObject", + "name": f"apple_{n}", + "category": "apple", + "model": "agveuv", + "scale": [1.5] * 3, + "position": [0.5 + SCENE_OFFSET[args.scene][0], -1.25 + SCENE_OFFSET[args.scene][1] + n * 0.2, 0.5], + "abilities": {"diceable": {}} if args.macro_particle_system else {}, + } + for n in range(NUM_SLICE_OBJECT) + ] + ) + cfg["objects"].extend( + [ + { + "type": "DatasetObject", + "name": f"knife_{n}", + "category": "table_knife", + "model": "jxdfyy", + "scale": [2.5] * 3, + } + for n in range(NUM_SLICE_OBJECT) + ] + ) + + load_start = time.time() + + # Launch OG before setting up the profiler. If we don't do this then the carb profiler + # overtakes the profiler and we don't get any useful data. + og.launch() + + if args.deep_profiling: + load_profiler = cProfile.Profile() + load_profiler.enable() + env = og.Environment(configs=cfg) + table = env.scene.object_registry("name", "table") + apples = [env.scene.object_registry("name", f"apple_{n}") for n in range(NUM_SLICE_OBJECT)] + knifes = [env.scene.object_registry("name", f"knife_{n}") for n in range(NUM_SLICE_OBJECT)] + if args.cloth: + clothes = [env.scene.object_registry("name", f"cloth_{n}") for n in range(NUM_CLOTH)] + for cloth in clothes: + cloth.root_link.mass = 1.0 + env.reset() + + for n, knife in enumerate(knifes): + knife.set_position_orientation( + position=apples[n].get_position_orientation()[0] + th.tensor([-0.15, 0.0, 0.1 * (n + 2)]), + orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)), + ) + knife.keep_still() + if args.fluids: + table.states[Covered].set_value(env.scene.get_system("water"), True) + + output = [] + + # Update the simulator's viewer camera's pose so it points towards the robot + og.sim.viewer_camera.set_position_orientation( + position=[SCENE_OFFSET[args.scene][0], -3 + SCENE_OFFSET[args.scene][1], 1] + ) + # record total load time + if args.deep_profiling: + load_profiler.disable() + load_profiler.dump_stats("load.prof") + total_load_time = time.time() - load_start + + # Reset profiler counters so we only measure the benchmark loop + og.sim._step_profiler.reset() + og.sim._pre_physics_step_profiler.reset() + og.sim._post_physics_step_profiler.reset() + og.sim._non_physics_step_profiler.reset() + + # Get robots from scene 0 (profiling always uses single scene) + scene_robots = env.robots[0] + for i in range(300): + if args.robot: + action_lo, action_hi = -0.3, 0.3 + env.step( + th.stack( + [th.rand(robot.action_dim) * (action_hi - action_lo) + action_lo for robot in scene_robots] + ).flatten() + ) + else: + env.step(None) + + # Compute timing metrics from simulator profilers (convert to ms) + n_steps = og.sim._step_profiler.call_count + avg_total_ms = og.sim._step_profiler.average_time * 1e3 + avg_og_ms = ( + ( + og.sim._pre_physics_step_profiler.total_time + + og.sim._post_physics_step_profiler.total_time + + og.sim._non_physics_step_profiler.total_time + ) + / n_steps + * 1e3 + ) + avg_isaac_ms = avg_total_ms - avg_og_ms + memory_usage = psutil.Process(os.getpid()).memory_info().rss / 1024**3 + vram_usage = get_vram_usage() + + result_values = [avg_total_ms, avg_isaac_ms, avg_og_ms, memory_usage, vram_usage] + + if n_steps % 100 == 0 or n_steps == 300: + print( + "total time: {:.3f} ms, Isaac time: {:.3f} ms, Non-Isaac time: {:.3f} ms, memory: {:.3f} GB, vram: {:.3f} GB.".format( + *result_values + ) + ) + + field = f"{args.scene}" if args.scene else "Empty scene" + if args.robot: + field += f", with {args.robot} Fetch" + if args.cloth: + field += ", cloth" + if args.fluids: + field += ", fluids" + if args.macro_particle_system: + field += ", macro particles" + output.append( + {"name": field, "unit": "time (ms)", "value": total_load_time, "extra": ["Loading time", "Loading time"]} + ) + for i, title in enumerate(PROFILING_FIELDS): + unit = "time (ms)" if "time" in title else "GB" + value = result_values[i] + if title == "FPS": + value = 1000 / value + unit = "fps" + output.append({"name": field, "unit": unit, "value": value, "extra": [title, title]}) + + ret = [] + if os.path.exists("output.json"): + with open("output.json", "r") as f: + ret = json.load(f) + ret.extend(output) + with open("output.json", "w") as f: + json.dump(ret, f, indent=4) + + # Save the simulation profilers + if args.deep_profiling: + og.sim._step_profiler.dump_stats("step.prof") + og.sim._pre_physics_step_profiler.dump_stats("pre_physics_step.prof") + og.sim._post_physics_step_profiler.dump_stats("post_physics_step.prof") + og.sim._non_physics_step_profiler.dump_stats("non_physics_step.prof") + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/vector_profiling.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/vector_profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..23331b76a915202a57d3e9a9a9e047ba65a000a3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/benchmark/vector_profiling.py @@ -0,0 +1,216 @@ +import argparse +import cProfile +import json +import os +import time + +import psutil +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.utils.profiling_utils import get_vram_usage + +parser = argparse.ArgumentParser() +parser.add_argument("-n", "--n-envs", type=int, default=1) +parser.add_argument("-r", "--rendering", action="store_true") +parser.add_argument("-t", "--task-type", choices=["simple", "behavior", "navigation"], default="simple") +parser.add_argument("-o", "--object-states", action="store_true") +parser.add_argument("-g", "--gpu-dynamics", action="store_true") +parser.add_argument("-d", "--deep-profiling", action="store_true") + +NUM_STEPS = 300 + +# Activity used for the "behavior" task type; must have a pre-sampled template for the scene below. +BEHAVIOR_ACTIVITY_NAME = "bringing_water" + + +def apply_macros(args): + # BehaviorTask relies on object states (and transition rules) to evaluate its + # symbolic conditions, so it cannot run with them disabled. + if args.task_type == "behavior" and not args.object_states: + print("[vector_profiling] --task-type behavior requires object states; enabling them.") + args.object_states = True + gm.ENABLE_OBJECT_STATES = args.object_states + gm.ENABLE_TRANSITION_RULES = args.object_states + gm.USE_GPU_DYNAMICS = args.gpu_dynamics + gm.ENABLE_DEEP_PROFILING = args.deep_profiling + + +def make_config(args): + cfg = { + "env": { + "action_frequency": 30, + "physics_frequency": 120, + }, + } + + if args.task_type == "behavior": + # Cached BehaviorTask requires (scene, activity) pair with pre-sampled template JSON. + # house_single_floor + bringing_water is one such pair. + # + # Restrict loading to the rooms the activity actually needs, using the same + # B100_task_misc.csv metadata the challenge evaluator reads (see + # omnigibson/eval/utils/eval_utils.py). house_single_floor has 21 room instances / + # 595 objects; bringing_water needs 7 of them. Loading the full house multiplies by + # n_envs and exhausts GPU memory well before n_envs=10, which is exactly the + # configuration this benchmark exists to measure -- and it is not how the stack is + # used in practice, since eval always loads a room subset. + cfg["scene"] = { + "type": "InteractiveTraversableScene", + "scene_model": "house_single_floor", + } + try: + from omnigibson.eval.utils.eval_utils import TASK_NAMES_TO_ROOMS + + rooms = TASK_NAMES_TO_ROOMS.get(BEHAVIOR_ACTIVITY_NAME) + except Exception as e: # metadata CSV absent -> fall back to the full scene + print(f"[vector_profiling] Could not read challenge room metadata ({e}); loading full scene.") + rooms = None + if rooms: + cfg["scene"]["load_room_instances"] = rooms + print(f"[vector_profiling] Loading {len(rooms)} room instance(s) for {BEHAVIOR_ACTIVITY_NAME}: {rooms}") + else: + print(f"[vector_profiling] No room metadata for {BEHAVIOR_ACTIVITY_NAME}; loading full scene.") + else: + cfg["scene"] = { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": ["floors", "breakfast_table"], + } + robot_cfg = { + "model": "r1pro", + "obs_modalities": ["rgb"] if args.rendering else ["proprio"], + } + if args.task_type != "behavior": + # Pose hand-picked for Rs_int (beside the breakfast_table). Only valid for the + # Rs_int-based task types. + robot_cfg["position"] = [-1.3, 0.5, 0.0] + robot_cfg["orientation"] = [0.0, 0.0, 0.7071, -0.7071] + # BehaviorTask deliberately gets NO pose here: it places the robot from the scene's + # presampled robot_poses metadata (behavior_task.py, use_presampled_robot_pose). Seeding + # an Rs_int pose into house_single_floor spawns the robot inside geometry, and because + # Environment.load() runs post_play_load -> scene.reset() -> step_physics() *before* + # BehaviorTask.reset() ever applies the presampled pose, that first physics step + # diverges to NaN. This matches how the challenge evaluator configures its robot + # (omnigibson/eval/r1pro.yaml declares no position). + cfg["robots"] = [robot_cfg] + if args.task_type == "behavior": + cfg["task"] = { + "type": "BehaviorTask", + "activity_name": BEHAVIOR_ACTIVITY_NAME, + "activity_definition_id": 0, + "online_object_sampling": False, + } + elif args.task_type == "navigation": + cfg["task"] = { + "type": "PointNavigationTask", + "robot_idn": 0, + "floor": 0, + "goal_tolerance": 0.36, + "path_range": [1.0, 10.0], + "visualize_goal": False, + "visualize_path": False, + } + else: + cfg["task"] = {"type": "DummyTask"} + + return cfg + + +def main(): + args = parser.parse_args() + + apply_macros(args) + + load_start = time.time() + og.launch() + + cfg = make_config(args) + cfg["env"]["num_envs"] = args.n_envs + if args.deep_profiling: + load_profiler = cProfile.Profile() + load_profiler.enable() + env = og.Environment(configs=cfg) + env.reset() + if args.deep_profiling: + load_profiler.disable() + load_profiler.dump_stats("load.prof") + total_load_time = time.time() - load_start + + og.sim._step_profiler.reset() + og.sim._pre_physics_step_profiler.reset() + og.sim._post_physics_step_profiler.reset() + og.sim._non_physics_step_profiler.reset() + + # Use small random actions so the controllers/physics still run with non-trivial motion + # but joint velocities stay in a safe regime. Larger commands (e.g. +/- 0.3) probabilistically + # drive r1pro into a physics divergence (NaN base_link), and with many envs the dice rolls + # add up to a near-certain failure within ~tens of steps. Profiling cost is dominated by the + # per-step pipeline (controllers, physics solver, contacts, state/obs reads), which all run + # regardless of action magnitude. + action_lo, action_hi = -0.02, 0.02 + action_dim = env.scenes[0].robots[0].action_dim + for _ in range(NUM_STEPS): + actions = th.rand(args.n_envs, action_dim) * (action_hi - action_lo) + action_lo + env.step(actions) + + n_steps = og.sim._step_profiler.call_count + avg_total_ms = og.sim._step_profiler.average_time * 1e3 + avg_og_ms = ( + ( + og.sim._pre_physics_step_profiler.total_time + + og.sim._post_physics_step_profiler.total_time + + og.sim._non_physics_step_profiler.total_time + ) + / n_steps + * 1e3 + ) + avg_isaac_ms = avg_total_ms - avg_og_ms + fps = 1000.0 / avg_total_ms * args.n_envs + memory_gb = psutil.Process(os.getpid()).memory_info().rss / 1024**3 + vram_gb = get_vram_usage() + + label = f"{args.n_envs} {'env' if args.n_envs == 1 else 'envs'}" + label += ", rendering" if args.rendering else ", no rendering" + label += f", {args.task_type} task" + label += ", states on" if args.object_states else ", states off" + + output = [ + {"name": label, "unit": "time (s)", "value": total_load_time, "extra": ["Loading time", "Loading time"]}, + {"name": label, "unit": "fps", "value": fps, "extra": ["FPS", "FPS"]}, + {"name": label, "unit": "time (ms)", "value": avg_isaac_ms, "extra": ["Isaac step time", "Isaac step time"]}, + { + "name": label, + "unit": "time (ms)", + "value": avg_og_ms, + "extra": ["Non-Isaac step time", "Non-Isaac step time"], + }, + {"name": label, "unit": "GB", "value": memory_gb, "extra": ["Memory usage", "Memory usage"]}, + {"name": label, "unit": "GB", "value": vram_gb, "extra": ["Vram usage", "Vram usage"]}, + ] + + ret = [] + if os.path.exists("vector_output.json"): + with open("vector_output.json") as f: + ret = json.load(f) + ret.extend(output) + with open("vector_output.json", "w") as f: + json.dump(ret, f, indent=4) + + print( + f"[{label}] load={total_load_time:.1f}s FPS={fps:.1f} Isaac={avg_isaac_ms:.2f}ms " + f"OG={avg_og_ms:.2f}ms RAM={memory_gb:.2f}GB VRAM={vram_gb:.2f}GB" + ) + + if args.deep_profiling: + og.sim._step_profiler.dump_stats("step.prof") + og.sim._pre_physics_step_profiler.dump_stats("pre_physics_step.prof") + og.sim._post_physics_step_profiler.dump_stats("post_physics_step.prof") + og.sim._non_physics_step_profiler.dump_stats("non_physics_step.prof") + + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/conftest.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..1cce64351c43c3689c9632c8de005e530c46f43f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/conftest.py @@ -0,0 +1,547 @@ +import pytest +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.objects import DatasetObject +from omnigibson.robots import Robot +from omnigibson.utils.constants import ParticleModifyCondition, ParticleModifyMethod + +from utils import MULTI_ENV_ROBOTS + + +@pytest.fixture +def stopped_env(): + if og.sim is None: + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_TRANSITION_RULES = True + + env = og.Environment(configs={"scene": {"type": "Scene"}}) + og.sim.stop() + yield env + + +def _add_obj(env, obj): + """Add object to scene and position it away from other objects.""" + env.scene.add_object(obj) + obj.set_position_orientation( + position=th.tensor([150, 150, 150 + len(env.scene.objects) * 5], dtype=th.float32), frame="scene" + ) + + +@pytest.fixture +def env(request, stopped_env): + for name in request.fixturenames: + if name not in ("env", "stopped_env", "request"): + request.getfixturevalue(name) + + og.sim.play() + yield stopped_env + + og.clear() + + +# --- Robot fixture --- + + +@pytest.fixture +def robot(stopped_env): + obj = Robot( + name="fetch", + model="fetch", + obs_modalities="rgb", + position=[150, 150, 100], + orientation=[0, 0, 0, 1], + ) + stopped_env.scene.add_object(obj) + return obj + + +@pytest.fixture +def assisted_robot(stopped_env): + obj = Robot( + name="r1pro", + model="r1pro", + grasping_mode="assisted", + obs_modalities=[], + position=[150, 150, 100], + orientation=[0, 0, 0, 1], + ) + stopped_env.scene.add_object(obj) + return obj + + +# --- Object fixtures --- + + +@pytest.fixture +def breakfast_table(stopped_env): + obj = DatasetObject(name="breakfast_table", category="breakfast_table", model="skczfi") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bottom_cabinet(stopped_env): + obj = DatasetObject(name="bottom_cabinet", category="bottom_cabinet", model="immwzb") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def dishtowel(stopped_env): + # TODO(#2042): Re-enable cloth behaviors for this object + obj = DatasetObject( + name="dishtowel", + category="dishtowel", + model="dtfspn", + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def carpet(stopped_env): + # TODO(#2042): Re-enable cloth behaviors for this object + obj = DatasetObject( + name="carpet", + category="carpet", + model="ctclvd", + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bowl(stopped_env): + obj = DatasetObject(name="bowl", category="bowl", model="ajzltc") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bagel(stopped_env): + obj = DatasetObject( + name="bagel", + category="bagel", + model="zlxkry", + abilities={"cookable": {}, "freezable": {}, "burnable": {}, "heatable": {}}, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def cookable_dishtowel(stopped_env): + # TODO(#2042): Re-enable cloth behaviors for this object + obj = DatasetObject( + name="cookable_dishtowel", + category="dishtowel", + model="dtfspn", + abilities={"cookable": {}, "freezable": {}, "burnable": {}, "heatable": {}}, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def microwave(stopped_env): + obj = DatasetObject(name="microwave", category="microwave", model="hjjxmi") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def stove(stopped_env): + obj = DatasetObject(name="stove", category="stove", model="yhjzwg") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def fridge(stopped_env): + obj = DatasetObject(name="fridge", category="fridge", model="xyejdx") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def plywood(stopped_env): + obj = DatasetObject(name="plywood", category="plywood", model="fkmkqa", abilities={"flammable": {}}) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bookcase_back(stopped_env): + obj = DatasetObject(name="bookcase_back", category="bookcase_back", model="gjsnrt", abilities={"attachable": {}}) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bookcase_shelf(stopped_env): + obj = DatasetObject(name="bookcase_shelf", category="bookcase_shelf", model="ymtnqa", abilities={"attachable": {}}) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bookcase_baseboard(stopped_env): + obj = DatasetObject( + name="bookcase_baseboard", category="bookcase_baseboard", model="hlhneo", abilities={"attachable": {}} + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bracelet(stopped_env): + obj = DatasetObject(name="bracelet", category="bracelet", model="thqqmo") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def furniture_sink(stopped_env): + obj = DatasetObject(name="furniture_sink", category="furniture_sink", model="bnpjjy", scale=th.ones(3)) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def stockpot(stopped_env): + obj = DatasetObject( + name="stockpot", category="stockpot", model="dcleem", abilities={"fillable": {}, "heatable": {}} + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def applier_dishtowel(stopped_env): + obj = DatasetObject( + name="applier_dishtowel", + category="dishtowel", + model="dtfspn", + abilities={"particleApplier": {"method": ParticleModifyMethod.ADJACENCY, "conditions": {"water": []}}}, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def remover_dishtowel(stopped_env): + obj = DatasetObject( + name="remover_dishtowel", + category="dishtowel", + model="dtfspn", + abilities={"particleRemover": {"method": ParticleModifyMethod.ADJACENCY, "conditions": {"water": []}}}, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def acetone_atomizer(stopped_env): + obj = DatasetObject( + name="acetone_atomizer", + category="acetone_atomizer", + model="krtwsl", + visual_only=True, + abilities={ + "toggleable": {}, + "particleApplier": { + "method": ParticleModifyMethod.PROJECTION, + "conditions": {"water": [(ParticleModifyCondition.TOGGLEDON, True)]}, + }, + }, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def vacuum(stopped_env): + obj = DatasetObject( + name="vacuum", + category="vacuum", + model="bdmsbr", + visual_only=True, + abilities={ + "toggleable": {}, + "particleRemover": { + "method": ParticleModifyMethod.PROJECTION, + "conditions": {"water": [(ParticleModifyCondition.TOGGLEDON, True)]}, + }, + }, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def blender(stopped_env): + obj = DatasetObject( + name="blender", + category="blender", + model="cwkvib", + bounding_box=[0.316, 0.318, 0.649], + abilities={"fillable": {}, "toggleable": {}, "heatable": {}}, + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def oven(stopped_env): + obj = DatasetObject(name="oven", category="oven", model="cgtaer", bounding_box=[0.943, 0.837, 1.297]) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def baking_sheet(stopped_env): + obj = DatasetObject(name="baking_sheet", category="baking_sheet", model="yhurut") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def bagel_dough(stopped_env): + obj = DatasetObject(name="bagel_dough", category="bagel_dough", model="iuembm", bounding_box=[0.20, 0.20, 0.02]) + _add_obj(stopped_env, obj) + obj.root_link.set_collision_approximation("boundingCube") + return obj + + +@pytest.fixture +def raw_egg(stopped_env): + obj = DatasetObject(name="raw_egg", category="raw_egg", model="ydgivr") + _add_obj(stopped_env, obj) + obj.root_link.set_collision_approximation("boundingCube") + return obj + + +@pytest.fixture +def another_raw_egg(stopped_env): + obj = DatasetObject(name="another_raw_egg", category="raw_egg", model="ydgivr") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def scoop_of_ice_cream(stopped_env): + obj = DatasetObject( + name="scoop_of_ice_cream", category="scoop_of_ice_cream", model="dodndj", bounding_box=[0.076, 0.077, 0.065] + ) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def food_processor(stopped_env): + obj = DatasetObject(name="food_processor", category="food_processor", model="gamkbo") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def electric_mixer(stopped_env): + obj = DatasetObject(name="electric_mixer", category="electric_mixer", model="qornxa") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def swiss_cheese(stopped_env): + obj = DatasetObject(name="swiss_cheese", category="swiss_cheese", model="hwxeto") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def apple(stopped_env): + obj = DatasetObject(name="apple", category="apple", model="agveuv") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def table_knife(stopped_env): + obj = DatasetObject(name="table_knife", category="table_knife", model="jxdfyy") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def half_apple(stopped_env): + obj = DatasetObject(name="half_apple", category="half_apple", model="sguztn") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def tablespoon(stopped_env): + obj = DatasetObject(name="tablespoon", category="tablespoon", model="huudhe") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def chicken(stopped_env): + obj = DatasetObject(name="chicken", category="chicken", model="nppsmz", scale=th.ones(3) * 0.7) + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def washer(stopped_env): + obj = DatasetObject(name="washer", category="washer", model="dobgmu") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def clothes_dryer(stopped_env): + obj = DatasetObject(name="clothes_dryer", category="clothes_dryer", model="smcyys") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture +def oyster(stopped_env): + obj = DatasetObject(name="oyster", category="oyster", model="enzocs") + _add_obj(stopped_env, obj) + return obj + + +@pytest.fixture(scope="module", params=MULTI_ENV_ROBOTS) +def robot_model(request): + """Robot model name under test (a string like "fetch"). + + Module-scoped and parametrized so pytest groups all tests for one robot together, which lets + `make_multi_env` build a single env per robot instead of one per test. + + NOTE: named `robot_model`, not `robot` -- the `robot` fixture above returns a Robot *object*. + """ + return request.param + + +@pytest.fixture(scope="module") +def make_multi_env(): + """Module-scoped *factory* for multi-env Environments, reusing one env across tests. + + NOTE: named `make_multi_env`, not `multi_env` -- test_multiple_envs_{heat_states, + heat_narrow_phase,transition_rules}.py already define a module fixture called `multi_env` + that is an Environment, not a factory. Keeping the names distinct avoids two things with the + same name meaning different types. + + Building an Environment is by far the dominant cost of the multi-env suites, so this keeps a + single env alive for the whole module and only rebuilds when a test asks for a different + (num_envs, robot, task_type, additional_objects_cfg) combination. Order the tests in a module + so that same-configuration tests are adjacent, and parametrize robots via a module-scoped fixture + (not @pytest.mark.parametrize) so pytest groups by robot instead of by test function. + + Every call returns a freshly `reset()` env, and the fixture owns teardown -- tests must NOT call + og.clear() themselves, or the cached env would be destroyed out from under the next test. + """ + from utils import setup_multi_environment + + state = {"key": None, "env": None} + + def _get(num_envs, robot="fetch", task_type="DummyTask", additional_objects_cfg=None): + key = (num_envs, robot, task_type, repr(additional_objects_cfg)) + if state["key"] != key: + if state["env"] is not None: + og.clear() + state["env"], state["key"] = None, None + state["env"] = setup_multi_environment( + num_envs=num_envs, + robot=robot, + task_type=task_type, + additional_objects_cfg=additional_objects_cfg, + ) + state["key"] = key + elif og.sim.is_stopped(): + # A prior test may have left the sim stopped (e.g. the stopped-sim setter tests) + og.sim.play() + state["env"].reset() + return state["env"] + + try: + yield _get + finally: + if state["env"] is not None: + og.clear() + + +# --------------------------------------------------------------------------- +# Shared BehaviorTask env, reused across the test_multiple_envs_behavior_* files +# --------------------------------------------------------------------------- +# +# Loading `house_double_floor_lower` x2 with a BehaviorTask takes ~40s and dominates those suites. +# The three files use an identical config, so when they run in one pytest invocation (see the +# combined entry in .github/workflows/tests.yml) they share a single env instead of loading one +# each. The env is cached by config here rather than held in a session-scoped fixture, so a test +# that needs a *different* config (e.g. use_presampled_robot_pose=False) simply rebuilds, and the +# ordering between files never matters. +# +# NOTE: because the env outlives individual tests, the per-test `reset()` below is load-bearing, +# not just tidiness. Tests must NOT call og.clear() themselves. +_BEHAVIOR_ENV_CACHE = {"key": None, "env": None} + + +def _get_behavior_env(num_envs, use_presampled_robot_pose): + from utils import setup_behavior_environment + + key = (num_envs, use_presampled_robot_pose) + if _BEHAVIOR_ENV_CACHE["key"] != key: + if _BEHAVIOR_ENV_CACHE["env"] is not None: + # An env built with a different config is still loaded -- tear it down first. Without an + # explicit clear, the new env's object-state machinery references prims from the previous + # scenes and crashes during play() with `'NoneType' object has no attribute 'state_updated'`. + og.clear() + _BEHAVIOR_ENV_CACHE["env"], _BEHAVIOR_ENV_CACHE["key"] = None, None + _BEHAVIOR_ENV_CACHE["env"] = setup_behavior_environment( + num_envs=num_envs, use_presampled_robot_pose=use_presampled_robot_pose + ) + _BEHAVIOR_ENV_CACHE["key"] = key + elif og.sim.is_stopped(): + og.sim.play() + _BEHAVIOR_ENV_CACHE["env"].reset() + return _BEHAVIOR_ENV_CACHE["env"] + + +@pytest.fixture(scope="session") +def _behavior_env_owner(): + """Owns teardown of whatever BehaviorTask env is cached at the end of the session.""" + yield + if _BEHAVIOR_ENV_CACHE["env"] is not None: + og.clear() + _BEHAVIOR_ENV_CACHE["env"], _BEHAVIOR_ENV_CACHE["key"] = None, None + + +@pytest.fixture +def behavior_env(_behavior_env_owner): + """The standard shared BehaviorTask env (num_envs=2, presampled robot pose), freshly reset.""" + from utils import BEHAVIOR_NUM_ENVS + + return _get_behavior_env(num_envs=BEHAVIOR_NUM_ENVS, use_presampled_robot_pose=True) + + +@pytest.fixture +def behavior_env_no_presample(_behavior_env_owner): + """BehaviorTask env built with use_presampled_robot_pose=False, freshly reset.""" + from utils import BEHAVIOR_NUM_ENVS + + return _get_behavior_env(num_envs=BEHAVIOR_NUM_ENVS, use_presampled_robot_pose=False) + + +def pytest_addoption(parser): + parser.addoption("--test-args", action="store", default="", help="Extra args passed to the example under test") + + +def pytest_unconfigure(config): + og.shutdown() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/data/r1_pro_source_config.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/data/r1_pro_source_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..460730f3e879ea5da1d55971f5f06d5acbd0de73 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/data/r1_pro_source_config.yaml @@ -0,0 +1,283 @@ +urdf_path: r1_pro_source.urdf # (str) Absolute path to robot URDF to import +name: r1 # (str) Name to assign to robot +headless: false # (bool) if set, run without GUI +overwrite: true # (bool) if set, overwrite any existing files +merge_fixed_joints: false # (bool) whether to merge fixed joints in the robot hierarchy or not +base_motion: + wheel_links: # (list of str): links corresponding to wheels + - wheel_link1 + - wheel_link2 + - wheel_link3 + wheel_joints: # (list of str): joints corresponding to wheel motion + - servo_joint1 + - servo_joint2 + - servo_joint3 + - wheel_joint1 + - wheel_joint2 + - wheel_joint3 + use_sphere_wheels: true # (bool) whether to use sphere approximation for wheels (better stability) + use_holonomic_joints: true # (bool) whether to use joints to approximate a holonomic base. In this case, all + # wheel-related joints will be made into fixed joints, and 6 additional + # "virtual" joints will be added to the robot's base capturing 6DOF movement, + # with the (x,y,rz) joints being controllable by motors +collision: + decompose_method: coacd # (str) [coacd, convex, or null] collision decomposition method + hull_count: 8 # (int) per-mesh max hull count to use during decomposition, only relevant for coacd + coacd_links: [] # (list of str): links that should use CoACD to decompose collision meshes + convex_links: # (list of str): links that should use convex hull to decompose collision meshes + - base_link + - wheel_link1 + - wheel_link2 + - wheel_link3 + - torso_link1 + - torso_link2 + - torso_link3 + - torso_link4 + - left_arm_link1 + - left_arm_link4 + - left_arm_link5 + - right_arm_link1 + - right_arm_link4 + - right_arm_link5 + no_decompose_links: [] # (list of str): links that should not have any post-processing done to them + no_collision_links: # (list of str) links that will have any associated collision meshes removed + - servo_link1 + - servo_link2 + - servo_link3 +eef_vis_links: # (list of dict) information for adding cameras to robot + - link: left_eef_link # same format as @camera_links + parent_link: left_arm_link6 + offset: + position: [0, 0, 0.06] + orientation: [0, 0, 0, 1] # NOTE: Convention for these eef vis links should be tuned such that: + # z-axis points out from the tips of the fingers + # y-axis points in the direction from the left finger to the right finger + # x-axis is automatically inferred from the above two axes + - link: right_eef_link # same format as @camera_links + parent_link: right_arm_link6 + offset: + position: [0, 0, 0.06] + orientation: [0, 0, 0, 1] +camera_links: # (list of dict) information for adding cameras to robot + - link: eyes # (str) link name to add camera. Must exist if @parent_link is null, else will be + # added as a child of the parent + parent_link: torso_link4 # (str) optional parent link to use if adding new link + offset: # (dict) local pos,ori offset values. if @parent_link is specified, defines offset + # between @parent_link and @link specified in @parent_link's frame. + # Otherwise, specifies offset of generated prim relative to @link's frame + position: [0.0732, 0, 0.4525] # (3-tuple) (x,y,z) offset -- this is done BEFORE the rotation + orientation: [0.4056, -0.4056, -0.5792, 0.5792] # (4-tuple) (x,y,z,w) offset + - link: left_eef_link + parent_link: null + offset: + position: [0.05, 0, -0.05] + orientation: [-0.7011, -0.7011, -0.0923, -0.0923] + - link: right_eef_link + parent_link: null + offset: + position: [0.05, 0, -0.05] + orientation: [-0.7011, -0.7011, -0.0923, -0.0923] +lidar_links: [] # (list of dict) information for adding cameras to robot +curobo: + eef_to_gripper_info: # (dict) Maps EEF link name to corresponding gripper links / joints + right_eef_link: + links: ["right_gripper_link1", "right_gripper_link2"] + joints: ["right_gripper_axis1", "right_gripper_axis2"] + left_eef_link: + links: ["left_gripper_link1", "left_gripper_link2"] + joints: ["left_gripper_axis1", "left_gripper_axis2"] + flip_joint_limits: [] # (list of str) any joints that have a negative axis specified in the + # source URDF + lock_joints: {} # (dict) Maps joint name to "locked" joint configuration. Any joints + # specified here will not be considered active when motion planning + # NOTE: All gripper joints and non-controllable holonomic joints + # will automatically be added here. Null means that the value will be + # dynamically computed at runtime based on the robot's reset qpos + self_collision_ignore: # (dict) Maps link name to list of other ignore links to ignore collisions + # with. Note that bi-directional specification is not necessary, + # e.g.: "torso_link1" does not need to be specified in + # "torso_link2"'s list if "torso_link2" is already specified in + # "torso_link1"'s list + base_link: ["torso_link1", "wheel_link1", "wheel_link2", "wheel_link3"] + torso_link1: ["torso_link2"] + torso_link2: ["torso_link3", "torso_link4"] + torso_link3: ["torso_link4"] + torso_link4: ["left_arm_link1", "right_arm_link1", "left_arm_link2", "right_arm_link2"] + left_arm_link1: ["left_arm_link2"] + left_arm_link2: ["left_arm_link3"] + left_arm_link3: ["left_arm_link4"] + left_arm_link4: ["left_arm_link5"] + left_arm_link5: ["left_arm_link6"] + left_arm_link6: ["left_gripper_link1", "left_gripper_link2"] + right_arm_link1: ["right_arm_link2"] + right_arm_link2: ["right_arm_link3"] + right_arm_link3: ["right_arm_link4"] + right_arm_link4: ["right_arm_link5"] + right_arm_link5: ["right_arm_link6"] + right_arm_link6: ["right_gripper_link1", "right_gripper_link2"] + left_gripper_link1: ["left_gripper_link2"] + right_gripper_link1: ["right_gripper_link2"] + collision_spheres: # (dict) Maps link name to list of collision sphere representations, + # where each sphere is defined by its (x,y,z) "center" and "radius" + # values. This defines the collision geometry during motion planning + base_link: + - "center": [-0.009, -0.094, 0.131] + "radius": 0.09128 + - "center": [-0.021, 0.087, 0.121] + "radius": 0.0906 + - "center": [0.019, 0.137, 0.198] + "radius": 0.07971 + - "center": [0.019, -0.14, 0.209] + "radius": 0.07563 + - "center": [0.007, -0.018, 0.115] + "radius": 0.08448 + - "center": [0.119, -0.176, 0.209] + "radius": 0.05998 + - "center": [0.137, 0.118, 0.208] + "radius": 0.05862 + - "center": [-0.152, -0.049, 0.204] + "radius": 0.05454 + torso_link1: + - "center": [-0.001, -0.014, -0.057] + "radius": 0.1 + - "center": [-0.001, -0.127, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.219, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.29, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.375, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.419, -0.064] + "radius": 0.07 + torso_link2: + - "center": [-0.001, -0.086, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.194, -0.064] + "radius": 0.07 + - "center": [-0.001, -0.31, -0.064] + "radius": 0.07 + torso_link4: + - "center": [0.005, -0.001, 0.062] + "radius": 0.1 + - "center": [0.005, -0.001, 0.245] + "radius": 0.15 + - "center": [0.005, -0.001, 0.458] + "radius": 0.1 + - "center": [0.002, 0.126, 0.305] + "radius": 0.08 + - "center": [0.002, -0.126, 0.305] + "radius": 0.08 + left_arm_link1: + - "center": [0.001, 0.0, 0.069] + "radius": 0.06 + left_arm_link2: + - "center": [-0.062, -0.016, -0.03] + "radius": 0.06 + - "center": [-0.135, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.224, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.31, -0.022, -0.03] + "radius": 0.06 + - "center": [-0.34, -0.027, -0.03] + "radius": 0.06 + left_arm_link3: + - "center": [0.037, -0.058, -0.044] + "radius": 0.05 + - "center": [0.095, -0.08, -0.044] + "radius": 0.03 + - "center": [0.135, -0.08, -0.043] + "radius": 0.03 + - "center": [0.176, -0.08, -0.043] + "radius": 0.03 + - "center": [0.22, -0.077, -0.043] + "radius": 0.03 + left_arm_link4: + - "center": [-0.002, 0.0, 0.276] + "radius": 0.04 + left_arm_link5: + - "center": [0.059, -0.001, -0.021] + "radius": 0.035 + left_arm_link6: + - "center": [0.0, 0.0, 0.04] + "radius": 0.04 + right_arm_link1: + - "center": [0.001, 0.0, 0.069] + "radius": 0.06 + right_arm_link2: + - "center": [-0.062, -0.016, -0.03] + "radius": 0.06 + - "center": [-0.135, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.224, -0.019, -0.03] + "radius": 0.06 + - "center": [-0.31, -0.022, -0.03] + "radius": 0.06 + - "center": [-0.34, -0.027, -0.03] + "radius": 0.06 + right_arm_link3: + - "center": [0.037, -0.058, -0.044] + "radius": 0.05 + - "center": [0.095, -0.08, -0.044] + "radius": 0.03 + - "center": [0.135, -0.08, -0.043] + "radius": 0.03 + - "center": [0.176, -0.08, -0.043] + "radius": 0.03 + - "center": [0.22, -0.077, -0.043] + "radius": 0.03 + right_arm_link4: + - "center": [-0.002, 0.0, 0.276] + "radius": 0.04 + right_arm_link5: + - "center": [0.059, -0.001, -0.021] + "radius": 0.035 + right_arm_link6: + - "center": [-0.0, 0.0, 0.04] + "radius": 0.035 + wheel_link1: + - "center": [-0.0, 0.0, -0.03] + "radius": 0.06 + wheel_link2: + - "center": [0.0, 0.0, 0.03] + "radius": 0.06 + wheel_link3: + - "center": [0.0, 0.0, -0.03] + "radius": 0.06 + left_gripper_link1: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, 0.0, -0.003] + "radius": 0.007 + - "center": [0.005, 0.0, -0.005] + "radius": 0.005 + - "center": [0.02, 0.0, -0.007] + "radius": 0.003 + left_gripper_link2: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, 0.0, -0.003] + "radius": 0.007 + - "center": [0.005, 0.0, -0.005] + "radius": 0.005 + - "center": [0.02, 0.0, -0.007] + "radius": 0.003 + right_gripper_link1: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, -0.0, -0.003] + "radius": 0.007 + - "center": [0.005, -0.0, -0.005] + "radius": 0.005 + - "center": [0.02, -0.0, -0.007] + "radius": 0.003 + right_gripper_link2: + - "center": [-0.03, 0.0, -0.002] + "radius": 0.008 + - "center": [-0.01, 0.0, -0.003] + "radius": 0.007 + - "center": [0.005, 0.0, -0.005] + "radius": 0.005 + - "center": [0.02, 0.0, -0.007] + "radius": 0.003 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/requirements-tests.txt b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/requirements-tests.txt new file mode 100644 index 0000000000000000000000000000000000000000..039a58b8f5717ff5f32bc078b1119359f7875531 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/requirements-tests.txt @@ -0,0 +1,4 @@ +pytest-subtests +stable-baselines3 +tensorboard +flask_apscheduler \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/robot_in_empty_scene_seg_semantic.npy b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/robot_in_empty_scene_seg_semantic.npy new file mode 100644 index 0000000000000000000000000000000000000000..85ceeb4b68c18474a8fd6bd09fc3368c62375c04 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/robot_in_empty_scene_seg_semantic.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69797c041c86c980f128efaf812c91175737e4286764f7daeca27053864dead9 +size 3686528 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/robot_in_empty_scene_seg_semantic.png b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/robot_in_empty_scene_seg_semantic.png new file mode 100644 index 0000000000000000000000000000000000000000..7c5f08d277290008437066f25de76b32ed745103 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/robot_in_empty_scene_seg_semantic.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2cb289613b9dbe95df96183d58de5e227ba178e7b9365a82ba716e8071d74e0 +size 6358 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/rs_int_with_objects_seg_semantic.npy b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/rs_int_with_objects_seg_semantic.npy new file mode 100644 index 0000000000000000000000000000000000000000..35589b9862a000abbbd4231d462bffd19061195e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/rs_int_with_objects_seg_semantic.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:218343c6d39c722ae2c535062c84e25a833779b94a20e710e8da96e8be82b9ba +size 3686528 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/rs_int_with_objects_seg_semantic.png b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/rs_int_with_objects_seg_semantic.png new file mode 100644 index 0000000000000000000000000000000000000000..05a2cde813eeabe233d045d62d3d6c945165ea07 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/snapshots/golden/rs_int_with_objects_seg_semantic.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:995980b432b9c3feeeead23136726cd156663b3fcabc1d1dbd78cd189683cb1a +size 20586 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_ag_states.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_ag_states.py new file mode 100644 index 0000000000000000000000000000000000000000..d4763ebb801131559e4cb0a3fa53fa8111c9c169 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_ag_states.py @@ -0,0 +1,315 @@ +""" +Tests for assisted-grasping (AG) state serialization. + +Covers: + - dict roundtrip (dump_state / load_state) + - tensor roundtrip (dump_state serialized=True / load_state serialized=True) + - single-arm grasps (left and right tested individually) and both-arms grasps + - backwards compatibility: tensors that predate AG serialization (no magic sentinel) load cleanly + - expected-value check: AG block in serialized tensor matches known hand-crafted params +""" + +import pytest +import torch as th + +import omnigibson as og +from omnigibson.robots.robot import _AG_MAGIC, _AG_STATE_SIZE +from omnigibson.macros import gm + +gm.ENABLE_OBJECT_STATES = True +gm.USE_GPU_DYNAMICS = True +gm.ENABLE_TRANSITION_RULES = False + +# Deterministic frame params — different per arm so an accidental swap would be detectable. +_LEFT_FRAME = { + "parent_frame_pos": th.tensor([0.1, 0.0, 0.0]), + "parent_frame_orn": th.tensor([0.0, 0.0, 0.0, 1.0]), + "child_frame_pos": th.tensor([0.0, 0.0, 0.05]), + "child_frame_orn": th.tensor([0.0, 0.0, 0.0, 1.0]), + "joint_type": "FixedJoint", +} +_RIGHT_FRAME = { + "parent_frame_pos": th.tensor([0.2, 0.0, 0.0]), + "parent_frame_orn": th.tensor([0.0, 0.0, 0.0, 1.0]), + "child_frame_pos": th.tensor([0.0, 0.0, 0.07]), + "child_frame_orn": th.tensor([0.0, 0.0, 0.0, 1.0]), + "joint_type": "FixedJoint", +} + +# Per-block element count in the serialized tensor: magic + arm_idx + payload +_AG_BLOCK_LEN = 2 + _AG_STATE_SIZE + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _force_ag_grasp(robot, arm, target_obj, frame_params): + """Create an AG joint on `arm` with deterministic hand-crafted params.""" + target_link_name = sorted(target_obj.links.keys())[0] + constraint_params = { + "target_obj": target_obj, + "target_link_name": target_link_name, + **frame_params, + } + robot._create_assisted_grasp_joint(arm, constraint_params) + return constraint_params + + +def _assert_ag_restored(robot, arm, original_params, target_obj): + restored = robot._ag_obj_constraint_params[arm] + assert restored is not None, f"AG constraint was not restored on arm {arm}" + assert restored["target_obj"] is target_obj + assert restored["target_link_name"] == original_params["target_link_name"] + assert th.allclose(restored["parent_frame_pos"], original_params["parent_frame_pos"], atol=1e-5) + assert th.allclose(restored["parent_frame_orn"], original_params["parent_frame_orn"], atol=1e-5) + assert th.allclose(restored["child_frame_pos"], original_params["child_frame_pos"], atol=1e-5) + assert th.allclose(restored["child_frame_orn"], original_params["child_frame_orn"], atol=1e-5) + assert restored["joint_type"] == original_params["joint_type"] + + +def _release_and_flush(robot, *arms): + for arm in arms: + robot.release_grasp_immediately(arm=arm) + assert robot._ag_obj_constraint_params[arm] is None + # Step to flush the prim deletion and rebuild physics handles; without this, + # SynchronizeToFabric() in editing_usd.__exit__ fires USD notices while the + # guard is inactive and leaves a deferred error that breaks the next load_state. + og.sim.step() + + +# --------------------------------------------------------------------------- +# Dict-path roundtrip tests +# --------------------------------------------------------------------------- + + +def test_ag_dict_no_grasp(env, assisted_robot): + """No active grasp: dump/load leaves all arms ungrasped.""" + state = og.sim.dump_state() + og.sim.load_state(state) + for arm in assisted_robot.arm_names: + assert assisted_robot._ag_obj_constraint_params[arm] is None + + +@pytest.mark.parametrize("arm_name,frame_params", [("left", _LEFT_FRAME), ("right", _RIGHT_FRAME)]) +def test_ag_dict_single_arm(env, assisted_robot, apple, arm_name, frame_params): + """dict roundtrip for a single-arm grasp, tested individually for each arm.""" + params = _force_ag_grasp(assisted_robot, arm_name, apple, frame_params) + + state = og.sim.dump_state() + _release_and_flush(assisted_robot, arm_name) + + og.sim.load_state(state) + _assert_ag_restored(assisted_robot, arm_name, params, apple) + other_arm = "right" if arm_name == "left" else "left" + assert assisted_robot._ag_obj_constraint_params[other_arm] is None + + +def test_ag_dict_both_arms(env, assisted_robot, apple, bowl): + """dict roundtrip with both arms grasping different objects.""" + left_params = _force_ag_grasp(assisted_robot, "left", apple, _LEFT_FRAME) + right_params = _force_ag_grasp(assisted_robot, "right", bowl, _RIGHT_FRAME) + + state = og.sim.dump_state() + _release_and_flush(assisted_robot, "left", "right") + + og.sim.load_state(state) + _assert_ag_restored(assisted_robot, "left", left_params, apple) + _assert_ag_restored(assisted_robot, "right", right_params, bowl) + + +# --------------------------------------------------------------------------- +# Tensor-path roundtrip tests (serialized=True) +# --------------------------------------------------------------------------- + + +def test_ag_tensor_no_grasp(env, assisted_robot): + """No active grasp: serialized dump/load leaves all arms ungrasped.""" + state = og.sim.dump_state(serialized=True) + og.sim.load_state(state, serialized=True) + for arm in assisted_robot.arm_names: + assert assisted_robot._ag_obj_constraint_params[arm] is None + + +@pytest.mark.parametrize("arm_name,frame_params", [("left", _LEFT_FRAME), ("right", _RIGHT_FRAME)]) +def test_ag_tensor_single_arm(env, assisted_robot, apple, arm_name, frame_params): + """Tensor roundtrip for a single-arm grasp, tested individually for each arm.""" + params = _force_ag_grasp(assisted_robot, arm_name, apple, frame_params) + + state = og.sim.dump_state(serialized=True) + _release_and_flush(assisted_robot, arm_name) + + og.sim.load_state(state, serialized=True) + _assert_ag_restored(assisted_robot, arm_name, params, apple) + other_arm = "right" if arm_name == "left" else "left" + assert assisted_robot._ag_obj_constraint_params[other_arm] is None + + +def test_ag_tensor_both_arms(env, assisted_robot, apple, bowl): + """Tensor roundtrip with both arms grasping different objects.""" + left_params = _force_ag_grasp(assisted_robot, "left", apple, _LEFT_FRAME) + right_params = _force_ag_grasp(assisted_robot, "right", bowl, _RIGHT_FRAME) + + state = og.sim.dump_state(serialized=True) + _release_and_flush(assisted_robot, "left", "right") + + og.sim.load_state(state, serialized=True) + _assert_ag_restored(assisted_robot, "left", left_params, apple) + _assert_ag_restored(assisted_robot, "right", right_params, bowl) + + +# --------------------------------------------------------------------------- +# Backwards-compatibility test +# --------------------------------------------------------------------------- + + +def test_ag_tensor_backwards_compat(env, assisted_robot, apple): + """ + A tensor that predates AG serialization (no magic sentinel) deserializes cleanly + with no grasp restored and no under/over-read. + + We simulate an old recording by serializing with a grasp active, then stripping + the AG block at the tail, and re-running deserialize directly. + """ + _force_ag_grasp(assisted_robot, "left", apple, _LEFT_FRAME) + + robot_state = assisted_robot._dump_state() + full_tensor = assisted_robot.serialize(robot_state) + + # One grasping arm = one block = magic + arm_idx + _AG_STATE_SIZE payload + assert full_tensor[-_AG_BLOCK_LEN].item() == _AG_MAGIC, "Expected AG magic at tail of serialized state" + old_tensor = full_tensor[:-_AG_BLOCK_LEN] + + state_dict, idx = assisted_robot.deserialize(old_tensor) + + assert idx == len(old_tensor), f"deserialize consumed {idx} of {len(old_tensor)} elements" + assert state_dict.get("ag_obj_constraint_params", {}) == {} + + +# --------------------------------------------------------------------------- +# Expected-value checks for the serialized AG block layout +# --------------------------------------------------------------------------- + + +def test_ag_serialized_block_right_arm_only(env, assisted_robot, apple): + """ + A right-arm-only grasp produces exactly one block whose arm_idx == 1. + This validates that arm_idx sits immediately after _AG_MAGIC and that no + zero-padding is emitted for the non-grasping (left) arm. + """ + _force_ag_grasp(assisted_robot, "right", apple, _RIGHT_FRAME) + serialized = assisted_robot.serialize(assisted_robot._dump_state()) + + ag_block = serialized[-_AG_BLOCK_LEN:] + expected = th.tensor( + [ + _AG_MAGIC, + 1.0, # arm_idx — "right" is index 1 in r1pro's arm_names + float(apple.uuid), + 0.0, # link_idx (first sorted link) + 0.2, + 0.0, + 0.0, # parent_frame_pos + 0.0, + 0.0, + 0.0, + 1.0, # parent_frame_orn + 0.0, + 0.0, + 0.07, # child_frame_pos + 0.0, + 0.0, + 0.0, + 1.0, # child_frame_orn + 0.0, # joint_type: FixedJoint + ] + ) + assert th.allclose( + ag_block, expected, atol=1e-6 + ), f"AG block mismatch.\n actual: {ag_block.tolist()}\n expected: {expected.tolist()}" + + +def test_ag_serialized_block_both_arms_layout(env, assisted_robot, apple, bowl): + """ + Both-arms grasp emits two sequential magic-prefixed blocks in arm_names order + (r1pro: left then right), each containing the correct arm_idx and uuid. + """ + _force_ag_grasp(assisted_robot, "left", apple, _LEFT_FRAME) + _force_ag_grasp(assisted_robot, "right", bowl, _RIGHT_FRAME) + serialized = assisted_robot.serialize(assisted_robot._dump_state()) + + blocks = serialized[-2 * _AG_BLOCK_LEN :] + + # Left block + assert blocks[0].item() == _AG_MAGIC + assert blocks[1].item() == 0.0 # arm_idx for "left" + assert blocks[2].item() == float(apple.uuid) + + # Right block + assert blocks[_AG_BLOCK_LEN].item() == _AG_MAGIC + assert blocks[_AG_BLOCK_LEN + 1].item() == 1.0 # arm_idx for "right" + assert blocks[_AG_BLOCK_LEN + 2].item() == float(bowl.uuid) + + +# --------------------------------------------------------------------------- +# Multi-env cross-model sanity check +# --------------------------------------------------------------------------- + + +def _run_ag_roundtrip(robot_model): + """Spin up a fresh env with the given robot and verify dict+tensor roundtrip.""" + og.clear() + + config = { + "scene": {"type": "Scene"}, + "robots": [ + { + "model": robot_model, + "grasping_mode": "assisted", + "obs_modalities": [], + "position": [150, 150, 100], + "orientation": [0, 0, 0, 1], + } + ], + "objects": [ + { + "type": "DatasetObject", + "name": "apple", + "category": "apple", + "model": "agveuv", + "position": [152, 150, 100], + } + ], + } + env = og.Environment(configs=config) + og.sim.play() + og.sim.step() + + robot = env.scene.robots[0] + obj = env.scene.object_registry("name", "apple") + arm = robot.arm_names[0] + params = _force_ag_grasp(robot, arm, obj, _LEFT_FRAME) + + state = og.sim.dump_state() + robot.release_grasp_immediately(arm=arm) + og.sim.step() + og.sim.load_state(state) + _assert_ag_restored(robot, arm, params, obj) + + robot.release_grasp_immediately(arm=arm) + og.sim.step() + robot._create_assisted_grasp_joint(arm, {**params, "target_obj": obj}) + state_t = og.sim.dump_state(serialized=True) + robot.release_grasp_immediately(arm=arm) + og.sim.step() + og.sim.load_state(state_t, serialized=True) + _assert_ag_restored(robot, arm, params, obj) + + og.clear() + + +@pytest.mark.parametrize("robot_model", ["fetch", "franka"]) +def test_ag_roundtrip_multi_env(robot_model): + """AG state roundtrips correctly across different single-arm robot models.""" + _run_ag_roundtrip(robot_model) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_base_qvel.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_base_qvel.py new file mode 100644 index 0000000000000000000000000000000000000000..ed54995eae09e14963dac7999ee4d0de0748971b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_base_qvel.py @@ -0,0 +1,64 @@ +from types import SimpleNamespace + +import numpy as np +import torch as th + +from omnigibson.eval.utils.eval_utils import holonomic_base_qvel_to_robot_frame +from omnigibson.robots.robot import Robot + + +def test_holonomic_base_qvel_to_robot_frame_supports_batched_3dof_and_6dof_inputs(): + yaws = np.array([0.0, np.pi / 2, -np.pi / 2, np.pi]) + world_qvel = np.array( + [ + [1.0, 2.0, 0.1], + [1.0, 0.0, 0.2], + [0.0, 1.0, 0.3], + [1.0, 2.0, 0.4], + ] + ) + expected = np.array( + [ + [1.0, 2.0, 0.1], + [0.0, -1.0, 0.2], + [-1.0, 0.0, 0.3], + [-1.0, -2.0, 0.4], + ] + ) + + qpos_3dof = np.stack([np.zeros_like(yaws), np.zeros_like(yaws), yaws], axis=-1) + np.testing.assert_allclose(holonomic_base_qvel_to_robot_frame(qpos_3dof, world_qvel), expected, atol=1e-7) + + qpos_6dof = np.zeros((len(yaws), 6)) + qpos_6dof[:, -1] = yaws + qvel_6dof = np.zeros((len(yaws), 6)) + qvel_6dof[:, :2] = world_qvel[:, :2] + qvel_6dof[:, -1] = world_qvel[:, -1] + np.testing.assert_allclose(holonomic_base_qvel_to_robot_frame(qpos_6dof, qvel_6dof), expected, atol=1e-7) + + +def test_robot_holonomic_base_qvel_for_proprioception_uses_robot_frame(): + robot = SimpleNamespace( + base_control_idx=th.tensor([0, 1, 5]), + base_idx=th.arange(6), + is_holonomic_base=True, + ) + joint_positions = th.tensor([0.0, 0.0, 0.0, 0.0, 0.0, np.pi / 2]) + joint_velocities = th.tensor([1.0, 0.0, 0.0, 0.0, 0.0, 0.25]) + + actual = Robot._get_base_qvel_for_proprioception(robot, joint_positions, joint_velocities) + + th.testing.assert_close(actual, th.tensor([0.0, -1.0, 0.25]), atol=1e-6, rtol=0.0) + + +def test_robot_nonholonomic_base_qvel_for_proprioception_is_unchanged(): + robot = SimpleNamespace( + base_control_idx=th.tensor([1, 3]), + is_holonomic_base=False, + ) + joint_positions = th.zeros(4) + joint_velocities = th.tensor([10.0, 1.5, 20.0, -2.5]) + + actual = Robot._get_base_qvel_for_proprioception(robot, joint_positions, joint_velocities) + + th.testing.assert_close(actual, th.tensor([1.5, -2.5])) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_behavior_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_behavior_task.py new file mode 100644 index 0000000000000000000000000000000000000000..4848b55d62f3b5fb8384a8a8cef93d4abc76b306 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_behavior_task.py @@ -0,0 +1,42 @@ +import omnigibson as og +from omnigibson.macros import gm +import sys + + +def test_behavior_task(): + gm.ENABLE_OBJECT_STATES = True + gm.HEADLESS = True + config = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + }, + "task": { + "type": "BehaviorTask", + "activity_name": "putting_away_Halloween_decorations", + "activity_definition_id": 0, + "online_object_sampling": True, + "use_presampled_robot_pose": False, + }, + "robots": [ + { + "type": "Fetch", + "obs_modalities": ["rgb"], + } + ], + } + try: + env = og.Environment(configs=config) + print( + "BehaviorTask instantiated successfully! Ground goal state options:", + len(env.task.ground_goal_state_options), + ) + except Exception: + import traceback + + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + test_behavior_task() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_controllers.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_controllers.py new file mode 100644 index 0000000000000000000000000000000000000000..0cee3944eae2bf65a9ec63bc9aa06224a67451e9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_controllers.py @@ -0,0 +1,587 @@ +import numpy as np +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.controllers import ControllerView + + +# -------------------- Helper Functions -------------------- +def _make_two_fetch_env(): + cfg = { + "scene": {"type": "Scene"}, + "objects": [], + "robots": [ + { + "model": "fetch", + "name": "fetch_a", + "obs_modalities": [], + "position": [150, 150, 100], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": False, + }, + { + "model": "fetch", + "name": "fetch_b", + "obs_modalities": [], + "position": [150, 155, 100], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": False, + }, + ], + } + return og.Environment(configs=cfg) + + +def _stabilize_and_reset(robots): + for i, robot in enumerate(robots): + robot.set_position_orientation( + position=th.tensor([0.0, i * 5.0, 0.0]), + orientation=T.euler2quat(th.tensor([0.0, 0.0, np.pi / 3])), + ) + robot.reset() + for _ in range(10): + og.sim.step() + for robot in robots: + robot.keep_still() + for name in robot.controller_order: + group_key, controller_idx = robot.controllers[name] + ControllerView.reset(group_key, controller_idx) + + +def _arm_start_idx(robot, arm): + controller_name = f"arm_{arm}" + start_idx = 0 + for c in robot.controller_order: + if c == controller_name: + break + start_idx += ControllerView.get_command_dim(robot.controllers[c][0]) + return start_idx + + +def _distance(a, b): + return th.norm(a - b).item() + + +# -------------------- Test Cases -------------------- +def test_arm_control(): + # Create env + cfg = { + "scene": { + "type": "Scene", + }, + "objects": [], + "robots": [ + { + "model": "franka", + "name": "robot0", + "obs_modalities": [], + "position": [150, 150, 100], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": True, + }, + { + "model": "fetch", + "name": "robot1", + "obs_modalities": [], + "position": [150, 150, 105], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": False, + }, + { + "model": "tiago", + "name": "robot2", + "obs_modalities": [], + "position": [150, 150, 110], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + }, + { + "model": "a1", + "name": "robot3", + "obs_modalities": [], + "position": [150, 150, 115], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": True, + }, + { + "model": "r1", + "name": "robot4", + "obs_modalities": [], + "position": [150, 150, 120], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + }, + { + "model": "fetch", + "name": "robot_5", + "obs_modalities": [], + "position": [150, 150, 125], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": False, + }, + ], + } + + env = og.Environment(configs=cfg) + + # Define error functions to use + def check_zero_error(curr_position, init_position, tol=1e-2): + return th.norm(curr_position - init_position).item() < tol + + def check_forward_error(curr_position, init_position, tol=1e-2, forward_tol=1e-2): + # x should be positive + return (curr_position[0] - init_position[0]).item() > forward_tol and th.norm( + curr_position[[1, 2]] - init_position[[1, 2]] + ).item() < tol + + def check_side_error(curr_position, init_position, tol=1e-2, side_tol=1e-2): + # y should be positive + return (curr_position[1] - init_position[1]).item() > side_tol and th.norm( + curr_position[[0, 2]] - init_position[[0, 2]] + ).item() < tol + + def check_up_error(curr_position, init_position, tol=1e-2, up_tol=1e-2): + # z should be positive + return (curr_position[2] - init_position[2]).item() > up_tol and th.norm( + curr_position[[0, 1]] - init_position[[0, 1]] + ).item() < tol + + def check_ori_error(curr_orientation, init_orientation, tol=0.1): + ori_err_normalized = th.norm( + T.quat2axisangle(T.mat2quat(T.quat2mat(init_orientation).T @ T.quat2mat(curr_orientation))) + ).item() / (np.pi * 2) + ori_err = np.abs(np.pi * 2 * (np.round(ori_err_normalized) - ori_err_normalized)) + return ori_err < tol + + # All functions take in (target, curr, init) tuple + err_checks = { + "pose_delta_ori": { + "zero": { + "pos": lambda target, curr, init: check_zero_error(curr, init), + "ori": lambda target, curr, init: check_ori_error(curr, init), + }, + "forward": { + "pos": lambda target, curr, init: check_forward_error(curr, init), + "ori": lambda target, curr, init: check_ori_error(curr, init), + }, + "side": { + "pos": lambda target, curr, init: check_side_error(curr, init), + "ori": lambda target, curr, init: check_ori_error(curr, init), + }, + "up": { + "pos": lambda target, curr, init: check_up_error(curr, init), + "ori": lambda target, curr, init: check_ori_error(curr, init), + }, + "rotate": { + "pos": lambda target, curr, init: check_zero_error(curr, init), + "ori": None, + }, + "base_move": { + "pos": lambda target, curr, init: check_zero_error( + curr, init, tol=0.02 + ), # Slightly bigger tolerance with base moving + "ori": lambda target, curr, init: check_ori_error(curr, init), + }, + }, + "absolute_pose": { + "zero": { + "pos": lambda target, curr, init: check_zero_error(target, curr, tol=5e-3), + "ori": lambda target, curr, init: check_ori_error(target, curr), + }, + "forward": { + "pos": lambda target, curr, init: check_zero_error(target, curr, tol=5e-3), + "ori": lambda target, curr, init: check_ori_error(target, curr), + }, + "side": { + "pos": lambda target, curr, init: check_zero_error(target, curr, tol=5e-3), + "ori": lambda target, curr, init: check_ori_error(target, curr), + }, + "up": { + "pos": lambda target, curr, init: check_zero_error(target, curr, tol=5e-3), + "ori": lambda target, curr, init: check_ori_error(target, curr), + }, + "rotate": { + "pos": lambda target, curr, init: check_zero_error(target, curr, tol=5e-3), + "ori": lambda target, curr, init: check_ori_error(target, curr, tol=0.05), + }, + "base_move": { + "pos": lambda target, curr, init: check_zero_error(target, curr, tol=5e-3), + "ori": lambda target, curr, init: check_ori_error(target, curr), + }, + }, + } + + n_steps = { + "pose_delta_ori": { + "zero": 40, + "forward": 40, + "side": 40, + "up": 40, + "rotate": 20, + "base_move": 30, + }, + "absolute_pose": { + "zero": 50, + "forward": 50, + "side": 50, + "up": 50, + "rotate": 50, + "base_move": 50, + }, + } + + # Position the robots, reset them, and keep them still + for i, robot in enumerate(env.robots[0]): + robot.set_position_orientation( + position=th.tensor([0.0, i * 5.0, 0.0]), orientation=T.euler2quat(th.tensor([0.0, 0.0, np.pi / 3])) + ) + robot.reset() + + # Take 10 steps to stabilize + for _ in range(10): + og.sim.step() + + # Keep all robots still + for robot in env.robots[0]: + robot.keep_still() + + # We need to explicitly reset the controllers to unify the initial state that will be seen + # during downstream action executions -- i.e.: the state seen after robot.reload_controllers() + # is called each time + for name in robot.controller_order: + group_key, controller_idx = robot.controllers[name] + ControllerView.reset(group_key, controller_idx) + + # Update initial state (robot should be stable and still) + env.scene.update_initial_file() + + env.scene.reset() + + # Record initial eef pose of all robots + initial_eef_pose = dict() + for i, robot in enumerate(env.robots[0]): + initial_eef_pose[robot.name] = {arm: robot.get_relative_eef_pose(arm=arm) for arm in robot.arm_names} + + for controller in ["InverseKinematicsController", "OperationalSpaceController"]: + for controller_mode in ["pose_delta_ori", "absolute_pose"]: + controller_kwargs = { + "mode": controller_mode, + } + if controller_mode == "absolute_pose": + controller_kwargs["command_input_limits"] = None + controller_kwargs["command_output_limits"] = None + actions = { + "zero": dict(), + "forward": dict(), + "side": dict(), + "up": dict(), + "rotate": dict(), + "base_move": dict(), + } + + # Load the initial state without stepping physics + env.scene.load_state(env.scene._initial_file["state"]) + + for i, robot in enumerate(env.robots[0]): + controller_config = {f"arm_{arm}": {"name": controller, **controller_kwargs} for arm in robot.arm_names} + robot.reload_controllers(controller_config) + + # Define actions to use + zero_action = th.zeros(robot.action_dim) + forward_action = th.zeros(robot.action_dim) + side_action = th.zeros(robot.action_dim) + up_action = th.zeros(robot.action_dim) + rot_action = th.zeros(robot.action_dim) + + # Populate actions and targets + for arm in robot.arm_names: + c_name = f"arm_{arm}" + start_idx = 0 + init_eef_pos, init_eef_quat = initial_eef_pose[robot.name][arm] + for c in robot.controller_order: + if c == c_name: + break + start_idx += ControllerView.get_command_dim(robot.controllers[c][0]) + if controller_mode == "pose_delta_ori": + forward_action[start_idx] = 0.02 + side_action[start_idx + 1] = 0.02 + up_action[start_idx + 2] = 0.02 + rot_action[start_idx + 3] = 0.02 + elif controller_mode == "absolute_pose": + for act in [zero_action, forward_action, side_action, up_action, rot_action]: + act[start_idx : start_idx + 3] = init_eef_pos.clone() + act[start_idx + 3 : start_idx + 6] = T.quat2axisangle(init_eef_quat.clone()) + forward_action[start_idx] += 0.1 + side_action[start_idx + 1] += 0.1 + up_action[start_idx + 2] += 0.1 + rot_action[start_idx + 3 : start_idx + 6] = T.quat2axisangle( + T.quat_multiply(T.euler2quat(th.tensor([th.pi / 10, 0, 0])), init_eef_quat.clone()) + ) + + else: + raise ValueError(f"Got invalid controller mode: {controller}") + actions["zero"][robot.name] = zero_action + actions["forward"][robot.name] = forward_action + actions["side"][robot.name] = side_action + actions["up"][robot.name] = up_action + actions["rotate"][robot.name] = rot_action + + # Add base movement action if locomotion robot + base_move_action = zero_action.clone() + if robot.is_locomotion: + c_name = "base" + start_idx = 0 + for c in robot.controller_order: + if c == c_name: + break + start_idx += ControllerView.get_command_dim(robot.controllers[c][0]) + base_move_action[start_idx] = 0.1 + actions["base_move"][robot.name] = base_move_action + + # Update the state (e.g. goal, which is None) of the new controllers to the initial state + # This step is crucial because if env.reset() is called directly, we will load the state of the old controllers and step physics, + # which causes can cause errors because the goal is obsolete. + env.scene.update_initial_file() + + # For each action set, reset the scene, then run actions and see if arm moves in expected way + for action_name, action in actions.items(): + env.scene.reset() + + # Take N steps with given action and check for error + for _ in range(n_steps[controller_mode][action_name]): + env.step(action) + + for i, robot in enumerate(env.robots[0]): + for arm in robot.arm_names: + # Make sure no arm joints are at their limit + normalized_qpos = robot.get_joint_positions(normalized=True)[robot.arm_control_idx[arm]] + assert not th.any(th.abs(normalized_qpos) == 1.0), ( + f"controller [{controller}], mode [{controller_mode}], robot [{robot.model}], arm [{arm}], action [{action_name}]:\n" + f"Some joints are at their limit (normalized values): {normalized_qpos}" + ) + + init_pos, init_quat = initial_eef_pose[robot.name][arm] + curr_pos, curr_quat = robot.get_relative_eef_pose(arm=arm) + arm_group_key, arm_ci = robot.controllers[f"arm_{arm}"] + arm_goal = ControllerView.get_goal(arm_group_key, arm_ci) + target_pos = arm_goal["target_pos"] + target_quat = T.mat2quat(arm_goal["target_ori_mat"]) + pos_check = err_checks[controller_mode][action_name]["pos"] + if pos_check is not None: + is_valid_pos = pos_check(target_pos, curr_pos, init_pos) + assert is_valid_pos, ( + f"Robot {robot.model}: Got mismatch for controller [{controller}], mode [{controller_mode}], robot [{robot.model}], action [{action_name}]\n" + f"target_pos: {target_pos}, curr_pos: {curr_pos}, init_pos: {init_pos}" + ) + ori_check = err_checks[controller_mode][action_name]["ori"] + if ori_check is not None: + is_valid_ori = ori_check(target_quat, curr_quat, init_quat) + assert is_valid_ori, ( + f"Robot {robot.model}: Got mismatch for controller [{controller}], mode [{controller_mode}], robot [{robot.model}], action [{action_name}]\n" + f"target_quat: {target_quat}, curr_quat: {curr_quat}, init_quat: {init_quat}" + ) + og.clear() + + +def test_two_fetch_reload_reuses_slots(): + """ + Verify unregister/reload reuses tombstoned slots in shared groups. + + This test reloads both Fetch robots twice and checks that slot reuse keeps the shared group + compact instead of growing with stale tombstones. It checks that: + - shared arm controllers still point to the same group + - active indices correspond exactly to the two live members + - stale tombstones are not accumulating after reload + - stepping the scene does not crash after repeated reloads + """ + env = _make_two_fetch_env() + _stabilize_and_reset(env.scene.robots) + + for robot in env.scene.robots: + controller_config = { + f"arm_{arm}": {"name": "InverseKinematicsController", "mode": "pose_delta_ori"} for arm in robot.arm_names + } + robot.reload_controllers(controller_config) + + # Reload each robot once more; reused slots should prevent group growth. + for robot in env.scene.robots: + controller_config = { + f"arm_{arm}": {"name": "InverseKinematicsController", "mode": "pose_delta_ori"} for arm in robot.arm_names + } + robot.reload_controllers(controller_config) + + arm_name = env.scene.robots[0].arm_names[0] + group_key_a, idx_a = env.scene.robots[0].controllers[f"arm_{arm_name}"] + group_key_b, idx_b = env.scene.robots[1].controllers[f"arm_{arm_name}"] + assert group_key_a == group_key_b + + controller = ControllerView._controller_groups[group_key_a] + unregistered = list(controller._unregistered_controllers) + active_slots = [i for i, u in enumerate(unregistered) if u == 0] + + # With slot reuse, shared group should stay compact for exactly two live members. + assert controller.n_members == 2 + assert len(active_slots) == 2 + assert idx_a in active_slots and idx_b in active_slots + assert set(active_slots) == {idx_a, idx_b} + assert sum(unregistered) == 0 + + actions = {r.name: th.zeros(r.action_dim) for r in env.scene.robots} + for _ in range(5): + env.step(actions) + + og.clear() + + +def test_shared_group_disable_one_member(): + """ + Verify per-member control masking inside a shared controller group. + + With two Fetch robots sharing the same arm controller group, disable one robot and apply + forward arm actions to both. The control-disabled robot should stay near its initial pose while + the enabled robot still moves forward. + """ + env = _make_two_fetch_env() + _stabilize_and_reset(env.scene.robots) + + for robot in env.scene.robots: + controller_config = { + f"arm_{arm}": {"name": "InverseKinematicsController", "mode": "pose_delta_ori"} for arm in robot.arm_names + } + robot.reload_controllers(controller_config) + + robot_a, robot_b = env.scene.robots + arm_a = robot_a.arm_names[0] + arm_b = robot_b.arm_names[0] + init_pos_a, _ = robot_a.get_relative_eef_pose(arm=arm_a) + init_pos_b, _ = robot_b.get_relative_eef_pose(arm=arm_b) + + action_a = th.zeros(robot_a.action_dim) + action_b = th.zeros(robot_b.action_dim) + action_a[_arm_start_idx(robot_a, arm_a)] = 0.02 + action_b[_arm_start_idx(robot_b, arm_b)] = 0.02 + + # Disable only robot_a; robot_b should still move. + robot_a.control_enabled = False + for _ in range(30): + env.step({robot_a.name: action_a, robot_b.name: action_b}) + + curr_pos_a, _ = robot_a.get_relative_eef_pose(arm=arm_a) + curr_pos_b, _ = robot_b.get_relative_eef_pose(arm=arm_b) + + assert _distance(curr_pos_a, init_pos_a) < 2e-2 + assert (curr_pos_b[0] - init_pos_b[0]).item() > 1e-2 + + og.clear() + + +def test_reload_changes_controller_mode_in_shared_group(): + """ + Verify repeated mode reloads preserve valid shared-group membership. + + Repeatedly reload the shared Fetch arm controller between pose-delta and absolute-pose modes, + ensuring both robots remain active members in the shared group and can still step successfully. + """ + env = _make_two_fetch_env() + _stabilize_and_reset(env.scene.robots) + + arm_name = env.scene.robots[0].arm_names[0] + mode_sequence = ["pose_delta_ori", "absolute_pose", "pose_delta_ori"] + + for mode in mode_sequence: + for robot in env.scene.robots: + cfg = {f"arm_{arm}": {"name": "InverseKinematicsController", "mode": mode} for arm in robot.arm_names} + if mode == "absolute_pose": + cfg[f"arm_{arm_name}"]["command_input_limits"] = None + cfg[f"arm_{arm_name}"]["command_output_limits"] = None + robot.reload_controllers(cfg) + + group_key_a, idx_a = env.scene.robots[0].controllers[f"arm_{arm_name}"] + group_key_b, idx_b = env.scene.robots[1].controllers[f"arm_{arm_name}"] + assert group_key_a == group_key_b + + controller = ControllerView._controller_groups[group_key_a] + unregistered = list(controller._unregistered_controllers) + active_slots = [i for i, u in enumerate(unregistered) if u == 0] + assert idx_a in active_slots and idx_b in active_slots + + actions = {r.name: th.zeros(r.action_dim) for r in env.scene.robots} + env.step(actions) + + og.clear() + + +def test_mixed_models_no_cross_group_contamination(): + """ + Verify grouping isolation across robot models. + + Two Fetch robots should share one arm controller group, while a Franka should be placed in + a distinct arm controller group. This guards against cross-model group contamination. + """ + cfg = { + "scene": {"type": "Scene"}, + "objects": [], + "robots": [ + { + "model": "fetch", + "name": "fetch_a", + "obs_modalities": [], + "position": [150, 150, 100], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": False, + }, + { + "model": "fetch", + "name": "fetch_b", + "obs_modalities": [], + "position": [150, 155, 100], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": False, + }, + { + "model": "franka", + "name": "franka_a", + "obs_modalities": [], + "position": [150, 160, 100], + "orientation": [0, 0, 0, 1], + "action_normalize": False, + "fixed_base": True, + }, + ], + } + env = og.Environment(configs=cfg) + + for i, robot in enumerate(env.scene.robots): + robot.set_position_orientation( + position=th.tensor([0.0, i * 5.0, 0.0]), orientation=th.tensor([0.0, 0.0, 0.0, 1.0]) + ) + robot.reset() + for _ in range(5): + og.sim.step() + + fetch_a, fetch_b, franka = env.scene.robots + fetch_arm = fetch_a.arm_names[0] + franka_arm = franka.arm_names[0] + + group_key_fetch_a, _ = fetch_a.controllers[f"arm_{fetch_arm}"] + group_key_fetch_b, _ = fetch_b.controllers[f"arm_{fetch_arm}"] + group_key_franka, _ = franka.controllers[f"arm_{franka_arm}"] + + assert group_key_fetch_a == group_key_fetch_b + assert group_key_fetch_a != group_key_franka + + ctrl_fetch = ControllerView._controller_groups[group_key_fetch_a] + ctrl_franka = ControllerView._controller_groups[group_key_franka] + assert ctrl_fetch.n_members >= 2 + assert ctrl_franka.n_members == 1 + + og.clear() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_curobo.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_curobo.py new file mode 100644 index 0000000000000000000000000000000000000000..29d5242b390aab9d449ee68ff2085800b57eb42d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_curobo.py @@ -0,0 +1,513 @@ +import gc +import math +import os +from collections import defaultdict + +import torch as th + +import omnigibson as og +from omnigibson.action_primitives.curobo import CuRoboMotionGenerator +from omnigibson.macros import gm +from omnigibson.utils.usd_utils import RigidContactAPI + + +def test_curobo(): + # Make sure object states are enabled + assert gm.ENABLE_OBJECT_STATES + + # Create env + cfg = { + "env": { + "action_frequency": 30, + "physics_frequency": 300, + }, + "scene": { + "type": "Scene", + }, + "objects": [ + { + "type": "PrimitiveObject", + "name": "obj0", + "primitive_type": "Cube", + "scale": [0.4, 0.4, 0.4], + "fixed_base": True, + "position": [0.5, -0.1, 0.2], + "orientation": [0, 0, 0, 1], + }, + { + "type": "PrimitiveObject", + "name": "eef_marker_0", + "primitive_type": "Sphere", + "radius": 0.05, + "visual_only": True, + "position": [0, 0, 0], + "orientation": [0, 0, 0, 1], + "rgba": [1, 0, 0, 1], + }, + { + "type": "PrimitiveObject", + "name": "eef_marker_1", + "primitive_type": "Sphere", + "radius": 0.05, + "visual_only": True, + "position": [0, 0, 0], + "orientation": [0, 0, 0, 1], + "rgba": [0, 1, 0, 1], + }, + ], + "robots": [], + } + + robot_cfgs = [ + { + "model": "a1", + "obs_modalities": "rgb", + "position": [0.6, -0.65, 0.0], + "orientation": [0, 0, 0.707, 0.707], + "self_collisions": True, + "action_normalize": False, + "controller_config": { + "arm_0": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_0": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + }, + }, + { + "model": "franka", + "obs_modalities": "rgb", + "position": [0.7, -0.55, 0.0], + "orientation": [0, 0, 0.707, 0.707], + "self_collisions": True, + "action_normalize": False, + "controller_config": { + "arm_0": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_0": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + }, + }, + { + "model": "r1", + "obs_modalities": "rgb", + "position": [0.7, -0.7, 0.0], + "orientation": [0, 0, 0.707, 0.707], + "self_collisions": True, + "action_normalize": False, + "controller_config": { + "base": { + "name": "HolonomicBaseJointController", + "motor_type": "position", + "command_input_limits": None, + "use_impedances": False, + }, + "trunk": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + }, + }, + { + "model": "tiago", + "obs_modalities": "rgb", + "position": [0.7, -0.85, 0], + "orientation": [0, 0, 0.707, 0.707], + "self_collisions": True, + "action_normalize": False, + "controller_config": { + "base": { + "name": "HolonomicBaseJointController", + "motor_type": "position", + "command_input_limits": None, + "use_impedances": False, + }, + "trunk": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "camera": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + }, + }, + { + "model": "r1pro", + "obs_modalities": "rgb", + "position": [0.7, -0.75, 0.0], + "orientation": [0, 0, 0.707, 0.707], + "self_collisions": True, + "action_normalize": False, + "controller_config": { + "base": { + "name": "HolonomicBaseJointController", + "motor_type": "position", + "command_input_limits": None, + "use_impedances": False, + }, + "trunk": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "arm_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_left": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + "gripper_right": { + "name": "JointController", + "motor_type": "position", + "command_input_limits": None, + "use_delta_commands": False, + "use_impedances": False, + }, + }, + }, + ] + for robot_cfg in robot_cfgs: + if th.cuda.is_available() and th.cuda.get_device_capability(0) == (12, 0): + # TODO [Wensi]: Check whether this is still true for future releases. + # Currently (v3.9.3), for cuda architecture 12.0 (e.g. RTX 50-series), using Default embodiment for Tiago or non-DEFAULT embodiment for R1Pro + # will raise CUDA illegal memory access error during mg.warmup() due to cuRobo compatibility issues. + # Therefore, we remove R1Pro for testing if we detect such GPU is being used. + if robot_cfg["model"] == "r1pro": + print( + f"Skipping testing for {robot_cfg['model']} on cuda architecture 12.0 GPU due to cuRobo embodiment compatibility issues." + ) + continue + cfg["robots"] = [robot_cfg] + + env = og.Environment(configs=cfg) + robot = env.scene.robots[0] + obj = env.scene.object_registry("name", "obj0") + eef_markers = [env.scene.object_registry("name", f"eef_marker_{i}") for i in range(2)] + + floor_touching_base_link_prim_paths = ( + [os.path.join(robot.prim_path, link_name) for link_name in robot.floor_touching_base_link_names] + if robot.is_locomotion + else [] + ) + + robot.reset() + + # Open the gripper(s) to match cuRobo's default state + for arm_name in robot.gripper_control_idx.keys(): + gripper_control_idx = robot.gripper_control_idx[arm_name] + robot.set_joint_positions(th.ones_like(gripper_control_idx), indices=gripper_control_idx, normalized=True) + + robot.keep_still() + + for _ in range(5): + og.sim.step() + + env.scene.update_initial_file() + env.scene.reset() + + # Create CuRobo instance + batch_size = 2 + n_samples = 20 + max_false_positive_rate = 0.05 + max_false_negative_rate = 0.0 + + cmg = CuRoboMotionGenerator( + robot=robot, + batch_size=batch_size, + debug=False, + use_cuda_graph=True, + collision_activation_distance=0.075, # Use larger activation distance for better reproducibility + use_default_embodiment_only=False, + ) + + # Sample values for robot + th.manual_seed(1) + lo, hi = robot.joint_lower_limits.clone().view(1, -1), robot.joint_upper_limits.clone().view(1, -1) + + if robot.is_holonomic_base: + lo[0, :2] = -0.1 + lo[0, 2:5] = 0.0 + lo[0, 5] = -math.pi + hi[0, :2] = 0.1 + hi[0, 2:5] = 0.0 + hi[0, 5] = math.pi + + random_qs = lo + th.rand((n_samples, robot.n_dof)) * (hi - lo) + + # Test collision with the environment (not including self-collisions) + collision_results = cmg.check_collisions(q=random_qs) + + target_pos, target_quat = defaultdict(list), defaultdict(list) + + floor_plane_prim_paths = {child.GetPath().pathString for child in og.sim.floor_plane._prim.GetChildren()} + + # View results + false_positive = 0 + false_negative = 0 + + for i, (q, curobo_has_contact) in enumerate(zip(random_qs, collision_results)): + # Set robot to desired qpos + robot.set_joint_positions(q) + robot.keep_still() + og.sim.step_physics() + + # To debug + # cmg.save_visualization(robot.get_joint_positions(), "test.obj") + + # Sanity check in the GUI that the robot pose makes sense + for _ in range(10): + og.sim.render() + + # Validate that expected collision result is correct + self_collision_pairs = set() + floor_contact_pairs = set() + wheel_contact_pairs = set() + obj_contact_pairs = set() + + for body0, body1 in RigidContactAPI.get_contact_pairs( + env.scene.idx, set(robot.links.values()), with_set=None, current_only=False + ): + assert body0 in robot.link_prim_paths + if body1 in robot.link_prim_paths: + self_collision_pairs.add((body0, body1)) + elif body1 in floor_plane_prim_paths: + if body0 not in floor_touching_base_link_prim_paths: + floor_contact_pairs.add((body0, body1)) + else: + wheel_contact_pairs.add((body0, body1)) + elif body1 in obj.link_prim_paths: + obj_contact_pairs.add((body0, body1)) + else: + assert False, f"Unexpected contact pair: {body0}, {body1}" + + touching_itself = len(self_collision_pairs) > 0 + touching_floor = len(floor_contact_pairs) > 0 + touching_object = len(obj_contact_pairs) > 0 + + curobo_has_contact = curobo_has_contact.item() + physx_has_contact = touching_itself or touching_floor or touching_object + + # cuRobo reports contact, but physx reports no contact + if curobo_has_contact and not physx_has_contact: + false_positive += 1 + print( + f"False positive {i}: {curobo_has_contact} vs. {physx_has_contact} (touching_itself/obj/floor: {touching_itself}/{touching_object}/{touching_floor})" + ) + + # physx reports contact, but cuRobo reports no contact + elif not curobo_has_contact and physx_has_contact: + false_negative += 1 + print( + f"False negative {i}: {curobo_has_contact} vs. {physx_has_contact} (touching_itself/obj/floor: {touching_itself}/{touching_object}/{touching_floor})" + ) + + # neither cuRobo nor physx reports contact, valid planning goals + elif not curobo_has_contact and not physx_has_contact: + for arm_name in robot.arm_names: + eef_pos, eef_quat = robot.get_eef_pose(arm_name) + target_pos[robot.eef_link_names[arm_name]].append(eef_pos) + target_quat[robot.eef_link_names[arm_name]].append(eef_quat) + + print( + f"Collision checking false positive: {false_positive / n_samples}, false negative: {false_negative / n_samples}." + ) + assert ( + false_positive / n_samples <= max_false_positive_rate + ), f"Collision checking false positive rate: {false_positive / n_samples} > {max_false_positive_rate}" + assert ( + false_negative / n_samples <= max_false_negative_rate + ), f"Collision checking false negative rate: {false_negative / n_samples} > {max_false_negative_rate}" + + env.scene.reset() + + for arm_name in robot.arm_names: + target_pos[robot.eef_link_names[arm_name]] = th.stack(target_pos[robot.eef_link_names[arm_name]], dim=0) + target_quat[robot.eef_link_names[arm_name]] = th.stack(target_quat[robot.eef_link_names[arm_name]], dim=0) + + # Cast defaultdict to dict + target_pos = dict(target_pos) + target_quat = dict(target_quat) + + print(f"Planning for {len(target_pos[robot.eef_link_names[robot.default_arm]])} eef targets...") + + # Make sure robot is kept still for better determinism before planning + robot.keep_still() + og.sim.step_physics() + + # Generate collision-free trajectories to the sampled eef poses (including self-collisions) + successes, traj_paths = cmg.compute_trajectories( + target_pos=target_pos, + target_quat=target_quat, + is_local=False, + max_attempts=100, + timeout=60.0, + ik_fail_return=50, + enable_finetune_trajopt=True, + finetune_attempts=1, + return_full_result=False, + success_ratio=1.0, + attached_obj=None, + ) + + # Make sure collision-free trajectories are generated + success_rate = successes.double().mean().item() + print(f"Collision-free trajectory generation success rate: {success_rate}") + assert success_rate == 1.0, f"Collision-free trajectory generation success rate: {success_rate}" + + # for bypass_physics in [True, False]: + for bypass_physics in [True]: + for traj_idx, (success, traj_path) in enumerate(zip(successes, traj_paths)): + if not success: + continue + + # Reset the environment + env.scene.reset() + + # Move the markers to the desired eef positions + for marker, arm_name in zip(eef_markers, robot.arm_names): + eef_link_name = robot.eef_link_names[arm_name] + marker.set_position_orientation(position=target_pos[eef_link_name][traj_idx]) + + q_traj = cmg.path_to_joint_trajectory(traj_path).cpu().float() + if not bypass_physics: + q_traj = cmg.add_linearly_interpolated_waypoints(traj=q_traj, max_inter_dist=0.01) + # joint_positions_set_point = [] + # joint_positions_response = [] + for i, q in enumerate(q_traj): + if bypass_physics: + print(f"Teleporting waypoint {i}/{len(q_traj)}") + robot.set_joint_positions(q) + robot.keep_still() + og.sim.step() + for body0, body1 in RigidContactAPI.get_contact_pairs( + env.scene.idx, set(robot.links.values()), with_set=None, current_only=False + ): + assert body0 in robot.link_prim_paths + if body1 in floor_plane_prim_paths and body0 in floor_touching_base_link_prim_paths: + continue + print(f"Unexpected contact pair during traj rollout: {body0}, {body1}") + assert False, f"Unexpected contact pair during traj rollout: {body0}, {body1}" + else: + # Convert target joint positions to action + action = robot.q_to_action(q) + + print(f"Executing waypoint {i}/{len(q_traj)}") + env.step(action) + + for body0, body1 in RigidContactAPI.get_contact_pairs( + env.scene.idx, set(robot.links.values()), with_set=None, current_only=False + ): + assert body0 in robot.link_prim_paths + if body1 in floor_plane_prim_paths and body0 in floor_touching_base_link_prim_paths: + continue + print(f"Unexpected contact pair during traj rollout: {body0}, {body1}") + # Controller is not perfect, so collisions might happen + # assert False, f"Unexpected contact pair during traj rollout: {body0}, {body1}" + + og.clear() + + del cmg + gc.collect() + th.cuda.empty_cache() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_data_collection.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_data_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e7e313f80904531881edbd2f5ae759a2b6a9c7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_data_collection.py @@ -0,0 +1,774 @@ +import h5py +import json +import tempfile +from unittest.mock import MagicMock + +import torch as th +import os + +import omnigibson as og +from omnigibson.envs import HDF5CollectionWrapper, HDF5PlaybackWrapper, LeRobotPlaybackWrapper, LeRobotDataWrapper +from omnigibson.envs.data_wrapper import ( + _align_scene_object_states_with_recorded_schema, + _is_system_particle_template_info, + _is_system_particle_template_name, +) +from omnigibson.envs.hdf5_data_wrapper import HDF5DataWrapper +from omnigibson.macros import gm +from omnigibson.objects import DatasetObject +from omnigibson.systems.macro_particle_system import MacroPhysicalParticleSystem + +from lerobot.datasets.lerobot_dataset import LeRobotDataset + + +# --------------------------------------------------------------------------- +# Helpers for unit tests +# --------------------------------------------------------------------------- + + +class _MockGymSpace: + def __init__(self, shape): + self.shape = shape + + +class _MinimalHDF5Wrapper(HDF5DataWrapper): + """Concrete subclass that bypasses Environment setup for unit testing.""" + + def __init__(self, hdf5_file, compression=None): + self.wrapped_obj = None + self.hdf5_file = hdf5_file + self.compression = compression or {} + self.traj_count = 0 + self.step_count = 0 + self.current_traj_history = [] + self.flush_every_n_traj = 10 + self.only_successes = False + self.max_state_size = 0 + self.current_transitions = dict() + self.checkpoint_rollback_trajs = None + + +def test_system_particle_template_transition_helpers(): + system_names = {"diced__head_cabbage"} + template_info = { + "class_module": "omnigibson.objects.usd_object", + "class_name": "USDObject", + "args": { + "name": "diced__head_cabbage_template", + "category": "diced__head_cabbage", + "relative_prim_path": "/diced__head_cabbage/template", + "usd_path": "/workspace/OmniGibson/omnigibson/data/og_dataset/systems/diced__head_cabbage/rflakn/usd/rflakn.usd", + }, + } + normal_object_info = { + "class_module": "omnigibson.objects.dataset_object", + "class_name": "DatasetObject", + "args": { + "name": "diced__head_cabbage_1", + "category": "diced__head_cabbage", + "relative_prim_path": "/diced__head_cabbage_1", + }, + } + + assert _is_system_particle_template_info(template_info, system_names) + assert not _is_system_particle_template_info(normal_object_info, system_names) + assert _is_system_particle_template_name("diced__head_cabbage_template", system_names) + assert not _is_system_particle_template_name("diced__head_cabbage_1", system_names) + + +def test_macro_physical_particle_system_update_handles_waits_for_physics_view(monkeypatch): + system = MacroPhysicalParticleSystem.__new__(MacroPhysicalParticleSystem) + system.particles_view = "stale_view" + + mock_sim = MagicMock() + mock_sim.is_playing.return_value = False + mock_sim.physics_sim_view = MagicMock() + monkeypatch.setattr(og, "sim", mock_sim) + + system.update_handles() + + assert system.particles_view is None + mock_sim.physics_sim_view.create_rigid_body_view.assert_not_called() + + system.particles_view = "stale_view" + mock_sim.is_playing.return_value = True + mock_sim.physics_sim_view = None + + system.update_handles() + + assert system.particles_view is None + + +def test_align_scene_object_states_with_recorded_schema_marks_serialized_states(): + class RecordedState: + pass + + class ExtraState: + pass + + obj = MagicMock() + obj.states = { + RecordedState: MagicMock(stateful=True), + ExtraState: MagicMock(stateful=True), + } + scene = MagicMock() + scene.object_registry.return_value = obj + recorded_scene_file = { + "state": { + "registry": { + "object_registry": { + "toaster_91": { + "non_kin": { + "RecordedState": {}, + }, + }, + }, + }, + }, + } + + _align_scene_object_states_with_recorded_schema(scene=scene, recorded_scene_file=recorded_scene_file) + + assert set(obj.states) == {RecordedState, ExtraState} + assert obj._recorded_non_kin_state_names == {"RecordedState"} + + +# --------------------------------------------------------------------------- +# Unit tests – HDF5DataWrapper._process_traj_to_hdf5 +# --------------------------------------------------------------------------- + + +def test_hdf5_process_traj_to_hdf5(): + fd, path = tempfile.mkstemp(".hdf5", dir=og.tempdir) + os.close(fd) + + with h5py.File(path, "w") as f: + wrapper = _MinimalHDF5Wrapper(hdf5_file=f) + traj_data = [ + {"obs": {"proprio": th.zeros(2)}}, + {"action": th.tensor([1.0, 2.0]), "reward": 0.5, "terminated": False}, + {"action": th.tensor([3.0, 4.0]), "reward": 1.0, "terminated": True}, + ] + grp = wrapper._process_traj_to_hdf5(traj_data, "demo_0") + + assert "action" in grp + assert grp["action"].shape == (2, 2) + assert th.allclose(th.tensor(grp["action"][()]), th.tensor([[1.0, 2.0], [3.0, 4.0]])) + + assert "reward" in grp + assert grp["reward"].shape == (2,) + assert th.allclose(th.tensor(grp["reward"][()]), th.tensor([0.5, 1.0])) + + assert "terminated" in grp + assert grp["terminated"].shape == (2,) + assert grp.attrs["num_samples"] == 2 + + +def test_hdf5_process_traj_nested_obs(): + fd, path = tempfile.mkstemp(".hdf5", dir=og.tempdir) + os.close(fd) + + with h5py.File(path, "w") as f: + wrapper = _MinimalHDF5Wrapper(hdf5_file=f) + traj_data = [ + {"obs": {"rgb": th.full((3, 4, 4), -1.0), "proprio": th.full((5,), -1.0)}}, + {"obs": {"rgb": th.zeros(3, 4, 4), "proprio": th.ones(5)}, "action": th.zeros(2)}, + {"obs": {"rgb": th.ones(3, 4, 4), "proprio": th.zeros(5)}, "action": th.ones(2)}, + ] + grp = wrapper._process_traj_to_hdf5(traj_data, "demo_0", nested_keys=["obs"]) + + assert "obs" in grp + assert grp["obs"]["rgb"].shape == (2, 3, 4, 4) + assert grp["obs"]["proprio"].shape == (2, 5) + assert grp["action"].shape == (2, 2) + + +def test_hdf5_add_metadata_roundtrip(): + fd, path = tempfile.mkstemp(".hdf5", dir=og.tempdir) + os.close(fd) + + with h5py.File(path, "w") as f: + wrapper = _MinimalHDF5Wrapper(hdf5_file=f) + data_grp = f.create_group("data") + + dict_data = {"key1": [1, 2, 3], "key2": "value"} + wrapper.add_metadata(data_grp, "config", dict_data) + + raw = data_grp.attrs["config"] + round_tripped = json.loads(raw) + assert round_tripped == dict_data + + wrapper.add_metadata(data_grp, "episode_count", 42) + assert data_grp.attrs["episode_count"] == 42 + + +def test_hdf5_close_dataset_attrs(): + fd, path = tempfile.mkstemp(".hdf5", dir=og.tempdir) + os.close(fd) + + with h5py.File(path, "w") as f: + wrapper = _MinimalHDF5Wrapper(hdf5_file=f) + f.create_group("data") + wrapper.traj_count = 7 + wrapper.step_count = 100 + wrapper.close_dataset() + + with h5py.File(path, "r") as f: + assert f["data"].attrs["n_episodes"] == 7 + assert f["data"].attrs["n_steps"] == 100 + + +def test_hdf5_traj_compression(): + fd, path = tempfile.mkstemp(".hdf5", dir=og.tempdir) + os.close(fd) + + compression = {"compression": "gzip", "compression_opts": 9} + with h5py.File(path, "w") as f: + wrapper = _MinimalHDF5Wrapper(hdf5_file=f, compression=compression) + traj_data = [ + {"obs": {"proprio": th.zeros(10)}}, + {"action": th.randn(10), "reward": th.tensor(0.1)}, + {"action": th.randn(10), "reward": th.tensor(0.2)}, + ] + grp = wrapper._process_traj_to_hdf5(traj_data, "demo_0") + + assert grp["action"].compression == "gzip" + assert grp["reward"].compression == "gzip" + expected_actions = th.stack([d["action"] for d in traj_data if "action" in d], dim=0) + assert th.allclose(th.tensor(grp["action"][()]), expected_actions) + + +# --------------------------------------------------------------------------- +# Unit tests – LeRobotDataWrapper.get_lerobot_obs_mapping +# --------------------------------------------------------------------------- + + +def test_lerobot_obs_mapping_proprio(): + mock_env = MagicMock() + mock_env.observation_space = { + "robot::fetch:proprio::proprio": _MockGymSpace((12,)), + } + + mapping, features = LeRobotDataWrapper.get_lerobot_obs_mapping(mock_env) + + assert "robot::fetch:proprio::proprio" in mapping + assert mapping["robot::fetch:proprio::proprio"] == "observation.state" + assert "observation.state" in features + assert features["observation.state"]["dtype"] == "float32" + assert features["observation.state"]["shape"] == (12,) + + +def test_lerobot_obs_mapping_rgb(): + mock_env = MagicMock() + mock_env.observation_space = { + "robot::fetch:eef_link:Camera:0::rgb": _MockGymSpace((128, 128, 4)), + } + + mapping, features = LeRobotDataWrapper.get_lerobot_obs_mapping(mock_env) + + assert mapping["robot::fetch:eef_link:Camera:0::rgb"] == "observation.rgb.eef_link_camera_0" + key = "observation.rgb.eef_link_camera_0" + assert key in features + assert features[key]["dtype"] == "video" + assert features[key]["shape"] == (128, 128, 3) + + +def test_lerobot_obs_mapping_depth(): + mock_env = MagicMock() + mock_env.observation_space = { + "robot::fetch:eef_link:Camera:0::depth_linear": _MockGymSpace((128, 128)), + } + + mapping, features = LeRobotDataWrapper.get_lerobot_obs_mapping(mock_env) + + assert "observation.depth_linear.eef_link_camera_0" in features + assert features["observation.depth_linear.eef_link_camera_0"]["dtype"] == "video" + assert features["observation.depth_linear.eef_link_camera_0"]["shape"] == (128, 128, 1) + + tf_key = "observation.robot2cam_pose.eef_link_camera_0" + assert tf_key in features + assert features[tf_key]["shape"] == (7,) + + +# --------------------------------------------------------------------------- +# Unit tests – DataWrapper.should_save_current_episode / flush_current_traj +# --------------------------------------------------------------------------- + + +def test_should_save_current_episode(): + mock_env = MagicMock() + # task.success is a (num_envs,) bool tensor post-#2001 vector-env refactor. + mock_env.task.success = th.tensor([False]) + + wrapper = _MinimalHDF5Wrapper(hdf5_file=MagicMock()) + wrapper.env = mock_env + wrapper.only_successes = True + wrapper.current_traj_history = [] + # Failed episode with no initial-obs-only exception should not be saved. + assert not wrapper.should_save_current_episode + # Initial observation only should NOT be saved. + wrapper.current_traj_history = [{"obs": {"proprio": th.zeros(2)}}] + assert not wrapper.should_save_current_episode + # Failed episode with trajectory data beyond initial obs should not be saved when only_successes=True. + wrapper.current_traj_history = [ + {"obs": {"proprio": th.zeros(2)}}, + {"action": th.zeros(2), "reward": 0.0, "terminated": False, "truncated": False}, + ] + assert not wrapper.should_save_current_episode + wrapper.only_successes = False + assert wrapper.should_save_current_episode + # Even when only_successes=False, obs-only trajectories are still excluded from saving. + wrapper.current_traj_history = [{"obs": {"proprio": th.zeros(2)}}] + assert not wrapper.should_save_current_episode + wrapper.only_successes = True + wrapper.current_traj_history = [ + {"obs": {"proprio": th.zeros(2)}}, + {"action": th.zeros(2), "reward": 0.0, "terminated": True, "truncated": False}, + ] + mock_env.task.success = th.tensor([True]) + assert wrapper.should_save_current_episode + + +def test_flush_current_traj_counter(): + fd, path = tempfile.mkstemp(".hdf5", dir=og.tempdir) + os.close(fd) + + with h5py.File(path, "w") as f: + wrapper = _MinimalHDF5Wrapper(hdf5_file=f) + mock_env = MagicMock() + mock_env.task.success = th.tensor([False]) + wrapper.env = mock_env + wrapper.only_successes = False + f.create_group("data") + + wrapper.current_traj_history = [ + {"obs": {"proprio": th.zeros(2)}}, + {"action": th.tensor([1.0, 2.0])}, + {"action": th.tensor([3.0, 4.0])}, + ] + assert wrapper.traj_count == 0 + wrapper.flush_current_traj() + assert wrapper.traj_count == 1 + assert len(wrapper.current_traj_history) == 0 + + +# --------------------------------------------------------------------------- +# Integration test helpers +# --------------------------------------------------------------------------- + + +def _get_test_cfg(): + return { + "env": { + "external_sensors": [], + }, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": ["floors", "breakfast_table"], + }, + "robots": [ + { + "model": "fetch", + "name": "fetch", + "obs_modalities": [], + "fixed_base": False, + } + ], + "task": { + "type": "BehaviorTask", + "activity_name": "laying_wood_floors", + "online_object_sampling": True, + "use_presampled_robot_pose": False, + }, + } + + +def _ensure_sim_stopped(): + if og.sim is None: + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_TRANSITION_RULES = False + else: + og.sim.stop() + + +def _get_playback_configs(img_h, img_w, cfg): + robot_sensor_config = { + "VisionSensor": { + "modalities": ["rgb", "depth_linear"], + "sensor_kwargs": { + "image_height": img_h, + "image_width": img_w, + }, + }, + } + external_sensors_config = [ + { + "sensor_type": "VisionSensor", + "name": "external_sensor0", + "relative_prim_path": f"/controllable__{cfg['robots'][0]['model'].lower()}__{cfg['robots'][0]['name']}/root_link/external_sensor0", + "modalities": ["rgb", "depth_linear"], + "sensor_kwargs": { + "image_height": img_h, + "image_width": img_w, + }, + "position": th.tensor([-0.26549, -0.30288, 1.0 + 0.861], dtype=th.float32), + "orientation": th.tensor([0.36165891, -0.24745751, -0.50752921, 0.74187715], dtype=th.float32), + }, + ] + return robot_sensor_config, external_sensors_config + + +# --------------------------------------------------------------------------- +# Integration tests – data collection +# --------------------------------------------------------------------------- + + +def test_collection_basic(): + cfg = _get_test_cfg() + _ensure_sim_stopped() + + _, collect_hdf5_path = tempfile.mkstemp("test_collection_basic.hdf5", dir=og.tempdir) + + env = og.Environment(configs=cfg) + env = HDF5CollectionWrapper( + env=env, + output_path=collect_hdf5_path, + only_successes=False, + obj_attr_keys=["scale", "visible"], + ) + + for _ in range(2): + env.reset() + for _ in range(3): + env.step(env.scene.robots[0].action_space.sample()) + + env.save_data() + + with h5py.File(collect_hdf5_path, "r") as f: + assert f["data"].attrs["n_episodes"] == 2 + assert f["data"].attrs["n_steps"] > 0 + assert "demo_0" in f["data"] + assert "demo_1" in f["data"] + + og.clear() + + +def test_collection_with_transitions(): + cfg = _get_test_cfg() + _ensure_sim_stopped() + + _, collect_hdf5_path = tempfile.mkstemp("test_collection_transitions.hdf5", dir=og.tempdir) + + env = og.Environment(configs=cfg) + env = HDF5CollectionWrapper( + env=env, + output_path=collect_hdf5_path, + only_successes=False, + ) + + env.reset() + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + obj = DatasetObject(name="banana", category="banana") + env.scene.add_object(obj) + obj.set_position(th.ones(3, dtype=th.float32) * 10.0) + + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + env.scene.remove_object(obj) + + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + water = env.scene.get_system("water") + water.generate_particles(positions=th.rand(5, 3, dtype=th.float32) * 10.0) + + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + env.scene.clear_system("water") + + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + env.save_data() + + with h5py.File(collect_hdf5_path, "r") as f: + demo_grp = f["data"]["demo_0"] + transitions = json.loads(demo_grp.attrs["transitions"]) + assert len(transitions) > 0 + + og.clear() + + +def test_collection_checkpoint_rollback(): + cfg = _get_test_cfg() + _ensure_sim_stopped() + + _, collect_hdf5_path = tempfile.mkstemp("test_collection_ckpt.hdf5", dir=og.tempdir) + + env = og.Environment(configs=cfg) + env = HDF5CollectionWrapper( + env=env, + output_path=collect_hdf5_path, + only_successes=False, + ) + + env.reset() + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + env.update_checkpoint() + robot_eef_state = {arm: env.scene.robots[0].get_eef_position(arm=arm) for arm in env.scene.robots[0].arm_names} + + env.step(env.scene.robots[0].action_space.sample()) + + water = env.scene.get_system("water") + water.generate_particles(positions=th.rand(10, 3, dtype=th.float32) * 10.0) + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + + env.rollback_to_checkpoint() + + assert "water" not in env.scene.active_systems + + for arm, pos in robot_eef_state.items(): + assert th.all(th.isclose(pos, env.scene.robots[0].get_eef_position(arm=arm))).item() + + for _ in range(2): + env.step(env.scene.robots[0].action_space.sample()) + env.save_data() + + with h5py.File(collect_hdf5_path, "r") as f: + assert f["data"].attrs["n_episodes"] == 1 + assert "demo_0" in f["data"] + + og.clear() + + +# --------------------------------------------------------------------------- +# Integration tests – playback +# --------------------------------------------------------------------------- + + +def test_hdf5_playback_and_dataset(): + cfg = _get_test_cfg() + img_h, img_w = 128, 128 + _ensure_sim_stopped() + + _, collect_hdf5_path = tempfile.mkstemp("test_hdf5_playback_collect.hdf5", dir=og.tempdir) + _, playback_hdf5_path = tempfile.mkstemp("test_hdf5_playback_output.hdf5", dir=og.tempdir) + + # --- Collect data --- + env = og.Environment(configs=cfg) + env = HDF5CollectionWrapper( + env=env, + output_path=collect_hdf5_path, + only_successes=False, + ) + + for _ in range(2): + env.reset() + for _ in range(3): + env.step(env.scene.robots[0].action_space.sample()) + + env.save_data() + + # --- Playback --- + og.clear( + physics_dt=0.001, + rendering_dt=0.001, + sim_step_dt=0.001, + ) + + robot_sensor_config, external_sensors_config = _get_playback_configs(img_h, img_w, cfg) + obs_modalities = ["proprio", "rgb", "depth_linear"] + + env = HDF5PlaybackWrapper.create_from_hdf5( + input_path=collect_hdf5_path, + output_path=playback_hdf5_path, + robot_obs_modalities=obs_modalities, + robot_sensor_config=robot_sensor_config, + external_sensors_config=external_sensors_config, + n_render_iterations=1, + only_successes=False, + ) + + obs, info = env.reset() + for mod in obs_modalities: + found_obs_key = False + for obs_key in obs.keys(): + if mod in obs_key.split("::")[-1]: + found_obs_key = True + break + assert found_obs_key, f"Failed to find obs modality: {mod} in observation keys: {tuple(obs.keys())}" + + env.playback_dataset(record_data=True) + env.save_data() + + with h5py.File(playback_hdf5_path, "r") as f: + assert f["data"].attrs["n_episodes"] == 2 + assert "demo_0" in f["data"] + assert "demo_1" in f["data"] + assert "omnigibson_git_hash" in f["data"].attrs + assert f["data"].attrs["omnigibson_git_hash"] is not None + + n_episodes = f["data"].attrs["n_episodes"] + assert n_episodes == 2, f"Expected 2 episodes, got {n_episodes}" + + for demo_idx in range(n_episodes): + demo_grp = f["data"][f"demo_{demo_idx}"] + + if "observation" in demo_grp: + obs_grp = demo_grp["observation"] + for obs_key in obs_grp.keys(): + obs_data = obs_grp[obs_key] + if isinstance(obs_data, h5py.Dataset): + assert obs_data.shape[0] > 0, f"Demo {demo_idx} observation {obs_key} has no data" + + if "rgb" in obs_key: + expected_shape = (obs_data.shape[0], 3, img_h, img_w) + assert ( + obs_data.shape == expected_shape + ), f"Demo {demo_idx} obs {obs_key}: expected {expected_shape}, got {obs_data.shape}" + if ( + "external_sensor0" not in obs_key + and "eef_link_camera_0" not in obs_key + and "eyes_camera_0" not in obs_key + ): + assert False, ( + f"Demo {demo_idx} obs {obs_key} has unexpected rgb key (expected one of: " + "observation.rgb.external_sensor0, observation.rgb.eef_link_camera_0, observation.rgb.eyes_camera_0)" + ) + elif "depth_linear" in obs_key: + expected_shape = (obs_data.shape[0], 3, img_h, img_w) + assert ( + obs_data.shape == expected_shape + ), f"Demo {demo_idx} obs {obs_key}: expected {expected_shape}, got {obs_data.shape}" + if "eef_link_camera_0" not in obs_key and "eyes_camera_0" not in obs_key: + assert False, ( + f"Demo {demo_idx} obs {obs_key} has unexpected depth_linear key (expected one of: " + "observation.depth_linear.eef_link_camera_0, observation.depth_linear.eyes_camera_0)" + ) + + if "action" in demo_grp: + action_data = demo_grp["action"] + if isinstance(action_data, h5py.Dataset): + assert action_data.shape[0] > 0, f"Demo {demo_idx} action has no data" + assert len(action_data.shape) == 2, f"Demo {demo_idx} action should be 2D" + + if "proprio" in demo_grp: + proprio_data = demo_grp["proprio"] + if isinstance(proprio_data, h5py.Dataset): + assert proprio_data.shape[0] > 0, f"Demo {demo_idx} proprio has no data" + + og.sim.stop() + og.clear( + physics_dt=1 / 120.0, + rendering_dt=1 / 30.0, + sim_step_dt=1 / 30.0, + ) + + +def test_lerobot_playback_and_dataset(): + cfg = _get_test_cfg() + img_h, img_w = 128, 128 + _ensure_sim_stopped() + + _, collect_hdf5_path = tempfile.mkstemp("test_lerobot_playback_collect.hdf5", dir=og.tempdir) + _, playback_hdf5_path = tempfile.mkstemp("test_lerobot_playback_output.hdf5", dir=og.tempdir) + + # --- Collect data --- + env = og.Environment(configs=cfg) + env = HDF5CollectionWrapper( + env=env, + output_path=collect_hdf5_path, + only_successes=False, + ) + + for _ in range(2): + env.reset() + for _ in range(3): + env.step(env.scene.robots[0].action_space.sample()) + + env.save_data() + + # --- LeRobot Playback --- + og.clear( + physics_dt=0.001, + rendering_dt=0.001, + sim_step_dt=0.001, + ) + + robot_sensor_config, external_sensors_config = _get_playback_configs(img_h, img_w, cfg) + obs_modalities = ["proprio", "rgb", "depth_linear"] + + lerobot_playback_kwargs = { + "output_path": "behavior1k/test_dataset", + "root_dir": os.path.dirname(playback_hdf5_path), + } + + env = LeRobotPlaybackWrapper.create_from_hdf5( + input_path=collect_hdf5_path, + robot_obs_modalities=obs_modalities, + robot_sensor_config=robot_sensor_config, + external_sensors_config=external_sensors_config, + n_render_iterations=1, + only_successes=False, + **lerobot_playback_kwargs, + ) + + obs, info = env.reset() + for mod in obs_modalities: + found_obs_key = False + for obs_key in obs.keys(): + if mod in obs_key.split("::")[-1]: + found_obs_key = True + break + assert found_obs_key, f"Failed to find obs modality: {mod} in observation keys: {tuple(obs.keys())}" + + env.playback_dataset(record_data=True) + env.save_data() + + # --- Validate LeRobot dataset --- + dataset = LeRobotDataset( + repo_id=lerobot_playback_kwargs["output_path"], + root=f"{lerobot_playback_kwargs['root_dir']}/{lerobot_playback_kwargs['output_path']}", + delta_timestamps={ + "observation.rgb.external_sensor0": [-i / 30 for i in reversed(range(5))], + }, + ) + + batch_size = 6 + data_loader = th.utils.data.DataLoader(dataset, batch_size=batch_size) + batch = next(iter(data_loader)) + + shape = (img_h, img_w) + for key, shape in ( + ("action", (12,)), + ("observation.rgb.external_sensor0", (5, 3, *shape)), + ("observation.rgb.eef_link_camera_0", (3, *shape)), + ("observation.rgb.eyes_camera_0", (3, *shape)), + ("observation.depth_linear.eef_link_camera_0", (3, *shape)), + ("observation.depth_linear.eyes_camera_0", (3, *shape)), + ): + assert key in batch + expected_shape = (batch_size, *shape) + assert ( + batch[key].shape == expected_shape + ), f"Expected key [{key}] to have shape {expected_shape}, but got {batch[key].shape}" + + # Validate metadata + assert dataset.meta.info["omnigibson_git_hash"] is not None + assert "cam_intrinsics" in dataset.meta.info + + og.sim.stop() + og.clear( + physics_dt=1 / 120.0, + rendering_dt=1 / 30.0, + sim_step_dt=1 / 30.0, + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_dump_load_states.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_dump_load_states.py new file mode 100644 index 0000000000000000000000000000000000000000..7a02149ef68e842bf02084ec87136ff17a0f0c97 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_dump_load_states.py @@ -0,0 +1,76 @@ +import tempfile + +import torch as th +from utils import SYSTEM_EXAMPLES + +import omnigibson as og +from omnigibson.object_states import Covered +from omnigibson.systems import VisualParticleSystem + + +def test_dump_load(env, breakfast_table): + for system_name, system_class in SYSTEM_EXAMPLES.items(): + system = env.scene.get_system(system_name) + assert isinstance(system, system_class) + if issubclass(system_class, VisualParticleSystem): + assert breakfast_table.states[Covered].set_value(system, True) + else: + system.generate_particles(positions=th.tensor([[0, 0, 1]])) + assert system.n_particles > 0 + system.remove_all_particles() + + state = og.sim.dump_state() + og.sim.load_state(state) + + for system_name, system_class in SYSTEM_EXAMPLES.items(): + env.scene.clear_system(system_name) + + +def test_dump_load_serialized(env, breakfast_table): + for system_name, system_class in SYSTEM_EXAMPLES.items(): + system = env.scene.get_system(system_name) + assert isinstance(system, system_class) + if issubclass(system_class, VisualParticleSystem): + assert breakfast_table.states[Covered].set_value(system, True) + else: + system.generate_particles(positions=th.tensor([[0, 0, 1]])) + assert system.n_particles > 0 + + state = og.sim.dump_state(serialized=True) + og.sim.load_state(state, serialized=True) + + for system_name, system_class in SYSTEM_EXAMPLES.items(): + env.scene.clear_system(system_name) + + +def test_save_restore_partial(env, breakfast_table): + decrypted_fd, tmp_json_path = tempfile.mkstemp("test_save_restore.json", dir=og.tempdir) + og.sim.save([tmp_json_path]) + + # Delete the breakfast table + env.scene.remove_object(breakfast_table) + + og.sim.step() + + # Restore the saved environment + og.sim.restore([tmp_json_path]) + + # Make sure we still have an object that existed beforehand + assert og.sim.scenes[0].object_registry("name", "breakfast_table") is not None + + +def test_save_restore_full(env, breakfast_table): + decrypted_fd, tmp_json_path = tempfile.mkstemp("test_save_restore.json", dir=og.tempdir) + og.sim.save([tmp_json_path]) + + # Clear the simulator + og.clear() + + # Restore the saved environment + og.sim.restore([tmp_json_path]) + + # This generates a new scene, so we monkey-patch it into the original env to avoid crashes + env._scenes[0] = og.sim.scenes[0] + + # Make sure we still have an object that existed beforehand + assert og.sim.scenes[0].object_registry("name", "breakfast_table") is not None diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_envs.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..b82f023f120965078af9ab62043a579191677a5a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_envs.py @@ -0,0 +1,94 @@ +import omnigibson as og +from omnigibson.macros import gm + + +def task_tester(task_type): + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": ["floors", "breakfast_table"], + }, + "robots": [ + { + "model": "fetch", + "obs_modalities": [], + } + ], + # Task kwargs + "task": { + "type": task_type, + # BehaviorTask-specific + "activity_name": "laying_wood_floors", + "online_object_sampling": True, + "use_presampled_robot_pose": False, + }, + } + + if og.sim is None: + # Make sure GPU dynamics are enabled (GPU dynamics needed for cloth) + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_TRANSITION_RULES = False + else: + # Make sure sim is stopped + og.sim.stop() + + # Create the environment + env = og.Environment(configs=cfg) + + env.reset() + for _ in range(5): + env.step(env.scenes[0].robots[0].action_space.sample()) + + # Clear the sim + og.clear() + + +def test_dummy_task(): + task_tester("DummyTask") + + +def test_point_reaching_task(): + task_tester("PointReachingTask") + + +def test_point_navigation_task(): + task_tester("PointNavigationTask") + + +def test_behavior_task(): + task_tester("BehaviorTask") + + +def test_rs_int_full_load(): + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + }, + "robots": [ + { + "type": "Fetch", + "obs_modalities": [], + } + ], + # Task kwargs + "task": { + "type": "DummyTask", + }, + } + + # Make sure sim is stopped + if og.sim: + og.sim.stop() + + # Create the environment + env = og.Environment(configs=cfg) + + env.reset() + for _ in range(5): + env.step(env.scenes[0].robots[0].action_space.sample()) + + # Clear the sim + og.clear() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_evaluator.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..11ffa907e4c30afe657117aa123a6373fb766b45 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_evaluator.py @@ -0,0 +1,177 @@ +from types import SimpleNamespace + +import pytest +import torch as th + +from omnigibson.eval.evaluator import ( + BatchedEvaluator, + InstanceEnvAccessor, + InstanceEvaluationState, + evaluate_instances_batched, +) +from omnigibson.metrics import TaskMetric + + +def test_evaluate_instances_batched_tracks_environments_and_requires_equal_batch_size(): + loaded_batches = [] + active_env_history = [] + + def load_fn(env_idx_to_instance): + loaded_batches.append(env_idx_to_instance) + + def step_fn(active_env_indices): + active_env_history.append(active_env_indices) + if len(active_env_history) == 1: + return [True, False], [False, False] + return [False, True], [False, False] + + def record_fn(**record): + return record + + results = evaluate_instances_batched( + instances=[101, 202], + num_envs=2, + load_fn=load_fn, + step_fn=step_fn, + record_fn=record_fn, + ) + + assert loaded_batches == [{0: 101, 1: 202}] + assert active_env_history == [[0, 1], [1]] + assert results[101] == {"env_idx": 0, "instance": 101, "step": 1, "terminated": True, "truncated": False} + assert results[202] == {"env_idx": 1, "instance": 202, "step": 2, "terminated": True, "truncated": False} + + with pytest.raises(ValueError, match="exactly one instance per logical environment"): + evaluate_instances_batched( + instances=[101], + num_envs=2, + load_fn=load_fn, + step_fn=step_fn, + record_fn=record_fn, + ) + + +def test_instance_evaluation_state_owns_one_logical_environment(): + robots = [object(), object()] + scenes = [SimpleNamespace(robots=[robot]) for robot in robots] + task = SimpleNamespace( + object_scope=[{"object": 0}, {"object": 1}], + success=th.tensor([False, True]), + get_goal_option_satisfaction=lambda env_idx: [[env_idx == 1]], + ) + shared_env = SimpleNamespace(scenes=scenes, task=task) + + states = [ + InstanceEvaluationState(InstanceEnvAccessor(shared_env=shared_env, env_idx=env_idx)) for env_idx in range(2) + ] + states[0].instance_id = 101 + states[0].obs = {"value": 1} + states[0].active = True + + assert states[0].env_accessor.scene is scenes[0] + assert states[1].env_accessor.robot is robots[1] + assert states[1].env_accessor.object_scope == {"object": 1} + assert states[1].env_accessor.success + assert states[1].env_accessor.get_goal_option_satisfaction() == [[True]] + assert states[1].instance_id is None + assert states[1].obs is None + assert not states[1].active + assert states[0].metrics is not states[1].metrics + + +def test_batched_evaluator_steps_shared_resources_once_and_freezes_finished_environments(): + class FakeMetric: + def __init__(self): + self.steps = [] + + def step(self, **kwargs): + self.steps.append(kwargs) + + class FakePolicy: + def __init__(self): + self.observations = [] + + def forward(self, obs): + self.observations.append(obs) + return th.tensor([[1.0, 2.0], [3.0, 4.0]]) + + class FakeEnv: + def __init__(self): + self.step_calls = [] + self.scenes = [ + SimpleNamespace(robots=[SimpleNamespace(action_dim=2)]), + SimpleNamespace(robots=[SimpleNamespace(action_dim=2)]), + ] + self.task = SimpleNamespace(activity_name="not_a_light_task") + + def step(self, actions, n_render_iterations): + self.step_calls.append((actions.clone(), n_render_iterations)) + obs = [{"value": th.tensor([10.0])}, {"value": th.tensor([20.0])}] + return obs, None, th.tensor([False, False]), th.tensor([False, False]), [{}, {}] + + shared_env = FakeEnv() + metrics = [FakeMetric(), FakeMetric()] + evaluator = BatchedEvaluator.__new__(BatchedEvaluator) + evaluator.num_envs = 2 + evaluator.env = shared_env + evaluator.policy = FakePolicy() + evaluator.instance_eval_states = [ + InstanceEvaluationState( + env_accessor=InstanceEnvAccessor(shared_env=shared_env, env_idx=env_idx), + metrics=[metrics[env_idx]], + obs={"value": th.tensor([float(env_idx)])}, + active=env_idx == 0, + ) + for env_idx in range(2) + ] + evaluator._preprocess_obs = lambda obs, instance_eval_state: obs + + evaluator._step_fn(active_env_indices=[0]) + + assert len(evaluator.policy.observations) == 1 + assert evaluator.policy.observations[0]["value"].shape == (2, 1) + assert len(shared_env.step_calls) == 1 + assert th.equal(shared_env.step_calls[0][0], th.tensor([[1.0, 2.0], [0.0, 0.0]])) + assert shared_env.step_calls[0][1] == 1 + assert th.equal(evaluator.instance_eval_states[0].obs["value"], th.tensor([10.0])) + assert th.equal(evaluator.instance_eval_states[1].obs["value"], th.tensor([1.0])) + assert len(metrics[0].steps) == 1 + assert metrics[1].steps == [] + + +def test_task_metrics_are_isolated_by_instance_environment_accessor(monkeypatch): + scenes = [object(), object()] + + class FakeTask: + def __init__(self): + self.success = th.tensor([False, True]) + self.goal_options = [[[False, False]], [[False, False]]] + + def get_goal_option_satisfaction(self, env_idx): + return self.goal_options[env_idx] + + task = FakeTask() + shared_env = SimpleNamespace(scenes=scenes, task=task) + monkeypatch.setattr("omnigibson.metrics.task_metric.og.sim", SimpleNamespace(get_rendering_dt=lambda: 0.1)) + metrics = [ + TaskMetric( + {"length": 10}, + env_accessor=InstanceEnvAccessor(shared_env=shared_env, env_idx=env_idx), + ) + for env_idx in range(2) + ] + + for metric in metrics: + metric.reset() + metric.step(action=None, obs={}, reward=0.0, terminated=False, truncated=False, info={}) + task.goal_options = [[[True, False]], [[False, False]]] + + assert metrics[0].aggregate()["q_score"]["final"] == 0.5 + assert metrics[1].aggregate()["q_score"]["final"] == 1.0 + + task.goal_options[0] = [[False, False]] + legacy_metric = TaskMetric({"length": 10}, env_idx=0) + legacy_metric.reset(shared_env) + legacy_metric.step(shared_env, None, {}, 0.0, False, False, {}) + task.goal_options[0] = [[True, False]] + assert legacy_metric.aggregate(shared_env)["q_score"]["final"] == 0.5 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_examples.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2832b9d7d79bc0e7230331a562d717c1b7b88e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_examples.py @@ -0,0 +1,78 @@ +import importlib +import os +from unittest.mock import patch + +import pytest + +# Must be set before omnigibson is imported so that gm.HEADLESS is True +os.environ.setdefault("OMNIGIBSON_HEADLESS", "1") + +# Explicit list of examples to test. In CI each example runs in its own matrix +# job (isolated process), so the Isaac Sim singleton is not an issue. When +# running locally always use -k to run a single example at a time. +EXAMPLES = [ + # --- BEGIN AUTO-GENERATED EXAMPLES --- + "environments.navigation_env_demo", + "environments.vector_env_demo", + "object_states.attachment_demo", + "object_states.dicing_demo", + "object_states.heated_state_demo", + "object_states.onfire_demo", + "object_states.overlaid_demo", + "object_states.particle_applier_remover_demo", + "object_states.sample_kinematics_demo", + "object_states.slicing_demo", + "object_states.temperature_demo", + "objects.draw_bounding_box", + "objects.highlight_objects", + "objects.load_object_selector", + "objects.visualize_object", + "robots.all_robots_visualizer", + "robots.grasping_mode_example", + "robots.import_custom_robot", + "robots.robot_control_example", + "scenes.scene_selector", + "scenes.scene_tour_demo", + "scenes.traversability_map_example", + "simulator.sim_save_load_example", + # --- END AUTO-GENERATED EXAMPLES --- +] + +# Examples excluded from automated testing +EXAMPLES_TO_SKIP = [ + "environments.behavior_env_demo", # requires pre-sampled cached BEHAVIOR activity scene + "learning.navigation_policy_demo", + "teleoperation.robot_teleoperate_demo", + "teleoperation.vr_robot_control_demo", # does not support headless mode + "teleoperation.vr_scene_tour_demo", # does not support headless mode + "objects.import_custom_object", # CLI conversion tool, requires demo / test asset files + "object_states.object_state_texture_demo", # disable temporarily due to contact API bug + # WIP examples: currently broken, to be supported again in the future + "wip.curobo_example", + "wip.folded_unfolded_state_demo", + "wip.heat_source_or_sink_demo", + "wip.particle_source_sink_demo", + "wip.rs_int_primitives_example", + "wip.solve_behavior_task", + "wip.solve_simple_task", + "wip.view_cloth_configurations", +] + + +@pytest.mark.parametrize("example_name", EXAMPLES) +def test_example(example_name, request): + import click + + module = importlib.import_module(f"omnigibson.examples.{example_name}") + test_args = request.config.getoption("--test-args", default="") + + if isinstance(module.main, click.BaseCommand): + from click.testing import CliRunner + + args = test_args.split() if test_args else [] + runner = CliRunner() + result = runner.invoke(module.main, args, catch_exceptions=False) + assert result.exit_code == 0, result.output + else: + with patch("omnigibson.shutdown"): + module.main(random_selection=True, headless=True, short_exec=True) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_behavior_scene.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_behavior_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..e53533c100d125ba817b0ec2fb00087abf263b72 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_behavior_scene.py @@ -0,0 +1,206 @@ +""" +test_multiple_envs_behavior_scene.py +==================================== +Multi-environment infrastructure tests using BehaviorTask with R1Pro. + +Covers: + - Task tensors (BehaviorTask's PotentialReward / Timeout / PredicateGoal wiring) + - Scene state dump/load + - Robot getter/setter + +The env comes from the shared `behavior_env` fixture (conftest.py). + +Deliberately NOT covered here: scene placement and frame conversions. Those are Scene/prim logic, +independent of the task, and are tested once in test_multiple_envs_dummy_scene.py. Only +dump/load state is kept on the BehaviorTask side, where the scene has far more objects. +""" + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.reward_functions.potential_reward import PotentialReward +from omnigibson.termination_conditions.predicate_goal import PredicateGoal +from omnigibson.termination_conditions.timeout import Timeout + +from utils import ( + BEHAVIOR_NUM_ENVS as NUM_ENVS, +) + +# =================================================================== +# Task / reward / termination tensors +# =================================================================== + + +class TestBehaviorTaskTensors: + """Verify BehaviorTask step outputs have correct tensor shapes.""" + + def test_task_step_tensors(self, behavior_env): + """Task reward / done / success are (num_envs,) tensors.""" + env = behavior_env + + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + env.step(actions) + + print(f" reward={env.task.reward}, done={env.task.done}, success={env.task.success}") + assert env.task.reward.shape == (NUM_ENVS,) + assert env.task.done.shape == (NUM_ENVS,) + assert env.task.success.shape == (NUM_ENVS,) + + def test_reward_tensor_returns(self, behavior_env): + """PotentialReward returns (num_envs,) float tensor.""" + env = behavior_env + + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + env.step(actions) + + for rf_name, rf in env.task._reward_functions.items(): + print(f" reward fn '{rf_name}': shape={rf._reward.shape}, values={rf._reward}") + assert rf._reward.shape == ( + NUM_ENVS, + ), f"Reward function '{rf_name}' _reward has wrong shape: {rf._reward.shape}" + + # BehaviorTask must have the potential reward + assert "potential" in env.task._reward_functions + assert isinstance(env.task._reward_functions["potential"], PotentialReward) + + def test_termination_tensor_returns(self, behavior_env): + """Timeout and PredicateGoal return (num_envs,) bool tensors.""" + env = behavior_env + + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + env.step(actions) + + for tc_name, tc in env.task._termination_conditions.items(): + print(f" termination '{tc_name}': shape={tc._done.shape}, dtype={tc._done.dtype}, values={tc._done}") + assert tc._done.shape == ( + NUM_ENVS, + ), f"Termination condition '{tc_name}' _done has wrong shape: {tc._done.shape}" + assert tc._done.dtype == th.bool + + # BehaviorTask must have timeout and predicate conditions + assert "timeout" in env.task._termination_conditions + assert "predicate" in env.task._termination_conditions + assert isinstance(env.task._termination_conditions["timeout"], Timeout) + assert isinstance(env.task._termination_conditions["predicate"], PredicateGoal) + + +# =================================================================== +# Scene state dump/load +# =================================================================== + + +class TestBehaviorSceneCoordinates: + """Multi-scene position/orientation and state dump/load tests with BehaviorTask.""" + + def test_dump_load_states(self, behavior_env): + """Scene state can be saved and restored correctly with BehaviorTask.""" + env = behavior_env + + pose_0 = (th.tensor([1, 1, 1], dtype=th.float32), th.tensor([0, 0, 0, 1], dtype=th.float32)) + pose_1 = (th.tensor([0, 2, 1], dtype=th.float32), th.tensor([0, 0, 0.7071, 0.7071], dtype=th.float32)) + + env.scenes[0].robots[0].set_position_orientation(*pose_0, frame="scene") + env.scenes[1].robots[0].set_position_orientation(*pose_1, frame="scene") + + print(" Running 10 sim steps...") + for _ in range(10): + og.sim.step() + + initial_pos_0 = env.scenes[0].robots[0].get_position_orientation(frame="scene") + initial_pos_1 = env.scenes[1].robots[0].get_position_orientation(frame="scene") + + print(" Saving states...") + state_0 = env.scenes[0]._dump_state() + state_1 = env.scenes[1]._dump_state() + + print(" Resetting env...") + env.reset() + + print(" Loading states in different order...") + env.scenes[1]._load_state(state_1) + env.scenes[0]._load_state(state_0) + + post_pos_0 = env.scenes[0].robots[0].get_position_orientation(frame="scene") + post_pos_1 = env.scenes[1].robots[0].get_position_orientation(frame="scene") + + print(f" scene 0: initial={initial_pos_0[0]} -> post={post_pos_0[0]}") + print(f" scene 1: initial={initial_pos_1[0]} -> post={post_pos_1[0]}") + + assert th.allclose(initial_pos_0[0], post_pos_0[0], atol=1e-3) + assert th.allclose(initial_pos_1[0], post_pos_1[0], atol=1e-3) + assert th.allclose(initial_pos_0[1], post_pos_0[1], atol=1e-3) + assert th.allclose(initial_pos_1[1], post_pos_1[1], atol=1e-3) + + +# =================================================================== +# Robot getter/setter (R1Pro only) +# =================================================================== + + +class TestBehaviorRobotGetterSetter: + """Position/orientation getter and setter correctness for R1Pro with BehaviorTask.""" + + def test_getter(self, behavior_env): + """Position getter works in both world and scene frames.""" + env = behavior_env + + # Scene 0 robot: world == scene (scene 0 at origin) + robot0 = env.scenes[0].robots[0] + r0_world_pos, r0_world_ori = robot0.get_position_orientation() + r0_scene_pos, r0_scene_ori = robot0.get_position_orientation(frame="scene") + + print(f" scene 0 robot: world_pos={r0_world_pos}, scene_pos={r0_scene_pos}") + assert th.allclose(r0_world_pos, r0_scene_pos, atol=1e-3) + assert th.allclose(r0_world_ori, r0_scene_ori, atol=1e-3) + + # Scene 1 robot: verify coordinate transform + robot1 = env.scenes[1].robots[0] + s1_pos, s1_ori = env.scenes[1].get_position_orientation() + r1_world_pos, r1_world_ori = robot1.get_position_orientation() + r1_scene_pos, r1_scene_ori = robot1.get_position_orientation(frame="scene") + + print(f" scene 1 robot: world_pos={r1_world_pos}, scene_pos={r1_scene_pos}") + combined_pos, combined_ori = T.pose_transform(s1_pos, s1_ori, r1_scene_pos, r1_scene_ori) + assert th.allclose(r1_world_pos, combined_pos, atol=1e-3) + assert th.allclose(r1_world_ori, combined_ori, atol=1e-3) + + def test_setter(self, behavior_env): + """Position setter works in both world and scene frames.""" + env = behavior_env + + robot = env.scenes[1].robots[0] + + # Test world frame setter + new_world_pos = th.tensor([1.0, 2.0, 0.5]) + new_world_ori = T.euler2quat(th.tensor([0, 0, th.pi / 2])) + robot.set_position_orientation(position=new_world_pos, orientation=new_world_ori) + + got_world_pos, got_world_ori = robot.get_position_orientation() + print(f" set world pos={new_world_pos}, got={got_world_pos}") + assert th.allclose(got_world_pos, new_world_pos, atol=1e-3) + assert th.allclose(got_world_ori, new_world_ori, atol=1e-3) + + # Test scene frame setter + new_scene_pos = th.tensor([0.5, 1.0, 0.25]) + new_scene_ori = T.euler2quat(th.tensor([0, th.pi / 4, 0])) + robot.set_position_orientation(position=new_scene_pos, orientation=new_scene_ori, frame="scene") + + got_scene_pos, got_scene_ori = robot.get_position_orientation(frame="scene") + print(f" set scene pos={new_scene_pos}, got={got_scene_pos}") + assert th.allclose(got_scene_pos, new_scene_pos, atol=1e-3) + assert th.allclose(got_scene_ori, new_scene_ori, atol=1e-3) + + # Setting a different scene-frame pose should change world-frame result + new_scene_pos2 = th.tensor([-1.0, -2.0, 0.1]) + new_scene_ori2 = T.euler2quat(th.tensor([th.pi / 6, 0, 0])) + robot.set_position_orientation(position=new_scene_pos2, orientation=new_scene_ori2, frame="scene") + + got_world_pos2, _ = robot.get_position_orientation() + assert not th.allclose(got_world_pos2, new_world_pos, atol=1e-3) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_behavior_task.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_behavior_task.py new file mode 100644 index 0000000000000000000000000000000000000000..7912bcba68c386ca67e145b4a486dd7caee781ef --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_behavior_task.py @@ -0,0 +1,407 @@ +""" +test_multiple_envs_behavior_task.py +=================================== +Multi-environment BehaviorTask-specific logic tests with R1Pro. + +Covers BDDL object scope, potential reward, task observations, presampled robot +pose, activity attributes, instructions, and end-to-end goal completion (moving +objects into the goal state and verifying per-env success / reward / reset). + +Uses the ``picking_up_trash`` activity on ``house_double_floor_lower``. +Env/scene infrastructure for the same env lives in ``test_multiple_envs_behavior_scene.py``. +""" + +import torch as th + +import omnigibson as og + +from omnigibson.object_states import Inside + +from utils import ( + BEHAVIOR_ACTIVITY_NAME as ACTIVITY_NAME, + BEHAVIOR_NUM_ENVS as NUM_ENVS, + BEHAVIOR_R_POTENTIAL as R_POTENTIAL, +) + + +# --------------------------------------------------------------------------- +# Goal-completion helpers +# --------------------------------------------------------------------------- +def _goal_objects(env, env_idx): + """Return ([can_of_soda, ...], ashcan) bound in @env_idx's BDDL object scope. + + picking_up_trash's goal is `forall can: inside(can, ashcan)`; these are the + objects we move to drive the task to success. + """ + scope = env.task.object_scopes[env_idx] + ashcans = [scope[k] for k in sorted(scope) if k.startswith("ashcan.n.01")] + cans = [scope[k] for k in sorted(scope) if k.startswith("can__of__soda.n.01")] + assert len(ashcans) == 1 and ashcans[0] is not None, f"ashcan not bound in scope[{env_idx}]" + assert len(cans) >= 1 and all(c is not None for c in cans), f"cans not bound in scope[{env_idx}]" + return cans, ashcans[0] + + +def _place_inside(can, ashcan, retries=3): + """Place @can Inside @ashcan via kinematic sampling, retrying for flakiness. + + Inside.set_value rejection-samples a pose, settles physics, and verifies the + object is still inside; it returns False on a failed sample. Retry a few times + before giving up (sample_kinematics is known to be occasionally flaky). + """ + for _ in range(retries): + if can.states[Inside].set_value(ashcan, True): + return True + return False + + +def _zero_actions(env): + """Build a (num_envs, action_dim) all-zeros action that holds the robots still. + + Zero (rather than random) actions keep the robot from disturbing cans we've + already placed, so a step purely re-evaluates the goal/reward. + """ + return th.stack( + [ + th.zeros_like(th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float()) + for i in range(env.num_envs) + ] + ) + + +def _random_actions(env): + """Build a (num_envs, action_dim) random action sampled per robot.""" + return th.stack([th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(env.num_envs)]) + + +# --------------------------------------------------------------------------- + + +# =================================================================== +# BehaviorTask-specific logic +# =================================================================== + + +class TestBehaviorTaskLogic: + """Tests for logic unique to BehaviorTask: BDDL scope, potential reward, + task observations, presampled robot pose, activity attributes, instructions.""" + + def test_object_scope_per_env(self, behavior_env): + """Each env has its own independent object scope bound to its own scene's robot.""" + env = behavior_env + + for env_idx in range(NUM_ENVS): + scope = env.task.object_scopes[env_idx] + assert scope is not None, f"object_scopes[{env_idx}] is None" + assert isinstance(scope, dict) + assert "agent.n.01_1" in scope, f"agent not found in object_scopes[{env_idx}]" + # Agent entity should be *this* scene's robot (raw sim object after #2040 BDDLEntity removal), + # not some other env's robot — this is what guarantees per-env predicate evaluation is isolated. + agent_entity = scope["agent.n.01_1"] + assert agent_entity is not None + assert ( + agent_entity is env.scenes[env_idx].robots[0] + ), f"agent in scope[{env_idx}] is not scene {env_idx}'s robot" + print(f" env {env_idx}: scope has {len(scope)} entries, agent={agent_entity.name}") + + # Scopes are independent dict objects + assert env.task.object_scopes[0] is not env.task.object_scopes[1] + + def test_potential_reward_computation(self, behavior_env): + """get_potential returns a finite float for each env.""" + env = behavior_env + + for env_idx in range(NUM_ENVS): + potential = env.task.get_potential(env, env_idx) + assert isinstance(potential, float), f"get_potential({env_idx}) returned {type(potential)}, expected float" + assert not th.isnan(th.tensor(potential)), f"get_potential({env_idx}) returned NaN" + assert not th.isinf(th.tensor(potential)), f"get_potential({env_idx}) returned Inf" + # Potential should be non-positive (negative success score) + assert potential <= 0.0, f"get_potential({env_idx}) = {potential}, expected <= 0" + print(f" env {env_idx}: potential={potential:.4f}") + + def test_task_obs_per_env(self, behavior_env): + """task.get_obs produces a per-env low-dim observation vector. + + (The env.step()->obs "task" key plumbing is already covered by + test_multiple_envs_dummy_api.py::test_step_return_shapes; here we exercise the + BehaviorTask-specific get_obs content directly.) + """ + env = behavior_env + + for env_idx in range(NUM_ENVS): + task_obs = env.task.get_obs(env=env, env_idx=env_idx) + assert isinstance(task_obs, dict) + # Should contain "low_dim" with flattened object state observations + if "low_dim" in task_obs: + low_dim = task_obs["low_dim"] + assert isinstance(low_dim, th.Tensor) + assert low_dim.dim() == 1 + assert low_dim.shape[0] > 0 + print(f" env {env_idx}: low_dim obs dim={low_dim.shape[0]}") + + def test_presampled_robot_pose(self, behavior_env): + """Robot is positioned at a presampled pose after reset (verifies case-insensitive lookup).""" + env = behavior_env + + for env_idx in range(NUM_ENVS): + robot = env.scenes[env_idx].robots[0] + pos, ori = robot.get_position_orientation(frame="scene") + print(f" env {env_idx}: robot pos={pos}, ori={ori}") + + # Position should be finite and not at the origin (presampled poses are non-trivial) + assert th.isfinite(pos).all(), f"Robot {env_idx} position has non-finite values" + assert th.isfinite(ori).all(), f"Robot {env_idx} orientation has non-finite values" + assert pos.norm() > 0.01, f"Robot {env_idx} at origin, expected presampled pose" + + # Orientation quaternion should be unit length + ori_norm = ori.norm() + assert th.allclose( + ori_norm, th.tensor(1.0), atol=1e-2 + ), f"Robot {env_idx} orientation not unit quaternion: norm={ori_norm:.4f}" + + def test_activity_attributes(self, behavior_env): + """BehaviorTask has correct activity attributes after construction.""" + env = behavior_env + + from omnigibson.utils.bddl_utils import BDDLSampler + + assert env.task.activity_name == ACTIVITY_NAME + assert env.task.activity_definition_id == 0 + assert env.task.activity_instance_id == 0 + assert env.task.compiled_task is not None + assert env.task.compiled_task.conditions is not None + assert env.task.activity_initial_conditions is not None + assert "BehaviorTask" in env.task.name + assert ACTIVITY_NAME in env.task.name + + # Natural language conditions should be available + assert env.task.activity_natural_language_initial_conditions is not None + assert env.task.activity_natural_language_goal_conditions is not None + + # Symbolic compiled task is now singular (shared across envs), not a list of NUM_ENVS + assert not isinstance(env.task.compiled_task, list) + # object_scopes stays per-env + assert isinstance(env.task.object_scopes, list) + assert len(env.task.object_scopes) == NUM_ENVS + # Sampler is a single BDDLSampler bound to env 0 + assert isinstance(env.task.sampler, BDDLSampler) + + # Multi-env fixture must be in cache mode; online+multi-env is forbidden by _load's assert + assert env.task.online_object_sampling is False + + print(f" task name: {env.task.name}") + print(f" NL goal conditions: {env.task.activity_natural_language_goal_conditions}") + + def test_show_instruction(self, behavior_env): + """show_instruction returns valid instruction data per env.""" + env = behavior_env + + # Need a step for goal evaluation to populate goal_status + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + env.step(actions) + + for env_idx in range(NUM_ENVS): + instruction, color, objects = env.task.show_instruction(env_idx=env_idx) + assert isinstance(instruction, str), f"instruction for env {env_idx} is not a string" + assert len(instruction) > 0, f"instruction for env {env_idx} is empty" + assert len(color) == 3, f"color for env {env_idx} should be RGB (3 values), got {len(color)}" + assert isinstance(objects, list), f"objects for env {env_idx} is not a list" + print(f" env {env_idx}: instruction='{instruction}', color={color}, n_objects={len(objects)}") + + # Test iterate_instruction + initial_idx = env.task.currently_viewed_index + env.task.iterate_instruction() + new_idx = env.task.currently_viewed_index + total_conditions = len(env.task.compiled_task.conditions.parsed_goal_conditions) + expected_idx = (initial_idx + 1) % total_conditions + assert new_idx == expected_idx, f"iterate_instruction: expected idx {expected_idx}, got {new_idx}" + print(f" iterate_instruction: {initial_idx} -> {new_idx} (total={total_conditions})") + + +# =================================================================== +# End-to-end goal completion (move objects to goal state, verify success) +# =================================================================== +# +# picking_up_trash's goal is a single quantified condition, +# forall ?can: inside(?can, ashcan), +# so get_potential / goal_status are binary at the goal-condition granularity: +# the one goal condition is unsatisfied (potential 0.0) until *every* can is +# inside, at which point it flips satisfied (potential -1.0). Per-can progress is +# therefore checked via the public states[Inside].get_value, not goal_status. + + +class TestBehaviorTaskGoalCompletion: + """Drive the task to its goal state and verify success, reward, and reset, + across the none / some / all and per-env-isolation combinations called for + by the picking_up_trash goal.""" + + def test_no_completion_under_random_actions(self, behavior_env): + """With nothing moved to the goal, no env ever reports success (none combination).""" + env = behavior_env + + for _ in range(10): + _, _, terminateds, _, infos = env.step(_random_actions(env)) + assert not terminateds.any(), f"task terminated under random actions: {terminateds}" + for env_idx in range(NUM_ENVS): + gs = infos[env_idx]["done"]["goal_status"] + assert len(gs["unsatisfied"]) > 0, f"env {env_idx} goal satisfied without placing cans" + + def test_single_env_completion_and_reward(self, behavior_env): + """Completing only env 0 makes env 0 (and only env 0) succeed, with correct reward.""" + env = behavior_env + + cans, ashcan = _goal_objects(env, 0) + for i, can in enumerate(cans): + assert _place_inside(can, ashcan), f"failed to place can {i} inside ashcan (env 0)" + + # Stored potential is 0.0 from the pre-test reset; placing cans does not touch it, + # so this completing step should earn reward == r_potential * (0 - (-1)) for env 0. + _, rewards, terminateds, _, infos = env.step(_zero_actions(env)) + + # env 0 succeeds, env 1 (untouched) does not + assert terminateds[0], "env 0 not terminated after all cans placed" + assert not terminateds[1], "env 1 terminated despite no cans placed" + assert infos[0]["done"]["termination_conditions"]["predicate"]["done"] + assert len(infos[0]["done"]["goal_status"]["unsatisfied"]) == 0, "env 0 goal still unsatisfied" + assert len(infos[1]["done"]["goal_status"]["unsatisfied"]) > 0, "env 1 goal unexpectedly satisfied" + + # All cans actually register Inside in env 0 + assert all(can.states[Inside].get_value(ashcan) for can in cans), "not all cans report Inside in env 0" + + # Reward is the potential delta on the completing step (env 1 sees no change) + print(f" rewards={rewards}") + assert abs(rewards[0].item() - R_POTENTIAL) < 1e-3, f"env 0 reward {rewards[0].item()} != {R_POTENTIAL}" + assert abs(rewards[1].item()) < 1e-3, f"env 1 reward {rewards[1].item()} != 0" + + # Potential reflects full success in env 0 only + assert abs(env.task.get_potential(env, 0) - (-1.0)) < 1e-6, "env 0 potential not -1.0 at success" + assert env.task.get_potential(env, 1) > -1.0, "env 1 potential indicates success without placement" + + def test_all_envs_completion(self, behavior_env): + """Completing every env makes every env succeed (all combination).""" + env = behavior_env + + for env_idx in range(NUM_ENVS): + cans, ashcan = _goal_objects(env, env_idx) + for i, can in enumerate(cans): + assert _place_inside(can, ashcan), f"failed to place can {i} inside ashcan (env {env_idx})" + + _, _, terminateds, _, infos = env.step(_zero_actions(env)) + + assert terminateds.all(), f"not all envs terminated: {terminateds}" + for env_idx in range(NUM_ENVS): + assert infos[env_idx]["done"]["termination_conditions"]["predicate"]["done"] + assert len(infos[env_idx]["done"]["goal_status"]["unsatisfied"]) == 0, f"env {env_idx} goal unsatisfied" + + def test_partial_progress_does_not_complete(self, behavior_env): + """Placing all-but-one can leaves the goal unsatisfied (some combination).""" + env = behavior_env + + cans, ashcan = _goal_objects(env, 0) + for i, can in enumerate(cans[:-1]): + assert _place_inside(can, ashcan), f"failed to place can {i} inside ashcan" + + _, rewards, terminateds, _, infos = env.step(_zero_actions(env)) + + # Goal is a single forall: partial progress does not satisfy it + assert not terminateds[0], "env 0 terminated with partial progress" + gs = infos[0]["done"]["goal_status"] + assert len(gs["satisfied"]) == 0, f"forall goal counted satisfied with partial progress: {gs}" + assert len(gs["unsatisfied"]) > 0, "goal unexpectedly fully satisfied" + + # ...but per-can progress is real: exactly the placed cans report Inside + n_inside = sum(bool(can.states[Inside].get_value(ashcan)) for can in cans) + assert n_inside == len(cans) - 1, f"expected {len(cans) - 1} cans inside, got {n_inside}" + + # Binary potential => still 0.0, and no reward delta, until the last can goes in + assert abs(env.task.get_potential(env, 0)) < 1e-6, "potential nonzero before full completion" + assert abs(rewards[0].item()) < 1e-3, f"env 0 earned reward {rewards[0].item()} on partial progress" + + def test_selective_reset_clears_completion(self, behavior_env): + """Resetting env 0 only clears its goal completion, leaving env 1 untouched.""" + env = behavior_env + + # Complete env 0 + cans, ashcan = _goal_objects(env, 0) + for i, can in enumerate(cans): + assert _place_inside(can, ashcan), f"failed to place can {i} inside ashcan" + _, _, terminateds, _, infos = env.step(_zero_actions(env)) + assert terminateds[0], "env 0 should be complete before reset" + # env 1 was never touched: capture its (incomplete) state to confirm the reset leaves it alone + assert not terminateds[1], "env 1 unexpectedly complete before reset" + env1_potential_before = env.task.get_potential(env, 1) + env1_unsatisfied_before = len(infos[1]["done"]["goal_status"]["unsatisfied"]) + + # Reset only env 0; step once so kinematic caches refresh against the restored poses + env.reset(env_indices=th.tensor([0])) + _, _, terminateds2, _, infos2 = env.step(_zero_actions(env)) + + assert not terminateds2[0], "env 0 still terminating after reset" + assert abs(env.task.get_potential(env, 0)) < 1e-6, "potential not restored to baseline after reset" + cans0, ashcan0 = _goal_objects(env, 0) + assert not any(can.states[Inside].get_value(ashcan0) for can in cans0), "cans still inside ashcan after reset" + + # env 1 must be untouched by the selective reset: still incomplete, same potential and goal status + assert not terminateds2[1], "selective reset of env 0 disturbed env 1's termination state" + assert ( + abs(env.task.get_potential(env, 1) - env1_potential_before) < 1e-6 + ), "selective reset of env 0 changed env 1's potential" + assert ( + len(infos2[1]["done"]["goal_status"]["unsatisfied"]) == env1_unsatisfied_before + ), "selective reset of env 0 changed env 1's goal status" + + +class TestBehaviorTaskPartialReset: + """Partial reset against a real BehaviorTask scene. + + The dummy_api version of this test only moves a robot in a near-empty scene; this one exercises + BehaviorTask's per-env scene/agent reset.""" + + def test_selective_reset(self, behavior_env): + """Resetting env_indices=[1] only resets scene 1, leaving scene 0 unchanged.""" + env = behavior_env + + known_pos = th.tensor([1.0, 1.0, 0.5]) + env.scenes[0].robots[0].set_position_orientation(position=known_pos, frame="scene") + og.sim.step() + + pos_before = env.scenes[0].robots[0].get_position_orientation(frame="scene")[0].clone() + + env.reset(env_indices=th.tensor([1])) + + pos_after = env.scenes[0].robots[0].get_position_orientation(frame="scene")[0] + print(f" pos_before={pos_before}, pos_after={pos_after}") + # BehaviorTask scenes have many objects, so physics settling causes more drift than minimal scenes + assert th.allclose( + pos_before, pos_after, atol=0.15 + ), f"Scene 0 robot moved after resetting only scene 1: {pos_before} vs {pos_after}" + + +# No-presampled-pose variant +# =================================================================== + + +class TestBehaviorTaskNoPresample: + """BehaviorTask with use_presampled_robot_pose=False. + + Uses its own env (different config from the shared `behavior_env`); `behavior_env_no_presample` + handles building and tearing down whichever env is cached, so this can run in any order. + """ + + def test_no_presampled_robot_pose(self, behavior_env_no_presample): + """BehaviorTask constructs, resets, and steps without a presampled pose. + + (Pose validity/unit-quaternion checks are covered by + TestBehaviorTaskLogic::test_presampled_robot_pose; this variant only needs + to prove the use_presampled_robot_pose=False path doesn't crash.) + """ + env = behavior_env_no_presample + env.step(_zero_actions(env)) + + for env_idx in range(NUM_ENVS): + pos, ori = env.scenes[env_idx].robots[0].get_position_orientation(frame="scene") + assert th.isfinite(pos).all(), f"Robot {env_idx} position has non-finite values" + assert th.isfinite(ori).all(), f"Robot {env_idx} orientation has non-finite values" + print(f" env {env_idx}: robot pos={pos}, ori={ori}") diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_dummy_api.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_dummy_api.py new file mode 100644 index 0000000000000000000000000000000000000000..34cfd3fd7966d1dd19ebe05dd3b2fcfb5816d37a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_dummy_api.py @@ -0,0 +1,162 @@ +import torch as th + +import omnigibson as og + + +TASK_TYPE = "DummyTask" + +# Number of envs for the multi-env tests. 3 rather than 2 so that "only env 1 was reset" has a +# third, untouched env to compare against. +NUM_ENVS = 3 + +# Scene layout constant: scenes are laid out along +X, separated by their AABB extent plus this +# margin (see Scene._load_scene_prim_with_objects / simulator m.SCENE_MARGIN). +SCENE_MARGIN = 10.0 + + +# =================================================================== +# Environment construction & properties +# =================================================================== + + +class TestEnvConstruction: + """Basic environment construction & property tests.""" + + def test_env_construction(self, make_multi_env): + """Environment with num_envs=NUM_ENVS creates that many scenes.""" + env = make_multi_env(NUM_ENVS) + assert len(env.scenes) == NUM_ENVS + assert env.num_envs == NUM_ENVS + for scene in env.scenes: + assert len(scene.robots) == 1 + + def test_scenes_spatially_separated(self, make_multi_env): + """Scenes tile along +X with at least SCENE_MARGIN between them, and every env places its + robot identically within its own scene.""" + env = make_multi_env(NUM_ENVS) + + scene_positions = [s.get_position_orientation()[0] for s in env.scenes] + + # Scene 0 anchors the layout at the origin + assert th.allclose( + scene_positions[0], th.zeros(3), atol=1e-3 + ), f"Scene 0 should sit at the origin, got {scene_positions[0]}" + + # Scenes are tiled along +X only, in index order, with at least SCENE_MARGIN of clearance + for i in range(1, NUM_ENVS): + delta = scene_positions[i] - scene_positions[i - 1] + print(f" Scene {i - 1} -> {i} offset: {delta}") + assert ( + delta[0] >= SCENE_MARGIN + ), f"Scenes {i - 1} and {i} are only {delta[0]:.2f} apart in X (expected >= {SCENE_MARGIN})" + assert th.allclose( + delta[1:], th.zeros(2), atol=1e-3 + ), f"Scenes should only be offset along X, but scene {i} is offset by {delta} from {i - 1}" + + # The layout must not leak into the scenes: each robot sits at the same pose *within* its + # own scene, and its world pose is exactly that local pose shifted by the scene origin. + # This is what a per-env placement bug would break -- a pure distance check would not. + ref_local_pos, ref_local_ori = env.scenes[0].robots[0].get_position_orientation(frame="scene") + for i in range(NUM_ENVS): + local_pos, local_ori = env.scenes[i].robots[0].get_position_orientation(frame="scene") + world_pos, _ = env.scenes[i].robots[0].get_position_orientation() + print(f" Scene {i} robot: local={local_pos}, world={world_pos}") + assert th.allclose( + local_pos, ref_local_pos, atol=1e-3 + ), f"Env {i} robot scene-local position {local_pos} differs from env 0's {ref_local_pos}" + assert th.allclose( + local_ori, ref_local_ori, atol=1e-3 + ), f"Env {i} robot scene-local orientation {local_ori} differs from env 0's {ref_local_ori}" + assert th.allclose( + world_pos, scene_positions[i] + local_pos, atol=1e-3 + ), f"Env {i} robot world position {world_pos} is not its scene origin plus its local position" + + +# =================================================================== +# step() / reset() contract +# =================================================================== + + +class TestStepAndReset: + """step() / reset() contract tests.""" + + def test_step_return_shapes(self, make_multi_env): + """step() returns tensors of shape (num_envs,) for rewards/terminateds/truncateds.""" + env = make_multi_env(NUM_ENVS) + + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + + obs_list, rewards, terminateds, truncateds, infos = env.step(actions) + + print(f" obs_list len={len(obs_list)}, rewards shape={rewards.shape}") + assert isinstance(obs_list, list) and len(obs_list) == NUM_ENVS + assert rewards.shape == (NUM_ENVS,) + assert terminateds.shape == (NUM_ENVS,) and terminateds.dtype == th.bool + assert truncateds.shape == (NUM_ENVS,) and truncateds.dtype == th.bool + assert isinstance(infos, list) and len(infos) == NUM_ENVS + + def test_selective_reset(self, make_multi_env): + """Resetting env_indices=[1] only resets scene 1, leaving 0 and 2 unchanged.""" + env = make_multi_env(NUM_ENVS) + + known_pos = th.tensor([1.0, 1.0, 0.5]) + env.scenes[0].robots[0].set_position_orientation(position=known_pos, frame="scene") + og.sim.step() + + pos_before = env.scenes[0].robots[0].get_position_orientation(frame="scene")[0].clone() + + env.reset(env_indices=th.tensor([1])) + + pos_after = env.scenes[0].robots[0].get_position_orientation(frame="scene")[0] + print(f" pos_before={pos_before}, pos_after={pos_after}") + assert th.allclose( + pos_before, pos_after, atol=0.05 + ), f"Scene 0 robot moved after resetting only scene 1: {pos_before} vs {pos_after}" + + def test_per_env_step_counters(self, make_multi_env): + """episode_steps is a (num_envs,) tensor that tracks steps independently.""" + env = make_multi_env(NUM_ENVS) + + assert env.episode_steps.shape == (NUM_ENVS,) + assert (env.episode_steps == 0).all() + + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + env.step(actions) + + print(f" episode_steps after 1 step: {env.episode_steps}") + assert (env.episode_steps == 1).all() + + env.reset(env_indices=th.tensor([0])) + print(f" episode_steps after resetting env 0: {env.episode_steps}") + assert env.episode_steps[0] == 0 + assert env.episode_steps[1] == 1 + + +# =================================================================== +# Single-env compatibility +# =================================================================== +# +# Placed last purely as an optimization: `make_multi_env` keeps one env alive and rebuilds whenever the +# requested configuration changes, so putting the lone num_envs=1 test after the NUM_ENVS ones +# avoids rebuilding them. Nothing here depends on ordering for correctness. + + +class TestSingleEnvCompat: + """num_envs=1 must keep working through the vectorized code paths.""" + + def test_single_env_compat(self, make_multi_env): + """num_envs=1 (default) should still work; scene property returns first scene.""" + env = make_multi_env(1) + + assert env.scene is env.scenes[0] + assert len(env.scenes) == 1 + + action = th.from_numpy(env.scenes[0].robots[0].action_space.sample()).float().unsqueeze(0) + obs_list, rewards, terminateds, truncateds, infos = env.step(action) + + assert rewards.shape == (1,) + assert len(obs_list) == 1 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_dummy_scene.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_dummy_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..d84f9d380aa934d9d6b2b8d3156a8318c086ba4d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_dummy_scene.py @@ -0,0 +1,318 @@ +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson import object_states +from omnigibson.utils.constants import ParticleModifyCondition +from omnigibson.utils.transform_utils import quat_multiply + + +# =================================================================== +# Scene coordinate system & state +# =================================================================== + + +class TestSceneCoordinates: + """Multi-scene position/orientation and state dump/load tests.""" + + def test_multi_scene_dump_load_states(self, make_multi_env): + env = make_multi_env(3) + robot_0 = env.scenes[0].robots[0] + robot_1 = env.scenes[1].robots[0] + robot_2 = env.scenes[2].robots[0] + + robot_0_pos = robot_0.get_position_orientation()[0] + robot_1_pos = robot_1.get_position_orientation()[0] + robot_2_pos = robot_2.get_position_orientation()[0] + + dist_0_1 = robot_1_pos - robot_0_pos + dist_1_2 = robot_2_pos - robot_1_pos + + print(f" dist_0_1={dist_0_1}, dist_1_2={dist_1_2}") + # Check x/y spacing is even (z can drift slightly due to physics settling) + assert th.allclose(dist_0_1[:2], dist_1_2[:2], atol=1e-3) + + # Set different poses for the robot in each environment + pose_1 = (th.tensor([1, 1, 1], dtype=th.float32), th.tensor([0, 0, 0, 1], dtype=th.float32)) + pose_2 = (th.tensor([0, 2, 1], dtype=th.float32), th.tensor([0, 0, 0.7071, 0.7071], dtype=th.float32)) + pose_3 = (th.tensor([-1, -1, 0.5], dtype=th.float32), th.tensor([0.5, 0.5, 0.5, 0.5], dtype=th.float32)) + + robot_0.set_position_orientation(*pose_1, frame="scene") + robot_1.set_position_orientation(*pose_2, frame="scene") + robot_2.set_position_orientation(*pose_3, frame="scene") + + print(" Running 10 sim steps...") + for _ in range(10): + og.sim.step() + + initial_robot_pos_scene_1 = robot_1.get_position_orientation(frame="scene") + initial_robot_pos_scene_2 = robot_2.get_position_orientation(frame="scene") + initial_robot_pos_scene_0 = robot_0.get_position_orientation(frame="scene") + + # Save states + print(" Saving states...") + robot_0_state = env.scenes[0]._dump_state() + robot_1_state = env.scenes[1]._dump_state() + robot_2_state = env.scenes[2]._dump_state() + + print(" Resetting env...") + env.reset() + + # Load the states in a different order + print(" Loading states in different order...") + env.scenes[1]._load_state(robot_1_state) + env.scenes[2]._load_state(robot_2_state) + env.scenes[0]._load_state(robot_0_state) + + post_robot_pos_scene_1 = env.scenes[1].robots[0].get_position_orientation(frame="scene") + post_robot_pos_scene_2 = env.scenes[2].robots[0].get_position_orientation(frame="scene") + post_robot_pos_scene_0 = env.scenes[0].robots[0].get_position_orientation(frame="scene") + + print(f" scene 0: initial={initial_robot_pos_scene_0[0]} -> post={post_robot_pos_scene_0[0]}") + print(f" scene 1: initial={initial_robot_pos_scene_1[0]} -> post={post_robot_pos_scene_1[0]}") + print(f" scene 2: initial={initial_robot_pos_scene_2[0]} -> post={post_robot_pos_scene_2[0]}") + + assert th.allclose(initial_robot_pos_scene_0[0], post_robot_pos_scene_0[0], atol=1e-3) + assert th.allclose(initial_robot_pos_scene_1[0], post_robot_pos_scene_1[0], atol=1e-3) + assert th.allclose(initial_robot_pos_scene_2[0], post_robot_pos_scene_2[0], atol=1e-3) + + assert th.allclose(initial_robot_pos_scene_0[1], post_robot_pos_scene_0[1], atol=1e-3) + assert th.allclose(initial_robot_pos_scene_1[1], post_robot_pos_scene_1[1], atol=1e-3) + assert th.allclose(initial_robot_pos_scene_2[1], post_robot_pos_scene_2[1], atol=1e-3) + + def test_multi_scene_get_local_position(self, make_multi_env): + env = make_multi_env(3) + + robot_1_pos_local = env.scenes[1].robots[0].get_position_orientation(frame="scene")[0] + robot_1_pos_global = env.scenes[1].robots[0].get_position_orientation()[0] + + pos_scene = env.scenes[1].get_position_orientation()[0] + + print(f" local={robot_1_pos_local}, global={robot_1_pos_global}, scene_origin={pos_scene}") + assert th.allclose(robot_1_pos_global, pos_scene + robot_1_pos_local, atol=1e-3) + + def test_multi_scene_set_local_position(self, make_multi_env): + env = make_multi_env(3) + + robot = env.scenes[1].robots[0] + initial_global_pos = robot.get_position_orientation()[0] + new_global_pos = initial_global_pos + th.tensor([1.0, 0.5, 0.0], dtype=th.float32) + + robot.set_position_orientation(position=new_global_pos) + + updated_global_pos = robot.get_position_orientation()[0] + scene_pos = env.scenes[1].get_position_orientation()[0] + updated_local_pos = robot.get_position_orientation(frame="scene")[0] + expected_local_pos = new_global_pos - scene_pos + + print(f" updated_global={updated_global_pos}, expected={new_global_pos}") + print(f" updated_local={updated_local_pos}, expected_local={expected_local_pos}") + + assert th.allclose( + updated_global_pos, new_global_pos, atol=1e-3 + ), f"Updated global position {updated_global_pos} does not match expected {new_global_pos}" + assert th.allclose( + updated_local_pos, expected_local_pos, atol=1e-3 + ), f"Updated local position {updated_local_pos} does not match expected {expected_local_pos}" + + global_pos_change = updated_global_pos - initial_global_pos + expected_change = th.tensor([1.0, 0.5, 0.0], dtype=th.float32) + assert th.allclose( + global_pos_change, expected_change, atol=1e-3 + ), f"Global position change {global_pos_change} does not match expected change {expected_change}" + + def test_multi_scene_position_orientation_relative_to_scene(self, make_multi_env): + env = make_multi_env(3) + + robot = env.scenes[1].robots[0] + new_relative_pos = th.tensor([1.0, 2.0, 0.5]) + new_relative_ori = th.tensor([0, 0, 0.7071, 0.7071]) + + robot.set_position_orientation(position=new_relative_pos, orientation=new_relative_ori, frame="scene") + updated_relative_pos, updated_relative_ori = robot.get_position_orientation(frame="scene") + + print(f" set relative pos={new_relative_pos}, got={updated_relative_pos}") + assert th.allclose( + updated_relative_pos, new_relative_pos, atol=1e-3 + ), f"Updated relative position {updated_relative_pos} does not match expected {new_relative_pos}" + assert th.allclose( + updated_relative_ori, new_relative_ori, atol=1e-3 + ), f"Updated relative orientation {updated_relative_ori} does not match expected {new_relative_ori}" + + scene_pos, scene_ori = env.scenes[1].get_position_orientation() + global_pos, global_ori = robot.get_position_orientation() + + expected_global_pos = scene_pos + updated_relative_pos + print(f" global_pos={global_pos}, expected={expected_global_pos}") + assert th.allclose( + global_pos, expected_global_pos, atol=1e-3 + ), f"Global position {global_pos} does not match expected {expected_global_pos}" + + expected_global_ori = quat_multiply(scene_ori, new_relative_ori) + assert th.allclose( + global_ori, expected_global_ori, atol=1e-3 + ), f"Global orientation {global_ori} does not match expected {expected_global_ori}" + + # Ordered last within this class purely as an optimization: it is the only num_envs=1 test + # here, so running it after the num_envs=3 tests avoids rebuilding the shared 3-env env. + # It also permanently moves the scene prim, which env.reset() does not restore. + def test_multi_scene_scene_prim(self, make_multi_env): + env = make_multi_env(1) + original_robot_pos = env.scenes[0].robots[0].get_position_orientation()[0] + scene_prim_displacement = th.tensor([10.0, 0.0, 0.0], dtype=th.float32) + original_scene_prim_pos = env.scenes[0]._scene_prim.get_position_orientation()[0] + env.scenes[0].set_position_orientation(position=original_scene_prim_pos + scene_prim_displacement) + new_scene_prim_pos = env.scenes[0]._scene_prim.get_position_orientation()[0] + new_robot_pos = env.scenes[0].robots[0].get_position_orientation()[0] + print(f" scene_prim moved: {original_scene_prim_pos} -> {new_scene_prim_pos}") + print(f" robot moved: {original_robot_pos} -> {new_robot_pos}") + assert th.allclose(new_scene_prim_pos - original_scene_prim_pos, scene_prim_displacement, atol=1e-3) + assert th.allclose(new_robot_pos - original_robot_pos, scene_prim_displacement, atol=1e-2) + + +# =================================================================== +# Robot getter/setter, across robots +# =================================================================== + + +class TestRobotGetterSetter: + """Position/orientation getter and setter correctness across robots.""" + + def test_getter(self, make_multi_env, robot_model): + env = make_multi_env(2, robot=robot_model) + robot1 = env.scenes[0].robots[0] + + robot1_world_position, robot1_world_orientation = robot1.get_position_orientation() + robot1_scene_position, robot1_scene_orientation = robot1.get_position_orientation(frame="scene") + + print(f" scene 0 robot: world_pos={robot1_world_position}, scene_pos={robot1_scene_position}") + # Robot in scene 0 is at origin, so world == scene + assert th.allclose(robot1_world_position, robot1_scene_position, atol=1e-3) + assert th.allclose(robot1_world_orientation, robot1_scene_orientation, atol=1e-3) + + # For scene 1 (non-zero offset), verify coordinate transform + robot2 = env.scenes[1].robots[0] + scene_position, scene_orientation = env.scenes[1].get_position_orientation() + + robot2_world_position, robot2_world_orientation = robot2.get_position_orientation() + robot2_scene_position, robot2_scene_orientation = robot2.get_position_orientation(frame="scene") + + print(f" scene 1 robot: world_pos={robot2_world_position}, scene_pos={robot2_scene_position}") + combined_position, combined_orientation = T.pose_transform( + scene_position, scene_orientation, robot2_scene_position, robot2_scene_orientation + ) + assert th.allclose(robot2_world_position, combined_position, atol=1e-3) + assert th.allclose(robot2_world_orientation, combined_orientation, atol=1e-3) + + def test_setter(self, make_multi_env, robot_model): + env = make_multi_env(2, robot=robot_model) + + robot_obj = env.scenes[1].robots[0] + + # Test setting in world frame + new_world_pos = th.tensor([1.0, 2.0, 0.5]) + new_world_ori = T.euler2quat(th.tensor([0, 0, th.pi / 2])) + robot_obj.set_position_orientation(position=new_world_pos, orientation=new_world_ori) + + got_world_pos, got_world_ori = robot_obj.get_position_orientation() + print(f" set world pos={new_world_pos}, got={got_world_pos}") + assert th.allclose(got_world_pos, new_world_pos, atol=1e-3) + assert th.allclose(got_world_ori, new_world_ori, atol=1e-3) + + # Test setting in scene frame + new_scene_pos = th.tensor([0.5, 1.0, 0.25]) + new_scene_ori = T.euler2quat(th.tensor([0, th.pi / 4, 0])) + robot_obj.set_position_orientation(position=new_scene_pos, orientation=new_scene_ori, frame="scene") + + got_scene_pos, got_scene_ori = robot_obj.get_position_orientation(frame="scene") + print(f" set scene pos={new_scene_pos}, got={got_scene_pos}") + assert th.allclose(got_scene_pos, new_scene_pos, atol=1e-3) + assert th.allclose(got_scene_ori, new_scene_ori, atol=1e-3) + + # Setting a different scene-frame pose should change world-frame result + new_scene_pos2 = th.tensor([-1.0, -2.0, 0.1]) + new_scene_ori2 = T.euler2quat(th.tensor([th.pi / 6, 0, 0])) + robot_obj.set_position_orientation(position=new_scene_pos2, orientation=new_scene_ori2, frame="scene") + + got_world_pos2, got_world_ori2 = robot_obj.get_position_orientation() + assert not th.allclose(got_world_pos2, new_world_pos, atol=1e-3) + assert not th.allclose(got_world_ori2, new_world_ori, atol=1e-3) + + def test_setter_sim_stopped(self, make_multi_env, robot_model): + """Getter/setter should work even when the simulator is stopped.""" + env = make_multi_env(2, robot=robot_model) + og.sim.stop() + print(" Sim stopped") + + robot_obj = env.scenes[1].robots[0] + + new_world_pos = th.tensor([1.0, 2.0, 0.5]) + new_world_ori = T.euler2quat(th.tensor([0, 0, th.pi / 2])) + robot_obj.set_position_orientation(position=new_world_pos, orientation=new_world_ori) + + got_world_pos, got_world_ori = robot_obj.get_position_orientation() + print(f" world frame: set={new_world_pos}, got={got_world_pos}") + assert th.allclose(got_world_pos, new_world_pos, atol=1e-3) + assert th.allclose(got_world_ori, new_world_ori, atol=1e-3) + + new_scene_pos = th.tensor([0.5, 1.0, 0.25]) + new_scene_ori = T.euler2quat(th.tensor([0, th.pi / 4, 0])) + robot_obj.set_position_orientation(position=new_scene_pos, orientation=new_scene_ori, frame="scene") + + got_scene_pos, got_scene_ori = robot_obj.get_position_orientation(frame="scene") + print(f" scene frame: set={new_scene_pos}, got={got_scene_pos}") + assert th.allclose(got_scene_pos, new_scene_pos, atol=1e-3) + assert th.allclose(got_scene_ori, new_scene_ori, atol=1e-3) + + new_scene_pos2 = th.tensor([-1.0, -2.0, 0.1]) + new_scene_ori2 = T.euler2quat(th.tensor([th.pi / 6, 0, 0])) + robot_obj.set_position_orientation(position=new_scene_pos2, orientation=new_scene_ori2, frame="scene") + + got_scene_pos2, got_scene_ori2 = robot_obj.get_position_orientation(frame="scene") + assert th.allclose(got_scene_pos2, new_scene_pos2, atol=1e-3) + assert th.allclose(got_scene_ori2, new_scene_ori2, atol=1e-3) + + got_world_pos2, got_world_ori2 = robot_obj.get_position_orientation() + assert not th.allclose(got_world_pos2, new_world_pos, atol=1e-3) + assert not th.allclose(got_world_ori2, new_world_ori, atol=1e-3) + + +# =================================================================== +# Particle systems +# =================================================================== + + +class TestParticles: + def test_multi_scene_particle_source(self, make_multi_env): + sink_cfg = dict( + type="DatasetObject", + name="sink", + category="furniture_sink", + model="czyfhq", + abilities={ + "toggleable": {}, + "particleSource": { + "conditions": { + "water": [(ParticleModifyCondition.TOGGLEDON, True)], + }, + "initial_speed": 0.0, + }, + "particleSink": { + "conditions": { + "water": [], + }, + }, + }, + position=[0.0, -1.5, 0.0], + ) + + env = make_multi_env(3, additional_objects_cfg=[sink_cfg]) + + for i, scene in enumerate(env.scenes): + sink = scene.object_registry("name", "sink") + assert sink.states[object_states.ToggledOn].set_value(True) + print(f" scene {i}: sink toggled on") + + print(" Running 50 sim steps...") + for _ in range(50): + og.sim.step() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_grasp.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_grasp.py new file mode 100644 index 0000000000000000000000000000000000000000..b5973baf0c163fb112d670f16a909123f90328c9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_grasp.py @@ -0,0 +1,29 @@ +""" +test_multiple_envs_grasp.py +=========================== +GraspTask-specific behavior under num_envs > 1. + +The per-env tensor-shape contract this file also used to cover (a byte-identical copy of +TestTaskTensors) now lives once in test_multiple_envs_task_tensors.py. +""" + +NUM_ENVS = 2 + + +class TestGraspTask: + """GraspTask-specific tests across robots.""" + + def test_grasp_task_precached_reset(self, make_multi_env, robot_model): + """GraspTask resets correctly using precached_reset_pose_path.""" + env = make_multi_env(NUM_ENVS, robot=robot_model, task_type="GraspTask") + + # Verify reset succeeded and objects exist + for env_idx in range(NUM_ENVS): + obj = env.scenes[env_idx].object_registry("name", "grasp_obj") + assert obj is not None, f"grasp_obj not found in scene {env_idx}" + robot_obj = env.scenes[env_idx].robots[0] + pos = robot_obj.get_position_orientation(frame="scene")[0] + print(f" scene {env_idx}: robot at {pos}") + + # Reset again to verify repeated resets work + env.reset() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_heat_narrow_phase.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_heat_narrow_phase.py new file mode 100644 index 0000000000000000000000000000000000000000..b1cd1fcc284940533222ce3bb48a08ec2c87336b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_heat_narrow_phase.py @@ -0,0 +1,261 @@ +"""Point heat sources must measure to the target's GEOMETRY, not to its AABB. + +Pre-vectorization, `HeatSourceOrSink` decided which objects a point source affects with +`og.sim.psqi.overlap_sphere(radius=distance_threshold, ...)`, a PhysX query against each +target's actual COLLISION GEOMETRY. The vectorized kernel cannot call that (CPU-side query, +one call per source, delivered by callback), so it reproduces it in two stages: a cheap +AABB distance test as a broad phase, then `wp.mesh_query_point` against the target's collision +meshes for whatever survives. + +The broad phase alone is not equivalent. An AABB always contains its geometry, so +distance-to-AABB <= distance-to-geometry, and the AABB test therefore ACCEPTS targets whose +real geometry is out of range. The gap is largest for long, thin or diagonally-oriented +objects: measured 0.69 m of slack for a bar lying along a box diagonal, against a default +threshold of 0.2 m. + +None of the tests in test_multiple_envs_heat_states.py cover this — they all place targets +directly on the heat element, where AABB and mesh agree. These do. + +Run standalone (one Environment per process): + OMNIGIBSON_HEADLESS=1 pytest tests/test_multiple_envs_heat_narrow_phase.py -v -s +""" + +import pytest +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.macros import macros as m +from omnigibson.object_states import HeatSourceOrSink, Temperature, ToggledOn + +N_ENVS = 3 +DEFAULT_TEMP = m.object_states.temperature.DEFAULT_TEMPERATURE + +OBJECTS_CFG = [ + {"type": "DatasetObject", "name": "stove", "category": "stove", "model": "yhjzwg", "position": [0.0, 0.0, 0.5]}, + # Flat sheet: rotated off-axis its AABB balloons well beyond the geometry, which is exactly + # the configuration where an AABB-only test over-reaches. + # + # Scaled up and made kinematic deliberately. At native size the sheet is 0.47 m long and the + # furthest an in-AABB point can sit from it is 0.30 m -- exactly the margin this test wants, + # with no room for error. Scaling 3x makes the gap comfortable instead of borderline. + # + # kinematic_only, NOT fixed_base: the board has to stay exactly where the search puts it. + # keep_still() only zeroes velocity, so gravity still moves it; and fixed_base is worse than + # nothing here, because it anchors a joint at the spawn pose and physics then drags the board + # back toward that anchor after every teleport. Measured drift with fixed_base was + # 0.682 -> 0.175 m over ten steps, i.e. into the threshold, which made the stove heat it + # correctly and the test blame the kernel for the test's own instability. + { + "type": "DatasetObject", + "name": "board", + "category": "plywood", + "model": "fkmkqa", + "abilities": {"cookable": {}, "heatable": {}}, + "scale": [3.0, 3.0, 3.0], + "kinematic_only": True, + "position": [15.0, 0.0, 0.1], + }, + # Compact control target: AABB and geometry nearly coincide, so it must still heat. + { + "type": "DatasetObject", + "name": "bagel", + "category": "bagel", + "model": "zlxkry", + "abilities": {"cookable": {}, "freezable": {}, "burnable": {}, "heatable": {}}, + "position": [15.0, 2.0, 0.1], + }, +] + + +@pytest.fixture(scope="module") +def multi_env(): + assert og.sim is None, "This module must run in a fresh process (one Environment per process)." + gm.RENDER_VIEWER_CAMERA = False + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_FLATCACHE = False + gm.ENABLE_TRANSITION_RULES = False + + cfg = { + "env": {"num_envs": N_ENVS}, + "scene": {"type": "Scene"}, + "robots": [{"model": "fetch", "obs_modalities": ["rgb"], "position": [20.0, 20.0, 0.1]}], + "objects": OBJECTS_CFG, + "task": {"type": "DummyTask"}, + } + env = og.Environment(configs=cfg) + for _ in range(10): + og.sim.step() + yield env + og.clear() + + +def scene_objs(env, name): + return [env.scenes[s].object_registry("name", name) for s in range(N_ENVS)] + + +def heat_link_world_pos(source): + link = source.states[HeatSourceOrSink].link + return link.get_position_orientation()[0] + + +def threshold_of(source): + return source.states[HeatSourceOrSink].distance_threshold + + +def aabb_distance(obj, point): + """Distance from @point to the closest point of @obj's world AABB (what the broad phase uses).""" + lo, hi = obj.aabb + return float(th.linalg.norm(point - th.clamp(point, lo, hi))) + + +def geometry_distance(obj, point): + """Distance from @point to the nearest collision-hull vertex of @obj. + + An upper bound on the true surface distance (a face interior can be nearer than any vertex), + so the tests below only rely on it together with a generous margin. + """ + best = float("inf") + for link in obj.links.values(): + pts = link.collision_boundary_points_world + if pts is None or len(pts) == 0: + continue + best = min(best, float(th.linalg.norm(pts - point.reshape(1, 3), dim=-1).min())) + return best + + +def reset_thermals(env): + for s in range(N_ENVS): + stove = env.scenes[s].object_registry("name", "stove") + if ToggledOn in stove.states: + stove.states[ToggledOn].set_value(False) + for name in ("board", "bagel"): + env.scenes[s].object_registry("name", name).states[Temperature].set_value(DEFAULT_TEMP) + og.sim.step() + + +def place_board_so_aabb_reaches_but_geometry_does_not(board, element, threshold): + """Find a pose where the element is inside the board's AABB but far from the board itself. + + A rotated flat sheet leaves most of its bounding box empty, so the interesting spots are the + AABB's own CORNERS: inside the box by construction, yet far from the sheet. For each candidate + orientation the board is shifted so a chosen corner (pulled slightly inward) lands on the heat + element, then the achieved distances are measured rather than assumed. + + Searching real corners instead of guessing offsets also keeps the test asset-agnostic: it does + not depend on the sheet's dimensions, only on its bounding box being much larger than itself. + + Returns the achieved (aabb_dist, geom_dist), or None if no pose qualified. + """ + orientations = [ + th.tensor([0.3826834, 0.0, 0.0, 0.9238795]), # 45 deg about X + th.tensor([0.0, 0.3826834, 0.0, 0.9238795]), # 45 deg about Y + th.tensor([0.5, 0.5, 0.5, 0.5]), # 120 deg about (1,1,1) + ] + for quat in orientations: + board.keep_still() + board.set_position_orientation(position=element, orientation=quat) + og.sim.step() + # AABB is only meaningful once the new orientation has been applied. + lo, hi = board.aabb + centre = 0.5 * (lo + hi) + for sx in (-1.0, 1.0): + for sy in (-1.0, 1.0): + for sz in (-1.0, 1.0): + sign = th.tensor([sx, sy, sz]) + # 0.8 keeps the target point inside the box rather than exactly on its surface. + corner = centre + 0.8 * sign * (hi - lo) * 0.5 + board.keep_still() + board.set_position_orientation( + position=board.get_position_orientation()[0] + (element - corner), orientation=quat + ) + og.sim.step() + a, g = aabb_distance(board, element), geometry_distance(board, element) + if a <= 0.5 * threshold and g >= 1.5 * threshold: + return a, g + return None + + +def test_point_source_ignores_target_whose_aabb_reaches_but_geometry_does_not_n3(multi_env): + """A toggled-on stove must NOT heat a board that only its AABB brings into range. + + This is the case the AABB-only broad phase gets wrong: the element sits inside the rotated + board's bounding box while the board itself is several thresholds away. overlap_sphere would + report no contact, so the kernel must not heat it. + """ + env = multi_env + reset_thermals(env) + + stoves, boards = scene_objs(env, "stove"), scene_objs(env, "board") + achieved = [] + for stove, board in zip(stoves, boards): + element = heat_link_world_pos(stove) + got = place_board_so_aabb_reaches_but_geometry_does_not(board, element, threshold_of(stove)) + assert got is not None, ( + "Could not place the board so that its AABB reaches the heat element while its " + "geometry stays out of range — the asset's dimensions may have changed. Adjust the " + "sweep in place_board_so_aabb_reaches_but_geometry_does_not; this test is meaningless " + "without that configuration." + ) + achieved.append(got) + + for stove in stoves: + assert stove.states[ToggledOn].set_value(True) + for _ in range(10): + og.sim.step() + + # Re-measure AFTER the heating steps. The distances above were taken before the sim ran, so a + # board that drifted (or was nudged by a collision) would make the verdict unreadable — the + # kernel would be judged against a geometry that no longer matches what it saw. + for s, (a, g) in enumerate(achieved): + element = heat_link_world_pos(stoves[s]) + a2, g2 = aabb_distance(boards[s], element), geometry_distance(boards[s], element) + print( + f"\nenv{s}: threshold {threshold_of(stoves[s]):.3f} m" + f"\n before heating: element->AABB {a:.3f}, element->geometry {g:.3f}" + f"\n after heating: element->AABB {a2:.3f}, element->geometry {g2:.3f}" + ) + assert g2 >= 1.5 * threshold_of(stoves[s]), ( + f"env{s}: the board moved during the heating steps (geometry distance {g:.3f} -> " + f"{g2:.3f} m), so this episode no longer tests the AABB-vs-geometry gap. Keep the " + f"board static instead of tightening the assertion below." + ) + print("board temps:", [round(b.states[Temperature].get_value(), 2) for b in boards]) + + heated = [ + f"env{s}: {b.states[Temperature].get_value():.2f} C" + for s, b in enumerate(boards) + if b.states[Temperature].get_value() > DEFAULT_TEMP + 1e-3 + ] + assert not heated, ( + "Stove heated a board whose collision geometry is out of range and only whose AABB is " + f"within the threshold — the narrow phase is not running: {heated}" + ) + reset_thermals(env) + + +def test_point_source_still_heats_a_target_on_the_element_n3(multi_env): + """Control: the narrow phase must not reject a target that genuinely IS in range. + + Guards the opposite failure — a too-strict mesh test would stop food cooking on a lit + burner, which is the regression the AABB-center bug originally caused. + """ + env = multi_env + reset_thermals(env) + + stoves, bagels = scene_objs(env, "stove"), scene_objs(env, "bagel") + for stove, bagel in zip(stoves, bagels): + bagel.keep_still() + bagel.set_position_orientation(position=heat_link_world_pos(stove) + th.tensor([0.0, 0.0, 0.05])) + og.sim.step() + for stove in stoves: + assert stove.states[ToggledOn].set_value(True) + for _ in range(10): + og.sim.step() + + temps = [round(b.states[Temperature].get_value(), 2) for b in bagels] + print("\nbagel temps on the element:", temps) + cold = [f"env{s}: {t}" for s, t in enumerate(temps) if t <= DEFAULT_TEMP + 1e-3] + assert not cold, f"Narrow phase rejected a target sitting on the heat element: {cold}" + reset_thermals(env) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_heat_states.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_heat_states.py new file mode 100644 index 0000000000000000000000000000000000000000..d27ea67794839247c0b375a7010a5a06facb6e20 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_heat_states.py @@ -0,0 +1,515 @@ +"""Multi-env (num_envs=3) versions of the heat / temperature object-state tests. + +Mirrors the heat-related coverage of ``test_object_states.py`` (test_temperature, +test_heat_source_or_sink, test_heated) across 3 cloned scenes, plus diagnostic +tests that read the vectorized heat pipeline's internal index maps to explain the +two failures observed in eval (2026-08-10, see eval-vector-check-20260810/REPORT.md): + + 1. An OFF oven (requires_toggled_on + requires_inside, both unsatisfied) heated a + popcorn bag sitting on a countertop to ~its 250 C source temperature. + 2. A toggled-ON burner/stove did not heat an object placed directly on it. + +Transition rules are intentionally DISABLED here (the clone-scene transition-rule +bug is tracked separately). + +Run standalone (one Environment per process): + OMNIGIBSON_HEADLESS=1 pytest tests/test_multiple_envs_heat_states.py -v -s +""" + +import pytest +import torch as th +import warp as wp + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.macros import macros as m +from omnigibson.object_states import HeatSourceOrSink, Inside, MaxTemperature, Open, Temperature, ToggledOn +from omnigibson.utils.usd_utils import RigidBodyViewAPI + +N_ENVS = 3 +DEFAULT_TEMP = m.object_states.temperature.DEFAULT_TEMPERATURE + +# Heat sources under test. stove = point source (requires_toggled_on only); +# microwave / oven = containment sources (requires_toggled_on + closed + inside); +# fridge = always-active containment cold source. +OBJECTS_CFG = [ + {"type": "DatasetObject", "name": "stove", "category": "stove", "model": "yhjzwg", "position": [0.0, 0.0, 0.5]}, + { + "type": "DatasetObject", + "name": "microwave", + "category": "microwave", + "model": "hjjxmi", + "position": [3.0, 0.0, 0.3], + }, + {"type": "DatasetObject", "name": "fridge", "category": "fridge", "model": "xyejdx", "position": [6.0, 0.0, 1.0]}, + {"type": "DatasetObject", "name": "oven", "category": "oven", "model": "amblrk", "position": [9.0, 0.0, 0.6]}, + # Fillable decoy + an object inside it: creates a true Inside pair that a + # misaligned requires_inside lookup could confuse with "inside the oven". + {"type": "DatasetObject", "name": "bowl", "category": "bowl", "model": "ajzltc", "position": [12.0, 0.0, 0.1]}, + { + "type": "DatasetObject", + "name": "bagel_in_bowl", + "category": "bagel", + "model": "zlxkry", + "abilities": {"cookable": {}, "freezable": {}, "burnable": {}, "heatable": {}}, + "position": [12.0, 0.0, 0.25], + }, + # Flammable object: exercises the OnFire dump/load path (eval bug #1). + { + "type": "DatasetObject", + "name": "plywood", + "category": "plywood", + "model": "fkmkqa", + "abilities": {"flammable": {}}, + "position": [18.0, 0.0, 0.1], + }, + # Far-away heatable targets (mirror bagel/cookable_dishtowel of the n=1 tests). + { + "type": "DatasetObject", + "name": "bagel_a", + "category": "bagel", + "model": "zlxkry", + "abilities": {"cookable": {}, "freezable": {}, "burnable": {}, "heatable": {}}, + "position": [15.0, 0.0, 0.1], + }, + { + "type": "DatasetObject", + "name": "bagel_b", + "category": "bagel", + "model": "zlxkry", + "abilities": {"cookable": {}, "freezable": {}, "burnable": {}, "heatable": {}}, + "position": [15.0, 1.0, 0.1], + }, +] + +TARGET_NAMES = ("bagel_a", "bagel_b", "bagel_in_bowl") +SOURCE_NAMES = ("stove", "microwave", "fridge", "oven") + + +@pytest.fixture(scope="module") +def multi_env(): + assert og.sim is None, "This module must run in a fresh process (one Environment per process)." + gm.RENDER_VIEWER_CAMERA = False + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_FLATCACHE = False + gm.ENABLE_TRANSITION_RULES = False # clone-scene transition-rule bug tracked separately + + cfg = { + "env": {"num_envs": N_ENVS}, + "scene": {"type": "Scene"}, + "robots": [{"model": "fetch", "obs_modalities": ["rgb"], "position": [20.0, 20.0, 0.1]}], + "objects": OBJECTS_CFG, + "task": {"type": "DummyTask"}, + } + env = og.Environment(configs=cfg) + for _ in range(10): + og.sim.step() + yield env + og.clear() + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def scene_objs(env, name): + """The per-scene clones of object @name, index-aligned with env indices.""" + return [env.scenes[s].object_registry("name", name) for s in range(N_ENVS)] + + +def temps(env, name): + return [round(o.states[Temperature].get_value(), 2) for o in scene_objs(env, name)] + + +def reset_thermals(env): + """All sources off / closed, all targets back to DEFAULT_TEMP.""" + for s in range(N_ENVS): + for name in ("stove", "microwave", "oven"): + obj = env.scenes[s].object_registry("name", name) + if ToggledOn in obj.states: + obj.states[ToggledOn].set_value(False) + for name in ("microwave", "fridge", "oven"): + obj = env.scenes[s].object_registry("name", name) + if Open in obj.states: + obj.states[Open].set_value(False, fully=True) + og.sim.step() + for s in range(N_ENVS): + for name in TARGET_NAMES: + obj = env.scenes[s].object_registry("name", name) + assert obj.states[Temperature].set_value(DEFAULT_TEMP) + assert obj.states[MaxTemperature].set_value(DEFAULT_TEMP) + og.sim.step() + + +def influence_pairs(env): + """Decode Temperature.INFLUENCE_MASK into human-readable (scene, source, target) triples.""" + mask = Temperature.INFLUENCE_MASK + if mask is None: + return [] + mask_t = wp.to_torch(mask).to("cpu") + pairs = [] + for s, h, n in th.nonzero(mask_t, as_tuple=False).tolist(): + src = HeatSourceOrSink.IDX_OBJS[s][h] if s < len(HeatSourceOrSink.IDX_OBJS) else None + tgt = Temperature.IDX_OBJS[s][n] if s < len(Temperature.IDX_OBJS) else None + pairs.append((s, src.name if src is not None else f"h={h}", tgt.name if tgt is not None else f"n={n}")) + return pairs + + +def heat_link_world_pos(obj): + """World position of a point heat source's heating element link.""" + hss = obj.states[HeatSourceOrSink] + link = hss.link if hss._links else obj.root_link + return link.get_position_orientation()[0] + + +def dump_heat_maps(env): + """Print the internal index maps the heat kernel consumes (diagnostic aid).""" + print("\n--- heat pipeline maps") + print("HSS OBJ_IDXS:", dict(HeatSourceOrSink.OBJ_IDXS or {})) + print("Temperature OBJ_IDXS:", dict(Temperature.OBJ_IDXS or {})) + print("Inside OBJ_IDXS:", dict(Inside.OBJ_IDXS or {})) + if HeatSourceOrSink._link_flat_idx is not None: + print("link_flat_idx:", wp.to_torch(HeatSourceOrSink._link_flat_idx).to("cpu").tolist()) + if Temperature._hss_self_inside_idx is not None: + print("hss_self_inside_idx:", wp.to_torch(Temperature._hss_self_inside_idx).to("cpu").tolist()) + if Temperature._temp_to_inside_idx is not None: + print("temp_to_inside_idx:", wp.to_torch(Temperature._temp_to_inside_idx).to("cpu").tolist()) + if Temperature._temp_to_aabb_idx is not None: + print("temp_to_aabb_idx:", wp.to_torch(Temperature._temp_to_aabb_idx).to("cpu").tolist()) + + +# --------------------------------------------------------------------------- +# 1) Leak detector — mirrors eval bug #1 (OFF oven heated the popcorn bag) +# --------------------------------------------------------------------------- + + +def test_all_sources_off_no_heating_n3(multi_env): + """With every heat source off/closed and all targets far away, no target's + temperature may change in ANY env. In eval, an OFF oven (both gates + unsatisfied) heated a countertop popcorn bag to ~250 C; `bagel_in_bowl` + reproduces the true-Inside decoy pair that a misaligned requires_inside + lookup could confuse with "inside the oven".""" + env = multi_env + reset_thermals(env) + + for _ in range(30): + og.sim.step() + + failures = [] + for name in TARGET_NAMES: + for s, t in enumerate(temps(env, name)): + if abs(t - DEFAULT_TEMP) > 1e-3: + failures.append(f"{name} env{s}: {t} != {DEFAULT_TEMP}") + if failures: + print("\nLEAK: temperatures changed with all sources off:", failures) + print("influence pairs this step:", influence_pairs(env)) + dump_heat_maps(env) + assert not failures, f"Heat leak with all sources off: {failures}" + + +# --------------------------------------------------------------------------- +# 2) Point-source heating — mirrors eval bug #2 (ON burner didn't heat hotdog) +# --------------------------------------------------------------------------- + + +def test_toggled_stove_heats_targets_in_every_env_n3(multi_env): + """A toggled-on stove must heat an object placed directly at its heating + element in EVERY env. Targets are placed at each scene's OWN heat-element + link position, so if the kernel resolves the element pose through a single + per-column link index (first scene wins) instead of a per-scene one, envs + beyond that scene compute a ~scene-offset distance and never heat.""" + env = multi_env + reset_thermals(env) + + stoves = scene_objs(env, "stove") + bagels = scene_objs(env, "bagel_a") + for stove, bagel in zip(stoves, bagels): + elem = heat_link_world_pos(stove) + bagel.keep_still() + bagel.set_position_orientation(position=elem + th.tensor([0.0, 0.0, 0.05])) + og.sim.step() + for stove in stoves: + assert stove.states[ToggledOn].set_value(True) + for _ in range(10): + og.sim.step() + + gate_values = [stove.states[HeatSourceOrSink].get_value() for stove in stoves] + print("\nstove HSS active per env:", gate_values) + print("bagel_a temps per env:", temps(env, "bagel_a")) + print("influence pairs:", influence_pairs(env)) + + assert all(gate_values), f"Toggled-on stove not active as heat source in all envs: {gate_values}" + + failures = [f"env{s}: {t}" for s, t in enumerate(temps(env, "bagel_a")) if t <= DEFAULT_TEMP + 1e-3] + if failures: + # Print exactly what the kernel used vs what each scene needs. + dump_heat_maps(env) + h = (HeatSourceOrSink.OBJ_IDXS or {}).get(stoves[0].relative_prim_path) + for s, stove in enumerate(stoves): + link = stove.states[HeatSourceOrSink].link + print( + f"env{s}: heat element world pos {heat_link_world_pos(stove).tolist()} " + f"flat_idx(per-scene link)={RigidBodyViewAPI.get_flat_idx(link.prim_path)}" + ) + if h is not None and HeatSourceOrSink._link_flat_idx is not None: + lfi = wp.to_torch(HeatSourceOrSink._link_flat_idx).to("cpu") + per_scene = lfi[:, h].tolist() if lfi.dim() == 2 else lfi[h].item() + print(f"kernel link_flat_idx for stove column {h}:", per_scene) + assert not failures, f"Toggled-on stove failed to heat bagel placed on its element: {failures}" + + reset_thermals(env) + + +def test_stove_heats_only_its_own_env_n3(multi_env): + """Toggling only env1's stove must heat only env1's target (targets remain + at each scene's heat element from the previous placement).""" + env = multi_env + reset_thermals(env) + + stoves = scene_objs(env, "stove") + bagels = scene_objs(env, "bagel_a") + for stove, bagel in zip(stoves, bagels): + bagel.keep_still() + bagel.set_position_orientation(position=heat_link_world_pos(stove) + th.tensor([0.0, 0.0, 0.05])) + og.sim.step() + assert stoves[1].states[ToggledOn].set_value(True) + for _ in range(10): + og.sim.step() + + t = temps(env, "bagel_a") + print("\nbagel_a temps (only env1 stove on):", t, "| influence:", influence_pairs(env)) + assert abs(t[0] - DEFAULT_TEMP) < 1e-3, f"env0 heated by env1's stove: {t}" + assert abs(t[2] - DEFAULT_TEMP) < 1e-3, f"env2 heated by env1's stove: {t}" + assert t[1] > DEFAULT_TEMP + 1e-3, f"env1's own stove did not heat its target: {t}" + + reset_thermals(env) + + +# --------------------------------------------------------------------------- +# 3) Containment sources per env (microwave heat, fridge cold) +# --------------------------------------------------------------------------- + + +def test_microwave_requires_inside_per_env_n3(multi_env): + """Objects inside a closed, toggled-on microwave heat up in every env; + the same objects do NOT heat while the microwave is off.""" + env = multi_env + reset_thermals(env) + + microwaves = scene_objs(env, "microwave") + bagels = scene_objs(env, "bagel_b") + for mw, bagel in zip(microwaves, bagels): + bagel.keep_still() + bagel.set_position_orientation(position=mw.aabb_center + th.tensor([0.0, 0.03, 0.0])) + for _ in range(3): + og.sim.step() + + inside_flags = [b.states[Inside].get_value(mw) for b, mw in zip(bagels, microwaves)] + print("\nbagel_b inside microwave per env:", inside_flags) + assert all(inside_flags), f"Placement failed, bagel not inside microwave in all envs: {inside_flags}" + + # Off: no heating. + for _ in range(5): + og.sim.step() + t_off = temps(env, "bagel_b") + assert all(abs(t - DEFAULT_TEMP) < 1e-3 for t in t_off), f"Heated by OFF microwave: {t_off}" + + # Closed + on: heats in every env. + for mw in microwaves: + assert mw.states[ToggledOn].set_value(True) + for _ in range(10): + og.sim.step() + t_on = temps(env, "bagel_b") + print("bagel_b temps with microwave on:", t_on, "| influence:", influence_pairs(env)) + failures = [f"env{s}: {t}" for s, t in enumerate(t_on) if t <= DEFAULT_TEMP + 1e-3] + if failures: + dump_heat_maps(env) + assert not failures, f"Closed+on microwave failed to heat inside object: {failures}" + + reset_thermals(env) + + +def test_fridge_cools_per_env_n3(multi_env): + """The fridge (always-active cold source) must cool objects inside it in every env.""" + env = multi_env + reset_thermals(env) + + fridges = scene_objs(env, "fridge") + bagels = scene_objs(env, "bagel_b") + for fridge, bagel in zip(fridges, bagels): + bagel.keep_still() + bagel.set_position_orientation(position=fridge.aabb_center + th.tensor([0.0, 0.0, 0.1])) + assert fridge.states[Open].set_value(False, fully=True) + for _ in range(3): + og.sim.step() + + inside_flags = [b.states[Inside].get_value(f) for b, f in zip(bagels, fridges)] + print("\nbagel_b inside fridge per env:", inside_flags) + assert all(inside_flags), f"Placement failed, bagel not inside fridge in all envs: {inside_flags}" + + for _ in range(10): + og.sim.step() + t = temps(env, "bagel_b") + print("bagel_b temps in closed fridge:", t) + failures = [f"env{s}: {v}" for s, v in enumerate(t) if v >= DEFAULT_TEMP - 1e-3] + if failures: + dump_heat_maps(env) + assert not failures, f"Fridge failed to cool inside object: {failures}" + + reset_thermals(env) + + +# --------------------------------------------------------------------------- +# 4) Gate logic per env — mirrors test_heat_source_or_sink at n=3 +# --------------------------------------------------------------------------- + + +def test_heat_source_gates_per_env_n3(multi_env): + """HeatSourceOrSink activation gates must be evaluated per env independently.""" + env = multi_env + reset_thermals(env) + + stoves = scene_objs(env, "stove") + microwaves = scene_objs(env, "microwave") + + # All off -> inactive everywhere. + for s in range(N_ENVS): + assert not stoves[s].states[HeatSourceOrSink].get_value(), f"stove env{s} active while off" + assert not microwaves[s].states[HeatSourceOrSink].get_value(), f"microwave env{s} active while off" + + # Toggle only env2's stove. + assert stoves[2].states[ToggledOn].set_value(True) + og.sim.step() + values = [st.states[HeatSourceOrSink].get_value() for st in stoves] + assert values == [False, False, True], f"stove gate per env wrong: {values}" + + # Microwave: open door blocks activation per env. + for mw in microwaves: + assert mw.states[ToggledOn].set_value(True) + assert microwaves[0].states[Open].set_value(True) + og.sim.step() + values = [mw.states[HeatSourceOrSink].get_value() for mw in microwaves] + assert values == [False, True, True], f"microwave open-door gate per env wrong: {values}" + + reset_thermals(env) + + +# --------------------------------------------------------------------------- +# 5) Index-map alignment diagnostics — the "why" for both eval bugs +# --------------------------------------------------------------------------- + + +def test_point_source_link_index_is_per_scene_n3(multi_env): + """THE smoking-gun check for eval bug #2: for point sources the kernel + resolves the heating-element pose via HeatSourceOrSink._link_flat_idx, + which is (N_hss,) — one flat RigidBodyView index per source COLUMN. With + S cloned scenes the element link is a different rigid body in each scene, + so a single per-column index cannot be right for all envs. This test + asserts the stored index matches every scene's own element link and + prints the full mismatch table when it does not.""" + env = multi_env + stoves = scene_objs(env, "stove") + col = (HeatSourceOrSink.OBJ_IDXS or {}).get(stoves[0].relative_prim_path) + assert col is not None, "stove not tracked by HeatSourceOrSink" + assert HeatSourceOrSink._link_flat_idx is not None + stored = wp.to_torch(HeatSourceOrSink._link_flat_idx).to("cpu") + + mismatches = [] + for s, stove in enumerate(stoves): + link = stove.states[HeatSourceOrSink].link + expected = RigidBodyViewAPI.get_flat_idx(link.prim_path) + kernel_uses = stored[s, col].item() if stored.dim() == 2 else stored[col].item() + print(f"env{s}: stove element link {link.prim_path} flat_idx={expected} (kernel uses {kernel_uses})") + if expected != kernel_uses: + mismatches.append((s, expected, kernel_uses)) + assert not mismatches, ( + f"Point-source link index is not per-scene (shape={tuple(stored.shape)}): scenes " + f"{mismatches} (scene, expected, kernel_uses) resolve the wrong element pose in " + f"_incoming_heat_kernel's distance check." + ) + + +def test_onfire_state_roundtrip_preserves_temperature_n3(multi_env): + """THE root-cause regression test for eval bug #1 (popcorn bag at ~249 C after + every reset): OnFire is a derived threshold state over Temperature, but it + inherits the generic TensorizedAbsoluteState._load_state, which routes + through _set_value. OnFire._set_value(False) writes + Temperature = ignition_temperature - 1 (= 249 with the 250 default) — correct + for a user-level "extinguish" call, catastrophic when replayed by + scene dump/load: restoring a COLD flammable object heats it to 249 C. + scene.reset() -> restore() -> load_state() does exactly this, so every + flammable object in every scene starts every episode Heated. This test + round-trips each env's flammable object through dump_state/load_state and + requires its temperature to be unchanged.""" + env = multi_env + reset_thermals(env) + + from omnigibson.object_states import OnFire + + failures = [] + for s, plywood in enumerate(scene_objs(env, "plywood")): + assert OnFire in plywood.states, "plywood should be flammable (OnFire state)" + assert plywood.states[Temperature].set_value(DEFAULT_TEMP) + og.sim.step() + assert not plywood.states[OnFire].get_value() + t_before = plywood.states[Temperature].get_value() + + state = plywood.dump_state(serialized=False) + plywood.load_state(state, serialized=False) + + t_after = plywood.states[Temperature].get_value() + print(f"env{s}: plywood T before dump/load={t_before:.1f} after={t_after:.1f}") + if abs(t_after - t_before) > 1e-3: + failures.append(f"env{s}: {t_before:.1f} -> {t_after:.1f}") + assert not failures, ( + "OnFire state round-trip changed a cold flammable object's temperature " + f"(load_state routes through _set_value which clamps Temperature to ignition-1): {failures}" + ) + + reset_thermals(env) + + +def test_requires_inside_index_alignment_n3(multi_env): + """Diagnostic for eval bug #1 (OFF oven heats far-away bag): validates the + requires_inside lookup chain end to end. For every (containment source, + target) pair, the kernel's inside_values[s, temp_to_inside_idx[n], + hss_self_inside_idx[h]] read must equal the ground-truth per-env + Inside.get_value(). Any mismatch is printed with names.""" + env = multi_env + reset_thermals(env) + for _ in range(3): + og.sim.step() + + inside_vals = wp.to_torch(Inside.VALUES_WP).to("cpu") if Inside.VALUES_WP is not None else None + assert inside_vals is not None, "Inside state has no tensorized values" + hss_inside = wp.to_torch(Temperature._hss_self_inside_idx).to("cpu") + temp_inside = wp.to_torch(Temperature._temp_to_inside_idx).to("cpu") + + mismatches = [] + for src_name in ("microwave", "fridge", "oven"): + sources = scene_objs(env, src_name) + h = (HeatSourceOrSink.OBJ_IDXS or {}).get(sources[0].relative_prim_path) + if h is None or not sources[0].states[HeatSourceOrSink].requires_inside: + continue + for tgt_name in TARGET_NAMES: + targets = scene_objs(env, tgt_name) + n = (Temperature.OBJ_IDXS or {}).get(targets[0].relative_prim_path) + if n is None: + continue + src_ii, tgt_ii = hss_inside[h].item(), temp_inside[n].item() + for s in range(N_ENVS): + truth = bool(targets[s].states[Inside].get_value(sources[s])) + if src_ii < 0 or tgt_ii < 0: + kernel_view = False + else: + kernel_view = bool(inside_vals[s, tgt_ii, src_ii].item()) + if truth != kernel_view: + mismatches.append( + f"env{s}: Inside({tgt_name}, {src_name}) truth={truth} but kernel reads " + f"inside_values[{s},{tgt_ii},{src_ii}]={kernel_view}" + ) + if mismatches: + dump_heat_maps(env) + assert not mismatches, "requires_inside index chain misaligned:\n" + "\n".join(mismatches) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_point_tasks.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_point_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..241efd1c20c9884ad4cfb78ed090daa4d88134af --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_point_tasks.py @@ -0,0 +1,46 @@ +""" +test_multiple_envs_point_tasks.py +================================= +Goal-based point tasks (PointNavigationTask, PointReachingTask) under num_envs > 1: stepping works +and each env exposes its own goal position. + +Replaces test_multiple_envs_point_navigation.py and test_multiple_envs_point_reaching.py, which were +byte-identical apart from the task-type string. The per-env tensor-shape contract they also each +duplicated now lives in test_multiple_envs_task_tensors.py. +""" + +import pytest +import torch as th + + +POINT_TASK_TYPES = ["PointNavigationTask", "PointReachingTask"] +NUM_ENVS = 2 + + +@pytest.fixture(scope="module", params=POINT_TASK_TYPES) +def point_task_type(request): + """Task type under test, module-scoped so pytest groups tests per task type.""" + return request.param + + +class TestPointTasks: + """Goal-based point-task behavior across robots and task types.""" + + def test_multi_step_and_goal_shape(self, make_multi_env, point_task_type, robot_model): + """Run a few steps and verify goal positions exist per env.""" + env = make_multi_env(NUM_ENVS, robot=robot_model, task_type=point_task_type) + + for step_i in range(3): + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(NUM_ENVS)] + ) + obs_list, rewards, terminateds, truncateds, infos = env.step(actions) + print(f" [{point_task_type}/{robot_model}] step {step_i + 1}/3: rewards={rewards}") + + assert rewards.shape == (NUM_ENVS,) + assert terminateds.shape == (NUM_ENVS,) + + for env_idx in range(NUM_ENVS): + goal = env.task.get_goal_pos(env_idx) + print(f" env {env_idx} goal_pos={goal}") + assert goal.shape == (3,) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_task_tensors.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_task_tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..2997b01a20dd468a5ab4246805aa7fdec5414b62 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_task_tensors.py @@ -0,0 +1,72 @@ +""" +test_multiple_envs_task_tensors.py +================================== +Per-env tensor contract shared by every task type: with num_envs=N, a task's reward / done / +success, each reward function's `_reward`, and each termination condition's `_done` must all be +(N,)-shaped tensors. + +This lives in one place and is parametrized over MULTI_ENV_TASK_TYPES. It used to be copy-pasted +into test_multiple_envs_{dummy_api,grasp,point_navigation,point_reaching}.py -- four byte-identical +copies, each additionally parametrized over all four robots, for 48 test instances of what is a +single property of task_base. The assertions are pure shape checks, so the robot axis added no +coverage; per-robot multi-env construction is covered by +test_multiple_envs_dummy_scene.py::TestRobotGetterSetter and the task-specific suites. +""" + +import pytest +import torch as th + +from utils import MULTI_ENV_TASK_TYPES + +NUM_ENVS = 2 + + +@pytest.fixture(scope="module", params=MULTI_ENV_TASK_TYPES) +def task_type(request): + """Task type under test. Module-scoped + parametrized so pytest groups all tests for one task + together, letting `make_multi_env` build a single env per task type instead of one per test.""" + return request.param + + +def _step_once(env): + actions = th.stack( + [th.from_numpy(env.scenes[i].robots[0].action_space.sample()).float() for i in range(env.num_envs)] + ) + env.step(actions) + + +class TestTaskTensors: + """Task step outputs must be per-env tensors, for every task type.""" + + def test_task_step_tensors(self, make_multi_env, task_type): + """Task reward / done / success are (num_envs,) tensors.""" + env = make_multi_env(NUM_ENVS, task_type=task_type) + _step_once(env) + + print(f" [{task_type}] reward={env.task.reward}, done={env.task.done}, success={env.task.success}") + assert env.task.reward.shape == (NUM_ENVS,) + assert env.task.done.shape == (NUM_ENVS,) + assert env.task.success.shape == (NUM_ENVS,) + + def test_reward_tensor_returns(self, make_multi_env, task_type): + """Reward functions return (num_envs,) tensors.""" + env = make_multi_env(NUM_ENVS, task_type=task_type) + _step_once(env) + + for rf_name, rf in env.task._reward_functions.items(): + print(f" [{task_type}] reward fn '{rf_name}': shape={rf._reward.shape}, values={rf._reward}") + assert rf._reward.shape == ( + NUM_ENVS, + ), f"Reward function '{rf_name}' _reward has wrong shape: {rf._reward.shape}" + + def test_termination_tensor_returns(self, make_multi_env, task_type): + """Termination conditions return (num_envs,) bool tensors.""" + env = make_multi_env(NUM_ENVS, task_type=task_type) + _step_once(env) + + for tc_name, tc in env.task._termination_conditions.items(): + print(f" [{task_type}] termination '{tc_name}': shape={tc._done.shape}, values={tc._done}") + assert tc._done.shape == ( + NUM_ENVS, + ), f"Termination condition '{tc_name}' _done has wrong shape: {tc._done.shape}" + assert tc._done.dtype == th.bool diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_transition_rules.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_transition_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..bda64b184c3e907a667c2490bf67ae2d39ad70f0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_multiple_envs_transition_rules.py @@ -0,0 +1,145 @@ +"""Multi-env (num_envs=2) transition-rule tests. + +Regression coverage for the multi-scene transition-rule bug where recipe rules +(e.g. CookingPhysicalParticleRule) effectively fired only in the canonical scene +(env 0): macro physical particle systems dumped/loaded their particle poses in +the WORLD frame, so any state authored in the canonical scene (dataset task +instances, scene-file init states) loaded cloned scenes' particles at env 0's +world coordinates -- outside the cloned scene's own containers -- and the +rules' Contains gate could then never pass outside env 0. + +Fixed by storing particle poses scene-relative in BaseSystem._dump_state / +_load_state (mirroring PhysxParticleInstancer, which was already scene-aware). + +Run standalone (one Environment per process): + OMNIGIBSON_HEADLESS=1 pytest tests/test_multiple_envs_transition_rules.py -v -s +""" + +import pytest +import torch as th + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.object_states import Contains, Heated + +N_ENVS = 2 + + +@pytest.fixture(scope="module") +def multi_env(): + assert og.sim is None, "This module must run in a fresh process (one Environment per process)." + gm.RENDER_VIEWER_CAMERA = False + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_FLATCACHE = False + gm.ENABLE_TRANSITION_RULES = True + + cfg = { + "env": {"num_envs": N_ENVS}, + "scene": {"type": "Scene"}, + "robots": [{"type": "Fetch", "obs_modalities": ["rgb"], "position": [20.0, 20.0, 0.1]}], + "objects": [ + { + "type": "DatasetObject", + "name": "stockpot", + "category": "stockpot", + "model": "dcleem", + "abilities": {"fillable": {}, "heatable": {}}, + "position": [0.0, 0.0, 0.15], + }, + ], + "task": {"type": "DummyTask"}, + } + env = og.Environment(configs=cfg) + for _ in range(10): + og.sim.step() + yield env + og.clear() + + +def _pots(env): + return [env.scenes[s].object_registry("name", "stockpot") for s in range(N_ENVS)] + + +def test_macro_physical_particle_state_is_scene_relative(multi_env): + """Macro physical particle poses (e.g. popcorn, the system from the make_microwave_popcorn + eval task) must be dumped scene-relative and loaded back through the OWNING scene's pose, + so a state authored in the canonical scene places a cloned scene's particles inside the + cloned scene's own geometry.""" + env = multi_env + pots = _pots(env) + popcorn = [env.scenes[s].get_system("popcorn") for s in range(N_ENVS)] + og.sim.step() + + for s in range(N_ENVS): + popcorn[s].generate_particles(positions=[(pots[s].aabb_center + th.tensor([0.0, 0.03, 0.05])).tolist()]) + og.sim.step() + for s in range(N_ENVS): + assert pots[s].states[Contains].get_value(popcorn[s]), f"setup failed: popcorn not contained in scene {s}" + + states = [popcorn[s].dump_state(serialized=False) for s in range(N_ENVS)] + + # 1) Dumped positions are scene-relative: no scene world-offset baked into the state. + identity_quat = th.tensor([0.0, 0.0, 0.0, 1.0]) + for s in range(N_ENVS): + world_pos = popcorn[s].get_particles_position_orientation()[0][0] + rel_expected = env.scenes[s].convert_world_pose_to_scene_relative(world_pos, identity_quat)[0] + delta = th.norm(states[s]["positions"][0] - rel_expected) + assert delta < 1e-4, ( + f"scene {s}: dumped particle position {states[s]['positions'][0].tolist()} is not scene-relative " + f"(expected {rel_expected.tolist()})" + ) + + # 2) Cross-scene load: a canonical-scene-authored state (env 0's dump) loaded into env 1's + # system must land inside env 1's own container, not env 0's. + popcorn[1].load_state(states[0], serialized=False) + og.sim.step() + pos_after = popcorn[1].get_particles_position_orientation()[0][0] + lo, hi = pots[1].aabb + assert th.all(pos_after > lo - 0.2) and th.all(pos_after < hi + 0.2), ( + f"canonical-authored particle state loaded into scene 1 landed at {pos_after.tolist()}, " + f"outside scene 1's stockpot aabb {lo.tolist()}..{hi.tolist()} (world-frame leak into scene 0)" + ) + assert pots[1].states[Contains].get_value(popcorn[1]), "scene 1's pot does not contain the cross-loaded particle" + + # Clean up so the (heatable) pots don't cook popcorn during the next test + for s in range(N_ENVS): + popcorn[s].remove_all_particles() + og.sim.step() + + +def test_cooking_physical_particle_rule_fires_per_scene_with_isolation(multi_env): + """CookingPhysicalParticleRule must fire in whichever scene meets its conditions -- + exclusively in a non-canonical scene when only that scene's container is heated, and in + the canonical scene when its container is heated too.""" + env = multi_env + pots = _pots(env) + rice = [env.scenes[s].get_system("brown_rice") for s in range(N_ENVS)] + water = [env.scenes[s].get_system("water") for s in range(N_ENVS)] + og.sim.step() + + for s in range(N_ENVS): + rice[s].generate_particles(positions=[(pots[s].aabb_center + th.tensor([0.03, 0.0, 0.0])).tolist()]) + water[s].generate_particles(positions=[(pots[s].aabb_center + th.tensor([-0.03, 0.0, 0.0])).tolist()]) + og.sim.step() + for s in range(N_ENVS): + assert pots[s].states[Contains].get_value(rice[s]), f"setup failed: rice not contained in scene {s}" + assert pots[s].states[Contains].get_value(water[s]), f"setup failed: water not contained in scene {s}" + + def cooked(s): + scene = env.scenes[s] + return scene.is_system_active("cooked__brown_rice") and scene.get_system("cooked__brown_rice").n_particles > 0 + + # Heat ONLY scene 1's pot: the rule must fire in scene 1 and ONLY in scene 1. + assert pots[1].states[Heated].set_value(True) + for _ in range(8): + og.sim.step() + assert cooked(1), "rule did not fire in scene 1 despite its container being heated with recipe inputs inside" + assert not cooked(0), "rule fired in scene 0 even though only scene 1's container was heated" + assert rice[0].n_particles > 0, "scene 0's raw particles were consumed without its container being heated" + + # Now heat scene 0's pot as well: the rule must fire there too. + assert pots[0].states[Heated].set_value(True) + for _ in range(8): + og.sim.step() + assert cooked(0), "rule did not fire in scene 0 after its container was heated" diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_object_removal.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_object_removal.py new file mode 100644 index 0000000000000000000000000000000000000000..243dbbe3970a4f3e031e4a5cd3d26c4c56526333 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_object_removal.py @@ -0,0 +1,75 @@ +import pytest + +import omnigibson as og +from omnigibson.objects import DatasetObject + + +def test_removal_and_readdition(env): + # Add an apple + apple = DatasetObject( + name="apple_unique", + category="apple", + model="agveuv", + ) + + # Import it into the scene + env.scene.add_object(apple) + + # Check that apple exists + assert env.scene.object_registry("name", "apple_unique") is not None + + # Step a few times + for _ in range(5): + og.sim.step() + + # Remove the apple + env.scene.remove_object(obj=apple) + + # Check that NAMES is the same as before + assert env.scene.object_registry("name", "apple_unique") is None + + # Importing should work now + apple2 = DatasetObject( + name="apple_unique", + category="apple", + model="agveuv", + ) + env.scene.add_object(apple2) + og.sim.step() + + # Clear the stuff we added + env.scene.remove_object(apple2) + + +def test_readdition(env): + # Add an apple + apple = DatasetObject( + name="apple_unique", + category="apple", + model="agveuv", + ) + + # Import it into the scene + env.scene.add_object(apple) + + # Check that apple exists + assert env.scene.object_registry("name", "apple_unique") is not None + + # Step a few times + for _ in range(5): + og.sim.step() + + # Creating and importing a new apple should fail + with pytest.raises(AssertionError): + apple2 = DatasetObject( + name="apple_unique", + category="apple", + model="agveuv", + ) + env.scene.add_object(apple2) + + # Check that apple exists + assert env.scene.object_registry("name", "apple_unique") is not None + + # Clear the stuff we added + env.scene.remove_object(apple) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_object_states.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_object_states.py new file mode 100644 index 0000000000000000000000000000000000000000..702e9cbff8a8ea2b607ac9b226bd064757d3f48c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_object_states.py @@ -0,0 +1,1479 @@ +import math + +import pytest +import torch as th +import warp as wp +from utils import SYSTEM_EXAMPLES, get_random_pose, place_obj_on_floor_plane, place_objA_on_objB_bbox + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import macros as m +from omnigibson.object_states import ( + AABB, + AttachedTo, + Burnt, + ContactParticles, + Adjacency, + Contains, + Cooked, + Covered, + Draped, + Filled, + Folded, + Frozen, + Heated, + HeatSourceOrSink, + Inside, + Joint, + MaxTemperature, + NextTo, + OnFire, + OnTop, + Open, + Overlaid, + ParticleApplier, + ParticleRemover, + ParticleSink, + ParticleSource, + Pose, + Saturated, + Temperature, + ToggledOn, + Touching, + Under, + Unfolded, +) +from omnigibson.object_states.slicer_active import SlicerActive +from omnigibson.systems import VisualParticleSystem +from omnigibson.utils.physx_utils import apply_force_at_pos +from omnigibson.utils.usd_utils import RigidContactAPI + + +def test_attached_to(env, bookcase_back, bookcase_shelf, bookcase_baseboard): + # Lower the mass of the shelf - otherwise, the gravity will create enough torque to break the joint + bookcase_shelf.root_link.mass = 0.1 + + bookcase_back.set_position_orientation(position=[0, 0, 0.01], orientation=[0, 0, 0, 1]) + bookcase_back.keep_still() + bookcase_shelf.set_position_orientation( + position=[0, 0.0286, 0.2], orientation=T.euler2quat(th.tensor([0.0, -math.pi / 2.0, math.pi / 2.0])) + ) + bookcase_shelf.keep_still() + + og.sim.step() + + # The shelf should not be attached to the back panel (no contact yet) + assert not bookcase_shelf.states[Touching].get_value(bookcase_back) + assert not bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + # Let the shelf fall + for _ in range(10): + og.sim.step() + + # The shelf should be attached to the back panel + assert bookcase_shelf.states[Touching].get_value(bookcase_back) + assert bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + # Try to attach again (should be no-op) + assert bookcase_shelf.states[AttachedTo].set_value(bookcase_back, True) + # The shelf should still be attached to the back panel + assert bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + # Detach + assert bookcase_shelf.states[AttachedTo].set_value(bookcase_back, False) + # The shelf should not be attached to the back panel + assert not bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + # Attach again + assert bookcase_shelf.states[AttachedTo].set_value(bookcase_back, True) + # shelf should be attached to the back panel + assert bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + force_dir = th.tensor([0, 0, 1]) + # A small force will not break the attachment + force_mag = 10 + apply_force_at_pos(bookcase_shelf.root_link, force_dir * force_mag, bookcase_shelf.get_position_orientation()[0]) + og.sim.step() + assert bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + # A large force will break the attachment + force_mag = 1000 + apply_force_at_pos(bookcase_shelf.root_link, force_dir * force_mag, bookcase_shelf.get_position_orientation()[0]) + og.sim.step() + assert not bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + bookcase_shelf.set_position_orientation(position=[0, 0, 10], orientation=[0, 0, 0, 1]) + assert not bookcase_shelf.states[AttachedTo].set_value(bookcase_back, True) + # The shelf should not be attached to the back panel because the alignment is wrong + assert not bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + assert bookcase_shelf.states[AttachedTo].set_value(bookcase_back, True, bypass_alignment_checking=True) + # The shelf should be attached to the back panel because the alignment checking is bypassed + assert bookcase_shelf.states[AttachedTo].get_value(bookcase_back) + + # The shelf baseboard should NOT be attached because the attachment has the wrong type + bookcase_baseboard.set_position_orientation(position=[0.37, -0.93, 0.03], orientation=[0, 0, 0, 1]) + assert not bookcase_baseboard.states[AttachedTo].set_value(bookcase_back, True, bypass_alignment_checking=True) + assert not bookcase_baseboard.states[AttachedTo].get_value(bookcase_back) + + +def test_on_top(env, breakfast_table, bowl, dishtowel): + place_obj_on_floor_plane(breakfast_table) + for i, obj in enumerate((bowl, dishtowel)): + place_objA_on_objB_bbox(obj, breakfast_table) + for _ in range(5): + og.sim.step() + + assert obj.states[OnTop].get_value(breakfast_table) + + obj.set_position_orientation(position=th.ones(3) * 10 * (i + 1)) + og.sim.step() + + assert not obj.states[OnTop].get_value(breakfast_table) + + assert bowl.states[OnTop].set_value(breakfast_table, True) + assert dishtowel.states[OnTop].set_value(breakfast_table, True) + + with pytest.raises(NotImplementedError): + bowl.states[OnTop].set_value(breakfast_table, False) + + +def test_inside(env, bottom_cabinet, bowl, dishtowel): + place_obj_on_floor_plane(bottom_cabinet) + bowl.set_position_orientation(position=[0.0, 0.0, 0.08]) + dishtowel.set_position_orientation(position=[0, 0.0, 0.5]) + + for _ in range(5): + og.sim.step() + + assert bowl.states[Inside].get_value(bottom_cabinet) + assert dishtowel.states[Inside].get_value(bottom_cabinet) + + bowl.set_position_orientation(position=[10.0, 10.0, 1.0]) + dishtowel.set_position_orientation(position=[20.0, 20.0, 1.0]) + + for _ in range(5): + og.sim.step() + + assert not bowl.states[Inside].get_value(bottom_cabinet) + assert not dishtowel.states[Inside].get_value(bottom_cabinet) + + assert bowl.states[Inside].set_value(bottom_cabinet, True) + assert dishtowel.states[Inside].set_value(bottom_cabinet, True) + + with pytest.raises(NotImplementedError): + bowl.states[OnTop].set_value(bottom_cabinet, False) + + +def test_under(env, breakfast_table, bowl, dishtowel): + place_obj_on_floor_plane(breakfast_table) + for i, obj in enumerate((bowl, dishtowel)): + place_obj_on_floor_plane(obj) + for _ in range(5): + og.sim.step() + + assert obj.states[Under].get_value(breakfast_table) + + obj.set_position_orientation(position=th.ones(3) * 10 * (i + 1)) + og.sim.step() + + assert not obj.states[Under].get_value(breakfast_table) + + assert bowl.states[Under].set_value(breakfast_table, True) + assert dishtowel.states[Under].set_value(breakfast_table, True) + + with pytest.raises(NotImplementedError): + bowl.states[Under].set_value(breakfast_table, False) + + +def test_touching(env, breakfast_table, bowl, dishtowel): + place_obj_on_floor_plane(breakfast_table) + for i, obj in enumerate((bowl, dishtowel)): + place_objA_on_objB_bbox(obj, breakfast_table) + for _ in range(5): + og.sim.step() + + assert obj.states[Touching].get_value(breakfast_table) + assert breakfast_table.states[Touching].get_value(obj) + + obj.set_position_orientation(position=th.ones(3) * 10 * (i + 1)) + og.sim.step() + + assert not obj.states[Touching].get_value(breakfast_table) + assert not breakfast_table.states[Touching].get_value(obj) + + with pytest.raises(NotImplementedError): + bowl.states[Touching].set_value(breakfast_table, None) + + +def test_rigid_contact_bodies(env, breakfast_table, bowl): + from omnigibson.utils.usd_utils import RigidContactAPI + + place_obj_on_floor_plane(breakfast_table) + place_objA_on_objB_bbox(bowl, breakfast_table) + for _ in range(5): + og.sim.step() + + # Bowl should be in contact with the table + assert RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=False + ) + assert RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=True + ) + + # Let bodies settle/sleep and verify contacts persist + for _ in range(300): + og.sim.step() + assert breakfast_table.is_asleep, "Table should be asleep" + assert bowl.root_link.is_asleep, "Bowl should be asleep" + assert RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=False + ) + assert RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=True + ) + + # Move the bowl far away and verify contacts clear + bowl.set_position_orientation(position=th.tensor([10.0, 10.0, 10.0])) + og.sim.step() + assert not RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=False + ) + assert not RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=True + ) + assert not RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[breakfast_table], with_set=[bowl], ignore_set=None, current_only=False + ) + assert not RigidContactAPI.is_in_contact( + scene_idx=env.scene.idx, query_set=[breakfast_table], with_set=[bowl], ignore_set=None, current_only=True + ) + + +def test_multi_object_contact_broadcast(env, breakfast_table, bowl): + """ + Test contact-detection for ToggledOn and SlicerActive when there are multiple toggle/slicer objects. + """ + place_obj_on_floor_plane(breakfast_table) + place_objA_on_objB_bbox(bowl, breakfast_table) + for _ in range(5): + og.sim.step() + + s = env.scene.idx + assert RigidContactAPI.is_in_contact( + scene_idx=s, query_set=[bowl], with_set=[breakfast_table], ignore_set=None, current_only=False + ), "Precondition failed: bowl should be resting in contact with the table" + + row_bowl = RigidContactAPI.get_contact_row_mask(s, [bowl]) # (R,) bool + col_table = RigidContactAPI.get_contact_col_mask(s, [breakfast_table]) # (C,) bool + R, C = row_bowl.shape[0], col_table.shape[0] + + def run_warp(query_u8, filter_u8, n_out): + q_wp = wp.from_torch(query_u8.cuda().contiguous(), dtype=wp.uint8) + w_wp = wp.from_torch(filter_u8.cuda().contiguous(), dtype=wp.uint8) + out_wp = wp.zeros(n_out, dtype=wp.int32, device="cuda") + RigidContactAPI.is_in_contact_batch_warp( + scene_idx=s, + query_masks_wp=q_wp, + with_masks_wp=w_wp, + ignore_masks_wp=None, + current_only=False, + out_wp=out_wp, + ) + return wp.to_torch(out_wp).cpu().tolist() + + # ToggledOn-style: query=(1, R) broadcast across with=(2, C); the contacting object (table) is at row 1. + query1 = row_bowl.unsqueeze(0).to(th.uint8) # (1, R) + with2 = th.stack([th.zeros(C, dtype=th.bool), col_table]).to(th.uint8) # (2, C): row0 empty, row1 table + ref1 = RigidContactAPI.is_in_contact_batch( + scene_idx=s, + query_masks=query1.bool().cuda(), + with_masks=with2.bool().cuda(), + ignore_masks=None, + current_only=False, + ) + assert ref1.cpu().tolist() == [False, True] + assert run_warp(query1, with2, 2) == [0, 1], "query-broadcast: object at with-mask row 1 was not evaluated" + + # SlicerActive-style: query=(2, R) vs with=(1, C) broadcast; the contacting query (bowl) is at row 1. + query2 = th.stack([th.zeros(R, dtype=th.bool), row_bowl]).to(th.uint8) # (2, R): row0 empty, row1 bowl + with1 = col_table.unsqueeze(0).to(th.uint8) # (1, C) + ref2 = RigidContactAPI.is_in_contact_batch( + scene_idx=s, + query_masks=query2.bool().cuda(), + with_masks=with1.bool().cuda(), + ignore_masks=None, + current_only=False, + ) + assert ref2.cpu().tolist() == [False, True] + assert run_warp(query2, with1, 2) == [0, 1], "filter-broadcast: query at row 1 was not evaluated" + + +def test_next_to(env, bottom_cabinet, bowl, dishtowel): + place_obj_on_floor_plane(bottom_cabinet) + for i, (axis, obj) in enumerate(zip(("x", "y"), (bowl, dishtowel))): + place_obj_on_floor_plane(obj, **{f"{axis}_offset": 0.3}) + for _ in range(5): + og.sim.step() + + assert obj.states[NextTo].get_value(bottom_cabinet) + assert bottom_cabinet.states[NextTo].get_value(obj) + + obj.set_position_orientation(position=th.ones(3) * 10 * (i + 1)) + og.sim.step() + + assert not obj.states[NextTo].get_value(bottom_cabinet) + assert not bottom_cabinet.states[NextTo].get_value(obj) + + with pytest.raises(NotImplementedError): + bowl.states[NextTo].set_value(bottom_cabinet, None) + + +@pytest.mark.skip(reason="disable cloth tests until #2042") +def test_overlaid(env, breakfast_table, carpet): + place_obj_on_floor_plane(breakfast_table) + place_objA_on_objB_bbox(carpet, breakfast_table) + + for _ in range(5): + og.sim.step() + + assert carpet.states[Overlaid].get_value(breakfast_table) + + carpet.set_position_orientation(position=th.ones(3) * 20.0) + og.sim.step() + + assert not carpet.states[Overlaid].get_value(breakfast_table) + + assert carpet.states[Overlaid].set_value(breakfast_table, True) + + with pytest.raises(NotImplementedError): + carpet.states[Overlaid].set_value(breakfast_table, False) + + +def test_pose(env, breakfast_table, dishtowel): + pos1, orn1 = get_random_pose() + breakfast_table.set_position_orientation(position=pos1, orientation=orn1) + + pos2, orn2 = get_random_pose() + dishtowel.set_position_orientation(position=pos2, orientation=orn2) + + assert th.allclose(breakfast_table.states[Pose].get_value()[0], pos1) + assert th.allclose(breakfast_table.states[Pose].get_value()[1], orn1) or th.allclose( + breakfast_table.states[Pose].get_value()[1], -orn1 + ) + assert th.allclose(dishtowel.states[Pose].get_value()[0], pos2) + assert th.allclose(dishtowel.states[Pose].get_value()[1], orn2) or th.allclose( + dishtowel.states[Pose].get_value()[1], -orn2 + ) + + with pytest.raises(NotImplementedError): + breakfast_table.states[Pose].set_value(None) + + +def test_joint(env, breakfast_table, bottom_cabinet): + lo = bottom_cabinet.joint_lower_limits + hi = bottom_cabinet.joint_upper_limits + q_rand = lo + (hi - lo) * th.rand(bottom_cabinet.n_joints) + bottom_cabinet.set_joint_positions(q_rand) + + assert th.allclose(bottom_cabinet.states[Joint].get_value(), q_rand) + assert len(breakfast_table.states[Joint].get_value()) == 0 + + with pytest.raises(NotImplementedError): + bottom_cabinet.states[Joint].set_value(None) + + +def test_aabb(env, breakfast_table, dishtowel): + pos1, orn1 = get_random_pose() + breakfast_table.set_position_orientation(position=pos1, orientation=orn1) + + pos2, orn2 = get_random_pose() + dishtowel.set_position_orientation(position=pos2, orientation=orn2) + + # Need to take one sim step + og.sim.step() + + assert th.allclose(breakfast_table.states[AABB].get_value()[0], breakfast_table.aabb[0]) + assert th.allclose(breakfast_table.states[AABB].get_value()[1], breakfast_table.aabb[1]) + assert th.all( + (breakfast_table.states[AABB].get_value()[0] < pos1) & (pos1 < breakfast_table.states[AABB].get_value()[1]) + ) + + # skip until #2042 + # pp = dishtowel.root_link.compute_particle_positions() + # offset = dishtowel.root_link.cloth_system.particle_contact_offset + # particle_aabb = (pp.min(dim=0).values - offset, pp.max(dim=0).values + offset) + # assert th.allclose(dishtowel.states[AABB].get_value()[0], particle_aabb[0]) + # assert th.allclose(dishtowel.states[AABB].get_value()[1], particle_aabb[1]) + # assert th.all( + # (dishtowel.states[AABB].get_value()[0] < pos2) & (pos2 < dishtowel.states[AABB].get_value()[1]) + # ).item() + + with pytest.raises(NotImplementedError): + breakfast_table.states[AABB].set_value(None) + + +def test_adjacency(env, bottom_cabinet, bowl, dishtowel): + """Verifies the unified Adjacency state's per-axis behavior on stacked and side-by-side fixtures. + + Axis layout for Adjacency.get_value(other) (shape (22,)): + k=0 : +Z (other above self) + k=1 : -Z (other below self) + k=2..11 : +dir of horizontal axes 0..9 + k=12..21 : -dir of horizontal axes 0..9 + """ + place_obj_on_floor_plane(bottom_cabinet) + place_obj_on_floor_plane(bowl, x_offset=0.4) + place_obj_on_floor_plane(dishtowel, y_offset=0.4) + og.sim.step() + + # Vertical: stack bowl above bottom_cabinet, dishtowel above both + bowl.set_position_orientation(position=[0.0, 0.0, 1.0]) + dishtowel.set_position_orientation(position=[0.0, 0.0, 2.0]) + og.sim.step() + + # Self-pair is always False + self_adj = bottom_cabinet.states[Adjacency].get_value(bottom_cabinet) + assert not bool(self_adj.any()), "diagonal must be all False" + + # bowl above bottom_cabinet: bottom_cabinet's +Z (k=0) cell for bowl is True + bc_to_bowl = bottom_cabinet.states[Adjacency].get_value(bowl) + bowl_to_bc = bowl.states[Adjacency].get_value(bottom_cabinet) + assert bool(bc_to_bowl[0]), "bowl should be above bottom_cabinet (k=0)" + assert bool(bowl_to_bc[1]), "bottom_cabinet should be below bowl (k=1)" + + # dishtowel above both + bc_to_dt = bottom_cabinet.states[Adjacency].get_value(dishtowel) + dt_to_bc = dishtowel.states[Adjacency].get_value(bottom_cabinet) + assert bool(bc_to_dt[0]), "dishtowel should be above bottom_cabinet (k=0)" + assert bool(dt_to_bc[1]), "bottom_cabinet should be below dishtowel (k=1)" + + # Horizontal: place objects side-by-side. The small object's side fires a horizontal axis + # because its AABB center is at the right height to ray onto the larger object's mesh. + place_obj_on_floor_plane(bottom_cabinet) + place_obj_on_floor_plane(bowl, x_offset=0.4) + og.sim.step() + + bowl_to_bc_h = bowl.states[Adjacency].get_value(bottom_cabinet) + assert bool( + bowl_to_bc_h[2:].any() + ), "bowl placed beside bottom_cabinet should fire at least one horizontal axis from bowl's side" + + # _set_value must raise on Adjacency + with pytest.raises(NotImplementedError): + bottom_cabinet.states[Adjacency].set_value(bowl, None) + + +def test_temperature_marks_changed_objects(env, stove, bagel, cookable_dishtowel): + """Regression test: objects whose temperature changes must be individually flagged as + state-updated. + + TensorizedAbsoluteState stores all objects' scalar values in a per-scene tensor, and + post_update() is responsible for calling state_updated() on each object whose value + changed so it stays "active" for that step. A previous implementation collapsed the object + axis when detecting changes, so only the first tracked object (index 0) was ever flagged. + This caused heated-but-asleep objects (e.g. food cooking in a closed oven) to be excluded + from the serialized state during data collection. Here we heat two objects at once and + assert both get flagged, which fails if only a single (index-0) object is marked. + """ + dishtowel = cookable_dishtowel + scene = env.scene + + # Position the stove on the floor plane and place both cookable objects on top of it + place_obj_on_floor_plane(stove, x_offset=1.0) + bagel.set_position_orientation(position=[0.78, -0.2, 0.88], orientation=[0, 0, 0, 1]) + dishtowel.set_position_orientation(position=[0.84, -0.15, 0.89], orientation=[0, 0, 0, 1]) + assert bagel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + assert dishtowel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + + # Turn the stove on and let it start heating both objects + stove.states[ToggledOn].set_value(True) + for _ in range(5): + og.sim.step() + + # Precondition: both objects' temperatures actually changed (so both should be flagged) + assert bagel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + + # The set of objects flagged on the most recent step must include every changed object, + # not just the first one tracked by the Temperature state. + assert bagel in scene.updated_state_objects + assert dishtowel in scene.updated_state_objects + + +def test_temperature(env, microwave, stove, fridge, plywood, bagel, cookable_dishtowel): + dishtowel = cookable_dishtowel + + # Not affected by any heat source + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + place_obj_on_floor_plane(microwave) + place_obj_on_floor_plane(stove, x_offset=1.0) + place_obj_on_floor_plane(fridge, x_offset=2.0) + place_obj_on_floor_plane(plywood, x_offset=3.0) + + # Set the objects to be far away + place_obj_on_floor_plane(bagel, x_offset=-0.5) + place_obj_on_floor_plane(dishtowel, x_offset=-1.0) + + # Not affected by any heat source + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + for _ in range(5): + og.sim.step() + + # Not affected by any heat source + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + # Open the microwave + microwave.joints["j_link_0"].set_pos(math.pi / 2) + + # Set the objects to be inside the microwave + bagel.set_position_orientation(position=[0, 0.03, 0.11], orientation=[0, 0, 0, 1]) + dishtowel.set_position_orientation(position=[0.0, -0.12, 0.11], orientation=[0, 0, 0, 1]) + + for _ in range(5): + og.sim.step() + + # Not affected by any heat source (the microwave is NOT toggled on) + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + # The microwave should not turn on when the door is open + assert not microwave.states[ToggledOn].set_value(True) + + for _ in range(5): + og.sim.step() + + # Not affected by any heat source (the microwave is open) + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + microwave.joints["j_link_0"].set_pos(0.0) + og.sim.step() + assert microwave.states[ToggledOn].set_value(True) + + for _ in range(5): + og.sim.step() + + # Affected by the microwave + bagel_new_temp = bagel.states[Temperature].get_value() + dishtowel_new_temp = dishtowel.states[Temperature].get_value() + assert bagel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + + # Set the objects to be far away + place_obj_on_floor_plane(bagel, x_offset=-0.5) + place_obj_on_floor_plane(dishtowel, x_offset=-1.0) + for _ in range(5): + og.sim.step() + + # Not affected by any heat source (should cool down by itself towards the default temp) + assert bagel.states[Temperature].get_value() < bagel_new_temp + assert dishtowel.states[Temperature].get_value() < dishtowel_new_temp + + # Setter should work + assert bagel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + assert dishtowel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + # Set the objects to be on top of the stove + bagel.set_position_orientation(position=[0.78, -0.2, 0.88], orientation=[0, 0, 0, 1]) + dishtowel.set_position_orientation(position=[0.84, -0.15, 0.89], orientation=[0, 0, 0, 1]) + + for _ in range(5): + og.sim.step() + + # Not affected by any heat source (the stove is off) + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + stove.states[ToggledOn].set_value(True) + + for _ in range(5): + og.sim.step() + + # Affected by the stove + assert bagel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + + # Reset + assert bagel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + assert dishtowel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + + # Set the objects to be inside the fridge + bagel.set_position_orientation(position=[1.9, 0, 0.7], orientation=[0, 0, 0, 1]) + dishtowel.set_position_orientation(position=[2.1, 0, 0.7], orientation=[0, 0, 0, 1]) + + assert fridge.states[Open].set_value(False, fully=True) + + for _ in range(5): + og.sim.step() + + # Affected by the fridge + assert bagel.states[Temperature].get_value() < m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() < m.object_states.temperature.DEFAULT_TEMPERATURE + + # Reset temp + assert bagel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + assert dishtowel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE) + + # Set the objects to be near the plywood + place_obj_on_floor_plane(bagel, x_offset=2.9) + place_obj_on_floor_plane(dishtowel, x_offset=3.1) + + for _ in range(5): + og.sim.step() + + # Not affected by any heat source (the plywood is NOT onfire) + assert bagel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + plywood.states[OnFire].set_value(True) + + for _ in range(5): + og.sim.step() + + assert bagel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[Temperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + + +def test_max_temperature(env, bagel, cookable_dishtowel): + dishtowel = env.scene.object_registry("name", "cookable_dishtowel") + + assert bagel.states[MaxTemperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[MaxTemperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE + + assert bagel.states[MaxTemperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE - 1) + assert dishtowel.states[MaxTemperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE - 1) + assert bagel.states[MaxTemperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE - 1 + assert dishtowel.states[MaxTemperature].get_value() == m.object_states.temperature.DEFAULT_TEMPERATURE - 1 + + bagel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE + 1) + dishtowel.states[Temperature].set_value(m.object_states.temperature.DEFAULT_TEMPERATURE + 1) + + og.sim.step() + + assert bagel.states[MaxTemperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + assert dishtowel.states[MaxTemperature].get_value() > m.object_states.temperature.DEFAULT_TEMPERATURE + + +def test_heat_source_or_sink(env, microwave, stove, fridge): + assert microwave.states[HeatSourceOrSink].requires_inside + assert microwave.states[HeatSourceOrSink].requires_closed + assert microwave.states[HeatSourceOrSink].requires_toggled_on + + microwave.joints["j_link_0"].set_pos(math.pi / 2) + microwave.states[ToggledOn].set_value(False) + + og.sim.step() + assert not microwave.states[HeatSourceOrSink].get_value() + + microwave.joints["j_link_0"].set_pos(0.0) + og.sim.step() + assert not microwave.states[HeatSourceOrSink].get_value() + + microwave.states[ToggledOn].set_value(True) + og.sim.step() + assert microwave.states[HeatSourceOrSink].get_value() + + assert fridge.states[HeatSourceOrSink].requires_inside + assert fridge.states[HeatSourceOrSink].requires_closed + assert not fridge.states[HeatSourceOrSink].requires_toggled_on + + fridge.joints["j_link_0"].set_pos(math.pi / 2) + + og.sim.step() + assert not fridge.states[HeatSourceOrSink].get_value() + + fridge.joints["j_link_0"].set_pos(0.0) + og.sim.step() + assert fridge.states[HeatSourceOrSink].get_value() + + assert not stove.states[HeatSourceOrSink].requires_inside + assert not stove.states[HeatSourceOrSink].requires_closed + assert stove.states[HeatSourceOrSink].requires_toggled_on + + stove.states[ToggledOn].set_value(False) + + og.sim.step() + assert not stove.states[HeatSourceOrSink].get_value() + + stove.states[ToggledOn].set_value(True) + og.sim.step() + assert stove.states[HeatSourceOrSink].get_value() + + +def test_cooked(env, bagel, cookable_dishtowel): + dishtowel = env.scene.object_registry("name", "cookable_dishtowel") + + assert not bagel.states[Cooked].get_value() + assert not dishtowel.states[Cooked].get_value() + + bagel.states[MaxTemperature].set_value(bagel.states[Cooked].cook_temperature) + dishtowel.states[MaxTemperature].set_value(dishtowel.states[Cooked].cook_temperature) + og.sim.step() + assert bagel.states[Cooked].get_value() + assert dishtowel.states[Cooked].get_value() + + assert bagel.states[Cooked].set_value(False) + assert dishtowel.states[Cooked].set_value(False) + assert not bagel.states[Cooked].get_value() + assert not dishtowel.states[Cooked].get_value() + assert bagel.states[MaxTemperature].get_value() < bagel.states[Cooked].cook_temperature + assert dishtowel.states[MaxTemperature].get_value() < dishtowel.states[Cooked].cook_temperature + + assert bagel.states[Cooked].set_value(True) + assert dishtowel.states[Cooked].set_value(True) + assert bagel.states[Cooked].get_value() + assert dishtowel.states[Cooked].get_value() + assert bagel.states[MaxTemperature].get_value() >= bagel.states[Cooked].cook_temperature + assert dishtowel.states[MaxTemperature].get_value() >= dishtowel.states[Cooked].cook_temperature + + +def test_burnt(env, bagel, cookable_dishtowel): + dishtowel = env.scene.object_registry("name", "cookable_dishtowel") + + assert not bagel.states[Burnt].get_value() + assert not dishtowel.states[Burnt].get_value() + + bagel.states[MaxTemperature].set_value(bagel.states[Burnt].burn_temperature) + dishtowel.states[MaxTemperature].set_value(dishtowel.states[Burnt].burn_temperature) + og.sim.step() + assert bagel.states[Burnt].get_value() + assert dishtowel.states[Burnt].get_value() + + assert bagel.states[Burnt].set_value(False) + assert dishtowel.states[Burnt].set_value(False) + assert not bagel.states[Burnt].get_value() + assert not dishtowel.states[Burnt].get_value() + assert bagel.states[MaxTemperature].get_value() < bagel.states[Burnt].burn_temperature + assert dishtowel.states[MaxTemperature].get_value() < dishtowel.states[Burnt].burn_temperature + + assert bagel.states[Burnt].set_value(True) + assert dishtowel.states[Burnt].set_value(True) + assert bagel.states[Burnt].get_value() + assert dishtowel.states[Burnt].get_value() + assert bagel.states[MaxTemperature].get_value() >= bagel.states[Burnt].burn_temperature + assert dishtowel.states[MaxTemperature].get_value() >= dishtowel.states[Burnt].burn_temperature + + +def test_frozen(env, bagel, cookable_dishtowel): + dishtowel = env.scene.object_registry("name", "cookable_dishtowel") + + assert not bagel.states[Frozen].get_value() + assert not dishtowel.states[Frozen].get_value() + + bagel.states[Temperature].set_value(bagel.states[Frozen].freeze_temperature - 1) + dishtowel.states[Temperature].set_value(dishtowel.states[Frozen].freeze_temperature - 1) + og.sim.step() + assert bagel.states[Frozen].get_value() + assert dishtowel.states[Frozen].get_value() + + assert bagel.states[Frozen].set_value(False) + assert dishtowel.states[Frozen].set_value(False) + assert not bagel.states[Frozen].get_value() + assert not dishtowel.states[Frozen].get_value() + assert bagel.states[Temperature].get_value() > bagel.states[Frozen].freeze_temperature + assert dishtowel.states[Temperature].get_value() > dishtowel.states[Frozen].freeze_temperature + + assert bagel.states[Frozen].set_value(True) + assert dishtowel.states[Frozen].set_value(True) + assert bagel.states[Frozen].get_value() + assert dishtowel.states[Frozen].get_value() + assert bagel.states[Temperature].get_value() <= bagel.states[Frozen].freeze_temperature + assert dishtowel.states[Temperature].get_value() <= dishtowel.states[Frozen].freeze_temperature + + +def test_heated(env, bagel, cookable_dishtowel): + dishtowel = env.scene.object_registry("name", "cookable_dishtowel") + + assert not bagel.states[Heated].get_value() + assert not dishtowel.states[Heated].get_value() + + bagel.states[Temperature].set_value(bagel.states[Heated].heat_temperature + 1) + dishtowel.states[Temperature].set_value(dishtowel.states[Heated].heat_temperature + 1) + og.sim.step() + assert bagel.states[Heated].get_value() + assert dishtowel.states[Heated].get_value() + + assert bagel.states[Heated].set_value(False) + assert dishtowel.states[Heated].set_value(False) + assert not bagel.states[Heated].get_value() + assert not dishtowel.states[Heated].get_value() + assert bagel.states[Temperature].get_value() < bagel.states[Heated].heat_temperature + assert dishtowel.states[Temperature].get_value() < dishtowel.states[Heated].heat_temperature + + assert bagel.states[Heated].set_value(True) + assert dishtowel.states[Heated].set_value(True) + assert bagel.states[Heated].get_value() + assert dishtowel.states[Heated].get_value() + assert bagel.states[Temperature].get_value() >= bagel.states[Heated].heat_temperature + assert dishtowel.states[Temperature].get_value() >= dishtowel.states[Heated].heat_temperature + + +def test_on_fire(env, plywood): + assert plywood.states[OnFire].temperature == m.object_states.heat_source_or_sink.DEFAULT_FIRE_TEMPERATURE + assert not plywood.states[OnFire].get_value() + + plywood.states[Temperature].set_value(plywood.states[OnFire].ignition_temperature + 1) + + og.sim.step() + assert plywood.states[OnFire].get_value() + + assert plywood.states[OnFire].set_value(False) + assert not plywood.states[OnFire].get_value() + assert plywood.states[Temperature].get_value() < plywood.states[OnFire].ignition_temperature + + assert plywood.states[OnFire].set_value(True) + assert plywood.states[OnFire].get_value() + assert plywood.states[Temperature].get_value() == plywood.states[OnFire].temperature + + for _ in range(5): + og.sim.step() + + assert plywood.states[Temperature].get_value() == plywood.states[OnFire].temperature + + +def test_toggled_on(env, stove, robot): + stove.set_position_orientation([1.487, 0.3, 0.443], T.euler2quat(th.tensor([0, 0, math.pi], dtype=th.float32))) + robot.set_position_orientation(position=[0.0, 0.38, 0.0], orientation=[0, 0, 0, 1]) + + assert not stove.states[ToggledOn].get_value() + + # Make the toggle button huge to add tolerance + stove.states[ToggledOn].link.scale = 3.0 + + q = robot.get_joint_positions() + jnt_idxs = {name: i for i, name in enumerate(robot.joints.keys())} + q[jnt_idxs["torso_lift_joint"]] = 0.0 + q[jnt_idxs["shoulder_pan_joint"]] = th.deg2rad(th.tensor([90.0])).item() + q[jnt_idxs["shoulder_lift_joint"]] = th.deg2rad(th.tensor([9.0])).item() + q[jnt_idxs["upperarm_roll_joint"]] = 0.0 + q[jnt_idxs["elbow_flex_joint"]] = 0.0 + q[jnt_idxs["forearm_roll_joint"]] = 0.0 + q[jnt_idxs["wrist_flex_joint"]] = 0.0 + q[jnt_idxs["wrist_roll_joint"]] = 0.0 + q[jnt_idxs["l_gripper_finger_joint"]] = 0.0 + q[jnt_idxs["r_gripper_finger_joint"]] = 0.0 + robot.set_joint_positions(q, drive=False) + + steps = math.ceil(m.object_states.toggle.CAN_TOGGLE_SECONDS / og.sim.get_sim_step_dt()) + for _ in range(steps): + og.sim.step() + + # End-effector not close to the button, stays False + assert not stove.states[ToggledOn].get_value() + + # Settle robot + for _ in range(10): + og.sim.step() + + q[jnt_idxs["shoulder_pan_joint"]] = 0.0 + robot.set_joint_positions(q, drive=False) + + for _ in range(steps - 1): + og.sim.step() + robot.set_joint_positions(q, drive=False) + robot.keep_still() + + # End-effector close to the button, but not enough time has passed, still False + assert not stove.states[ToggledOn].get_value() + + robot.set_joint_positions(q, drive=False) + robot.keep_still() + og.sim.step() + + # Enough time has passed, turns True + assert stove.states[ToggledOn].get_value() + + # Setter should work + assert stove.states[ToggledOn].set_value(False) + assert not stove.states[ToggledOn].get_value() + + +def test_toggled_on_requires_closed(env, microwave): + """ + Test when an object's ToggledOn has requires_closed=True and + its Open state is True, both: + (a) `_set_value` should refuse to flip on, and + (b) the `_check_requires_closed_kernel` should force VALUES=0 and steps=0 + even if those were poked True/non-zero outside the kernel. + """ + microwave = env.scene.object_registry("name", "microwave") + if not microwave.states[ToggledOn].requires_closed: + pytest.skip("Microwave asset does not have requires_closed=True; nothing to test.") + + # Open the microwave door. + microwave.states[Open].set_value(True) + for _ in range(3): + og.sim.step() + assert microwave.states[Open].get_value(), "Failed to open microwave door" + + # (a) Python short-circuit: set_value(True) returns False, value stays False. + assert not microwave.states[ToggledOn].set_value(True) + assert not microwave.states[ToggledOn].get_value() + + # (b) Kernel knockdown: bypass set_value, force VALUES and the seconds counter directly, + # then step the sim once. The requires_closed kernel should zero both because Open is True. + s = microwave.scene.idx + obj_idx = ToggledOn.OBJ_IDXS[microwave.relative_prim_path] + ToggledOn.VALUES[s, obj_idx] = 1 + # _robots_can_toggle_time is a wp.array — wp.to_torch gives a zero-copy view we can poke. + wp.to_torch(ToggledOn._robots_can_toggle_time)[s, obj_idx] = 100.0 + og.sim.step() + assert not microwave.states[ + ToggledOn + ].get_value(), "requires_closed kernel should knock VALUES back to 0 while Open is True" + assert ( + wp.to_torch(ToggledOn._robots_can_toggle_time)[s, obj_idx].item() == 0.0 + ), "requires_closed kernel should reset the seconds counter to 0" + + # Close the door — set_value should now succeed. + microwave.states[Open].set_value(False) + for _ in range(3): + og.sim.step() + assert not microwave.states[Open].get_value() + assert microwave.states[ToggledOn].set_value(True) + assert microwave.states[ToggledOn].get_value() + + +def test_zero_dt_refresh_does_not_advance_time_dependent_states(env, microwave, table_knife): + """ + Time-dependent tensorized states are driven by Δt computed from og.sim.current_time. When + _refresh_state_caches() is called without any physics elapsing between the previous + update and this one, Δt is 0 and any pure-dt accumulation is a no-op. + + Load-bearing case: lazy reads triggered between real sim steps (e.g. get_value() called + during sample_kinematics() / settling) must not artificially tick task-relevant timers. + + We assert this only for Temperature and for the slicer in its default active state — + those are the cases where the kernel's behavior reduces to "multiply by Δt". The toggle + kernel (and the slicer's cooldown branch) also resets the counter unconditionally when + eligibility/contact breaks; that reset path is correct and runs regardless of Δt, so it + isn't meaningful to assert "counter frozen" without engineering real contact. + """ + microwave = env.scene.object_registry("name", "microwave") + table_knife = env.scene.object_registry("name", "table_knife") + + # One real step so all tensorized state views are fully initialized. + og.sim.step() + + s_mw = microwave.scene.idx + temp_idx = Temperature.OBJ_IDXS[microwave.relative_prim_path] + s_knife = table_knife.scene.idx + slicer_idx = SlicerActive.OBJ_IDXS[table_knife.relative_prim_path] + + # Seed non-default values so any spurious tick would be visible. + Temperature.VALUES[s_mw, temp_idx] = 100.0 + # Slicer starts active by default; in the active branch the kernel leaves DELAY_COUNTER alone, + # so seeding it lets us verify the kernel truly takes the no-op path under Δt=0. + wp.to_torch(SlicerActive.DELAY_COUNTER)[s_knife, slicer_idx] = 7.0 + + snap_temp = Temperature.VALUES[s_mw, temp_idx].clone() + snap_slicer = wp.to_torch(SlicerActive.DELAY_COUNTER)[s_knife, slicer_idx].clone() + + # Five back-to-back refreshes with no physics in between — Δt = 0 each time. + for _ in range(5): + og.sim._refresh_state_caches() + + assert th.equal(Temperature.VALUES[s_mw, temp_idx], snap_temp), ( + f"Temperature drifted on Δt=0 refresh: " f"{snap_temp.item()} -> {Temperature.VALUES[s_mw, temp_idx].item()}" + ) + slicer_after = wp.to_torch(SlicerActive.DELAY_COUNTER)[s_knife, slicer_idx] + assert th.equal( + slicer_after, snap_slicer + ), f"SlicerActive counter drifted on Δt=0 refresh: {snap_slicer.item()} -> {slicer_after.item()}" + + # A real og.sim.step() advances time by sim_step_dt — Temperature should decay. + og.sim.step() + assert ( + Temperature.VALUES[s_mw, temp_idx].item() < 100.0 + ), "Temperature should decay toward DEFAULT_TEMPERATURE after a real step" + + +def test_particle_source(env, furniture_sink): + sink = env.scene.object_registry("name", "furniture_sink") + + place_obj_on_floor_plane(sink) + for _ in range(3): + og.sim.step() + + assert not sink.states[ToggledOn].get_value() + water_system = env.scene.get_system("water") + # Sink is toggled off, no water should be present + assert water_system.n_particles == 0 + + sink.states[ToggledOn].set_value(True) + + for _ in range(sink.states[ParticleSource].n_steps_per_modification): + og.sim.step() + + # Sink is toggled on, some water should be present + assert water_system.n_particles > 0 + + # Cannot set this state + with pytest.raises(NotImplementedError): + sink.states[ParticleSource].set_value(True) + + water_system.remove_all_particles() + + +def test_particle_sink(env, furniture_sink): + sink = env.scene.object_registry("name", "furniture_sink") + place_obj_on_floor_plane(sink) + for _ in range(3): + og.sim.step() + + water_system = env.scene.get_system("water") + # There should be no water particles. + assert water_system.n_particles == 0 + + sink_pos = sink.states[ParticleSink].link.get_position_orientation()[0] + water_system.generate_particles(positions=[(sink_pos + th.tensor([0, 0, 0.05])).tolist()]) + # There should be exactly 1 water particle. + assert water_system.n_particles == 1 + + for _ in range(sink.states[ParticleSink].n_steps_per_modification): + og.sim.step() + + # There should be no water particles because the fluid source absorbs them. + assert water_system.n_particles == 0 + + # Cannot set this state + with pytest.raises(NotImplementedError): + sink.states[ParticleSink].set_value(True) + + water_system.remove_all_particles() + + +@pytest.mark.skip(reason="investigate why particle applier and remover tests are failing, see issue #2066") +def test_particle_applier(env, breakfast_table, acetone_atomizer, applier_dishtowel): + # Test projection + + place_obj_on_floor_plane(breakfast_table) + place_objA_on_objB_bbox(acetone_atomizer, breakfast_table, z_offset=0.1) + acetone_atomizer.set_orientation(th.tensor([0.707, 0, 0, 0.707])) + for _ in range(3): + og.sim.step() + + assert not acetone_atomizer.states[ToggledOn].get_value() + water_system = env.scene.get_system("water") + # Spray bottle is toggled off, no water should be present + assert water_system.n_particles == 0 + + # Take number of steps for water to be generated, make sure there is still no water + n_applier_steps = acetone_atomizer.states[ParticleApplier].n_steps_per_modification + for _ in range(n_applier_steps): + og.sim.step() + + assert water_system.n_particles == 0 + + # Turn particle applier on, and verify particles are generated after the same number of steps are taken + acetone_atomizer.states[ToggledOn].set_value(True) + + for _ in range(n_applier_steps): + og.sim.step() + + # Some water should be present + assert water_system.n_particles > 0 + + # Test adjacency + + water_system.remove_all_particles() + acetone_atomizer.set_position_orientation(position=th.ones(3) * 50.0, orientation=th.tensor([0, 0, 0, 1.0])) + + place_objA_on_objB_bbox(applier_dishtowel, breakfast_table) + og.sim.step() + + # no water should be present + assert water_system.n_particles == 0 + + # Take number of steps for water to be generated + n_applier_steps = applier_dishtowel.states[ParticleApplier].n_steps_per_modification + for _ in range(n_applier_steps): + og.sim.step() + + # Some water should be present + assert water_system.n_particles > 0 + + # Cannot set this state + with pytest.raises(NotImplementedError): + acetone_atomizer.states[ParticleApplier].set_value(True) + + water_system.remove_all_particles() + + +@pytest.mark.skip(reason="investigate why particle applier and remover tests are failing, see issue #2066") +def test_particle_remover(env, breakfast_table, vacuum, remover_dishtowel): + # Test projection + + place_obj_on_floor_plane(breakfast_table) + place_objA_on_objB_bbox(vacuum, breakfast_table, z_offset=0.02) + for _ in range(3): + og.sim.step() + + assert not vacuum.states[ToggledOn].get_value() + water_system = env.scene.get_system("water") + # Place single particle of water on middle of table + water_system.generate_particles( + positions=[[0, 0, breakfast_table.aabb[1][2].item() + water_system.particle_radius]] + ) + assert water_system.n_particles > 0 + + # Take number of steps for water to be removed, make sure there is still water + n_remover_steps = vacuum.states[ParticleRemover].n_steps_per_modification + for _ in range(n_remover_steps): + og.sim.step() + + assert water_system.n_particles > 0 + + # Turn particle remover on, and verify particles are generated after the same number of steps are taken + vacuum.states[ToggledOn].set_value(True) + + for _ in range(n_remover_steps): + og.sim.step() + + # No water should be present + assert water_system.n_particles == 0 + + # Test adjacency + + vacuum.set_position_orientation(position=th.ones(3) * 50.0) + place_objA_on_objB_bbox(remover_dishtowel, breakfast_table, z_offset=0.03) + og.sim.step() + # Place single particle of water on middle of table + water_system.generate_particles( + positions=[[0, 0, breakfast_table.aabb[1][2].item() + water_system.particle_radius]] + ) + + # Water should be present + assert water_system.n_particles > 0 + + # Take number of steps for water to be removed + n_remover_steps = remover_dishtowel.states[ParticleRemover].n_steps_per_modification + for _ in range(n_remover_steps): + og.sim.step() + + # No water should be present + assert water_system.n_particles == 0 + + # Cannot set this state + with pytest.raises(NotImplementedError): + vacuum.states[ParticleRemover].set_value(True) + + water_system.remove_all_particles() + + +def test_saturated(env, remover_dishtowel): + place_obj_on_floor_plane(remover_dishtowel) + + for _ in range(5): + og.sim.step() + + water_system = env.scene.get_system("water") + + # Place single row of water above dishtowel + n_particles = 5 + remover_dishtowel.states[Saturated].set_limit(water_system, n_particles) + water_system.generate_particles( + positions=[ + [0, 0, remover_dishtowel.aabb[1][2].item() + water_system.particle_radius * (1 + 2 * i)] + for i in range(n_particles) + ], + ) + + # Take a few steps + for _ in range(20): + og.sim.step() + + # Make sure Saturated is True, and no particles exist + assert water_system.n_particles == 0 + assert remover_dishtowel.states[Saturated].get_value(water_system) + + # Make sure we can toggle saturated to be true and false + assert remover_dishtowel.states[Saturated].set_value(water_system, False) + assert remover_dishtowel.states[Saturated].set_value(water_system, True) + + water_system.remove_all_particles() + + +def test_open(env, microwave, bottom_cabinet): + # By default, objects should not be open. + assert not microwave.states[Open].get_value() + assert not bottom_cabinet.states[Open].get_value() + + # Set the joints to their upper limits. + microwave.joints["j_link_0"].set_pos(microwave.joints["j_link_0"].upper_limit) + bottom_cabinet.joints["j_link_2"].set_pos(bottom_cabinet.joints["j_link_2"].upper_limit) + + og.sim.step() + + # The objects should be open. + assert microwave.states[Open].get_value() + assert bottom_cabinet.states[Open].get_value() + + # Set the joints to their lower limits. + microwave.joints["j_link_0"].set_pos(microwave.joints["j_link_0"].lower_limit) + bottom_cabinet.joints["j_link_2"].set_pos(bottom_cabinet.joints["j_link_2"].lower_limit) + + og.sim.step() + + # The objects should not be open. + assert not microwave.states[Open].get_value() + assert not bottom_cabinet.states[Open].get_value() + + # Setters should work. + assert microwave.states[Open].set_value(True) + assert bottom_cabinet.states[Open].set_value(True) + + # The objects should be open. + assert microwave.states[Open].get_value() + assert bottom_cabinet.states[Open].get_value() + + # Setters should work. + assert microwave.states[Open].set_value(False) + assert bottom_cabinet.states[Open].set_value(False) + + # The objects should not be open. + assert not microwave.states[Open].get_value() + assert not bottom_cabinet.states[Open].get_value() + + +@pytest.mark.skip(reason="disable cloth tests until #2042") +def test_folded_unfolded(env, carpet): + place_obj_on_floor_plane(carpet) + + for _ in range(10): + og.sim.step() + + carpet.reset() + carpet.keep_still() + + for _ in range(10): + og.sim.step() + + assert not carpet.states[Folded].get_value() + assert carpet.states[Unfolded].get_value() + + pos = carpet.root_link.compute_particle_positions() + y_min, y_max = th.min(pos, dim=0).values[1], th.max(pos, dim=0).values[1] + y_extent = y_max - y_min + # Get indices for the bottom 10 percent vertices in the y-axis + indices = th.argsort(pos, dim=0)[:, 1][: (pos.shape[0] // 10)] + start = th.clone(pos[indices]) + + # lift up a bit + mid = th.clone(start) + mid[:, 2] += y_extent * 0.2 + + # move towards y_max + end = th.clone(mid) + end[:, 1] += y_extent * 0.9 + + increments = 25 + total_points = increments * 2 + + # Create interpolation weights + t = th.linspace(0, 1, total_points).unsqueeze(1).unsqueeze(2) + + # Interpolate between start, mid, and end + first_half = t < 0.5 + ctrl_pts = th.where(first_half, start * (1 - 2 * t) + mid * (2 * t), mid * (2 - 2 * t) + end * (2 * t - 1)) + + for pt in ctrl_pts: + carpet.root_link.set_particle_positions(pt, idxs=indices) + og.sim.step() + + assert carpet.states[Folded].get_value() + assert not carpet.states[Unfolded].get_value() + assert carpet.states[Unfolded].set_value(True) + + with pytest.raises(NotImplementedError): + carpet.states[Unfolded].set_value(False) + + with pytest.raises(NotImplementedError): + carpet.states[Folded].set_value(True) + + +@pytest.mark.skip(reason="disable cloth tests until #2042") +def test_draped(env, breakfast_table, carpet): + place_obj_on_floor_plane(breakfast_table) + place_objA_on_objB_bbox(carpet, breakfast_table) + + for _ in range(10): + og.sim.step() + + assert carpet.states[Draped].get_value(breakfast_table) + + carpet.set_position_orientation(position=[20.0, 20.0, 1.0]) + + for _ in range(5): + og.sim.step() + + assert not carpet.states[Draped].get_value(breakfast_table) + + assert carpet.states[Draped].set_value(breakfast_table, True) + + with pytest.raises(NotImplementedError): + carpet.states[Draped].set_value(breakfast_table, False) + + +def test_filled(env, stockpot): + systems = [ + env.scene.get_system(system_name) + for system_name, system_class in SYSTEM_EXAMPLES.items() + if not issubclass(system_class, VisualParticleSystem) + ] + for system in systems: + stockpot.set_position_orientation(position=th.ones(3) * 50.0, orientation=[0, 0, 0, 1.0]) + place_obj_on_floor_plane(stockpot) + for _ in range(5): + og.sim.step() + + assert stockpot.states[Filled].set_value(system, True) + og.sim.step() + assert stockpot.states[Filled].get_value(system) + + # Cannot set Filled state False + with pytest.raises(NotImplementedError): + stockpot.states[Filled].set_value(system, False) + + system.remove_all_particles() + og.sim.step() + assert not stockpot.states[Filled].get_value(system) + + +def test_contains(env, stockpot): + systems = [env.scene.get_system(system_name) for system_name, system_class in SYSTEM_EXAMPLES.items()] + for system in systems: + print(f"Testing Contains {stockpot.name} with {system.name}") + stockpot.set_position_orientation(position=th.ones(3) * 50.0, orientation=[0, 0, 0, 1.0]) + place_obj_on_floor_plane(stockpot) + for _ in range(5): + og.sim.step() + + # Sample single particle + if env.scene.is_physical_particle_system(system_name=system.name): + system.generate_particles(positions=[[0, 0, stockpot.aabb[1][2].item() - 0.1]]) + else: + if system.get_group_name(stockpot) not in system.groups: + system.create_attachment_group(stockpot) + system.generate_group_particles( + group=system.get_group_name(stockpot), + positions=[th.tensor([0, 0, stockpot.aabb[1][2] - 0.1])], + link_prim_paths=[stockpot.root_link.prim_path], + ) + + og.sim.step() + assert stockpot.states[Contains].get_value(system) + + # Remove all particles and make sure contains returns False + stockpot.states[Contains].set_value(system, False) + og.sim.step() + assert not stockpot.states[Contains].get_value(system) + + # Cannot set Contains state + with pytest.raises(NotImplementedError): + stockpot.states[Contains].set_value(system, True) + + system.remove_all_particles() + + +def test_covered(env, bracelet, bowl, microwave): + systems = [env.scene.get_system(system_name) for system_name, system_class in SYSTEM_EXAMPLES.items()] + for obj in (bracelet, bowl, microwave): + for system in systems: + # bracelet is too small to sample physical particles on it + sampleable = env.scene.is_visual_particle_system(system.name) or obj != bracelet + if sampleable: + print(f"Testing Covered {obj.name} with {system.name}") + obj.set_position_orientation(position=th.ones(3) * 50.0, orientation=[0, 0, 0, 1.0]) + place_obj_on_floor_plane(obj) + for _ in range(5): + og.sim.step() + + assert obj.states[Covered].set_value(system, True) + og.sim.step() + assert obj.states[Covered].get_value(system) + + assert obj.states[Covered].set_value(system, False) + # We don't call og.sim.step() here because it's possible for the "second" layer of particles to fall down + # and make Covered to be True again. Instead, we clear the caches and check that Covered is False. + obj.states[Covered].clear_cache() + obj.states[ContactParticles].clear_cache() + assert not obj.states[Covered].get_value(system) + + system.remove_all_particles() + + obj.set_position_orientation(position=th.ones(3) * 75.0, orientation=[0, 0, 0, 1.0]) + + +def test_kinematic_only_contact_no_error(): + """ + A scene containing only kinematic/fixed-base rigid objects (no dynamic + bodies) must not crash during RigidContactAPI.initialize_view(), and contact queries must + return False rather than raise an exception. + """ + test_clear_sim() + + cfg = { + "scene": {"type": "Scene"}, + "objects": [ + { + "type": "DatasetObject", + "name": "table", + "category": "breakfast_table", + "model": "skczfi", + "kinematic_only": True, + "fixed_base": True, + "position": [0, 0, 0.5], + }, + { + "type": "DatasetObject", + "name": "bowl", + "category": "bowl", + "model": "ajzltc", + "kinematic_only": True, + "fixed_base": True, + "position": [0, 0, 1.0], + }, + ], + } + env = og.Environment(configs=cfg) + + # og.sim.step() internally calls RigidContactAPI.initialize_view(); must not raise. + og.sim.step() + + # Explicit call must also not raise. + RigidContactAPI.initialize_view() + + scene_idx = env.scene.idx + table = env.scene.object_registry("name", "table") + bowl = env.scene.object_registry("name", "bowl") + + # Contact queries against a kinematic-only scene must return False, not error. + assert not RigidContactAPI.is_in_contact( + scene_idx=scene_idx, query_set=[table], with_set=[bowl], ignore_set=None, current_only=False + ) + assert not RigidContactAPI.is_in_contact( + scene_idx=scene_idx, query_set=[table], with_set=[bowl], ignore_set=None, current_only=True + ) + assert not RigidContactAPI.is_in_contact( + scene_idx=scene_idx, query_set=[bowl], with_set=[table], ignore_set=None, current_only=False + ) + assert not RigidContactAPI.is_in_contact( + scene_idx=scene_idx, query_set=[bowl], with_set=[table], ignore_set=None, current_only=True + ) + + test_clear_sim() + + +def test_clear_sim(): + if og.sim is not None: + og.clear() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_of_example_template.txt b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_of_example_template.txt new file mode 100644 index 0000000000000000000000000000000000000000..10bd2f8178bc685b6baccdf25a2ae2987dbf0072 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_of_example_template.txt @@ -0,0 +1,4 @@ +import omnigibson.examples.$module as example_module + +def test_$name(): + example_module.main(random_selection=True, headless=True, short_exec=True) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_primitives.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..f2d461bbef09148b4b8f4985469d8a97a36676da --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_primitives.py @@ -0,0 +1,194 @@ +import os +import random + +import numpy as np +import torch as th +import yaml +from pytest_rerunfailures import pytest + +import omnigibson as og +from omnigibson.action_primitives.starter_semantic_action_primitives import ( + StarterSemanticActionPrimitives, + StarterSemanticActionPrimitiveSet, +) +from omnigibson.macros import gm +from omnigibson.objects.dataset_object import DatasetObject + +# Make sure that Omniverse is launched before setting up the tests. +og.launch() + + +def load_robot_config(robot_name): + config_filename = os.path.join(og.example_config_path, f"{robot_name.lower()}_primitives.yaml") + with open(config_filename, "r") as file: + full_config = yaml.safe_load(file) + return full_config.get("robots", {})[0] + + +def setup_environment(load_object_categories, robot="R1"): + if robot not in ["R1", "Tiago"]: + raise ValueError("Invalid robot configuration") + + robots = load_robot_config(robot) + + cfg = { + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": load_object_categories, + }, + "robots": [robots], + } + + seed = 40 + random.seed(seed) + np.random.seed(seed) + th.manual_seed(seed) + th.cuda.manual_seed(seed) + th.backends.cudnn.benchmark = False + th.backends.cudnn.deterministic = True + + if og.sim is None: + # Make sure GPU dynamics are enabled (GPU dynamics needed for cloth) + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = False + gm.ENABLE_TRANSITION_RULES = False + else: + # Make sure sim is stopped + og.sim.stop() + + # Create the environment + env = og.Environment(configs=cfg) + env.reset() + return env + + +def execute_controller(ctrl_gen, env): + for action in ctrl_gen: + env.step(action) + + +def primitive_tester(env, objects, primitives, primitives_args): + for obj in objects: + env.scene.add_object(obj["object"]) + obj["object"].set_position_orientation(position=obj["position"], orientation=obj["orientation"]) + og.sim.step() + + # Let the objects settle + for _ in range(30): + og.sim.step() + + controller = StarterSemanticActionPrimitives( + env, env.scene.robots[0], enable_head_tracking=False, curobo_batch_size=1 + ) + try: + for primitive, args in zip(primitives, primitives_args): + execute_controller(controller.apply_ref(primitive, *args, attempts=1), env) + finally: + # Clear the sim + og.clear() + + +ROBOTS_UNDER_TEST = ["Tiago", "R1"] +if th.cuda.is_available() and th.cuda.get_device_capability(0) == (12, 0): + # TODO: Currently for 50 series, only Default embodiment works for Tiago, and for R1Pro, all embodiment except Default work. + # Here, we remove Tiago for testing. + ROBOTS_UNDER_TEST = ["R1"] + + +@pytest.mark.parametrize("robot", ROBOTS_UNDER_TEST) +class TestPrimitives: + def test_navigate(self, robot): + categories = ["floors", "ceilings", "walls"] + env = setup_environment(categories, robot=robot) + + objects = [] + obj_1 = { + "object": DatasetObject(name="cologne", category="bottle_of_cologne", model="lyipur"), + "position": [-0.3, -0.8, 0.5], + "orientation": [0, 0, 0, 1], + } + objects.append(obj_1) + + primitives = [StarterSemanticActionPrimitiveSet.NAVIGATE_TO] + primitives_args = [(obj_1["object"],)] + + primitive_tester(env, objects, primitives, primitives_args) + + def test_grasp(self, robot): + categories = ["floors", "ceilings", "walls", "coffee_table"] + env = setup_environment(categories, robot=robot) + + objects = [] + obj_1 = { + "object": DatasetObject(name="cologne", category="bottle_of_cologne", model="lyipur"), + "position": [-0.3, -0.8, 0.5], + "orientation": [0, 0, 0, 1], + } + objects.append(obj_1) + + primitives = [StarterSemanticActionPrimitiveSet.GRASP] + primitives_args = [(obj_1["object"],)] + + primitive_tester(env, objects, primitives, primitives_args) + + def test_place(self, robot): + categories = ["floors", "ceilings", "walls", "coffee_table"] + env = setup_environment(categories, robot=robot) + + objects = [] + obj_1 = { + "object": DatasetObject(name="table", category="breakfast_table", model="rjgmmy", scale=[0.3, 0.3, 0.3]), + "position": [-0.7, 0.5, 0.09], + "orientation": [0, 0, 0, 1], + } + obj_2 = { + "object": DatasetObject(name="cologne", category="bottle_of_cologne", model="lyipur"), + "position": [-0.3, -0.8, 0.5], + "orientation": [0, 0, 0, 1], + } + objects.append(obj_1) + objects.append(obj_2) + + primitives = [StarterSemanticActionPrimitiveSet.GRASP, StarterSemanticActionPrimitiveSet.PLACE_ON_TOP] + primitives_args = [(obj_2["object"],), (obj_1["object"],)] + + primitive_tester(env, objects, primitives, primitives_args) + + @pytest.mark.skip(reason="primitives are broken") + def test_open_prismatic(self, robot): + categories = ["floors"] + env = setup_environment(categories, robot=robot) + + objects = [] + obj_1 = { + "object": DatasetObject( + name="bottom_cabinet", category="bottom_cabinet", model="bamfsz", scale=[0.7, 0.7, 0.7] + ), + "position": [-1.2, -0.4, 0.5], + "orientation": [0, 0, 0, 1], + } + objects.append(obj_1) + + primitives = [StarterSemanticActionPrimitiveSet.OPEN] + primitives_args = [(obj_1["object"],)] + + primitive_tester(env, objects, primitives, primitives_args) + + @pytest.mark.skip(reason="primitives are broken") + def test_open_revolute(self, robot): + categories = ["floors"] + env = setup_environment(categories, robot=robot) + + objects = [] + obj_1 = { + "object": DatasetObject(name="fridge", category="fridge", model="dszchb", scale=[0.7, 0.7, 0.7]), + "position": [-1.2, -0.4, 0.5], + "orientation": [0, 0, 0, 1], + } + objects.append(obj_1) + + primitives = [StarterSemanticActionPrimitiveSet.OPEN] + primitives_args = [(obj_1["object"],)] + + primitive_tester(env, objects, primitives, primitives_args) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_robot_states_flatcache.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_robot_states_flatcache.py new file mode 100644 index 0000000000000000000000000000000000000000..ed672675e83bb1d513022991fd8e1287df72e931 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_robot_states_flatcache.py @@ -0,0 +1,442 @@ +import torch as th +import pytest +import omnigibson as og +import omnigibson.lazy as lazy +from omnigibson.action_primitives.starter_semantic_action_primitives import StarterSemanticActionPrimitives +from omnigibson.controllers import ControllerView +from omnigibson.macros import gm +from omnigibson.robots import REGISTERED_ROBOTS, Robot +from omnigibson.sensors import VisionSensor +from omnigibson.utils.transform_utils import mat2pose, pose2mat, quaternions_close, relative_pose_transform +from omnigibson.utils.usd_utils import get_world_pose_with_scale +from omnigibson.object_states.robot_related_states import ObjectsInFOVOfRobot +from omnigibson.utils.constants import semantic_class_name_to_id + + +def setup_environment(): + """ + Sets up the environment. + """ + if og.sim is None: + # Set global flags + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_TRANSITION_RULES = False + else: + # Clear the simulator + og.clear() + + # Define the environment configuration + config = { + "scene": { + "type": "Scene", + }, + "robots": [ + { + "model": "fetch", + "obs_modalities": ["rgb", "seg_semantic", "seg_instance"], + "position": [150, 150, 100], + "orientation": [0, 0, 0, 1], + } + ], + } + + env = og.Environment(configs=config) + return env + + +def test_camera_pose(): + env = setup_environment() + robot = env.scene.robots[0] + env.reset() + og.sim.step() + + sensors = [s for s in robot.sensors.values() if isinstance(s, VisionSensor)] + assert len(sensors) > 0 + vision_sensor = sensors[0] + + # Get vision sensor world pose via directly calling get_position_orientation + robot_world_pos, robot_world_ori = robot.get_position_orientation() + sensor_world_pos, sensor_world_ori = vision_sensor.get_position_orientation() + + robot_to_sensor_mat = pose2mat( + relative_pose_transform(sensor_world_pos, sensor_world_ori, robot_world_pos, robot_world_ori) + ) + + sensor_world_pos_gt = th.tensor([150.5134, 149.8278, 101.0816]) + sensor_world_ori_gt = th.tensor([0.0176, -0.1205, 0.9910, -0.0549]) + + assert th.allclose(sensor_world_pos, sensor_world_pos_gt, atol=1e-3) + assert quaternions_close(sensor_world_ori, sensor_world_ori_gt, atol=1e-3) + + # Now, we want to move the robot and check if the sensor pose has been updated + old_camera_local_pose = vision_sensor.get_position_orientation(frame="parent") + + robot.set_position_orientation(position=[100, 100, 100]) + new_camera_local_pose = vision_sensor.get_position_orientation(frame="parent") + new_camera_world_pose = vision_sensor.get_position_orientation() + robot_pose_mat = pose2mat(robot.get_position_orientation()) + expected_camera_world_pos, expected_camera_world_ori = mat2pose(robot_pose_mat @ robot_to_sensor_mat) + assert th.allclose(old_camera_local_pose[0], new_camera_local_pose[0], atol=1e-3) + assert th.allclose(new_camera_world_pose[0], expected_camera_world_pos, atol=1e-3) + assert quaternions_close(new_camera_world_pose[1], expected_camera_world_ori, atol=1e-3) + + # Then, we want to move the local pose of the camera and check + # 1) if the world pose is updated 2) if the robot stays in the same position + old_camera_local_pose = vision_sensor.get_position_orientation(frame="parent") + vision_sensor.set_position_orientation(position=[10, 10, 10], orientation=[0, 0, 0, 1], frame="parent") + new_camera_world_pose = vision_sensor.get_position_orientation() + camera_parent_prim = lazy.isaacsim.core.utils.prims.get_prim_parent(vision_sensor.prim) + camera_parent_path = str(camera_parent_prim.GetPath()) + camera_parent_world_transform = get_world_pose_with_scale(camera_parent_path) + expected_new_camera_world_pos, expected_new_camera_world_ori = mat2pose( + camera_parent_world_transform + @ pose2mat((th.tensor([10, 10, 10], dtype=th.float32), th.tensor([0, 0, 0, 1], dtype=th.float32))) + ) + assert th.allclose(new_camera_world_pose[0], expected_new_camera_world_pos, atol=1e-3) + assert quaternions_close(new_camera_world_pose[1], expected_new_camera_world_ori, atol=1e-3) + assert th.allclose(robot.get_position_orientation()[0], th.tensor([100, 100, 100], dtype=th.float32), atol=1e-3) + + # Finally, we want to move the world pose of the camera and check + # 1) if the local pose is updated 2) if the robot stays in the same position + robot.set_position_orientation(position=[150, 150, 100]) + old_camera_local_pose = vision_sensor.get_position_orientation(frame="parent") + vision_sensor.set_position_orientation( + position=[150, 150, 101.36912537], orientation=[-0.29444987, 0.29444981, 0.64288363, -0.64288352] + ) + new_camera_local_pose = vision_sensor.get_position_orientation(frame="parent") + assert not th.allclose(old_camera_local_pose[0], new_camera_local_pose[0], atol=1e-3) + assert not quaternions_close(old_camera_local_pose[1], new_camera_local_pose[1], atol=1e-3) + assert th.allclose(robot.get_position_orientation()[0], th.tensor([150, 150, 100], dtype=th.float32), atol=1e-3) + + # Another test we want to try is setting the camera's parent scale and check if the world pose is updated + camera_parent_prim.scale = th.tensor([2.0, 2.0, 2.0]) + camera_parent_world_transform = get_world_pose_with_scale(camera_parent_path) + camera_local_pose = vision_sensor.get_position_orientation(frame="parent") + expected_mat = camera_parent_world_transform @ pose2mat(camera_local_pose) + expected_mat[:3, :3] = expected_mat[:3, :3] / th.norm(expected_mat[:3, :3], dim=0, keepdim=True) + expected_new_camera_world_pos, _ = mat2pose(expected_mat) + new_camera_world_pose = vision_sensor.get_position_orientation() + assert th.allclose(new_camera_world_pose[0], expected_new_camera_world_pos, atol=1e-3) + + og.clear() + + +@pytest.mark.parametrize("robot_name", REGISTERED_ROBOTS) +def test_robot_load_drive(robot_name): + if robot_name == "stretch" or robot_name == "locobot": + pytest.skip( + f"Skipping {robot_name} for now due to issues with turning" + ) # TODO: https://github.com/StanfordVL/BEHAVIOR-1K/issues/2018 + + if robot_name == "husky": + pytest.skip("Husky base motion is a little messed up because of the 4-wheel drive; skipping for now") + + try: + if og.sim is None: + # Set global flags + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_TRANSITION_RULES = False + else: + # Make sure sim is stopped + og.sim.stop() + + config = { + "scene": { + "type": "Scene", + }, + } + + env = og.Environment(configs=config) + og.sim.stop() + + robot = Robot( + name=robot_name, + model=robot_name.lower(), + obs_modalities=[], + ) + env.scene.add_object(robot) + + # At least one step is always needed while sim is playing for any imported object to be fully initialized + og.sim.play() + + # Reset robot and make sure it's not moving + robot.reset() + robot.keep_still() + + og.sim.step() + + # Set viewer in front facing robot + og.sim.viewer_camera.set_position_orientation( + position=[2.69918369, -3.63686664, 4.57894564], + orientation=[0.39592411, 0.1348514, 0.29286304, 0.85982], + ) + + # If this is a manipulation robot, we want to test moving the arm + if robot.is_manipulation: + # load IK controller + controller_config = { + f"arm_{robot.default_arm}": {"name": "InverseKinematicsController", "mode": "pose_absolute_ori"} + } + robot.reload_controllers(controller_config=controller_config) + env.scene.update_initial_file() + + action_primitives = StarterSemanticActionPrimitives(env, robot, skip_curobo_initilization=True) + + eef_pos = env.scene.robots[0].get_eef_position() + eef_orn = env.scene.robots[0].get_eef_orientation() + if robot.model == "stretch": # Stretch arm faces the y-axis + target_eef_pos = th.tensor([eef_pos[0], eef_pos[1] - 0.1, eef_pos[2]], dtype=th.float32) + else: + target_eef_pos = th.tensor([eef_pos[0] + 0.1, eef_pos[1], eef_pos[2]], dtype=th.float32) + target_eef_orn = eef_orn + for action in action_primitives._move_hand_direct_ik((target_eef_pos, target_eef_orn)): + env.step(action) + assert th.norm(robot.get_eef_position() - target_eef_pos) < 0.05 + + # If this is a locomotion robot, we want to test driving + if robot.is_locomotion: + action_primitives = StarterSemanticActionPrimitives(env, robot, skip_curobo_initilization=True) + goal_location = th.tensor([0, 1, 0], dtype=th.float32) + for action in action_primitives._navigate_to_pose_direct(goal_location): + env.step(action) + assert th.norm(robot.get_position()[:2] - goal_location[:2]) < 0.1 + yaw_diff = robot.get_rpy()[2] - goal_location[2] + wrapped_yaw_diff = th.atan2(th.sin(yaw_diff), th.cos(yaw_diff)) + assert th.abs(wrapped_yaw_diff) < 0.1 + + # Stop the simulator and remove the robot + og.sim.stop() + env.scene.remove_object(obj=robot) + finally: + if og.sim is not None: + og.clear() + + +def _object_is_in_hand(robot, obj, grasping_mode): + if grasping_mode in ["sticky", "assisted"]: + return robot._ag_obj_in_hand[robot.default_arm] == obj + elif grasping_mode == "physical": + prim_paths = robot._find_gripper_raycast_collisions() + return len(prim_paths.intersection(obj.link_prim_paths)) > 0 + else: + raise ValueError(f"Unknown grasping mode: {grasping_mode}") + + +@pytest.mark.parametrize( + "grasping_mode", + [ + "sticky", + "assisted", + pytest.param( + "physical", + marks=pytest.mark.skip( + reason="Physical grasping is released mid-move: a finger-velocity transient from the " + "object's inertia trips the is_grasping heuristic (VEL_TOLERANCE=0.02 vs a measured " + "0.11 m/s), which flips the gripper's no-op command to open. Pre-existing on main, " + "where it is masked only because a leaked physics callback zeroes the velocity " + "estimate for any second environment. Re-enable once the grasp gate is fixed upstream." + ), + ), + ], +) +def test_grasping_mode(grasping_mode): + try: + if og.sim is not None: + # Make sure sim is stopped + og.sim.stop() + + scene_cfg = dict(type="Scene") + objects_cfg = [] + objects_cfg.append( + dict( + type="DatasetObject", + name="table", + category="breakfast_table", + model="lcsizg", + bounding_box=[0.5, 0.5, 0.8], + fixed_base=True, + position=[0.7, -0.1, 0.6], + ) + ) + objects_cfg.append( + dict( + type="PrimitiveObject", + name="box", + primitive_type="Cube", + rgba=[1.0, 0, 0, 1.0], + size=0.05, + position=[0.53, 0.0, 0.87], + ) + ) + cfg = dict(scene=scene_cfg, objects=objects_cfg) + + env = og.Environment(configs=cfg) + og.sim.viewer_camera.set_position_orientation( + position=[1.0170, 0.5663, 1.0554], + orientation=[0.1734, 0.5006, 0.8015, 0.2776], + ) + og.sim.stop() + + robot = Robot( + name="Fetch", + model="fetch", + obs_modalities=[], + controller_config={"arm_0": {"name": "InverseKinematicsController", "mode": "pose_absolute_ori"}}, + grasping_mode=grasping_mode, + ) + env.scene.add_object(robot) + + # At least one step is always needed while sim is playing for any imported object to be fully initialized + og.sim.play() + + env.scene.reset(hard=False) + + # Reset robot and make sure it's not moving + robot.reset() + robot.keep_still() + + # Let the box settle + for _ in range(10): + og.sim.step() + + action_primitives = StarterSemanticActionPrimitives(env=env, robot=robot, skip_curobo_initilization=True) + + box_object = env.scene.object_registry("name", "box") + target_eef_pos = box_object.get_position_orientation()[0] + target_eef_orn = robot.get_eef_orientation() + + # Move eef to the box + for action in action_primitives._move_hand_direct_ik((target_eef_pos, target_eef_orn), pos_thresh=0.01): + env.step(action) + + group_key, controller_idx = robot.controllers["gripper_0"] + + # Grasp the box + ControllerView.update_goal(group_key, controller_idx, th.tensor([-1.0])) + for _ in range(30): + og.sim.step() + + assert _object_is_in_hand( + robot, box_object, grasping_mode + ), f"Grasping mode {grasping_mode} failed to grasp the object" + + # Move eef + eef_offset = th.tensor([0.0, 0.2, 0.2]) + for action in action_primitives._move_hand_direct_ik((target_eef_pos + eef_offset, target_eef_orn)): + env.step(action) + + assert _object_is_in_hand( + robot, box_object, grasping_mode + ), f"Grasping mode {grasping_mode} failed to keep the object in hand" + + # Release the box + ControllerView.update_goal(group_key, controller_idx, th.tensor([1.0])) + for _ in range(20): + og.sim.step() + + assert not _object_is_in_hand( + robot, box_object, grasping_mode + ), f"Grasping mode {grasping_mode} failed to release the object" + finally: + if og.sim is not None: + og.clear() + + +def test_camera_semantic_segmentation(): + env = setup_environment() + robot = env.scene.robots[0] + env.reset() + sensors = [s for s in robot.sensors.values() if isinstance(s, VisionSensor)] + assert len(sensors) > 0 + vision_sensor = sensors[0] + env.reset() + all_observation, all_info = vision_sensor.get_obs() + seg_semantic = all_observation["seg_semantic"] + seg_semantic_info = all_info["seg_semantic"] + agent_label = semantic_class_name_to_id()["agent"] + background_label = semantic_class_name_to_id()["background"] + assert th.all(th.isin(seg_semantic, th.tensor([agent_label, background_label], device=seg_semantic.device))) + assert set(seg_semantic_info.keys()) == {agent_label, background_label} + og.clear() + + +def test_object_in_FOV_of_robot(): + env = setup_environment() + robot = env.scene.robots[0] + env.reset() + objs_in_fov = robot.states[ObjectsInFOVOfRobot].get_value() + assert len(objs_in_fov) == 1 and next(iter(objs_in_fov)) == robot + sensors = [s for s in robot.sensors.values() if isinstance(s, VisionSensor)] + assert len(sensors) > 0 + for vision_sensor in sensors: + vision_sensor.set_position_orientation(position=[100, 150, 100]) + og.sim.step() + for _ in range(5): + og.sim.render() + # Since the sensor is moved away from the robot, the robot should not see itself + assert len(robot.states[ObjectsInFOVOfRobot].get_value()) == 0 + og.clear() + + +def test_holonomic_robot_tuck_untuck_base_joint_invariance(): + """ + Test that calling tuck() and untuck() on a holonomic base robot + should not move the robot's body. + """ + if og.sim is None: + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_TRANSITION_RULES = False + else: + og.sim.stop() + + # Use R1 which has holonomic base and mobile_manipulation (tucked/untucked) + config = { + "scene": { + "type": "Scene", + }, + "robots": [ + { + "model": "r1", + "obs_modalities": [], + "position": [10.0, 20.0, 0.5], + "orientation": [0, 0, 0.3827, 0.9239], # 45 degree rotation around z + } + ], + } + + env = og.Environment(configs=config) + robot = env.scene.robots[0] + env.reset() + og.sim.step() + + assert robot.is_holonomic_base, "R1 should have holonomic base" + assert robot.is_mobile_manipulation, "R1 should have mobile manipulation capability" + + # Record initial base joint positions (the 6 DoF controlling robot pose) + initial_base_joint_pos = robot.get_joint_positions()[robot.base_idx].clone() + initial_pos, initial_ori = robot.get_position_orientation() + + # Test tuck() - should preserve base joint positions and pose + robot.tuck() + base_joint_pos_after_tuck = robot.get_joint_positions()[robot.base_idx] + pos_after_tuck, ori_after_tuck = robot.get_position_orientation() + assert th.allclose( + initial_base_joint_pos, base_joint_pos_after_tuck, atol=1e-6 + ), f"tuck() changed base joint positions! Initial: {initial_base_joint_pos}, After tuck: {base_joint_pos_after_tuck}" + assert th.allclose(initial_pos, pos_after_tuck, atol=1e-6), "tuck() changed robot position" + assert th.allclose(initial_ori, ori_after_tuck, atol=1e-6), "tuck() changed robot orientation" + + # Test untuck() - should preserve base joint positions and pose + robot.untuck() + base_joint_pos_after_untuck = robot.get_joint_positions()[robot.base_idx] + pos_after_untuck, ori_after_untuck = robot.get_position_orientation() + assert th.allclose( + initial_base_joint_pos, base_joint_pos_after_untuck, atol=1e-6 + ), f"untuck() changed base joint positions! Initial: {initial_base_joint_pos}, After untuck: {base_joint_pos_after_untuck}" + assert th.allclose(initial_pos, pos_after_untuck, atol=1e-6), "untuck() changed robot position" + assert th.allclose(initial_ori, ori_after_untuck, atol=1e-6), "untuck() changed robot orientation" + + og.clear() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_robot_teleoperation.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_robot_teleoperation.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3ce52a6ab6bbd1b14cd258f758f33df221e7e3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_robot_teleoperation.py @@ -0,0 +1,65 @@ +import pytest +import torch as th +from telemoma.human_interface.teleop_core import TeleopAction + +import omnigibson as og +from omnigibson.macros import gm +from omnigibson.utils.transform_utils import quat2euler + + +@pytest.mark.skip(reason="test hangs on CI") +def test_teleop(): + cfg = { + "env": {"action_timestep": 1 / 60.0, "physics_timestep": 1 / 120.0}, + "scene": {"type": "Scene"}, + "robots": [ + { + "model": "fetch", + "action_normalize": False, + "controller_config": { + "arm_0": { + "name": "InverseKinematicsController", + "command_input_limits": None, + }, + }, + } + ], + } + + if og.sim is None: + # Make sure GPU dynamics are enabled (GPU dynamics needed for cloth) + gm.USE_GPU_DYNAMICS = False + else: + # Make sure sim is stopped + og.sim.stop() + + # Create the environment + env = og.Environment(configs=cfg) + robot = env.scene.robots[0] + env.reset() + teleop_action = TeleopAction() + start_base_pose = robot.get_position_orientation() + start_eef_pose = robot.links[robot.eef_link_names[robot.default_arm]].get_position_orientation() + + # test moving robot arm + teleop_action.right = th.cat(([0.01], th.zeros(6))) + for _ in range(50): + action = robot.teleop_data_to_action(teleop_action) + env.step(action) + cur_eef_pose = robot.links[robot.eef_link_names[robot.default_arm]].get_position_orientation() + assert cur_eef_pose[0][0] - start_eef_pose[0][0] > 0.02, "Robot arm not moving forward" + + # test moving robot base + teleop_action.right = th.zeros(7) + teleop_action.base = th.tensor([0.1, 0, 0.1]) + for _ in range(50): + action = robot.teleop_data_to_action(teleop_action) + env.step(action) + cur_base_pose = robot.get_position_orientation() + assert cur_base_pose[0][0] - start_base_pose[0][0] > 0.02, "robot base not moving forward" + assert ( + quat2euler(cur_base_pose[1])[2] - quat2euler(start_base_pose[1])[2] > 0.02 + ), "robot base not rotating counter-clockwise" + + # Clear the sim + og.clear() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_scene_graph.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_scene_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc149077b4822a99a1a891a3b3488aa2d965073 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_scene_graph.py @@ -0,0 +1,112 @@ +import math + +import torch as th +from utils import place_obj_on_floor_plane + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.scene_graphs.graph_builder import SceneGraphBuilder, visualize_scene_graph +from omnigibson.utils.constants import PrimType + + +def test_scene_graph(): + if og.sim is None: + # Set global flags + gm.ENABLE_OBJECT_STATES = True + else: + # Make sure sim is stopped + og.sim.stop() + + def create_robot_config(name, position): + return { + "name": name, + "model": "fetch", + "obs_modalities": ["rgb", "seg_instance"], + "position": position, + "orientation": T.euler2quat(th.tensor([0, 0, -math.pi / 2], dtype=th.float32)), + "controller_config": { + "arm_0": { + "name": "NullJointController", + "motor_type": "position", + }, + }, + } + + robot_names = ["fetch_1", "fetch_2", "fetch_3"] + robot_positions = [[0, 0.8, 0], [1, 0.8, 0], [2, 0.8, 0]] + + config = { + "scene": { + "type": "Scene", + }, + "robots": [create_robot_config(name, position) for name, position in zip(robot_names, robot_positions)], + "objects": [ + { + "type": "DatasetObject", + "fit_avg_dim_volume": True, + "name": "breakfast_table", + "category": "breakfast_table", + "model": "skczfi", + "prim_type": PrimType.RIGID, + "position": [150, 150, 150], + "scale": None, + "bounding_box": None, + "abilities": None, + "visual_only": False, + }, + { + "type": "DatasetObject", + "fit_avg_dim_volume": True, + "name": "bowl", + "category": "bowl", + "model": "ajzltc", + "prim_type": PrimType.RIGID, + "position": [150, 150, 150], + "scale": None, + "bounding_box": None, + "abilities": None, + "visual_only": False, + }, + ], + } + + env = og.Environment(configs=config) + scene = env.scene + + breakfast_table = scene.object_registry("name", "breakfast_table") + bowl = scene.object_registry("name", "bowl") + place_obj_on_floor_plane(breakfast_table) + bowl.set_position_orientation(position=[0.0, -0.8, 0.1], orientation=[0, 0, 0, 1]) + + # Test single robot scene graph + scene_graph_builder_single = SceneGraphBuilder( + robot_names=robot_names[:1], egocentric=False, full_obs=True, only_true=True, merge_parallel_edges=True + ) + scene_graph_builder_single.start(scene) + for _ in range(3): + og.sim.step() + scene_graph_builder_single.step(scene) + + assert isinstance( + visualize_scene_graph( + scene, scene_graph_builder_single.get_scene_graph(), show_window=False, cartesian_positioning=True + ), + th.Tensor, + ) + + # Test multi robot scene graph + scene_graph_builder_multi = SceneGraphBuilder( + robot_names=robot_names, egocentric=False, full_obs=True, only_true=True, merge_parallel_edges=True + ) + scene_graph_builder_multi.start(scene) + for _ in range(3): + og.sim.step() + scene_graph_builder_multi.step(scene) + + assert isinstance( + visualize_scene_graph( + scene, scene_graph_builder_multi.get_scene_graph(), show_window=False, cartesian_positioning=True + ), + th.Tensor, + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_sensors.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_sensors.py new file mode 100644 index 0000000000000000000000000000000000000000..4739af04adf0146d3ef07b77eb50a04c0c60ef0c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_sensors.py @@ -0,0 +1,107 @@ +import torch as th +from utils import SYSTEM_EXAMPLES, place_obj_on_floor_plane + +import omnigibson as og +from omnigibson.systems import MacroParticleSystem, MicroParticleSystem +from omnigibson.utils.constants import semantic_class_id_to_name + + +def test_segmentation_modalities(env, breakfast_table, dishtowel): + place_obj_on_floor_plane(breakfast_table) + dishtowel.set_position_orientation(position=[-0.4, 0.0, 0.55], orientation=[0, 0, 0, 1]) + + og.sim.viewer_camera.set_position_orientation(position=[-0.0017, -0.1072, 1.4969], orientation=[0.0, 0.0, 0.0, 1.0]) + + modalities_required = ["seg_semantic", "seg_instance", "seg_instance_id"] + for modality in modalities_required: + og.sim.viewer_camera.add_modality(modality) + + systems = [env.scene.get_system(system_name) for system_name in SYSTEM_EXAMPLES.keys()] + for i, system in enumerate(systems): + # Sample two particles for each system + pos = th.tensor([-0.2 + i * 0.2, 0, 0.55]) + if env.scene.is_physical_particle_system(system_name=system.name): + system.generate_particles(positions=[pos.tolist(), (pos + th.tensor([0.1, 0.0, 0.0])).tolist()]) + else: + if system.get_group_name(breakfast_table) not in system.groups: + system.create_attachment_group(breakfast_table) + system.generate_group_particles( + group=system.get_group_name(breakfast_table), + positions=[pos, pos + th.tensor([0.1, 0.0, 0.0])], + link_prim_paths=[breakfast_table.root_link.prim_path] * 2, + ) + + og.sim.step() + for _ in range(3): + og.sim.render() + + all_observation, all_info = og.sim.viewer_camera.get_obs() + + seg_semantic = all_observation["seg_semantic"] + seg_semantic_info = all_info["seg_semantic"] + assert set(int(x.item()) for x in th.unique(seg_semantic)) == set(seg_semantic_info.keys()) + expected_semantic_names = {"floors", "breakfast_table", "dishtowel", *SYSTEM_EXAMPLES.keys()} + assert set(seg_semantic_info.values()) == expected_semantic_names + + seg_instance = all_observation["seg_instance"] + seg_instance_info = all_info["seg_instance"] + assert set(int(x.item()) for x in th.unique(seg_instance)) == set(seg_instance_info.keys()) + expected_instance_names = {"groundPlane", "breakfast_table", "dishtowel", *SYSTEM_EXAMPLES.keys()} + assert set(seg_instance_info.values()) == expected_instance_names + + seg_instance_id = all_observation["seg_instance_id"] + seg_instance_id_info = all_info["seg_instance_id"] + assert set(int(x.item()) for x in th.unique(seg_instance_id)) == set(seg_instance_id_info.keys()) + expected_instance_id_paths = { + "/World/ground_plane/geom", + *[visual_mesh.prim_path for visual_mesh in breakfast_table.root_link.visual_meshes.values()], + *[visual_mesh.prim_path for visual_mesh in dishtowel.root_link.visual_meshes.values()], + } + for system in systems: + if isinstance(system, MicroParticleSystem): + for instancer in system.particle_instancers.values(): + instancer_scope_path = instancer.prim_path.rsplit("/instancer", 1)[0] + expected_instance_id_paths.update( + f"{instancer_scope_path}/prototype{int(prototype_id.item())}" + for prototype_id in th.unique(instancer.particle_prototype_ids) + ) + elif isinstance(system, MacroParticleSystem): + expected_instance_id_paths.update(particle.prim_path for particle in system.particles.values()) + assert set(seg_instance_id_info.values()) == expected_instance_id_paths + + for system in systems: + env.scene.clear_system(system.name) + + +def test_bbox_modalities(env, breakfast_table, dishtowel): + place_obj_on_floor_plane(breakfast_table) + dishtowel.set_position_orientation(position=[-0.4, 0.0, 0.55], orientation=[0, 0, 0, 1]) + + og.sim.viewer_camera.set_position_orientation(position=[-0.0017, -0.1072, 1.4969], orientation=[0.0, 0.0, 0.0, 1.0]) + + modalities_required = ["bbox_2d_tight", "bbox_2d_loose", "bbox_3d"] + for modality in modalities_required: + og.sim.viewer_camera.add_modality(modality) + + og.sim.step() + for _ in range(3): + og.sim.render() + + all_observation, all_info = og.sim.viewer_camera.get_obs() + + bbox_2d_tight = all_observation["bbox_2d_tight"] + bbox_2d_loose = all_observation["bbox_2d_loose"] + bbox_3d = all_observation["bbox_3d"] + + assert len(bbox_2d_tight) == 3 + assert len(bbox_2d_loose) == 3 + assert len(bbox_3d) == 2 + + bbox_2d_expected_objs = set(["floors", "breakfast_table", "dishtowel"]) + bbox_3d_expected_objs = set(["breakfast_table", "dishtowel"]) + + bbox_2d_objs = set([semantic_class_id_to_name()[bbox[0]] for bbox in bbox_2d_tight]) + bbox_3d_objs = set([semantic_class_id_to_name()[bbox[0]] for bbox in bbox_3d]) + + assert bbox_2d_objs == bbox_2d_expected_objs + assert bbox_3d_objs == bbox_3d_expected_objs diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_snapshots.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_snapshots.py new file mode 100644 index 0000000000000000000000000000000000000000..95ce7ceb1a8595e748433617d3c69bba84d53ab7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_snapshots.py @@ -0,0 +1,186 @@ +""" +Deterministic snapshot tests. +Each test loads a fixed scene and compares sensor output against a stored .npy reference. + +To regenerate all snapshots: + SNAPSHOT_UPDATE=1 OMNIGIBSON_HEADLESS=1 pytest tests/test_snapshots.py + +A companion .png is written alongside each .npy on every test run for visual +inspection. Commit both the .npy and .png files together. +""" + +import os +from pathlib import Path + +import numpy as np +import omnigibson as og +import pytest +import torch as th +from omnigibson.objects import DatasetObject +from PIL import Image + +SNAPSHOTS_DIR = Path(__file__).parent / "snapshots" +GOLDEN_DIR = SNAPSHOTS_DIR / "golden" +ACTUAL_DIR = SNAPSHOTS_DIR / "actual" + +# Camera pose used across multiple tests, positioned to view the Rs_int kitchen area. +_CAM_POS = th.tensor([1.5, -4, 2.25]) +_CAM_ORN = th.tensor([0.56829048, 0.09569975, 0.13571846, 0.80589577]) + + +# --------------------------------------------------------------------------- +# Visualisation helpers +# --------------------------------------------------------------------------- + + +def _id_to_rgb(semantic_id: int) -> tuple[int, int, int]: + """Map a semantic class ID to a stable RGB colour via a simple hash spread.""" + h = int(semantic_id) & 0xFFFFFFFF + h = ((h >> 16) ^ h) * 0x45D9F3B + h = ((h >> 16) ^ h) * 0x45D9F3B + h = (h >> 16) ^ h + return ((h & 0xFF0000) >> 16, (h & 0x00FF00) >> 8, h & 0x0000FF) + + +def _array_to_png(array: np.ndarray, png_path: Path) -> None: + """ + Write a 2-D numpy array as a colour PNG. + + Integer arrays (seg_semantic, seg_instance) are false-coloured by unique ID. + Float arrays (depth_linear, depth) are normalised to grayscale. + """ + if np.issubdtype(array.dtype, np.integer): + h, w = array.shape + rgb = np.zeros((h, w, 3), dtype=np.uint8) + for uid in np.unique(array): + rgb[array == uid] = _id_to_rgb(int(uid)) + else: + finite = array[np.isfinite(array)] + lo, hi = (float(finite.min()), float(finite.max())) if finite.size else (0.0, 1.0) + normalized = np.clip((array - lo) / max(hi - lo, 1e-6), 0.0, 1.0) + gray = (normalized * 255).astype(np.uint8) + rgb = np.stack([gray, gray, gray], axis=-1) + Image.fromarray(rgb).save(png_path) + + +# --------------------------------------------------------------------------- +# Test infrastructure +# --------------------------------------------------------------------------- + + +def _update_mode(): + return os.environ.get("SNAPSHOT_UPDATE", "").lower() in ("1", "true", "yes") + + +def _capture(camera_pos, camera_orn, modalities): + """Step the sim, render, and return a dict of {modality: numpy array}.""" + cam = og.sim.viewer_camera + cam.set_position_orientation(position=camera_pos, orientation=camera_orn) + for m in modalities: + cam.add_modality(m) + + og.sim.step() + for _ in range(3): + og.sim.render() + + obs, _ = cam.get_obs() + out = {} + for m in modalities: + data = obs[m] + if hasattr(data, "cpu"): + data = data.cpu() + out[m] = np.array(data) + return out + + +def _check(name, array): + """Compare array against stored golden reference, or save it if SNAPSHOT_UPDATE is set. + + On mismatch the actual output is written to snapshots/actual/ for debugging. + """ + GOLDEN_DIR.mkdir(parents=True, exist_ok=True) + path = GOLDEN_DIR / f"{name}.npy" + + if _update_mode(): + np.save(path, array) + png_path = path.with_suffix(".png") + _array_to_png(array, png_path) + print(f"Image can be viewed at : {png_path}") + pytest.skip(f"Snapshot updated: {path}") + + if not path.exists(): + pytest.fail( + f"Missing golden snapshot '{name}': {path}. " "Set SNAPSHOT_UPDATE=1 to generate it and commit the result." + ) + + reference = np.load(path) + shape_match = array.shape == reference.shape + similarity = (np.array_equal(array, reference) * 1.0) if not shape_match else np.mean(array == reference) + similar_enough = shape_match and similarity >= 0.99 + + if not similar_enough: + ACTUAL_DIR.mkdir(parents=True, exist_ok=True) + actual_npy = ACTUAL_DIR / f"{name}.npy" + actual_png = ACTUAL_DIR / f"{name}.png" + np.save(actual_npy, array) + _array_to_png(array, actual_png) + + if not shape_match: + pytest.fail(f"Shape mismatch for '{name}': got {array.shape}, expected {reference.shape}") + assert similar_enough, ( + f"Snapshot mismatch for '{name}': {similarity:.2%} similar (threshold 99%). " + "Set SNAPSHOT_UPDATE=1 to regenerate the reference." + ) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +def test_snapshot_rs_int(): + """ + Semantic segmentation of Rs_int with a bowl and apple placed at fixed positions. + Covers: interactive scene loading, object placement, seg_semantic modality. + """ + env = og.Environment(configs={"scene": {"type": "InteractiveTraversableScene", "scene_model": "Rs_int"}}) + + bowl = DatasetObject(name="bowl", category="bowl", model="ajzltc") + env.scene.add_object(bowl) + bowl.set_position_orientation(position=th.tensor([0.5, -1.5, 0.5]), frame="scene") + + apple = DatasetObject(name="apple", category="apple", model="agveuv") + env.scene.add_object(apple) + apple.set_position_orientation(position=th.tensor([0.8, -1.5, 0.5]), frame="scene") + + obs = _capture(_CAM_POS, _CAM_ORN, ["seg_semantic"]) + og.clear() + + _check("rs_int_with_objects_seg_semantic", obs["seg_semantic"]) + + +def test_snapshot_items_in_scene(): + """ + Semantic segmentation of a Fetch robot and a few objects in an empty scene. + Covers: robot loading, robot segmentation class, viewer camera setup. + """ + env = og.Environment( + configs={ + "scene": {"type": "Scene"}, + "robots": [{"type": "Fetch", "obs_modalities": [], "position": [0, 0, 0], "orientation": [0, 0, 0, 1]}], + } + ) + for name, category, model, pos in [ + ("bowl", "bowl", "ajzltc", [-0.5, 0.0, 0.1]), + ("apple", "apple", "agveuv", [0.0, 1.0, 0.1]), + ("microwave", "microwave", "hjjxmi", [0.5, 3.0, 0.1]), + ("stove", "stove", "dusebh", [1.0, 0.0, 0.1]), + ]: + obj = DatasetObject(name=name, category=category, model=model) + env.scene.add_object(obj) + obj.set_position_orientation(position=th.tensor(pos), frame="scene") + + obs = _capture(_CAM_POS, _CAM_ORN, ["seg_semantic"]) + og.clear() + + _check("robot_in_empty_scene_seg_semantic", obs["seg_semantic"]) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_symbolic_primitives.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_symbolic_primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..0766419d03e8407594b1bf2ad0359f6b05414742 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_symbolic_primitives.py @@ -0,0 +1,330 @@ +import os + +import pytest +import yaml + +import omnigibson as og +from omnigibson import object_states +from omnigibson.action_primitives.symbolic_semantic_action_primitives import ( + SymbolicSemanticActionPrimitives, + SymbolicSemanticActionPrimitiveSet, +) + +# TODO: Using GPU dynamics causes cuda memory issues, need to investigate +# gm.USE_GPU_DYNAMICS = True +# gm.ENABLE_TRANSITION_RULES = True +current_robot_type = "R1" + + +def load_robot_config(robot_name): + config_filename = os.path.join(og.example_config_path, f"{robot_name.lower()}_primitives.yaml") + with open(config_filename, "r") as file: + full_config = yaml.safe_load(file) + robot_config = full_config.get("robots", {})[0] + robot_config["disable_grasp_handling"] = True + return robot_config + + +def start_env(robot_type): + global current_robot_type + if og.sim: + og.sim.stop() + if robot_type != current_robot_type: + current_robot_type = robot_type + og.clear() + + if robot_type not in ["R1", "Tiago"]: + raise ValueError("Invalid robot configuration") + robots = load_robot_config(robot_type) + config = { + "render": {"viewer_width": 1280, "viewer_height": 720}, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Wainscott_0_int", + "load_object_categories": ["floors", "walls", "countertop", "fridge", "furniture_sink", "stove"], + "scene_source": "OG", + }, + "robots": [robots], + "objects": [ + { + "type": "DatasetObject", + "name": "pan", + "category": "frying_pan", + "model": "mhndon", + "position": [5.31, 10.75, 1.0], + }, + { + "type": "DatasetObject", + "name": "knife", + "category": "carving_knife", + "model": "awvoox", + "position": [10.31, 10.75, 1.2], + }, + { + "type": "DatasetObject", + "name": "apple", + "category": "apple", + "model": "agveuv", + "position": [4.75, 10.75, 1.0], + }, + { + "type": "DatasetObject", + "name": "sponge", + "category": "sponge", + "model": "qewotb", + "position": [4.75, 10.75, 1.0], + }, + ], + } + env = og.Environment(configs=config) + + return env + + +def retrieve_obj_cfg(obj): + return { + "name": obj.name, + "category": obj.category, + "model": obj.model, + "prim_type": obj.prim_type, + "position": obj.get_position_orientation()[0], + "scale": obj.scale, + "abilities": obj.abilities, + "visual_only": obj.visual_only, + } + + +def pytest_generate_tests(metafunc): + if "robot_type" in metafunc.fixturenames: + metafunc.parametrize("robot_type", ["R1", "Tiago"], scope="session") + + +@pytest.fixture(scope="module") +def shared_env(robot_type): + """Create the environment once per session for each robot type.""" + env = start_env(robot_type=robot_type) + return env + + +@pytest.fixture(scope="function") +def env(shared_env): + """Reset the environment before each test function.""" + shared_env.scene.reset() + return shared_env + + +@pytest.fixture +def robot(env): + return env.scene.robots[0] + + +@pytest.fixture +def prim_gen(env): + return SymbolicSemanticActionPrimitives(env, env.scene.robots[0]) + + +@pytest.fixture +def countertop(env): + return next(iter(env.scene.object_registry("category", "countertop"))) + + +@pytest.fixture +def fridge(env): + return next(iter(env.scene.object_registry("category", "fridge"))) + + +@pytest.fixture +def stove(env): + return next(iter(env.scene.object_registry("category", "stove"))) + + +@pytest.fixture +def furniture_sink(env): + return next(iter(env.scene.object_registry("category", "furniture_sink"))) + + +@pytest.fixture +def pan(env): + return next(iter(env.scene.object_registry("category", "frying_pan"))) + + +@pytest.fixture +def apple(env): + return next(iter(env.scene.object_registry("category", "apple"))) + + +@pytest.fixture +def sponge(env): + return next(iter(env.scene.object_registry("category", "sponge"))) + + +@pytest.fixture +def knife(env): + return next(iter(env.scene.object_registry("category", "carving_knife"))) + + +class TestSymbolicPrimitives: + def test_in_hand_state(self, env, robot, prim_gen, apple): + assert not robot.states[object_states.IsGrasping].get_value(apple) + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, apple): + env.step(action) + assert robot.states[object_states.IsGrasping].get_value(apple) + + # def test_navigate(): + # pass + + def test_open(self, env, prim_gen, fridge): + assert not fridge.states[object_states.Open].get_value() + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.OPEN, fridge): + env.step(action) + assert fridge.states[object_states.Open].get_value() + + def test_close(self, env, prim_gen, fridge): + fridge.states[object_states.Open].set_value(True) + assert fridge.states[object_states.Open].get_value() + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.CLOSE, fridge): + env.step(action) + assert not fridge.states[object_states.Open].get_value() + + def test_place_inside(self, env, prim_gen, apple, fridge): + assert not apple.states[object_states.Inside].get_value(fridge) + assert not fridge.states[object_states.Open].get_value() + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.OPEN, fridge): + env.step(action) + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, apple): + env.step(action) + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.PLACE_INSIDE, fridge): + env.step(action) + assert apple.states[object_states.Inside].get_value(fridge) + + def test_place_ontop(self, env, prim_gen, apple, pan): + assert not apple.states[object_states.OnTop].get_value(pan) + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, apple): + env.step(action) + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.PLACE_ON_TOP, pan): + env.step(action) + assert apple.states[object_states.OnTop].get_value(pan) + + def test_toggle_on(self, env, prim_gen, stove, furniture_sink): + assert not stove.states[object_states.ToggledOn].get_value() + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.TOGGLE_ON, stove): + env.step(action) + assert stove.states[object_states.ToggledOn].get_value() + + assert not furniture_sink.states[object_states.ToggledOn].get_value() + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.TOGGLE_ON, furniture_sink): + env.step(action) + assert furniture_sink.states[object_states.ToggledOn].get_value() + + @pytest.mark.skip("Disabled until GPU dynamics does not cause cuda memory issues") + def test_soak_under(self, env, prim_gen, robot, sponge, furniture_sink): + water_system = env.scene.get_system("water") + assert not sponge.states[object_states.Saturated].get_value(water_system) + assert not furniture_sink.states[object_states.ToggledOn].get_value() + + # First grasp the sponge + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, sponge): + env.step(action) + assert robot.states[object_states.IsGrasping].get_value(sponge) + + # Then toggle on the furniture_sink + furniture_sink.states[object_states.ToggledOn].set_value(True) + assert furniture_sink.states[object_states.ToggledOn].get_value() + + # Then soak the sponge under the water + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.SOAK_UNDER, furniture_sink): + env.step(action) + assert sponge.states[object_states.Saturated].get_value(water_system) + + # toggle off the furniture_sink after the test is done + furniture_sink.states[object_states.ToggledOn].set_value(False) + assert not furniture_sink.states[object_states.ToggledOn].get_value() + + @pytest.mark.skip("Disabled until GPU dynamics does not cause cuda memory issues") + def test_wipe(self, env, prim_gen, robot, sponge, furniture_sink, countertop): + # Some pre-assertions + water_system = env.scene.get_system("water") + assert not sponge.states[object_states.Saturated].get_value(water_system) + assert not furniture_sink.states[object_states.ToggledOn].get_value() + + # Dirty the countertop as the setup + mud_system = env.scene.get_system("mud") + countertop.states[object_states.Covered].set_value(mud_system, True) + + # First grasp the sponge + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, sponge): + env.step(action) + assert robot.states[object_states.IsGrasping].get_value(sponge) + + # Then toggle on the furniture_sink + furniture_sink.states[object_states.ToggledOn].set_value(True) + assert furniture_sink.states[object_states.ToggledOn].get_value() + + # Then soak the sponge under the water + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.SOAK_UNDER, furniture_sink): + env.step(action) + assert sponge.states[object_states.Saturated].get_value(water_system) + + # Then toggle off the furniture_sink + furniture_sink.states[object_states.ToggledOn].set_value(False) + assert not furniture_sink.states[object_states.ToggledOn].get_value() + + # Wipe the countertop with the sponge + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.WIPE, countertop): + env.step(action) + assert not countertop.states[object_states.Covered].get_value(mud_system) + + @pytest.mark.skip("Disabled until env reset can add/remove objects") + def test_cut(self, env, prim_gen, apple, knife, countertop): + # Store the apple object information for scene reset + # deleted_objs = [apple] + # deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + # assert not apple.states[object_states.Cut].get_value(knife) + # start a new environment to enable transition rules + print("Grasping knife") + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, knife): + env.step(action) + print("Cutting apple") + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.CUT, apple): + env.step(action) + print("Putting knife back on countertop") + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.PLACE_ON_TOP, countertop): + env.step(action) + + # clean up + # half_apples = env.scene.object_registry("category", "half_apple", set()).copy() + # for apple in half_apples: + # env.scene.remove_object(apple) + + # objs = [DatasetObject(**obj_cfg) for obj_cfg in deleted_objs_cfg] + # og.sim.batch_add_objects(objs, scenes=[env.scene] * len(objs)) + # og.sim.step() + + def test_persistent_sticky_grasping(self, env, robot, prim_gen, apple): + assert not robot.states[object_states.IsGrasping].get_value(apple) + for action in prim_gen.apply_ref(SymbolicSemanticActionPrimitiveSet.GRASP, apple): + env.step(action) + assert robot.states[object_states.IsGrasping].get_value(apple) + state = og.sim.dump_state() + og.sim.stop() + og.sim.play() + og.sim.load_state(state) + assert robot.states[object_states.IsGrasping].get_value(apple) + + for _ in range(10): + env.step(prim_gen._empty_action()) + + assert robot.states[object_states.IsGrasping].get_value(apple) + + # def test_soak_inside(): + # pass + + # def test_place_near_heating_element(): + # pass + + # def test_wait_for_cooked(): + # pass + + def teardown_class(cls): + og.clear() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_systems.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_systems.py new file mode 100644 index 0000000000000000000000000000000000000000..cd020df474759e087e224d9eeea1258273298550 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_systems.py @@ -0,0 +1,39 @@ +import torch as th + +from utils import SYSTEM_EXAMPLES + +import omnigibson as og +from omnigibson.object_states import Covered +from omnigibson.systems import VisualParticleSystem, MicroPhysicalParticleSystem + + +def test_system_spawn_and_clear(env, breakfast_table): + og.sim.viewer_camera.set_position_orientation( + th.tensor([0.1525, -0.2867, 0.0773]), th.tensor([0.6538, 0.1604, 0.1762, 0.7181]) + ) + og.sim.step() + for system_name, system_class in SYSTEM_EXAMPLES.items(): + for _ in range(3): + system = env.scene.get_system(system_name) + assert isinstance(system, system_class) + if issubclass(system_class, VisualParticleSystem): + assert breakfast_table.states[Covered].set_value(system, True) + else: + system.generate_particles(positions=[[0, 0, 0.05]]) + assert th.allclose( + system.get_particle_position_orientation(idx=0)[0], th.tensor([0.0, 0.0, 0.05], dtype=th.float32) + ) + for _ in range(10): + og.sim.step() + if issubclass(system_class, MicroPhysicalParticleSystem): + assert th.allclose( + system.get_particle_position_orientation(idx=0)[0], + th.tensor([0, 0, system.particle_contact_radius], dtype=th.float32), + atol=1e-3, + ) + assert system.n_particles > 0 + og.sim.step() + env.scene.clear_system(system_name) + # This is a bit of a hack to address a very niche situation where we clear a system and immediately reinitialize it + # If we do not take a physics step here, the system will not be reinitialized properly + og.sim.step() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_tiled_rendering.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_tiled_rendering.py new file mode 100644 index 0000000000000000000000000000000000000000..42ade89d16a82a4d8770febeec2d297b26aef593 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_tiled_rendering.py @@ -0,0 +1,256 @@ +""" +Tests for tiled rendering in multi-env (vectorized) environments. + +In multi-env mode (num_envs > 1) with gm.ENABLE_TILED_RENDERING enabled, all per-env robot cameras are +batched into a single tiled render product (TiledVisionSensor), and per-env camera observations are slices +of the batched buffer. Tiled rendering is opt-in, so this suite turns the macro on explicitly. +""" + +import pytest +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.sensors import VisionSensor + +# Deliberately use 5 envs: the tile grid is 3x2 with one empty tile, which exercises the +# non-square indexing math of the reshape_tiled_image warp kernel. +NUM_ENVS = 5 + +# Distance of the marker cube in front of each env's camera (distinct per env so that tile<->env +# misalignment is detectable via depth). NOTE: the fetch camera looks downward and its optical axis +# hits the floor at ~1.14m, so distances must stay below that for the marker to remain above the floor. +MARKER_DISTANCES = [0.4 + 0.15 * i for i in range(NUM_ENVS)] +MARKER_SIZE = 0.4 +# Tile<->env misalignment shifts the measured depth by >= the 0.15 distance spacing, so a tolerance +# below that detects any tile shuffle while absorbing rendering noise +DEPTH_TOLERANCE = 0.07 + +MARKER_CFG = [ + { + "type": "PrimitiveObject", + "name": "marker", + "primitive_type": "Cube", + "rgba": [1.0, 0, 0, 1.0], + "size": MARKER_SIZE, + "visual_only": True, + # Initially hidden far below the floor; tests teleport it in front of each env's camera + "position": [0, 0, -50.0], + } +] + + +def _init_macros(): + """Set simulator macros (only once, before the first Environment is created).""" + if og.sim is None: + gm.RENDER_VIEWER_CAMERA = False + gm.USE_GPU_DYNAMICS = False + gm.ENABLE_TRANSITION_RULES = False + gm.ENABLE_OBJECT_STATES = False + # Tiled rendering is opt-in (gm.ENABLE_TILED_RENDERING defaults to False); this suite tests + # it, so turn it on explicitly. Must be set here, before the first env load reads it -- gm + # locks a macro once read, so assigning it again on a later call would raise. + gm.ENABLE_TILED_RENDERING = True + else: + og.sim.stop() + + +def _setup_vec_env(num_envs, obs_modalities, scene_cfg=None, objects_cfg=None, env_cfg_extra=None): + _init_macros() + cfg = { + "env": {"num_envs": num_envs, **(env_cfg_extra or {})}, + "scene": scene_cfg + or { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": ["floors", "walls"], + }, + "robots": [{"model": "fetch", "obs_modalities": list(obs_modalities)}], + "task": {"type": "DummyTask"}, + } + if objects_cfg: + cfg["objects"] = objects_cfg + return og.Environment(configs=cfg) + + +def _camera_sensor_name(robot): + return next(name for name, sensor in robot.sensors.items() if isinstance(sensor, VisionSensor)) + + +def _place_markers(env, distances): + """Teleport each scene's marker cube directly in front of that env's camera at the given distance.""" + for env_idx, scene in enumerate(env._scenes): + robot = scene.robots[0] + cam = robot.sensors[_camera_sensor_name(robot)] + cam_pos, cam_quat = cam.get_position_orientation() + # USD cameras look down their local -z axis + cam_forward = T.quat2mat(cam_quat) @ th.tensor([0.0, 0.0, -1.0]) + marker = scene.object_registry("name", "marker") + marker.set_position_orientation(position=cam_pos + cam_forward * distances[env_idx]) + # Step + render so that annotator buffers reflect the new marker poses + og.sim.step() + for _ in range(3): + og.sim.render() + + +def _center_patch(img, half=8): + h, w = img.shape[0], img.shape[1] + return img[h // 2 - half : h // 2 + half, w // 2 - half : w // 2 + half] + + +def test_tiled_rendering_core(): + """Alignment, shapes/dtypes, proprio, per-sensor parity, obs space conformance and reset freshness.""" + try: + env = _setup_vec_env( + num_envs=NUM_ENVS, + obs_modalities=["rgb", "depth_linear", "proprio"], + objects_cfg=MARKER_CFG, + ) + robot_name = env._scenes[0].robots[0].name + cam_name = _camera_sensor_name(env._scenes[0].robots[0]) + + # --- Tiled sensor is active and covers the camera with the requested modalities --- + assert ( + env._tiled_sensor is not None + ), "Tiled sensor should be created when num_envs > 1 and gm.ENABLE_TILED_RENDERING is True" + assert cam_name in env._tiled_sensor.modalities + assert {"rgb", "depth_linear"} == set(env._tiled_sensor.modalities[cam_name]) + for scene in env._scenes: + camera = scene.robots[0].sensors[cam_name] + assert ( + not camera.render_product.hydra_texture.updates_enabled + ), "Individual camera render products must be paused when tiled rendering supplies observations" + + # --- Knob plumbing: default number of re-renders on reset --- + assert env._num_rerenders_on_reset == 3 + + _place_markers(env, MARKER_DISTANCES) + obs_list, info_list = env.get_obs() + assert len(obs_list) == NUM_ENVS + + expected_center_depths = [d - MARKER_SIZE / 2 for d in MARKER_DISTANCES] + for i in range(NUM_ENVS): + cam_obs = obs_list[i][robot_name][cam_name] + + # --- Shapes / dtypes / device --- + rgb = cam_obs["rgb"] + depth = cam_obs["depth_linear"] + assert rgb.shape == (128, 128, 4), f"env {i}: rgb shape {rgb.shape}" + assert rgb.dtype == th.uint8 + assert rgb.is_cuda, "Tiled rgb should live on GPU" + assert depth.shape == (128, 128), f"env {i}: depth shape {depth.shape}" + assert depth.dtype == th.float32 + + # --- Tile <-> env alignment: the marker cube of env i must appear in tile i at distance d_i --- + center_depth = _center_patch(depth).median().item() + assert abs(center_depth - expected_center_depths[i]) < DEPTH_TOLERANCE, ( + f"env {i}: center depth {center_depth:.3f} does not match expected " + f"{expected_center_depths[i]:.3f} -- tile/env misalignment?" + ) + # The marker is pure red: red must dominate green/blue at the image center + center_rgb = _center_patch(rgb).float() + red, green, blue = center_rgb[..., 0].mean(), center_rgb[..., 1].mean(), center_rgb[..., 2].mean() + assert ( + red > green + 20 and red > blue + 20 + ), f"env {i}: expected red marker at center, got rgb=({red:.1f}, {green:.1f}, {blue:.1f})" + + # --- Proprio must be preserved in multi-env mode --- + proprio = obs_list[i][robot_name]["proprio"] + assert proprio.numel() > 0 and th.all(th.isfinite(proprio)), f"env {i}: invalid proprio" + + # --- Parity with per-sensor rendering. Depth is the strict geometric check; rgb is loose since + # the tiled and per-sensor render products denoise/accumulate samples differently --- + individual_sensors = [scene.robots[0].sensors[cam_name] for scene in env._scenes] + individual_obs = [] + with og.sim.editing_usd(): + for sensor in individual_sensors: + sensor.render_product.hydra_texture.updates_enabled = True + try: + for _ in range(8): + og.sim.render() + parity_tiled_obs, _ = env.get_obs() + individual_obs = [sensor.get_obs()[0] for sensor in individual_sensors] + finally: + with og.sim.editing_usd(): + for sensor in individual_sensors: + sensor.render_product.hydra_texture.updates_enabled = False + for i, s_obs in enumerate(individual_obs): + tiled_rgb = parity_tiled_obs[i][robot_name][cam_name]["rgb"].float().cpu() + sensor_rgb = s_obs["rgb"].float().cpu() + mean_diff = (tiled_rgb - sensor_rgb).abs().mean().item() + assert mean_diff < 40.0, f"env {i}: tiled vs per-sensor rgb mean abs diff {mean_diff:.1f}" + tiled_depth_center = _center_patch(parity_tiled_obs[i][robot_name][cam_name]["depth_linear"].cpu()).median() + sensor_depth_center = _center_patch(s_obs["depth_linear"].cpu()).median() + assert abs(tiled_depth_center - sensor_depth_center) < 0.2, f"env {i}: tiled vs per-sensor depth mismatch" + + # --- Reset: returned observations must conform to the observation space (checked internally by + # reset()) and, with num_rerenders_on_reset > 0, reflect the *reset* state (markers back below + # the floor), not the pre-reset frame --- + pre_reset_center_depth = _center_patch(obs_list[0][robot_name][cam_name]["depth_linear"]).median().item() + reset_obs_list, _ = env.reset() + assert len(reset_obs_list) == NUM_ENVS + post_reset_center_depth = _center_patch(reset_obs_list[0][robot_name][cam_name]["depth_linear"]).median().item() + assert post_reset_center_depth > pre_reset_center_depth + 0.3, ( + f"reset() returned a stale frame: center depth {post_reset_center_depth:.3f} still matches the " + f"pre-reset marker at {pre_reset_center_depth:.3f}" + ) + + # --- step() returns tiled observations as well --- + actions = th.stack( + [th.from_numpy(env._scenes[i].robots[0].action_space.sample()).float() for i in range(env.num_envs)] + ) + obs_list, _, _, _, _ = env.step(actions) + assert obs_list[0][robot_name][cam_name]["rgb"].shape == (128, 128, 4) + finally: + if og.sim is not None: + og.clear() + + +def test_tiled_rendering_empty_scene(): + """Multi-env layout of object-less scenes must produce finite, increasing scene offsets (AABB fix).""" + try: + env = _setup_vec_env( + num_envs=3, + obs_modalities=["rgb"], + scene_cfg={"type": "Scene", "use_floor_plane": True}, + env_cfg_extra={"num_rerenders_on_reset": 2}, + ) + + # --- Knob plumbing: custom number of re-renders on reset --- + assert env._num_rerenders_on_reset == 2 + + # --- Scene offsets must be finite and strictly increasing along x --- + xs = [scene.get_position_orientation()[0][0].item() for scene in env._scenes] + assert all(th.isfinite(th.tensor(xs))), f"Non-finite scene positions: {xs}" + assert xs[0] == pytest.approx(0.0, abs=1e-3) + assert xs[1] > xs[0] and xs[2] > xs[1], f"Scene positions not increasing: {xs}" + + # --- Robots must be placed apart accordingly --- + robot_xs = [scene.robots[0].get_position_orientation()[0][0].item() for scene in env._scenes] + assert robot_xs[1] > robot_xs[0] and robot_xs[2] > robot_xs[1], f"Robot positions not increasing: {robot_xs}" + + # --- Stepping and tiled observations work in empty scenes --- + robot_name = env._scenes[0].robots[0].name + cam_name = _camera_sensor_name(env._scenes[0].robots[0]) + actions = th.stack( + [th.from_numpy(env._scenes[i].robots[0].action_space.sample()).float() for i in range(env.num_envs)] + ) + obs_list, _, _, _, _ = env.step(actions) + for i in range(3): + rgb = obs_list[i][robot_name][cam_name]["rgb"] + assert rgb.shape == (128, 128, 4) and rgb.dtype == th.uint8 + finally: + if og.sim is not None: + og.clear() + + +def test_tiled_rendering_unsupported_modality(): + """Modalities that cannot be tiled (e.g. pointcloud) must fail at construction with a clear error. + + NOTE: this test must remain LAST in the module. It deliberately leaves a partially-constructed + environment behind (og.clear() cannot recover from a failed construction), which is reclaimed + at process exit. + """ + with pytest.raises(ValueError, match="Unsupported modality"): + _setup_vec_env(num_envs=2, obs_modalities=["rgb", "pointcloud"]) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_transform_utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_transform_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..14d7b681c56bb224bc02c655aa3194398686e2b7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_transform_utils.py @@ -0,0 +1,491 @@ +import math + +import numpy as np +import torch as th +import trimesh +from scipy.spatial.transform import Rotation as R +from scipy.spatial.transform import Slerp +from torch.testing import assert_close + +from omnigibson.utils.numpy_utils import NumpyTypes +from omnigibson.utils.transform_utils import ( + align_vector_sets, + anorm, + axisangle2quat, + cartesian_to_polar, + check_quat_right_angle, + convert_quat, + copysign, + dot, + euler2mat, + euler2quat, + integer_spiral_coordinates, + l2_distance, + mat2euler, + mat2pose, + matrix_inverse, + normalize, + pose2mat, + pose_inv, + quat2axisangle, + quat2euler, + quat2mat, + quat_apply, + quat_conjugate, + quat_distance, + quat_inverse, + quat_multiply, + quat_slerp, + quaternions_close, + random_axis_angle, + random_quaternion, + rotation_matrix, + transform_points, + transformation_matrix, + vecs2axisangle, + vecs2quat, + z_angle_from_quat, +) + +# Create constants for vectors +RANDOM_VECTORS = [ + th.tensor([0.56853108, 0.53382016, 0.30716877], dtype=th.float32), + th.tensor([0.52257347, 0.61831128, 0.83885363], dtype=th.float32), + th.tensor([0.21115992, 0.21581846, 0.32354917], dtype=th.float32), + th.tensor([0.29239464, 0.56651807, 0.18654108], dtype=th.float32), +] + +# Create constants for matrices +RANDOM_MATRICES = [ + th.tensor( + [ + [0.73807538, 0.34566713, 0.22840234], + [0.6477331, 0.11909693, 0.54837387], + [0.80250765, 0.98231487, 0.30666593], + ], + dtype=th.float32, + ), + th.tensor( + [ + [0.49792992, 0.34195128, 0.97021054], + [0.34943073, 0.94597711, 0.4247565], + [0.33942933, 0.34367859, 0.12948883], + ], + dtype=th.float32, + ), + th.tensor( + [ + [0.14253589, 0.0570198, 0.52688842], + [0.13947784, 0.71386355, 0.25629677], + [0.49064311, 0.72391959, 0.46148444], + ], + dtype=th.float32, + ), + th.tensor( + [ + [0.37922823, 0.11913949, 0.97869396], + [0.17461795, 0.55869352, 0.18168803], + [0.88240868, 0.57003021, 0.09736692], + ], + dtype=th.float32, + ), +] + +# Create constants for quaternions +RANDOM_QUATERNIONS = [ + th.tensor([-0.67976515, 0.50242053, -0.18529368, -0.50115786], dtype=th.float32), + th.tensor([0.7823932, -0.18596287, -0.43777126, 0.40203857], dtype=th.float32), + th.tensor([-0.66576888, 0.56006078, 0.06682257, -0.4884859], dtype=th.float32), + th.tensor([0.6827, 0.7298, 0.0191, 0.0301], dtype=th.float32), +] + + +def are_rotations_close(R1, R2, atol=1e-3): + return ( + th.allclose(R1 @ R1.t(), th.eye(3), atol=atol) + and th.allclose(R2 @ R2.t(), th.eye(3), atol=atol) + and th.allclose(R1, R2, atol=atol) + ) + + +class TestQuaternionOperations: + def test_quat2mat_special_cases(self): + special_quats = [ + th.tensor([0.0, 0.0, 0.0, 1.0]), # Identity quaternion + th.tensor([1.0, 0.0, 0.0, 0.0]), # 180 degree rotation around x + th.tensor([0.0, 1.0, 0.0, 0.0]), # 180 degree rotation around y + th.tensor([0.0, 0.0, 1.0, 0.0]), # 180 degree rotation around z + ] + for q in special_quats: + q_np = q.cpu().numpy() + scipy_mat = R.from_quat(q_np).as_matrix() + our_mat = quat2mat(q) + assert_close(our_mat, th.from_numpy(scipy_mat.astype(NumpyTypes.FLOAT32))) + + def test_quat_multiply(self): + for i in range(0, len(RANDOM_QUATERNIONS), 2): + q1, q2 = RANDOM_QUATERNIONS[i], RANDOM_QUATERNIONS[i + 1] + q1_scipy = q1.cpu().numpy() + q2_scipy = q2.cpu().numpy() + scipy_result = R.from_quat(q1_scipy) * R.from_quat(q2_scipy) + scipy_quat = scipy_result.as_quat() + our_quat = quat_multiply(q1, q2) + assert quaternions_close(our_quat, th.from_numpy(scipy_quat.astype(NumpyTypes.FLOAT32))) + + def test_quat_conjugate(self): + for q in RANDOM_QUATERNIONS: + q_scipy = q.cpu().numpy() + scipy_conj = R.from_quat(q_scipy).inv().as_quat() + our_conj = quat_conjugate(q) + assert quaternions_close(our_conj, th.from_numpy(scipy_conj.astype(NumpyTypes.FLOAT32))) + + def test_quat_inverse(self): + for q in RANDOM_QUATERNIONS: + scipy_inv = R.from_quat(q.cpu().numpy()).inv().as_quat().astype(NumpyTypes.FLOAT32) + our_inv = quat_inverse(q) + assert quaternions_close(our_inv, th.from_numpy(scipy_inv)) + q_identity = quat_multiply(q, our_inv) + assert quaternions_close(q_identity, th.tensor([0.0, 0.0, 0.0, 1.0])) + + def test_quat_distance(self): + for i in range(0, len(RANDOM_QUATERNIONS), 2): + q1, q2 = RANDOM_QUATERNIONS[i], RANDOM_QUATERNIONS[i + 1] + dist = quat_distance(q2, q1) + assert quaternions_close(quat_multiply(dist, q1), q2) + + +class TestVectorOperations: + def test_normalize(self): + for v in RANDOM_VECTORS: + normalized = normalize(v) + assert_close(th.norm(normalized), th.tensor(1.0)) + + def test_dot_product(self): + for i in range(0, len(RANDOM_VECTORS), 2): + v1, v2 = RANDOM_VECTORS[i], RANDOM_VECTORS[i + 1] + for dim in [-1, 0]: + assert_close(dot(v1, v2, dim=dim), th.dot(v1, v2)) + + def test_l2_distance(self): + for i in range(0, len(RANDOM_VECTORS), 2): + v1, v2 = RANDOM_VECTORS[i], RANDOM_VECTORS[i + 1] + dist = l2_distance(v1, v2) + assert_close(dist, th.norm(v1 - v2)) + + +class TestMatrixOperations: + def test_rotation_matrix_properties(self): + for rand_quat in RANDOM_QUATERNIONS: + R_mat = quat2mat(rand_quat) + scipy_R = R.from_quat(rand_quat.cpu().numpy()).as_matrix().astype(NumpyTypes.FLOAT32) + assert_close(R_mat, th.from_numpy(scipy_R)) + assert_close(R_mat @ R_mat.t(), th.eye(3)) + assert_close(th.det(R_mat), th.tensor(1.0)) + + def test_rotation_matrix(self): + angles = [0, math.pi / 4, math.pi / 2, math.pi] + for angle in angles: + for direction in RANDOM_VECTORS: + direction = normalize(direction) + R_mat = rotation_matrix(angle, direction) + scipy_R = R.from_rotvec(angle * direction.cpu().numpy()).as_matrix().astype(NumpyTypes.FLOAT32) + assert_close(R_mat, th.from_numpy(scipy_R)) + + identity = th.eye(3, dtype=R_mat.dtype, device=R_mat.device) + assert_close(R_mat @ R_mat.t(), identity) + assert_close(R_mat.t() @ R_mat, identity) + assert_close(th.det(R_mat), th.tensor(1.0, dtype=R_mat.dtype, device=R_mat.device)) + + test_vector = th.randn(3, dtype=R_mat.dtype, device=R_mat.device) + rotated_vector = R_mat @ test_vector + assert_close(th.norm(rotated_vector), th.norm(test_vector)) + + if angle != 0: + axis = R_mat @ direction + assert_close(axis, direction) + perpendicular = th.cross(direction, th.randn(3, dtype=R_mat.dtype, device=R_mat.device)) + perpendicular = normalize(perpendicular) + rotated_perpendicular = R_mat @ perpendicular + cos_angle = th.dot(perpendicular, rotated_perpendicular) + assert_close(cos_angle, th.cos(th.tensor(angle))) + + def test_transformation_matrix(self): + angles = [0, math.pi / 4, math.pi / 2, math.pi] + for angle in angles: + for direction in RANDOM_VECTORS: + for point in RANDOM_VECTORS: + direction = normalize(direction) + T = transformation_matrix(angle, direction, point) + + direction_np = direction.cpu().numpy() + scipy_R = R.from_rotvec(angle * direction_np).as_matrix().astype(NumpyTypes.FLOAT32) + scipy_T = np.eye(4, dtype=NumpyTypes.FLOAT32) + scipy_T[:3, :3] = scipy_R + scipy_T[:3, 3] = point.cpu().numpy() - np.dot(scipy_R, point.cpu().numpy()) + assert_close(T, th.from_numpy(scipy_T)) + + rot = T[:3, :3] + identity = th.eye(3, dtype=rot.dtype, device=rot.device) + assert_close(rot @ rot.t(), identity) + assert_close(rot.t() @ rot, identity) + assert_close(th.det(rot), th.tensor(1.0, dtype=rot.dtype, device=rot.device)) + assert_close(T[3, :], th.tensor([0, 0, 0, 1], dtype=T.dtype, device=T.device)) + + def test_transformation_matrix_no_point(self): + angles = [0, math.pi / 4, math.pi / 2, math.pi] + for angle in angles: + for direction in RANDOM_VECTORS: + direction = normalize(direction) + T = transformation_matrix(angle, direction) + + scipy_R = R.from_rotvec(angle * direction.cpu().numpy()).as_matrix().astype(NumpyTypes.FLOAT32) + scipy_T = np.eye(4, dtype=NumpyTypes.FLOAT32) + scipy_T[:3, :3] = scipy_R + assert_close(T, th.from_numpy(scipy_T)) + + assert_close(T[:3, 3], th.zeros(3, dtype=T.dtype, device=T.device)) + rot = rotation_matrix(angle, direction) + assert_close(T[:3, :3], rot) + + def test_matrix_inverse(self): + for M in RANDOM_MATRICES: + M_inv = matrix_inverse(M) + scipy_M_inv = np.linalg.inv(M.cpu().numpy()).astype(NumpyTypes.FLOAT32) + assert_close(M_inv, th.from_numpy(scipy_M_inv), atol=1e-3, rtol=1e-3) + assert_close(M @ M_inv, th.eye(3)) + + +class TestCoordinateTransformations: + def test_cartesian_to_polar(self): + for v in RANDOM_VECTORS: + x, y = v[0], v[1] + rho, phi = cartesian_to_polar(x, y) + np_rho, np_phi = np.hypot(x, y), np.arctan2(y, x) + assert_close(rho, th.tensor(np_rho, dtype=th.float32)) + assert_close(phi, th.tensor(np_phi, dtype=th.float32)) + + +class TestPoseTransformations: + def test_pose2mat_and_mat2pose(self): + for pos in RANDOM_VECTORS: + for orn in RANDOM_QUATERNIONS: + T = pose2mat((pos, orn)) + + scipy_R = R.from_quat(orn.cpu().numpy()) + scipy_T = np.eye(4, dtype=NumpyTypes.FLOAT32) + scipy_T[:3, :3] = scipy_R.as_matrix() + scipy_T[:3, 3] = pos.cpu().numpy() + + assert_close(T, th.from_numpy(scipy_T)) + + recovered_pos, recovered_orn = mat2pose(T) + assert_close(pos, recovered_pos) + assert quaternions_close(orn, recovered_orn) + + def test_pose_inv(self): + for pos in RANDOM_VECTORS: + for orn in RANDOM_QUATERNIONS: + T = pose2mat((pos, orn)) + T_inv = pose_inv(T) + + scipy_R = R.from_quat(orn.cpu().numpy()) + scipy_T = np.eye(4, dtype=NumpyTypes.FLOAT32) + scipy_T[:3, :3] = scipy_R.as_matrix() + scipy_T[:3, 3] = pos.cpu().numpy() + scipy_T_inv = np.linalg.inv(scipy_T) + + assert_close(T_inv, th.from_numpy(scipy_T_inv)) + assert_close(T @ T_inv, th.eye(4)) + + +class TestAxisAngleConversions: + def test_axisangle2quat_and_quat2axisangle(self): + angles = [0.0, math.pi / 4, math.pi / 2, math.pi] + for angle in angles: + for axis in RANDOM_VECTORS: + axis = normalize(axis) + axisangle = axis * angle + quat = axisangle2quat(axisangle) + + scipy_R = R.from_rotvec(axisangle.cpu().numpy()) + scipy_quat = scipy_R.as_quat().astype(NumpyTypes.FLOAT32) + + assert quaternions_close(quat, th.from_numpy(scipy_quat)) + + recovered_axisangle = quat2axisangle(quat) + scipy_recovered_axisangle = scipy_R.as_rotvec().astype(NumpyTypes.FLOAT32) + + assert th.allclose(recovered_axisangle, th.from_numpy(scipy_recovered_axisangle)) or th.allclose( + recovered_axisangle, -th.from_numpy(scipy_recovered_axisangle) + ), f"Axis-angles not equivalent: {recovered_axisangle} vs {scipy_recovered_axisangle}" + + def test_vecs2axisangle(self): + vec1 = th.tensor([1.0, 0.0, 0.0]) + vec2 = th.tensor([0.0, 1.0, 0.0]) + axisangle = vecs2axisangle(vec1, vec2) + + scipy_R = R.align_vectors(vec2.unsqueeze(0).cpu().numpy(), vec1.unsqueeze(0).cpu().numpy())[0] + scipy_axisangle = scipy_R.as_rotvec().astype(NumpyTypes.FLOAT32) + + assert_close(axisangle, th.from_numpy(scipy_axisangle)) + + def test_vecs2quat(self): + vec1 = th.tensor([1.0, 0.0, 0.0]) + vec2 = th.tensor([0.0, 1.0, 0.0]) + quat = vecs2quat(vec1, vec2) + + scipy_R = R.align_vectors(vec2.unsqueeze(0).cpu().numpy(), vec1.unsqueeze(0).cpu().numpy())[0] + scipy_quat = scipy_R.as_quat().astype(NumpyTypes.FLOAT32) + + assert quaternions_close(quat, th.from_numpy(scipy_quat)) + + +class TestEulerAngleConversions: + def test_euler2quat_and_quat2euler(self): + euler_angles = [ + th.tensor([0.0, 0.0, 0.0]), + th.tensor([math.pi / 4, math.pi / 3, math.pi / 2]), + ] + for euler in euler_angles: + quat = euler2quat(euler) + scipy_R = R.from_euler("xyz", euler.cpu().numpy()) + scipy_quat = scipy_R.as_quat().astype(NumpyTypes.FLOAT32) + assert quaternions_close(quat, th.from_numpy(scipy_quat)) + + recovered_euler = quat2euler(quat) + scipy_recovered_euler = scipy_R.as_euler("xyz").astype(NumpyTypes.FLOAT32) + assert_close(recovered_euler, th.from_numpy(scipy_recovered_euler)) + + def test_euler2mat_and_mat2euler(self): + euler_angles = [ + th.tensor([0.0, 0.0, 0.0]), + th.tensor([math.pi / 4, math.pi / 3, math.pi / 2]), + ] + for euler in euler_angles: + mat = euler2mat(euler) + scipy_R = R.from_euler("xyz", euler.cpu().numpy()) + scipy_mat = scipy_R.as_matrix().astype(NumpyTypes.FLOAT32) + assert_close(mat, th.from_numpy(scipy_mat)) + + recovered_euler = mat2euler(mat) + scipy_recovered_euler = scipy_R.as_euler("xyz").astype(NumpyTypes.FLOAT32) + assert_close(recovered_euler, th.from_numpy(scipy_recovered_euler)) + + +class TestQuaternionApplications: + def test_quat_apply(self): + for quat in RANDOM_QUATERNIONS: + for vec in RANDOM_VECTORS: + rotated_vec = quat_apply(quat, vec) + + scipy_R = R.from_quat(quat.cpu().numpy()) + scipy_rotated_vec = scipy_R.apply(vec.cpu().numpy()).astype(NumpyTypes.FLOAT32) + + assert rotated_vec.shape == (3,) + assert_close(rotated_vec, th.from_numpy(scipy_rotated_vec), atol=1e-3, rtol=1e-3) + assert_close(th.norm(rotated_vec), th.norm(vec), atol=1e-3, rtol=1e-3) + + def test_quat_slerp(self): + for i in range(0, len(RANDOM_QUATERNIONS), 2): + q1, q2 = RANDOM_QUATERNIONS[i], RANDOM_QUATERNIONS[i + 1] + t = th.rand(1) + q_slerp = quat_slerp(q1, q2, t) + + key_rots = R.from_quat(np.stack([q1.cpu().numpy(), q2.cpu().numpy()])) + key_times = [0, 1] + slerp = Slerp(key_times, key_rots) + scipy_q_slerp = slerp([t.item()]).as_quat()[0].astype(NumpyTypes.FLOAT32) + + assert quaternions_close(q_slerp, th.from_numpy(scipy_q_slerp)) + assert_close(th.norm(q_slerp), th.tensor(1.0)) + + +class TestTransformPoints: + def test_transform_points_2d(self): + points = th.tensor([[1.0, 0.0], [0.0, 1.0]]) + for matrix in RANDOM_MATRICES: + matrix_2d = th.eye(3) + matrix_2d[:2, :2] = matrix[:2, :2] + matrix_2d[:2, 2] = matrix[:2, 2] + transformed = transform_points(points, matrix_2d) + transformed_trimesh = th.tensor(trimesh.transform_points(points, matrix_2d), dtype=th.float32) + assert_close(transformed, transformed_trimesh) + + def test_transform_points_3d(self): + points = th.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) + for matrix in RANDOM_MATRICES: + matrix_4d = th.eye(4) + matrix_4d[:3, :3] = matrix + matrix_4d[:3, 3] = th.tensor([1.0, 2.0, 3.0]) + transformed = transform_points(points, matrix_4d) + transformed_trimesh = th.tensor(trimesh.transform_points(points, matrix_4d), dtype=th.float32) + assert_close(transformed, transformed_trimesh) + + +class TestMiscellaneousFunctions: + def test_convert_quat(self): + for quat_wxyz in RANDOM_QUATERNIONS: + quat_xyzw = convert_quat(quat_wxyz, to="xyzw") + assert_close(quat_xyzw, th.tensor([quat_wxyz[1], quat_wxyz[2], quat_wxyz[3], quat_wxyz[0]])) + + def test_random_quaternion(self): + num_quats = 10 + quats = random_quaternion(num_quaternions=num_quats) + assert quats.shape == (num_quats, 4) + assert_close(th.norm(quats, dim=1), th.ones(num_quats)) + + def test_random_axis_angle(self): + axis, angle = random_axis_angle() + assert_close(th.norm(axis), th.tensor(1.0)) + assert 0 <= angle <= 2 * math.pi + + def test_align_vector_sets(self): + # Test case 1: 90-degree rotation + vec_set1 = th.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=th.float32) + vec_set2 = th.tensor([[0, 1, 0], [0, 0, 1], [1, 0, 0]], dtype=th.float32) + quat = align_vector_sets(vec_set2, vec_set1) + expected_quat = th.tensor([0.5, 0.5, 0.5, 0.5], dtype=th.float32) + assert th.allclose(quat.abs(), expected_quat.abs(), atol=1e-6) + + # Test case 2: Identity rotation + vec_set1 = th.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=th.float32) + vec_set2 = vec_set1.clone() + quat = align_vector_sets(vec_set2, vec_set1) + expected_quat = th.tensor([0, 0, 0, 1], dtype=th.float32) + assert th.allclose(quat.abs(), expected_quat.abs(), atol=1e-6) + + # Test case 3: 120-degree rotation around [1, 1, 1] axis + vec_set1 = th.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=th.float32) + vec_set2 = th.tensor([[0, 1, 0], [0, 0, 1], [1, 0, 0]], dtype=th.float32) + quat = align_vector_sets(vec_set2, vec_set1) + expected_quat = th.tensor([0.5, 0.5, 0.5, 0.5], dtype=th.float32) + assert th.allclose(quat.abs(), expected_quat.abs(), atol=1e-6) + + def test_copysign(self): + a = 2.0 + b = th.tensor([-1.0, 1.0]) + result = copysign(a, b) + assert_close(result, th.tensor([-2.0, 2.0])) + + def test_anorm(self): + x = th.tensor([[1.0, 2.0], [3.0, 4.0]]) + norm = anorm(x, dim=1) + expected = th.tensor([math.sqrt(5), math.sqrt(25)]) + assert_close(norm, expected) + + def test_check_quat_right_angle(self): + right_angle_quat = th.tensor([0.0, 0.707106781, 0.0, 0.707106781]) + assert check_quat_right_angle(right_angle_quat) + + non_right_angle_quat = th.tensor([0.1, 0.2, 0.3, 0.9]) + assert not check_quat_right_angle(non_right_angle_quat) + + def test_z_angle_from_quat(self): + quat = euler2quat(th.tensor([0.0, 0.0, math.pi / 4])) + angle = z_angle_from_quat(quat) + assert_close(angle, th.tensor(math.pi / 4)) + + def test_integer_spiral_coordinates(self): + coords = [integer_spiral_coordinates(i) for i in range(5)] + expected = [(0, 0), (1, 0), (1, 1), (0, 1), (-1, 1)] + assert coords == expected diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_transition_rules.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_transition_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..1978269c5235cc5fc933053a4babd35e9fcc2c9a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/test_transition_rules.py @@ -0,0 +1,1522 @@ +import math + +import pytest + +import torch as th +from utils import place_obj_on_floor_plane, remove_all_systems, retrieve_obj_cfg + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import macros as m +from omnigibson.object_states import ( + Contains, + Cooked, + Covered, + Heated, + HeatSourceOrSink, + Inside, + OnTop, + Open, + Saturated, + Temperature, + ToggledOn, + Touching, +) +from omnigibson.objects import DatasetObject +from omnigibson.transition_rules import REGISTERED_RULES + + +def test_dryer_rule(env, clothes_dryer, remover_dishtowel, bowl): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + water = env.scene.get_system("water") + + place_obj_on_floor_plane(clothes_dryer) + og.sim.step() + + # Place the two objects inside the dryer + remover_dishtowel.set_position_orientation( + position=[0.06, 0, 0.2], orientation=[0.0311883, -0.23199339, -0.06849886, 0.96980107] + ) + bowl.set_position_orientation(position=[0.0, 0.0, 0.2], orientation=[0, 0, 0, 1]) + og.sim.step() + + assert remover_dishtowel.states[Saturated].set_value(water, True) + assert bowl.states[Covered].set_value(water, True) + og.sim.step() + + assert remover_dishtowel.states[Saturated].get_value(water) + assert clothes_dryer.states[Contains].get_value(water) + + # The rule will not execute if Open is True + clothes_dryer.states[Open].set_value(True) + clothes_dryer.states[ToggledOn].set_value(True) + og.sim.step() + + assert remover_dishtowel.states[Saturated].get_value(water) + assert clothes_dryer.states[Contains].get_value(water) + + # The rule will not execute if ToggledOn is False + clothes_dryer.states[Open].set_value(False) + clothes_dryer.states[ToggledOn].set_value(False) + og.sim.step() + + assert remover_dishtowel.states[Saturated].get_value(water) + assert clothes_dryer.states[Contains].get_value(water) + + # The rule will execute if Open is False and ToggledOn is True + clothes_dryer.states[Open].set_value(False) + clothes_dryer.states[ToggledOn].set_value(True) + og.sim.step() + + # Need to take one more step for the state setters to take effect + og.sim.step() + + assert not remover_dishtowel.states[Saturated].get_value(water) + # TODO: check this once we fix the dryer fillable volume + # assert not clothes_dryer.states[Contains].get_value(water) + + # Clean up + remove_all_systems(env.scene) + + +def test_washer_rule(env, baking_sheet, washer, remover_dishtowel, bowl): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + water = env.scene.get_system("water") + dust = env.scene.get_system("dust") # always remove + salt = env.scene.get_system("salt") # always remove (not explicitly specified) + rust = env.scene.get_system("rust") # never remove + spray_paint = env.scene.get_system("spray_paint") # requires acetone + acetone = env.scene.get_system("acetone") # solvent for spray paint + cooking_oil = env.scene.get_system("cooking_oil") # requires vinegar, lemon_juice, vinegar, etc. + + place_obj_on_floor_plane(washer) + og.sim.step() + + # Place the two objects inside the washer + # (Hacky) use baking_sheet as a stepping stone to elevate the objects so that they are inside the container volume. + baking_sheet.set_position_orientation( + position=[0.0, 0.0, 0.04], orientation=T.euler2quat(th.tensor([math.pi, 0, 0], dtype=th.float32)) + ) + remover_dishtowel.set_position_orientation(position=[0.0, 0.0, 0.05], orientation=[0, 0, 0, 1]) + bowl.set_position_orientation(position=[0.10, 0.0, 0.08], orientation=[0, 0, 0, 1]) + og.sim.step() + + assert bowl.states[Covered].set_value(dust, True) + assert bowl.states[Covered].set_value(salt, True) + assert bowl.states[Covered].set_value(rust, True) + assert bowl.states[Covered].set_value(spray_paint, True) + assert bowl.states[Covered].set_value(acetone, True) + assert bowl.states[Covered].set_value(cooking_oil, True) + assert not remover_dishtowel.states[Saturated].get_value(water) + assert not bowl.states[Covered].get_value(water) + + # The rule will not execute if Open is True + washer.states[Open].set_value(True) + og.sim.step() + + assert bowl.states[Covered].get_value(dust) + assert bowl.states[Covered].get_value(salt) + assert bowl.states[Covered].get_value(rust) + assert bowl.states[Covered].get_value(spray_paint) + assert bowl.states[Covered].get_value(acetone) + assert bowl.states[Covered].get_value(cooking_oil) + assert not remover_dishtowel.states[Saturated].get_value(water) + assert not bowl.states[Covered].get_value(water) + + washer.states[Open].set_value(False) + washer.states[ToggledOn].set_value(True) + + # The rule will execute when Open is False and ToggledOn is True + og.sim.step() + + # Need to take one more step for the state setters to take effect + og.sim.step() + + assert not bowl.states[Covered].get_value(dust) + assert not bowl.states[Covered].get_value(salt) + assert bowl.states[Covered].get_value(rust) + assert not bowl.states[Covered].get_value(spray_paint) + assert not bowl.states[Covered].get_value(acetone) + assert bowl.states[Covered].get_value(cooking_oil) + assert remover_dishtowel.states[Saturated].get_value(water) + assert bowl.states[Covered].get_value(water) + + # Clean up + remove_all_systems(env.scene) + + +def test_slicing_rule(env, apple, table_knife): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + + deleted_objs = [apple] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + assert apple.states[Cooked].set_value(True) + + initial_half_apples = env.scene.object_registry("category", "half_apple", set()).copy() + + place_obj_on_floor_plane(apple) + og.sim.step() + + table_knife.set_position_orientation( + position=[-0.05, 0.0, 0.15], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + assert not table_knife.states[Touching].get_value(apple) + final_half_apples = env.scene.object_registry("category", "half_apple", set()).copy() + assert len(final_half_apples) == len(initial_half_apples) + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is not None + + table_knife.set_position_orientation( + position=[-0.05, 0.0, 0.10], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + final_half_apples = env.scene.object_registry("category", "half_apple", set()).copy() + assert len(final_half_apples) > len(initial_half_apples) + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # One more step for the half apples to be initialized + og.sim.step() + + # All new half_apple should be cooked + new_half_apples = final_half_apples - initial_half_apples + for half_apple in new_half_apples: + assert half_apple.states[Cooked].get_value() + + # Clean up + for apple in new_half_apples: + env.scene.remove_object(apple) + og.sim.step() + + objs = [DatasetObject(**obj_cfg) for obj_cfg in deleted_objs_cfg] + og.sim.batch_add_objects(objs, scenes=[env.scene] * len(objs)) + og.sim.step() + + +def test_dicing_rule_cooked(env, half_apple, table_knife): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + cooked_diced_apple = env.scene.get_system("cooked__diced__apple") + + deleted_objs = [half_apple] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + half_apple.set_orientation(T.euler2quat(th.tensor([0, -math.pi / 2, 0], dtype=th.float32))) + place_obj_on_floor_plane(half_apple) + og.sim.step() + + assert half_apple.states[Cooked].set_value(True) + + assert cooked_diced_apple.n_particles == 0 + + table_knife.set_position_orientation( + position=[-0.05, 0.0, 0.15], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + + assert not table_knife.states[Touching].get_value(half_apple) + assert cooked_diced_apple.n_particles == 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is not None + + table_knife.set_position_orientation( + position=[-0.05, 0.0, 0.065], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + + assert cooked_diced_apple.n_particles > 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Move the knife away so that it doesn't immediately dice the half_apple again once it's imported back + table_knife.set_position_orientation( + position=[-0.05, 0.0, 1.15], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_dicing_rule_uncooked(env, half_apple, table_knife): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + diced_apple = env.scene.get_system("diced__apple") + + deleted_objs = [half_apple] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + half_apple.set_orientation(T.euler2quat(th.tensor([0, -math.pi / 2, 0], dtype=th.float32))) + place_obj_on_floor_plane(half_apple) + og.sim.step() + + assert diced_apple.n_particles == 0 + + table_knife.set_position_orientation( + position=[-0.05, 0.0, 0.15], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + + assert not table_knife.states[Touching].get_value(half_apple) + assert diced_apple.n_particles == 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is not None + + table_knife.set_position_orientation( + position=[-0.05, 0.0, 0.065], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + + assert diced_apple.n_particles > 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Move the knife away so that it doesn't immediately dice the half_apple again once it's imported back + table_knife.set_position_orientation( + position=[-0.05, 0.0, 1.15], orientation=T.euler2quat(th.tensor([-math.pi / 2, 0, 0], dtype=th.float32)) + ) + og.sim.step() + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_melting_rule(env, stove, stockpot, swiss_cheese): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + melted_swiss_cheese = env.scene.get_system("melted__swiss_cheese") + + deleted_objs = [swiss_cheese] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + swiss_cheese.set_position_orientation(position=stockpot.aabb_center, orientation=[0, 0, 0, 1]) + og.sim.step() + assert swiss_cheese.states[Inside].get_value(stockpot) + + assert melted_swiss_cheese.n_particles == 0 + + # To save time, directly set the temperature of the swiss cheese to be below the melting point + assert swiss_cheese.states[Temperature].set_value(m.transition_rules.MELTING_TEMPERATURE - 1) + og.sim.step() + + assert melted_swiss_cheese.n_particles == 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is not None + + # To save time, directly set the temperature of the swiss cheese to be above the melting point + assert swiss_cheese.states[Temperature].set_value(m.transition_rules.MELTING_TEMPERATURE + 1) + og.sim.step() + + # Recipe should execute successfully: new melted swiss cheese should be created, and the ingredients should be deleted + assert melted_swiss_cheese.n_particles > 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_cooking_physical_particle_rule_failure_recipe_systems(env, stove, stockpot): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + brown_rice = env.scene.get_system("brown_rice") + water = env.scene.get_system("water") + cooked_water = env.scene.get_system("cooked__water") + cooked_brown_rice = env.scene.get_system("cooked__brown_rice") + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + brown_rice.generate_particles(positions=[(stockpot.aabb_center + th.tensor([0.03, 0.0, 0.0])).tolist()]) + # This fails the recipe because water (recipe system) is not in the stockpot + water.generate_particles(positions=[[-0.25, 0.17, 1.95]]) + + assert stockpot.states[Contains].get_value(brown_rice) + assert not stockpot.states[Contains].get_value(water) + + assert cooked_brown_rice.n_particles == 0 + + # To save time, directly set the stockpot to be heated + assert stockpot.states[Heated].set_value(True) + og.sim.step() + + # Recipe should fail: no cooked arborio rice should be created + assert water.n_particles > 0 + assert cooked_water.n_particles == 0 + assert brown_rice.n_particles > 0 + assert cooked_brown_rice.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_physical_particle_rule_success(env, stove, stockpot): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + brown_rice = env.scene.get_system("brown_rice") + water = env.scene.get_system("water") + cooked_water = env.scene.get_system("cooked__water") + cooked_brown_rice = env.scene.get_system("cooked__brown_rice") + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + brown_rice.generate_particles(positions=[(stockpot.aabb_center + th.tensor([0.03, 0.0, 0.0])).tolist()]) + water.generate_particles(positions=[(stockpot.aabb_center + th.tensor([-0.03, 0.0, 0.0])).tolist()]) + + assert stockpot.states[Contains].get_value(brown_rice) + assert stockpot.states[Contains].get_value(water) + + assert cooked_brown_rice.n_particles == 0 + assert cooked_water.n_particles == 0 + + # To save time, directly set the stockpot to be heated + assert stockpot.states[Heated].set_value(True) + og.sim.step() + + assert water.n_particles == 0 + assert cooked_water.n_particles > 0 + assert brown_rice.n_particles > 0 + assert cooked_brown_rice.n_particles == 0 + + # Recipe should execute successfully: new cooked arborio rice should be created, and the ingredients should be deleted + og.sim.step() + + assert water.n_particles == 0 + assert cooked_water.n_particles == 0 + assert brown_rice.n_particles == 0 + assert cooked_brown_rice.n_particles > 0 + + # Clean up + remove_all_systems(env.scene) + + +def test_mixing_rule_failure_recipe_systems(env, bowl, tablespoon): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + water = env.scene.get_system("water") + granulated_sugar = env.scene.get_system("granulated_sugar") + lemon_juice = env.scene.get_system("lemon_juice") + lemonade = env.scene.get_system("lemonade") + sludge = env.scene.get_system("sludge") + + place_obj_on_floor_plane(bowl) + og.sim.step() + + water.generate_particles(positions=[[-0.02, 0.0, 0.02]]) + granulated_sugar.generate_particles(positions=[[0.0, 0.0, 0.02]]) + # This fails the recipe because lemon juice (recipe system) is not in the bowl + lemon_juice.generate_particles(positions=[[0.02, 0.0, 1.02]]) + + assert bowl.states[Contains].get_value(water) + assert bowl.states[Contains].get_value(granulated_sugar) + assert not bowl.states[Contains].get_value(lemon_juice) + + assert lemonade.n_particles == 0 + assert sludge.n_particles == 0 + + # Move the tablespoon to touch the bowl + tablespoon.set_position_orientation( + position=[0.10, 0.0, 0.01], orientation=T.euler2quat(th.tensor([0.0, -math.pi / 2, 0.0])) + ) + og.sim.step() + tablespoon.keep_still() + tablespoon.set_linear_velocity(th.tensor([-1.0, 0.0, 0.0])) + for _ in range(3): + og.sim.step() + + assert tablespoon.states[Touching].get_value(bowl) + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert lemonade.n_particles == 0 + assert sludge.n_particles > 0 + assert water.n_particles == 0 + assert granulated_sugar.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + + +def test_mixing_rule_failure_nonrecipe_systems(env, bowl, tablespoon): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + water = env.scene.get_system("water") + granulated_sugar = env.scene.get_system("granulated_sugar") + lemon_juice = env.scene.get_system("lemon_juice") + lemonade = env.scene.get_system("lemonade") + salt = env.scene.get_system("salt") + sludge = env.scene.get_system("sludge") + + place_obj_on_floor_plane(bowl) + og.sim.step() + + water.generate_particles(positions=[[-0.02, 0, 0.02]]) + granulated_sugar.generate_particles(positions=[[0.0, 0.0, 0.02]]) + lemon_juice.generate_particles(positions=[[0.02, 0.0, 0.02]]) + # This fails the recipe because salt (nonrecipe system) is in the bowl + salt.generate_particles(positions=[[0.0, 0.02, 0.02]]) + + assert bowl.states[Contains].get_value(water) + assert bowl.states[Contains].get_value(granulated_sugar) + assert bowl.states[Contains].get_value(lemon_juice) + assert bowl.states[Contains].get_value(salt) + + assert lemonade.n_particles == 0 + assert sludge.n_particles == 0 + + # Move the tablespoon to touch the bowl + tablespoon.set_position_orientation( + position=[0.10, 0.0, 0.01], orientation=T.euler2quat(th.tensor([0.0, -math.pi / 2, 0.0])) + ) + og.sim.step() + tablespoon.keep_still() + tablespoon.set_linear_velocity(th.tensor([-1.0, 0.0, 0.0])) + for _ in range(3): + og.sim.step() + + assert tablespoon.states[Touching].get_value(bowl) + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert lemonade.n_particles == 0 + assert sludge.n_particles > 0 + assert water.n_particles == 0 + assert granulated_sugar.n_particles == 0 + assert lemon_juice.n_particles == 0 + assert salt.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + + +def test_mixing_rule_success(env, bowl, tablespoon): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + water = env.scene.get_system("water") + granulated_sugar = env.scene.get_system("granulated_sugar") + lemon_juice = env.scene.get_system("lemon_juice") + lemonade = env.scene.get_system("lemonade") + + place_obj_on_floor_plane(bowl) + og.sim.step() + + water.generate_particles(positions=[[-0.02, 0.0, 0.02]]) + granulated_sugar.generate_particles(positions=[[0.0, 0.0, 0.02]]) + lemon_juice.generate_particles(positions=[[0.02, 0.0, 0.02]]) + + assert bowl.states[Contains].get_value(water) + assert bowl.states[Contains].get_value(granulated_sugar) + assert bowl.states[Contains].get_value(lemon_juice) + + assert lemonade.n_particles == 0 + + # Move the tablespoon to touch the bowl + tablespoon.set_position_orientation( + position=[0.10, 0.0, 0.01], orientation=T.euler2quat(th.tensor([0.0, -math.pi / 2, 0.0])) + ) + og.sim.step() + tablespoon.keep_still() + tablespoon.set_linear_velocity(th.tensor([-1.0, 0.0, 0.0])) + for _ in range(3): + og.sim.step() + + assert tablespoon.states[Touching].get_value(bowl) + + # Recipe should execute successfully: new lemonade should be created, and the ingredients should be deleted + assert lemonade.n_particles > 0 + assert water.n_particles == 0 + assert granulated_sugar.n_particles == 0 + assert lemon_juice.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_system_rule_failure_recipe_systems(env, stove, stockpot, chicken): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + chicken_broth = env.scene.get_system("chicken_broth") + diced_carrot = env.scene.get_system("diced__carrot") + diced_celery = env.scene.get_system("diced__celery") + salt = env.scene.get_system("salt") + rosemary = env.scene.get_system("rosemary") + chicken_soup = env.scene.get_system("cooked__chicken_soup") + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + chicken.set_position_orientation(position=stockpot.aabb_center, orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + # This fails the recipe because chicken broth (recipe system) is not in the stockpot + chicken_broth.generate_particles(positions=[[-0.1, -0.22, 1.93]]) + diced_carrot.generate_particles(positions=[[-0.1, -0.24, 0.93]]) + diced_celery.generate_particles(positions=[[-0.1, -0.26, 0.93]]) + salt.generate_particles(positions=[[-0.1, -0.28, 0.93]]) + rosemary.generate_particles(positions=[[-0.1, -0.3, 0.93]]) + og.sim.step() + + assert chicken.states[Inside].get_value(stockpot) + assert not chicken.states[Cooked].get_value() + assert not stockpot.states[Contains].get_value(chicken_broth) + assert stockpot.states[Contains].get_value(diced_carrot) + assert stockpot.states[Contains].get_value(diced_celery) + assert stockpot.states[Contains].get_value(salt) + assert stockpot.states[Contains].get_value(rosemary) + + assert chicken_soup.n_particles == 0 + + assert stove.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no chicken soup should be created + assert chicken_soup.n_particles == 0 + assert chicken_broth.n_particles > 0 + assert diced_carrot.n_particles > 0 + assert diced_celery.n_particles > 0 + assert salt.n_particles > 0 + assert rosemary.n_particles > 0 + assert env.scene.object_registry("name", "chicken") is not None + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_system_rule_failure_nonrecipe_systems(env, stove, stockpot, chicken): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + water = env.scene.get_system("water") + chicken_broth = env.scene.get_system("chicken_broth") + diced_carrot = env.scene.get_system("diced__carrot") + diced_celery = env.scene.get_system("diced__celery") + salt = env.scene.get_system("salt") + rosemary = env.scene.get_system("rosemary") + chicken_soup = env.scene.get_system("cooked__chicken_soup") + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + chicken.set_position_orientation(position=stockpot.aabb_center, orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + # This fails the recipe because water (nonrecipe system) is inside the stockpot + water.generate_particles(positions=[[-0.1, -0.18, 0.93]]) + chicken_broth.generate_particles(positions=[[-0.1, -0.22, 0.93]]) + diced_carrot.generate_particles(positions=[[-0.1, -0.24, 0.93]]) + diced_celery.generate_particles(positions=[[-0.1, -0.26, 0.93]]) + salt.generate_particles(positions=[[-0.1, -0.28, 0.93]]) + rosemary.generate_particles(positions=[[-0.1, -0.3, 0.93]]) + og.sim.step() + + assert chicken.states[Inside].get_value(stockpot) + assert not chicken.states[Cooked].get_value() + assert stockpot.states[Contains].get_value(water) + assert stockpot.states[Contains].get_value(chicken_broth) + assert stockpot.states[Contains].get_value(diced_carrot) + assert stockpot.states[Contains].get_value(diced_celery) + assert stockpot.states[Contains].get_value(salt) + assert stockpot.states[Contains].get_value(rosemary) + + assert chicken_soup.n_particles == 0 + + assert stove.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no chicken soup should be created + assert chicken_soup.n_particles == 0 + assert chicken_broth.n_particles > 0 + assert diced_carrot.n_particles > 0 + assert diced_celery.n_particles > 0 + assert salt.n_particles > 0 + assert rosemary.n_particles > 0 + assert water.n_particles > 0 + assert env.scene.object_registry("name", "chicken") is not None + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_system_rule_failure_nonrecipe_objects(env, stove, stockpot, chicken, bowl): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + chicken_broth = env.scene.get_system("chicken_broth") + diced_carrot = env.scene.get_system("diced__carrot") + diced_celery = env.scene.get_system("diced__celery") + salt = env.scene.get_system("salt") + rosemary = env.scene.get_system("rosemary") + chicken_soup = env.scene.get_system("cooked__chicken_soup") + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + chicken.set_position_orientation(position=stockpot.aabb_center, orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + # This fails the recipe because the bowl (nonrecipe object) is inside the stockpot + bowl.set_position_orientation(position=[-0.1, -0.15, 1], orientation=[0, 0, 0, 1]) + chicken_broth.generate_particles(positions=[[-0.1, -0.22, 0.93]]) + diced_carrot.generate_particles(positions=[[-0.1, -0.24, 0.93]]) + diced_celery.generate_particles(positions=[[-0.1, -0.26, 0.93]]) + salt.generate_particles(positions=[[-0.1, -0.28, 0.93]]) + rosemary.generate_particles(positions=[[-0.1, -0.3, 0.93]]) + og.sim.step() + + assert chicken.states[Inside].get_value(stockpot) + assert bowl.states[Inside].get_value(stockpot) + assert not chicken.states[Cooked].get_value() + assert stockpot.states[Contains].get_value(chicken_broth) + assert stockpot.states[Contains].get_value(diced_carrot) + assert stockpot.states[Contains].get_value(diced_celery) + assert stockpot.states[Contains].get_value(salt) + assert stockpot.states[Contains].get_value(rosemary) + + assert chicken_soup.n_particles == 0 + + assert stove.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no chicken soup should be created + assert chicken_soup.n_particles == 0 + assert chicken_broth.n_particles > 0 + assert diced_carrot.n_particles > 0 + assert diced_celery.n_particles > 0 + assert salt.n_particles > 0 + assert rosemary.n_particles > 0 + assert env.scene.object_registry("name", "chicken") is not None + assert env.scene.object_registry("name", "bowl") is not None + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_system_rule_success(env, stove, stockpot, chicken): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + chicken_broth = env.scene.get_system("chicken_broth") + diced_carrot = env.scene.get_system("diced__carrot") + diced_celery = env.scene.get_system("diced__celery") + salt = env.scene.get_system("salt") + rosemary = env.scene.get_system("rosemary") + chicken_soup = env.scene.get_system("cooked__chicken_soup") + + deleted_objs = [chicken] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(stove) + og.sim.step() + + stockpot.set_position_orientation(position=[-0.1, -0.2, 0.89], orientation=[0, 0, 0, 1]) + og.sim.step() + assert stockpot.states[OnTop].get_value(stove) + + chicken.set_position_orientation(stockpot.aabb_center, [0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + chicken_broth.generate_particles(positions=[[-0.1, -0.22, 0.93]]) + diced_carrot.generate_particles(positions=[[-0.1, -0.24, 0.93]]) + diced_celery.generate_particles(positions=[[-0.1, -0.26, 0.93]]) + salt.generate_particles(positions=[[-0.1, -0.28, 0.93]]) + rosemary.generate_particles(positions=[[-0.1, -0.3, 0.93]]) + og.sim.step() + + assert chicken.states[Inside].get_value(stockpot) + assert not chicken.states[Cooked].get_value() + assert stockpot.states[Contains].get_value(chicken_broth) + assert stockpot.states[Contains].get_value(diced_carrot) + assert stockpot.states[Contains].get_value(diced_celery) + assert stockpot.states[Contains].get_value(salt) + assert stockpot.states[Contains].get_value(rosemary) + + assert chicken_soup.n_particles == 0 + + assert stove.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should execute successfully: new chicken soup should be created, and the ingredients should be deleted + assert chicken_soup.n_particles > 0 + assert chicken_broth.n_particles == 0 + assert diced_carrot.n_particles == 0 + assert diced_celery.n_particles == 0 + assert salt.n_particles == 0 + assert rosemary.n_particles == 0 + + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_cooking_object_rule_failure_wrong_container(env, oven, stockpot, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + place_obj_on_floor_plane(oven) + og.sim.step() + + # This fails the recipe because it requires the baking sheet to be inside the oven, not the stockpot + stockpot.set_position_orientation([0, 0, 0.487], [0, 0, 0, 1]) + for _ in range(10): + og.sim.step() + assert stockpot.states[Inside].get_value(oven) + + bagel_dough.set_position_orientation([0, 0, 0.464], [0, 0, 0, 1]) + raw_egg.set_position_orientation([0.02, 0, 0.506], [0, 0, 0, 1]) + for _ in range(10): + og.sim.step() + assert bagel_dough.states[Inside].get_value(stockpot) + assert raw_egg.states[OnTop].get_value(bagel_dough) + + assert bagel_dough.states[Cooked].set_value(False) + assert raw_egg.states[Cooked].set_value(False) + og.sim.step() + + assert bagel_dough.states[Covered].set_value(sesame_seed, True) + og.sim.step() + + assert oven.states[ToggledOn].set_value(True) + og.sim.step() + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + assert len(final_bagels) == len(initial_bagels) + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_object_rule_failure_recipe_objects(env, oven, baking_sheet, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + place_obj_on_floor_plane(oven) + og.sim.step() + + baking_sheet.set_position_orientation(position=[0.0, 0.05, 0.455], orientation=[0, 0, 0, 1]) + og.sim.step() + assert baking_sheet.states[Inside].get_value(oven) + + # This fails the recipe because it requires the bagel dough to be on top of the baking sheet + bagel_dough.set_position_orientation(position=[1, 0, 0.5], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[1.02, 0, 0.55], orientation=[0, 0, 0, 1]) + og.sim.step() + assert not bagel_dough.states[OnTop].get_value(baking_sheet) + + assert bagel_dough.states[Cooked].set_value(False) + assert raw_egg.states[Cooked].set_value(False) + og.sim.step() + + assert bagel_dough.states[Covered].set_value(sesame_seed, True) + og.sim.step() + + assert oven.states[ToggledOn].set_value(True) + og.sim.step() + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + assert len(final_bagels) == len(initial_bagels) + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_object_rule_failure_unary_states(env, oven, baking_sheet, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + place_obj_on_floor_plane(oven) + og.sim.step() + + baking_sheet.set_position_orientation(position=[0.0, 0.07, 0.42], orientation=[0, 0, 0, 1]) + for _ in range(5): + og.sim.step() + assert baking_sheet.states[Inside].get_value(oven) + + bagel_dough.set_position_orientation(position=[0.0, 0.07, 0.45], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[0.0, 0.07, 0.48], orientation=[0, 0, 0, 1]) + for _ in range(10): + og.sim.step() + assert bagel_dough.states[OnTop].get_value(baking_sheet) + assert raw_egg.states[OnTop].get_value(bagel_dough) + + # This fails the recipe because it requires the bagel dough and the raw egg to be not cooked + assert bagel_dough.states[Cooked].set_value(True) + assert raw_egg.states[Cooked].set_value(True) + og.sim.step() + + assert bagel_dough.states[Covered].set_value(sesame_seed, True) + og.sim.step() + + assert oven.states[ToggledOn].set_value(True) + og.sim.step() + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + assert len(final_bagels) == len(initial_bagels) + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_object_rule_failure_binary_system_states(env, oven, baking_sheet, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + place_obj_on_floor_plane(oven) + og.sim.step() + + baking_sheet.set_position_orientation(position=[0.0, 0.07, 0.42], orientation=[0, 0, 0, 1]) + for _ in range(5): + og.sim.step() + assert baking_sheet.states[Inside].get_value(oven) + + bagel_dough.set_position_orientation(position=[0.0, 0.07, 0.45], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[0.0, 0.07, 0.48], orientation=[0, 0, 0, 1]) + for _ in range(10): + og.sim.step() + assert bagel_dough.states[OnTop].get_value(baking_sheet) + assert raw_egg.states[OnTop].get_value(bagel_dough) + + assert bagel_dough.states[Cooked].set_value(False) + assert raw_egg.states[Cooked].set_value(False) + og.sim.step() + + # This fails the recipe because it requires the bagel dough to be covered with sesame seed + assert bagel_dough.states[Covered].set_value(sesame_seed, False) + og.sim.step() + + assert oven.states[ToggledOn].set_value(True) + og.sim.step() + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + assert len(final_bagels) == len(initial_bagels) + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_object_rule_failure_binary_object_states(env, oven, baking_sheet, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + place_obj_on_floor_plane(oven) + og.sim.step() + + baking_sheet.set_position_orientation(position=[0.0, 0.07, 0.42], orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + assert baking_sheet.states[Inside].get_value(oven) + + bagel_dough.set_position_orientation(position=[0.0, 0.07, 0.45], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[2.0, 0.07, 0.48], orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + assert bagel_dough.states[OnTop].get_value(baking_sheet) + # This fails the recipe because it requires the raw egg to be on top of the bagel dough + assert not raw_egg.states[OnTop].get_value(bagel_dough) + + assert bagel_dough.states[Cooked].set_value(False) + assert raw_egg.states[Cooked].set_value(False) + og.sim.step() + + assert bagel_dough.states[Covered].set_value(sesame_seed, True) + og.sim.step() + + assert oven.states[ToggledOn].set_value(True) + og.sim.step() + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + assert len(final_bagels) == len(initial_bagels) + + # Clean up + remove_all_systems(env.scene) + + +def test_cooking_object_rule_failure_wrong_heat_source(env, stove, baking_sheet, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + # This fails the recipe because it requires the oven to be the heat source, not the stove + place_obj_on_floor_plane(stove) + og.sim.step() + + # Check that the stove heat source link exists + stove.states[HeatSourceOrSink].link.get_position_orientation()[0] + + # Put the baking sheet on the stove + baking_sheet.set_position_orientation(position=[-0.1, -0.15, 0.80], orientation=[0, 0, 0, 1]) + og.sim.step() + + bagel_dough.set_position_orientation(position=[-0.1, -0.15, 0.84], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[-0.1, -0.15, 0.89], orientation=[0, 0, 0, 1]) + for _ in range(10): + og.sim.step() + assert bagel_dough.states[OnTop].get_value(baking_sheet) + assert raw_egg.states[OnTop].get_value(bagel_dough) + + assert bagel_dough.states[Cooked].set_value(True) + assert raw_egg.states[Cooked].set_value(True) + og.sim.step() + + assert bagel_dough.states[Covered].set_value(sesame_seed, True) + og.sim.step() + + assert stove.states[ToggledOn].set_value(True) + og.sim.step() + + # Make sure the stove affects the baking sheet + assert stove.states[HeatSourceOrSink].affects_obj(baking_sheet) + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + assert len(final_bagels) == len(initial_bagels) + + # Clean up + remove_all_systems(env.scene) + + +@pytest.mark.skip(reason="To be fixed as part of #2017.") +def test_cooking_object_rule_success(env, oven, baking_sheet, bagel_dough, raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + sesame_seed = env.scene.get_system("sesame_seed") + + deleted_objs = [bagel_dough, raw_egg] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + initial_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + place_obj_on_floor_plane(oven) + og.sim.step() + + baking_sheet.set_position_orientation(position=[0.0, 0.07, 0.42], orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + assert baking_sheet.states[Inside].get_value(oven) + + bagel_dough.set_position_orientation(position=[0.0, 0.07, 0.45], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[0.0, 0.07, 0.48], orientation=[0, 0, 0, 1]) + for _ in range(3): + og.sim.step() + assert bagel_dough.states[OnTop].get_value(baking_sheet) + assert raw_egg.states[OnTop].get_value(bagel_dough) + + assert bagel_dough.states[Cooked].set_value(False) + assert raw_egg.states[Cooked].set_value(False) + og.sim.step() + + assert bagel_dough.states[Covered].set_value(sesame_seed, True) + og.sim.step() + + assert oven.states[ToggledOn].set_value(True) + og.sim.step() + + final_bagels = env.scene.object_registry("category", "bagel", set()).copy() + + # Recipe should execute successfully: new bagels should be created, and the ingredients should be deleted + assert len(final_bagels) > len(initial_bagels) + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Need to step again for the new bagels to be initialized, placed in the container, and cooked. + og.sim.step() + + # All new bagels should be cooked + new_bagels = final_bagels - initial_bagels + for bagel in new_bagels: + assert bagel.states[Cooked].get_value() + # This assertion occasionally fails, because when four bagels are sampled on top of the baking sheet one by one, + # there is no guarantee that all four of them will be on top of the baking sheet at the end. + assert ( + bagel.states[OnTop].get_value(baking_sheet) + or bagel.states[Inside].get_value(oven) + or bagel.states[Touching].get_value(baking_sheet) + or bagel.states[Touching].get_value(oven) + ) + + # Clean up + remove_all_systems(env.scene) + + for bagel in new_bagels: + env.scene.remove_object(bagel) + og.sim.step() + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +@pytest.mark.skip(reason="To be fixed as part of #2017.") +def test_single_toggleable_machine_rule_output_system_failure_wrong_container(env, food_processor, scoop_of_ice_cream): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + ice_cream = env.scene.object_registry("name", "scoop_of_ice_cream") + milk = env.scene.get_system("whole_milk") + chocolate_sauce = env.scene.get_system("chocolate_sauce") + milkshake = env.scene.get_system("milkshake") + sludge = env.scene.get_system("sludge") + + deleted_objs = [ice_cream] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + # This fails the recipe because it requires the blender to be the container, not the food processor + place_obj_on_floor_plane(food_processor) + og.sim.step() + + milk.generate_particles(positions=th.tensor([[0.02, 0.06, 0.22]])) + chocolate_sauce.generate_particles(positions=th.tensor([[-0.05, -0.04, 0.22]])) + ice_cream.set_position_orientation(position=[0.03, -0.02, 0.23], orientation=[0, 0, 0, 1]) + + og.sim.step() + + assert food_processor.states[Contains].get_value(milk) + assert food_processor.states[Contains].get_value(chocolate_sauce) + assert ice_cream.states[Inside].get_value(food_processor) + + assert milkshake.n_particles == 0 + assert sludge.n_particles == 0 + + food_processor.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert milkshake.n_particles == 0 + assert sludge.n_particles > 0 + assert milk.n_particles == 0 + assert chocolate_sauce.n_particles == 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_single_toggleable_machine_rule_output_system_failure_recipe_systems(env, blender, scoop_of_ice_cream): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + ice_cream = env.scene.object_registry("name", "scoop_of_ice_cream") + milk = env.scene.get_system("whole_milk") + chocolate_sauce = env.scene.get_system("chocolate_sauce") + milkshake = env.scene.get_system("milkshake") + sludge = env.scene.get_system("sludge") + + deleted_objs = [ice_cream] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(blender) + og.sim.step() + + # This fails the recipe because it requires the milk to be in the blender + milk.generate_particles(positions=th.tensor([[0.02, 0, 1.57]], dtype=th.float32)) + chocolate_sauce.generate_particles(positions=th.tensor([[0, -0.02, 0.57]], dtype=th.float32)) + ice_cream.set_position_orientation(position=[0, 0, 0.51], orientation=[0, 0, 0, 1]) + og.sim.step() + + assert not blender.states[Contains].get_value(milk) + assert blender.states[Contains].get_value(chocolate_sauce) + assert ice_cream.states[Inside].get_value(blender) + + assert milkshake.n_particles == 0 + assert sludge.n_particles == 0 + + blender.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert milkshake.n_particles == 0 + assert sludge.n_particles > 0 + assert chocolate_sauce.n_particles == 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_single_toggleable_machine_rule_output_system_failure_recipe_objects(env, blender, scoop_of_ice_cream): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + ice_cream = env.scene.object_registry("name", "scoop_of_ice_cream") + milk = env.scene.get_system("whole_milk") + chocolate_sauce = env.scene.get_system("chocolate_sauce") + milkshake = env.scene.get_system("milkshake") + sludge = env.scene.get_system("sludge") + + place_obj_on_floor_plane(blender) + og.sim.step() + + milk.generate_particles(positions=th.tensor([[0.02, 0, 0.57]])) + chocolate_sauce.generate_particles(positions=th.tensor([[0, -0.02, 0.57]])) + # This fails the recipe because it requires the ice cream to be inside the blender + ice_cream.set_position_orientation(position=[0, 0, 1.51], orientation=[0, 0, 0, 1]) + + og.sim.step() + + assert blender.states[Contains].get_value(milk) + assert blender.states[Contains].get_value(chocolate_sauce) + assert not ice_cream.states[Inside].get_value(blender) + + assert milkshake.n_particles == 0 + assert sludge.n_particles == 0 + + blender.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert milkshake.n_particles == 0 + assert sludge.n_particles > 0 + assert milk.n_particles == 0 + assert chocolate_sauce.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + + +def test_single_toggleable_machine_rule_output_system_failure_nonrecipe_systems(env, blender, scoop_of_ice_cream): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + ice_cream = env.scene.object_registry("name", "scoop_of_ice_cream") + milk = env.scene.get_system("whole_milk") + chocolate_sauce = env.scene.get_system("chocolate_sauce") + milkshake = env.scene.get_system("milkshake") + sludge = env.scene.get_system("sludge") + water = env.scene.get_system("water") + + deleted_objs = [ice_cream] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(blender) + og.sim.step() + + milk.generate_particles(positions=th.tensor([[0.02, 0, 0.57]])) + chocolate_sauce.generate_particles(positions=th.tensor([[0, -0.02, 0.57]])) + # This fails the recipe because water (nonrecipe system) is in the blender + water.generate_particles(positions=th.tensor([[0, 0, 0.57]])) + ice_cream.set_position_orientation(position=[0, 0, 0.51], orientation=[0, 0, 0, 1]) + + og.sim.step() + + assert blender.states[Contains].get_value(milk) + assert blender.states[Contains].get_value(chocolate_sauce) + assert blender.states[Contains].get_value(water) + assert ice_cream.states[Inside].get_value(blender) + + assert milkshake.n_particles == 0 + assert sludge.n_particles == 0 + + blender.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert milkshake.n_particles == 0 + assert sludge.n_particles > 0 + assert milk.n_particles == 0 + assert chocolate_sauce.n_particles == 0 + assert water.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_single_toggleable_machine_rule_output_system_failure_nonrecipe_objects(env, blender, scoop_of_ice_cream, bowl): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + ice_cream = env.scene.object_registry("name", "scoop_of_ice_cream") + milk = env.scene.get_system("whole_milk") + chocolate_sauce = env.scene.get_system("chocolate_sauce") + milkshake = env.scene.get_system("milkshake") + sludge = env.scene.get_system("sludge") + + deleted_objs = [ice_cream, bowl] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(blender) + og.sim.step() + + milk.generate_particles(positions=th.tensor([[0.02, 0, 0.57]])) + chocolate_sauce.generate_particles(positions=th.tensor([[0, -0.02, 0.57]])) + ice_cream.set_position_orientation(position=[0, 0, 0.51], orientation=[0, 0, 0, 1]) + # This fails the recipe because the bowl (nonrecipe object) is in the blender + bowl.set_position_orientation(position=[0, 0, 0.58], orientation=[0, 0, 0, 1]) + + og.sim.step() + + assert blender.states[Contains].get_value(milk) + assert blender.states[Contains].get_value(chocolate_sauce) + assert ice_cream.states[Inside].get_value(blender) + assert bowl.states[Inside].get_value(blender) + + assert milkshake.n_particles == 0 + assert sludge.n_particles == 0 + + blender.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no milkshake should be created, and sludge should be created. + assert milkshake.n_particles == 0 + assert sludge.n_particles > 0 + assert milk.n_particles == 0 + assert chocolate_sauce.n_particles == 0 + + # Clean up + remove_all_systems(env.scene) + # Spawning the bowl in the blender's location causes PhysX to crash, + # resulting in "Invalid PhysX transform detected" errors. To avoid this, we temporarily move the blender aside. + blender.set_position_orientation( + position=blender.get_position_orientation()[0] + th.tensor([1.0, 0.0, 0.0], dtype=th.float32) + ) + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_single_toggleable_machine_rule_output_system_success(env, blender, scoop_of_ice_cream): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + ice_cream = env.scene.object_registry("name", "scoop_of_ice_cream") + milk = env.scene.get_system("whole_milk") + chocolate_sauce = env.scene.get_system("chocolate_sauce") + milkshake = env.scene.get_system("milkshake") + sludge = env.scene.get_system("sludge") + + deleted_objs = [ice_cream] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(blender) + og.sim.step() + + milk.generate_particles(positions=th.tensor([[0.02, 0, 0.57]])) + chocolate_sauce.generate_particles(positions=th.tensor([[0, -0.02, 0.57]])) + ice_cream.set_position_orientation(position=[0, 0, 0.51], orientation=[0, 0, 0, 1]) + + og.sim.step() + + assert blender.states[Contains].get_value(milk) + assert blender.states[Contains].get_value(chocolate_sauce) + assert ice_cream.states[Inside].get_value(blender) + + assert milkshake.n_particles == 0 + assert sludge.n_particles == 0 + + blender.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should execute successfully: new milkshake should be created, and the ingredients should be deleted + assert milkshake.n_particles > 0 + assert sludge.n_particles == 0 + assert milk.n_particles == 0 + assert chocolate_sauce.n_particles == 0 + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_single_toggleable_machine_rule_output_object_failure_unary_states( + env, electric_mixer, raw_egg, another_raw_egg +): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + flour = env.scene.get_system("flour") + granulated_sugar = env.scene.get_system("granulated_sugar") + vanilla = env.scene.get_system("vanilla") + melted_butter = env.scene.get_system("melted__butter") + baking_powder = env.scene.get_system("baking_powder") + salt = env.scene.get_system("salt") + sludge = env.scene.get_system("sludge") + + initial_doughs = env.scene.object_registry("category", "sugar_cookie_dough", set()).copy() + + deleted_objs = [raw_egg, another_raw_egg] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(electric_mixer) + og.sim.step() + + another_raw_egg.set_position_orientation(position=[-0.01, -0.14, 0.47], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[-0.01, -0.14, 0.45], orientation=[0, 0, 0, 1]) + flour.generate_particles(positions=th.tensor([[-0.01, -0.15, 0.43]])) + granulated_sugar.generate_particles(positions=th.tensor([[0.01, -0.15, 0.43]])) + vanilla.generate_particles(positions=th.tensor([[0.03, -0.15, 0.43]])) + melted_butter.generate_particles(positions=th.tensor([[-0.01, -0.13, 0.43]])) + baking_powder.generate_particles(positions=th.tensor([[0.01, -0.13, 0.43]])) + salt.generate_particles(positions=th.tensor([[0.03, -0.13, 0.43]])) + # This fails the recipe because the egg should not be cooked + raw_egg.states[Cooked].set_value(True) + og.sim.step() + + assert electric_mixer.states[Contains].get_value(flour) + assert electric_mixer.states[Contains].get_value(granulated_sugar) + assert electric_mixer.states[Contains].get_value(vanilla) + assert electric_mixer.states[Contains].get_value(melted_butter) + assert electric_mixer.states[Contains].get_value(baking_powder) + assert electric_mixer.states[Contains].get_value(salt) + assert raw_egg.states[Inside].get_value(electric_mixer) + assert raw_egg.states[Cooked].get_value() + assert another_raw_egg.states[Inside].get_value(electric_mixer) + assert not another_raw_egg.states[Cooked].get_value() + + assert sludge.n_particles == 0 + + electric_mixer.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should fail: no dough should be created, and sludge should be created. + final_doughs = env.scene.object_registry("category", "sugar_cookie_dough", set()).copy() + + # Recipe should execute successfully: new dough should be created, and the ingredients should be deleted + assert len(final_doughs) == len(initial_doughs) + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + assert flour.n_particles == 0 + assert granulated_sugar.n_particles == 0 + assert vanilla.n_particles == 0 + assert melted_butter.n_particles == 0 + assert baking_powder.n_particles == 0 + assert salt.n_particles == 0 + assert sludge.n_particles > 0 + + # Clean up + remove_all_systems(env.scene) + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() + + +def test_single_toggleable_machine_rule_output_object_success(env, electric_mixer, raw_egg, another_raw_egg): + assert len(REGISTERED_RULES) > 0, "No rules registered!" + flour = env.scene.get_system("flour") + granulated_sugar = env.scene.get_system("granulated_sugar") + vanilla = env.scene.get_system("vanilla") + melted_butter = env.scene.get_system("melted__butter") + baking_powder = env.scene.get_system("baking_powder") + salt = env.scene.get_system("salt") + sludge = env.scene.get_system("sludge") + + initial_doughs = env.scene.object_registry("category", "sugar_cookie_dough", set()).copy() + + deleted_objs = [raw_egg, another_raw_egg] + deleted_objs_cfg = [retrieve_obj_cfg(obj) for obj in deleted_objs] + + place_obj_on_floor_plane(electric_mixer) + og.sim.step() + + another_raw_egg.set_position_orientation(position=[-0.01, -0.14, 0.47], orientation=[0, 0, 0, 1]) + raw_egg.set_position_orientation(position=[-0.01, -0.14, 0.45], orientation=[0, 0, 0, 1]) + flour.generate_particles(positions=th.tensor([[-0.01, -0.15, 0.43]])) + granulated_sugar.generate_particles(positions=th.tensor([[0.01, -0.15, 0.43]])) + vanilla.generate_particles(positions=th.tensor([[0.03, -0.15, 0.43]])) + melted_butter.generate_particles(positions=th.tensor([[-0.01, -0.13, 0.43]])) + baking_powder.generate_particles(positions=th.tensor([[0.01, -0.13, 0.43]])) + salt.generate_particles(positions=th.tensor([[0.03, -0.13, 0.43]])) + + og.sim.step() + + assert electric_mixer.states[Contains].get_value(flour) + assert electric_mixer.states[Contains].get_value(granulated_sugar) + assert electric_mixer.states[Contains].get_value(vanilla) + assert electric_mixer.states[Contains].get_value(melted_butter) + assert electric_mixer.states[Contains].get_value(baking_powder) + assert electric_mixer.states[Contains].get_value(salt) + assert raw_egg.states[Inside].get_value(electric_mixer) + assert not raw_egg.states[Cooked].get_value() + assert another_raw_egg.states[Inside].get_value(electric_mixer) + assert not another_raw_egg.states[Cooked].get_value() + + assert sludge.n_particles == 0 + + electric_mixer.states[ToggledOn].set_value(True) + og.sim.step() + + # Recipe should execute successfully: new dough should be created, and the ingredients should be deleted + final_doughs = env.scene.object_registry("category", "sugar_cookie_dough", set()).copy() + + # Recipe should execute successfully: new dough should be created, and the ingredients should be deleted + assert len(final_doughs) > len(initial_doughs) + for obj in deleted_objs: + assert env.scene.object_registry("name", obj.name) is None + assert flour.n_particles == 0 + assert granulated_sugar.n_particles == 0 + assert vanilla.n_particles == 0 + assert melted_butter.n_particles == 0 + assert baking_powder.n_particles == 0 + assert salt.n_particles == 0 + + # Need to step again for the new dough to be initialized, placed in the container, and cooked. + og.sim.step() + + # All new doughs should not be cooked + new_doughs = final_doughs - initial_doughs + for dough in new_doughs: + assert not dough.states[Cooked].get_value() + assert dough.states[OnTop].get_value(electric_mixer) + + # Clean up + for dough in new_doughs: + env.scene.remove_object(dough) + og.sim.step() + + for obj_cfg in deleted_objs_cfg: + obj = DatasetObject(**obj_cfg) + env.scene.add_object(obj) + og.sim.step() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/update_example_tests.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/update_example_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..f004bc3b5534d6458aa5f9f47bc28616e7fd18f3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/update_example_tests.py @@ -0,0 +1,133 @@ +""" +Updates the example test list in test_examples.py and tests.yml to match the +current set of examples in omnigibson/examples/. + +Run this script whenever examples are added or removed: + python tests/update_example_tests.py + +In CI, run with --check to fail if the files would change: + python tests/update_example_tests.py --check +""" + +import argparse +import pkgutil +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).parent.parent.parent +OMNIGIBSON_ROOT = Path(__file__).parent.parent +TEST_EXAMPLES_PY = Path(__file__).parent / "test_examples.py" +TESTS_YML = REPO_ROOT / ".github" / "workflows" / "tests.yml" + +# Markers used to delimit the auto-generated sections +EXAMPLES_START = " # --- BEGIN AUTO-GENERATED EXAMPLES ---" +EXAMPLES_END = " # --- END AUTO-GENERATED EXAMPLES ---" +INCLUDE_START = "# --- BEGIN AUTO-GENERATED EXAMPLE INCLUDES ---" +INCLUDE_END = "# --- END AUTO-GENERATED EXAMPLE INCLUDES ---" + + +def discover_examples(): + """Return sorted list of all example module names (e.g. 'objects.draw_bounding_box').""" + sys.path.insert(0, str(OMNIGIBSON_ROOT)) + from omnigibson import examples + + prefix = examples.__name__ + "." + return sorted(p.name[len(prefix) :] for p in pkgutil.walk_packages(examples.__path__, prefix) if not p.ispkg) + + +def get_skip_list(content): + """Parse EXAMPLES_TO_SKIP list from test_examples.py source.""" + match = re.search(r"EXAMPLES_TO_SKIP\s*=\s*\[([^\]]*)\]", content, re.DOTALL) + if not match: + return set() + return set(re.findall(r'"([\w.]+)"', match.group(1))) + + +def generate_examples_list(examples, skip_list): + """Generate content between (and including) the marker lines.""" + lines = [EXAMPLES_START] + for name in examples: + if name not in skip_list: + lines.append(f' "{name}",') + lines.append(EXAMPLES_END) + return "\n".join(lines) + + +# Per-example extra args passed via --test-args when running in CI. +# Add entries here for examples that require CLI arguments (e.g. click-based tools). +EXAMPLE_ARGS = { + "robots.import_custom_robot": "--config tests/data/r1_pro_source_config.yaml", +} + + +def generate_yml_includes(examples, skip_list): + """Generate the matrix include entries for test_examples.""" + lines = [f" {INCLUDE_START}"] + for name in examples: + if name not in skip_list: + if name in EXAMPLE_ARGS: + lines.append( + f' - {{test_file: test_examples, example: "{name}", args: "{EXAMPLE_ARGS[name]}"}}' + ) + else: + lines.append(f' - {{test_file: test_examples, example: "{name}"}}') + lines.append(f" {INCLUDE_END}") + return "\n".join(lines) + + +def replace_section(content, start_marker, end_marker, new_block): + """Replace from the start marker line to the end marker line (inclusive).""" + pattern = re.compile( + rf"^[^\n]*{re.escape(start_marker)}[^\n]*$.*?^[^\n]*{re.escape(end_marker)}[^\n]*$", + re.MULTILINE | re.DOTALL, + ) + if not pattern.search(content): + raise ValueError(f"Could not find markers '{start_marker}' / '{end_marker}'") + return pattern.sub(new_block, content) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true", help="Exit with error if files would change") + args = parser.parse_args() + + all_examples = discover_examples() + + # --- Update test_examples.py --- + py_content = TEST_EXAMPLES_PY.read_text() + skip_list = get_skip_list(py_content) + + new_examples_block = generate_examples_list(all_examples, skip_list) + new_py_content = replace_section(py_content, EXAMPLES_START, EXAMPLES_END, new_examples_block) + + # --- Update tests.yml --- + yml_content = TESTS_YML.read_text() + new_includes = generate_yml_includes(all_examples, skip_list) + new_yml_content = replace_section(yml_content, INCLUDE_START, INCLUDE_END, new_includes) + + if args.check: + changed = [] + if new_py_content != py_content: + changed.append(str(TEST_EXAMPLES_PY.relative_to(REPO_ROOT))) + if new_yml_content != yml_content: + changed.append(str(TESTS_YML.relative_to(REPO_ROOT))) + if changed: + print("The following files are out of date. Run `python tests/update_example_tests.py` to fix:") + for f in changed: + print(f" {f}") + sys.exit(1) + else: + print("Example test lists are up to date.") + else: + TEST_EXAMPLES_PY.write_text(new_py_content) + TESTS_YML.write_text(new_yml_content) + print(f"Updated {TEST_EXAMPLES_PY.relative_to(REPO_ROOT)}") + print(f"Updated {TESTS_YML.relative_to(REPO_ROOT)}") + skipped = [e for e in all_examples if e in skip_list] + included = [e for e in all_examples if e not in skip_list] + print(f" {len(included)} examples included, {len(skipped)} skipped") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/utils.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2795b9cc3757a68b89f07247b5cf5318589c0a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/tests/utils.py @@ -0,0 +1,244 @@ +import math + +import torch as th + +import omnigibson as og +import omnigibson.utils.transform_utils as T +from omnigibson.macros import gm +from omnigibson.systems import FluidSystem, GranularSystem, MacroPhysicalParticleSystem, MacroVisualParticleSystem +from omnigibson.utils.constants import PrimType + +SYSTEM_EXAMPLES = { + "water": FluidSystem, + "white_rice": GranularSystem, + "diced__apple": MacroPhysicalParticleSystem, + "stain": MacroVisualParticleSystem, +} + + +def retrieve_obj_cfg(obj): + return { + "name": obj.name, + "category": obj.category, + "model": obj.model, + "prim_type": obj.prim_type, + "position": obj.get_position_orientation()[0], + "scale": obj.scale, + "abilities": obj.abilities, + "visual_only": obj.visual_only, + } + + +def get_random_pose(pos_low=10.0, pos_hi=20.0): + pos = th.rand(3) * (pos_hi - pos_low) + pos_low + ori_lo, ori_hi = -math.pi, math.pi + orn = T.euler2quat(th.rand(3) * (ori_hi - ori_lo) + ori_lo) + return pos, orn + + +def place_objA_on_objB_bbox(objA, objB, x_offset=0.0, y_offset=0.0, z_offset=0.001): + objA.keep_still() + objB.keep_still() + # Reset pose if cloth object + if objA.prim_type == PrimType.CLOTH: + objA.root_link.reset() + + objA_aabb_center, objA_aabb_extent = objA.aabb_center, objA.aabb_extent + objB_aabb_center, objB_aabb_extent = objB.aabb_center, objB.aabb_extent + objA_aabb_offset = objA.get_position_orientation()[0] - objA_aabb_center + + target_objA_aabb_pos = ( + objB_aabb_center + + th.tensor([0, 0, (objB_aabb_extent[2] + objA_aabb_extent[2]) / 2.0]) + + th.tensor([x_offset, y_offset, z_offset]) + ) + objA.set_position_orientation(position=target_objA_aabb_pos + objA_aabb_offset) + + +def place_obj_on_floor_plane(obj, x_offset=0.0, y_offset=0.0, z_offset=0.01): + obj.keep_still() + # Reset pose if cloth object + if obj.prim_type == PrimType.CLOTH: + obj.root_link.reset() + + obj_aabb_center, obj_aabb_extent = obj.aabb_center, obj.aabb_extent + obj_aabb_offset = obj.get_position_orientation()[0] - obj_aabb_center + + target_obj_aabb_pos = th.tensor([0, 0, obj_aabb_extent[2] / 2.0]) + th.tensor([x_offset, y_offset, z_offset]) + obj.set_position_orientation(position=target_obj_aabb_pos + obj_aabb_offset) + + +def remove_all_systems(scene): + for system in scene.active_systems.values(): + system.remove_all_particles() + og.sim.step() + + +# --------------------------------------------------------------------------- +# Shared helpers for test_multiple_envs_*.py +# --------------------------------------------------------------------------- + +MULTI_ENV_ROBOTS = ["fetch", "tiago", "r1", "r1pro"] + +MULTI_ENV_TASK_TYPES = ["DummyTask", "PointNavigationTask", "PointReachingTask", "GraspTask"] + +GRASP_OBJECTS_CFG = [ + { + "type": "PrimitiveObject", + "name": "grasp_obj", + "primitive_type": "Cube", + "rgba": [1.0, 0, 0, 1.0], + "scale": [0.04, 0.04, 0.04], + "mass": 0.1, + "position": [0.5, 0.0, 0.55], + } +] + +ROBOT_JOINT_COUNTS = {"fetch": 8, "tiago": 8, "r1": 10, "r1pro": 11} + + +def _grasp_reset_pose_path(robot): + """Create a temporary precached reset pose file sized for the given robot.""" + import json + import tempfile + + n_joints = ROBOT_JOINT_COUNTS[robot] + reset_poses = [{"joint_pos": [0.0] * n_joints, "base_pos": [0.0, 0.0, 0.0], "base_ori": [0.0, 0.0, 0.0, 1.0]}] + f = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) + json.dump(reset_poses, f) + f.close() + return f.name + + +def multi_env_task_cfg(task_type, robot="fetch"): + """Return the task config dict for a given task type string.""" + if task_type == "GraspTask": + return { + "type": "GraspTask", + "obj_name": "grasp_obj", + "objects_config": GRASP_OBJECTS_CFG, + "termination_config": {"max_steps": 10}, + "precached_reset_pose_path": _grasp_reset_pose_path(robot), + } + return {"type": task_type} + + +def _init_multi_env_macros(): + """Set simulator macros (only once, before first Environment is created).""" + if og.sim is None: + gm.RENDER_VIEWER_CAMERA = False + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = True + gm.ENABLE_FLATCACHE = False + gm.ENABLE_TRANSITION_RULES = False + else: + og.sim.stop() + + +# --------------------------------------------------------------------------- +# Map of the test_multiple_envs_* suites +# +# Two axes: which task backs the env, and what is under test. +# +# | DummyTask (minimal env) | BehaviorTask (real task) +# ------------------|--------------------------------|----------------------------------- +# env contract | test_multiple_envs_dummy_api | (covered by dummy_api -- the +# | | vectorized Environment contract +# | | is task-independent) +# world / frames | test_multiple_envs_dummy_scene | test_multiple_envs_behavior_scene +# task semantics | -- | test_multiple_envs_behavior_task +# +# _api -> the vectorized Environment contract: construction, step/reset return shapes, +# selective reset, per-env counters, scene layout. +# _scene -> the world: scene placement, frame conversions, robot getters/setters, dump/load. +# +# Cross-cutting suites, one per concern rather than one per task: +# test_multiple_envs_task_tensors -- the (num_envs,) reward/done/success contract, parametrized +# over MULTI_ENV_TASK_TYPES +# test_multiple_envs_point_tasks -- PointNavigationTask + PointReachingTask goal behavior +# test_multiple_envs_grasp -- GraspTask specifics +# test_multiple_envs_heat_* -- temperature / heat-source states (need their own process) +# test_multiple_envs_transition_rules -- needs gm.ENABLE_TRANSITION_RULES=True, so it cannot +# share a process with the others (macros lock once read) +# --------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- +# Shared BehaviorTask multi-env setup +# +# test_multiple_envs_behavior_{infra_api,infra_scene,task}.py all exercise the *same* BehaviorTask +# environment (same scene, robot, activity and macros), and loading it is by far the dominant cost of +# those suites. The config and the loader live here so that a single env can be shared across all +# three files when they run in one pytest invocation (see the `behavior_env` fixture in conftest.py +# and the combined entry in .github/workflows/tests.yml). +# --------------------------------------------------------------------------- +BEHAVIOR_NUM_ENVS = 2 +BEHAVIOR_ACTIVITY_NAME = "picking_up_trash" +BEHAVIOR_SCENE_MODEL = "house_double_floor_lower" +BEHAVIOR_R_POTENTIAL = 1.0 + + +def _init_behavior_env_macros(): + """Set simulator macros (only once, before the first Environment is created).""" + if og.sim is None: + gm.RENDER_VIEWER_CAMERA = False + gm.ENABLE_OBJECT_STATES = True + gm.USE_GPU_DYNAMICS = False + gm.ENABLE_FLATCACHE = False + gm.ENABLE_TRANSITION_RULES = False + else: + og.sim.stop() + + +def setup_behavior_environment(num_envs=BEHAVIOR_NUM_ENVS, use_presampled_robot_pose=True): + """Create an Environment with BehaviorTask and R1Pro.""" + _init_behavior_env_macros() + cfg = { + "env": {"num_envs": num_envs}, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": BEHAVIOR_SCENE_MODEL, + "load_room_types": ["living_room", "kitchen"], + }, + "robots": [{"model": "r1pro", "obs_modalities": []}], + "task": { + "type": "BehaviorTask", + "activity_name": BEHAVIOR_ACTIVITY_NAME, + "activity_definition_id": 0, + "activity_instance_id": 0, + "online_object_sampling": False, + "use_presampled_robot_pose": use_presampled_robot_pose, + "termination_config": {"max_steps": 500}, + "reward_config": {"r_potential": BEHAVIOR_R_POTENTIAL}, + }, + } + print( + f" Setting up BehaviorTask env: num_envs={num_envs}, robot=r1pro, " + f"activity={BEHAVIOR_ACTIVITY_NAME}, presampled_pose={use_presampled_robot_pose}" + ) + env = og.Environment(configs=cfg) + print(" BehaviorTask environment created successfully") + return env + + +def setup_multi_environment(num_envs, robot="fetch", task_type="DummyTask", additional_objects_cfg=None): + """Create an Environment with *num_envs* cloned scenes.""" + _init_multi_env_macros() + + cfg = { + "env": {"num_envs": num_envs}, + "scene": { + "type": "InteractiveTraversableScene", + "scene_model": "Rs_int", + "load_object_categories": ["floors", "walls"], + }, + "robots": [{"model": robot, "obs_modalities": []}], + "task": multi_env_task_cfg(task_type, robot=robot), + } + if additional_objects_cfg: + cfg["objects"] = additional_objects_cfg + + print(f" Setting up env: num_envs={num_envs}, robot={robot}, task={task_type}") + env = og.Environment(configs=cfg) + print(" Environment created successfully") + return env diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/README.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c35855e6d6e6684b780535bd6e338cbc3f2c0d07 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/README.md @@ -0,0 +1,24 @@ +

BEHAVIOR-1K

+ +![BEHAVIOR-1K](./docs/assets/readme_splash_logo.png) + +**BEHAVIOR-1K** is a comprehensive simulation benchmark for testing embodied AI agents on 1,000 everyday household activities. This monolithic repository provides everything needed to train and evaluate agents on human-centered tasks like cleaning, cooking, and organizing — activities selected from real human time-use surveys and preference studies. + +***Check out our [main website](https://behavior.stanford.edu/) for more details!*** + +# 🛠️ Installation + +BEHAVIOR-1K provides an installation script that handles all dependencies and components. The script supports modular installation, allowing you to install only the components you need. + +Please check out [Installation Guide](https://behavior.stanford.edu/getting_started/installation.html) for more details! + +## 📄 Citation + +```bibtex +@article{li2024behavior1k, + title = {BEHAVIOR-1K: A Human-Centered, Embodied AI Benchmark with 1,000 Everyday Activities and Realistic Simulation}, + author = {Chengshu Li and Ruohan Zhang and Josiah Wong and Cem Gokmen and Sanjana Srivastava and Roberto Martín-Martín and Chen Wang and Gabrael Levine and Wensi Ai and Benjamin Martinez and Hang Yin and Michael Lingelbach and Minjune Hwang and Ayano Hiranaka and Sujay Garlanka and Arman Aydin and Sharon Lee and Jiankai Sun and Mona Anvari and Manasi Sharma and Dhruva Bansal and Samuel Hunter and Kyu-Young Kim and Alan Lou and Caleb R Matthews and Ivan Villa-Renteria and Jerry Huayang Tang and Claire Tang and Fei Xia and Yunzhu Li and Silvio Savarese and Hyowon Gweon and C. Karen Liu and Jiajun Wu and Li Fei-Fei}, + journal = {arXiv preprint arXiv:2403.09227}, + year = {2024} +} +``` diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dockerignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..02e19731150f96aefdd90ded5b6d256d3cf367be --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dockerignore @@ -0,0 +1,4 @@ +.git +.dvc +cad +artifacts diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvc/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvc/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..528f30c71c687de473bbb506c071e902beba6cd9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvc/.gitignore @@ -0,0 +1,3 @@ +/config.local +/tmp +/cache diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvc/config b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvc/config new file mode 100644 index 0000000000000000000000000000000000000000..60ea58b6eb998dcbe5213809b47dd7f55510b987 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvc/config @@ -0,0 +1,8 @@ +[core] + remote = google + autostage = true + hardlink_lock = false +[cache] + type = symlink +['remote "google"'] + url = gs://ig-pipeline-cache diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvcignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvcignore new file mode 100644 index 0000000000000000000000000000000000000000..51973055237895f2d23e65e015793fd302f4b9da --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.dvcignore @@ -0,0 +1,3 @@ +# Add patterns of files dvc should ignore, which could improve +# the performance. Learn more at +# https://dvc.org/doc/user-guide/dvcignore diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.gitattributes b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..c4cff1bc1197bf7940c129058e253173c8895336 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.gitattributes @@ -0,0 +1,6 @@ +*.dvc merge=dvc +*.json eol=lf +*.py eol=lf +*.yaml eol=lf +*.yml eol=lf +dvc.lock eol=lf \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.github/workflows/check-dvc.yaml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.github/workflows/check-dvc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f1070668c9d3bf2f3678b5730d515419de25ce0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.github/workflows/check-dvc.yaml @@ -0,0 +1,38 @@ +name: Check DVC push + +on: + pull_request: + push: + branches: + - main + +jobs: + check-dvc: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup python + uses: actions/setup-python@v2 + with: + python-version: "3.8" + architecture: x64 + + - name: Install DVC + run: pip install dvc[gs]===3.42.0 + + - name: Authenticate on Google Cloud + uses: 'google-github-actions/auth@v1' + with: + credentials_json: '${{ secrets.GCP_CREDENTIALS }}' + + - name: Check that the important stages are pullable + run: dvc pull object_inventory combined_room_object_list combined_file_manifest + + # dvc status returns empty dict JSON if everything is up to date. check that using jq. + - name: Check the status of the stages + run: | + python b1k_pipeline/check_dvc_stage_current.py object_inventory + python b1k_pipeline/check_dvc_stage_current.py combined_room_object_list + python b1k_pipeline/check_dvc_stage_current.py combined_file_manifest diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.github/workflows/compare-manifests.yml b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.github/workflows/compare-manifests.yml new file mode 100644 index 0000000000000000000000000000000000000000..c67215aadf3d2f06df221fefef1a9900b13c4ccf --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.github/workflows/compare-manifests.yml @@ -0,0 +1,135 @@ +name: Compare 3ds Max File Manifests + +on: + pull_request: + types: [opened, synchronize] # Run on PR creation and updates + +# Define permissions needed for the workflow +permissions: + contents: read # To check out code + pull-requests: write # To post/update the PR comment + +jobs: + diff_output: + runs-on: ubuntu-latest + env: + # Temporary file paths + DIFF_FILE: /tmp/output.diff + + steps: + - name: Setup python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + architecture: x64 + + - name: Install DVC + run: pip install dvc[gs]===3.42.0 deepdiff fs numpy trimesh pyyaml + + - name: Authenticate on Google Cloud + uses: 'google-github-actions/auth@v1' + with: + credentials_json: '${{ secrets.GCP_CREDENTIALS }}' + + - name: Checkout PR Branch + uses: actions/checkout@v4 + with: + path: pr + + - name: Pull combined file manifest for PR branch + working-directory: pr + run: dvc pull combined_file_manifest file_manifest + + # - name: Check repro output on PR branch + # working-directory: pr + # run: dvc repro --dry --allow-missing combined_file_manifest + + # - name: Check PR branch file manifest for validity + # working-directory: pr + # run: python b1k_pipeline/check_dvc_stage_current.py combined_file_manifest + + - name: Checkout Base Branch (${{ github.base_ref }}) + uses: actions/checkout@v4 + with: + ref: ${{ github.base_ref }} # Checkout the base branch + path: base + + - name: Pull combined file manifest for base branch + working-directory: base + run: dvc pull combined_file_manifest file_manifest + + # - name: Check repro output on base branch + # working-directory: base + # run: dvc repro --dry --allow-missing combined_file_manifest + + # - name: Check base branch file manifest for validity + # working-directory: base + # run: python b1k_pipeline/check_dvc_stage_current.py combined_file_manifest + + - name: Generate Diff + id: diff_step # Give the step an ID to reference its outputs + run: | + echo "Generating diff between base and PR file manifests..." + # Use 'diff' command. It exits with 0 if no diff, 1 if diff, >1 if error. + # We use '|| true' to ensure the workflow continues even if differences are found (exit code 1). + # diff -u5 base/artifacts/pipeline/combined_file_manifest.json pr/artifacts/pipeline/combined_file_manifest.json > ${{ env.DIFF_FILE }} || true + PYTHONPATH="pr:${PYTHONPATH}" python pr/b1k_pipeline/deep_diff.py > ${{ env.DIFF_FILE }} + + # Check if diff file has content + if [ -s "${{ env.DIFF_FILE }}" ]; then + echo "Differences found." + echo "diff_found=true" >> $GITHUB_OUTPUT + else + echo "No differences found." + echo "diff_found=false" >> $GITHUB_OUTPUT + fi + + # 4. Output Diff to Job Summary + - name: Write Diff to Job Summary + run: | + echo "### 3ds Max File Manifest Comparison" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY # Newline + echo "Comparison of the 3ds Max file manifest between the base branch (\`${{ github.base_ref }}\`) and the PR branch (\`${{ github.head_ref }}\`)." >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + + if [ "${{ steps.diff_step.outputs.diff_found }}" == "true" ]; then + echo "**Result:** Differences found." >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo '```diff' >> $GITHUB_STEP_SUMMARY + # Limit the diff size in the summary if needed (e.g., first 100 lines) + # head -n 100 ${{ env.DIFF_FILE }} >> $GITHUB_STEP_SUMMARY + # Or display the full diff (might be large) + cat ${{ env.DIFF_FILE }} >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + # Optionally, mention if the diff was truncated + # line_count=$(wc -l < ${{ env.DIFF_FILE }}) + # if [ $line_count -gt 100 ]; then + # echo "" >> $GITHUB_STEP_SUMMARY + # echo "*Note: Diff output truncated to the first 100 lines. See the full diff artifact.*" >> $GITHUB_STEP_SUMMARY + # fi + else + echo "**Result:** No differences found." >> $GITHUB_STEP_SUMMARY + fi + + # Optional: Upload full diff as artifact (useful if diffs can be very large) + - name: Upload Diff Artifact + if: steps.diff_step.outputs.diff_found == 'true' # Only upload if there are differences + uses: actions/upload-artifact@v4 + with: + name: command-output-diff + path: ${{ env.DIFF_FILE }} + + # 5. Post/Update a status comment on the PR + - name: Create or Update PR Comment + uses: marocchino/sticky-pull-request-comment@v2 + with: + # Use a header to identify the comment uniqueness + header: command-diff-output-check + # Use github.server_url for GHES compatibility + message: | + 📊 **3ds Max File Manifest Diff Check** + + ${{ steps.diff_step.outputs.diff_found == 'true' && format('Differences found between 3ds Max file manifests in base (`{0}`) and PR (`{1}`).', github.base_ref, github.head_ref) || format('No differences found between 3ds Max file manifests in base (`{0}`) and PR (`{1}`).', github.base_ref, github.head_ref) }} + + [**See details in the Job Summary →**](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) + ${{ steps.diff_step.outputs.diff_found == 'true' && format('\n[Download full diff artifact]({0}/{1}/actions/runs/{2}/artifacts/{3})', github.server_url, github.repository, github.run_id, 'command-output-diff') || '' }} diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a82a92129394cf3db9a474325778dc6e4ce4326c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.gitignore @@ -0,0 +1,12 @@ +*.max +*.zip +__pycache__ +*.pyc +.ipynb_checkpoints +gha-creds-*.json +*.sqsh +b1k_pipeline/docker/data/ +b1k_pipeline/docker/isaac_cache/ +b1k_pipeline/docker/scheduler-logs/ +tmp/ +logs/ diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.vscode/settings.json b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..de288e1eab6a537caed290ce0fc5e70be7ae9dba --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.formatting.provider": "black" +} \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7za.exe b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7za.exe new file mode 100644 index 0000000000000000000000000000000000000000..54ebfbb84935639ea71e0601e83fbfa67a65bd81 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7za.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbb3dadcc29bcbc5460484d858c5f33f99e5317f5f6cd8d9c83f4dd8c39b3e30 +size 1327616 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7zzs b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7zzs new file mode 100644 index 0000000000000000000000000000000000000000..4fa351b3337d5229f214bf0af70a6f5d0b45b24e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7zzs @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ef56fbef44a9b618036a90039d4a709a18e0950d7939112114f5c43674c5422 +size 3759224 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/README.md b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/README.md new file mode 100644 index 0000000000000000000000000000000000000000..683f436f143557b744876019a764a38ea69565b8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/README.md @@ -0,0 +1,131 @@ +# BEHAVIOR-1K Asset Pipeline + +This repository contains a DVC-based pipeline for converting 3D assets, primarily from the BEHAVIOR-1K project's 3ds Max format, into USD format suitable for OmniGibson simulation. It also includes data pointers to fetch the raw 3ds Max files. + +## Setup + +**Requirements**: + +* Windows 10 or 11 with at least 32GB RAM (64GB recommended). +* Autodesk 3ds Max 2022 (Student license available). +* V-Ray 5 (Free trial available). +* Git and Conda installed. + +**Installation Steps**: + +1. **Clone Repository:** Clone this repository to `D:\BEHAVIOR-1K\asset_pipeline`. **Note:** This path might be hardcoded in some scripts. +2. **Create Conda Environment:** Open PowerShell and run: + ```powershell + conda env create --file environment.yml + ``` +3. **Install 3ds Max Python Packages:** Run the following commands in PowerShell (update the 3ds Max installation path if necessary): + ```powershell + & 'C:\Program Files\Autodesk\3ds Max 2022\Python37\python.exe' -m ensurepip + & 'C:\Program Files\Autodesk\3ds Max 2022\Python37\python.exe' -m pip install -r requirements_3dsmax.txt + ``` +4. **Import 3ds Max Export Settings:** Copy `configs/gw_objexp.ini` to `%LocalAppData%\Autodesk\3dsMax\2022 - 64bit\ENU\en-US\plugcfg`, overwriting if necessary. Launch 3ds Max once if the folder doesn't exist. + +## Pulling Raw BEHAVIOR-1K 3ds Max Files + +This pipeline is primarily designed for the BEHAVIOR-1K 3ds Max files. + +* **Licensing:** Due to licensing restrictions, raw BEHAVIOR-1K model files cannot be released to non-Stanford-affiliated users. +* **Stanford Users:** + 1. Authenticate with Google Cloud: + ```powershell + gcloud auth application-default login + ``` + 2. Pull the data using DVC: + ```powershell + dvc pull + ``` + +## Repository Structure + +``` +asset_pipeline/ +├── b1k_pipeline/ #-> Core pipeline scripts +│ ├── max/ #-> Scripts run within 3ds Max +│ ├── usd_conversion/ #-> Scripts for URDF to USD conversion +│ └── ... #-> Other pipeline modules and utilities +├── artifacts/ #-> Pipeline output directory +│ ├── pipeline/ #-> Intermediate outputs +│ ├── aggregate/ #-> Aggregated outputs for the final dataset (objects, scenes, metadata) +│ ├── parallels/ #-> Outputs from parallel processing stages (e.g., zipped objects, scenes) +│ └── og_dataset.zip #-> Final dataset ZIP file +├── cad/ #-> Directory containing raw 3ds Max files +│ ├── scenes/ #-> Raw 3ds Max scene files +│ │ └── {scene_name}/ #-> Data for each scene +│ │ ├── artifacts/ #-> Scene-specific pipeline outputs [cite: 84, 85] +│ │ ├── textures/ #-> Texture files required by .max files +│ │ ├── raw.max #-> (Optional) Original raw scene file +│ │ └── processed.max #-> Processed scene file with annotations (Pipeline Input) [cite: 85, 86] +│ └── objects/ #-> Raw 3ds Max object files (similar structure to scenes) +├── metadata/ #-> Metadata files (e.g., mappings, parameters) +├── notebooks/ #-> Jupyter notebooks for analysis, examination, etc. +├── render_presets/ #-> Render presets for 3ds Max +├── configs/ #-> Configuration files (e.g., gw_objexp.ini) +├── dvc-tmpl.yaml #-> Template for dvc.yaml, used by generate_params.py +├── dvc.yaml #-> DVC pipeline definition (generated by script) +├── dvc.lock #-> DVC lockfile with dependency hashes +├── environment.yml #-> Conda environment definition +└── README.md #-> This file +``` + +## Stages + +The pipeline uses DVC (Data Version Control) to manage stages and dependencies. Key stages defined in `dvc.yaml` include: + +| Stage Name | Description | Requirements | +| :---------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- | :----------------------- | +| `object_list` | Lists meshes and iGibson objects within a `.max` file. | 3ds Max | +| `object_list_success` | Aggregates and checks `object_list` results. | | +| `sanitycheck` | Runs tests against the `.max` file format and outputs results[cite: 146, 98]. | 3ds Max | +| `sanitycheck_success` | Aggregates and checks `sanitycheck` results. | | +| `check_collisions` | Checks for collisions between objects within a scene file. | 3ds Max | +| `check_collisions_success` | Aggregates and checks `check_collisions` results. | | +| `check_collisions_with_clutter` | Checks for collisions including clutter objects. | 3ds Max | +| `check_collisions_with_clutter_success` | Aggregates and checks `check_collisions_with_clutter` results. | | +| `validate_meta_links` | Validates meta-links defined in `object_list` files[cite: 151, 152]. | | +| `object_inventory` | Aggregates object lists, checks for required objects, name collisions, etc. | | +| `object_inventory_success` | Checks `object_inventory` results. | | +| `export_meshes` | Exports OBJ/MTL files with baked textures for each mesh in the `.max` file[cite: 155, 110]. | 3ds Max | +| `export_meshes_success` | Aggregates and checks `export_meshes` results. | | +| `generate_max_object_images` | Renders images of individual objects within the `.max` file. | 3ds Max | +| `aggregate_max_object_images` | Aggregates the object images generated per-target[cite: 158, 172]. | | +| `generate_max_object_images_success`| Aggregates and checks `generate_max_object_images` results. | | +| `export_objs_global` | Processes exported meshes (OBJ/MTL) into URDF objects with joints, links, metadata[cite: 159, 114]. | | +| `export_objs_global_success` | Checks `export_objs_global` results. | | +| `combined_room_object_list` | Generates a combined list of objects per room across scenes, with synset mappings[cite: 161, 126]. | | +| `export_scenes_global` | Creates scene URDF files referencing exported meshes and objects[cite: 163, 128]. | | +| `export_scenes_global_success` | Checks `export_scenes_global` results. | | +| `validate_scenes` | Runs validation checks (e.g., physics stability) on exported scene files[cite: 164, 130]. | | +| `validate_scenes_success` | Checks `validate_scenes` results. | | +| `usdify_objects` | Converts URDF objects into USD format[cite: 165, 121]. | Docker, WSL2, Windows 11 | +| `usdify_objects_success` | Checks `usdify_objects` results. | | +| `usdify_scenes` | Converts scene URDFs into USD format[cite: 166, 135]. | Docker, WSL2, Windows 11 | +| `generate_systems` | Generates USD system definitions (e.g., for substances) based on USD objects. | | +| `generate_systems_success` | Checks `generate_systems` results. | | +| `aggregate_fillable_volumes` | Aggregates pre-generated fillable volume meshes based on annotations. | | +| `collision_average_volumes` | Calculates average collision volumes per category. | | +| `collision_average_volumes_success` | Checks `collision_average_volumes` results. | | +| `aggregate_metadata` | Aggregates various metadata files (object inventory, category mappings, etc.) into a single archive[cite: 169, 177]. | | +| `aggregate_metadata_success` | Checks `aggregate_metadata` results. | | +| `pack_dataset` | Packages the final aggregated objects, scenes, and metadata into a ZIP file for distribution[cite: 170, 137, 248]. | | +| `patch_sampled` | (Optional) Patches the dataset zip files with sampled task data. | `sampled_tasks.zip` | + +*(Note: Some stages from the original README like `generate_object_images`, `validate_objs`, `generate_scene_images`, `generate_camera_images` might be deprecated or replaced by newer stages like `generate_max_object_images` and USD-based validation)*. + +## Scripts + +Details on the scripts powering the pipeline can be found in the [b1k_pipeline module README](./b1k_pipeline). + +## Running Pipeline + +*(Execution details TBD)* + +## Contributing + +* Changes should be submitted via Pull Request to Cem Gokmen (cgokmen). +* **Stanford Affiliates:** Ensure relevant data changes are pushed to the cvgl storage. +* **External Users:** Provide instructions for accessing your remote storage so data can be fetched. \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/VERSION b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..a5c4c763394f2d3796e7145b038054d03d66861a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/VERSION @@ -0,0 +1 @@ +3.9.0 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..030416cf8423bd15b676afca9b08523d33fe95e0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/.gitignore @@ -0,0 +1,3 @@ +/og_dataset_encrypted.tar.gz +/og_dataset_sampled.tar.gz +/og_dataset_demo_sampled.tar.gz diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/parallels/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/parallels/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..46f2b42748c067ee757e7cd458d875e165a45524 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/parallels/.gitignore @@ -0,0 +1 @@ +/fillable_volumes diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/parallels/fillable_volumes.dvc b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/parallels/fillable_volumes.dvc new file mode 100644 index 0000000000000000000000000000000000000000..7f0425623eb35f300ee22157a9672c60470a558d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/parallels/fillable_volumes.dvc @@ -0,0 +1,6 @@ +outs: +- md5: 03351d4e7ac341771d0a401feadf1e5b.dir + size: 12846689 + nfiles: 1599 + path: fillable_volumes + hash: md5 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/.gitignore b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f0f6c2599fc6e1dbd3037b42eb70bf4a2f85b597 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/.gitignore @@ -0,0 +1,42 @@ +/object_inventory.json +/combined_room_object_list.json +/combined_room_object_list.success +/object_inventory.success +/aggregate_objs.success +/aggregate_objs.json +/aggregate_scenes.success +/aggregate_scenes.json +/pack_dataset.json +/pack_dataset.success +/usdify_objs.success +/usdify_scenes.success +/aggregate_metadata.json +/aggregate_metadata.success +/sanitycheck.success +/object_list.success +/export_meshes.success +/export_objs.json +/export_objs.success +/make_maps.success +/vertex_reduction.json +/vertex_reduction.success +/usdify_objects.success +/usdify_objects.json +/usdify_scenes.json +/collision_selection_validation.json +/collision_selection_validation.success +/collision_average_volumes.json +/collision_average_volumes.success +/validate_scenes.json +/validate_meta_links.json +/generate_systems.json +/generate_systems.success +/generate_fillable_volumes.json +/export_scenes.json +/export_scenes.success +/object_images +/patch_sampled.success +/generate_max_object_images.success +/combined_file_manifest.json +/check_collisions_challenge.json +/check_collisions_challenge.success diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/export_collision_meshes.json b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/export_collision_meshes.json new file mode 100644 index 0000000000000000000000000000000000000000..f50b5849cad52764851a5f944764872a916d99b9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/export_collision_meshes.json @@ -0,0 +1 @@ +{"success": true, "errors": {}} \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/fillable_ids.json b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/fillable_ids.json new file mode 100644 index 0000000000000000000000000000000000000000..41e3c739e0a8b1cbdd5a4421f4e9cb123ae45684 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/fillable_ids.json @@ -0,0 +1 @@ +["dhkkfo", "nfuxzd", "lgopij", "yhurut", "swytaw", "dtjmai", "effbnc", "exzsal", "fxrsyi", "fyrkzs", "jdijek", "qwoqqr", "rhohgs", "sfvswx", "sstojv", "uobdoq", "uzgibd", "zycgen", "ecqxgd", "nigfha", "lymciz", "mxsliu", "rxscji", "xtqbuf", "dpxnlc", "hvlkjx", "cwkvib", "dhfqid", "eyedvd", "xnjqix", "adciys", "ajzltc", "aspeds", "belcml", "bexgtn", "bnobdx", "byzaxy", "ckxwea", "cypjlv", "dalyim", "eawgwj", "eipwho", "fedafr", "feuaak", "fiarri", "fwdfeg", "hitnkv", "hpqjug", "hynhgz", "jblalf", "jfvjep", "jhtxxh", "jpvcjv", "kasebx", "kdkrov", "kthvrl", "lgaxzt", "mspdar", "nkkhbn", "npuuir", "oyidja", "pihjqa", "qzodht", "rbnyxi", "rlwpcd", "sqqahm", "szgdpc", "tvtive", "tyczoo", "vccsrl", "wryghu", "wtepsx", "xplzbo", "xpnlup", "pbvpua", "uftzyo", "bdhvnt", "lsmlzi", "wlilma", "qixpto", "gqwnfv", "xcppkc", "ouhqnw", "ttxunv", "hdbsog", "mdtkkv", "ocjcgp", "causya", "cdmmwy", "hhlmbi", "libote", "msfzpz", "sxlklf", "uartvl", "ylrxhe", "mmbavt", "ncbsee", "heuzgu", "rclizj", "lbcxwi", "zndohl", "sfkezf", "xkixrg", "ztripg", "ooyqcr", "jeqtzg", "cvdbum", "gklybu", "hacehh", "jwxbpa", "qhnpmc", "qlxhhh", "uzkxtz", "ovjhuf", "fhtvuq", "jasnzj", "smcyys", "wivnic", "xsuyua", "zlmnfg", "cqdioi", "xevdnl", "kxwgoo", "cjmtvq", "phimqa", "loduxu", "ckkwmj", "dkxddg", "fgizgn", "ibhhfj", "nbhcgu", "nhzrei", "rixzrk", "rypdvd", "siksnl", "skamgp", "xjdyon", "ykuftq", "fwlabx", "pyttso", "oyqdtz", "fvkdos", "cfdond", "gqemcq", "dhseui", "lfjmos", "hfclfn", "lspxjq", "xdahvv", "ofasfw", "yufawg", "ifqdxn", "vxxcvg", "xmxvml", "qmdgct", "hkdsla", "ceaeqf", "qornxa", "bpwjxr", "iwwpsf", "uyixwc", "qxnzpx", "fzhcdb", "zhsjcs", "gamkbo", "ztyxyi", "aewpzn", "cprjvq", "hzspwg", "jpzusm", "mhndon", "sfbdjn", "snvhlz", "vycozd", "bfaqfe", "oxknkz", "nawrfs", "egpkea", "yzeuqo", "qwthua", "oywwzz", "fxnjfr", "arryyl", "krgqwl", "lwsgzd", "aeslmf", "dhgtvg", "nuzkuf", "wbnkfk", "jvnqly", "luhnej", "vlurir", "lulzdz", "gewlsk", "gcyvrx", "ycgxwb", "lkbvad", "wengzf", "bqpmsv", "crlhmi", "gejwoi", "gqtsam", "ifgcmr", "jdwvyt", "jnjtrl", "kijnrj", "lvuvbf", "mefezc", "ociqav", "pjaljg", "qdnmwg", "vxqpnm", "waousd", "wcqjew", "zdeyzf", "nftsal", "lrjoro", "aysfhf", "oqyoos", "gjgwvi", "hjjeeh", "llexze", "pvxfot", "quzmfw", "bzisss", "vjbldp", "qsdqik", "yprkek", "bnekjp", "rsvypp", "ykfkyq", "hazvbh", "rwnakn", "omknho", "adxzhe", "wigtue", "owqbsb", "cydfkt", "ahtzhp", "icvmix", "bsgybx", "deudkt", "rgnjdt", "xifive", "xjzyfc", "dhnxww", "ehnmxj", "fapsrj", "jgethp", "kewbyf", "kitxam", "lgxhsc", "ntgftr", "ppdqbj", "ppzttc", "waqrdy", "yiamah", "yxaapv", "zsrpiu", "tmjxno", "xdhysb", "gcixra", "yoxfyu", "zfvhus", "jjlfla", "bzsxgw", "ruryqd", "wvhmww", "guobeq", "jaypjo", "xdxqxj", "jgyqpd", "fhfqys", "vbiqcq", "xfqatj", "csvdbe", "wsasmm", "barzwx", "ankfvi", "bbewjo", "mbrlge", "ompiss", "tsyims", "tzbnmh", "wmkwhg", "ihnfbi", "skbcqq", "vhglly", "ygrtaz", "aewthq", "akfjxx", "amhlqh", "aynjhg", "bgxzec", "dbprwc", "dnqekb", "eixyyn", "eozsdg", "fhdyrj", "fkpaie", "haewxp", "iawoof", "ihrjrb", "itoeew", "ivbrtz", "ivuveo", "iwfvwf", "kkjiko", "kkmkbd", "ksgizx", "lixwwc", "lkomhp", "luhkiz", "molqhs", "mtetqm", "nbuspz", "nhodax", "nikfgd", "nmhxfz", "nrjump", "ntedfx", "odmjdd", "pjinwe", "pkkgzc", "pyilfa", "qbxfmv", "qtfzeq", "qyuyjr", "spppps", "tgrsui", "uakqei", "ujodgo", "uumkbl", "vitdwc", "vjqzwa", "vtjwof", "wgcgia", "wqgndf", "xfjmld", "xtdcau", "ypdfrp", "zpddxu", "csanbr", "ekjpdj", "hnlivs", "iadlti", "ieoasd", "kiiamx", "hldhxl", "hdcpqg", "otyngn", "wyojnz", "svkdji", "yowyst", "tnjpsf", "trtrsl", "uaijua", "ukayce", "xstykf", "duugbb", "nuoypc", "dafdgk", "qatgeb", "fjytro", "hmzafz", "injdmj", "tqyiso", "ueagnt", "ugqdao", "wdpcmk", "fsinsu", "chjetk", "fbfmwt", "kvgaar", "obuxbe", "ozrwwk", "pkfydm", "sthkfz", "tfzijn", "urqzec", "uvzmss", "vqtkwq", "wfryvm", "cjsbft", "mgbeah", "oxivmf", "szzjzd", "vghfkh", "bupgpj", "tukaoq", "nedrsh", "vsxhsv", "gswpdr", "hamffy", "xbkwbi", "fsfsas", "gnzegv", "lpanoc", "vicaqs", "upfssc", "vxtjjn", "gzcqwx", "nbctrk", "vlplhs", "azoiaq", "dcleem", "fuzmdd", "grrcna", "gxiqbw", "lfnbhc", "oshwps", "yvhmex", "xixblr", "dhwlaw", "kohria", "qjhauf", "vnvmkx", "bsdexp", "cpozxi", "kccqwj", "oxfzfe", "tfzfam", "vckahe", "wopjex", "zdvgol", "foaehs", "jlalfc", "mvrhya", "apybok", "iyrrna", "krarex", "krfzqk", "aefcem", "cdzyew", "cjmezk", "djgllo", "dnvpag", "eahqyq", "fkosow", "gilsji", "glzckq", "gsgutn", "gvnfgj", "gxajos", "hqdnjz", "hxsyxo", "ifzxzj", "jlawet", "leazin", "mcukuh", "mdojox", "pdmzhv", "rbqckd", "rteihy", "uknjdm", "vasiit", "wklill", "wkxtxh", "xkqkbf", "zotrbg", "avotsj", "coqeme", "glwebh", "gsxbym", "hbjdlb", "hjxczh", "huwhjg", "hvlfig", "iaaiyi", "incirm", "jpcflq", "mhhoga", "mkdcha", "spopfj", "thkphg", "tkgsho", "txcjux", "uekqey", "vxbtax", "wbwmcs", "xzcnjq", "yqtlhy", "zcmnji", "zsddtq", "mkstwr", "aegxpb", "atgnsc", "bbduix", "bedkqu", "cvyops", "dfjcsi", "dwspgo", "eqhgiy", "euqzpy", "gopbrh", "hkwtnf", "hliauj", "htyvuz", "icpews", "ipbgrw", "jdddsr", "jpwsrp", "kjeudr", "mawxva", "mdmwcs", "meetii", "nodcpg", "nuqzjs", "qebiei", "rfegnv", "rfigof", "rusmlm", "rwotxo", "saenda", "stqkvx", "tjrbxv", "toreid", "twknia", "uuypot", "vmbzmm", "wltgjn", "xfduug", "ysdoep", "zaziny", "zwekzu", "hbsbwt", "ykysuc", "bojwlu", "sbvksi", "yjmnej", "dobgmu", "jgyzhv", "mrgspe", "omeuop", "xusefg", "ynwamu", "zgzvcv", "ziomqg", "ackxiy", "lzdzkk", "bbpraa", "cdteyb", "edfzlt", "elwfms", "evaida", "ewgotr", "ggpnlr", "gypzlg", "igyuko", "imsnkt", "kttdbu", "ktuvuo", "kuiiai", "lvqgvn", "nfoydb", "onbiqg", "ptciim", "slscza", "szjfpb", "uwtdng", "vcwsbm", "wvztiw", "ybhepe", "zbridw", "msaevo", "jpduev", "xiwkwz", "hlzfxw", "inkqch", "vjdkci", "zuctnl", "aakcyj", "adiwil", "akusda", "bnored", "bovcqx", "cmdagy", "euzudc", "exasdr", "ezsdil", "ggbdlq", "hxccge", "jzmrdd", "kxovsj", "oadvet", "ovoceo", "vxmzmq", "yfzibn", "pobfpe", "vmajcm", "ahbhsd"] \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/generate_fillable_volumes_flat.json b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/generate_fillable_volumes_flat.json new file mode 100644 index 0000000000000000000000000000000000000000..4ec7c36d7cf88518691c6b40bd246a587a9a18dd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/generate_fillable_volumes_flat.json @@ -0,0 +1 @@ +{"success": true, "failed_objects": [], "logs": []} \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/generate_images.success b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/artifacts/pipeline/generate_images.success new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/3dsMax.ini b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/3dsMax.ini new file mode 100644 index 0000000000000000000000000000000000000000..b5c95e6ca6443422e71bfcda67d44b6ce9ecc2bc Binary files /dev/null and b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/3dsMax.ini differ diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/__init__.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/link_to_obj.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/link_to_obj.py new file mode 100644 index 0000000000000000000000000000000000000000..603eac6e13e068cac345539d172b45c90d2b0cb9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/link_to_obj.py @@ -0,0 +1,34 @@ +import csv +import matplotlib.pyplot as plt +import urllib.parse +from collections import defaultdict + +links = [] +data = defaultdict(list) +with open(r"objlinks.csv", "r") as f: + reader = csv.reader(f) + + # This skips the first row of the CSV file. + next(reader) + + for i, row in enumerate(reader): + obj = row[0] + link = row[7] + if link.startswith("https"): + parsed = urllib.parse.urlparse(link) + sanitized = "https://www.turbosquid.com" + parsed.path + data[sanitized].append(obj.strip().replace(" ", "_")) + elif link.lower() != "true" and link.lower() != "false" and link.lower() != "": + print(f"Skipping line {i}: {link} due to unknown format.") + +print(f"Read {len(data)} URLs.") + +with open("link_to_obj.csv", "w", newline="") as csvfile: + fieldnames = ["link", "objs"] + writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_ALL) + writer.writeheader() + + for link, objs in data.items(): + writer.writerow({"link": link, "objs": ",".join(objs)}) + +print("Saved mapping.") diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_cart.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c1354d8633539a7f1722203d89d88532b309d4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_cart.py @@ -0,0 +1,94 @@ +import numpy as np +from selenium import webdriver +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.common.by import By + +import csv +import json +import matplotlib.pyplot as plt +import time + +START = 500 +END = 1000 + +links = [] +with open(r"objlinks.csv", "r") as f: + reader = csv.DictReader(f) + for i, row in enumerate(reader): + link = row["purchase_link"] + if link.startswith("https"): + links.append(link.strip()) + elif link.lower() != "true" and link.lower() != "false" and link.lower() != "": + print(f"Skipping line {i}: {link} due to unknown format.") + +links = links[START:END] +print(f"Read {len(links)} lines.") + +driver = webdriver.Chrome( + executable_path=r"C:\Users\capri28\Downloads\chromedriver_win32\chromedriver" +) +driver.get("https://www.turbosquid.com/MemberInfo/") +driver.implicitly_wait(10) + +print("Waiting for user to log in and go to Account Info.") +WebDriverWait(driver, 300).until( + EC.title_contains("Member Info") +) # Check for login to happen and user to go to + +bought_links = {x: 0 for x in links[:START]} +for i, link in enumerate(links): + # Load the page + driver.get(link) + WebDriverWait(driver, 10).until( + EC.element_to_be_clickable((By.CLASS_NAME, "addToCartBtn")) + ) + + # Try to get the price. + try: + price_box = driver.find_element_by_id("product-price") + price = float(price_box.text) + except: + try: + free_box = driver.find_element_by_id("free-price") + price = 0 + except: + print(f"Something went wrong with item {i}: {link}. No price tag.") + continue + + # Store the price. + bought_links[link] = price + + # Skipping already-bought link. + if link not in bought_links: + continue + + time.sleep(3) + + # If it's not free, let's buy it. + if price > 0: + button = driver.find_element_by_class_name("addToCartBtn") + button.click() + WebDriverWait(driver, 10).until( + EC.visibility_of_element_located((By.ID, "quickPurchaseModalLabel")) + ) + print(f"Added {link}, {i + 1}/{len(links)}") + else: + print(f"Skipping free {link}, {i + 1}/{len(links)}") + + time.sleep(3) + +with open(r"objprices.json", "w") as f: + json.dump(bought_links, f) + +x = np.array(list(bought_links.values())) +print(f"Saved prices. Total: {np.sum(x)}") + +q25, q75 = np.percentile(x, [25, 75]) +bin_width = 2 * (q75 - q25) * len(x) ** (-1 / 3) +bins = round((x.max() - x.min()) / bin_width) +plt.hist(x, bins=bins) +plt.show() + +driver.close() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_prices.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_prices.py new file mode 100644 index 0000000000000000000000000000000000000000..d382579de7f06455a3dfa8925e65bc7097a36bf9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_prices.py @@ -0,0 +1,57 @@ +import csv +import json +import tqdm +import requests +import bs4 +import concurrent.futures +import numpy as np +import matplotlib.pyplot as plt + +links = [] +with open(r"objlinks.csv", "r") as f: + reader = csv.DictReader(f) + for i, row in enumerate(reader): + link = row["purchase_link"] + if link.startswith("https"): + links.append(link.strip()) + elif link.lower() != "true" and link.lower() != "false" and link.lower() != "": + print(f"Skipping line {i}: {link} due to unknown format.") + +print(f"Read {len(links)} lines.") + + +def load_price(link, timeout): + html = requests.get(link).content + dom = bs4.BeautifulSoup(html, "html.parser") + price_thing = dom.find(id="product-price") + price_text = price_thing.attrs["content"] + price = float(price_text) if price_text.lower() != "free" else 0 + return price + + +prices = {} +with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: + # Start the load operations and mark each future with its URL + future_to_url = {executor.submit(load_price, link, 10): link for link in links} + for future in tqdm.tqdm(concurrent.futures.as_completed(future_to_url)): + link = future_to_url[future] + try: + price = future.result() + prices[link] = price + except Exception as exc: + print("%r generated an exception: %s" % (link, exc)) + +paid_objs = len([price for price in prices.values() if price > 0]) +print(f"Total of {paid_objs} non-free objects.") + +with open(r"C:\Users\capri28\Downloads\objprices.json", "w") as f: + json.dump(prices, f) + +print("Saved prices.") + +x = np.array(list(prices.values())) +q25, q75 = np.percentile(x, [25, 75]) +bin_width = 2 * (q75 - q25) * len(x) ** (-1 / 3) +bins = round((x.max() - x.min()) / bin_width) +plt.hist(x, bins=bins) +plt.show() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_prices_plot.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_prices_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..0040d662dd355f1ba55fd2261bff573692734cf4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/acquisition/object_prices_plot.py @@ -0,0 +1,17 @@ +import numpy as np +import matplotlib.pyplot as plt +import json + +with open(r"C:\Users\Cem\Downloads\objprices.json", "r") as f: + prices = json.load(f) + +x = np.array(list(prices.values())) +q25, q75 = np.percentile(x, [25, 75]) +bin_width = 2 * (q75 - q25) * len(x) ** (-1 / 3) +bins = round((x.max() - x.min()) / bin_width) +plt.hist(x, bins=bins) +plt.show() + +print( + "\n".join(str(x) for x in sorted(prices.items(), key=lambda x: x[1], reverse=True)) +) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_fillable_volumes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_fillable_volumes.py new file mode 100644 index 0000000000000000000000000000000000000000..527d4f3e4cb3b541afa1387eaee9a6fdbaa14eaa --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_fillable_volumes.py @@ -0,0 +1,98 @@ +import json +import fs.path +from fs.multifs import MultiFS +import numpy as np +import tqdm +import trimesh + +import b1k_pipeline.utils + + +MAX_BBOX = 0.3 + + +def get_fillable_mesh(option, combined_object_and_volume_fs): + options = {} + + dip_path = "fillable_dip.obj" + if combined_object_and_volume_fs.exists(dip_path): + # Find the scale the mesh was generated at + metadata = json.loads( + combined_object_and_volume_fs.readtext("misc/metadata.json") + ) + native_bbox = np.array(metadata["bbox_size"]) + scale = np.minimum(1, MAX_BBOX / np.max(native_bbox)) + + dip_mesh = b1k_pipeline.utils.load_mesh( + combined_object_and_volume_fs, dip_path, force="mesh" + ) + inv_scale = 1 / scale + transform = np.diag([inv_scale, inv_scale, inv_scale, 1]) + dip_mesh.apply_transform(transform) + options["dip"] = dip_mesh + + ray_path = "fillable_ray.obj" + if combined_object_and_volume_fs.exists(ray_path): + ray_mesh = b1k_pipeline.utils.load_mesh( + combined_object_and_volume_fs, ray_path, force="mesh" + ) + options["ray"] = ray_mesh + + if "dip" in options and "ray" in options: + # Check if either mesh contains the entire other mesh + combined_mesh = trimesh.convex.convex_hull( + np.concatenate([dip_mesh.vertices, ray_mesh.vertices], axis=0) + ) + options["combined"] = combined_mesh + + assert option in options, f"Option {option} not found in {options.keys()}" + return options[option] + + +def aggregate_fillable_volumes(): + with b1k_pipeline.utils.PipelineFS().open( + "metadata/fillable_assignments.json" + ) as f: + data = json.load(f) + + errors = [] + + # Process objects one by one + with ( + b1k_pipeline.utils.ParallelZipFS("objects.zip") as objects_fs, + b1k_pipeline.utils.PipelineFS().opendir( + "artifacts/parallels/fillable_volumes" + ) as fillables_fs, + b1k_pipeline.utils.ParallelZipFS("fillable_volumes.zip", write=True) as out_fs, + ): + input_fs = MultiFS() + input_fs.add_fs("objects", objects_fs) + input_fs.add_fs("fillables", fillables_fs) + objdir_glob = list(objects_fs.glob("objects/*/*/")) + for item in tqdm.tqdm(objdir_glob): + # If it doesnt have an annotation, nothing to do. + model_id = fs.path.parts(item.path)[-1] + if model_id not in data: + continue + + # If it does not have a selection annotated, nothing to do. + selection = data[model_id] + if selection not in ("combined", "dip", "ray"): + continue + + # Otherwise let's process the mesh and save it. + try: + mesh = get_fillable_mesh(selection, input_fs.opendir(item.path)) + b1k_pipeline.utils.save_mesh( + mesh, out_fs.makedirs(item.path), "fillable.obj" + ) + except Exception as e: + print("Error processing", item.path, e) + errors.append(item.path) + + if errors: + raise ValueError("Some meshes failed to process") + + +if __name__ == "__main__": + aggregate_fillable_volumes() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_max_object_images.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_max_object_images.py new file mode 100644 index 0000000000000000000000000000000000000000..0806329c8a8f9ab82b77d57c5593750f8b5f8510 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_max_object_images.py @@ -0,0 +1,42 @@ +from fs.zipfs import ZipFS +import fs.path +import fs.copy +import tqdm + +from b1k_pipeline.utils import PipelineFS, get_targets, parse_name + + +def main(): + with PipelineFS() as pipeline_fs: + with ( + pipeline_fs.pipeline_output().open("max_object_images.zip", "wb") as zip_f, + ZipFS(zip_f, write=True) as zip_fs, + ): + for target in tqdm.tqdm( + get_targets("combined"), desc=" targets", position=0 + ): + target_output_fs = pipeline_fs.target_output(target) + + with ZipFS( + target_output_fs.open("max_object_images.zip", "rb") + ) as target_images: + # Walk through all images + paths = list(target_images.listdir("/")) + + for path in tqdm.tqdm( + paths, desc=" images", position=1, leave=False + ): + name, ext = fs.path.splitext(path) + obj_name, photo_name = name.split("--") + parsed_name = parse_name(obj_name) + assert ( + parsed_name is not None + ), f"Found bad name {path} in {target}" + model_id = parsed_name.group("model_id") + output_path = f"{model_id}-{photo_name}{ext}" + + fs.copy.copy_file(target_images, path, zip_fs, output_path) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_metadata.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..4f609fe7c0aba35385607c98e88831a08bc2e460 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/aggregate_metadata.py @@ -0,0 +1,158 @@ +import numpy as np + +import csv +import json +import traceback + +import b1k_pipeline.utils + + +def main(): + with ( + b1k_pipeline.utils.PipelineFS() as pipeline_fs, + b1k_pipeline.utils.ParallelZipFS("metadata.zip", write=True) as archive_fs, + ): + pipeline_output_dir = pipeline_fs.pipeline_output() + metadata_in_dir = pipeline_fs.opendir("metadata") + metadata_out_dir = archive_fs.makedirs("metadata") + + success = True + error_msgs = [] + warning_msgs = [] + try: + with pipeline_output_dir.open("object_inventory.json", "r") as f: + object_inventory = json.load(f) + + with pipeline_output_dir.open("collision_average_volumes.json", "r") as f: + collision_average_volumes = json.load(f)["average_volumes"] + + # For now, get categories from CSV file + categories_by_id = {} + avg_category_specs = {} + with metadata_in_dir.open("category_mapping.csv", newline="") as csvfile: + reader = csv.DictReader(csvfile) + for i, row in enumerate(reader): + # TODO: Use something more authoritative than this entry + # Get the has_system entry to check if the category is a particle system, + # and if so, skip it entirely. + has_system = row["has_system"].strip().lower() + if has_system == "true": + continue + + cat_id = int(row["ID"].strip()) + category = row["category"].strip() + categories_by_id[cat_id] = category + + assert ( + category in collision_average_volumes + ), f"Category {category} not in collision_average_volumes" + + volume = collision_average_volumes[category] + mass = ( + float(row["mass (auto)"]) + if row["mass (auto)"] and row["mass (auto)"] != "#DIV/0!" + else None + ) + assert ( + mass is not None and mass > 0 + ), f"Invalid mass for category {category}" + density = mass / volume if mass and volume else None + + # The density needs to be temporarily capped at 10000 kg/m^3 - values above that + # are likely due to errors in the mass annotation (LLM based) or in the volume + # obtained from the collision mesh (infinitesimal dimension). + # if density and density > 10000: + # print( + # f"Warning: Density for category {category} is {density} kg/m^3, capping to 10000 kg/m^3" + # ) + # density = 10000 + + avg_category_specs[category] = { + "mass": mass, + "volume": volume, + "density": density, + } + + # Validate: have we found all categories on the list? + for cat in avg_category_specs: + if cat not in categories_by_id.values(): + error_msgs.append(f"Could not find ID for category {cat}") + + if cat not in avg_category_specs: + error_msgs.append( + f"Category {cat} not found in avg_category_specs file" + ) + else: + missing_things = { + k for k, v in avg_category_specs[cat].items() if v is None + } + joined_missing_things = ", ".join(sorted(missing_things)) + if missing_things & {"enable_ag", "mass"}: # Errors + error_msgs.append( + f"Category {cat} missing {joined_missing_things} data" + ) + elif missing_things: + warning_msgs.append( + f"Category {cat} missing {joined_missing_things} data" + ) + + # Only continue if no errors are found by now + assert not error_msgs + + # Fill missing IDs with spaces + category_ids = [ + categories_by_id[i] if i in categories_by_id else "" + for i in range(max(categories_by_id.keys()) + 1) + ] + category_ids_w_newline = "".join([x + "\n" for x in category_ids]) + with metadata_out_dir.open("categories.txt", "w") as f: + f.write(category_ids_w_newline) + + # Get the room categories + with metadata_in_dir.open("allowed_room_types.csv", "r") as f: + reader = csv.DictReader(f) + room_categories = "".join( + [row["Room Name"].strip() + "\n" for row in reader] + ) + with metadata_out_dir.open("room_categories.txt", "w") as f: + f.write(room_categories) + + # Compile the avg_category_specs.json file + with metadata_out_dir.open("avg_category_specs.json", "w") as f: + json.dump(avg_category_specs, f, indent=4) + + # Read and dump the non sampleable cats file + with metadata_in_dir.open("non_sampleable_categories.csv", "r") as f: + reader = csv.DictReader(f) + non_sampleable_cats = "".join( + [row["synset"].strip() + "\n" for row in reader] + ) + with metadata_out_dir.open("non_sampleable_categories.txt", "w") as f: + f.write(non_sampleable_cats) + + except Exception as e: + success = False + error_msgs.append(traceback.format_exc()) + + if error_msgs: + print("Errors:") + print("\n".join(error_msgs)) + + if warning_msgs: + print("Warnings:") + print("\n".join(warning_msgs)) + + with pipeline_fs.pipeline_output().open("aggregate_metadata.json", "w") as f: + json.dump( + { + "success": success, + "error_msgs": error_msgs, + "warning_msgs": warning_msgs, + }, + f, + indent=4, + ) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/batch_3dsmax.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/batch_3dsmax.py new file mode 100644 index 0000000000000000000000000000000000000000..853e16e976e34f3bb7b20d5dec91e742310d1ad3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/batch_3dsmax.py @@ -0,0 +1,44 @@ +from asyncio import subprocess +import subprocess +import sys +import xmlrpc.client + +# TODO: Remove this and call it with python -m when ready to rerun everything. +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") +import b1k_pipeline.utils + +USE_RPC = False + +THREEDSMAX_PATH = r"C:\Program Files\Autodesk\3ds Max 2022\3dsmaxbatch.exe" + + +def main(): + scene_file = (b1k_pipeline.utils.PIPELINE_ROOT / sys.argv[1]).absolute() + assert ( + scene_file.exists() and scene_file.suffix == ".max" + ), f"Can't find {scene_file}." + + script_file = (b1k_pipeline.utils.PIPELINE_ROOT / sys.argv[2]).absolute() + assert ( + script_file.exists() and script_file.suffix == ".py" + ), f"Can't find {script_file}." + + args = [x.split("=") for x in sys.argv[3:]] + parsed_args = {key: value for key, value in args} + assert all(key and value for key, value in parsed_args.items()) + + if USE_RPC: + with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy: + return proxy.run_script(str(scene_file), str(script_file), args) + else: + max_args = [ + ["-mxsString", f"{key}:{value}"] for key, value in parsed_args.items() + ] + cmd = [THREEDSMAX_PATH, str(script_file), "-sceneFile", str(scene_file)] + if max_args: + cmd += [x for args in max_args for x in args] + subprocess.run(cmd) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/bbox_offsets_from_usd_for_fillables.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/bbox_offsets_from_usd_for_fillables.py new file mode 100644 index 0000000000000000000000000000000000000000..63aedaec7bc2808f3255ea5ea164b4fcea5ba979 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/bbox_offsets_from_usd_for_fillables.py @@ -0,0 +1,220 @@ +from concurrent.futures import ProcessPoolExecutor, as_completed +import json +import os +import pathlib +import tempfile +from cryptography.fernet import Fernet +from pxr import Usd, UsdGeom, Gf, Sdf +import numpy as np +from scipy.spatial.transform import Rotation as R +from tqdm import tqdm +import fs.path +from fs.zipfs import ZipFS + +FILLABLE_DIR = pathlib.Path(r"D:\fillable-10-21") +KEY_PATH = pathlib.Path( + r"C:\Users\cgokmen\research\OmniGibson\omnigibson\data\omnigibson.key" +) +PIPELINE_ROOT = pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline") +MODE = "JSON" # use one of "ATTRIBUTE", "USD" or "JSON" + + +def _set_xform_properties(prim, pos, quat): + properties_to_remove = [ + "xformOp:rotateX", + "xformOp:rotateXZY", + "xformOp:rotateY", + "xformOp:rotateYXZ", + "xformOp:rotateYZX", + "xformOp:rotateZ", + "xformOp:rotateZYX", + "xformOp:rotateZXY", + "xformOp:rotateXYZ", + "xformOp:transform", + ] + prop_names = prim.GetPropertyNames() + xformable = UsdGeom.Xformable(prim) + xformable.ClearXformOpOrder() + # TODO: wont be able to delete props for non root links on articulated objects + for prop_name in prop_names: + if prop_name in properties_to_remove: + prim.RemoveProperty(prop_name) + if "xformOp:scale" not in prop_names: + xform_op_scale = xformable.AddXformOp( + UsdGeom.XformOp.TypeScale, UsdGeom.XformOp.PrecisionDouble, "" + ) + xform_op_scale.Set(Gf.Vec3d([1.0, 1.0, 1.0])) + else: + xform_op_scale = UsdGeom.XformOp(prim.GetAttribute("xformOp:scale")) + + if "xformOp:translate" not in prop_names: + xform_op_translate = xformable.AddXformOp( + UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.PrecisionDouble, "" + ) + else: + xform_op_translate = UsdGeom.XformOp(prim.GetAttribute("xformOp:translate")) + + if "xformOp:orient" not in prop_names: + xform_op_rot = xformable.AddXformOp( + UsdGeom.XformOp.TypeOrient, UsdGeom.XformOp.PrecisionDouble, "" + ) + else: + xform_op_rot = UsdGeom.XformOp(prim.GetAttribute("xformOp:orient")) + xformable.SetXformOpOrder([xform_op_translate, xform_op_rot, xform_op_scale]) + + position = Gf.Vec3d(*pos.tolist()) + xform_op_translate.Set(position) + + orientation = quat[[3, 0, 1, 2]].tolist() + if xform_op_rot.GetTypeName() == "quatf": + rotq = Gf.Quatf(*orientation) + else: + rotq = Gf.Quatd(*orientation) + xform_op_rot.Set(rotq) + + +def decrypt_file(encrypted_filename, decrypted_filename): + with open(KEY_PATH, "rb") as filekey: + key = filekey.read() + fernet = Fernet(key) + + with open(encrypted_filename, "rb") as enc_f: + encrypted = enc_f.read() + + decrypted = fernet.decrypt(encrypted) + + with open(decrypted_filename, "wb") as decrypted_file: + decrypted_file.write(decrypted) + + +def compute_bbox(prim: Usd.Prim) -> Gf.Range3d: + """ + Compute Bounding Box using ComputeWorldBound at UsdGeom.Imageable + See https://openusd.org/release/api/class_usd_geom_imageable.html + + Args: + prim: A prim to compute the bounding box. + Returns: + A range (i.e. bounding box), see more at: https://openusd.org/release/api/class_gf_range3d.html + """ + imageable = UsdGeom.Imageable(prim) + time = Usd.TimeCode.Default() # The time at which we compute the bounding box + bound = imageable.ComputeWorldBound(time, UsdGeom.Tokens.default_) + bound_range = bound.ComputeAlignedBox() + return np.array(bound_range.GetMin()), np.array(bound_range.GetMax()) + + +def keep_paths_to_all_visuals(stage): + """ + Keeps only the paths to all prims named 'visuals' and their ancestors. + + Args: + stage (Usd.Stage): The USD stage to modify. + """ + + # Find all prims named 'visuals' + def find_visuals_prims(prim, visuals_paths): + for child in prim.GetChildren(): + if child.GetName() == "visuals": + visuals_paths.add(child.GetPath()) + find_visuals_prims(child, visuals_paths) + + visuals_paths = set() + root_prim = stage.GetPseudoRoot() + find_visuals_prims(root_prim, visuals_paths) + + if not visuals_paths: + print("No prims named 'visuals' found.") + return + + # Collect paths to keep (visuals and their ancestors) + paths_to_keep = set() + for path in visuals_paths: + current_path = path + while current_path != Sdf.Path.emptyPath: + paths_to_keep.add(current_path) + current_path = current_path.GetParentPath() + + # Traverse and prune + def traverse_and_prune(prim): + for child in prim.GetChildren(): + traverse_and_prune(child) + + # Remove the prim if its path is not in paths_to_keep + if prim.GetPath() not in paths_to_keep: + stage.RemovePrim(prim.GetPath()) + + traverse_and_prune(root_prim) + + +def get_bounding_box_from_usd(input_usd, rotmat, tempdir): + encrypted_filename = input_usd + fd, decrypted_filename = tempfile.mkstemp(suffix=".usd", dir=tempdir) + os.close(fd) + decrypt_file(encrypted_filename, decrypted_filename) + stage = Usd.Stage.Open(str(decrypted_filename)) + prim = stage.GetDefaultPrim() + keep_paths_to_all_visuals(stage) + stage.Save() + + if MODE == "ATTRIBUTE": + base_link_size = np.array(prim.GetAttribute("ig:nativeBB").Get()) * 1000 + base_link_offset = np.array(prim.GetAttribute("ig:offsetBaseLink").Get()) * 1000 + + # THIS IS INACCURATE FOR NON-AA ROTATIONS! + return (rotmat @ base_link_offset).tolist(), (rotmat @ base_link_size).tolist() + + elif MODE == "USD": + # Rotate the object by the rotmat and get the bounding box + _set_xform_properties(prim, np.zeros(3), R.from_matrix(rotmat).as_quat()) + bb_min, bb_max = compute_bbox(prim) + center = ((bb_min + bb_max) / 2) * 1000 + size = (bb_max - bb_min) * 1000 + return center.tolist(), size.tolist() + + elif MODE == "JSON": + json_path = input_usd.parent.parent / "bbox.json" + with open(json_path, "r") as f: + data = json.load(f) + + size = np.array(data["bbox_extents"]) * 1000 + center = (np.array(data["bbox_center"]) - np.array(data["base_pos"])) * 1000 + return center.tolist(), size.tolist() + + raise ValueError("Invalid mode.") + + +def main(): + input_usds = list(FILLABLE_DIR.glob("objects/*/*/usd/*.usd")) + input_usds.sort(key=lambda x: x.parts[-3]) + print(len(input_usds)) + + # Scale up + futures = {} + with tempfile.TemporaryDirectory() as tempdir: + with ProcessPoolExecutor() as executor: + for input_usd in tqdm(input_usds, desc="Queueing up jobs"): + mdl = input_usd.parts[-3] + rot = R.identity() + euler = np.rad2deg(rot.as_euler("xyz")) + if not np.allclose(np.remainder(np.abs(euler), 90), 0, atol=5): + print("Non-axis aligned rotation detected for", mdl, euler.tolist()) + future = executor.submit( + get_bounding_box_from_usd, input_usd, rot.as_matrix(), tempdir + ) + futures[future] = input_usd + + # Gather the results (with a tqdm progress bar) + results = {} + for future in tqdm( + as_completed(futures), total=len(futures), desc="Processing results" + ): + input_usd = futures[future] + results[input_usd.parts[-3]] = future.result() + + with open(FILLABLE_DIR / "fillable_bboxes.json", "w") as f: + json.dump(results, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/category_qa_viewer.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/category_qa_viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..a0ce80e01d3be5bd20e92d0f1589fa16063c0687 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/category_qa_viewer.py @@ -0,0 +1,170 @@ +import logging +import os +import json +import sys +import nltk +import numpy as np +import csv +import pybullet as p +import shutil + +nltk.download("wordnet") +nltk.download("omw-1.4") +from nltk.corpus import wordnet as wn + +import igibson + +from igibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from igibson.objects.articulated_object import URDFObject +from igibson.render.mesh_renderer.mesh_renderer_settings import MeshRendererSettings +from igibson.scenes.empty_scene import EmptyScene +from igibson.simulator import Simulator +from igibson.utils.assets_utils import ( + get_all_object_categories, + get_ig_avg_category_specs, + get_ig_model_path, + get_object_models_of_category, +) + +from b1k_pipeline.utils import PIPELINE_ROOT + +skip_file_path = PIPELINE_ROOT / "qa-logs/category-pass-skips.json" + +# INVENTORY_PATH = PIPELINE_ROOT / "artifacts"/ "pipeline"/"object_inventory.json" +# with open(INVENTORY_PATH, "r") as f: +# INVENTORY_DICT = json.load(f)["providers"] + +CATEGORY_TO_SYNSET = {} +with open(PIPELINE_ROOT / "metadata/category_mapping.csv", "r") as f: + r = csv.DictReader(f) + for row in r: + CATEGORY_TO_SYNSET[row["category"].strip()] = row["synset"].strip() + + +def main(dataset_path, record_path): + """ + Minimal example to visualize all the models available in the iG dataset + It queries the user to select an object category and a model of that category, loads it and visualizes it + No physical simulation + """ + igibson.ignore_visual_shape = False + igibson.ig_dataset_path = dataset_path + + print("*" * 80 + "\nDescription:" + main.__doc__ + "*" * 80) + + processed_cats = set() + if os.path.exists(record_path): + # Load the processed objects from the pass record file + with open(record_path) as f: + processed_cats = set(json.load(f)) + + skipped_cats = set() + if os.path.exists(skip_file_path): + # Load the processed objects from the pass record file + with open(skip_file_path) as f: + skipped_cats = set(json.load(f)) + # Get all the objects in the dataset + all_cats = set(get_all_object_categories()) + + # Compute the remaining objects to be processed + remaining_cats = all_cats - (processed_cats - skipped_cats) + + print(f"{len(remaining_cats)} cats remaining out of {len(all_cats)}.") + + for i, obj_category in enumerate(sorted(remaining_cats)): + print(f"Cat {i + 1}/{len(remaining_cats)}: {obj_category}.") + try: + sim = Simulator(mode="headless", use_pb_gui=True) + sim.import_scene(EmptyScene(floor_plane_rgba=[0.6, 0.6, 0.6, 1])) + for i, obj_model in enumerate(get_object_models_of_category(obj_category)): + obj_name = "{}_{}".format(obj_category, obj_model) + model_path = get_ig_model_path(obj_category, obj_model) + filename = os.path.join(model_path, "urdf", obj_model + ".urdf") + + print( + "Visualizing category {}, model {}".format(obj_category, obj_model) + ) + bbox = URDFObject( + filename, + name=obj_name, + category=obj_category, + model_path=model_path, + fixed_base=True, + ).bounding_box + + # Get the right scale + scale = np.min(1 / bbox) + simulator_obj = URDFObject( + filename, + name=obj_name, + category=obj_category, + model_path=model_path, + fixed_base=True, + scale=np.array([scale, scale, scale]), + ) + + sim.import_object(simulator_obj) + simulator_obj.set_bbox_center_position_orientation( + np.array([i + 0.5, 0.5, 0.5]), np.array([0, 0, 0, 1]) + ) + + print("Synset info:", get_synset(obj_category)) + user_input = input("Hit enter to continue, 's' to skip") + if user_input == "s": + save_to_skip_file(obj_category, skip_file_path) + + with open(record_path, "w") as f: + processed_cats.add(obj_category) + json.dump(sorted(processed_cats), f) + + finally: + sim.disconnect() + shutil.rmtree( + PIPELINE_ROOT / "artifacts/aggregate/scene_instances", + ignore_errors=True, + ) + + +def save_to_skip_file(category, skip_file_path): + skipped_categories = set() + + if os.path.exists(skip_file_path): + with open(skip_file_path, "r") as f: + skipped_categories = set(json.load(f)) + + skipped_categories.add(category) + + with open(skip_file_path, "w") as f: + json.dump(sorted(skipped_categories), f) + + +def get_synset(category): + if category not in CATEGORY_TO_SYNSET: + return "", "" + + synset_name = CATEGORY_TO_SYNSET[category] + + # Read the custom synsets from the CSV file + custom_synsets = [] + with open(PIPELINE_ROOT / "metadata/synsets.csv", "r") as csvfile: + reader = csv.reader(csvfile) + for row in reader: + if synset_name == row[0].strip(): + return row[1] + " (custom synset)", row[2] + "(hypernyms): " + ( + wn.synset(row[2]) + ).definition() + try: + synset = wn.synset(synset_name) + except: + return synset_name, "No definition found" + return synset.name(), synset.definition() + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + if len(sys.argv) != 3: + print( + "Usage: python -m b1k_pipeline.category_qa_viewer dataset_path record_file_path.json" + ) + sys.exit(1) + main(sys.argv[1], sys.argv[2]) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_collisions_challenge.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_collisions_challenge.py new file mode 100644 index 0000000000000000000000000000000000000000..9bc1070396ac644d41467c7a256779b8c968ec81 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_collisions_challenge.py @@ -0,0 +1,94 @@ +import json + +import b1k_pipeline.utils + + +OUTPUT_PATH = "artifacts/pipeline/check_collisions_challenge.json" + + +def get_scene_parts(scene_target): + scene_name = scene_target.replace("scenes/", "") + object_list_path = ( + b1k_pipeline.utils.PIPELINE_ROOT + / "cad" + / scene_target + / "artifacts" + / "object_list.json" + ) + + with open(object_list_path, "r") as f: + room_object_list = json.load(f) + + scene_parts = {scene_name} + for partial_scene_name in room_object_list.get("outgoing_portals", {}): + scene_parts.add(partial_scene_name) + + return sorted("scenes/" + scene_part for scene_part in scene_parts) + + +def load_collision_result(scene_target): + collision_path = ( + b1k_pipeline.utils.PIPELINE_ROOT + / "cad" + / scene_target + / "artifacts" + / "check_collisions.json" + ) + + if not collision_path.exists(): + return { + "success": False, + "collisions": [], + "error": f"Missing collision output: {collision_path}", + } + + with open(collision_path, "r") as f: + return json.load(f) + + +def main(): + challenge_scenes = b1k_pipeline.utils.params.get("challenge_scenes", []) + challenge_scenes_and_deps = b1k_pipeline.utils.params.get( + "challenge_scenes_and_deps", challenge_scenes + ) + + scene_parts = {} + errors = {} + for scene_target in challenge_scenes: + try: + parts = get_scene_parts(scene_target) + except Exception as e: + parts = [scene_target] + errors[scene_target] = repr(e) + + scene_parts[scene_target] = parts + + collision_results = { + scene_target: load_collision_result(scene_target) + for scene_target in sorted(challenge_scenes_and_deps) + } + failed_scenes = sorted( + scene_target + for scene_target, result in collision_results.items() + if not result["success"] + ) + + results = { + "success": not errors and not failed_scenes, + "challenge_scenes": challenge_scenes, + "challenge_scenes_and_deps": challenge_scenes_and_deps, + "scene_parts": scene_parts, + "checked_scenes": sorted(challenge_scenes_and_deps), + "failed_scenes": failed_scenes, + "errors": errors, + "collision_results": collision_results, + } + + output_path = b1k_pipeline.utils.PIPELINE_ROOT / OUTPUT_PATH + output_path.parent.mkdir(parents=True, exist_ok=True) + with open(output_path, "w") as f: + json.dump(results, f, indent=4) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_dataset_distribution_slurm.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_dataset_distribution_slurm.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3e008e669f3b48e116a4f2f28e444b511c363a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_dataset_distribution_slurm.sh @@ -0,0 +1,6 @@ +sinfo -p viscam -o "%N,%n" -h | \ + sed s/,.*//g | \ + xargs -L1 -I{} \ + sbatch \ + --account=viscam --partition=viscam --nodelist={} --mem=2G --cpus-per-task=1 \ + --wrap 'python -c '\''import os; print(os.path.exists("/scr-ssd/og-data-1-0-0"))'\'' > /cvgl2/u/cgokmen/dataset-check/${SLURM_NODELIST}.txt' \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_dvc_stage_current.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_dvc_stage_current.py new file mode 100644 index 0000000000000000000000000000000000000000..ce64309e9d529a39b64b025c60ebeed26b2912f5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_dvc_stage_current.py @@ -0,0 +1,28 @@ +import sys +from dvc.repo import Repo, lock_repo + + +def main(): + (stage_name,) = sys.argv[1:] + repo = Repo(".") + stage_infos = repo.stage.collect_granular(stage_name, with_deps=True) + stages = [si.stage for si in stage_infos] + assert len(stages) > 0, f"Stage {stage_name} not found!" + + up_to_date = True + with lock_repo(repo): + for s in stages: + if s.changed(allow_missing=True): + up_to_date = False + print(f"Stage {s} is out-of-date.") + + if up_to_date: + print(stage_name, "is up-to-date.") + sys.exit(0) + else: + print(stage_name, "is NOT up-to-date. Please reproduce.") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_success.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_success.py new file mode 100644 index 0000000000000000000000000000000000000000..f7500e4023f31688492bdd5b171b51c1754013d5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_success.py @@ -0,0 +1,28 @@ +import json +import sys +import b1k_pipeline.utils + + +def main(): + # Validate file paths. + json_file = (b1k_pipeline.utils.PIPELINE_ROOT / sys.argv[1]).absolute() + assert ( + json_file.exists() and json_file.suffix == ".json" + ), f"Can't find {json_file}." + success_file = (b1k_pipeline.utils.PIPELINE_ROOT / sys.argv[2]).absolute() + assert ( + not success_file.exists() and success_file.suffix == ".success" + ), f"Existing or invalid {success_file}." + + # Load the JSON file. + with open(json_file, "r") as f: + j = json.load(f) + + # Create the success file if successful. + if j["success"]: + with open(success_file, "w") as f: + pass + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_success_aggregate.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_success_aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6307ffbd14493cb84b9106f8bd5667c1a14a87 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/check_success_aggregate.py @@ -0,0 +1,44 @@ +import json +import sys +import b1k_pipeline.utils + + +def main(): + # Validate file paths. + failures = [] + target_type = "combined" if len(sys.argv) < 4 else sys.argv[3] + for target in b1k_pipeline.utils.get_targets(target_type): + target_path = b1k_pipeline.utils.PIPELINE_ROOT / "cad" / target + json_file = (target_path / sys.argv[1]).absolute() + assert ( + json_file.exists() and json_file.suffix == ".json" + ), f"Can't find {json_file}." + success_file = (b1k_pipeline.utils.PIPELINE_ROOT / sys.argv[2]).absolute() + assert ( + not success_file.exists() and success_file.suffix == ".success" + ), f"Existing or invalid {success_file}." + + # Load the JSON file. + with open(json_file, "r") as f: + j = json.load(f) + + if not j["success"]: + failures.append(target) + + # Create the success file if successful. + if failures: + print("Failures found!") + print("\n".join(failures)) + print( + "\nTo edit the failed files, copy and paste the below command, and use the Next Failed button on 3ds Max:" + ) + print("dvc unprotect " + " ".join(f"cad/{x}/processed.max" for x in failures)) + return + + # Otherwise, save the success file + with open(success_file, "w") as f: + pass + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_average_volumes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_average_volumes.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3aba24c9372575f8ac20fa6a7e6dd19002d669 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_average_volumes.py @@ -0,0 +1,88 @@ +from collections import defaultdict +from concurrent import futures +import numpy as np +import tqdm +import json + +from b1k_pipeline import mesh_tree +from b1k_pipeline.utils import PipelineFS, get_targets, parse_name + + +def process_target(target): + # Get the mesh tree + G = mesh_tree.build_mesh_tree( + target, load_upper=False, load_bad=False, load_nonzero=False + ) + roots = [node for node, in_degree in G.in_degree() if in_degree == 0] + + # Compute volumes from this target + volumes = defaultdict(dict) + errors = {} + for node in roots: + try: + assert ( + "combined_collision_mesh" in G.nodes[node] + ), f"Node {node} does not have a combined collision mesh." + + obj_volume = G.nodes[node]["combined_collision_mesh"].volume + assert ( + obj_volume > 0 + ), f"Node {node} has a non-positive volume: {obj_volume}" + volumes[node[0]][node[1]] = obj_volume + except Exception as e: + errors[str(node)] = str(e) + + return volumes, errors + + +def main(): + target_futures = {} + targets = get_targets("combined") + + # Collect the volumes from each target + volumes = defaultdict(dict) + errors = {} + with futures.ProcessPoolExecutor(max_workers=16) as executor: + # Submit all targets for execution + for target in tqdm.tqdm(targets): + target_futures[executor.submit(process_target, target)] = target + + # Collect the volumes from each target + with tqdm.tqdm(total=len(target_futures)) as pbar: + for future in futures.as_completed(target_futures.keys()): + target = target_futures[future] + target_volumes, target_errors = future.result() + + if target_errors: + errors[target] = target_errors + + for category, category_volumes in target_volumes.items(): + volumes[category].update(category_volumes) + + pbar.update(1) + + # Convert the volumes to average volumes + average_volumes = { + category: np.median(list(category_volumes.values())) + for category, category_volumes in volumes.items() + } + + with PipelineFS() as pipeline_fs: + with pipeline_fs.pipeline_output().open( + "collision_average_volumes.json", "w" + ) as f: + # TODO: set success + json.dump( + { + "success": True, + "average_volumes": average_volumes, + "volumes": volumes, + "errors": errors, + }, + f, + indent=4, + ) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_complaint_viewer.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_complaint_viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e6901018107bc572c9bd558a75e45b32d51642 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_complaint_viewer.py @@ -0,0 +1,235 @@ +from collections import defaultdict +from contextlib import contextmanager +import hashlib +import os +import random +import sys +import numpy as np +import tqdm + +import matplotlib.pyplot as plt +import pybullet as p +import json +from fs.zipfs import ZipFS +from fs.tempfs import TempFS +import b1k_pipeline.utils + + +@contextmanager +def suppress_stdout(): + fd = sys.stdout.fileno() + + def _redirect_stdout(to): + sys.stdout.close() # + implicit flush() + os.dup2(to.fileno(), fd) # fd writes to 'to' file + sys.stdout = os.fdopen(fd, "w") # Python writes to fd + + with os.fdopen(os.dup(fd), "w") as old_stdout: + with open(os.devnull, "w") as file: + _redirect_stdout(to=file) + try: + yield # allow code to be run with the redirected stdout + finally: + _redirect_stdout(to=old_stdout) # restore stdout. + # buffering and flags such as + # CLOEXEC may be different + + +def load_mesh(mesh_fs, mesh_fn, index, offset=None, scale=None): + # First, load into trimesh + m = b1k_pipeline.utils.load_mesh( + mesh_fs, mesh_fn, force="mesh", skip_materials=index > 0 + ) + + # Apply the desired offset if one is provided. Otherwise, center. + if offset is None: + offset = -m.centroid + m.apply_translation(offset) + + # Scale the object to fit in the [1, 1, 1] bounding box + if scale is None: + scale = 1 / m.bounding_box.extents.max() + m.apply_scale(scale) + + hulls = [m] + if index != 0: + hulls = m.split(only_watertight=True) + + # Apply a different color to each part + cmap = plt.get_cmap("hsv") + colors = cmap(np.linspace(0, 1, len(hulls) + 1)) + + for smi, sm in enumerate(hulls): + with TempFS() as temp_fs: + # Save as an OBJ to a temp directory + b1k_pipeline.utils.save_mesh(sm, temp_fs, mesh_fn) + + # Load the obj into pybullet + vis_kwargs = { + "shapeType": p.GEOM_MESH, + "fileName": temp_fs.getsyspath(mesh_fn), + } + if index > 0: + vis_kwargs["rgbaColor"] = colors[smi] + vis = p.createVisualShape(**vis_kwargs) + bid = p.createMultiBody( + baseVisualShapeIndex=vis, basePosition=[index * 1.5, 0, 0] + ) + if bid == -1: + print("Could not load mesh", mesh_fn) + return + + label = mesh_fn + if index == 0: + label = "visual" + volume = sum(x.volume for x in hulls) + p.addUserDebugText( + text=f"{index}\n{label[:6]}\nv={len(m.vertices)}\nh={len(hulls)}\nvol=\n{volume:.2e}", + textPosition=[index * 1.5, 0, -1], + textOrientation=p.getQuaternionFromEuler([np.pi / 2, 0, 0]), + textSize=0.4, + ) + + # Return the offset so that everything can be aligned the same way. + return offset, scale + + +def select_mesh(target_output_fs, mesh_name, object_complaints): + with suppress_stdout(): + p.connect(p.GUI) + + try: + p.addUserDebugText( + text=mesh_name, + textPosition=[1.5, 0, 1], + textOrientation=p.getQuaternionFromEuler([np.pi / 2, 0, 0]), + textSize=0.5, + ) + + # First, load the visual mesh. + with suppress_stdout(): + with ( + target_output_fs.open("meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + zip_fs.opendir(mesh_name) as mesh_fs, + ): + visual_offset, visual_scale = load_mesh(mesh_fs, f"{mesh_name}.obj", 0) + + # Load in each of the meshes + with ( + target_output_fs.open("collision_meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + zip_fs.opendir(mesh_name) as mesh_fs, + ): + candidates = [] + filenames = [x.name for x in mesh_fs.filterdir("/", files=["*.obj"])] + for i, fn in enumerate(sorted(filenames)): + # Load the candidate + if load_mesh(mesh_fs, fn, i + 1, visual_offset, visual_scale): + candidates.append(fn.replace(".obj", "")) + else: + candidates.append(None) + + # Fix the camera + p.resetDebugVisualizerCamera( + cameraDistance=6, + cameraYaw=0, + cameraPitch=0, + cameraTargetPosition=[len(candidates) * 1.5 / 2, 0, 0], + ) + + parsed_name = b1k_pipeline.utils.parse_name(mesh_name) + object_key = parsed_name.group("category") + "-" + parsed_name.group("model_id") + print("\n".join(object_complaints[object_key])) + + input("Press enter to continue.") + finally: + with suppress_stdout(): + p.disconnect() + + +def main(): + with b1k_pipeline.utils.PipelineFS() as pipeline_fs: + all_targets = b1k_pipeline.utils.get_targets("scenes") + random.shuffle(all_targets) + + # Now get a list of all the objects that we can process. + print("Getting list of objects to process...") + candidates = {} + total_in_batch = 0 + object_complaints = defaultdict(list) + for target in tqdm.tqdm(all_targets): + with ( + pipeline_fs.target_output(target) as target_output_fs, + pipeline_fs.target(target) as target_fs, + ): + if not target_output_fs.exists( + "collision_meshes.zip" + ) or not target_output_fs.exists("object_list.json"): + continue + + with target_output_fs.open("object_list.json", "r") as f: + mesh_list = json.load(f)["meshes"] + + complaints_file = "complaints.json" + if target_fs.exists(complaints_file): + with target_fs.open(complaints_file, "r") as f: + try: + complaints = json.load(f) + except: + raise ValueError(f"Could not load complaints from {target}") + for c in complaints: + if ( + c["message"] + != "Was at least one of the collision mesh candidates acceptable?" + ): + continue + object_complaints[c["object"]].append(c["complaint"]) + + with ( + target_output_fs.open("collision_meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + ): + for mesh_name in mesh_list: + parsed_name = b1k_pipeline.utils.parse_name(mesh_name) + if not parsed_name: + print("Bad name", parsed_name) + continue + should_convert = ( + int(parsed_name.group("instance_id")) == 0 + and not parsed_name.group("bad") + and parsed_name.group("joint_side") != "upper" + and parsed_name.group("category") + not in ("walls", "floors", "ceilings") + ) + if not should_convert: + continue + object_key = ( + parsed_name.group("category") + + "-" + + parsed_name.group("model_id") + ) + if object_key not in object_complaints: + continue + if not zip_fs.exists(mesh_name): + print("Missing mesh", mesh_name) + continue + + total_in_batch += 1 + + candidates[mesh_name] = target + + print("Total objects in your batch:", total_in_batch) + + # Start iterating. + for i, (mesh_name, target) in enumerate(candidates.items()): + print( + "\n--------------------------------------------------------------------------" + ) + print(f"{i + 1} / {len(candidates)}: {mesh_name} (from {target})\n") + with pipeline_fs.target_output(target) as target_output_fs: + select_mesh(target_output_fs, mesh_name, object_complaints) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_dataset_generation.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_dataset_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3910e73789825a1805bb2980ca1f94fb4f2862 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_dataset_generation.py @@ -0,0 +1,164 @@ +from collections import defaultdict +from concurrent.futures import ProcessPoolExecutor, as_completed +from contextlib import contextmanager +import hashlib +import os +import re +import sys +import numpy as np +import tqdm + +import matplotlib.pyplot as plt +import pybullet as p +import json +from fs.zipfs import ZipFS +from fs.osfs import OSFS +import fs.copy +import trimesh +import b1k_pipeline.utils + + +def load_mesh(mesh_fs, option_name, mesh_fns, output_fs, offset): + # First, load into trimesh + hulls = [ + b1k_pipeline.utils.load_mesh( + mesh_fs, mesh_fn, force="mesh", skip_materials=True + ) + for mesh_fn in mesh_fns + ] + # Check that none of the hulls has zero volume + # if index != 0 and any(x.volume == 0 for x in hulls): + # return + m = trimesh.util.concatenate(hulls) + + # Apply the desired offset if one is provided. Otherwise, center. + m.apply_translation(-offset) + + # Scale the object to fit in the [1, 1, 1] bounding box + # if scale is None: + # scale = 1 / m.bounding_box.extents.max() + # m.apply_scale(scale) + # for mesh in hulls: + # mesh.apply_scale(scale) + + # Apply a different color to each part + b1k_pipeline.utils.save_mesh(m, output_fs, f"{option_name}.obj") + + +def select_mesh(target_output_fs, mesh_name, out_fs): + with ( + target_output_fs.open("meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + zip_fs.opendir(mesh_name) as mesh_fs, + out_fs.makedir(mesh_name) as mesh_out_fs, + ): + fs.copy.copy_fs(mesh_fs, mesh_out_fs) + fs.copy.copy_file(mesh_fs, f"{mesh_name}.obj", mesh_out_fs, "visual.obj") + # fs.copy.copy_file(mesh_fs, f"{mesh_name}.mtl", mesh_out_fs, f"{mesh_name}.mtl") + # fs.copy.copy_dir(mesh_fs, "material", mesh_out_fs, "material") + + offset = b1k_pipeline.utils.load_mesh( + mesh_fs, f"{mesh_name}.obj", force="mesh", skip_materials=True + ).centroid + + # Load in each of the meshes + with ( + target_output_fs.open("collision_meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + zip_fs.opendir(mesh_name) as mesh_fs, + ): + filenames = [x.name for x in mesh_fs.filterdir("/", files=["*.obj"])] + filename_bases = {x.rsplit("-", 1)[0] for x in filenames} + for i, fn in enumerate(sorted(filename_bases)): + # Load the candidate + selection_matching_pattern = re.compile(fn + r"-(\d+).obj") + load_mesh( + mesh_fs, + fn, + [x for x in filenames if selection_matching_pattern.fullmatch(x)], + mesh_out_fs, + offset, + ) + + +# Start iterating. +def process_target(target, target_meshes): + with OSFS(target) as target_output_fs, OSFS("/scr/cmesh_test_dataset") as out_fs: + # Load the meshes and do the selection. + for mesh_name in target_meshes: + select_mesh(target_output_fs, mesh_name, out_fs) + + +def preprocess_target(target): + candidates = [] + with OSFS(target) as target_output_fs: + if not target_output_fs.exists("collision_meshes.zip"): + return + + with ( + target_output_fs.open("collision_meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + target_output_fs.open("meshes.zip", "rb") as meshes_zip_file, + ZipFS(meshes_zip_file) as meshes_zip_fs, + ): + for mesh_name in meshes_zip_fs.listdir("/"): + parsed_name = b1k_pipeline.utils.parse_name(mesh_name) + if not parsed_name: + print("Bad name", parsed_name) + continue + mesh_model = parsed_name.group("model_id") + mesh_link = parsed_name.group("link_name") + if not mesh_link: + mesh_link = "base_link" + should_convert = ( + int(parsed_name.group("instance_id")) == 0 + and not parsed_name.group("bad") + and parsed_name.group("joint_side") != "upper" + ) + if not should_convert: + continue + + # collision_found = any("Mcollision" in item for item in meshes_zip_fs.listdir(mesh_name)) + # if collision_found: + # continue + + if not zip_fs.exists(mesh_name): + print("Missing mesh", mesh_name) + continue + + candidates.append(mesh_name) + + return candidates + + +def main(): + all_targets = ["/scr/BEHAVIOR-1K/asset_pipeline/obj_out"] + + # Now get a list of all the objects that we can process. + print("Getting list of objects to process...") + candidates = defaultdict(list) + with ProcessPoolExecutor(max_workers=32) as executor: + futures = {} + for target in tqdm.tqdm(all_targets): + futures[executor.submit(preprocess_target, target)] = target + + for future in tqdm.tqdm(as_completed(futures.keys()), total=len(futures)): + target = futures[future] + candidates[target] = future.result() + + print( + "Total objects (including completed) in your batch:", + sum(len(x) for x in candidates.values()), + ) + + with ProcessPoolExecutor(max_workers=32) as executor: + futures = [] + for target, mesh_names in candidates.items(): + futures.append(executor.submit(process_target, target, mesh_names)) + + for future in tqdm.tqdm(as_completed(futures), total=len(futures)): + future.result() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_generation.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..c36d305d5457db236f477a57be22bfc3ea125399 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_generation.py @@ -0,0 +1,531 @@ +from concurrent import futures +import os +import random +import subprocess +import sys +import tempfile +import traceback +from dask.distributed import Client +import itertools +import tqdm +import numpy as np +import io +import json +import uuid + +import trimesh +import random + +from fs.osfs import OSFS +from fs.zipfs import ZipFS + +from b1k_pipeline.utils import ( + PipelineFS, + get_targets, + parse_name, + load_mesh, + save_mesh, + launch_cluster, +) + +GENERATE_SELECTED_ONLY = False +VHACD_EXECUTABLE = "TestVHACD" +COACD_SCRIPT_PATH = "coacd" + +MAX_VERTEX_COUNT = 60 +REDUCTION_STEP = 5 + +resolutions = [ + "1000000" +] ## [-r] : Total number of voxels to use. Default is 100,000 +depth = [ + "20" +] # ["5", "10", "20"] ## [-d] : Maximum recursion depth. Default value is 10. +maxHullVertCounts = [ + "60" +] ## [-v] : Maximum number of vertices in the output convex hull. Default value is 64 +maxHulls = [ + "4", + "8", + "32", +] ## [-h] : Maximum number of output convex hulls. Default is 32 +fillmode = [ + "flood" +] # ["flood", "surface", "raycast"] ## [-f] : Fill mode. Default is 'flood', also 'surface' and 'raycast' are valid. +errorp = [ + "10" +] ## [-e] : Volume error allowed as a percentage. Default is 1%. Valid range is 0.001 to 10 +split = [ + "true" +] ## [-p] : If false, splits hulls in the middle. If true, tries to find optimal split plane location. False by default. +edgelength = [ + "2" +] ## [-l] : Minimum size of a voxel edge. Default value is 2 voxels. + +thresholds = [ + "0.05" +] # ["0.05", "0.1", "0.5"] ## [-t] : concavity threshold for terminating the decomposition (0.01~1), default = 0.05. +prep_resolutions = [ + "100" +] # , "100", "75", "25"] ## [-pr] : resolution for manifold preprocess (20~100), default = 50. +max_convex_hulls = [ + "8", + "32", +] # , "32", "64"] ## [-c] : max # convex hulls in the result, -1 for no maximum limitation, works only when merge is enabled, +# default = -1 (may introduce convex hull with a concavity larger than the threshold) + + +def option_bbox(m, dask_client): + axis_aligned_bbox = m.bounding_box_oriented + bbox = trimesh.creation.box( + axis_aligned_bbox.primitive.extents, axis_aligned_bbox.primitive.transform + ) + return [bbox] + + +def generate_option_coacd(threshold, prep_resolution, max_convex_hull): + def _option_coacd(m, dask_client): + # Use IO to send the mesh to the worker + input_stream = io.BytesIO() + m.export(input_stream, file_type="obj") + coacd_future = dask_client.submit( + coacd_worker, + input_stream.getvalue(), + threshold, + prep_resolution, + max_convex_hull, + retries=5, + ) + result = coacd_future.result() + if not result: + raise ValueError("coacd failed") + # Read the result back into a trimesh + output_stream = io.BytesIO(result) + # TODO: Do NOT do this + combined_mesh = trimesh.load( + output_stream, + file_type="obj", + force="mesh", + skip_material=True, + merge_tex=True, + merge_norm=True, + ) + return combined_mesh.split(only_watertight=False) + + return _option_coacd + + +def coacd_worker(file_bytes, t, pr, max_hull): + # This is the function that runs on the worker. It needs to locally save the sent file bytes, + # call VHACD on that file, grab the output file's contents and return it as a bytes object. + with tempfile.TemporaryDirectory(prefix=str(uuid.uuid4())) as td: + in_path = os.path.join(td, "in.obj") + out_path = os.path.join( + td, "decomp.obj" + ) # This is the path that VHACD outputs to. + with open(in_path, "wb") as f: + f.write(file_bytes) + + vhacd_cmd = [ + str(COACD_SCRIPT_PATH), + "-i", + in_path, + "-o", + out_path, + "-t", + t, + "-c", + max_hull, + "-pr", + "50", + ] # For now, we are forcing the default resolution + try: + subprocess.run( + vhacd_cmd, + shell=False, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=td, + check=True, + ) + with open(out_path, "rb") as f: + return f.read() + except subprocess.CalledProcessError as e: + raise ValueError( + f"COACD failed with exit code {e.returncode}. Output:\n{e.output}" + ) + except futures.CancelledError as e: + raise ValueError("Got cancelled.") + + +def generate_option_vhacd( + resolution, depth, fillmode, errorp, split, edgelength, maxHullVertCount, maxHull +): + def _option_vhacd(m, dask_client): + input_stream = io.BytesIO() + m.export(input_stream, file_type="obj") + vhacd_future = dask_client.submit( + vhacd_worker, + input_stream.getvalue(), + resolution, + depth, + fillmode, + errorp, + split, + edgelength, + maxHullVertCount, + maxHull, + retries=3, + ) + result = vhacd_future.result() + if not result: + raise ValueError("vhacd failed") + # Read the result back into a trimesh + output_stream = io.BytesIO(result) + # TODO: Do NOT do this. + combined_mesh = trimesh.load( + output_stream, + file_type="obj", + force="mesh", + skip_material=True, + merge_tex=True, + merge_norm=True, + ) + return combined_mesh.split(only_watertight=False) + + return _option_vhacd + + +def vhacd_worker( + file_bytes, + resolution, + depth, + fillmode, + errorp, + split, + edgelength, + maxHullVertCount, + maxHull, +): + # This is the function that runs on the worker. It needs to locally save the sent file bytes, + # call VHACD on that file, grab the output file's contents and return it as a bytes object. + with tempfile.TemporaryDirectory(prefix=str(uuid.uuid4())) as td: + in_path = os.path.join(td, "in.obj") + out_path = os.path.join( + td, "decomp.obj" + ) # This is the path that VHACD outputs to. + with open(in_path, "wb") as f: + f.write(file_bytes) + + vhacd_cmd = [ + str(VHACD_EXECUTABLE), + in_path, + "-r", + resolution, + "-d", + depth, + "-f", + fillmode, + "-e", + errorp, + "-p", + split, + "-l", + edgelength, + "-v", + maxHullVertCount, + "-h", + maxHull, + ] + try: + proc = subprocess.run( + vhacd_cmd, + shell=False, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=td, + check=True, + ) + if not os.path.exists(out_path): + raise ValueError( + "VHACD failed to produce an output file. VHACD output:\n" + + proc.stdout.decode("utf-8") + ) + with open(out_path, "rb") as f: + return f.read() + except subprocess.CalledProcessError as e: + raise ValueError( + f"VHACD failed with exit code {e.returncode}. Output:\n{e.output}" + ) + except futures.CancelledError as e: + raise ValueError("Got cancelled.") + + +PROCESSING_OPTIONS = ( + [ + # Fixed options + ("chull", lambda m, dask_client: [m]), + ("bbox", option_bbox), + ] + + [ + # VHACD options + ( + "vhacd-r_%s-d_%s-f_%s-e_%s-p_%s-l_%s-v%s-h%s" % param_combo, + generate_option_vhacd(*param_combo), + ) + for param_combo in itertools.product( + resolutions, + depth, + fillmode, + errorp, + split, + edgelength, + maxHullVertCounts, + maxHulls, + ) + ] + + [ + # COACD options + ("coacd-t_%s-pr_%s-c_%s" % param_combo, generate_option_coacd(*param_combo)) + for param_combo in itertools.product( + thresholds, prep_resolutions, max_convex_hulls + ) + ] +) + + +convexify_vhacd_substep = generate_option_vhacd( + "1000000", "20", "flood", "10", "true", "2", "60", "1" +) + + +def convexify_and_reduce(m, dask_client): + try: + # Try directly converting the mesh into a convex hull + convex_m = trimesh.convex.convex_hull(m) + except: + # If that doesn't work, retry with a simplified VHACD run + convex_m = trimesh.convex.convex_hull(convexify_vhacd_substep(m, dask_client)) + assert convex_m.is_watertight, f"Found non-watertight mesh - should not be possible" + + # Check its vertex count and reduce as necessary + reduced_m = convex_m + reduction_target_vertex_count = MAX_VERTEX_COUNT + REDUCTION_STEP + while len(reduced_m.vertices) > MAX_VERTEX_COUNT: + # Reduction function takes a number of faces as its input. We estimate this, if it doesn't + # work out, we keep trying with a smaller estimate. + reduction_target_vertex_count -= REDUCTION_STEP + if reduction_target_vertex_count < MAX_VERTEX_COUNT / 2: + # Don't want to reduce too far + raise ValueError("Vertex reduction failed.") + + reduction_target_face_count = int( + reduction_target_vertex_count / len(convex_m.vertices) * len(convex_m.faces) + ) + reduced_m = convex_m.simplify_quadric_decimation(reduction_target_face_count) + reduced_m = trimesh.convex.convex_hull(reduced_m) + + assert ( + reduced_m.is_watertight + ), "Reduction & convexify resulted in non-watertight mesh" + return reduced_m + + +def process_object_with_option(m, out_fs, option_name, option_fn, dask_client): + # Run the option + submeshes = option_fn(m, dask_client) + assert len(submeshes) > 0, f"{option_name} returned no submeshes" + assert len(submeshes) <= 32, f"{option_name} returned too many submeshes" + + # Convexify and reduce each submesh + reduced_submeshes = [ + convexify_and_reduce(submesh, dask_client) for submesh in submeshes + ] + + # Save the result + for i, submesh in enumerate(reduced_submeshes): + save_mesh(submesh, out_fs, f"{option_name}-{i}.obj") + + +def process_target(target, pipeline_fs, link_executor, dask_client): + with pipeline_fs.target_output(target).open("object_list.json", "r") as f: + object_list = json.load(f) + mesh_list = object_list["meshes"] + manual_collision_list = { + parent + for obj, objtype, parent in object_list["max_tree"] + if "Mcollision" in obj + } + + target_fs = pipeline_fs.target_output(target) + + # Compute the in-fs hash. + script_hash = OSFS(os.path.dirname(__file__)).hash( + os.path.basename(__file__), "md5" + ) + in_hash = target_fs.hash("meshes.zip", "md5") + + # Compare it to the saved hash if one exists. + try: + if target_fs.exists("collision_meshes.zip"): + with ( + target_fs.open("collision_meshes.zip", "rb") as out_zip, + ZipFS(out_zip) as collision_mesh_archive_fs, + ): + if collision_mesh_archive_fs.exists("hash.txt"): + with collision_mesh_archive_fs.open("hash.txt", "r") as f: + out_hash = f.read() + + # Return if the hash has not changed. + # if in_hash + script_hash == out_hash: + if out_hash.startswith(in_hash): + print(target, "already processed, skipping.") + return + except: + pass + + print(f"Reprocessing {target} due to hash mismatch or missing file.") + + with ( + target_fs.open("meshes.zip", "rb") as in_zip, + target_fs.open("collision_meshes.zip", "wb") as out_zip, + ): + with ( + ZipFS(in_zip) as mesh_archive_fs, + ZipFS(out_zip, write=True) as collision_mesh_archive_fs, + ): + # Go through each object. + object_futures = {} + for mesh_name in mesh_list: + # First decide if we need to process this + parsed_name = parse_name(mesh_name) + should_convert = ( + int(parsed_name.group("instance_id")) == 0 + and not parsed_name.group("bad") + and parsed_name.group("joint_side") != "upper" + ) + has_existing_collision_mesh = mesh_name in manual_collision_list + if not should_convert or has_existing_collision_mesh: + continue + assert mesh_archive_fs.exists( + mesh_name + ), f"Mesh {mesh_name} does not exist in the archive." + # print(f"Start {mesh_name} from {target}") + + # Load the mesh + m = load_mesh( + mesh_archive_fs.opendir(mesh_name), + f"{mesh_name}.obj", + force="mesh", + skip_material=True, + merge_tex=True, + merge_norm=True, + ) + + # Check if we have already selected a processing option for this mesh + processing_options = PROCESSING_OPTIONS + if GENERATE_SELECTED_ONLY and target_fs.exists( + "collision_selection.json" + ): + with target_fs.open("collision_selection.json", "r") as f: + selection = json.load(f) + # Here we currently match the model ID and the link name + matching_key = ( + parsed_name.group("model_id"), + parsed_name.group("link_name"), + ) + for k, v in selection.items(): + vs = {v} + if v == "bbox": + vs.add("chull") + parsed_key = parse_name(k) + if not parsed_key: + continue + if ( + parsed_key.group("model_id"), + parsed_key.group("link_name"), + ) == matching_key: + # Get a list containing only the selected option + processing_options = [ + (option_name, option_fn) + for option_name, option_fn in processing_options + if option_name in vs + ] + break + + # Now queue a target for each of the processing options + mesh_dir = collision_mesh_archive_fs.makedir(mesh_name) + for option_name, option_fn in processing_options: + future = link_executor.submit( + process_object_with_option, + m, + mesh_dir, + option_name, + option_fn, + dask_client, + ) + object_futures[future] = mesh_name + "--" + option_name + + # Wait for all the futures - this acts as some kind of rate limiting on more futures being queued by blocking this thread + futures.wait(object_futures.keys()) + + # Save the hash + with collision_mesh_archive_fs.open("hash.txt", "w") as f: + f.write(in_hash + script_hash) + + # Accumulate the errors + error_msg = "" + for future, root_node in object_futures.items(): + exc = future.exception() + if exc: + error_msg += f"{root_node}: {exc}\n\n" + if error_msg: + raise ValueError(error_msg) + + +def main(): + with PipelineFS() as pipeline_fs: + errors = {} + target_futures = {} + + # dask_client = Client(sys.argv[1]) # + ":35423") + dask_client = launch_cluster(16) + + with ( + futures.ThreadPoolExecutor(max_workers=8) as target_executor, + futures.ThreadPoolExecutor(max_workers=200) as mesh_executor, + ): + targets = get_targets("combined") + for target in tqdm.tqdm(targets): + target_futures[ + target_executor.submit( + process_target, target, pipeline_fs, mesh_executor, dask_client + ) + ] = target + + with tqdm.tqdm(total=len(target_futures)) as object_pbar: + for future in futures.as_completed(target_futures.keys()): + try: + future.result() + except: + name = target_futures[future] + errors[name] = traceback.format_exc() + + object_pbar.update(1) + + remaining_targets = [ + v for k, v in target_futures.items() if not k.done() + ] + if len(remaining_targets) < 10: + print("Remaining:", remaining_targets) + + print("Finished processing") + + with pipeline_fs.pipeline_output().open( + "export_collision_meshes.json", "w" + ) as f: + json.dump({"success": not errors, "errors": errors}, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_selection.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..373463b39cb57568b3813ef202e618153c066d20 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_selection.py @@ -0,0 +1,334 @@ +from contextlib import contextmanager +import hashlib +import os +import re +import sys +import numpy as np +import tqdm + +import matplotlib.pyplot as plt +import pybullet as p +import json +from fs.zipfs import ZipFS +from fs.tempfs import TempFS +import trimesh +import b1k_pipeline.utils + +# These change the stepping logic +YOUR_ID = 0 +TOTAL_IDS = 1 + + +@contextmanager +def suppress_stdout(): + fd = sys.stdout.fileno() + + def _redirect_stdout(to): + sys.stdout.close() # + implicit flush() + os.dup2(to.fileno(), fd) # fd writes to 'to' file + sys.stdout = os.fdopen(fd, "w") # Python writes to fd + + with os.fdopen(os.dup(fd), "w") as old_stdout: + with open(os.devnull, "w") as file: + _redirect_stdout(to=file) + try: + yield # allow code to be run with the redirected stdout + finally: + _redirect_stdout(to=old_stdout) # restore stdout. + # buffering and flags such as + # CLOEXEC may be different + + +def load_mesh(mesh_fs, mesh_fns, basename, index, offset=None, scale=None): + # First, load into trimesh + hulls = [ + b1k_pipeline.utils.load_mesh( + mesh_fs, mesh_fn, force="mesh", skip_materials=index > 0 + ) + for mesh_fn in mesh_fns + ] + # Check that none of the hulls has zero volume + if index != 0 and any(x.volume == 0 for x in hulls): + return + m = trimesh.util.concatenate(hulls) + + # Apply the desired offset if one is provided. Otherwise, center. + if offset is None: + offset = -m.centroid + m.apply_translation(offset) + for mesh in hulls: + mesh.apply_translation(offset) + + # Scale the object to fit in the [1, 1, 1] bounding box + if scale is None: + scale = 1 / m.bounding_box.extents.max() + m.apply_scale(scale) + for mesh in hulls: + mesh.apply_scale(scale) + + # Apply a different color to each part + cmap = plt.get_cmap("hsv") + colors = cmap(np.linspace(0, 1, len(hulls) + 1)) + + for smi, sm in enumerate(hulls): + with TempFS() as temp_fs: + # Save as an OBJ to a temp directory + b1k_pipeline.utils.save_mesh(sm, temp_fs, "obj.obj") + + # Load the obj into pybullet + vis_kwargs = { + "shapeType": p.GEOM_MESH, + "fileName": temp_fs.getsyspath("obj.obj"), + } + if index > 0: + vis_kwargs["rgbaColor"] = colors[smi] + vis = p.createVisualShape(**vis_kwargs) + bid = p.createMultiBody( + baseVisualShapeIndex=vis, basePosition=[index * 1.5, 0, 0] + ) + if bid == -1: + print("Could not load mesh") + return + + label = basename + if index == 0: + label = "visual" + volume = sum(x.volume for x in hulls) + p.addUserDebugText( + text=f"{index}\n{label[:6]}\nv={len(m.vertices)}\nh={len(hulls)}\nvol=\n{volume:.2e}", + textPosition=[index * 1.5, 0, -1], + textOrientation=p.getQuaternionFromEuler([np.pi / 2, 0, 0]), + textSize=0.4, + ) + + # Return the offset so that everything can be aligned the same way. + return offset, scale + + +def select_mesh(target_output_fs, mesh_name): + p.resetSimulation() + + try: + p.addUserDebugText( + text=mesh_name, + textPosition=[1.5, 0, 1], + textOrientation=p.getQuaternionFromEuler([np.pi / 2, 0, 0]), + textSize=0.5, + ) + + # First, load the visual mesh. + with suppress_stdout(): + with ( + target_output_fs.open("meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + zip_fs.opendir(mesh_name) as mesh_fs, + ): + visual_offset, visual_scale = load_mesh( + mesh_fs, [f"{mesh_name}.obj"], mesh_name, 0 + ) + + # Load in each of the meshes + with ( + target_output_fs.open("collision_meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + zip_fs.opendir(mesh_name) as mesh_fs, + ): + candidates = [] + filenames = [x.name for x in mesh_fs.filterdir("/", files=["*.obj"])] + filename_bases = {x.rsplit("-", 1)[0] for x in filenames} + for i, fn in enumerate(sorted(filename_bases)): + # Load the candidate + selection_matching_pattern = re.compile(fn + r"-(\d+).obj") + if load_mesh( + mesh_fs, + [ + x + for x in filenames + if selection_matching_pattern.fullmatch(x) + ], + fn, + i + 1, + visual_offset, + visual_scale, + ): + candidates.append(fn) + else: + candidates.append(None) + + # Fix the camera + p.resetDebugVisualizerCamera( + cameraDistance=6, + cameraYaw=0, + cameraPitch=0, + cameraTargetPosition=[len(candidates) * 1.5 / 2, 0, 0], + ) + + # Ask user to choose which is best mesh + mesh_opt = None + print("Choose a collision mesh for the object shown on the far left.") + print("Note that we need to pick a mesh for every object for the time being.") + print( + "If none of the collision meshes fits your objects well, still pick the best one." + ) + print( + "You will be able to leave a complaint for the objects that don't fit well." + ) + while True: + valid_inputs = [str(x) for x in range(1, len(candidates) + 1)] + comp_res = input( + f"Choose a mesh to save 1-{len(candidates)} or 's' to temporarily skip: " + ).lower() + if comp_res == "s": + return None, None + try: + idx = valid_inputs.index(comp_res) + mesh_opt = candidates[idx] + break + except ValueError: + continue + + print("Was at least one of the collision mesh candidates acceptable?") + complaint = input("If so, press enter. Otherwise, type a complaint: ").strip() + complaint = complaint if complaint else None + + return mesh_opt, complaint + except: + pass + + +def main(): + with b1k_pipeline.utils.PipelineFS() as pipeline_fs: + all_targets = sorted(b1k_pipeline.utils.get_targets("combined")) + + # Get a list of all the objects that have already been processed + print("Getting list of processed objects...") + selections = set() + for target in tqdm.tqdm(all_targets): + with pipeline_fs.target_output(target) as target_output_fs: + if not target_output_fs.exists("collision_selection.json"): + continue + + with target_output_fs.open("collision_selection.json", "r") as f: + this_selections = [ + b1k_pipeline.utils.parse_name(x) for x in json.load(f).keys() + ] + selections |= { + ( + x.group("model_id"), + x.group("link_name") + if x.group("link_name") + else "base_link", + ) + for x in this_selections + } + + # Now get a list of all the objects that we can process. + print("Getting list of objects to process...") + candidates = [] + total_in_batch = 0 + for target in tqdm.tqdm(all_targets): + with pipeline_fs.target_output(target) as target_output_fs: + if not target_output_fs.exists( + "collision_meshes.zip" + ) or not target_output_fs.exists("object_list.json"): + continue + + with target_output_fs.open("object_list.json", "r") as f: + object_list = json.load(f) + + mesh_list = object_list["meshes"] + + with ( + target_output_fs.open("collision_meshes.zip", "rb") as zip_file, + ZipFS(zip_file) as zip_fs, + target_output_fs.open("meshes.zip", "rb") as meshes_zip_file, + ZipFS(meshes_zip_file) as meshes_zip_fs, + ): + for mesh_name in mesh_list: + parsed_name = b1k_pipeline.utils.parse_name(mesh_name) + if not parsed_name: + print("Bad name", parsed_name) + continue + mesh_model = parsed_name.group("model_id") + mesh_link = parsed_name.group("link_name") + if not mesh_link: + mesh_link = "base_link" + should_convert = ( + int(parsed_name.group("instance_id")) == 0 + and not parsed_name.group("bad") + and parsed_name.group("joint_side") != "upper" + ) + hash_int = int(hashlib.md5(mesh_name.encode()).hexdigest(), 16) + if hash_int % TOTAL_IDS != YOUR_ID: + continue + if not should_convert: + continue + + collision_found = any( + "Mcollision" in item + for item in meshes_zip_fs.listdir(mesh_name) + ) + if collision_found: + continue + + if not zip_fs.exists(mesh_name): + print("Missing mesh", mesh_name) + continue + + total_in_batch += 1 + + matching_key = (mesh_model, mesh_link) + if matching_key in selections: + continue + candidates.append((mesh_name, target)) + + print("Total objects (including completed) in your batch:", total_in_batch) + + # Start iterating. + p.connect(p.GUI) + for i, (mesh_name, target) in enumerate(candidates): + print( + "\n--------------------------------------------------------------------------" + ) + print(f"{i + 1} / {len(candidates)}: {mesh_name} (from {target})\n") + with pipeline_fs.target_output(target) as target_output_fs: + # Load the meshes and do the selection. + result, complaint = select_mesh(target_output_fs, mesh_name) + if result is None: + continue + + # Now that we have the result, update the record + target_record = {} + if target_output_fs.exists("collision_selection.json"): + with target_output_fs.open("collision_selection.json", "r") as f: + target_record = json.load(f) + target_record[mesh_name] = result + with target_output_fs.open("collision_selection.json", "w") as f: + json.dump(target_record, f, indent=4, sort_keys=True) + + if complaint is not None: + parsed_name = b1k_pipeline.utils.parse_name(mesh_name) + object_key = ( + parsed_name.group("category") + "-" + parsed_name.group("model_id") + ) + complaint = { + "object": object_key, + "message": "Was at least one of the collision mesh candidates acceptable?", + "complaint": complaint, + "processed": False, + } + + with pipeline_fs.target(target) as target_fs: + complaints_file = "complaints.json" + complaints = [] + if target_fs.exists(complaints_file): + with target_fs.open(complaints_file, "r") as f: + complaints = json.load(f) + complaints.append(complaint) + with target_fs.open(complaints_file, "w") as f: + json.dump(complaints, f, indent=4) + p.disconnect() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_selection_validation.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_selection_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..8d36d98933e96494498b835fc8983b1d66b12a9b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/collision_selection_validation.py @@ -0,0 +1,222 @@ +import collections +from concurrent import futures +import traceback +import numpy as np +import tqdm +import json + +from b1k_pipeline import mesh_tree +from b1k_pipeline.utils import PipelineFS, get_targets, parse_name + +NUKE_SELECTIONS = False + + +def get_aabb_corners(mesh): + aabb = mesh.bounding_box + center = aabb.transform[:3, 3] + half_extent = aabb.extents / 2 + return np.array([center - half_extent, center + half_extent]) + + +def compare_aabbs(lower_mesh, collision_meshes): + # Get the AABB of the lower mesh + lower_aabb = get_aabb_corners(lower_mesh) + lower_min = np.min(lower_aabb, axis=0) + lower_max = np.max(lower_aabb, axis=0) + + # Get the AABB of the collision meshes + collision_aabbs = np.concatenate( + [get_aabb_corners(mesh) for mesh in collision_meshes], axis=0 + ) + collision_min = np.min(collision_aabbs, axis=0) + collision_max = np.max(collision_aabbs, axis=0) + + # Check if the corners are close enough + min_diff = np.linalg.norm(lower_min - collision_min) + max_diff = np.linalg.norm(lower_max - collision_max) + if min_diff > 2: + return f"Lower mesh AABB min is too far ({min_diff}m) away from collision mesh AABB min." + elif max_diff > 2: + return f"Lower mesh AABB max is too far ({max_diff}m) away from collision mesh AABB max." + + return None + + +def process_target(target): + try: + with PipelineFS() as pipeline_fs: + errors = collections.defaultdict(list) + + with pipeline_fs.target_output(target).open( + "collision_selection.json", "r" + ) as f: + collision_selection = json.load(f) + + selected = {} + for obj in collision_selection: + m = parse_name(obj) + model = m.group("model_id") + link = m.group("link_name") + if not link: + link = "base_link" + if (model, link) in selected: + errors[obj].append( + "Duplicate collision selection. Seen before as " + + selected[(model, link)] + + "." + ) + selected[(model, link)] = obj + + # Get the mesh tree + G = mesh_tree.build_mesh_tree( + target, load_upper=False, load_bad=False, load_nonzero=False + ) + + # Check that each object matches at least one of the options + for node in G.nodes: + # If the object has a collision mesh we are probably good. + if "collision_mesh" in G.nodes[node]: + # Validate the mesh + splits = G.nodes[node]["collision_mesh"] + if len(splits) == 0: + errors[node].append( + "Collision mesh was found but contains no meshes." + ) + elif len(splits) > 32: + errors[node].append( + "Collision mesh was found but contains too many meshes: {len(splits)}." + ) + elif any(not split.is_watertight for split in splits): + errors[node].append( + "Collision mesh was found but contains non-watertight meshes." + ) + elif any( + not split.is_volume or split.volume <= 0 for split in splits + ): + errors[node].append( + "Collision mesh was found but contains zero volume meshes." + ) + elif any( + np.any(split.bounding_box.extents == 0) for split in splits + ): + errors[node].append( + "Collision mesh was found but contains zero bbox dimension meshes." + ) + else: + aabb_error = compare_aabbs( + G.nodes[node]["lower_mesh"], G.nodes[node]["collision_mesh"] + ) + if aabb_error and node[0] not in [ + "floors", + "ceilings", + "walls", + ]: + errors[node].append(aabb_error) + + # Identify manual collision mesh in error + if "manual_collision_filename" in G.nodes[node] and node in errors: + errors[node] = ["Manual " + x for x in errors[node]] + # If we reach here, no errors! + elif "manual_collision_filename" in G.nodes[node]: + # The object has a manual collision mesh but it was not loaded + errors[node].append( + "Manual collision mesh was found but could not be loaded." + ) + elif "collision_selection" not in G.nodes[node]: + # No collision selection was made + errors[node].append("No collision selection was made.") + elif ( + "collision_options" not in G.nodes[node] + or not G.nodes[node]["collision_options"] + ): + errors[node].append("No collision options were available.") + elif ( + G.nodes[node]["collision_selection"] + not in G.nodes[node]["collision_options"] + ): + errors[node].append( + "Collision selection was not in the available options." + ) + else: + errors[node].append("Something unexpected happened.") + + return errors + except Exception as e: + return {"Exception": str(e) + "\n" + traceback.format_exc()} + + +def main(): + errors = {} + target_futures = {} + targets = get_targets("combined") + + with futures.ProcessPoolExecutor(max_workers=16) as executor: + for target in tqdm.tqdm(targets): + target_futures[executor.submit(process_target, target)] = target + + with tqdm.tqdm(total=len(target_futures)) as pbar: + for future in futures.as_completed(target_futures.keys()): + target = target_futures[future] + target_errors = future.result() + if target_errors: + errors[target] = {k: v for k, v in target_errors.items()} + + pbar.update(1) + + if errors: + print("Errors found:") + for target in errors: + print("\n", target) + for node, msg in errors[target].items(): + print(" ", node, msg) + + with PipelineFS() as pipeline_fs: + if NUKE_SELECTIONS: + for target in errors: + # Load the collision selections + with pipeline_fs.target_output(target).open( + "collision_selection.json", "r" + ) as f: + target_selections = json.load(f) + + # Get model-link pairs that have errors + error_keys = { + (model, link) + for (_, model, _, link), error_list in errors[target].items() + if not all("Manual" in error for error in error_list) + # if error in ( + # "Collision selection was not in the available options.", + # ) + } + + # Build a new collision selection without the errors + new_selections = {} + for key, selection in target_selections.items(): + # Parse the key to get model ID and link name + parsed_name = parse_name(key) + model_id = parsed_name.group("model_id") + link_name = parsed_name.group("link_name") + if not link_name: + link_name = "base_link" + if (model_id, link_name) not in error_keys: + new_selections[key] = selection + else: + print("Removing", key) + + # Save the collision selection + with pipeline_fs.target_output(target).open( + "collision_selection.json", "w" + ) as f: + json.dump(new_selections, f, indent=4) + + with pipeline_fs.pipeline_output().open( + "collision_selection_validation.json", "w" + ) as f: + printable_errors = { + k: {str(k2): v2 for k2, v2 in v.items()} for k, v in errors.items() + } + json.dump({"success": not errors, "errors": printable_errors}, f, indent=4) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/combined_file_manifest.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/combined_file_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7ae1c0df628f3ec815f753d69fc179cde39ce7 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/combined_file_manifest.py @@ -0,0 +1,25 @@ +import json + +import b1k_pipeline.utils + + +def main(): + targets = b1k_pipeline.utils.get_targets("combined") + with b1k_pipeline.utils.PipelineFS() as pipeline_fs: + combined_file_manifest = {} + + # Merge the object lists. + for target in targets: + with pipeline_fs.target_output(target) as target_output_fs: + with target_output_fs.open("file_manifest.json", "r") as f: + combined_file_manifest[target] = json.load(f) + + # Write the combined list + with pipeline_fs.open( + "artifacts/pipeline/combined_file_manifest.json", "w", newline="\n" + ) as f: + json.dump(combined_file_manifest, f, indent=2) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/combined_room_object_list.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/combined_room_object_list.py new file mode 100644 index 0000000000000000000000000000000000000000..a57178fe57cedd37d3c455953604e91c7fd4985f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/combined_room_object_list.py @@ -0,0 +1,153 @@ +import argparse + +from collections import Counter, defaultdict +import glob +import json +import os + +import numpy as np +import b1k_pipeline.utils +from nltk.corpus import wordnet as wn +import yaml +import csv + + +def get_approved_room_types(pipeline_fs): + approved = [] + with pipeline_fs.open("metadata/allowed_room_types.csv", newline="") as csvfile: + reader = csv.reader(csvfile) + for row in reader: + approved.append(row[0]) + + return approved + + +def main(): + scenes = {} + skipped_files = [] + + not_approved_rooms = defaultdict(set) + + with b1k_pipeline.utils.PipelineFS() as pipeline_fs: + approved_rooms = set(get_approved_room_types(pipeline_fs)) + + # Get the list of targets + with pipeline_fs.open("params.yaml", "r") as f: + params = yaml.load(f, Loader=yaml.SafeLoader) + targets = params["scenes"] + final_scenes = [x.replace("scenes/", "") for x in params["final_scenes"]] + + outgoing_portals = {} + incoming_portals = {} + + # Add the object lists. + for target in targets: + with pipeline_fs.target_output(target) as target_output_fs: + with target_output_fs.open("object_list.json", "r") as f: + object_list = json.load(f) + + if not object_list["success"]: + skipped_files.append(target) + continue + + scene_name = target.split("/")[-1] + scene_info = object_list["objects_by_room"] + + room_types = {rm_name.rsplit("_", 1)[0] for rm_name in scene_info.keys()} + this_not_approved_rooms = room_types - approved_rooms + for rm in this_not_approved_rooms: + not_approved_rooms[scene_name].add(rm) + + scene_content_info = {} + for rm, models in scene_info.items(): + contents = Counter() + + for model, cnt in models.items(): + contents[model] += cnt + + scene_content_info[rm] = dict(contents) + + scenes[scene_name] = scene_content_info + + outgoing_portals[scene_name] = object_list["outgoing_portals"] + incoming_portals[scene_name] = object_list["incoming_portal"] + + # Merge the stuff + room_collision_errors = [] + for base, room_objects in scenes.items(): + for addition_scene, portal_info in outgoing_portals[base].items(): + # Check that the corresponding scene also has the incoming portal + assert incoming_portals[ + addition_scene + ], f"Scene {addition_scene} has no incoming portal but is linked to {base}" + + # Assert the portal sizes are the same + outgoing_size = portal_info[2] + incoming_size = incoming_portals[addition_scene][2] + assert np.allclose( + outgoing_size, incoming_size + ), f"Scene {addition_scene} has incoming portal size {incoming_size} but {base} has outgoing portal size {outgoing_size}" + + # Add all the rooms + base_keys = set(room_objects.keys()) + add_keys = set(scenes[addition_scene].keys()) + if not base_keys.isdisjoint(add_keys): + room_collision_errors.append( + f"Rooms colliding between {base} and {addition_scene}: {base_keys} vs {add_keys}" + ) + scenes[base].update(scenes[addition_scene]) + + assert not room_collision_errors, "\n".join(room_collision_errors) + + # Delete any exclusion scenes + scenes_to_exclude = [x for x in scenes if x not in final_scenes] + for scene in scenes_to_exclude: + del scenes[scene] + + # Check that the IDs of all the rooms are contiguous + non_contiguous_rooms = defaultdict(dict) + for scene_name, scene_info in scenes.items(): + try: + room_type_keys = defaultdict(set) + for rm_name in scene_info.keys(): + if "_" not in rm_name: + print( + "Found invalid room name", rm_name, "in scene", scene_name + ) + continue + room_type, room_id = rm_name.rsplit("_", 1) + room_type_keys[room_type].add(int(room_id)) + + for room_type, room_ids in room_type_keys.items(): + if room_ids != set(range(len(room_ids))): + non_contiguous_rooms[scene_name][room_type] = sorted(room_ids) + except: + raise ValueError( + "Error parsing room name", rm_name, "in scene", scene_name + ) + + success = ( + len(skipped_files) == 0 + and len(not_approved_rooms) == 0 + and len(non_contiguous_rooms) == 0 + ) + with pipeline_fs.pipeline_output() as pipeline_output_fs: + with pipeline_output_fs.open("combined_room_object_list.json", "w") as f: + json.dump( + { + "success": success, + "scenes": scenes, + "error_skipped_files": sorted(skipped_files), + "error_not_approved_rooms": { + rm: list(scenes) + for rm, scenes in sorted(not_approved_rooms.items()) + }, + "error_non_contiguous_rooms": non_contiguous_rooms, + }, + f, + indent=4, + ) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/deep_diff.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/deep_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..323c284a43e8d09302902afd98089768948f583f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/deep_diff.py @@ -0,0 +1,137 @@ +import json +import pathlib +from deepdiff import DeepDiff + +from b1k_pipeline.utils import parse_name + + +def model_ids_from_objects(objs): + model_ids = set() + for obj in objs: + pn = parse_name(obj) + if not pn: + continue + model_ids.add(pn.group("model_id")) + + return model_ids + + +def get_meta_type(obj): + """ + Get the meta type of an object. + :param obj: The object to get the meta type from. + :return: The meta type of the object. + """ + pn = parse_name(obj) + assert pn, f"Could not parse object name {obj}" + if pn.group("meta_type"): + return pn.group("meta_type") + elif pn.group("light_id"): + return "light" + else: + return "None" + + +def main(): + deep_glob = "cad/*/*/artifacts/file_manifest.json" # maybe use _deep ? + base_files = pathlib.Path("base").glob(deep_glob) + base_manifest_by_target = {"/".join(f.parts[-4:-2]): f for f in base_files} + pr_files = pathlib.Path("pr").glob(deep_glob) + pr_manifest_by_target = {"/".join(f.parts[-4:-2]): f for f in pr_files} + all_targets = set(base_manifest_by_target.keys()) | set( + pr_manifest_by_target.keys() + ) + + full_diffs = {} + object_diffs = {} + for target in sorted(all_targets): + # Load the manifests + base_manifest = ( + json.loads(base_manifest_by_target[target].read_text()) + if target in base_manifest_by_target + else [] + ) + pr_manifest = ( + json.loads(pr_manifest_by_target[target].read_text()) + if target in pr_manifest_by_target + else [] + ) + + # Convert the manifests to dicts based on the object name + base_manifest_dict = {v["name"]: v for v in base_manifest} + pr_manifest_dict = {v["name"]: v for v in pr_manifest} + + # Discard the mtl_hash for now. Should not matter until we start material work. + for val in base_manifest_dict.values(): + del val["mtl_hash"] + for val in pr_manifest_dict.values(): + del val["mtl_hash"] + + diff = DeepDiff(base_manifest_dict, pr_manifest_dict) + object_diffs[target] = sorted(diff.affected_root_keys) + full_diffs[target] = diff.pretty() + + meta_type_diffs = sorted( + { + get_meta_type(x) + for target_object_diffs in object_diffs.values() + for x in target_object_diffs + if parse_name(x) + } + ) + + print("-------------------------------------------------") + print("OBJECT DIFFS") + print("Unique edited obj names:", sum(len(vals) for vals in object_diffs.values())) + print( + "Unique edited model IDs:", + len( + { + mid + for objs in object_diffs.values() + for mid in model_ids_from_objects(objs) + } + ), + ) + print("Unique edited meta types:", len(meta_type_diffs), meta_type_diffs) + print("-------------------------------------------------") + print("All edited models:") + for mid in sorted( + {mid for objs in object_diffs.values() for mid in model_ids_from_objects(objs)} + ): + print(" " + str(mid)) + print() + print("BY TARGET:") + for target in sorted(all_targets): + target_objs = sorted(object_diffs[target]) + target_meta_types = sorted( + {get_meta_type(x) for x in target_objs if parse_name(x)} + ) + target_mids = sorted(model_ids_from_objects(target_objs)) + + print(f"\n\n-------------------------\n{target}") + print("Unique edited obj names:", len(target_objs)) + print("Unique edited model IDs:", len(target_mids)) + print("Unique edited meta types:", len(target_meta_types), target_meta_types) + + print("Objects:") + for root in target_objs: + print(" " + str(root)) + + print("Models:") + for mid in target_mids: + print(" " + str(mid)) + + print() + + print("-------------------------------------------------") + print("FULL DIFFS") + print("-------------------------------------------------") + for target in sorted(all_targets): + print(f"\n\n-------------------------\n{target}") + print(" " + full_diffs[target].replace("\n", "\n ")) + print() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/encode_h264.sh b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/encode_h264.sh new file mode 100644 index 0000000000000000000000000000000000000000..346507638d5ac39c4e32ba56c92cc60fc20c02d5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/encode_h264.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +# Loop through all .mp4 files in the current directory +for input_file in /scr/BEHAVIOR-1K/asset_pipeline/artifacts/pipeline/object_images/*.mp4; do + # Define the output filename. This example adds "_h264" before the extension + # and places it in the 'reencoded_h264' subdirectory. + output_file="${input_file%.mp4}_h264.mp4" + + echo "Processing: $input_file" + + # Run ffmpeg to re-encode the video to H.264 + # -i: specifies the input file + # -c:v libx264: sets the video codec to H.264 (using the libx264 encoder) + # -crf 23: sets the Constant Rate Factor for quality (lower is better, 18-28 is a sane range) + # -preset medium: sets the encoding speed/compression trade-off (slower presets offer better compression) + # -c:a aac: sets the audio codec to AAC (a common choice for MP4) + # -b:a 192k: sets the audio bitrate to 192 kbps (adjust as needed) + # -movflags +faststart: optimizes the MP4 for web streaming (allows playback before full download) + ffmpeg -i "$input_file" \ + -c:v libx264 \ + -crf 23 \ + -preset medium \ + -movflags +faststart \ + -y "$output_file" + +done + +echo "All .mp4 files have been processed." diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_glbs.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_glbs.py new file mode 100644 index 0000000000000000000000000000000000000000..12d6153136854e79f35adabd06a23df02d0b904e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_glbs.py @@ -0,0 +1,87 @@ +import os +import traceback +from b1k_pipeline.urdfpy import URDF +import b1k_pipeline.utils +import trimesh +import fs.copy +from fs.tempfs import TempFS +from dask.distributed import LocalCluster, as_completed +import tqdm +import glob + + +def urdf_to_glb(in_obj_dir, out_obj_dir): + # Get the URDF file + urdf_files = glob.glob(in_obj_dir + "/urdf/*.urdf") + assert ( + len(urdf_files) == 1 + ), f"Expected exactly one URDF file in {in_obj_dir}, found {len(urdf_files)}" + + urdf_file = urdf_files[0] + + robot = URDF.load(urdf_file) + links = [l for l in robot.links if "meta__" not in l.name] + visual_fk = robot.visual_trimesh_fk(links=links) + + scene = trimesh.Scene() + for mesh, transform in visual_fk.items(): + m = mesh.copy() + m.apply_transform(transform) + scene.add_geometry(m) + + model_id = os.path.splitext(os.path.basename(urdf_file))[0] + out_file = os.path.join(out_obj_dir, f"{model_id}.glb") + scene.export(out_file) + + +def main(): + with ( + b1k_pipeline.utils.ParallelZipFS("objects.zip") as source_fs, + TempFS(temp_dir=str(b1k_pipeline.utils.TMP_DIR)) as temp_fs, + b1k_pipeline.utils.ParallelZipFS("objects_glb.zip", write=True) as out_fs, + ): + # Copy everything over to the temp FS + print("Copying input to temp fs...") + objdir_glob = [item.path for item in source_fs.glob("objects/*/*/")] + for item in tqdm.tqdm(objdir_glob): + if ( + source_fs.opendir(item).opendir("urdf").glob("*.urdf").count().files + == 0 + ): + continue + fs.copy.copy_fs( + source_fs.opendir(item), temp_fs.makedirs(item, recreate=True) + ) + + cluster = LocalCluster() + dask_client = cluster.get_client() + + obj_futures = {} + + for objdir in tqdm.tqdm( + objdir_glob, desc="Processing targets to queue objects" + ): + obj_futures[ + dask_client.submit( + urdf_to_glb, + temp_fs.opendir(objdir).getsyspath("/"), + out_fs.makedirs(objdir).getsyspath("/"), + pure=False, + ) + ] = objdir + + for future in tqdm.tqdm( + as_completed(obj_futures.keys()), + total=len(obj_futures), + desc="Processing objects", + ): + try: + future.result() + except: + traceback.print_exc() + + print("Finished processing") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_objs_global.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_objs_global.py new file mode 100644 index 0000000000000000000000000000000000000000..69693a3acc490995800cc57dfb7843d54a9643ee --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_objs_global.py @@ -0,0 +1,978 @@ +import collections +import copy +import io +import json +import logging +import os +import traceback +import xml.etree.ElementTree as ET +from concurrent.futures import ProcessPoolExecutor, as_completed +from xml.dom import minidom + +import fs.copy +from fs.tempfs import TempFS +from fs.osfs import OSFS +import networkx as nx +import numpy as np +import tqdm +import trimesh +from scipy.spatial.transform import Rotation as R +from PIL import Image + +from b1k_pipeline import mesh_tree +import b1k_pipeline.utils +from b1k_pipeline.utils import ( + parse_name, + get_targets, + save_mesh, +) + +from bddl.knowledge_base import KnowledgeBase + +logger = logging.getLogger("trimesh") +logger.setLevel(logging.ERROR) + + +CHANNEL_MAPPING = { + "Diffuse map": ("diffuse", "map_Kd"), + "Bump map": ("normal", "map_bump"), + "Refl. gloss.": ("roughness", "map_Pr"), + "Metalness": ("metalness", "map_Pm"), + "Refract map": ("refraction", "map_Tf"), + "Reflect map": ("reflection", "map_Ks"), + "Fresnel IOR": ("ior", "map_Ns"), +} + +ALLOWED_PART_TAGS = { + "subpart", + "extrapart", + "connectedpart", +} + +# Objects that don't require these meta types should not have them +REQUIRED_ONLY_META_TYPES = { + "fluidsource", + "togglebutton", + "heatsource", + "particleapplier", + "particleremover", + "fluidsink", + "slicer", + "fillable", +} + +CLOTH_SUBDIVISION_THRESHOLD = 0.05 + +LOG_SURFACE_AREA_RANGE = (-6, 4) +LOG_TEXTURE_RANGE = (4, 11) + + +def get_required_meta_links(kb, category): + cat = kb.get_category(category) + ps = kb.get_particle_system(category) + synset = cat.synset if cat else (ps.synset if ps else None) + if synset is None: + raise ValueError(f"Category {category} not found in taxonomy.") + return synset.required_meta_links + + +class NumpyEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, np.ndarray): + return obj.tolist() + return json.JSONEncoder.default(self, obj) + + +def save_mesh_unit_bbox(mesh, *args, **kwargs): + mesh_copy = mesh.copy() + + # Find how much the mesh would need to be scaled to fit into a unit cube + bounding_box = mesh_copy.bounding_box.extents + assert np.all( + bounding_box > 0 + ), f"Bounding box extents are not all positive: {bounding_box}" + scale = 1 / bounding_box + + # Scale the mesh + scale_matrix = np.eye(4) + scale_matrix[:3, :3] = np.diag(scale) + mesh_copy.apply_transform(scale_matrix) + + # Save the scaled mesh + save_mesh(mesh_copy, *args, **kwargs) + + # Return the inverse scale that needs to be applied for the mesh + return 1 / scale + + +def transform_mesh(orig_mesh, translation, rotation): + mesh = orig_mesh.copy() + + # Rotate the object around the CoM of the base link frame by the transpose of its canonical orientation + # so that the object has identity orientation in the end + + transform = np.eye(4) + transform[:3, :3] = R.from_quat(rotation).as_matrix() + transform[:3, 3] = translation + inv_transform = trimesh.transformations.inverse_matrix(transform) + mesh.apply_transform(inv_transform) + + return mesh + + +def transform_points(points, translation, rotation): + # Rotate the object around the CoM of the base link frame by the transpose of its canonical orientation + # so that the object has identity orientation in the end + transform = np.eye(4) + transform[:3, :3] = R.from_quat(rotation).as_matrix() + transform[:3, 3] = translation + inv_transform = trimesh.transformations.inverse_matrix(transform) + return trimesh.transformations.transform_points(points, inv_transform) + + +def transform_meta_links(orig_meta_links, translation, rotation): + meta_links = copy.deepcopy(orig_meta_links) + rotation_inv = R.from_quat(rotation).inv() + for meta_link_id_to_subid in meta_links.values(): + for meta_link_subid_to_link in meta_link_id_to_subid.values(): + for meta_link in meta_link_subid_to_link: + meta_link["position"] = meta_link["position"] + meta_link["position"] -= translation + meta_link["position"] = np.dot( + rotation_inv.as_matrix(), meta_link["position"] + ) + # meta_link["position"] += translation + meta_link["orientation"] = ( + rotation_inv * R.from_quat(meta_link["orientation"]) + ).as_quat() + + return meta_links + + +def normalize_meta_links(orig_meta_links, offset): + meta_links = copy.deepcopy(orig_meta_links) + for meta_link_id_to_subid in meta_links.values(): + for meta_link_subid_to_link in meta_link_id_to_subid.values(): + for meta_link in meta_link_subid_to_link: + meta_link["position"] += offset + + return meta_links + + +def get_mesh_center(mesh): + if mesh.is_watertight: + return mesh.center_mass + else: + return mesh.centroid + + +def get_part_nodes(G, root_node): + root_node_metadata = G.nodes[root_node]["metadata"] + part_nodes = [] + for part_name in root_node_metadata["parts"]: + # Find the part node + part_name_parsed = parse_name(part_name) + part_cat = part_name_parsed.group("category") + part_model = part_name_parsed.group("model_id") + part_inst_id = part_name_parsed.group("instance_id") + part_link_name = part_name_parsed.group("link_name") + part_link_name = "base_link" if part_link_name is None else part_link_name + if part_link_name != "base_link": + continue + part_node_key = (part_cat, part_model, part_inst_id, part_link_name) + if part_node_key not in G.nodes: + print(list(G.nodes)) + assert part_node_key in G.nodes, f"Could not find part node {part_node_key}" + part_nodes.append(part_node_key) + + return part_nodes + + +def get_bbox_data_for_mesh(mesh): + axis_aligned_bbox = mesh.bounding_box + axis_aligned_bbox_dict = { + "extent": np.array(axis_aligned_bbox.primitive.extents).tolist(), + "transform": np.array(axis_aligned_bbox.primitive.transform).tolist(), + } + + oriented_bbox = mesh.bounding_box_oriented + oriented_bbox_dict = { + "extent": np.array(oriented_bbox.primitive.extents).tolist(), + "transform": np.array(oriented_bbox.primitive.transform).tolist(), + } + + return {"axis_aligned": axis_aligned_bbox_dict, "oriented": oriented_bbox_dict} + + +def compute_link_aligned_bounding_boxes(G, root_node): + link_bounding_boxes = collections.defaultdict(dict) + for link_node in nx.dfs_preorder_nodes(G, root_node): + obj_cat, obj_model, obj_inst_id, link_name = link_node + + # Get the pose and transform it + for key in ["collision", "visual"]: + try: + mesh = ( + G.nodes[link_node]["visual_mesh"] + if key == "visual" + else G.nodes[link_node]["canonical_collision_mesh"] + ) + link_bounding_boxes[link_name][key] = get_bbox_data_for_mesh( + transform_mesh( + mesh, -G.nodes[link_node]["mesh_in_link_frame"], [0, 0, 0, 1] + ) + ) + except Exception as e: + print(f"Problem with {obj_cat}-{obj_model} link {link_name}: {str(e)}") + + return link_bounding_boxes + + +def process_link( + G, + link_node, + base_link_center, + canonical_orientation, + required_meta_types, + output_fs, + tree_root, + out_metadata, +): + category_name, model_id, _, link_name = link_node + raw_meta_links = G.nodes[link_node]["meta_links"] + + # Create a canonicalized copy of the lower and upper meshes. + mesh_center = get_mesh_center(G.nodes[link_node]["lower_mesh"]) + canonical_mesh = transform_mesh( + G.nodes[link_node]["lower_mesh"], mesh_center, canonical_orientation + ) + meta_links = transform_meta_links( + raw_meta_links, mesh_center, canonical_orientation + ) + + # Somehow we need to manually write the vertex normals to cache + canonical_mesh._cache.cache["vertex_normals"] = canonical_mesh.vertex_normals + + in_edges = list(G.in_edges(link_node)) + assert ( + len(in_edges) <= 1 + ), f"Something's wrong: there's more than 1 in-edge to node {link_node}" + + # Compute the texture resolution needed + mesh_surface_area = canonical_mesh.area + log_area = np.clip(np.log(mesh_surface_area) / np.log(10), *LOG_SURFACE_AREA_RANGE) + log_area_range_fraction = (log_area - LOG_SURFACE_AREA_RANGE[0]) / ( + LOG_SURFACE_AREA_RANGE[1] - LOG_SURFACE_AREA_RANGE[0] + ) + log2_area = LOG_TEXTURE_RANGE[0] + log_area_range_fraction * ( + LOG_TEXTURE_RANGE[1] - LOG_TEXTURE_RANGE[0] + ) + log2_area = int(np.clip(np.round(log2_area), *LOG_TEXTURE_RANGE)) + texture_res = int(2**log2_area) + + # Save the mesh + with TempFS() as tfs: + obj_relative_path = f"{model_id}__{link_name}.obj" + save_mesh(canonical_mesh, tfs, obj_relative_path) + + # Move the mesh to the correct path + obj_link_mesh_folder_fs = output_fs.makedir("shape", recreate=True) + obj_link_visual_mesh_folder_fs = obj_link_mesh_folder_fs.makedir( + "visual", recreate=True + ) + obj_link_material_folder_fs = output_fs.makedir("material", recreate=True) + + # Check if a material got exported. + material_files = [x for x in tfs.listdir("/") if x.endswith(".mtl")] + assert material_files, "No materials found after OBJ export! Not good." + if material_files: + assert ( + len(material_files) == 1 + ), f"Something's wrong: there's more than 1 material file in {tfs.listdir('/')}" + original_material_filename = material_files[0] + + # Fix texture file paths if necessary. + material_maps = G.nodes[link_node]["material_maps"] + moved_material_maps = {} + for map_channel, map_path in material_maps.items(): + assert os.path.exists( + map_path + ), f"Texture file {map_path} does not exist!" + + # Convert the path to a dirname + filename so that we can use an OSFS + # to copy the file. + src_map_dir = os.path.dirname(map_path) + src_map_filename = os.path.basename(map_path) + src_map_ext = os.path.splitext(src_map_filename)[1] + src_map_fs = OSFS(src_map_dir) + + assert map_channel in CHANNEL_MAPPING, f"Unknown channel {map_channel}" + dst_fname, _ = CHANNEL_MAPPING[map_channel] + dst_texture_filename = ( + f"{model_id}__{link_name}__{dst_fname}{src_map_ext}" + ) + + # Load the image + # TODO: Re-enable this after tuning it. + # texture = Image.open(original_material_fs.open(src_texture_file, "rb"), formats=("png",)) + # existing_texture_res = texture.size[0] + # if existing_texture_res > texture_res: + # texture = texture.resize((texture_res, texture_res), Image.BILINEAR) + # texture.save(obj_link_material_folder_fs.open(dst_texture_file, "wb"), format="png") + + fs.copy.copy_file( + src_map_fs, + src_map_filename, + obj_link_material_folder_fs, + dst_texture_filename, + ) + + moved_material_maps[map_channel] = dst_texture_filename + + # Copy the OBJ into the right spot + fs.copy.copy_file( + tfs, obj_relative_path, obj_link_visual_mesh_folder_fs, obj_relative_path + ) + + # Save and merge precomputed convex meshes e.g. collision, fillable + canonical_convex_meshes = {} + convex_mesh_filenames_and_scales = {} + for convex_mesh_type in mesh_tree.CONVEX_MESH_TYPES: + convex_mesh_key = f"{convex_mesh_type}_mesh" + if convex_mesh_key not in G.nodes[link_node]: + continue + canonical_convex_meshes[convex_mesh_type] = [] + convex_mesh_filenames_and_scales[convex_mesh_type] = [] + for i, convex_mesh in enumerate(G.nodes[link_node][convex_mesh_key]): + canonical_convex_mesh = transform_mesh( + convex_mesh, mesh_center, canonical_orientation + ) + canonical_convex_mesh._cache.cache["vertex_normals"] = ( + canonical_convex_mesh.vertex_normals + ) + convex_filename = obj_relative_path.replace( + ".obj", f"__{convex_mesh_type}__{i}.obj" + ) + obj_link_convex_mesh_folder_fs = obj_link_mesh_folder_fs.makedir( + convex_mesh_type, recreate=True + ) + convex_scale = save_mesh_unit_bbox( + canonical_convex_mesh, + obj_link_convex_mesh_folder_fs, + convex_filename, + ) + convex_mesh_filenames_and_scales[convex_mesh_type].append( + (convex_filename, convex_scale) + ) + canonical_convex_meshes[convex_mesh_type].append(canonical_convex_mesh) + + # Store the final meshes + G.nodes[link_node]["visual_mesh"] = canonical_mesh.copy() + G.nodes[link_node]["canonical_collision_mesh"] = trimesh.util.concatenate( + canonical_convex_meshes["collision"] + ) + + if material_files: + # Modify MTL reference in OBJ file + mtl_name = f"{model_id}__{link_name}.mtl" + with obj_link_visual_mesh_folder_fs.open(obj_relative_path, "r") as f: + new_lines = [] + for line in f.readlines(): + if f"mtllib {original_material_filename}" in line: + line = f"mtllib {mtl_name}\n" + new_lines.append(line) + + with obj_link_visual_mesh_folder_fs.open(obj_relative_path, "w") as f: + for line in new_lines: + f.write(line) + + # Modify texture reference in MTL file + with tfs.open(original_material_filename, "r") as f: + new_lines = [] + for line in f.readlines(): + if "map_Kd material_0.png" in line: + line = "" + for ( + channel_name, + channel_filename, + ) in moved_material_maps.items(): + _, mtl_key = CHANNEL_MAPPING[channel_name] + line += f"{mtl_key} ../../material/{channel_filename}\n" + new_lines.append(line) + + with obj_link_visual_mesh_folder_fs.open(mtl_name, "w") as f: + for line in new_lines: + f.write(line) + + # Create the link in URDF + link_xml = ET.SubElement(tree_root, "link") + link_xml.attrib = {"name": link_name} + visual_xml = ET.SubElement(link_xml, "visual") + visual_origin_xml = ET.SubElement(visual_xml, "origin") + visual_origin_xml.attrib = {"xyz": " ".join([str(item) for item in [0.0] * 3])} + visual_geometry_xml = ET.SubElement(visual_xml, "geometry") + visual_mesh_xml = ET.SubElement(visual_geometry_xml, "mesh") + visual_mesh_xml.attrib = { + "filename": os.path.join("..", "shape", "visual", obj_relative_path).replace( + "\\", "/" + ), + "scale": " ".join([str(item) for item in np.ones(3)]), + } + + collision_origin_xmls = [] + for collision_filename, collision_scale in convex_mesh_filenames_and_scales[ + "collision" + ]: + collision_xml = ET.SubElement(link_xml, "collision") + collision_xml.attrib = {"name": collision_filename.replace(".obj", "")} + collision_origin_xml = ET.SubElement(collision_xml, "origin") + collision_origin_xml.attrib = { + "xyz": " ".join([str(item) for item in [0.0] * 3]) + } + collision_geometry_xml = ET.SubElement(collision_xml, "geometry") + collision_mesh_xml = ET.SubElement(collision_geometry_xml, "mesh") + collision_mesh_xml.attrib = { + "filename": os.path.join( + "..", "shape", "collision", collision_filename + ).replace("\\", "/"), + "scale": " ".join([str(item) for item in collision_scale]), + } + collision_origin_xmls.append(collision_origin_xml) + + # This object might be a base link and thus without an in-edge. Nothing to do then. + if len(in_edges) == 0: + G.nodes[link_node]["link_frame_in_base"] = np.zeros(3) + G.nodes[link_node]["mesh_in_link_frame"] = np.zeros(3) + else: + # Grab the lone edge to the parent. + (edge,) = in_edges + parent_node, child_node = edge + assert ( + child_node == link_node + ), f"Something's wrong: the child node of the edge is not the link node {link_node}" + joint_type = G.edges[edge]["joint_type"] + parent_frame = G.nodes[parent_node]["link_frame_in_base"] + + rotated_parent_frame = R.from_quat(canonical_orientation).apply(parent_frame) + + # Load the meshes. + lower_canonical_points = transform_points( + G.nodes[child_node]["lower_points"], + base_link_center + rotated_parent_frame, + canonical_orientation, + ) + + # Get the center of mass of the child link in the parent frame. + child_center = transform_points( + np.array([mesh_center]), + base_link_center + rotated_parent_frame, + canonical_orientation, + )[0] + + # Create the joint in the URDF + joint_xml = ET.SubElement(tree_root, "joint") + joint_xml.attrib = { + "name": f"j_{child_node[3]}", + "type": {"P": "prismatic", "R": "revolute", "F": "fixed", "C": "continuous"}[joint_type], + } + + joint_parent_xml = ET.SubElement(joint_xml, "parent") + joint_parent_xml.attrib = {"link": parent_node[3]} + joint_child_xml = ET.SubElement(joint_xml, "child") + joint_child_xml.attrib = {"link": child_node[3]} + + mesh_offset = np.zeros(3) + if joint_type in ("P", "R", "C"): + upper_canonical_points = transform_points( + G.nodes[child_node]["upper_points"], + base_link_center + rotated_parent_frame, + canonical_orientation, + ) + + if joint_type in ("R", "C"): + # Revolute joint + num_v_lower = lower_canonical_points.shape[0] + num_v_upper = upper_canonical_points.shape[0] + assert ( + num_v_lower == num_v_upper + ), f"{child_node} lower mesh has {num_v_lower} vertices while upper has {num_v_upper}. These should match." + num_v = num_v_lower + random_index = np.random.choice(num_v, min(num_v, 20), replace=False) + from_vertices = lower_canonical_points[random_index] + to_vertices = upper_canonical_points[random_index] + + # Find joint axis and joint limit + r = R.align_vectors( + to_vertices - np.mean(to_vertices, axis=0), + from_vertices - np.mean(from_vertices, axis=0), + )[0] + upper_limit = r.magnitude() + assert upper_limit < np.deg2rad( + 180 + ), "upper limit of revolute joint should be <180 degrees" + joint_axis = r.as_rotvec() / r.magnitude() + + # Let X = from_vertices_mean, Y = to_vertices_mean, R is rotation, T is translation + # R * (X - T) + T = Y + # => (I - R) T = Y - R * X + # Find the translation part of the joint origin + r_mat = r.as_matrix() + from_vertices_mean = from_vertices.mean(axis=0) + to_vertices_mean = to_vertices.mean(axis=0) + left_mat = np.eye(3) - r_mat + arbitrary_point_on_joint_axis = np.linalg.lstsq( + left_mat, + (to_vertices_mean - np.dot(r_mat, from_vertices_mean)), + rcond=None, + )[0] + + # The joint origin has infinite number of solutions along the joint axis + # Find the translation part of the joint origin that is closest to the CoM of the link + # by projecting the CoM onto the joint axis + arbitrary_point_to_center = child_center - arbitrary_point_on_joint_axis + joint_origin = arbitrary_point_on_joint_axis + ( + np.dot(arbitrary_point_to_center, joint_axis) * joint_axis + ) + + # Assign visual and collision mesh origin so that the offset from the joint origin is removed. + mesh_offset = child_center - joint_origin + visual_origin_xml.attrib = { + "xyz": " ".join([str(item) for item in mesh_offset]) + } + + for collision_origin_xml in collision_origin_xmls: + collision_origin_xml.attrib = { + "xyz": " ".join([str(item) for item in mesh_offset]) + } + + meta_links = normalize_meta_links(meta_links, mesh_offset) + elif joint_type == "P": + # Prismatic joint + diff = np.mean(upper_canonical_points, axis=0) - np.mean( + lower_canonical_points, axis=0 + ) + + # Find joint axis and joint limit + if not np.allclose(diff, 0): + upper_limit = np.linalg.norm(diff) + joint_axis = diff / upper_limit + else: + upper_limit = 0 + joint_axis = np.array([0, 0, 1]) + + # Assign the joint origin relative to the parent CoM + joint_origin = child_center + + # Save these joints' data + joint_origin_xml = ET.SubElement(joint_xml, "origin") + joint_origin_xml.attrib = { + "xyz": " ".join([str(item) for item in joint_origin]) + } + joint_axis_xml = ET.SubElement(joint_xml, "axis") + joint_axis_xml.attrib = { + "xyz": " ".join([str(item) for item in joint_axis]) + } + if joint_type != "C": # Continuous joints do not have limits + joint_limit_xml = ET.SubElement(joint_xml, "limit") + joint_limit_xml.attrib = {"lower": str(0.0), "upper": str(upper_limit)} + else: + # Fixed joints are quite simple. + joint_origin = child_center + + if joint_type == "F": + joint_origin_xml = ET.SubElement(joint_xml, "origin") + joint_origin_xml.attrib = { + "xyz": " ".join([str(item) for item in joint_origin]) + } + else: + raise ValueError("Unexpected joint type: " + str(joint_type)) + + G.nodes[link_node]["link_frame_in_base"] = parent_frame + joint_origin + G.nodes[link_node]["mesh_in_link_frame"] = mesh_offset + + # # Compute the moment of inertia + # moment_of_inertia = G.nodes[link_node][ + # "canonical_collision_mesh" + # ].moment_inertia_frame(trimesh.transformations.translation_matrix(com)) + + # Annotate mass, center of mass and moment of inertia directly on the URDF + inertial_xml = ET.SubElement(link_xml, "inertial") + inertial_origin_xml = ET.SubElement(inertial_xml, "origin") + inertial_origin_xml.attrib = { + "xyz": "0 0 0", + "rpy": "0 0 0", + } + inertial_mass_xml = ET.SubElement(inertial_xml, "mass") + inertial_mass_xml.attrib = {"value": "1.0"} + # inertial_inertia_xml = ET.SubElement(inertial_xml, "inertia") + # inertial_inertia_xml.attrib = { + # "ixx": str(moment_of_inertia[0, 0]), + # "ixy": str(moment_of_inertia[0, 1]), + # "ixz": str(moment_of_inertia[0, 2]), + # "iyy": str(moment_of_inertia[1, 1]), + # "iyz": str(moment_of_inertia[1, 2]), + # "izz": str(moment_of_inertia[2, 2]), + # } + + # Walk over the meta links to add visual meshes for non-collision convex meshes, since this + # is the only way to get them into the URDF. + for cm_type in mesh_tree.NON_COLLISION_CONVEX_MESH_TYPES: + # Skip the convex mesh type if the object does not have one + if f"{cm_type}_mesh" not in G.nodes[link_node]: + continue + + # Unpack some info + cm_link_name = f"meta__{link_name}_{cm_type}_0_0_link" + cm_joint_name = f"meta__{link_name}_{cm_type}_0_0_joint" + + # Create the link in URDF + cm_link_xml = ET.SubElement(tree_root, "link") + cm_link_xml.attrib = {"name": cm_link_name} + cm_inertial_xml = ET.SubElement(cm_link_xml, "inertial") + cm_inertial_origin_xml = ET.SubElement(cm_inertial_xml, "origin") + cm_inertial_origin_xml.attrib = { + "xyz": "0 0 0", + "rpy": "0 0 0", + } + cm_inertial_mass_xml = ET.SubElement(cm_inertial_xml, "mass") + cm_inertial_mass_xml.attrib = {"value": "0.001"} + # cm_inertial_inertia_xml = ET.SubElement(cm_inertial_xml, "inertia") + # cm_moment_of_inertia = np.eye(3) * 1e-7 + # cm_inertial_inertia_xml.attrib = { + # "ixx": str(cm_moment_of_inertia[0, 0]), + # "ixy": str(cm_moment_of_inertia[0, 1]), + # "ixz": str(cm_moment_of_inertia[0, 2]), + # "iyy": str(cm_moment_of_inertia[1, 1]), + # "iyz": str(cm_moment_of_inertia[1, 2]), + # "izz": str(cm_moment_of_inertia[2, 2]), + # } + + # Create the joint in URDF + cm_joint_xml = ET.SubElement(tree_root, "joint") + cm_joint_xml.attrib = { + "name": cm_joint_name, + "type": "fixed", + } + cm_joint_parent_xml = ET.SubElement(cm_joint_xml, "parent") + cm_joint_parent_xml.attrib = {"link": link_name} + cm_joint_child_xml = ET.SubElement(cm_joint_xml, "child") + cm_joint_child_xml.attrib = {"link": cm_link_name} + cm_joint_origin_xml = ET.SubElement(cm_joint_xml, "origin") + cm_joint_origin_xml.attrib = {"xyz": "0 0 0"} + + # Save the meshes into the visual mesh FS and record them in the URDF + for cm_filename, cm_scale in convex_mesh_filenames_and_scales[cm_type]: + cm_visual_xml = ET.SubElement(cm_link_xml, "visual") + cm_visual_origin_xml = ET.SubElement(cm_visual_xml, "origin") + cm_visual_origin_xml.attrib = {"xyz": "0 0 0"} + cm_visual_geometry_xml = ET.SubElement(cm_visual_xml, "geometry") + cm_visual_mesh_xml = ET.SubElement(cm_visual_geometry_xml, "mesh") + cm_visual_mesh_xml.attrib = { + "filename": os.path.join("..", "shape", cm_type, cm_filename).replace( + "\\", "/" + ), + "scale": " ".join([str(item) for item in cm_scale]), + } + + # Filter non-required meta links + found_nonoptional_meta_types = set(meta_links.keys()) & REQUIRED_ONLY_META_TYPES + found_extra_nonoptional_meta_types = ( + found_nonoptional_meta_types - required_meta_types + ) + if found_extra_nonoptional_meta_types: + for extra_meta_type in found_extra_nonoptional_meta_types: + del meta_links[extra_meta_type] + + # Assert no CoM meta link anywhere except the base link + assert not ( + "com" in meta_links and link_name != "base_link" + ), f"CoM meta link found in {link_name} of {link_node}. Only base link should have CoM." + + out_metadata["meta_links"][link_name] = meta_links + out_metadata["link_tags"][link_name] = G.nodes[link_node]["tags"] + + +def process_object(root_node, target, relevant_nodes, requried_meta_types, output_dir): + obj_cat, obj_model, obj_inst_id, _ = root_node + + G = mesh_tree.build_mesh_tree( + target, + filter_nodes=relevant_nodes, + ) + + with OSFS(output_dir) as output_fs: + # Prepare the URDF tree + tree_root = ET.Element("robot") + tree_root.attrib = {"name": obj_model} + + # Extract base link orientation and position + canonical_orientation = np.array(G.nodes[root_node]["canonical_orientation"]) + base_link_mesh = G.nodes[root_node]["lower_mesh"] + base_link_center = get_mesh_center(base_link_mesh) + + out_metadata = { + "meta_links": {}, + "link_tags": {}, + "object_parts": [], + } + + # Iterate over each link. + for link_node in nx.dfs_preorder_nodes(G, root_node): + process_link( + G, + link_node, + base_link_center, + canonical_orientation, + requried_meta_types, + output_fs, + tree_root, + out_metadata, + ) + + # Save the URDF file. + xmlstr = minidom.parseString(ET.tostring(tree_root)).toprettyxml(indent=" ") + xmlio = io.StringIO(xmlstr) + tree = ET.parse(xmlio) + + urdf_fs = output_fs.makedir("urdf", recreate=True) + with urdf_fs.open(f"{obj_model}.urdf", "wb") as f: + tree.write(f, xml_declaration=True) + + bbox_size = np.array(G.nodes[root_node]["object_bounding_box"]["extent"]) + bbox_world_pos = np.array(G.nodes[root_node]["object_bounding_box"]["position"]) + base_link_offset_in_world = bbox_world_pos - base_link_center + base_link_offset = ( + R.from_quat(canonical_orientation).inv().apply(base_link_offset_in_world) + ) + + # Compute part information + for part_node_key in get_part_nodes(G, root_node): + # Get the part node bounding box + part_bb_size = G.nodes[part_node_key]["object_bounding_box"]["extent"] + part_bb_in_world_pos = G.nodes[part_node_key]["object_bounding_box"][ + "position" + ] + part_bb_in_world_rot = R.from_quat( + G.nodes[part_node_key]["object_bounding_box"]["rotation"] + ) + + # Convert into our base link frame + our_transform = np.eye(4) + our_transform[:3, 3] = base_link_center + our_transform[:3, :3] = R.from_quat(canonical_orientation).as_matrix() + bb_transform = np.eye(4) + bb_transform[:3, 3] = part_bb_in_world_pos + bb_transform[:3, :3] = part_bb_in_world_rot.as_matrix() + bb_transform_in_our = np.linalg.inv(our_transform) @ bb_transform + bb_pos_in_our = bb_transform_in_our[:3, 3] + bb_quat_in_our = R.from_matrix(bb_transform_in_our[:3, :3]).as_quat() + + # Get the part type + part_tags = set(G.nodes[part_node_key]["tags"]) & ALLOWED_PART_TAGS + assert ( + len(part_tags) == 1 + ), f"Part node {part_node_key} has multiple part tags: {part_tags}" + (part_type,) = part_tags + + # Add the metadata + out_metadata["object_parts"].append( + { + "category": part_node_key[0], + "model": part_node_key[1], + "type": part_type, + "bb_pos": bb_pos_in_our, + "bb_orn": bb_quat_in_our, + "bb_size": part_bb_size, + } + ) + + # If it's a connectedpart, we also need to generate the corresponding female attachment point. + if part_type == "connectedpart": + base_link_meta_links = out_metadata["meta_links"]["base_link"] + if "attachment" not in base_link_meta_links: + base_link_meta_links["attachment"] = {} + attachment_type = f"{part_node_key[1]}parent".lower() + "F" + if attachment_type not in base_link_meta_links["attachment"]: + base_link_meta_links["attachment"][attachment_type] = {} + next_id = len(base_link_meta_links["attachment"][attachment_type]) + + # pretend that the attachment point is at the center of the part bbox with its transform + # actually add the point + base_link_meta_links["attachment"][attachment_type][str(next_id)] = { + "position": bb_pos_in_our, + "orientation": bb_quat_in_our, + } + + # Similarly, if we are a connectedpart, we need to generate the corresponding male attachment point. + if "connectedpart" in G.nodes[root_node]["tags"]: + base_link_meta_links = out_metadata["meta_links"]["base_link"] + if "attachment" not in base_link_meta_links: + base_link_meta_links["attachment"] = {} + attachment_type = f"{obj_model}parent".lower() + "M" + if attachment_type not in base_link_meta_links["attachment"]: + base_link_meta_links["attachment"][attachment_type] = {} + next_id = len(base_link_meta_links["attachment"][attachment_type]) + + # Pretend that the attachment point is at the center of the part bbox with its transform + next_id = len(base_link_meta_links["attachment"][attachment_type]) + base_link_meta_links["attachment"][attachment_type][str(next_id)] = { + "position": base_link_offset.tolist(), + "orientation": [0.0, 0.0, 0.0, 1.0], + } + + openable_joint_ids = [ + (i, joint.attrib["name"]) + for i, joint in enumerate(tree.findall("joint")) + if "openable" + in out_metadata["link_tags"].get(joint.find("child").attrib["link"], []) + ] + + # If there is a center of mass annotation for the base link, we need to pop it to store it + # separately in the metadata. + if "com" in out_metadata["meta_links"]["base_link"]: + assert ( + len(out_metadata["meta_links"]["base_link"]["com"]) == 1 + ), f"Something's wrong: there's more than 1 CoM in {link_node}" + com_links = list(out_metadata["meta_links"]["base_link"]["com"].values())[0] + assert ( + len(com_links) == 1 + ), f"Something's wrong: there's more than 1 CoM in {link_node}" + com = np.array(com_links[0]["position"]) + del out_metadata["meta_links"]["base_link"]["com"] + out_metadata["center_of_mass"] = com.tolist() + + # Save metadata json + out_metadata.update( + { + "base_link_offset": base_link_offset.tolist(), + "bbox_size": bbox_size.tolist(), + "orientations": [], + "link_bounding_boxes": compute_link_aligned_bounding_boxes( + G, root_node + ), + } + ) + if openable_joint_ids: + out_metadata["openable_joint_ids"] = openable_joint_ids + with output_fs.makedir("misc").open("metadata.json", "w") as f: + json.dump(out_metadata, f, cls=NumpyEncoder) + + +def process_target(target, objects_path, kb, model_whitelist, executor): + object_futures = {} + + # Build the mesh tree using our mesh tree library. The scene code also uses this system. + G = mesh_tree.build_mesh_tree(target, load_meshes=False) + + # Go through each object. + roots = [node for node, in_degree in G.in_degree() if in_degree == 0] + + # Only save the 0th instance. + saveable_roots = [ + root_node + for root_node in roots + if int(root_node[2]) == 0 + and not G.nodes[root_node]["is_broken"] + and (not model_whitelist or root_node[1] in model_whitelist) + ] + for root_node in saveable_roots: + # Start processing the object. We start by creating an object-specific + # copy of the mesh tree (also including info about any parts) + relevant_nodes = set(nx.dfs_tree(G, root_node).nodes()) + relevant_nodes |= { + node + for part_root_node in get_part_nodes( + G, root_node + ) # Get every part root node + for node in nx.dfs_tree(G, part_root_node).nodes() + } # Get the subtree of each part + + obj_cat, obj_model, obj_inst_id, _ = root_node + output_dirname = f"{obj_cat}/{obj_model}" + output_dirname_abs = os.path.join(objects_path, output_dirname) + os.makedirs(output_dirname_abs, exist_ok=True) + object_futures[ + executor.submit( + process_object, + root_node, + target, + relevant_nodes, + get_required_meta_links(kb, obj_cat), + output_dirname_abs, + ) + ] = str(root_node) + + return object_futures + + +def main(): + kb = KnowledgeBase(populate=True) + + # If this variable is set, we will only export the models in this list. This is useful for quickly + # iterating on scenes (usdify otherwise takes 8+ hours). If this list is empty, we will export all models. + SCENES_TO_INCLUDE_MODELS_FOR = [] # ["house_single_floor", "house_double_floor_lower", "house_double_floor_upper"] + + # Start with a whitelist of some hardcoded objects + model_whitelist = set() + pipeline_fs = b1k_pipeline.utils.PipelineFS() + for scene in SCENES_TO_INCLUDE_MODELS_FOR: + target_output_fs = pipeline_fs.target_output(f"scenes/{scene}") + + # Load the object list for the file + with target_output_fs.open("object_list.json", "r") as f: + object_list = json.load(f) + + # Get the needed object models + needed_objects = {x.split("-")[-1] for x in object_list["needed_objects"]} + + # Remove the ones that only show up as clutter + found_as_non_clutter = set() + for name in object_list["meshes"]: + pn = b1k_pipeline.utils.parse_name(name) + if not pn: + continue + model_id = pn.group("model_id") + is_clutter = pn.group("loose") == "C-" + if not is_clutter: + found_as_non_clutter.add(model_id) + needed_objects = needed_objects & found_as_non_clutter + + # Add the needed models to the whitelist + model_whitelist.update(needed_objects) + + with b1k_pipeline.utils.ParallelZipFS("objects.zip", write=True) as archive_fs: + objects_dir = archive_fs.makedir("objects").getsyspath("/") + # Load the mesh list from the object list json. + errors = {} + + targets = get_targets("combined") + + obj_futures = {} + + with ProcessPoolExecutor() as executor: + for target in tqdm.tqdm(targets, desc="Processing targets to queue objects"): + obj_futures.update( + process_target( + target, objects_dir, kb, model_whitelist, executor + ) + ) + + for future in tqdm.tqdm( + as_completed(obj_futures.keys()), + total=len(obj_futures), + desc="Processing objects", + ): + try: + future.result() + except: + name = obj_futures[future] + errors[name] = traceback.format_exc() + + print("Finished processing") + + with pipeline_fs.pipeline_output().open("export_objs.json", "w") as f: + json.dump({"success": not errors, "errors": errors}, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_scenes_global.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_scenes_global.py new file mode 100644 index 0000000000000000000000000000000000000000..bf58d1dc072858ff8c1d55001fd356be477823d2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/export_scenes_global.py @@ -0,0 +1,216 @@ +import io +import json +import os +import sys +import numpy as np +import xml.etree.ElementTree as ET +from xml.dom import minidom +from fs.osfs import OSFS +from scipy.spatial.transform import Rotation as R +from concurrent import futures +import tqdm +import traceback + +from b1k_pipeline.mesh_tree import build_mesh_tree +import b1k_pipeline.utils + +ALLOWED_PART_TAGS = { + "subpart", + "extrapart", + "connectedpart", +} + + +def process_target(target, scenes_dir): + scene_name = os.path.split(target)[-1] + pipeline_fs = b1k_pipeline.utils.PipelineFS() + + # Create XML trees for two different versions of the scene, with and without clutter. + scene_tree_roots = {} + for suffix in ["best", "with_clutter"]: + scene_tree_root = ET.Element("robot") + scene_tree_root.attrib = {"name": "igibson_scene"} + world_link = ET.SubElement(scene_tree_root, "link") + world_link.attrib = {"name": "world"} + scene_tree_roots[suffix] = scene_tree_root + + # Load info about the scene parts. + target_output_fs = pipeline_fs.target_output(target) + scene_parts = {scene_name: None} + with target_output_fs.open("object_list.json") as f: + room_object_list = json.load(f) + for partial_scene_name, (portal_pos, portal_quat, _) in room_object_list[ + "outgoing_portals" + ].items(): + transform = np.eye(4) + transform[:3, :3] = R.from_quat(portal_quat).as_matrix() + transform[:3, 3] = np.array(portal_pos) / 1000.0 + scene_parts[partial_scene_name] = transform + + # Get the mesh tree of each part. + for partial_scene_name, portal_pose_in_parent in scene_parts.items(): + partial_scene_target_name = "scenes/" + partial_scene_name + partial_scene_output_fs = pipeline_fs.target_output(partial_scene_target_name) + + # Compute the incoming transform + rel_transform = np.eye(4) + if portal_pose_in_parent is not None: + with partial_scene_output_fs.open("object_list.json", "r") as f: + room_object_list = json.load(f) + assert room_object_list["incoming_portal"] is not None + portal_pos, portal_quat, _ = room_object_list["incoming_portal"] + incoming_portal_transform = np.eye(4) + incoming_portal_transform[:3, :3] = R.from_quat(portal_quat).as_matrix() + incoming_portal_transform[:3, 3] = np.array(portal_pos) / 1000.0 + + # Each object needs to be reorigined at the incoming portal and then moved to the outgoing + rel_transform = portal_pose_in_parent @ np.linalg.inv( + incoming_portal_transform + ) + + # Assert that the rel transform represents only a Z rotation + rel_rot = R.from_matrix(rel_transform[:3, :3]) + if rel_rot.magnitude() > 1e-4: + rot_axis = np.abs(rel_rot.as_rotvec() / rel_rot.magnitude()) + assert np.allclose( + rot_axis, [0, 0, 1] + ), f"Relative transform should only be a Z rotation. Current axis: {rot_axis}" + + # Build the mesh tree using our mesh tree library. + # We don't need the upper side joints since we will only use these objects for bboxes. + G = build_mesh_tree(partial_scene_target_name, load_upper=False) + + # Go through each object. + roots = [ + node + for node, in_degree in G.in_degree() + if in_degree == 0 and not (set(G.nodes[node]["tags"]) & ALLOWED_PART_TAGS) + ] + + for root_node in roots: + obj_cat, obj_model, obj_inst_id, _ = root_node + + # For now, skip clutter objects + is_clutter = G.nodes[root_node]["is_loose"] == "C-" + + obj_name_in_scene = "-".join([obj_cat, obj_model, obj_inst_id]) + obj_rooms = G.nodes[root_node]["object_bounding_box"]["layer"] + # TODO: Verify rooms. + if obj_rooms == "0": + obj_rooms = "" + + # Get the relevant bbox info. + bbox_size = G.nodes[root_node]["object_bounding_box"]["extent"] + bbox_world_center = G.nodes[root_node]["object_bounding_box"]["position"] + bbox_world_rot = R.from_quat( + G.nodes[root_node]["object_bounding_box"]["rotation"] + ) + + # Apply the relevant transformation + bbox_transform = np.eye(4) + bbox_transform[:3, :3] = bbox_world_rot.as_matrix() + bbox_transform[:3, 3] = bbox_world_center + corrected_bbox_transform = rel_transform @ bbox_transform + assert ( + corrected_bbox_transform[3, 3] == 1 + ), "Homogeneous coordinate should be 1" + corrected_bbox_center = corrected_bbox_transform[:3, 3] + corrected_bbox_rot = R.from_matrix(corrected_bbox_transform[:3, :3]) + + # Save pose to scene URDF + roots_to_add_to = ["with_clutter"] # definitely add to the cluttered scene + if not is_clutter: + # If not clutter, add to the uncluttered scene also + roots_to_add_to.append("best") + for suffix in roots_to_add_to: + scene_tree_root = scene_tree_roots[suffix] + scene_link = ET.SubElement(scene_tree_root, "link") + scene_link.attrib = { + "category": obj_cat, + "model": obj_model, + "name": obj_name_in_scene, + "rooms": obj_rooms, + } + scene_link.attrib["bounding_box"] = " ".join( + ["%.4f" % item for item in bbox_size] + ) + joint = ET.SubElement(scene_tree_root, "joint") + joint_fixed = G.nodes[root_node]["is_loose"] is None + joint.attrib = { + "name": f"j_{obj_name_in_scene}", + "type": "fixed" if joint_fixed else "floating", + } + joint_origin = ET.SubElement(joint, "origin") + joint_origin_xyz = corrected_bbox_center.tolist() + joint_origin_rpy = corrected_bbox_rot.as_euler("xyz").tolist() + joint_origin.attrib = { + "xyz": " ".join([str(item) for item in joint_origin_xyz]), + "rpy": " ".join([str(item) for item in joint_origin_rpy]), + } + joint_parent = ET.SubElement(joint, "parent") + joint_parent.attrib = {"link": "world"} + joint_child = ET.SubElement(joint, "child") + joint_child.attrib = {"link": obj_name_in_scene} + + # Write, reparse, and write with header, using the XML library, + urdf_dir = OSFS(scenes_dir).makedir(scene_name).makedir("urdf") + for suffix, scene_tree_root in scene_tree_roots.items(): + xmlstr = minidom.parseString(ET.tostring(scene_tree_root)).toprettyxml( + indent=" " + ) + xmlio = io.StringIO(xmlstr) + tree = ET.parse(xmlio) + with urdf_dir.open(f"{scene_name}_{suffix}.urdf", "wb") as f: + tree.write(f, xml_declaration=True) + + +def main(): + # If this variable is set, we will only export the scenes in this list. This is useful for quickly + # iterating on scenes (usdify otherwise takes 8+ hours) to resolve stability etc. issues. + SCENES_TO_INCLUDE = [] # ["house_single_floor", "house_double_floor_lower", "house_double_floor_upper"] + + with b1k_pipeline.utils.ParallelZipFS("scenes.zip", write=True) as archive_fs: + scenes_dir = archive_fs.makedir("scenes").getsyspath("/") + errors = {} + target_futures = {} + + with futures.ProcessPoolExecutor(max_workers=16) as target_executor: + targets = b1k_pipeline.utils.get_targets("final_scenes") + if SCENES_TO_INCLUDE: + targets = [ + target + for target in targets + if target.replace("scenes/", "") in SCENES_TO_INCLUDE + ] + for target in tqdm.tqdm(targets): + target_futures[ + target_executor.submit(process_target, target, scenes_dir) + ] = target + + with tqdm.tqdm(total=len(target_futures)) as pbar: + for future in futures.as_completed(target_futures.keys()): + try: + result = future.result() + except: + name = target_futures[future] + errors[name] = traceback.format_exc() + + pbar.update(1) + + remaining_targets = [ + v for k, v in target_futures.items() if not k.done() + ] + if len(remaining_targets) < 10: + print("Remaining:", remaining_targets) + + print("Time for executor shutdown") + + print("Finished processing") + + pipeline_fs = b1k_pipeline.utils.PipelineFS() + with pipeline_fs.pipeline_output().open("export_scenes.json", "w") as f: + json.dump({"success": not errors, "errors": errors}, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/fillable_browser.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/fillable_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..33b3fc9e222286bd8ef99c8a74627530f612396f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/fillable_browser.py @@ -0,0 +1,74 @@ +import json +import pathlib +import sys +import glob +import os +import pybullet as p + +import numpy as np +from scipy.spatial.transform import Rotation as R +import tqdm + +import igibson + +igibson.ig_dataset_path = "/scr/BEHAVIOR-1K/asset_pipeline/tmp/fedafr" + +from igibson.simulator import Simulator +from igibson.scenes.igibson_indoor_scene import InteractiveIndoorScene +from igibson.scenes.empty_scene import EmptyScene +from igibson.objects.articulated_object import URDFObject +from igibson.external.pybullet_tools import utils + + +def main(): + # Load the scene into iGibson 2 + s = Simulator(mode="headless", use_pb_gui=True, image_height=1080, image_width=1920) + scene = EmptyScene() + s.import_scene(scene) + + fillable_models = json.loads( + pathlib.Path( + "/scr/BEHAVIOR-1K/asset_pipeline/artifacts/pipeline/fillable_ids.json" + ).read_text() + ) + fillable_paths = sorted( + [ + path + for fm in fillable_models + for path in glob.glob( + os.path.join( + igibson.ig_dataset_path, "objects", "*", fm, "urdf", f"{fm}.urdf" + ) + ) + ] + ) + print("Found", len(fillable_paths), "fillable objects out of", len(fillable_models)) + + START_ID = 0 + for i, path in enumerate(fillable_paths[START_ID : START_ID + 250]): + ctr_x = i * 1.2 + metadata = json.loads( + (pathlib.Path(path).parent / "misc/metadata.json").read_text() + ) + native_bbox_size = np.array(metadata["bbox_size"]) + scale = 1.0 / np.max(native_bbox_size) + obj = URDFObject(path, scale=scale * np.array([1.0, 1.0, 1.0]), fixed_base=True) + s.import_object(obj) + obj.set_bbox_center_position_orientation( + np.array([ctr_x, 0, 1]), np.array([0, 0, 0, 1]) + ) + p.addUserDebugText( + text=pathlib.Path(path).parts[-2], + textPosition=[ctr_x - 0.5, 0, 1.75], + textOrientation=p.getQuaternionFromEuler([np.pi / 2, 0, 0]), + textSize=0.4, + ) + print(i) + + # Step the simulation by 5 seconds. + while True: + s.step() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/fix_bakery_mtimes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/fix_bakery_mtimes.py new file mode 100644 index 0000000000000000000000000000000000000000..db94bce36f80665622f56de266236443dd500cd8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/fix_bakery_mtimes.py @@ -0,0 +1,165 @@ +"""Fix mtimes of files under cad/*/*/bakery/* using upload times from the DVC GCS remote. + +Files in the bakery directories are symlinks into the DVC cache (cache.type=symlink). +The DVC cache layout (DVC 3.x: files/md5//) matches the layout in the GCS +remote bucket, so the symlink's path relative to .dvc/cache is also the GCS object name. + +We update the mtime of the cache target (not the symlink), because: + * os.path.getmtime follows symlinks, so this is what readers observe. + * Multiple bakery files may point at the same content-addressed cache entry; updating + the target dedupes the work and keeps mtimes consistent across all references. +""" + +from __future__ import annotations + +import argparse +import os +import pathlib +import sys +from concurrent.futures import ThreadPoolExecutor, as_completed + +import tqdm +from google.cloud import storage + +DEFAULT_REPO = pathlib.Path(__file__).resolve().parents[1] +DEFAULT_PROJECT = "lucid-inquiry-205018" +DEFAULT_BUCKET = "ig-pipeline-cache" + + +def iter_bakery_files(repo_root: pathlib.Path): + """Yield paths matching cad/*/*/bakery/* (one level).""" + for file in (repo_root / "cad").glob("*/*/bakery/*"): + yield file + + +def symlink_to_cache_relpath( + symlink_path: pathlib.Path, cache_root: pathlib.Path +) -> pathlib.PurePosixPath | None: + """Resolve a bakery symlink to a path relative to the DVC cache root. + + Uses os.path.realpath, which on Windows strips any ``\\\\?\\`` extended-path + prefix that os.readlink may return for DVC symlinks. + """ + try: + real = pathlib.Path(os.path.realpath(symlink_path)) + except OSError: + return None + try: + rel = real.relative_to(cache_root) + except ValueError: + return None + return pathlib.PurePosixPath(*rel.parts) + + +def fetch_mtime(bucket: storage.Bucket, relpath: pathlib.PurePosixPath) -> float | None: + blob = bucket.get_blob(str(relpath)) + if blob is None or blob.updated is None: + return None + return blob.updated.timestamp() + + +def main() -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument( + "--repo", + type=pathlib.Path, + default=DEFAULT_REPO, + help="Path to the asset_pipeline repo root (default: parent of this script).", + ) + p.add_argument("--project", default=DEFAULT_PROJECT, help="GCP project name.") + p.add_argument("--bucket", default=DEFAULT_BUCKET, help="GCS bucket name.") + p.add_argument("--workers", type=int, default=32, help="Parallel GCS metadata workers.") + p.add_argument("--dry-run", action="store_true", help="Don't actually call os.utime.") + args = p.parse_args() + + repo = pathlib.Path(os.path.realpath(args.repo)) + cache_root = pathlib.Path(os.path.realpath(repo / ".dvc" / "cache")) + if not cache_root.is_dir(): + print(f"DVC cache not found at {cache_root}", file=sys.stderr) + return 1 + + print(f"Scanning bakery files under {repo} ...") + by_rel: dict[pathlib.PurePosixPath, list[pathlib.Path]] = {} + n_total = 0 + n_not_symlink = 0 + for f in iter_bakery_files(repo): + n_total += 1 + if not f.is_symlink(): + n_not_symlink += 1 + continue + rel = symlink_to_cache_relpath(f, cache_root) + if rel is None: + print(f"WARN: cannot derive cache relpath for {f}", file=sys.stderr) + continue + by_rel.setdefault(rel, []).append(f) + n_links = sum(len(v) for v in by_rel.values()) + print( + f" {n_total} matched files, {n_not_symlink} non-symlinks skipped, " + f"{n_links} symlinks pointing to {len(by_rel)} unique cache entries." + ) + if not by_rel: + if n_total > 0 and n_not_symlink == n_total: + print( + "No symlinks found among matched files. On Windows, DVC only creates\n" + "symlinks when Developer Mode is enabled or the process runs as admin;\n" + "otherwise it falls back to copy/hardlink and there is no cache target\n" + "to look up. Re-run `dvc checkout` with symlinks enabled, or adapt this\n" + "script to look up hashes via the .dvc files directly.", + file=sys.stderr, + ) + return 0 + + print(f"Querying GCS bucket gs://{args.bucket} ...") + client = storage.Client(project=args.project) + bucket = client.bucket(args.bucket) + + mtimes: dict[pathlib.PurePosixPath, float] = {} + missing: list[pathlib.PurePosixPath] = [] + with ThreadPoolExecutor(max_workers=args.workers) as ex: + futs = {ex.submit(fetch_mtime, bucket, rel): rel for rel in by_rel} + for fut in tqdm.tqdm(as_completed(futs), total=len(futs), desc="GCS"): + rel = futs[fut] + try: + t = fut.result() + except Exception as e: + print(f"WARN: failed to fetch {rel}: {e}", file=sys.stderr) + continue + if t is None: + missing.append(rel) + continue + mtimes[rel] = t + if missing: + print( + f"WARN: {len(missing)} cache entries not found in bucket " + f"(first few: {[str(x) for x in missing[:5]]})", + file=sys.stderr, + ) + + print( + f"{'(dry-run) ' if args.dry_run else ''}" + f"Setting mtime on {len(mtimes)} cache files ..." + ) + n_done = 0 + n_missing_local = 0 + affected_links = 0 + for rel, t in mtimes.items(): + target = cache_root / pathlib.Path(*rel.parts) + if not target.exists(): + n_missing_local += 1 + continue + if not args.dry_run: + os.utime(target, (t, t)) + n_done += 1 + affected_links += len(by_rel[rel]) + + print(f"Updated {n_done} cache entries (affects {affected_links} bakery symlinks).") + if n_missing_local: + print( + f"WARN: {n_missing_local} cache entries had GCS mtimes but no local file.", + file=sys.stderr, + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_og.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_og.py new file mode 100644 index 0000000000000000000000000000000000000000..95014b2ca5bc97af8887947d26a1e59618abf8ea --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_og.py @@ -0,0 +1,181 @@ +import pathlib +import sys + +import cv2 +import numpy as np +import torch as th +from PIL import Image +import os + +import omnigibson as og +from omnigibson.macros import gm +import omnigibson.utils.transform_utils as T +from omnigibson.objects.dataset_object import DatasetObject + +CENTER_HEIGHT = 1.0 # meters + +IMG_WIDTH = 1280 +IMG_HEIGHT = 720 + + +def main(): + dataset_path = sys.argv[1] + output_path = sys.argv[2] + batch = sys.argv[3:] + + # Set the dataset path + gm.DATASET_PATH = dataset_path + + # Create the scene config to load -- empty scene + cfg = { + "scene": { + "type": "Scene", + "floor_plane_visible": False, + }, + "render": { + "viewer_width": IMG_WIDTH, + "viewer_height": IMG_HEIGHT, + }, + } + + # Create the environment + env = og.Environment(configs=cfg) + + # Make it brighter + dome_light = og.sim.skybox + dome_light.intensity = 0.25e4 + + for item in batch: + obj_category, obj_model = pathlib.Path(item).parts[-2:] + og.sim.stop() + obj = DatasetObject( + name="obj", + category=obj_category, + model=obj_model, + visual_only=True, + ) + env.scene.add_object(obj) + # Make sure the object fits in a box of unit size 1 + obj.scale = (th.ones(3) / obj.aabb_extent).min() + og.sim.play() + + # Move the object so that its center is at [0, 0, 1] + camera_dist = obj.aabb_extent[:2].max() * 4.0 + height_range = th.maximum( + th.sin(th.deg2rad(th.tensor(45.0))) * camera_dist, # Either 45 degrees + obj.aabb_extent[2] * 2.0, # Or twice the object height + ) + center_offset = obj.get_position() - obj.aabb_center + target_pos = th.tensor([0.0, 0.0, CENTER_HEIGHT]) + + # Place the center at [0, 0, CENTER_HEIGHT] + obj.set_position_orientation( + position=center_offset + target_pos, orientation=[0, 0, 0, 1] + ) + og.sim.viewer_camera.set_position_orientation( + position=th.tensor([camera_dist, 0, CENTER_HEIGHT]), + orientation=T.euler2quat(th.tensor([th.pi / 2.0, 0.0, th.pi / 2.0])), + ) + + og.sim.step() + for _ in range(10): + og.sim.render() + + total_time_ms = 6000 + fps = 30 + total_frames = (total_time_ms * fps) // 1000 + total_horizontal_revolutions = 3 + total_vertical_revolutions = 2 + total_joint_loops = 1.5 + pitch_angular_velocity = th.tensor( + 2 * th.pi * total_vertical_revolutions / total_frames + ) + yaw_angular_velocity = th.tensor( + 2 * th.pi * total_horizontal_revolutions / total_frames + ) + joint_angular_velocity = th.tensor(2 * th.pi * total_joint_loops / total_frames) + + # Make the collision meshes also visible by just the visibility argument + # (if they have the "guide" purpose, they are not visible even if the visibility is True) + for link in obj.links.values(): + for mesh in link.visual_meshes.values(): + # Set the purpose to "default" for all visual meshes and all meta meshes except containers. + mesh.purpose = ( + "default" + if not link.is_meta_link or link.meta_link_type != "container" + else "guide" + ) + mesh.visible = not link.is_meta_link + for mesh in link.collision_meshes.values(): + mesh.purpose = "default" + mesh.visible = False + + # Open the video file + filename = os.path.join(output_path, f"{obj_model}.mp4") + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + video_writer = cv2.VideoWriter(filename, fourcc, 30.0, (IMG_WIDTH, IMG_HEIGHT)) + + # Open/close joints for 3 times (lower_limit -> upper_limit -> lower_limit, 3 times) + for view_collision_mesh in [False, True]: + for link in obj.links.values(): + for mesh in link.visual_meshes.values(): + mesh.visible = not view_collision_mesh + for mesh in link.collision_meshes.values(): + mesh.visible = view_collision_mesh + + for i in range(total_frames): + camera_yaw = th.tensor(yaw_angular_velocity * i) + camera_pos = th.tensor( + [ + th.cos(camera_yaw) * camera_dist, + th.sin(camera_yaw) * camera_dist, + th.sin(pitch_angular_velocity * i) * height_range + + CENTER_HEIGHT, + ] + ) + camera_pitch = th.arctan((CENTER_HEIGHT - camera_pos[2]) / camera_dist) + og.sim.viewer_camera.set_position_orientation( + position=camera_pos, + orientation=T.euler2quat( + th.tensor( + [camera_pitch + th.pi / 2.0, 0.0, camera_yaw + th.pi / 2.0] + ) + ), + ) + if obj.n_dof > 0: + j_frac = th.sin(joint_angular_velocity * i) + obj.set_joint_positions( + positions=j_frac * th.ones(obj.n_dof), + normalized=True, + drive=False, + ) + + og.sim.step() + og.sim.render() + og.sim.render() + + # Get the image as a 3-channel uint8 rgb image + image = ( + og.sim.viewer_camera.get_obs()[0]["rgb"] + .cpu() + .numpy()[:, :, :3] + .astype(np.uint8) + ) + + # Convert to BGR format for OpenCV + image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + + video_writer.write(image) + + video_writer.release() + with open(filename.replace(".mp4", ".success"), "w") as f: + pass + + env.scene.remove_object(obj) + + # Shut down at the end + og.shutdown() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_pb.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_pb.py new file mode 100644 index 0000000000000000000000000000000000000000..b34df6d90b2ff0307e5602f73e6b9b5e517c1261 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_pb.py @@ -0,0 +1,165 @@ +import logging +import os +import json +import random +import sys +from matplotlib import pyplot as plt +import nltk +import numpy as np +import csv +import pybullet as p +import shutil +from PIL import Image +from fs.copy import copy_dir +from fs.osfs import OSFS +from fs.tempfs import TempFS +from fs.zipfs import ZipFS +import tqdm + +nltk.download("wordnet") +nltk.download("omw-1.4") +from nltk.corpus import wordnet as wn + +import igibson + +import igibson.external.pybullet_tools.utils as pb_utils +from igibson.object_states.link_based_state_mixin import LinkBasedStateMixin +from igibson.objects.articulated_object import URDFObject +from igibson.render.mesh_renderer.mesh_renderer_settings import MeshRendererSettings +from igibson.scenes.empty_scene import EmptyScene +from igibson.simulator import Simulator +from igibson.utils.assets_utils import ( + get_all_object_categories, + get_ig_model_path, + get_object_models_of_category, +) + +from b1k_pipeline.utils import PipelineFS, TMP_DIR + +USE_IG_RENDERER = False + + +def main(): + # TempFS(temp_dir=str(TMP_DIR)) as dataset_fs, \ + + with ( + PipelineFS() as pipeline_fs, + OSFS(r"D:\dataset-5-3") as dataset_fs, + ZipFS( + pipeline_fs.pipeline_output().open("object_images.zip", "wb"), write=True + ) as out_fs, + ): + # First copy over all the objects + # with ZipFS(pipeline_fs.open("artifacts/og_dataset.zip", "rb")) as dataset_zip_fs: + # print("Copying objects over") + # copy_dir(dataset_zip_fs, "objects", dataset_fs, "objects") + # print("Done copying objects over") + igibson.ignore_visual_shape = False + igibson.ig_dataset_path = dataset_fs.getsyspath("/") + + # Get all the objects in the dataset + all_objs = [ + (cat, model) + for cat in get_all_object_categories() + for model in get_object_models_of_category(cat) + ] + all_objs.sort() + + for obj_category, obj_model in tqdm.tqdm(all_objs): + obj_name = "{}-{}".format(obj_category, obj_model) + if out_fs.exists(f"{obj_name}.jpg"): + continue + + height, width = 768, 1024 + if USE_IG_RENDERER: + settings = MeshRendererSettings( + env_texture_filename=None, enable_shadow=True, msaa=True + ) + sim = Simulator( + mode="headless", + use_pb_gui=False, + image_width=width, + image_height=height, + vertical_fov=70, + rendering_settings=settings, + ) + else: + sim = Simulator(mode="headless", use_pb_gui=True) + sim.import_scene(EmptyScene(render_floor_plane=False)) + + model_path = get_ig_model_path(obj_category, obj_model) + filename = os.path.join(model_path, "urdf", f"{obj_model}.urdf") + + try: + bbox = URDFObject( + filename, + name=obj_name, + category=obj_category, + model_path=model_path, + fixed_base=True, + ).bounding_box + + # Get the right scale + scale = np.min(1 / bbox) + simulator_obj = URDFObject( + filename, + name=obj_name, + category=obj_category, + model_path=model_path, + fixed_base=True, + scale=np.array([scale, scale, scale]), + ) + + sim.import_object(simulator_obj) + simulator_obj.set_bbox_center_position_orientation( + np.array([0, 0, 0.5]), np.array([0, 0, 0, 1]) + ) + + dist = 1 + if USE_IG_RENDERER: + target = [0, 0, simulator_obj.bounding_box[2] / 2] + cam = [ + dist * np.cos(np.deg2rad(30)), + dist * np.sin(np.deg2rad(30)), + dist * np.sin(np.deg2rad(30)), + ] + sim.renderer.set_camera(cam, target, [0, 0, 1]) + img = sim.renderer.render(modes=("rgb",))[0] + img = np.reshape(img, (height, width, 4)) + img = img[:, :, :3] * 255 + else: + p.resetDebugVisualizerCamera( + cameraDistance=dist, + cameraYaw=30, + cameraPitch=-30, + cameraTargetPosition=[0, 0, simulator_obj.bounding_box[2] / 2], + ) + w, h, V, P = p.getDebugVisualizerCamera()[:4] + img = p.getCameraImage( + w, + h, + viewMatrix=V, + projectionMatrix=P, + renderer=p.ER_BULLET_HARDWARE_OPENGL, + )[2] + img = np.reshape(img, (h, w, 4)) + img = img[:, :, :3] + + with out_fs.open(f"{obj_name}.jpg", "wb") as f: + im = Image.fromarray(img.astype(np.uint8)) + im.save(f, format="JPEG") + + # for bid in simulator_obj.get_body_ids(): + # for joint in pb_utils.get_movable_joints(bid): + # name = pb_utils.get_link_name(bid, joint) + # _, upper = pb_utils.get_joint_limits(bid, joint) + # pb_utils.set_joint_position(bid, joint, upper) + # message += f"- {name}\n" + except: + print(obj_name, "failed - continuing.") + finally: + sim.disconnect() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_slurm.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_slurm.py new file mode 100644 index 0000000000000000000000000000000000000000..309c5881ad8e25c35f17f244b89bdcc14abdd6c9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_object_images_slurm.py @@ -0,0 +1,176 @@ +import os +import signal +import subprocess +import sys +from concurrent.futures import as_completed + +import fs.path +from fs.copy import copy_fs +from fs.tempfs import TempFS +from fs.osfs import OSFS +from fs.zipfs import ZipFS + +from b1k_pipeline.utils import ( + PipelineFS, + TMP_DIR, + make_og_pool_executor, + worker_subprocess_env, +) + +import tqdm + + +BATCH_SIZE = 8 +assert BATCH_SIZE % 2 == 0 +WORKER_COUNT = 6 +MAX_TIME_PER_PROCESS = 5 * 60 # 5 minutes + + +def run_on_batch(dataset_path, out_path, batch): + cmd = [ + sys.executable, + "-m", + "b1k_pipeline.generate_object_images_og", + dataset_path, + out_path, + ] + batch + obj = batch[0].split("/")[-1] + os.makedirs("/scr/BEHAVIOR-1K/asset_pipeline/logs", exist_ok=True) + with ( + open(f"/scr/BEHAVIOR-1K/asset_pipeline/logs/{obj}.log", "w") as f, + open(f"/scr/BEHAVIOR-1K/asset_pipeline/logs/{obj}.err", "w") as ferr, + ): + try: + # process_group=0 puts the subprocess in its OWN process group + # (so os.killpg below only reaches the subprocess and its + # descendants — not the pool worker that called us) but leaves + # it in the parent's session, so a terminal SIGHUP / + # head-process crash still tears it down. + p = subprocess.Popen( + cmd, + stdout=f, + stderr=ferr, + cwd="/scr/BEHAVIOR-1K/asset_pipeline", + process_group=0, + env=worker_subprocess_env(), + ) + return p.wait(timeout=MAX_TIME_PER_PROCESS) + except subprocess.TimeoutExpired: + print( + f"Timeout for {batch} ({MAX_TIME_PER_PROCESS}s) expired. Killing", + file=sys.stderr, + ) + os.killpg(p.pid, signal.SIGKILL) + return p.wait() + + +def main(): + with PipelineFS() as pipeline_fs: + with ( + ZipFS(pipeline_fs.open("artifacts/og_dataset.zip", "rb")) as dataset_zip_fs, + TempFS(temp_dir=str(TMP_DIR)) as dataset_fs, + OSFS( + pipeline_fs.makedirs( + "artifacts/pipeline/object_images", recreate=True + ).getsyspath("/") + ) as out_temp_fs, + ): + # Copy everything over to the dataset FS + print("Copy everything over to the dataset FS...") + objdir_glob = list(dataset_zip_fs.glob("objects/*/*/")) + for item in tqdm.tqdm(objdir_glob): + if ( + dataset_zip_fs.opendir(item.path).glob("usd/*.usd").count().files + == 0 + ): + continue + objdir_normalized = fs.path.normpath(item.path) + obj_id = fs.path.basename(objdir_normalized) + if out_temp_fs.exists(f"{obj_id}.success"): + continue + copy_fs( + dataset_zip_fs.opendir(item.path), dataset_fs.makedirs(item.path) + ) + + # Launch the cluster + print("Launching cluster...") + with make_og_pool_executor(WORKER_COUNT) as executor: + # Start the batched run + object_glob = [ + fs.path.normpath(x.path) for x in dataset_fs.glob("objects/*/*/") + ] + + print("Queueing batches.") + print("Total count: ", len(object_glob)) + futures = {} + batch_size = min(BATCH_SIZE, len(object_glob) // WORKER_COUNT) + for start in range(0, len(object_glob), batch_size): + end = start + batch_size + batch = object_glob[start:end] + if batch: + worker_future = executor.submit( + run_on_batch, + dataset_fs.getsyspath("/"), + out_temp_fs.getsyspath("/"), + batch, + ) + futures[worker_future] = batch + + # Wait for all the workers to finish + print("Queued all batches. Waiting for them to finish...") + while True: + for future in tqdm.tqdm( + as_completed(futures.keys()), total=len(futures) + ): + # Check the batch results. + batch = futures[future] + return_code = future.result() # we dont use the return code since we check the output files directly + + # Remove everything that failed and make a new batch from them. + new_batch = [] + for item in batch: + item_basename = fs.path.basename(item) + expected_output = f"{item_basename}.success" + if not out_temp_fs.exists(expected_output): + print("Could not find", expected_output) + new_batch.append(item) + + # If there's nothing to requeue, we are good! + if not new_batch: + continue + + # Otherwise, decide if we are going to requeue or just skip. + if len(batch) == 1: + print(f"Failed on a single item {batch[0]}. Skipping.") + else: + print(f"Subdividing batch of length {len(new_batch)}") + batch_size = len(new_batch) // 2 + subbatches = [new_batch[:batch_size], new_batch[batch_size:]] + for subbatch in subbatches: + if not subbatch: + continue + worker_future = executor.submit( + run_on_batch, + dataset_fs.getsyspath("/"), + out_temp_fs.getsyspath("/"), + subbatch, + ) + futures[worker_future] = subbatch + del futures[future] + + # Restart the for loop so that the counter can update + break + else: + # Completed successfully - break out of the while loop. + break + + print("Finished processing. Shutting down executor...") + + print("Archiving results...") + + # At this point, out_temp_fs's contents will be zipped. Save the success file. + pipeline_fs.pipeline_output().touch("generate_images.success") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_params.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_params.py new file mode 100644 index 0000000000000000000000000000000000000000..86e82ee941d0a9adee956be334fd830d2ce11b1b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_params.py @@ -0,0 +1,239 @@ +"""Regenerate the params.yaml file to contain all of the object and scenes.""" + +import os +import re +import sys +import yaml +import hashlib +import json + +OBJS_DIR = "../cad/objects" +SCENES_DIR = "../cad/scenes" +OUT_PATH = "../params.yaml" +ROOT_PATH = ".." + +DVC_TMPL_PATH = "../dvc-tmpl.yaml" +DVC_OUT_PATH = "../dvc.yaml" + +DEP_REGEX = re.compile(r"#\{(.*?)\}") + +FINAL_SCENES = [ + "Beechwood_0_int", + "Beechwood_1_int", + "Benevolence_0_int", + "Benevolence_1_int", + "Benevolence_2_int", + "Ihlen_0_int", + "Ihlen_1_int", + "Merom_0_int", + "Merom_1_int", + "Pomaria_0_int", + "Pomaria_1_int", + "Pomaria_2_int", + "Rs_int", + "Wainscott_0_int", + "Wainscott_1_int", + "Beechwood_0_garden", + "Rs_garden", + "Pomaria_0_garden", + "Merom_0_garden", + "Wainscott_0_garden", + "house_single_floor", + "house_double_floor_lower", + "house_double_floor_upper", + "grocery_store_asian", + "grocery_store_cafe", + "grocery_store_convenience", + "grocery_store_half_stocked", + "hall_arch_wood", + "hall_train_station", + "hall_glass_ceiling", + "hall_conference_large", + "hotel_suite_large", + "hotel_suite_small", + "hotel_gym_spa", + "office_bike", + "office_cubicles_left", + "office_cubicles_right", + "office_large", + "office_vendor_machine", + "restaurant_asian", + "restaurant_cafeteria", + "restaurant_diner", + "restaurant_brunch", + "restaurant_urban", + "restaurant_hotel", + "school_gym", + "school_geography", + "school_biology", + "school_chemistry", + "school_computer_lab_and_infirmary", + "gates_bedroom", +] + +CHALLENGE_SCENES = [ + "house_single_floor", + "house_double_floor_lower", + "house_double_floor_upper", + "restaurant_diner", + "hotel_suite_large", + "office_cubicles_right", + "Rs_int", +] + +APPROVED_OBJS = { + ".*", +} + +REJECTED_OBJS = set() + +# APPROVED_SCENES = set() + +APPROVED_SCENES = { + ".*", +} + +REJECTED_SCENES = set() + +VERIFIED_SCENES = { + ".*", +} + + +def get_challenge_scene_deps(challenge_scenes, approved_scenes): + challenge_scenes_and_deps = set(challenge_scenes) + for scene_name in sorted(challenge_scenes): + object_list_path = os.path.join( + os.path.dirname(__file__), + SCENES_DIR, + scene_name, + "artifacts", + "object_list.json", + ) + if not os.path.exists(object_list_path): + print(f"Missing object list for challenge scene: {scene_name}") + continue + + with open(object_list_path, "r") as f: + room_object_list = json.load(f) + + challenge_scenes_and_deps.update(room_object_list.get("outgoing_portals", {}).keys()) + + missing_challenge_deps = challenge_scenes_and_deps - set(approved_scenes) + if missing_challenge_deps: + print(f"Missing challenge scene dependencies: {missing_challenge_deps}") + + return sorted(challenge_scenes_and_deps & set(approved_scenes)) + + +def main(): + objects_path = os.path.join(os.path.dirname(__file__), OBJS_DIR) + all_object_list = [ + x + for x in os.listdir(objects_path) + if os.path.exists(os.path.join(objects_path, x, "processed.max")) + ] + approved_objects = sorted( + x + for x in all_object_list + if any(re.fullmatch(exp, x) for exp in APPROVED_OBJS) + and not any(re.fullmatch(exp, x) for exp in REJECTED_OBJS) + ) + objects = sorted( + ["objects/" + x for x in approved_objects] + ) + + scenes_path = os.path.join(os.path.dirname(__file__), SCENES_DIR) + all_scenes_list = [ + x + for x in os.listdir(scenes_path) + if os.path.exists(os.path.join(scenes_path, x, "processed.max")) + ] + approved_scenes = sorted( + x + for x in all_scenes_list + if any(re.fullmatch(exp, x) for exp in APPROVED_SCENES) + and not any(re.fullmatch(exp, x) for exp in REJECTED_SCENES) + ) + scenes = sorted(["scenes/" + x for x in approved_scenes]) # + + combined = objects + scenes + + found_final_scenes = set(FINAL_SCENES) & set(approved_scenes) + missing_final_scene_paths = set(FINAL_SCENES) - found_final_scenes + if missing_final_scene_paths: + print(f"Missing scenes: {missing_final_scene_paths}") + final_scenes = sorted(["scenes/" + x for x in found_final_scenes]) + + found_challenge_scenes = set(CHALLENGE_SCENES) & set(approved_scenes) + missing_challenge_scene_paths = set(CHALLENGE_SCENES) - found_challenge_scenes + if missing_challenge_scene_paths: + print(f"Missing challenge scenes: {missing_challenge_scene_paths}") + challenge_scenes = sorted(["scenes/" + x for x in found_challenge_scenes]) + challenge_scenes_and_deps = sorted( + "scenes/" + x + for x in get_challenge_scene_deps(found_challenge_scenes, approved_scenes) + ) + + found_verified_scenes = set( + x + for x in all_scenes_list + if any(re.fullmatch(exp, x) for exp in VERIFIED_SCENES) + ) & set(approved_scenes) + verified_scenes = sorted(["scenes/" + x for x in found_verified_scenes]) + + out_path = os.path.join(os.path.dirname(__file__), OUT_PATH) + params = { + "objects": objects, + "scenes": scenes, + "final_scenes": final_scenes, + "challenge_scenes": challenge_scenes, + "challenge_scenes_and_deps": challenge_scenes_and_deps, + "verified_scenes": verified_scenes, + "combined": combined, + } + with open(out_path, "w") as f: + yaml.dump(params, f) + + # Now update the # placeholders in deps + dvc_tmpl_path = os.path.join(os.path.dirname(__file__), DVC_TMPL_PATH) + with open(dvc_tmpl_path, "r") as f: + dvc_conf = yaml.load(f, Loader=yaml.SafeLoader) + + for stage in dvc_conf["stages"].values(): + deps_list = None + if "deps" in stage: + deps_list = stage["deps"] + elif "do" in stage and "deps" in stage["do"]: + deps_list = stage["do"]["deps"] + else: + continue + + new_deps_list = [] + for dep in deps_list: + match = DEP_REGEX.search(dep) + if match is None: + new_deps_list.append(dep) + continue + + key = match.group(1) + assert key in params, f"Unknown placeholder {key}" + replacements = params[key] + for replacement in replacements: + new_deps_list.append(DEP_REGEX.sub(replacement, dep)) + + if "deps" in stage: + stage["deps"] = new_deps_list + elif "do" in stage and "deps" in stage["do"]: + stage["do"]["deps"] = new_deps_list + + # Write the DVC file. + dvc_out_path = os.path.join(os.path.dirname(__file__), DVC_OUT_PATH) + with open(dvc_out_path, "w") as f: + yaml.dump(dvc_conf, f) + + print("Params updated successfully.") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_systems.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_systems.py new file mode 100644 index 0000000000000000000000000000000000000000..256262d018c3d14ba7a633ddf1a2f17f06c1718a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/generate_systems.py @@ -0,0 +1,52 @@ +import csv +import json +import fs.copy +from fs.multifs import MultiFS +import fs.path + +from b1k_pipeline.utils import ParallelZipFS, PipelineFS + + +def main(): + with ( + PipelineFS() as pipeline_fs, + ParallelZipFS("objects_usd.zip") as objects_usd_fs, + ParallelZipFS("objects.zip") as objects_urdf_fs, + ): + objects_fs = MultiFS() + objects_fs.add_fs("objects_usd", objects_usd_fs, priority=0) + objects_fs.add_fs("objects_urdf", objects_urdf_fs, priority=1) + + with ParallelZipFS("systems.zip", write=True) as out_fs: + substances = {} + with pipeline_fs.open("metadata/substance_hyperparams.csv") as csvfile: + reader = csv.DictReader(csvfile, delimiter=",", quotechar='"') + for row in reader: + name = row["substance"] + print(name) + assert name not in substances, f"Duplicate substance {name}" + params = json.loads(row["hyperparams"]) + substances[name] = params + + system_root_dir = out_fs.makedir("systems") + objects_root_dir = objects_fs.opendir("objects") + for system_name, metadata in substances.items(): + system_dir = system_root_dir.makedir(system_name) + + # Copy over asset files if they exist + if objects_root_dir.exists(system_name): + fs.copy.copy_fs(objects_root_dir.opendir(system_name), system_dir) + + # Dump the metadata + with system_dir.open("metadata.json", "w") as f: + json.dump(metadata, f) + + print("Done processing. Archiving things now.") + + # Save the logs + with pipeline_fs.pipeline_output().open("generate_systems.json", "w") as f: + json.dump({"success": True}, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/gw_objexp.ini b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/gw_objexp.ini new file mode 100644 index 0000000000000000000000000000000000000000..bd9b3bb3c03951e302c483fe4f54d4fc3532c721 Binary files /dev/null and b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/gw_objexp.ini differ diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/joint_inertias_from_usd.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/joint_inertias_from_usd.py new file mode 100644 index 0000000000000000000000000000000000000000..263a999bbba4ef0338e0274c6e8ff7e301355f66 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/joint_inertias_from_usd.py @@ -0,0 +1,118 @@ +from concurrent.futures import ProcessPoolExecutor, as_completed +import json +import os +import pathlib +import tempfile +from cryptography.fernet import Fernet +from pxr import Usd, UsdGeom, Gf, Sdf, UsdPhysics +import numpy as np +from scipy.spatial.transform import Rotation as R +from tqdm import tqdm +import fs.path +from fs.zipfs import ZipFS +import networkx as nx + +DATASET_PATH = pathlib.Path("/scr/og-docker-data/datasets/og_dataset") +KEY_PATH = pathlib.Path("/scr/og-docker-data/datasets/omnigibson.key") + + +def decrypt_file(encrypted_filename, decrypted_filename): + with open(KEY_PATH, "rb") as filekey: + key = filekey.read() + fernet = Fernet(key) + + with open(encrypted_filename, "rb") as enc_f: + encrypted = enc_f.read() + + decrypted = fernet.decrypt(encrypted) + + with open(decrypted_filename, "wb") as decrypted_file: + decrypted_file.write(decrypted) + + +def get_joint_inertias_from_usd(input_usd, tempdir): + encrypted_filename = input_usd + fd, decrypted_filename = tempfile.mkstemp(suffix=".usd", dir=tempdir) + os.close(fd) + decrypt_file(encrypted_filename, decrypted_filename) + stage = Usd.Stage.Open(str(decrypted_filename)) + prim = stage.GetDefaultPrim() + + # Build a graph of joints and links + G = nx.DiGraph() + link_masses = {} + + # Get all the links + for child in prim.GetChildren(): + if not child.HasAPI(UsdPhysics.MassAPI): + continue + path = str(child.GetPath()) + massapi = UsdPhysics.MassAPI(child) + mass = massapi.GetMassAttr().Get() + link_masses[path] = mass + + # Get all the joints + def find_all_prim_children_with_type(prim_type, root_prim): + found_prims = [] + for child in root_prim.GetChildren(): + if prim_type in child.GetTypeName(): + found_prims.append(child) + found_prims += find_all_prim_children_with_type( + prim_type=prim_type, root_prim=child + ) + return found_prims + + prismatics = find_all_prim_children_with_type("PhysicsPrismaticJoint", prim) + revolutes = find_all_prim_children_with_type("PhysicsRevoluteJoint", prim) + fixeds = find_all_prim_children_with_type("PhysicsFixedJoint", prim) + joints = prismatics + revolutes + fixeds + joint_children = {} + for joint in joints: + body0 = joint.GetRelationship("physics:body0").GetTargets()[0].__str__() + body1 = joint.GetRelationship("physics:body1").GetTargets()[0].__str__() + G.add_edge(body0, body1) + joint_children[joint] = body1 + + def _get_subtree(G, n): + return {n} | nx.descendants(G, n) + + movable_joints = prismatics + revolutes + joint_inertias = { + str(joint.GetPath()): sum( + link_masses[link] for link in _get_subtree(G, joint_children[joint]) + ) + for joint in movable_joints + } + + return joint_inertias + + +def main(): + input_usds = list(DATASET_PATH.glob("objects/*/*/usd/*.usd")) + input_usds.sort(key=lambda x: x.parts[-3]) + print(len(input_usds)) + + # Scale up + futures = {} + with tempfile.TemporaryDirectory() as tempdir: + with ProcessPoolExecutor() as executor: + for input_usd in tqdm(input_usds, desc="Queueing up jobs"): + future = executor.submit( + get_joint_inertias_from_usd, input_usd, tempdir + ) + futures[future] = input_usd + + # Gather the results (with a tqdm progress bar) + results = {} + for future in tqdm( + as_completed(futures), total=len(futures), desc="Processing results" + ): + input_usd = futures[future] + results[input_usd.parts[-3]] = future.result() + + with open(DATASET_PATH / "joint_inertias.json", "w") as f: + json.dump(results, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/json_merge_append.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/json_merge_append.py new file mode 100644 index 0000000000000000000000000000000000000000..31e3ad236f0ab47eb12bb5190de305cad29592cd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/json_merge_append.py @@ -0,0 +1,79 @@ +import itertools +import json +import os +import sys + + +def combine_list(ancestor, ours, theirs): + assert ( + isinstance(ancestor, list) + and isinstance(ours, list) + and isinstance(theirs, list) + ) + + # Check that all the elements in ancestor are in ours and theirs + for x in ancestor: + assert x in ours and x in theirs + + # Combine by appending the elements in ours and theirs that are not in ancestor + for x in theirs + ours: + if x not in ancestor: + ancestor.append(x) + + return ancestor + + +def combine_obj(ancestor, ours, theirs): + assert ( + isinstance(ancestor, dict) + and isinstance(ours, dict) + and isinstance(theirs, dict) + ) + + # Check that all the keys in ancestor are in ours and theirs + for k in ancestor.keys(): + assert k in ours and k in theirs + + # Check that ours and theirs have the same value for overlapping keys + collision_keys = (set(ours.keys()) & set(theirs.keys())) - set(ancestor.keys()) + assert not collision_keys, f"Collision keys: {collision_keys}" + + # Combine by appending the elements in ours and theirs that are not in ancestor + for k, v in itertools.chain(theirs.items(), ours.items()): + if k not in ancestor: + ancestor[k] = v + + return ancestor + + +def main(): + if len(sys.argv) != 5: + print( + "Usage: python json_merge.py " + ) + return + + mode, ancestor_fn, ours_fn, theirs_fn = sys.argv[1:] + assert mode in ["list", "obj"] + + ancestor = [] if mode == "list" else {} + if os.path.getsize(ancestor_fn) > 0: + with open(ancestor_fn, "r") as f: + ancestor = json.load(f) + with open(ours_fn, "r") as f: + ours = json.load(f) + with open(theirs_fn, "r") as f: + theirs = json.load(f) + + combined = ( + combine_list(ancestor, ours, theirs) + if mode == "list" + else combine_obj(ancestor, ours, theirs) + ) + + with open(ours_fn, "w") as f: + json.dump(combined, f, indent=4) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/llm_object_statistics.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/llm_object_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..15f66a02f311739e5387757f16de3f1001c0d12b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/llm_object_statistics.py @@ -0,0 +1,75 @@ +from transformers import ( + Qwen2_5_VLForConditionalGeneration, + AutoTokenizer, + AutoProcessor, +) +from qwen_vl_utils import process_vision_info +import torch + +# default: Load the model on the available device(s) +# model = Qwen2_5_VLForConditionalGeneration.from_pretrained( +# "Qwen/Qwen2.5-VL-7B-Instruct", torch_dtype="auto", device_map="auto" +# ) + +# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios. +model = Qwen2_5_VLForConditionalGeneration.from_pretrained( + "Qwen/Qwen2.5-VL-7B-Instruct-AWQ", + # torch_dtype=torch.bfloat16, + # attn_implementation="flash_attention_2", + device_map="auto", +) + +# default processer +# processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct-AWQ, ) + +# The default range for the number of visual tokens per image in the model is 4-16384. +# You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost. +min_pixels = 256 * 28 * 28 +max_pixels = 1280 * 28 * 28 +processor = AutoProcessor.from_pretrained( + "Qwen/Qwen2.5-VL-7B-Instruct-AWQ", min_pixels=min_pixels, max_pixels=max_pixels +) + +fps = 1.0 + +messages = [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": "file:///scr/BEHAVIOR-1K/asset_pipeline/frames/out.mp4", + # "max_pixels": 360 * 420, + "fps": fps, + }, + { + "type": "text", + "text": "In this video, an object from a 3D simulation environment is shown in front of an (unrelated) skybox. It's a printer object. What should be the realistic dimensions of this object? Output a JSON string in the format of {'height': x, 'width': y, 'depth': z} where x, y, z are the object dimensions in centimeters.", + }, + ], + } +] + +text = processor.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True +) +image_inputs, video_inputs = process_vision_info(messages) +inputs = processor( + text=[text], + images=image_inputs, + videos=video_inputs, + fps=fps, + padding=True, + return_tensors="pt", +) +inputs = inputs.to("cuda") + +# Inference +generated_ids = model.generate(**inputs, max_new_tokens=128) +generated_ids_trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) +] +output_text = processor.batch_decode( + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False +) +print(output_text) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/load_unique_class_info.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/load_unique_class_info.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7edfe388a2b50f16bd90675d08c2997abc82e1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/load_unique_class_info.py @@ -0,0 +1,136 @@ +from b1k_pipeline.utils import parse_name + +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R +import json + +rt = pymxs.runtime +local_coordsys = pymxs.runtime.Name("local") + +EIGVAL_TOL = 1e-3 + + +def get_object_key(obj): + """ + Get a unique key for an object. + """ + return parse_name(obj.name).group("model_id") + + +def get_object_category(obj): + """ + Get a unique key for an object. + """ + return parse_name(obj.name).group("category") + + +def change_object_category(obj, new_category): + """ + Change the category of an object. + """ + # Get the old category + old_category = get_object_category(obj) + + # Change the category + obj.name = obj.name.replace(old_category, new_category) + + +def change_object_key(obj, new_key): + """ + Change the key of an object. + """ + # Get the old key + old_key = get_object_key(obj) + + # Change the key + obj.name = obj.name.replace(old_key, new_key) + + +def load_unique_class_infos(): + saved_infos = json.load(open("unique_class_info.json", "r")) + for obj in rt.objects: + # Skip everything that's not an editable poly + if rt.classOf(obj) != rt.editable_poly: + continue + + # Skip if object is not the base link + link_name = parse_name(obj.name).group("link_name") + if link_name is not None and link_name != "basename": + continue + + model_id, category, material_name, eigvals = get_unique_class_info(obj) + # Get the class with the same material name and eigvals within EIGVAL_TOL + # i = 0 + for saved_model_id, saved_info in saved_infos.items(): + # i+=1 + if saved_info["material_name"] == material_name and np.allclose( + saved_info["eigvals"], eigvals, atol=EIGVAL_TOL + ): + # Change the category + rt.messageBox( + "Changing key of {} to {}".format(obj.name, saved_model_id) + ) + change_object_key(obj, saved_model_id) + rt.messageBox( + "Changed key of {} to {}".format(obj.name, saved_model_id) + ) + # if i>1: + # assert False + break + + +def get_unique_class_info(src_obj): + """ + Uniquely identify a class by its material name and the eigenvalues of its covariance matrix. + """ + X = np.array( + rt.polyop.getVerts( + src_obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(src_obj)) + ) + ) + n, m = X.shape + u = np.mean(X, axis=0) + # rt.messageBox("u: {}".format(u)) + B = X - u + # rt.messageBox("B: {}".format(B)) + C = 1 / (n - 1) * B.T @ B + eigvals, V = np.linalg.eig(C) + sorted_idxs = np.argsort(eigvals)[::-1] + eigvals = eigvals[sorted_idxs] + V = V[:, sorted_idxs] + # rt.messageBox("eigvals: {}".format(eigvals)) + # rt.messageBox("V: {}".format(V)) + + model_id = get_object_key(src_obj) + category = get_object_category(src_obj) + material_name = src_obj.material.name if src_obj.material else None + + return model_id, category, material_name, eigvals + # json.dump( + # { + # "model_id": model_id, + # "material_name": material_name, + # "eigvals": eigvals.tolist(), + # }, + # open("unique_class_info.json", "a"), + # ) + + +def load_unique_class_info_button(): + try: + load_unique_class_infos() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Unique class info loaded") + + +if __name__ == "__main__": + load_unique_class_info_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/add_buttons.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/add_buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc9e902eb1bed1c87549bf21517144454167692 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/add_buttons.py @@ -0,0 +1,123 @@ +import os +import pathlib +import re + +import pymxs + +rt = pymxs.runtime + +REMACRO = re.compile('^[0-9]+ +"[^"]*" +"([^"]*)" +"[^"]*" +"([^"]*)"', re.M) + +ENTRYPOINTS = { + "add_buttons.py": "Update the SVL script buttons in the 3ds Max menu.", + "add_fillable_seed.py": "Add a seed for generating fillable volumes.", + "align_pivots.py": "Find instances with unaligned pivots and align them.", + "assign_light.py": "Assign lights to objects.", + "assign_toggle.py": "Assign toggle button metalink to object", + "collision_vertex_reduction.py": "Reduce vertex count of a collision mesh.", + "demirror.py": "Fix objects that are mirrored.", + "find_duplicates.py": "Find duplicate objects in the scene.", + "generate_fillable_volume.py": "Generate fillable volume from seed point using ray casting.", + "generate_open_fillable_volume.py": "Generate open fillable volume from seed point using ray casting.", + # "fix_common_issues.py": "Fix common issues like scale.", + "fix_instance_materials.py": "Update object instances to use single material.", + "fix_legacy_obj_rots.py": "Fix legacy object rotations > 180deg.", + "flat_floor_to_cmesh.py": "Extrude flat floors to make collision meshes.", + "import_legacy_objs.py": "Import missing legacy objects from iG2.", + "import_scene_obj_orientations.py": "Fix legacy scene orientations.", + "instanceify.py": "Convert objects into instances.", + "instance_select.py": "Select all instances of objects.", + "match_links.py": "Match the links on all instances of the selected object.", + "merge_collision.py": "Merge collision objects into a single object and parent them.", + "create_collision_from_self.py": "Create a collision object from the selected object.", + "new_sanity_check.py": "Run a number of sanity checks.", + "next_failed.py": "Open the next object file that has failed sanity check.", + "qa_next_failed.py": "Open the next object file that has unprocessed QA comments.", + "qa_next_failed_task_required.py": "Open the next task-required object file that has unprocessed QA comments.", + "object_qa.py": "Walk through scene objects for quality assurance.", + "category_qa.py": "Walk through scene categories for quality assurance.", + "prereduce.py": "Apply vertex reduction without collapsing.", + "randomize_obj_names.py": "Randomize objects named in the legacy format.", + "renumber.py": "Renumber all objects in this file s.t. they're consecutive", + "replace_bad_object.py": "Replace bad object instances with copy of the same object from provider file.", + "rpc_server.py": "Run RPC Server for DVC stages.", + "convex_decomposition.py": "Run CoACD and VHACD to generate collision mesh.", + "convex_hull.py": "Generate collision mesh from the convex hull of the selected object or faces.", + "validate_collision.py": "Validate the selected collision or fillable mesh.", + "triangulate.py": "Triangulate the selected object.", + "select_mismatched_pivot.py": "Select groups of object instances whose pivots dont match.", + "spherify.py": "Convert point helpers into spheres.", + "switch_loose.py": "Switch visible object between different looseness options.", + "switch_metalink.py": "Switch type of selected metalinks", + "toggle_meta_visibility.py": "Toggle visibility of meta links.", + "translate_ig_dataset.py": "Update names of iG2 objects to new format.", + "two_room_assignment.py": "Assign objects to a combined layer for two rooms.", + "three_room_assignment.py": "Assign objects to a combined layer for three rooms.", + "view_complaints.py": "View QA complaints for this file.", + "resolve_complaints.py": "Resolve QA complaints for this file.", + "wensi_view_complaints.py": "View Wensi's TODO complaints for this file.", + "wensi_resolve_complaints.py": "Resolve Wensi's TODO complaints for this file.", + "require_rebake.py": "Mark the object for rebaking of its texture.", + "prebake_textures.py": "Prebake textures for the selected objects (or all objects that need it if nothing is selected).", +} + + +def main(): + # Get the main menu bar + mainMenuBar = rt.menuMan.getMainMenuBar() + + # Create the menu if it doesnt exist + if rt.menuMan.registerMenuContext(0x5F77DD6D): + # Create a new menu + subMenu = rt.menuMan.createMenu("SVL") + # Create a new menu item with the menu as its sub-menu + subMenuItem = rt.menuMan.createSubMenuItem("SVL", subMenu) + # Compute the index of the next-to-last menu item in the main menu bar + subMenuIndex = mainMenuBar.numItems() - 1 + # Add the sub-menu just at the second to last slot + mainMenuBar.addItem(subMenuItem, subMenuIndex) + else: + # Get the existing menu + (subMenuItem,) = [ + mainMenuBar.getItem(x + 1) + for x in range(mainMenuBar.numItems()) + if mainMenuBar.getItem(x + 1).getTitle() == "SVL" + ] + subMenu = subMenuItem.getSubMenu() + + this_dir = pathlib.Path(__file__).parent + + for entrypoint, tooltip in ENTRYPOINTS.items(): + script_name = entrypoint.replace(".py", "") + script_human_readable_name = script_name.replace("_", " ").title() + + # Create the script + entrypoint_fullname = str((this_dir / entrypoint).absolute()) + script = f'Python.ExecuteFile @"{entrypoint_fullname}"' + rt.macros.new( + "SVL_Tools", script_name, tooltip, script_human_readable_name, script + ) + + # Check if it already exists + existing_menu_items_with_name = [ + x + for x in range(subMenu.numItems()) + if subMenu.getItem(x + 1).getTitle() == script_human_readable_name + ] + if existing_menu_items_with_name: + for i in reversed(existing_menu_items_with_name): + print("Removing existing menu item at position", i + 1) + subMenu.removeItemByPosition(i + 1) + + # Create a menu item that calls the sample macroScript + actionItem = rt.menuMan.createActionItem(script_name, "SVL_Tools") + assert actionItem, "Failed to create action item " + script_human_readable_name + # Add the item to the menu + subMenu.addItem(actionItem, -1) + + # Redraw the menu bar with the new item + rt.menuMan.updateMenuBar() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/add_fillable_seed.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/add_fillable_seed.py new file mode 100644 index 0000000000000000000000000000000000000000..ec15dbd36d757f1949cd1861c0231170cd877ad9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/add_fillable_seed.py @@ -0,0 +1,110 @@ +import pymxs + +rt = pymxs.runtime + +import numpy as np +import networkx as nx + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name + + +def add_fillable_seed(): + # Assert that the currently selected object is a seed point + assert len(rt.selection) == 1, "Expected exactly one object to be selected" + (target_obj,) = rt.selection + + # Some checks about the target object + parsed_name = parse_name(target_obj.name) + assert parsed_name, "Failed to parse the name of the target object" + assert not parsed_name.group("bad"), "Expected the target object to not be bad" + assert ( + parsed_name.group("instance_id") == "0" + ), "Expected the target object to be the 0 instance" + assert not parsed_name.group( + "meta_type" + ), "Expected the target object to not have a meta type" + assert ( + parsed_name.group("joint_side") != "upper" + ), "Expected the target object to not be an upper joint" + target_link_name = parsed_name.group("link_name") or "base_link" + + # Browse the entire scene to find the articulation tree of the target object + articulation_tree = nx.DiGraph() + link_objs = {} + for obj in rt.objects: + candidate_parsed_name = parse_name(obj.name) + if not candidate_parsed_name: + continue + if candidate_parsed_name.group("model_id") != parsed_name.group("model_id"): + continue + if candidate_parsed_name.group("instance_id") != parsed_name.group( + "instance_id" + ): + continue + if candidate_parsed_name.group("bad"): + continue + if candidate_parsed_name.group("meta_type"): + continue + if candidate_parsed_name.group("joint_side") == "upper": + continue + if candidate_parsed_name.group("light_id"): + continue + link_name = candidate_parsed_name.group("link_name") or "base_link" + + # Assert that it has a collision mesh + collision_mesh_objects = [] + for child in obj.children: + if rt.classOf(child) == rt.Editable_Poly and "Mcollision" in child.name: + collision_mesh_objects.append(child) + assert ( + len(collision_mesh_objects) == 1 + ), f"Expected {obj.name} to have exactly one collision mesh" + collision_mesh_object = collision_mesh_objects[0] + + # Add it into the graph + articulation_tree.add_node(link_name) + link_objs[link_name] = collision_mesh_object + if link_name != "base_link": + parent_link_name = candidate_parsed_name.group("parent_link_name") + articulation_tree.add_edge(parent_link_name, link_name) + + # Get all the descendants of the target link. These will be used when computing the fillable volume + links_to_include = set(nx.descendants(articulation_tree, target_link_name)) | { + target_link_name + } + collision_mesh_objects_to_include = [ + link_objs[link_name] for link_name in links_to_include + ] + + # Get the bounding box + vert_sets = np.concatenate( + [ + np.array( + [ + rt.polyop.getVert(node, i + 1) + for i in range(rt.polyop.GetNumVerts(node)) + ], + dtype=np.float64, + ) + for node in collision_mesh_objects_to_include + ], + axis=0, + ) + bb_min = np.min(vert_sets, axis=0) + bb_max = np.max(vert_sets, axis=0) + bb_center = (bb_min + bb_max) / 2 + + # Create the point + seed = rt.Point() + seed.name = "fillable_seed" + seed.rotation = target_obj.rotation + seed.position = rt.Point3(*bb_center.tolist()) + seed.parent = target_obj + + +if __name__ == "__main__": + add_fillable_seed() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/align_pivots.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/align_pivots.py new file mode 100644 index 0000000000000000000000000000000000000000..b889d697a974f036d5c05d6b90faeee2604d65fd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/align_pivots.py @@ -0,0 +1,84 @@ +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +rt = pymxs.runtime +local_coordsys = pymxs.runtime.Name("local") + + +def align_pivots(): + src_obj = rt.pickobject() + # Center pivot to object + src_obj.pivot = src_obj.center + src_pc = np.array( + rt.polyop.getVerts( + src_obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(src_obj)) + ) + ) + old_src_quat = [ + src_obj.rotation.x, + src_obj.rotation.y, + src_obj.rotation.z, + src_obj.rotation.w, + ] + old_src_R = R.from_quat(old_src_quat) + + for tgt_obj in rt.selection: + # Center pivot to object + tgt_obj.pivot = tgt_obj.center + tgt_pc = np.array( + rt.polyop.getVerts( + tgt_obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(tgt_obj)) + ) + ) + assert ( + src_pc.shape == tgt_pc.shape + ), "source object ({}) and target object ({}) are not instances of each other - they have different number of vertices.".format( + src_obj.name, tgt_obj.name + ) + + r = R.align_vectors( + tgt_pc - np.mean(tgt_pc, axis=0), + src_pc - np.mean(src_pc, axis=0), + )[0] + + new_rotation = r * old_src_R # desired orientation in the world frame + + old_target_quat = [ + tgt_obj.rotation.x, + tgt_obj.rotation.y, + tgt_obj.rotation.z, + tgt_obj.rotation.w, + ] + old_target_R = R.from_quat(old_target_quat) + + new_rotation_local = ( + old_target_R.inv() * new_rotation + ) # desired orientation in the local frame of the target object + delta_quat = rt.quat(*new_rotation_local.as_quat().tolist()) + + coordsys = getattr(pymxs.runtime, "%coordsys_context") + prev_coordsys = coordsys(local_coordsys, None) + tgt_obj.rotation *= delta_quat + tgt_obj.objectOffsetRot *= delta_quat + tgt_obj.objectOffsetPos *= delta_quat + coordsys(prev_coordsys, None) + + +def align_pivots_button(): + try: + align_pivots() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Align pivots complete - no errors found!") + + +if __name__ == "__main__": + align_pivots_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/apply_qa_fixes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/apply_qa_fixes.py new file mode 100644 index 0000000000000000000000000000000000000000..5658666a1225bbf2fb1e4e484f8d6098d1fb0a5a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/apply_qa_fixes.py @@ -0,0 +1,176 @@ +from collections import defaultdict +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pathlib +import json + +import pymxs +from scipy.spatial.transform import Rotation as R +import numpy as np + +import b1k_pipeline.utils + +rt = pymxs.runtime +local_coordsys = pymxs.runtime.Name("local") +parent_coordsys = pymxs.runtime.Name("parent") + + +def rotate_pivot(tgt_obj, delta_rot_local): + # Unparent all of the children + children = list(tgt_obj.children) + for child in children: + child.parent = None + + delta_quat = rt.quat(*delta_rot_local.as_quat().tolist()) + coordsys = getattr(pymxs.runtime, "%coordsys_context") + prev_coordsys = coordsys(local_coordsys, None) + tgt_obj.rotation *= delta_quat + tgt_obj.objectOffsetRot *= delta_quat + tgt_obj.objectOffsetPos *= delta_quat + coordsys(prev_coordsys, None) + + # Reparent the children + for child in children: + child.parent = tgt_obj + + +def scale_pivot(tgt_obj, delta_scale): + # Update the object offset of the original + print(tgt_obj.name, tgt_obj.position, delta_scale) + coordsys = getattr(pymxs.runtime, "%coordsys_context") + prev_coordsys = coordsys(parent_coordsys, None) + tgt_obj.position *= delta_scale + tgt_obj.objectOffsetPos *= delta_scale + if rt.classOf(tgt_obj) != rt.Point: + tgt_obj.objectOffsetScale *= delta_scale + coordsys(prev_coordsys, None) + + # Recurse through the children + for c in tgt_obj.children: + scale_pivot(c, delta_scale) + + +def apply_qa_fixes_in_open_file(apply_scale=True, apply_orientation=True): + # Load the fixes + fixes = defaultdict(dict) + with open( + r"D:\BEHAVIOR-1K\asset_pipeline\metadata\orientation_and_scale_edits.json" + ) as f: + data = json.load(f) + for model, orientation in data["orientations"].items(): + if not np.allclose(orientation, [0, 0, 0, 1], atol=1e-3): + fixes[model]["orientation"] = orientation + for model, scale in data["scales"].items(): + if not np.allclose(scale, [1, 1, 1], atol=1e-3): + assert np.allclose( + scale, scale[0], atol=1e-3 + ), "Non-uniform scale not supported." + fixes[model]["scale"] = scale[0] + + # Prior to starting, let's get the minimum y value and add a bit of margin to it. This is + # where we'll put our rescaled objects. + bboxes = [] + for node in rt.objects: + bbox_min, bbox_max = rt.NodeGetBoundingBox(node, rt.Matrix3(1)) + bboxes.extend([np.array(bbox_min), np.array(bbox_max)]) + bboxes = np.array(bboxes) + max_y = np.max(bboxes[:, 1]) + + # Go through all objects and apply rotation fix if they are the base link and not a metalink + objects_by_model_and_id = defaultdict(list) + base_links_by_model_and_id = {} + + # Make a pass for orientations + for obj in rt.objects: + pn = b1k_pipeline.utils.parse_name(obj.name) + if not pn: + continue + + # If there are no fixes for this model, we can continue + model_id = pn.group("model_id") + if model_id not in fixes: + continue + model_fixes = fixes[model_id] + + # If this is a meta link, continue + if pn.group("meta_type"): + continue + + print("Applying fixes to", obj.name) + + # Apply orientation fixes (the pivot needs to be rotated by the inverse of the fix) + # Note that child links also get their pivots rotated here. Is that good? idk. + # But we definitely don't want to rotate lights. + if ( + apply_orientation + and "orientation" in model_fixes + and rt.ClassOf(obj) == rt.Editable_Poly + ): + rotate_pivot(obj, R.from_quat(model_fixes["orientation"]).inv()) + + # Record the object for possible scale fixes. We're doing this only for root-level + # objects. We will reparent these objects for the process of applying scale fixes. + if "scale" in model_fixes and not obj.parent: + is_base_link = pn.group("link_name") in (None, "", "base_link") + key = (model_id, pn.group("instance_id")) + if is_base_link: + base_links_by_model_and_id[key] = obj + else: + objects_by_model_and_id[key].append(obj) + + # Make a pass for scales, only for object files + if apply_scale and "objects" in pathlib.Path(rt.maxFilePath).parts: + # Assert that all children have bases + assert set(base_links_by_model_and_id.keys()).issuperset( + set(objects_by_model_and_id.keys()) + ), "Not all objects have base links." + + # Go through the base links + current_x = 0 + align_y = max_y + 1000.0 + for key, base_link in base_links_by_model_and_id.items(): + # If there are links, temporarily parent them under the base link + children = ( + objects_by_model_and_id[key] if key in objects_by_model_and_id else [] + ) + for child in children: + child.parent = base_link + + # Apply scale fixes for the base link + scale_fix = fixes[key[0]]["scale"] + print("Applying scale fix to object", key, scale_fix) + scale_pivot(base_link, scale_fix) + + # If the scale is greater than 1, let's move the object to be safe + if scale_fix > 1: + # Get the current guy's bbox + bbox_min, bbox_max = rt.NodeGetBoundingBox(base_link, rt.Matrix3(1)) + bbox_min = np.array(bbox_min) + bbox_max = np.array(bbox_max) + bbox_extent = bbox_max - bbox_min + bbox_center = (bbox_max + bbox_min) / 2 + base_link_wrt_bbox = np.array(base_link.position) - bbox_center + + # Lay out the bbox + bbox_center_goal_position = np.array( + [ + current_x + bbox_extent[0] / 2, + align_y + bbox_extent[1] / 2, + bbox_extent[2] / 2, + ] + ) + base_link_goal_position = bbox_center_goal_position + base_link_wrt_bbox + base_link.position = rt.Point3(*base_link_goal_position.tolist()) + + # Move the current x + current_x += bbox_extent[0] + 1000.0 + + # Unparent all of the children + for child in children: + child.parent = None + + +if __name__ == "__main__": + apply_qa_fixes_in_open_file() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/assign_light.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/assign_light.py new file mode 100644 index 0000000000000000000000000000000000000000..68f304267ae1acfe30e8eeb43340709a538e767c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/assign_light.py @@ -0,0 +1,39 @@ +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +rt = pymxs.runtime + + +def assign_light(): + physical_light = rt.pickobject() + + assert ( + len(rt.selection) == 1 + ), "You have to assign light one at a time - Select light first, then click this button, then select the physical light object." + + light = rt.selection[0] + + existing_lights = [ + obj for obj in rt.objects if physical_light.name + "-L" in obj.name + ] + light.name = physical_light.name + "-L{}".format(len(existing_lights)) + + +def assign_light_button(): + try: + assign_light() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Assign light complete - no errors found!") + + +if __name__ == "__main__": + assign_light_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/assign_toggle.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/assign_toggle.py new file mode 100644 index 0000000000000000000000000000000000000000..ab695fdff16baf968eda5d1f580ee5da04d1e126 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/assign_toggle.py @@ -0,0 +1,43 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +from b1k_pipeline.utils import parse_name + +rt = pymxs.runtime + + +def assign_toggle(): + target = rt.pickobject() + + assert ( + len(rt.selection) == 1 + ), "You have to assign toggle button one at a time - Select toggle button first, then click this button, then select the target object." + + button = rt.selection[0] + + # Parent the collision object to the target object + button.parent = target + + # Rename the first object to match the selected object + button.name = target.name + "-Mtogglebutton" + + # Validate that the object name is valid + assert ( + parse_name(button.name) is not None + ), f"Done, but please fix invalid name {button.name} for collision object" + + +def assign_toggle_button(): + try: + assign_toggle() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + assign_toggle_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/category_qa.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/category_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa6c4eb3fe6aac5b12d71c798fa11e5a12062bc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/category_qa.py @@ -0,0 +1,103 @@ +import csv +import json +import os +import sys +import textwrap + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +import nltk + +nltk.download("wordnet") +nltk.download("omw-1.4") +from nltk.corpus import wordnet as wn + +from b1k_pipeline.utils import parse_name, PIPELINE_ROOT + +IGNORE_CATEGORIES = {"walls", "floors", "ceilings"} + +PASS_NAME = "benjamin-scene-looseness-category" +RECORD_PATH = PIPELINE_ROOT / "qa-logs" / f"{PASS_NAME}.json" + + +def main(): + # Read completed groups record + completed_groups = set() + if os.path.exists(RECORD_PATH): + with open(RECORD_PATH) as f: + completed_groups = set(json.load(f)) + + # Find incomplete groups + parsed_names = [parse_name(x.name) for x in rt.objects] + available_groups = { + x.group("category") + for x in parsed_names + if x is not None + and int(x.group("instance_id")) == 0 + and x.group("category") not in IGNORE_CATEGORIES + } + remaining_groups = sorted(available_groups - completed_groups) + if not remaining_groups: + rt.messageBox("Scene complete.") + return + + # Find objects corresponding to the next remaining group's instance zero + next_group = remaining_groups[0] + next_group_objects = [] + has_loose = False + has_fixed = False + has_clutter = False + for obj in rt.objects: + n = parse_name(obj.name) + if n is None: + continue + if int(n.group("instance_id")) != 0: + continue + if n.group("category") != next_group: + continue + next_group_objects.append(obj) + obj.isHidden = False + if n.group("loose") == "L-": + has_loose = True + elif n.group("loose") == "C-": + has_clutter = True + else: + has_fixed = True + + # Select that object and print + rt.select(next_group_objects) + rt.IsolateSelection.EnterIsolateSelectionMode() + rt.execute("max tool zoomextents") + print( + f"{len(available_groups) - len(remaining_groups) + 1} / {len(available_groups)}: {next_group}" + ) + + if has_loose and not has_fixed and not has_clutter: + print("Used as loose") + elif has_fixed and not has_loose and not has_clutter: + print("Used as fixed") + elif has_clutter and not has_loose and not has_fixed: + print("Used as clutter") + else: + print( + textwrap.fill( + f"Used as loose: {has_loose}. Used as fixed: {has_fixed}. Used as clutter: {has_clutter}" + ) + ) + + # Show a popup with the synset info + # category_name = next_group.split("-")[0] + # synset_name, synset_desc = get_synset(category_name) + # print(textwrap.fill(f"Category {category_name} is currently mapped to synset {synset_name} ({synset_desc})")) + + # Record that object as completed + with open(RECORD_PATH, "w") as f: + json.dump(list(completed_groups | {next_group}), f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/check_collisions.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/check_collisions.py new file mode 100644 index 0000000000000000000000000000000000000000..0f73157b02b0df9601c16c2e84ff69cf6b53b392 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/check_collisions.py @@ -0,0 +1,504 @@ +from collections import defaultdict +import json +import pathlib +import re +import sys +import traceback + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +from b1k_pipeline.utils import mat2arr, parse_name, PIPELINE_ROOT + +import networkx as nx +import numpy as np +import tqdm +import trimesh + +MINIMUM_COLLISION_DEPTH_METERS = 0.01 # 1cm of collision +MINIMUM_COLLISION_DEPTH_METERS_SENSITIVE = 0 # any collision +DEBUG_COLLISION_ROOT = PIPELINE_ROOT / "tmp" / "debug_collision" + +inventory_path = PIPELINE_ROOT / "artifacts" / "pipeline" / "object_inventory.json" +with open(inventory_path, "r") as f: + providers = {k.split("-")[-1]: v for k, v in json.load(f)["providers"].items()} + + +def get_collision_meshes_relative_to_base(obj, base_transform): + # Assert that collision meshes do not share instances in the scene + assert not [ + x for x in rt.objects if x.baseObject == obj.baseObject and x != obj + ], f"{obj.name} should not have instances." + + world_to_base = rt.inverse(base_transform) + + # Get vertices and faces into numpy arrays for conversion + verts = np.array( + [ + rt.polyop.getVert(obj, i + 1) * world_to_base + for i in range(rt.polyop.GetNumVerts(obj)) + ] + ) + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + # Split the faces into elements + elems = { + tuple(rt.polyop.GetElementsUsingFace(obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(obj)) + } + assert len(elems) <= 40, f"{obj.name} should not have more than 32 elements." + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + # Iterate through the elements + meshes = [] + for i, elem in enumerate(elems): + # Load the mesh into trimesh and assert convexity + relevant_faces = faces[elem] + m = trimesh.Trimesh(vertices=verts, faces=relevant_faces, process=False) + m.remove_unreferenced_vertices() + assert m.is_volume, f"{obj.name} element {i} is not a volume" + # assert m.is_convex, f"{obj.name} element {i} is not convex" + assert ( + len(m.split()) == 1 + ), f"{obj.name} element {i} has elements trimesh still finds splittable" + + # Add the mesh to the list + meshes.append(m) + + return meshes + + +def import_bad_model_originals(model_id): + # Get the provider file + provider = providers[model_id] + filename = str(PIPELINE_ROOT / "cad" / provider / "processed.max") + + # Get the right object names from the file + f_objects = rt.getMAXFileObjectNames(filename, quiet=True) + visual_objects = {} + collision_objects = {} + for obj in f_objects: + m = parse_name(obj) + if not m: + continue + if ( + m.group("model_id") != model_id + or m.group("instance_id") != "0" + or m.group("joint_side") == "upper" + ): + continue + + # We have no way of checking if the object is an editable poly so we just apply some heuristics + if m.group("meta_type") and m.group("meta_type") != "collision": + continue + if m.group("light_id"): + continue + + # If we get here this is a lower link of an instance zero + assert not m.group("bad"), "Bad objects should not be in the inventory" + + link_name = m.group("link_name") if m.group("link_name") else "base_link" + if "Mcollision" in obj: + collision_objects[link_name] = obj + else: + visual_objects[link_name] = obj + + assert set(visual_objects.keys()) == set( + collision_objects.keys() + ), f"Visual and collision objects should match in source for {model_id}. Currently: {visual_objects.keys()} vs {collision_objects.keys()}" + + objects_to_import = sorted( + set(visual_objects.values()) | set(collision_objects.values()) + ) + + success, imported_meshes = rt.mergeMaxFile( + filename, + objects_to_import, + rt.Name("select"), + rt.Name("autoRenameDups"), + rt.Name("useSceneMtlDups"), + rt.Name("neverReparent"), + rt.Name("noRedraw"), + quiet=True, + mergedNodes=pymxs.byref(None), + ) + assert success, f"Failed to import {model_id}." + imported_objs_by_name = {obj.name: obj for obj in imported_meshes} + assert set(objects_to_import) == set( + imported_objs_by_name.keys() + ), "Not all objects were imported. Missing: " + str( + set(objects_to_import) - set(imported_objs_by_name.keys()) + ) + + # Make sure the objects all have the right parents + for link_name in visual_objects.keys(): + visual_obj = imported_objs_by_name[visual_objects[link_name]] + collision_obj = imported_objs_by_name[collision_objects[link_name]] + assert visual_obj.parent == None, "Visual objects should not have parents" + assert ( + collision_obj.parent == visual_obj + ), "Collision objects should be children of visual objects" + + return imported_meshes + + +def prepare_scene(use_clutter=False): + # Get all the collision meshes in the scene that belong to lower, instance-zero meshes + scene = trimesh.Scene() + + # Get a list of all exportable objects + all_objects = list(rt.objects) + + # Pre-import meshes for all bad objects + bad_object_model_ids = set() + for obj in all_objects: + parsed_name = parse_name(obj.name) + if not parsed_name or not parsed_name.group("bad"): + continue + bad_object_model_ids.add(parsed_name.group("model_id")) + imported_bad_models = [] + for model_id in tqdm.tqdm(bad_object_model_ids, desc="Importing bad models"): + imported_bad_models.extend(import_bad_model_originals(model_id)) + + # Get the base link frame for each model + base_link_frames = {} + categories_by_model_id = {} + for obj in tqdm.tqdm(all_objects, desc="Getting base link frames"): + parsed_name = parse_name(obj.name) + if not parsed_name: + continue + + if parsed_name.group("model_id") not in categories_by_model_id: + categories_by_model_id[parsed_name.group("model_id")] = parsed_name.group( + "category" + ) + assert ( + parsed_name.group("category") + == categories_by_model_id[parsed_name.group("model_id")] + ), f"{parsed_name.group('model_id')} has different categories: {parsed_name.group('category')} vs {categories_by_model_id[parsed_name.group('model_id')]}." + + if int(parsed_name.group("instance_id")) != 0: + continue + + if parsed_name.group("bad"): + continue + + if ( + parsed_name.group("link_name") + and parsed_name.group("link_name") != "base_link" + ): + continue + + if parsed_name.group("meta_type"): + continue + + if rt.classOf(obj) != rt.Editable_Poly: + continue + + model_id = parsed_name.group("model_id") + assert model_id not in base_link_frames, f"{model_id} already exists" + base_link_frames[model_id] = obj.transform + + # Process the collision meshes into a base-relative dictionary + meshes = defaultdict(dict) # meshes[model_id][link_name] = [trimesh.Trimesh] + collision_objs = [x for x in all_objects if "Mcollision" in x.name] + for obj in tqdm.tqdm(collision_objs, desc="Processing collision meshes"): + if "Mcollision" not in obj.name: + continue + + # Get some information about the parent + parent = obj.parent + if parent is None: + continue + + parsed_name = parse_name(parent.name) + if not parsed_name: + continue + + if parsed_name.group("bad") or int(parsed_name.group("instance_id")) != 0: + continue + + # Record the meshes + link_name = ( + parsed_name.group("link_name") + if parsed_name.group("link_name") + else "base_link" + ) + model_id = parsed_name.group("model_id") + assert ( + link_name not in meshes[model_id] + ), f"{link_name} already exists in {model_id}" + meshes[model_id][link_name] = get_collision_meshes_relative_to_base( + obj, base_link_frames[model_id] + ) + + # Remove any bad models that were imported + for obj in imported_bad_models: + rt.delete(obj) + + # Then go through every other object in the scene and add it onto the physics scene + for obj in tqdm.tqdm(all_objects, desc="Building physics scene"): + if rt.classOf(obj) != rt.Editable_Poly: + continue + + parsed_name = parse_name(obj.name) + if not parsed_name: + continue + + if "Mcollision" in obj.name: + continue + + # For now, skip clutter + loose_key = parsed_name.group("loose") + if loose_key and "C" in loose_key and not use_clutter: + continue + + # Only use the base link to get everything else's position + if ( + parsed_name.group("link_name") + and parsed_name.group("link_name") != "base_link" + ): + continue + + is_loose = "true" if loose_key else "false" + model_id = parsed_name.group("model_id") + category = categories_by_model_id[model_id] + instance_id = parsed_name.group("instance_id") + obj_transform = np.hstack([mat2arr(obj.transform), [[0], [0], [0], [1]]]).T + + # Actually add the meshes + for link_name, link_meshes in meshes[model_id].items(): + for mesh_idx, link_mesh in enumerate(link_meshes): + node_key = f"{category}-{model_id}-{instance_id}-{link_name}-{mesh_idx}-{is_loose}" + scene.add_geometry( + link_mesh, node_name=node_key, transform=obj_transform + ) + + return scene + + +def _safe_filename_part(value): + return re.sub(r"[^A-Za-z0-9_.-]+", "_", value)[:120] + + +def prepare_debug_collision_dir(): + debug_collision_dir = DEBUG_COLLISION_ROOT / pathlib.Path(rt.maxFilePath).name + debug_collision_dir.mkdir(parents=True, exist_ok=True) + for debug_file in debug_collision_dir.glob("*.ply"): + debug_file.unlink() + return debug_collision_dir + + +def export_debug_collision_pair( + scene, left_info, right_info, depth, debug_collision_dir, collision_idx +): + meshes = [] + for info, color in ( + (left_info, [255, 64, 64, 255]), + (right_info, [64, 128, 255, 255]), + ): + transform, geometry_name = scene.graph.get(info["node"]) + mesh = scene.geometry[geometry_name].copy() + mesh.apply_transform(transform) + mesh.visual.vertex_colors = np.tile(color, (len(mesh.vertices), 1)) + meshes.append(mesh) + + filename = ( + f"{collision_idx:04d}_" + f"{depth:.3f}mm_" + f"{_safe_filename_part(left_info['node'])}__" + f"{_safe_filename_part(right_info['node'])}.ply" + ) + output_path = debug_collision_dir / filename + trimesh.util.concatenate(meshes).export(output_path) + return str(output_path.relative_to(PIPELINE_ROOT)) + + +def check_collisions(scene, debug_collision_dir): + cm, _ = trimesh.collision.scene_to_collision(scene) + _, collision_data = cm.in_collision_internal(return_data=True) + + # Then go through every object in the scene and find out which links can be reached from the base_link + # using only fixed links + graphs_by_model = defaultdict(nx.Graph) + for obj in tqdm.tqdm(list(rt.objects), desc="Building link graphs"): + parsed_name = parse_name(obj.name) + if not parsed_name: + continue + + if int(parsed_name.group("instance_id")) != 0: + continue + + model_id = parsed_name.group("model_id") + this_link = ( + parsed_name.group("link_name") + if parsed_name.group("link_name") + else "base_link" + ) + graphs_by_model[model_id].add_node(this_link) + + parent_link = parsed_name.group("parent_link_name") + joint_type = parsed_name.group("joint_type") + if parent_link and joint_type == "F": + graphs_by_model[model_id].add_edge(parent_link, this_link) + + links_fixed_to_base = { + model_id: set(nx.dfs_tree(graph, "base_link").nodes) + for model_id, graph in graphs_by_model.items() + } + + def parse_collision_node(node_name): + category, model, instance, link, body, loose = node_name.split("-") + return { + "category": category, + "model": model, + "instance": instance, + "link": link, + "body": body, + "loose": loose == "true", + "node": node_name, + } + + pairs_collision = {} + for collision in tqdm.tqdm(collision_data, desc="Filtering collisions"): + left, right = sorted( + tuple(collision.names) + ) # Sorting here gives deterministic category ordering + left_info = parse_collision_node(left) + right_info = parse_collision_node(right) + left_category = left_info["category"] + left_model = left_info["model"] + left_instance = left_info["instance"] + left_link = left_info["link"] + left_loose = left_info["loose"] + right_category = right_info["category"] + right_model = right_info["model"] + right_instance = right_info["instance"] + right_link = right_info["link"] + right_loose = right_info["loose"] + + # Exclude self-collisions + if left_model == right_model and left_instance == right_instance: + continue + + # Exclude collisions between fixed links of two fixed objects + left_fixed_link = left_link in links_fixed_to_base[left_model] + right_fixed_link = right_link in links_fixed_to_base[right_model] + if not left_loose and not right_loose: + if left_fixed_link and right_fixed_link: + continue + + # Exclude collisions between walls and sliding doors + if left_category == "sliding_door" and right_category == "walls": + continue + + # Decide what the depth limit is. We are especially sensitive to collisions between moving + # links of fixed objects and other fixed objects, so we set a lower threshold for those. + depth_threshold = MINIMUM_COLLISION_DEPTH_METERS + is_left_moving_part_of_fixed_obj = not left_loose and not left_fixed_link + is_right_moving_part_of_fixed_obj = not right_loose and not right_fixed_link + if is_left_moving_part_of_fixed_obj or is_right_moving_part_of_fixed_obj: + depth_threshold = MINIMUM_COLLISION_DEPTH_METERS_SENSITIVE + + # Print the collision + depth = float(collision.depth) + if depth < depth_threshold * 1000: + continue + + pair = tuple( + sorted( + [ + (left_category, left_model, left_instance), + (right_category, right_model, right_instance), + ] + ) + ) + if pair not in pairs_collision: + pairs_collision[pair] = { + "left": left_info, + "right": right_info, + "objects": pair, + "depth": depth, + } + elif depth > pairs_collision[pair]["depth"]: + pairs_collision[pair] = { + "left": left_info, + "right": right_info, + "objects": pair, + "depth": depth, + } + + collisions = [pairs_collision[pair] for pair in sorted(pairs_collision)] + for collision_idx, collision in enumerate(collisions): + collision["debug_ply"] = export_debug_collision_pair( + scene, + collision["left"], + collision["right"], + collision["depth"], + debug_collision_dir, + collision_idx, + ) + + return collisions + + +def main(): + opts = rt.maxops.mxsCmdLineArgs + use_clutter = opts[rt.name("clutter")] == "true" + + scene = None + error = None + collisions = [] + try: + scene = prepare_scene(use_clutter=use_clutter) + scene.export(r"D:\physics.ply") + debug_collision_dir = prepare_debug_collision_dir() + collisions = check_collisions(scene, debug_collision_dir) + for collision in collisions: + left = collision["left"] + right = collision["right"] + depth = collision["depth"] + print( + f"Collision between {left['node']} and {right['node']}: {depth} mm" + ) + except Exception: + raise + # error = traceback.format_exc() + # traceback.print_exc() + + output_dir = pathlib.Path(rt.maxFilePath) / "artifacts" + output_dir.mkdir(parents=True, exist_ok=True) + + filename = output_dir / ( + "check_collisions.json" + if not use_clutter + else "check_collisions_with_clutter.json" + ) + results = { + "success": not error and len(collisions) == 0, + "collisions": collisions, + "error": error, + } + print(results) + with open(filename, "w") as f: + json.dump(results, f, indent=4) + + return scene + + +if __name__ == "__main__": + scene = main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/cloneandalign.mcr b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/cloneandalign.mcr new file mode 100644 index 0000000000000000000000000000000000000000..5fb6174c61f876ad552e478081498d0175b236bd --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/cloneandalign.mcr @@ -0,0 +1,22 @@ +macroScript cloneandalign Buttontext: "Clone and Align" category: "SVL-Tools" +( + + On isEnabled do --the script will not be available if no objects are selected + ( + selection.count > 0 + )--end on isenabled + + On Execute do + ( + undo on --Undo the operation done using the script + ( + local source_obj = pickobject() + for target_obj in selection do + ( + maxOps.cloneNodes source_obj cloneType:#instance newNodes:&new_obj #nodialog + new_obj.transform = target_obj.transform + new_obj.scale = target_obj.scale + ) + )--end undo on + )--end on execute +)--end macroscript \ No newline at end of file diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/collision_vertex_reduction.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/collision_vertex_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..10f1c6d5b4bdb6cdb6a75e9d1085d9b933f5b2ef --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/collision_vertex_reduction.py @@ -0,0 +1,169 @@ +import trimesh +import numpy as np + +import pymxs + +rt = pymxs.runtime + +MAX_VERTEX_COUNT = 60 +REDUCTION_STEP = 5 + + +def reduce_mesh(mesh): + # Check its vertex count and reduce as necessary + reduction_target_vertex_count = MAX_VERTEX_COUNT + REDUCTION_STEP + reduced_mesh = mesh + while len(reduced_mesh.vertices) > MAX_VERTEX_COUNT: + # Reduction function takes a number of faces as its input. We estimate this, if it doesn't + # work out, we keep trying with a smaller estimate. + reduction_target_vertex_count -= REDUCTION_STEP + if reduction_target_vertex_count < MAX_VERTEX_COUNT / 2: + # Don't want to reduce too far + raise ValueError("Vertex reduction failed.") + + reduction_target_face_count = int( + reduction_target_vertex_count / len(mesh.vertices) * len(mesh.faces) + ) + reduced_mesh = mesh.simplify_quadratic_decimation(reduction_target_face_count) + + return reduced_mesh.convex_hull + + +def convert_to_trimesh(obj, checks=True): + # Get vertices and faces into numpy arrays for conversion + verts = np.array( + [rt.polyop.getVert(obj, i + 1) for i in range(rt.polyop.GetNumVerts(obj))] + ) + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + # Split the faces into elements + elems = { + tuple(rt.polyop.GetElementsUsingFace(obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(obj)) + } + # assert len(elems) <= 40, f"{obj.name} should not have more than 40 elements." + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + # Iterate through the elements + meshes = [] + for i, elem in enumerate(elems): + # Load the mesh into trimesh and assert convexity + relevant_faces = faces[elem] + m = trimesh.Trimesh(vertices=verts, faces=relevant_faces, process=False) + m.remove_unreferenced_vertices() + assert not checks or m.is_volume, f"{obj.name} element {i} is not a volume" + # assert not checks or m.is_convex, f"{obj.name} element {i} is not convex" + assert ( + not checks or len(m.split()) == 1 + ), f"{obj.name} element {i} has elements trimesh still finds splittable" + meshes.append(m) + + return meshes + + +def process_convex_obj(obj, force=False): + # Get the collision meshes into a set of trimeshes + convex_meshes = convert_to_trimesh(obj, checks=False) + + # Check if any of the meshes have too many verts + too_many_verts = any(len(m.vertices) > MAX_VERTEX_COUNT for m in convex_meshes) + + # Check if any of the meshes is not a volume + not_volume = any(not m.is_volume for m in convex_meshes) + + # Check if any of the meshes is nonconvex + not_convex = any(m.volume / m.convex_hull.volume < 0.99 for m in convex_meshes) + + if not force and not too_many_verts and not not_volume and not not_convex: + return + + print("Reducing", obj.name) + + # Individually reduce each of the trimeshes. This has multiple effects: it will reduce the vertices + # if the vertex count is too high, and replace the shape with its convex hull helping with the volumeness + # issues. + reduced_trimeshes = [reduce_mesh(m) for m in convex_meshes] + assert all( + m.is_volume for m in reduced_trimeshes + ), f"{obj.name} reduced part is not a volume. Not quite sure how that can be." + + # Get a flattened list of vertices and faces + all_vertices = [] + all_faces = [] + for split in reduced_trimeshes: + vertices = [rt.Point3(*v.tolist()) for v in split.vertices] + # Offsetting here by the past vertex count + faces = [[v + len(all_vertices) + 1 for v in f.tolist()] for f in split.faces] + all_vertices.extend(vertices) + all_faces.extend(faces) + + # Remove the original mesh + rt.polyop.deleteVerts(obj, rt.execute("#{1..%d}" % rt.polyop.GetNumVerts(obj))) + + # Add the vertices + for v in all_vertices: + rt.polyop.createVert(obj, v) + + # Add the faces + for f in all_faces: + rt.polyop.createPolygon(obj, f) + + # Update the mesh to reflect changes + rt.update(obj) + + # Check that the new element count is the same as the split count + elems = { + tuple(rt.polyop.GetElementsUsingFace(obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(obj)) + } + assert len(elems) == len( + convex_meshes + ), f"{obj.name} has different number of elements in input vs output" + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + # Convert back to trimesh this time with checks to check volumeness, convexness, etc. + # convert_to_trimesh(obj, checks=True) + + +def process_all_convex_meshes(objs=None): + if objs is None: + objs = list(rt.objects) + for obj in objs: + if ( + "Mcollision" not in obj.name + and "Mfillable" not in obj.name + and "Mopenfillable" not in obj.name + ): + continue + + process_convex_obj(obj) + + +def main(): + for obj in rt.selection: + assert ( + "Mcollision" in obj.name + or "Mfillable" in obj.name + or "Mopenfillable" in obj.name + ), "Please select a collision or fillable object" + process_convex_obj(obj, force=True) + + # process_all_convex_meshes() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/convex_decomposition.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/convex_decomposition.py new file mode 100644 index 0000000000000000000000000000000000000000..33cbe0bdba78ffffc94c533a3ee9b50151b2653d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/convex_decomposition.py @@ -0,0 +1,261 @@ +import numpy as np +import coacd +import trimesh +import subprocess + +import pymxs + +rt = pymxs.runtime + +import os +import sys +import tempfile + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name +from b1k_pipeline.max.collision_vertex_reduction import reduce_mesh + +VHACD_EXECUTABLE = r"D:\BEHAVIOR-1K\asset_pipeline\b1k_pipeline\vhacd2.exe" + + +def run_coacd(input_mesh, hull_count): + coacd_mesh = coacd.Mesh(input_mesh.vertices, input_mesh.faces) + result = coacd.run_coacd( + coacd_mesh, + max_convex_hull=hull_count, + ) + output_meshes = [] + for vertices, faces in result: + output_trimesh = trimesh.Trimesh(vertices=vertices, faces=faces) + output_meshes.append(output_trimesh) + return output_meshes + + +def run_vhacd(input_mesh, hull_count): + with tempfile.TemporaryDirectory() as td: + in_path = os.path.join(td, "in.obj") + out_path = os.path.join( + td, "decomp.obj" + ) # This is the path that VHACD outputs to. + input_mesh.export(in_path) + + vhacd_cmd = [ + str(VHACD_EXECUTABLE), + in_path, + "-r", + "1000000", + "-d", + "20", + "-f", + "flood", + "-e", + "0.01", + "-p", + "true", + "-l", + "2", + "-v", + "60", + "-h", + str(hull_count), + ] + try: + proc = subprocess.run( + vhacd_cmd, + shell=False, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=td, + check=True, + ) + if not os.path.exists(out_path): + raise ValueError( + "VHACD failed to produce an output file. VHACD output:\n" + + proc.stdout.decode("utf-8") + ) + out_mesh = trimesh.load( + out_path, + file_type="obj", + force="mesh", + skip_material=True, + merge_tex=True, + merge_norm=True, + ) + return out_mesh.split(only_watertight=False) + except subprocess.CalledProcessError as e: + print(e.output.decode("utf-8")) + raise ValueError(f"VHACD failed with exit code {e.returncode}") + + +HULL_COUNTS = [16] +USE_METHODS = { + "coacd": run_coacd, + # "vhacd": run_vhacd, +} + + +def _create_collision_obj_from_verts_faces(vertices, faces, parent, tag): + # Create a new node for the collision mesh + collision_obj = rt.Editable_Mesh() + rt.ConvertToPoly(collision_obj) + parsed_name = parse_name(parent.name) + # if parsed_name: + # collision_obj.name = f"{parsed_name.group('mesh_basename')}-Mcollision{tag}" + # else: + # collision_obj.name = parent.name + "-Mcollision" + collision_obj.name = "collisioncandidate" + tag + collision_obj.rotation = parent.rotation + collision_obj.position = parent.position + + # Add the vertices + for v in vertices: + rt.polyop.createVert(collision_obj, rt.Point3(*v.tolist())) + + # Add the faces + for f in faces: + rt.polyop.createPolygon(collision_obj, (f + 1).tolist()) + + # Optionally set its wire color + collision_obj.wirecolor = rt.yellow + + # Update the mesh to reflect changes + rt.update(collision_obj) + + # Parent the mesh + collision_obj.parent = parent + + return collision_obj + + +def generate_convex_decompositions( + obj, preferred_method=None, preferred_hull_count=None +): + if rt.classOf(obj) != rt.Editable_Poly: + return + + # Get the vertices and faces + verts = np.array( + [rt.polyop.getVert(obj, i + 1) for i in range(rt.polyop.GetNumVerts(obj))] + ) + face_selection = rt.polyop.GetFaceSelection(obj) + if face_selection.isEmpty: + face_selection = rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + faces = np.array(rt.polyop.getFacesVerts(obj, face_selection)) - 1 + assert all( + len(f) == 3 for f in faces + ), f"{obj.name} has non-triangular faces. Apply the Triangulate script." + print("\nGenerating collision meshes for", obj.name) + + # Run the convex hull option + tm = trimesh.Trimesh(vertices=verts, faces=faces) + tm.remove_unreferenced_vertices() + + if preferred_method is None or preferred_method == "chull": + chull = reduce_mesh(tm.convex_hull) + # TODO: Quadric decimation + convex_hull_obj = _create_collision_obj_from_verts_faces( + chull.vertices, + chull.faces, + obj, + ("_chull" if preferred_method is None else ""), + ) + print("Generated convex hull", convex_hull_obj.name) + + # Run CoACD a number of times + hull_counts = ( + [preferred_hull_count] if preferred_hull_count is not None else HULL_COUNTS + ) + for method_name, method in USE_METHODS.items(): + if preferred_method is not None and method_name != preferred_method: + continue + for hull_count in hull_counts: + meshes = method(tm, hull_count) + reduced_meshes = [reduce_mesh(m) for m in meshes] + + # Get a flattened list of vertices and faces + all_vertices = [] + all_faces = [] + for cmesh in reduced_meshes: + # Offsetting here by the past vertex count + all_faces.extend(cmesh.faces + len(all_vertices)) + all_vertices.extend(cmesh.vertices) + all_vertices = np.array(all_vertices) + all_faces = np.array(all_faces) + collision_obj = _create_collision_obj_from_verts_faces( + all_vertices, + all_faces, + obj, + ( + f"_{method_name}{hull_count}" + if preferred_method is None or preferred_hull_count is None + else "" + ), + ) + + # Check that the new element count is the same as the split count + elems = { + tuple(rt.polyop.GetElementsUsingFace(collision_obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(collision_obj)) + } + assert ( + len(elems) == len(reduced_meshes) + ), f"{obj.name} has different number of faces in collision mesh than in splits" + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + print( + f"Generated {method_name} w/ max hull count {hull_count}, actual hull count {len(reduced_meshes)}, name {collision_obj.name}" + ) + + if preferred_method is None or preferred_hull_count is None: + print("Don't forget to make a selection!") + + +def generate_all_missing_collision_meshes(): + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + parsed_name = parse_name(obj.name) + if not parsed_name: + continue + if parsed_name.group("bad"): + continue + if parsed_name.group("instance_id") != "0": + continue + if parsed_name.group("meta_type"): + continue + if parsed_name.group("joint_side") == "upper": + continue + + # Does it already have a collision mesh? If so, move on. + for child in obj.children: + parsed_child_name = parse_name(child.name) + if not parsed_child_name: + continue + + # Skip parts etc. + if parsed_child_name.group("mesh_basename") != parsed_name.group( + "mesh_basename" + ): + continue + + if parsed_child_name.group("meta_type") == "collision": + print("Collision mesh already exists for", obj.name, ", skipping.") + break + else: + # Generate teh collision mesh if we didnt already find one. + generate_convex_decompositions( + obj, + ) + + +def main(): + for obj in rt.selection: + generate_convex_decompositions(obj) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/convex_hull.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/convex_hull.py new file mode 100644 index 0000000000000000000000000000000000000000..d61f58d8182ca84c64907161bc0b172e977730a1 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/convex_hull.py @@ -0,0 +1,15 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.max.convex_decomposition import generate_convex_decompositions +from pymxs import runtime as rt + + +def main(): + for obj in rt.selection: + generate_convex_decompositions(obj, preferred_method="chull") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/create_collision_from_self.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/create_collision_from_self.py new file mode 100644 index 0000000000000000000000000000000000000000..353efabcb0a1eefcfa4a85a570d8ad0c7b51894f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/create_collision_from_self.py @@ -0,0 +1,72 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import b1k_pipeline.utils +import tqdm + +import pymxs + +rt = pymxs.runtime + + +def create_collision_from_self(obj): + # Check that the object is parentless and not already a collision object + assert obj.parent is None, f"Object {obj.name} has a parent {obj.parent.name}, expected it to be parentless" + assert "-Mcollision" not in obj.name, f"Object {obj.name} already has '-Mcollision' in its name, expected it to not already be a collision object" + assert b1k_pipeline.utils.parse_name(obj.name) is not None, f"Object {obj.name} does not have a valid name according to the naming convention, please rename it before creating collision from self" + assert rt.classOf(obj) == rt.Editable_Poly, f"Object {obj.name} is of type {rt.classOf(obj)}, expected it to be an Editable Poly" + for child in obj.children: + assert "-Mcollision" not in child.name, f"Child object {child.name} of {obj.name} already has '-Mcollision' in its name, expected it to not already be a collision object" + + # Clone the object + success, baseObj = rt.maxOps.cloneNodes( + obj, + cloneType=rt.name("copy"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {obj.name}" + (baseObj,) = baseObj + + # Triangulate the faces + ttp = rt.Turn_To_Poly() + ttp.limitPolySize = True + ttp.maxPolySize = 3 + rt.addmodifier(baseObj, ttp) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # Parent the collision object to the target object + baseObj.parent = obj + + # Rename the first object to match the selected object + baseObj.name = obj.name + "-Mcollision" + + # Remove the material + baseObj.material = None + + # Validate that the object name is valid + assert ( + b1k_pipeline.utils.parse_name(baseObj.name) is not None + ), f"Done, but please fix invalid name {baseObj.name} for collision object" + + +def create_collision_from_all_selections(): + for obj in tqdm.tqdm(list(rt.selection)): + try: + # Merge the collision objects + create_collision_from_self(obj) + except AssertionError as e: + print(f"Failed to create collision for {obj.name}, skipping.", e) + +def create_collision_from_self_button(): + try: + create_collision_from_all_selections() + # rt.messageBox("Success!") + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + create_collision_from_self_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/demirror.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/demirror.py new file mode 100644 index 0000000000000000000000000000000000000000..af2e9369a27c672ff8e4117c207338c2c7af7db2 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/demirror.py @@ -0,0 +1,101 @@ +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +rt = pymxs.runtime + +X_MIRROR_MATRIX = rt.Matrix3( + rt.Point3(-1, 0, 0), rt.Point3(0, 1, 0), rt.Point3(0, 0, 1), rt.Point3(0, 0, 0) +) + + +def demirror(): + objects = rt.selection + + # First, find all the qualifying objects. + assert all( + np.allclose(obj.scale, 1) for obj in objects + ), "Objects should have 1, 1, 1 scale before this feature is executed." + bases = defaultdict(set) + for obj in objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + neg_scale = any(x < 0 for x in obj.objectoffsetscale) + bases[obj.baseObject].add(neg_scale) + + # Bases qualify only if they are negative in all instances. + qualifying_bases = {base for base, scales in bases.items() if scales == {True}} + qualifying_objects_per_base = { + base: [obj for obj in objects if obj.baseObject == base] + for base in qualifying_bases + } + + # Start by adding the modifier to the first one. + for base, objs in qualifying_objects_per_base.items(): + start_positions = { + obj: np.mean( + np.array( + rt.polyop.getVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj)) + ) + ), + axis=0, + ) + for obj in objs + } + + # First apply the geometry mirroring + baseobj = objs[0] + modifier = rt.mirror() + rt.addmodifier(baseobj, modifier) + + # TODO: Base this on bounding box and not the object + object_in_pivot_frame = baseobj.objecttransform * rt.inverse(baseobj.transform) + pivot_in_object_frame = rt.inverse(object_in_pivot_frame) + + modifier.Mirror_Center.rotation = object_in_pivot_frame.rotation + modifier.Mirror_Center.position = pivot_in_object_frame.position + assert np.allclose( + modifier.Mirror_Center.position, pivot_in_object_frame.position + ) + assert np.allclose( + modifier.Mirror_Center.rotation, object_in_pivot_frame.rotation + ) + + rt.maxOps.collapseNodeTo(baseobj, 1, True) + + # Then apply the transform mirroring + for obj in objs: + obj.transform = X_MIRROR_MATRIX * obj.transform + end_position = np.mean( + np.array( + rt.polyop.getVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj)) + ) + ), + axis=0, + ) + diff = np.linalg.norm(end_position - start_positions[obj]) + assert ( + diff < 1 + ), f"{obj.name} should not have moved, but it moved by {diff} units." + print("Demirrored ", obj.name) + + +def demirror_button(): + try: + demirror() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Demirror complete - no errors found!") + + +if __name__ == "__main__": + demirror_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/export_meshes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/export_meshes.py new file mode 100644 index 0000000000000000000000000000000000000000..dd12eae46b168fb67ed566e79d5c9bd1a50368df --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/export_meshes.py @@ -0,0 +1,450 @@ +import pathlib +import sys +import traceback + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import os +import tempfile +import traceback +import cv2 +import numpy as np +from pymxs import runtime as rt +import json +import re +from collections import defaultdict +import b1k_pipeline.utils + +import trimesh +from fs.zipfs import ZipFS +from fs.osfs import OSFS +from fs.tempfs import TempFS +import fs.copy + +USE_NATIVE_EXPORT = True + +allow_list = [] +black_list = [] + + +def save_meta_mesh(obj, output_fs): + # Assert that collision meshes do not share instances in the scene + assert not [ + x for x in rt.objects if x.baseObject == obj.baseObject and x != obj + ], f"{obj.name} should not have instances." + + # Get vertices and faces into numpy arrays for conversion + verts = np.array( + [rt.polyop.getVert(obj, i + 1) for i in range(rt.polyop.GetNumVerts(obj))] + ) + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + # Split the faces into elements + faces_not_yet_found = np.zeros(faces.shape[0], dtype=bool) + elems = [] + while not np.all(faces_not_yet_found): + next_not_found_face = int(np.where(~faces_not_yet_found)[0][0]) + elem = np.array(rt.polyop.GetElementsUsingFace(obj, [next_not_found_face + 1])) + assert elem[next_not_found_face], "Searched face not found in element." + elems.append(elem) + faces_not_yet_found[elem] = True + assert len(elems) <= 40, f"{obj.name} should not have more than 40 elements." + elems = np.array(elems) + assert not np.any( + np.sum(elems.astype(int), axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + # Iterate through the elements + for i, elem in enumerate(elems): + # Load the mesh into trimesh and assert convexity + relevant_faces = faces[elem] + m = trimesh.Trimesh(vertices=verts, faces=relevant_faces, process=False) + m.remove_unreferenced_vertices() + assert m.is_volume, f"{obj.name} element {i} is not a volume" + # assert m.is_convex, f"{obj.name} element {i} is not convex" + assert ( + len(m.split()) == 1 + ), f"{obj.name} element {i} has elements trimesh still finds splittable" + + # Save the mesh into an obj file + assert b1k_pipeline.utils.save_mesh( + m, output_fs, obj.name + f"-{i}.obj" + ), f"{obj.name} element {i} could not be saved" + + +def save_mesh(obj, output_path): + # Get vertices and faces into numpy arrays for conversion + verts = np.array( + [rt.polyop.getVert(obj, i + 1) for i in range(rt.polyop.GetNumVerts(obj))] + ) + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + # Convert to Trimesh + m = trimesh.Trimesh(vertices=verts, faces=faces, process=False) + m.remove_unreferenced_vertices() + + # Save the mesh into an obj file + dirname = os.path.dirname(output_path) + basename = os.path.basename(output_path) + assert b1k_pipeline.utils.save_mesh( + m, OSFS(dirname), basename + ), f"{obj.name} could not be saved" + + # TODO: Add material saving capability + + +class ObjectExporter: + def __init__(self, obj_out_dir): + self.obj_out_dir = obj_out_dir + assert os.path.exists(obj_out_dir) + + def get_process_objs(self): + objs = [] + wrong_objs = [] + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + if allow_list and all( + re.fullmatch(p, obj.name) is None for p in allow_list + ): + continue + if black_list and any( + re.fullmatch(p, obj.name) is not None for p in black_list + ): + continue + parsed_name = b1k_pipeline.utils.parse_name(obj.name) + if parsed_name is None: + wrong_objs.append((obj.name, rt.ClassOf(obj))) + continue + if parsed_name.group("meta_type"): + continue + if int(parsed_name.group("instance_id")) != 0: + continue + if parsed_name.group("bad"): + continue + + # obj_dir = os.path.join(self.obj_out_dir, obj.name) + # obj_file = os.path.join(obj_dir, obj.name + ".obj") + # json_file = os.path.join(obj_dir, obj.name + ".json") + # if os.path.exists(obj_file) and os.path.exists(json_file): + # continue + objs.append(obj) + + for light in rt.lights: + if b1k_pipeline.utils.parse_name(light.name) is None: + wrong_objs.append((light.name, rt.ClassOf(light))) + + if len(wrong_objs) != 0: + for obj_name, obj_type in wrong_objs: + print(obj_name, obj_type) + assert False, wrong_objs + + objs.sort( + key=lambda obj: int( + b1k_pipeline.utils.parse_name(obj.name).group("instance_id") + ) + ) + + return objs + + def export_obj(self, obj): + print("export_meshes", obj.name) + + obj_dir = os.path.join(self.obj_out_dir, obj.name) + os.makedirs(obj_dir, exist_ok=True) + + # WARNING: we don't know how to set fine-grained setting of OBJ export. It always inherits the setting of the last export. + obj_path = os.path.join(obj_dir, obj.name + ".obj") + + if USE_NATIVE_EXPORT: + rt.select(obj) + + # rt.ObjExp.setIniName(os.path.join(os.path.parent(__file__), "gw_objexp.ini")) + # assert ( + # rt.getIniSetting(rt.ObjExp.getIniName(), "Material", "UseMapPath") + # == "0" + # ), "Map path should be disabled." + # assert ( + # rt.getIniSetting(rt.ObjExp.getIniName(), "Material", "MapPath") + # == "./material/" + # ), "Wrong material path." + assert ( + rt.getIniSetting(rt.ObjExp.getIniName(), "Geometry", "FlipZyAxis") + == "0" + ), "Should not flip axes when exporting." + assert rt.units.systemScale == 1, "System scale not set to 1mm." + assert rt.units.systemType == rt.Name( + "millimeters" + ), "System scale not set to 1mm." + + rt.exportFile( + obj_path, rt.Name("noPrompt"), selectedOnly=True, using=rt.ObjExp + ) + else: + save_mesh(obj, obj_path) + + assert os.path.exists(obj_path), f"Could not export object {obj.name}" + self.export_obj_metadata(obj, obj_dir) + + def export_obj_metadata(self, obj, obj_dir): + print("export_meshes_metadata", obj.name) + + metadata = {} + + # Export the canonical position and orientation + metadata["position"] = [ + obj.position.x, + obj.position.y, + obj.position.z, + ] + metadata["orientation"] = [ + obj.rotation.x, + obj.rotation.y, + obj.rotation.z, + obj.rotation.w, + ] + + # Export information about the material + mtl = obj.material + assert ( + rt.classOf(obj.material) == rt.Shell_Material + ), f"Material {obj.material} is not a shell material." + baked_mtl = mtl.bakedMaterial + metadata["material_maps"] = {} + for map_idx in range(rt.getNumSubTexmaps(baked_mtl)): + sub_texmap = rt.getSubTexmap(baked_mtl, map_idx + 1) + if sub_texmap is not None: + sub_texmap_slot_name = rt.getSubTexmapSlotName(baked_mtl, map_idx + 1) + assert ( + rt.classOf(sub_texmap) == rt.Bitmaptexture + ), f"Object {obj.name} baked material map {sub_texmap_slot_name} has unexpected type {rt.classOf(sub_texmap)}" + + # Use os.path.abspath which normalizes + absolutifies the paths but does not resolve symlinks unlike pathlib (problem with dvc) + map_path_str = os.path.abspath(sub_texmap.filename) + # Fix legacy-format paths + if "ig_pipeline" in map_path_str: + map_path_str = map_path_str.replace( + "ig_pipeline", "BEHAVIOR-1K/asset_pipeline" + ) + map_path = pathlib.Path(map_path_str) + assert ( + map_path.exists() + ), f"Object {obj.name} baked material map {sub_texmap_slot_name} does not exist at {map_path}" + bakery_path = pathlib.Path( + os.path.abspath(os.path.join(rt.maxFilePath, "bakery")) + ) + + # Then switch to Pathlib which asserts that the path is a subpath before normalizing + metadata["material_maps"][sub_texmap_slot_name] = map_path.relative_to( + bakery_path + ).as_posix() + + assert len(metadata["material_maps"]) > 0, f"Object {obj.name} has no maps." + + metadata["meta_links"] = defaultdict( + lambda: defaultdict(lambda: defaultdict(dict)) + ) + metadata["parts"] = [] + metadata["layer_name"] = obj.layer.name + obj_name_result = b1k_pipeline.utils.parse_name(obj.name) + assert obj_name_result, f"Unparseable object name {obj.name}" + for light in rt.lights: + light_name_result = b1k_pipeline.utils.parse_name(light.name) + assert light_name_result, f"Unparseable light name {light.name}" + if ( + obj_name_result.group("category") == light_name_result.group("category") + and obj_name_result.group("model_id") + == light_name_result.group("model_id") + and obj_name_result.group("instance_id") + == light_name_result.group("instance_id") + ): + # assert light.normalizeColor == 1, "The light's unit is NOT lm." + assert light_name_result.group( + "light_id" + ), "The light does not have an ID." + light_id = str(int(light_name_result.group("light_id"))) + metadata["meta_links"]["lights"][light_id]["0"] = { + "type": light.type, + "length": light.sizeLength, + "width": light.sizeWidth, + "color": [light.color.r, light.color.g, light.color.b], + "intensity": light.multiplier, + "position": [ + light.objecttransform.position.x, + light.objecttransform.position.y, + light.objecttransform.position.z, + ], + "orientation": [ + light.objecttransform.rotation.x, + light.objecttransform.rotation.y, + light.objecttransform.rotation.z, + light.objecttransform.rotation.w, + ], + } + + for child in obj.children: + child_name_result = b1k_pipeline.utils.parse_name(child.name) + + # Take care of exporting object parts. + if rt.classOf(child) in (rt.Editable_Poly, rt.PolyMeshObject): + if child_name_result.group("meta_type"): + # Save collision mesh. + assert child_name_result.group("meta_type") in ( + "collision", + "fillable", + "openfillable", + ), f"Only Mcollision, Mfillable and Mopenfillable can be a mesh." + save_meta_mesh(child, OSFS(obj_dir)) + else: + # Save part metadata. + metadata["parts"].append(child.name) + continue + + is_valid_meta = rt.classOf(child) in { + rt.Point, + rt.Box, + rt.Cylinder, + rt.Sphere, + rt.Cone, + } + assert ( + is_valid_meta + ), f"Meta link {child.name} has unexpected type {rt.classOf(child)}" + + if not child_name_result.group("meta_type"): + continue + + meta_info = child_name_result.group("meta_info") + meta_type = child_name_result.group("meta_type") + meta_id_str = child_name_result.group("meta_id") + meta_id = "0" if meta_id_str is None else meta_id_str + meta_subid_str = child_name_result.group("meta_subid") + meta_subid = "0" if meta_subid_str is None else meta_subid_str + assert ( + meta_subid not in metadata["meta_links"][meta_type][meta_id] + ), f"Meta subID {meta_info} is repeated in object {obj.name}" + object_transform = child.objecttransform # This is a 4x3 array + position = object_transform.position + rotation = object_transform.rotation + scale = np.array(list(object_transform.scale)) + + metadata["meta_links"][meta_type][meta_id][meta_subid] = { + "position": list(position), + "orientation": [rotation.x, rotation.y, rotation.z, rotation.w], + } + + if rt.classOf(child) == rt.Sphere: + size = np.array([child.radius, child.radius, child.radius]) * scale + metadata["meta_links"][meta_type][meta_id][meta_subid]["type"] = "sphere" + metadata["meta_links"][meta_type][meta_id][meta_subid]["size"] = list( + size + ) + elif rt.classOf(child) == rt.Box: + size = np.array([child.width, child.length, child.height]) * scale + metadata["meta_links"][meta_type][meta_id][meta_subid]["type"] = "box" + metadata["meta_links"][meta_type][meta_id][meta_subid]["size"] = list( + size + ) + elif rt.classOf(child) == rt.Cylinder: + size = np.array([child.radius, child.radius, child.height]) * scale + metadata["meta_links"][meta_type][meta_id][meta_subid]["type"] = "cylinder" + metadata["meta_links"][meta_type][meta_id][meta_subid]["size"] = list( + size + ) + elif rt.classOf(child) == rt.Cone: + assert np.isclose( + child.radius1, 0 + ), f"Cone radius1 should be 0 for {child.name}" + size = np.array([child.radius2, child.radius2, child.height]) * scale + metadata["meta_links"][meta_type][meta_id][meta_subid]["type"] = "cone" + metadata["meta_links"][meta_type][meta_id][meta_subid]["size"] = list( + size + ) + + # Convert the subID to a list + for keyed_by_id in metadata["meta_links"].values(): + for id, keyed_by_subid in keyed_by_id.items(): + found_subids = set(keyed_by_subid.keys()) + expected_subids = {str(x) for x in range(len(found_subids))} + assert ( + found_subids == expected_subids + ), f"{obj.name} has non-continuous subids {sorted(found_subids)}" + int_keyed = { + int(subid): meshes for subid, meshes in keyed_by_subid.items() + } + keyed_by_id[id] = [meshes for _, meshes in sorted(int_keyed.items())] + + json_file = os.path.join(obj_dir, obj.name + ".json") + with open(json_file, "w") as f: + json.dump(metadata, f) + + def run(self): + # assert rt.classOf(rt.renderers.current) == rt.V_Ray_5__update_2_3, f"Renderer should be set to V-Ray 5.2.3 CPU instead of {rt.classOf(rt.renderers.current)}" + assert rt.execute("max modify mode") + + objs = self.get_process_objs() + failures = {} + for i, obj in enumerate(objs): + try: + print(f"{i + 1} / {len(objs)} total") + + obj.isHidden = False + for child in obj.children: + child.isHidden = False + + self.export_obj(obj) + except Exception as e: + failures[obj.name] = traceback.format_exc() + + failure_msg = "\n".join(f"{obj}: {err}" for obj, err in failures.items()) + assert len(failures) == 0, f"Some objects could not be exported:\n{failure_msg}" + + +def main(): + out_dir = os.path.join(rt.maxFilePath, "artifacts") + + success = True + error_msg = "" + try: + with TempFS(temp_dir=r"D:\tmp") as obj_out_fs, ZipFS( + os.path.join(out_dir, "meshes.zip"), write=True, temp_fs=obj_out_fs + ) as zip_fs: + exp = ObjectExporter(obj_out_fs.getsyspath("/")) + exp.run() + + print("Move files to archive.") + + print("Finished copying.") + except: + success = False + error_msg = traceback.format_exc() + + json_file = os.path.join(out_dir, "export_meshes.json") + with open(json_file, "w") as f: + json.dump({"success": success, "error_msg": error_msg}, f) + + if success: + print("Export successful!") + else: + print("Export failed.") + print(error_msg) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/extract_particle_objects.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/extract_particle_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..55a76d6abc444684f5691046e91be25c1c475437 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/extract_particle_objects.py @@ -0,0 +1,261 @@ +from collections import defaultdict +import glob +import pathlib + +import sys + +import numpy as np +import tqdm + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +from b1k_pipeline.utils import parse_name + +# Items to merge +MERGES_BY_TARGET = { + # "objects/batch-04": [ + # "oedkgo", + # "wrtgbv", + # "pfapuv", + # "xzizzj", + # "zseasm", + # "onpcoz", + # "rlcnca", + # "diwmzn", + # "voawxd", + # "dwnzxq", + # "lderti", + # "hhtouu", + # "zrerox", + # "qjkibp", + # "knqyja", + # ], + # "objects/batch-07": [ + # "goprkj", + # "nkzvwy", + # "tgekwx", + # "ffmpvs", + # "mqxqgs", + # "detbvf", + # "vjruxb", + # "dwxvxp", + # "ptcdjs", + # "mkvtje", + # "izavdu", + # "sspnhq", + # "pxsxoj", + # "ppwcrm", + # "wlktgt", + # "wzbjba", + # "bdsaeg", + # "vnvhzd", + # "iobqqp", + # "crltjn", + # "mbvbqt", + # "lfkjfd", + # "qlrgsg", + # "ywnfer", + # "uenxiu", + # "kjjkii", + # "nhljib", + # "vskces", + # "gkmvqk", + # "xvvsij", + # "jjxhmf", + # "axloyp", + # "kkckpq", + # "puxhag", + # "nizghj", + # "zdcjqz", + # "qbfkpo", + # "xkpcoi", + # "yujqba", + # "nvtnsi", + # "qctxuz", + # "qyglnm", + # "wodmnd", + # "lceujn", + # "vmnhqj", + # "wywdvp", + # ], + # "objects/batch-01": ["kqhokv", "ozvqdx"], + # "objects/batch-08": [ + # "etejri", + # "hgswfr", + # "bajppk", + # "ncvtfs", + # "jwqrer", + # "pqlafi", + # "huevxh", + # "bmnejm", + # ], + # "objects/legacy_batch-10": [ + # "fjafda", + # "fjdkah", + # "fkasda", + # "iwoaoo", + # "rtuiww", + # "lwuaas", + # ], + # "objects/task_relevant-xy": ["prxfhj", "gqmvyh", "fayhga", "hppsgv"], + # "objects/batch-02": [ + # "hpnnry", + # "uyqrik", + # "fdmgww", + # "kiwkye", + # "wfhrzf", + # "zwkoax", + # "vgfyvo", + # "sasyin", + # "wvqiai", + # "dcosbg", + # ], + # "objects/batch-06": ["gltrdw", "wocjtj", "fwupto", "wufirc", "fyvbms"], + # "objects/batch-00": [ + # "bceugv", + # "cdirwq", + # "wsitbh", + # "absogx", + # "svozzf", + # "jvkhxe", + # "oqfzwb", + # "akpsld", + # "eillnh", + # "gikvpd", + # "ucrnic", + # "ukbqku", + # "unfdjb", + # "ypyicv", + # "ujyxaz", + # "tmsvpt", + # "dougsx", + # "hzlhrs", + # "xkewvu", + # "wyswqr", + # "duigmh", + # "fkhgbp", + # "gapzju", + # "rravgd", + # "lprbcf", + # "tweqol", + # "ahhnsg", + # "nldcwc", + # "tjbgmz", + # ], + # "objects/batch-03": ["cfmerb", "yrjoai", "numpzy", "glalke", "hkujlj", "abcedi"], + # "objects/batch-05": [ + # "scegcm", + # "evzqom", + # "tjrevb", + # "rxnxmg", + # "ohhozd", + # "irgjqx", + # "wbgews", + # "jbfabl", + # "kdwqco", + # "deftjq", + # "uwdwzw", + # "clvjuy", + # ], + "objects/batch-09": ["acjxoq"], + "objects/legacy_batch-05": ["acooui"], + "objects/legacy_batch-04": ["mfkwzi"], + "objects/batch-11": ["rxefdu"], + "objects/batch-12": ["avvshq"], + "objects/legacy_batch-11": ["bhirar"], +} + + +def merge_files(): + x_so_far = 19000 + + # Merge in each file + for target, ids in tqdm.tqdm(MERGES_BY_TARGET.items()): + p = ( + pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline\cad") + / target + / "processed.max" + ) + filename = str(p) + + # Get the right object names from the file + f_objects = rt.getMAXFileObjectNames(filename, quiet=True) + visual_objects_to_merge = defaultdict(set) + for obj in f_objects: + m = parse_name(obj) + if not m: + continue + if m.group("bad") or m.group("instance_id") != "0": + continue + + visual_objects_to_merge[m.group("model_id")].add(obj) + + model_ids_to_import = set(visual_objects_to_merge.keys()) & set(ids) + print( + f"Importing {len(model_ids_to_import)} models from {filename}: {sorted(model_ids_to_import)}" + ) + + # Clean up all the objects in the current file belonging to that model ID + deletion_queue = [] + for obj in rt.objects: + m = parse_name(obj.name) + if not m: + continue + if m.group("model_id") in model_ids_to_import: + deletion_queue.append(obj) + assert not deletion_queue, f"Objects to delete: {deletion_queue}" + # for obj in deletion_queue: + # rt.delete(obj) + + # Concatenate the list of all the objects that we need to import + objects_to_import = [ + object_name + for model_id in model_ids_to_import + for object_name in visual_objects_to_merge[model_id] + ] + + success, imported_meshes = rt.mergeMaxFile( + filename, + objects_to_import, + rt.Name("select"), + rt.Name("autoRenameDups"), + rt.Name("useSceneMtlDups"), + rt.Name("neverReparent"), + rt.Name("noRedraw"), + quiet=True, + mergedNodes=pymxs.byref(None), + ) + assert success, f"Failed to import" + imported_objs_by_name = {obj.name: obj for obj in imported_meshes} + assert set(objects_to_import) == set(imported_objs_by_name.keys()), ( + "Not all objects were imported. Missing: " + + str(set(objects_to_import) - set(imported_objs_by_name.keys())) + ) + + # Unhide everything + for x in imported_meshes: + x.isHidden = False + + # Move the root-level objects to the right place + for x in imported_meshes: + if x.parent is not None: + continue + + bbox_min, bbox_max = rt.NodeGetBoundingBox(x, rt.Matrix3(1)) + bbox_min = np.array(bbox_min) + bbox_max = np.array(bbox_max) + bbox_extent = bbox_max - bbox_min + bbox_min_wrt_pos = np.array(x.position) - bbox_min + target_bbox_min = np.array([x_so_far, 4000, 0]) + x.position = rt.Point3(*(target_bbox_min + bbox_min_wrt_pos).tolist()) + x_so_far += bbox_extent[0] + 100 + + print("Done!") + + +if __name__ == "__main__": + merge_files() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/extract_school_objects.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/extract_school_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..1284f9e17a4228b25c930022c1cf813dd80cac66 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/extract_school_objects.py @@ -0,0 +1,179 @@ +from collections import defaultdict +import glob +import pathlib + +import sys + +import tqdm + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +from b1k_pipeline.utils import parse_name + +# Items to merge +IDS_TO_MERGE = { + "aknswb", + "arbekb", + "ayuubt", + "bftrar", + "bgpvtb", + "bpwjxr", + "cgvoho", + "ebtgyg", + "ehwmol", + "enfumt", + "ertfpr", + "ewqpfv", + "exaqtm", + "fdxevw", + "fjytro", + "fkosow", + "flctdz", + "ftvzzg", + "gemgfz", + "gvkgsi", + "gxajos", + "hfianz", + "hlktkb", + "hocerb", + "hvjwvj", + "hwhisw", + "hxbrop", + "hylkmj", + "inkwmw", + "izhouj", + "jchomn", + "jwagmm", + "khxpgc", + "kjxpdi", + "kkrlrc", + "ldbalq", + "ldrjoi", + "lufqkq", + "mbfgxr", + "mcukuh", + "mgzyjy", + "mstxjw", + "muqeud", + "myaxie", + "nbwrns", + "neqiyu", + "nwlbit", + "oedwla", + "oynrtw", + "paaegg", + "pktarr", + "pmtynn", + "qebtel", + "qemval", + "qvvvxz", + "qzrpiw", + "rgmujm", + "rpprcc", + "rwmofs", + "sdsfzw", + "shnohg", + "skcdiz", + "tbzucx", + "tfgypq", + "tfrisv", + "tiscsa", + "tjawkk", + "tmluxa", + "tqyiso", + "uztisk", + "vaoegv", + "vgsgxk", + "wraizn", + "wttqrk", + "wxkuww", + "xijidt", + "xjupjc", + "xkfmjp", + "xnjodq", + "xxipyh", + "ydfgju", + "yhthgr", + "zoolef", + "zrsytt", + "zughoy", + "zywgbh", +} + + +def merge_files(): + max_files = glob.glob(r"D:\BEHAVIOR-1K\asset_pipeline\cad\scenes\*\processed.max") + school_files = sorted( + [pathlib.Path(x) for x in max_files if "scenes" in x and "school_" in x] + ) + + # Merge in each file + for p in tqdm.tqdm(school_files): + filename = str(p) + + # Get the right object names from the file + f_objects = rt.getMAXFileObjectNames(filename, quiet=True) + visual_objects_to_merge = defaultdict(set) + for obj in f_objects: + m = parse_name(obj) + if not m: + continue + if m.group("bad") or m.group("instance_id") != "0": + continue + + visual_objects_to_merge[m.group("model_id")].add(obj) + + model_ids_to_import = set(visual_objects_to_merge.keys()) & IDS_TO_MERGE + print( + f"Importing {len(model_ids_to_import)} models from {filename}: {sorted(model_ids_to_import)}" + ) + + # Clean up all the objects in the current file belonging to that model ID + deletion_queue = [] + for obj in rt.objects: + m = parse_name(obj.name) + if not m: + continue + if m.group("model_id") in model_ids_to_import: + deletion_queue.append(obj) + for obj in deletion_queue: + rt.delete(obj) + + # Concatenate the list of all the objects that we need to import + objects_to_import = [ + object_name + for model_id in model_ids_to_import + for object_name in visual_objects_to_merge[model_id] + ] + + success, imported_meshes = rt.mergeMaxFile( + filename, + objects_to_import, + rt.Name("select"), + rt.Name("autoRenameDups"), + rt.Name("useSceneMtlDups"), + rt.Name("neverReparent"), + rt.Name("noRedraw"), + quiet=True, + mergedNodes=pymxs.byref(None), + ) + assert success, f"Failed to import" + imported_objs_by_name = {obj.name: obj for obj in imported_meshes} + assert set(objects_to_import) == set(imported_objs_by_name.keys()), ( + "Not all objects were imported. Missing: " + + str(set(objects_to_import) - set(imported_objs_by_name.keys())) + ) + + # Unhide everything + for x in imported_meshes: + x.isHidden = False + + print("Done!") + + +if __name__ == "__main__": + merge_files() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/file_manifest.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/file_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..a3cb4365b820e4d9fed2285af591db20b37bb5c3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/file_manifest.py @@ -0,0 +1,196 @@ +import hashlib +import json +import pathlib +import pymxs +from pymxs import runtime as rt +from tqdm import tqdm + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.max.prebake_textures import hash_object + +OUTPUT_FILENAME = "file_manifest.json" +OUTPUT_FILENAME_DEEP = "file_manifest_deep.json" + + +class MaxscriptEncoder(json.JSONEncoder): + def default(self, obj): + if type(obj) == pymxs.MXSWrapperBase: + # Here we support certain known types + if rt.classOf(obj) == rt.Color: + return [obj.r, obj.g, obj.b, obj.a] + elif rt.classOf(obj) == rt.Array: + return list(obj) + elif rt.classOf(obj) == rt.Time: + return obj.frame + # Let the base class default method raise the TypeError + return super().default(obj) + + +def hash_single_thing(thing): + # try: + # This tries to check if the thing can be JSON dumped. If it can, then we can do a proper hash + # by sha256'ing its bytes. + json_string = json.dumps( + thing, sort_keys=True, separators=(",", ":"), cls=MaxscriptEncoder + ) + + # Encode the string to bytes, as hashlib works on bytes + json_bytes = json_string.encode("utf-8") + + # Use a standard hash algorithm like SHA-256 + # Use hexdigest() for a string representation of the hash + return hashlib.sha256(json_bytes).hexdigest() + # except TypeError: + # # Otherwise, we have to rely on the hash() function which is not stable across runs for + # # non-maxscript objects. But - no alternatives here! + # return hash(thing) + + +def should_skip_attr(k, v): + # We skip None because its hash changes every time we run the script. + # It's fine to do this because if the value changes to not none, it will stop being + # skipped and we'll get a different hash. + if v is None: + return True + if k in [ + "setmxsprop", + "getmxsprop", + "bitmap", + "excludeList", + "brdf_newGTRAnisotropy", + ]: + return True + # These get hashed as part of the submtl / subtexmap searches. + if rt.superClassOf(v) == rt.textureMap or rt.superClassOf(v) == rt.Material: + return True + return False + + +def hash_attrs(obj): + hash_dict = {} + for k in dir(obj): + try: + v = getattr(obj, k) + if not should_skip_attr(k, v): + hash_dict[k] = hash_single_thing(v) + except: + hash_dict[k] = None + + # Here it's possible to just return the dict rather than hashing it again. That allows saving + # far more detailed information e.g. as to what was changed about the object or material. However + # it makes the files grow to tens of megabytes and makes them really hard to diff so we don't do that. + # But if you want to, just return hash_dict instead of the hash to get the full information for + # debugging. + return hash_dict # {"unified_hash": hash_single_thing(hash_dict)} + + +def hash_material(root_mat): + """ + Get the hash of a material by recursively hashing its sub-materials. + This is a very blind hash - it will just identify if ANYTHING in the hierarchy + of materials has changed. + """ + + hash_dict = {} + + def _recursively_hash_materials_and_textures(mtl, partial_hash_dict): + # Do the actual hashing + partial_hash_dict.update(hash_attrs(mtl)) + + # We can check for submtls for material instances + if rt.superClassOf(mtl) == rt.Material: + partial_hash_dict["submtls"] = {} + for i in range(rt.getNumSubMtls(mtl)): + sub_mtl = rt.getSubMtl(mtl, i + 1) + sub_mtl_slot_name = rt.getSubMtlSlotName(mtl, i + 1) + partial_hash_dict["submtls"][sub_mtl_slot_name] = {} + if sub_mtl is not None: + _recursively_hash_materials_and_textures( + sub_mtl, partial_hash_dict["submtls"][sub_mtl_slot_name] + ) + + # We can check for subtexmaps for texture maps and materials + if rt.superClassOf(mtl) == rt.textureMap or rt.superClassOf(mtl) == rt.Material: + partial_hash_dict["subtexmaps"] = {} + for i in range(rt.getNumSubTexmaps(mtl)): + sub_texmap = rt.getSubTexmap(mtl, i + 1) + sub_texmap_slot_name = rt.getSubTexmapSlotName(mtl, i + 1) + partial_hash_dict["subtexmaps"][sub_texmap_slot_name] = {} + if sub_texmap is not None: + _recursively_hash_materials_and_textures( + sub_texmap, + partial_hash_dict["subtexmaps"][sub_texmap_slot_name], + ) + + _recursively_hash_materials_and_textures(root_mat, hash_dict) + return hash_dict + + +def main(): + # Go through all the objects and store their information. + file_manifest = [] + file_manifest_deep = [] + for obj in tqdm(list(rt.objects)): + obj_id = obj.inode.handle + obj_name = obj.name + obj_parent = obj.parent.name if obj.parent else None + obj_layer = obj.layer.name + obj_class = str(rt.classOf(obj)) + if rt.classOf(obj) == rt.Editable_Poly: + obj_hash = hash_object(obj) + else: + obj_hash = hash_attrs(obj) + obj_mtl_hash = hash_material(obj.material) if obj.material else None + obj_transform = str(obj.transform) + obj_objecttransform = str(obj.objectTransform) + file_manifest_deep.append( + { + "id": obj_id, + "name": obj_name, + "parent": obj_parent, + "layer": obj_layer, + "class": obj_class, + "hash": obj_hash, + "mtl_hash": obj_mtl_hash, + "transform": obj_transform, + "objecttransform": obj_objecttransform, + } + ) + file_manifest.append( + { + "id": obj_id, + "name": obj_name, + "parent": obj_parent, + "layer": obj_layer, + "class": obj_class, + "hash": obj_hash + if isinstance(obj_hash, str) + else hash_single_thing(obj_hash), + "mtl_hash": hash_single_thing(obj_mtl_hash), + "transform": obj_transform, + "objecttransform": obj_objecttransform, + } + ) + + # Sort the list by id + file_manifest_deep.sort(key=lambda x: x["name"]) + file_manifest.sort(key=lambda x: x["name"]) + + # Dump into a JSON file + output_dir = pathlib.Path(rt.maxFilePath) / "artifacts" + output_dir.mkdir(parents=True, exist_ok=True) + + filename = output_dir / OUTPUT_FILENAME + with open(filename, "w") as f: + json.dump(file_manifest, f, indent=4) + + filename_deep = output_dir / OUTPUT_FILENAME_DEEP + with open(filename_deep, "w") as f: + json.dump(file_manifest_deep, f, indent=4) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/find_duplicates.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/find_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..856840fdc33f2c4b11dde1409d369c1d4a8bef5b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/find_duplicates.py @@ -0,0 +1,53 @@ +import numpy as np +import pymxs +from scipy.spatial.distance import pdist, squareform + +rt = pymxs.runtime + + +def find_duplicates(): + keys = [x for x in rt.objects if rt.classOf(x) == rt.Editable_Poly] + positions = [ + np.mean( + np.array( + rt.polyop.getVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj)) + ) + ), + axis=0, + ) + for obj in keys + ] + + positions = np.asarray(positions) + print(positions.shape) + distances = squareform(pdist(positions)) + + threshold = 1 # mm + above_threshold = distances < threshold + + candidate_pairs = set() + for i, key in enumerate(keys): + if not rt.isValidNode(key): + continue + candidates = [ + keys[a] + for a in np.nonzero(above_threshold[i])[0] + if rt.isValidNode(keys[a]) + ] + if len(candidates) > 1: + pair = tuple({x.baseObject for x in candidates}) + assert len(pair) == 2, ( + "Whoa! " + str(candidates) + " has weird pair " + str(pair) + ) + if len(pair) == 2: + candidate_pairs.add(pair) + + print(f"{len(candidate_pairs)} pairs remaining.") + picked_pair = next(iter(candidate_pairs)) + all_2nd = [x for x in rt.objects if x.baseObject == picked_pair[1]] + rt.select(all_2nd) + + +if __name__ == "__main__": + find_duplicates() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_common_issues.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_common_issues.py new file mode 100644 index 0000000000000000000000000000000000000000..125085244a71644ce1573703fc58c04247ce6782 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_common_issues.py @@ -0,0 +1,1014 @@ +import csv +import datetime +import hashlib +import json +import os +import shutil +import sys + +import numpy as np + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import glob +import pathlib +import random +import re +import string +from collections import defaultdict + +import pymxs +import tqdm + +import b1k_pipeline.utils +import b1k_pipeline.max.apply_qa_fixes +import b1k_pipeline.max.import_fillable_meshes +import b1k_pipeline.max.extract_particle_objects +import b1k_pipeline.max.extract_school_objects +import b1k_pipeline.max.prebake_textures +import b1k_pipeline.max.replace_bad_object +import b1k_pipeline.max.collision_vertex_reduction +import b1k_pipeline.max.convex_decomposition +import b1k_pipeline.max.match_links +from b1k_pipeline.max.merge_collision import merge_collision + +rt = pymxs.runtime + +PASS_FILENAME = "done-reunwrapbad.success" +VRAY_LOG_FILENAME = pathlib.Path(r"D:/BEHAVIOR-1K/asset_pipeline/mtlconvert.log") +RENDER_PRESET_FILENAME = str( + (b1k_pipeline.utils.PIPELINE_ROOT / "render_presets" / "objrender.rps").absolute() +) + +# Any baked map with an mtime newer than this cutoff is considered "recently +# (re)uploaded" and the corresponding object should be re-unwrapped and re-baked. +# Use a naive local-time datetime to match os.path.getmtime semantics. +RECENT_BAKE_CUTOFF_TS = datetime.datetime(2026, 1, 1).timestamp() + +from bddl.knowledge_base import KnowledgeBase + +kb = KnowledgeBase(populate=True) + + +def get_approved_room_types(): + approved = [] + with open( + b1k_pipeline.utils.PIPELINE_ROOT / "metadata/allowed_room_types.csv", newline="" + ) as csvfile: + reader = csv.reader(csvfile) + for row in reader: + approved.append(row[0]) + + return set(approved) + + +APPROVED_ROOM_TYPES = get_approved_room_types() + + +def get_renames(): + with open( + b1k_pipeline.utils.PIPELINE_ROOT / "metadata/object_renames.csv", "r" + ) as f: + reader = csv.DictReader(f) + renames = {} + for row in reader: + obj_id = row["ID (auto)"] + old_cat = row["Original category (auto)"] + new_cat = row["New Category"] + in_name = f"{old_cat}-{obj_id}" + out_name = f"{new_cat}-{obj_id}" + renames[obj_id] = (in_name, out_name) + + return renames + + +RENAMES = get_renames() + + +def get_deletions(): + with open( + b1k_pipeline.utils.PIPELINE_ROOT / "metadata/deletion_queue.csv", "r" + ) as f: + reader = csv.DictReader(f) + deletions = set() + for row in reader: + obj_id = row["ID (auto)"] + deletions.add(obj_id) + + return deletions + + +DELETIONS = get_deletions() + + +def fix_layers(filename) -> bool: + # If this is an object file, remove all layers + if filename.parts[-3] == "objects": + zero_layer = rt.LayerManager.getLayer(0) + zero_layer.current = True + for obj in rt.objects: + zero_layer.addNode(obj) + + layers_to_remove = [] + for layer_id in range(1, rt.LayerManager.count): + layers_to_remove.append(rt.LayerManager.getLayer(layer_id).name) + + for layer_name in layers_to_remove: + rt.LayerManager.deleteLayerByName(layer_name) + + else: + # Load and apply room assignments. + # First, load from the file. + old_room_assignment_file = ( + pathlib.Path(r"D:\rooms") / f"{filename.parts[-2]}.json" + ) + old_room_assignments = json.loads(old_room_assignment_file.read_text()) + + # Unfold the assignments by model ID + model_centers = defaultdict(list) + model_rooms = defaultdict(list) + for name, room, bbmin, bbmax in old_room_assignments: + m = b1k_pipeline.utils.parse_name(name) + if not m: + continue + model_id = m.group("model_id") + center = (np.array(bbmin) + np.array(bbmax)) / 2 + model_centers[model_id].append(center) + model_rooms[model_id].append(room) + model_centers = {k: np.array(v) for k, v in model_centers.items()} + + # Then, for each object instance base link in the scene, get the nearest room assignment + rooms_by_model_and_instance = {} + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + m = b1k_pipeline.utils.parse_name(obj.name) + if not m: + continue + model_id = m.group("model_id") + instance_id = m.group("instance_id") + link_name = m.group("link_name") or "base_link" + if link_name != "base_link": + continue + if m.group("meta_type"): + continue + + bbox_min, bbox_max = rt.NodeGetBoundingBox(obj, rt.Matrix3(1)) + center = (np.array(bbox_min) + np.array(bbox_max)) / 2 + + # Get the nearest room assignment (and make sure it's less than 1m away) + if model_id not in model_centers: + continue + all_centers = model_centers[model_id] + all_rooms = model_rooms[model_id] + nearest_center_idx = np.argmin(np.linalg.norm(all_centers - center, axis=1)) + nearest_center = all_centers[nearest_center_idx] + nearest_room = all_rooms[nearest_center_idx] + if np.linalg.norm(nearest_center - center) > 1000: + continue + rooms_by_model_and_instance[(model_id, instance_id)] = nearest_room + + # Then finally apply the room assignments + for obj in rt.objects: + m = b1k_pipeline.utils.parse_name(obj.name) + if not m: + continue + model_id = m.group("model_id") + instance_id = m.group("instance_id") + if (model_id, instance_id) not in rooms_by_model_and_instance: + continue + room = rooms_by_model_and_instance[(model_id, instance_id)] + layer = rt.LayerManager.getLayerFromName( + room + ) or rt.LayerManager.newLayerFromName(room) + layer.addNode(obj) + print("Reassigned", obj.name, "to", room) + + return True + + +def remove_root_level_meta_links(filename) -> bool: + to_delete = [] + for obj in rt.objects: + if obj.parent is not None: + continue + + match = b1k_pipeline.utils.parse_name(obj.name) + if match and match.group("meta_type"): + to_delete.append(obj) + + if not to_delete: + return False + + for obj in to_delete: + rt.delete(obj) + + return True + + +def apply_deletions(filename): + # No deletions on scenes. + if "scenes" in str(filename): + return False + + # Get the particle deletions + particle_deletions = { + mid + for mids in b1k_pipeline.max.extract_particle_objects.MERGES_BY_TARGET.values() + for mid in mids + } + + to_delete = [] + for obj in rt.objects: + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + + model_id = match.group("model_id") + if model_id in DELETIONS or ( + "substances-01" not in filename.parts and model_id in particle_deletions + ): + to_delete.append(obj) + + if not to_delete: + return False + + for obj in to_delete: + rt.delete(obj) + + return True + + +def apply_renames(filename): + made_any_changes = False + for obj in rt.objects: + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + + category = match.group("category") + model_id = match.group("model_id") + rename_key = f"{category}-{model_id}" + if model_id in RENAMES: + old_key, new_key = RENAMES[model_id] + if rename_key == old_key: + obj.name = obj.name.replace(old_key, new_key) + made_any_changes = True + + return made_any_changes + + +def update_visibilities(): + # Exit isolate mode + rt.IsolateSelection.ExitIsolateSelectionMode() + + # Unhide everything + for obj in rt.objects: + obj.isHidden = False + + # # Hide collision meshes + for obj in rt.objects: + if ( + "Mcollision" in obj.name + or "Mfillable" in obj.name + or "Mopenfillable" in obj.name + ): + obj.isHidden = True + + +def match_instance_materials(): + objs_by_base = defaultdict(list) + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + pn = b1k_pipeline.utils.parse_name(obj.name) + if not pn: + continue + objs_by_base[obj.baseObject].append(obj) + + for base, objs in objs_by_base.items(): + if len(objs) < 2: + continue + if len({obj.material for obj in objs}) == 1: + continue + + # Pick the good material instance + good_instance = None + for obj in objs: + pn = b1k_pipeline.utils.parse_name(obj.name) + if not pn: + continue + if pn.group("joint_side") == "upper": + continue + if pn.group("instance_id") != "0": + continue + assert not good_instance, f"Multiple good instances: {good_instance}, {obj}" + good_instance = obj + + # Assign it to all the instances + for obj in objs: + obj.material = good_instance.material + + print("Fixed material for instances of", good_instance.name) + + +def remove_nested_shell_materials(filename, keep_top_level=True): + def _replace_shell(mat): + # If this is a multi material, recurse through its submaterials + if rt.classOf(mat) == rt.MultiMaterial: + for i in range(len(mat.materialList)): + mat.materialList[i] = _replace_shell(mat.materialList[i]) + + # If it's a shell material recurse down the original side + if rt.classOf(mat) == rt.Shell_Material: + mat.originalMaterial = _replace_shell(mat.originalMaterial) + + # If this is a shell material, return the unbaked material + if rt.classOf(mat) == rt.Shell_Material: + return mat.originalMaterial + + # Otherwise just return this material + return mat + + for obj in rt.objects: + # Note that we don't assign the return value here, in effect keeping the top-level + # material and only replacing the nested ones. + tmp_mtl = _replace_shell(obj.material) + if not keep_top_level: + obj.material = tmp_mtl + + # Save here to clear material library + rt.saveMaxFile(str(filename)) + + +def remove_unnecessary_lights(): + for light in list(rt.lights): + match = b1k_pipeline.utils.parse_name(light.name) + if not match: + continue + if match.group("bad") or match.group("instance_id") != "0": + rt.delete(light) + made_any_changes = True + return made_any_changes + + +def merge_preexisting_fillable_meshes(): + processed_fillable = set() + while True: + for obj in list(rt.objects): + if not rt.classOf(obj) == rt.Editable_Poly: + continue + + if obj in processed_fillable: + continue + + fillable_meshes = [] + for child in obj.children: + if "Mfillable" in child.name: + fillable_meshes.append(child) + + if len(fillable_meshes) < 1: + continue + + print("Processing", obj.name, "with fillable meshes", fillable_meshes) + new_fillable = merge_collision(fillable_meshes, obj) + new_fillable.name = re.sub( + r"(-M([a-z]+)(?:_([A-Za-z0-9]+))?(?:_([0-9]+))?)", + "-Mfillable", + new_fillable.name, + ) + made_any_changes = True + + processed_fillable.add(obj) + + # Break out of the for loop so that the iteration list restarts. + # Otherwise, we might get a RuntimeError due to the list changing size. + break + else: + # Break out of the while loop + break + return made_any_changes + + +def run_bad_object_replacement_for_legacy_scenes(filename): + target_name = filename.parts[-2] + if target_name.endswith("_int") or target_name.endswith("_garden"): + comparison_data = ( + b1k_pipeline.max.replace_bad_object.replace_all_bad_legacy_objects_in_open_file() + ) + print(f"Replaced {len(comparison_data)} bad objects in {filename}") + with open( + filename.parent / "artifacts" / "replaced_bad_objects.json", "w" + ) as f: + json.dump(comparison_data, f) + + +def convert_legacy_uv_unwrap_attribute_to_new(): + for obj in rt.objects: + # Get the attribute that's currently on there + saved_hash = b1k_pipeline.max.prebake_textures.get_recorded_uv_unwrapping_hash( + obj + ) + if saved_hash is None: + continue + + # Otherwise generate the new hash and save it + hash_digest = b1k_pipeline.max.prebake_textures.hash_object(obj) + + # Add the new attr + b1k_pipeline.max.prebake_textures.set_recorded_uv_unwrapping_hash( + obj, hash_digest + ) + + +def delete_parts_from_nonzero_instances(): + for obj in rt.objects: + if not obj.parent: + continue + tags = {"subpart", "extrapart", "connectedpart"} + if not any("T" + tag in obj.name for tag in tags): + continue + match = b1k_pipeline.utils.parse_name(obj.parent.name) + if not match: + continue + if match.group("instance_id") == "0": + continue + rt.delete(obj) + + +def delete_upper_links_from_nonzero_instances(): + for obj in rt.objects: + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + if not match.group("bad") and match.group("instance_id") == "0": + continue + if match.group("joint_side") != "upper": + continue + rt.delete(obj) + + +def delete_meta_links_from_unnecessary_instances(): + for obj in rt.objects: + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + if not match.group("bad") and match.group("instance_id") == "0": + continue + if not match.group("meta_type"): + continue + rt.delete(obj) + + +def fix_extracted_school_objects(): + ids_to_bad = b1k_pipeline.max.extract_school_objects.IDS_TO_MERGE + for obj in rt.objects: + m = b1k_pipeline.utils.parse_name(obj.name) + if not m: + continue + if m.group("model_id") in ids_to_bad and not m.group("bad"): + obj.name = "B-" + obj.name + made_any_changes = True + return made_any_changes + + +def fix_triangulation(): + for obj in tqdm.tqdm(list(rt.objects)): + if rt.classOf(obj) != rt.Editable_Poly: + continue + + # Check all faces are triangular + all_triangular = all( + len(rt.polyop.getFaceVerts(obj, i + 1)) == 3 + for i in range(rt.polyop.GetNumFaces(obj)) + ) + if not all_triangular: + print("Need to triangulate", obj.name) + + # Triangulate + ttp = rt.Turn_To_Poly() + ttp.limitPolySize = True + ttp.maxPolySize = 3 + rt.addmodifier(obj, ttp) + rt.maxOps.collapseNodeTo(obj, 1, True) + + # Check that there are no dead elements + if rt.polyop.GetHasDeadStructs(obj) != 0: + # Remove dead structs + # print("Need to collapse", obj.name) + rt.polyop.CollapseDeadStructs(obj) + + +def convert_old_model_ids_to_new(): + objs_by_model = defaultdict(list) + for obj in rt.objects: + result = b1k_pipeline.utils.parse_name(obj.name) + if result is None: + print("{} does not match naming convention".format(obj.name)) + continue + + if re.fullmatch("[a-z]{6}", result.group("model_id")) is None: + objs_by_model[ + ( + result.group("category"), + result.group("model_id"), + result.group("bad"), + ) + ].append(obj) + + for category, model_id, bad in objs_by_model: + if bad: + random_str = "todo" + random.choices(string.ascii_lowercase, k=2) + else: + random_str = "".join( + random.choice(string.ascii_lowercase) for _ in range(6) + ) + for obj in objs_by_model[(category, model_id, bad)]: + old_str = "-".join([category, model_id]) + new_str = "-".join([category, random_str]) + obj.name = obj.name.replace(old_str, new_str) + + +def rename_hallway_to_corridor(): + existing_layer_names = { + rt.LayerManager.getLayer(x).name for x in range(rt.LayerManager.count) + } + for layer_id in range(rt.LayerManager.count): + layer = rt.LayerManager.getLayer(layer_id) + if "hallway_" in layer.name: + to_name = layer.name.replace("hallway_", "corridor_") + assert ( + to_name not in existing_layer_names + ), f"Layer {to_name} already exists" + layer.setName(to_name) + + +def remove_soft_tags(): + for obj in rt.objects: + if "-Tsoft" in obj.name: + obj.name = obj.name.replace("-Tsoft", "") + + +def load_vray_renderer(): + preset_categories = rt.renderpresets.LoadCategories(RENDER_PRESET_FILENAME) + assert rt.renderpresets.Load(0, RENDER_PRESET_FILENAME, preset_categories) + + +def convert_materials_to_vray(filename): + # First, remove all baked materials and save + # remove_nested_shell_materials(filename, keep_top_level=False) + + rt.orig_mtls = rt.Array() + rt.new_mtls = rt.Array() + rt.orig_texmaps = rt.Array() + rt.new_texmaps = rt.Array() + + # Get the objects to process. This doesnt need to be in any particular order because we call + # a per-node processing function rather htan the recursive one. + objects = list(rt.objects) + + # Get each object's prior materials first for tracking purposes + obj_materials_and_texmaps = {} + for obj in objects: + recursive_materials_and_texmaps = set() + + def _recursively_get_materials(mtl_or_texmap): + if mtl_or_texmap is None: + return + + recursive_materials_and_texmaps.add(mtl_or_texmap) + + # We can check for submtls for material instances + if rt.superClassOf(mtl_or_texmap) == rt.Material: + for i in range(rt.getNumSubMtls(mtl_or_texmap)): + sub_mtl = rt.getSubMtl(mtl_or_texmap, i + 1) + if sub_mtl is not None: + _recursively_get_materials(sub_mtl) + + # We can check for subtexmaps for texture maps and materials + if ( + rt.superClassOf(mtl_or_texmap) == rt.textureMap + or rt.superClassOf(mtl_or_texmap) == rt.Material + ): + for i in range(rt.getNumSubTexmaps(mtl_or_texmap)): + sub_texmap = rt.getSubTexmap(mtl_or_texmap, i + 1) + if sub_texmap is not None: + _recursively_get_materials(sub_texmap) + + _recursively_get_materials(obj.material) + obj_materials_and_texmaps[obj] = recursive_materials_and_texmaps + + # Then do the actual conversion + for obj in objects: + converted_mtl = rt.createVRayMtl(obj.material) + obj.material = converted_mtl + + # Check if any materials were converted, and if so, require rebake by removing the shell material + converted_so_far = set(rt.orig_mtls) | set(rt.orig_texmaps) + converted_this_object_uses = obj_materials_and_texmaps[obj] & converted_so_far + if len(converted_this_object_uses) > 0: + print(f"Object {obj.name} had materials converted, removing shell material") + VRAY_LOG_FILENAME.write_text( + VRAY_LOG_FILENAME.read_text() + + f"{obj.name}: {','.join(x.name for x in converted_this_object_uses)}\n" + ) + if rt.classOf(obj.material) == rt.Shell_Material: + obj.material = obj.material.originalMaterial + + # Clear these arrays the same way as in the original script + rt.orig_mtls = rt.Array() + rt.new_mtls = rt.Array() + rt.orig_texmaps = rt.Array() + rt.new_texmaps = rt.Array() + + # Save again to get rid of all the unused materials + rt.saveMaxFile(str(filename)) + + # # Obtain all the materials used in the scene somehow + # materials_directly_in_use = list(rt.scenematerials) + [obj.material for obj in rt.objects if rt.classOf(obj) == rt.Editable_Poly and obj.material is not None] + # recursive_materials = set() + # def _recursively_get_materials(mtl): + # recursive_materials.add(mtl) + # for i in range(rt.getNumSubMtls(mtl)): + # sub_mtl = rt.getSubMtl(mtl, i + 1) + # if sub_mtl is not None: + # _recursively_get_materials(sub_mtl) + # for mtl in materials_directly_in_use: + # _recursively_get_materials(mtl) + + # # Check the found materials for any materials that are not VrayMtl or MultiMaterial + # found_bad = False + # for mat in rt.sceneMaterials: + # if rt.classOf(mat) != rt.MultiMaterial and "vray" not in str(rt.classOf(mat)).lower(): + # print("Non-Vray material", mat.name) + # found_bad = True + # #assert not found_bad, "Non-Vray material found" + + +def update_texture_paths(): + for obj in rt.objects: + mtl = obj.material + if not mtl or rt.classOf(mtl) != rt.Shell_Material: + continue + baked_mtl = mtl.bakedMaterial + for map_idx in range(rt.getNumSubTexmaps(baked_mtl)): + sub_texmap = rt.getSubTexmap(baked_mtl, map_idx + 1) + if sub_texmap is not None: + sub_texmap_slot_name = rt.getSubTexmapSlotName(baked_mtl, map_idx + 1) + assert ( + rt.classOf(sub_texmap) == rt.Bitmaptexture + ), f"Object {obj.name} baked material map {sub_texmap_slot_name} has unexpected type {rt.classOf(sub_texmap)}" + + # Use os.path.abspath which normalizes + absolutifies the paths but does not resolve symlinks unlike pathlib (problem with dvc) + map_path = pathlib.Path(os.path.abspath(sub_texmap.filename)) + assert ( + map_path.exists() + ), f"Object {obj.name} baked material map {sub_texmap_slot_name} does not exist at {map_path}" + bakery_path = b1k_pipeline.utils.PIPELINE_ROOT / "bakery" + + if bakery_path in map_path.parents: + # This is the correct bakery path, so ignore this object + continue + + # Otherwise, we need to update the path. + correct_path = bakery_path / map_path.name + + # The below is for actually moving the files around. Here we don't need to do that. + if correct_path.exists(): + # If the path already exists, check that it's the same file. + with open(map_path, "rb") as f: + map_hash = hashlib.md5(f.read()).hexdigest() + with open(correct_path, "rb") as f: + correct_hash = hashlib.md5(f.read()).hexdigest() + if map_hash != correct_hash: + print("\nHash mismatch for", map_path, "and", correct_path) + print("Correct path hash is", correct_hash) + print("Map path hash is", map_hash) + raise ValueError( + f"Hash mismatch for {map_path} and {correct_path}. Please check the files." + ) + + else: + shutil.copyfile(map_path, correct_path) + + # Then update the path in the bitmap texture + sub_texmap.filename = str(correct_path) + + +def convert_baked_material_to_vray_and_add_ior(): + MAP_TRANSLATION = { + "Diffuse map": "Base Color Map", + "Bump map": "Bump Map", + "Refl. gloss.": "Roughness Map", + "Reflect map": "Reflectivity Map", + "Refract map": "Transparency Map", + "Metalness": "Metalness Map", + "Fresnel IOR": "IOR Map", + } + + for obj in rt.objects: + parsed_name = b1k_pipeline.utils.parse_name(obj.name) + if not parsed_name: + continue + if parsed_name.group("meta_type"): + continue + if parsed_name.group("instance_id") != "0": + continue + if parsed_name.group("bad"): + continue + if parsed_name.group("joint_side") == "upper": + continue + + mtl = obj.material + if not mtl or rt.classOf(mtl) != rt.Shell_Material: + continue + + baked_mtl = mtl.bakedMaterial + assert ( + rt.classOf(baked_mtl) == rt.Physical_Material + ), f"Object {obj.name} baked material is not a Physical Material, but {rt.classOf(baked_mtl)}" + + maps = {} + for map_idx in range(rt.getNumSubTexmaps(baked_mtl)): + channel_name = rt.getSubTexmapSlotName(baked_mtl, map_idx + 1) + sub_texmap = rt.getSubTexmap(baked_mtl, map_idx + 1) + if sub_texmap is not None: + if channel_name == "Transparency Color Map": + channel_name = "Transparency Map" + maps[channel_name] = sub_texmap + + # If there is no IOR map, try to guess it from the name + if "IOR Map" not in maps: + ior_map_filename = ( + pathlib.Path(rt.maxFilePath) + / "bakery" + / f"{obj.name}_VRayMtlReflectIORBake.exr" + ) + assert ( + ior_map_filename.exists() + ), f"IOR map {ior_map_filename} for object {obj.name} does not exist" + + # Create a new bitmap and use it as the IOR map + ior_map = rt.Bitmaptexture() + ior_map.filename = str(ior_map_filename) + ior_map.coords.mapChannel = 99 + + maps["IOR Map"] = ior_map + + # Check that we have ALL of the maps we need + missing_keys = set(MAP_TRANSLATION.values()) - set(maps.keys()) + assert ( + not missing_keys + ), f"Missing maps {missing_keys} for object {obj.name}. Found only {set(maps.keys())}" + + # Start converting to the new material + new_mtl = rt.VRayMtl() + new_mtl.name = obj.name + "__baked" + new_mtl.reflection_lockIOR = False + converted_keys = set() + for map_idx in range(rt.getNumSubTexmaps(new_mtl)): + channel_name = rt.getSubTexmapSlotName(new_mtl, map_idx + 1) + if channel_name not in MAP_TRANSLATION: + continue + assert ( + channel_name not in converted_keys + ), f"Duplicate channel name {channel_name} for object {obj.name}" + + old_map = maps[MAP_TRANSLATION[channel_name]] + rt.setSubTexmap(new_mtl, map_idx + 1, old_map) + old_map.name = f"{obj.name}__baked__{channel_name}" + converted_keys.add(channel_name) + missing_converted_keys = set(MAP_TRANSLATION.keys()) - converted_keys + assert ( + not missing_converted_keys + ), f"Not all maps converted for object {obj.name}: {missing_converted_keys}" + + mtl.bakedMaterial = new_mtl + + +def mark_recently_baked_objects_for_rebake() -> int: + """Force re-unwrap (and thus re-bake) for every object whose baked material has + at least one bitmap whose mtime is newer than RECENT_BAKE_CUTOFF_TS. + + We clear the recorded UV-unwrap hash so prebake_textures.uv_unwrapping no longer + short-circuits. That function then switches the object back to its unbaked + material, which cascades into a fresh bake inside prebake_textures.process_open_file. + """ + n_marked = 0 + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + parsed_name = b1k_pipeline.utils.parse_name(obj.name) + if not parsed_name: + continue + if parsed_name.group("meta_type"): + continue + if parsed_name.group("instance_id") != "0": + continue + if parsed_name.group("bad"): + continue + if parsed_name.group("joint_side") == "upper": + continue + + mtl = obj.material + if not mtl or rt.classOf(mtl) != rt.Shell_Material: + continue + baked_mtl = mtl.bakedMaterial + if baked_mtl is None: + continue + + recent_map = None + for map_idx in range(rt.getNumSubTexmaps(baked_mtl)): + sub_texmap = rt.getSubTexmap(baked_mtl, map_idx + 1) + if sub_texmap is None: + continue + if rt.classOf(sub_texmap) != rt.Bitmaptexture: + continue + # Use os.path.abspath (not pathlib.resolve) so we don't follow symlinks + # into the DVC cache -- the mtime we care about is the one of the file + # in the bakery directory (which is itself a symlink whose target was + # touched by fix_bakery_mtimes.py). + map_path = os.path.abspath(sub_texmap.filename) + try: + mtime = os.path.getmtime(map_path) + except OSError: + continue + if mtime > RECENT_BAKE_CUTOFF_TS: + recent_map = (map_path, mtime) + break + + if recent_map is None: + continue + + when = datetime.datetime.fromtimestamp(recent_map[1]).isoformat(timespec="seconds") + print( + f"Marking {obj.name} for re-unwrap/re-bake " + f"(recent map {recent_map[0]} @ {when})" + ) + # Empty hash digest causes get_recorded_uv_unwrapping_hash to return None, + # which never matches the current geometry hash -> forces an unwrap. + b1k_pipeline.max.prebake_textures.set_recorded_uv_unwrapping_hash(obj, "") + n_marked += 1 + + print(f"Marked {n_marked} objects for re-unwrap/re-bake.") + return n_marked + + +def processFile(filename: pathlib.Path): + # Load file, fixing the units + print(f"\n\nProcessing {filename}") + assert rt.loadMaxFile(str(filename), useFileUnits=False, quiet=True) + assert rt.units.systemScale == 1, "System scale not set to 1mm." + assert rt.units.systemType == rt.Name("millimeters"), "System scale not set to 1mm." + + # Switch to Vray + # load_vray_renderer() + + # Apply deletions + apply_deletions(filename) + + # Remove shell materials that might show up under multi materials + remove_nested_shell_materials(filename) + + # Fix any bad materials + # convert_materials_to_vray(filename) + + # Remove root_level meta links + # remove_root_level_meta_links(filename) + + # Apply renames + apply_renames(filename) + + # Fix layering (room assignments and object files) + # fix_layers(filename) + + # Remove soft tags + # remove_soft_tags() + + # Fix layers called hallway + # rename_hallway_to_corridor() + + # Fix any old names + # convert_old_model_ids_to_new() + + # Get all editable polies + # fix_triangulation() + + # Convert extracted school objects to BAD on these scenes + # fix_extracted_school_objects() + + # Delete meta links from non-zero or bad instances + # delete_meta_links_from_unnecessary_instances() + + # Delete upper links from non-zero instances + # delete_upper_links_from_nonzero_instances() + + # Delete parts from non-zero instances + # delete_parts_from_nonzero_instances() + + # Update UV unwrap to use correct attribute + # convert_legacy_uv_unwrap_attribute_to_new() + + # Run the bad object replacement system for legacy scenes + # For this particular task we are only doing this to the legacy-containing scenes + # run_bad_object_replacement_for_legacy_scenes(filename) + + # Generate all missing collision meshes + # b1k_pipeline.max.convex_decomposition.generate_all_missing_collision_meshes() + + # Reduce collision mesh vertex counts + # b1k_pipeline.max.collision_vertex_reduction.process_all_convex_meshes() + + # Match links + # b1k_pipeline.max.match_links.process_all_objects() + + # Merge preexisting fillable meshes + # merge_preexisting_fillable_meshes() + + # Import fillable meshes + # b1k_pipeline.max.import_fillable_meshes.process_current_file() + + # Remove lights from bad objects and nonzero instances + # remove_unnecessary_lights() + + # Apply the same material to all instances + # match_instance_materials() + + # Remove materials from meta links + # for obj in rt.objects: + # pn = b1k_pipeline.utils.parse_name(obj.name) + # if not pn: + # continue + # if pn.group("meta_type"): + # obj.material = None + + # Temporary hack for rebaking just the reflection channel + # baked_mtls_by_object = {} + # for obj in rt.objects: + # if obj.material and rt.classOf(obj.material) == rt.Shell_Material: + # # baked_mtls_by_object[obj] = obj.material.bakedMaterial + # obj.material = obj.material.originalMaterial + # assert rt.classOf(obj.material) != rt.Shell_Material, f"{obj} material should not be shell material before baking" + + # Mark objects whose baked maps were re-uploaded recently (per their mtimes) as + # needing a fresh unwrap. prebake_textures.process_open_file below will then + # re-unwrap and re-bake all of them. + mark_recently_baked_objects_for_rebake() + b1k_pipeline.max.prebake_textures.process_open_file() + # for obj, old_baked_mtl in baked_mtls_by_object.items(): + # # Make sure it got baked again + # if not rt.classOf(obj.material) == rt.Shell_Material: + # print(f"{obj} material is not shell material after baking - meaning this object was not baked.") + # continue + + # new_baked_mtl = obj.material.bakedMaterial + + # # Copy the new material's reflection channel to the old one's slot too + # old_baked_mtl.reflectivity_map = new_baked_mtl.reflectivity_map + + # # Switch back to the old shell material + # obj.material.bakedMaterial = old_baked_mtl + + # Update baked texture paths if the baked textures are not in the same folder as the max file + # convert_baked_material_to_vray_and_add_ior() + + # Apply the orientation and scale changes + # b1k_pipeline.max.apply_qa_fixes.apply_qa_fixes_in_open_file() + + # Update visibility settings + update_visibilities() + + # Save again. + rt.saveMaxFile(str(filename)) + + with open(filename.parent / PASS_FILENAME, "w") as f: + pass + + +def fix_common_issues_in_all_files(): + # candidates = [ + # x + # for x in pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline").glob( + # "cad/*/*/processed.max" + # ) + # ] + + targets_to_do = { + 'objects/batch-01', + 'objects/legacy_batch-06', + 'scenes/Pomaria_0_garden', + 'scenes/hotel_suite_large', + 'scenes/house_double_floor_lower', + 'scenes/office_cubicles_right', + 'scenes/commercial_kitchen_fire_extinguisher', + } + candidates = [pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline\cad") / x / "processed.max" for x in targets_to_do] + + for i, f in enumerate(tqdm.tqdm(candidates)): + if (f.parent / PASS_FILENAME).exists(): + continue + processFile(f) + + +if __name__ == "__main__": + fix_common_issues_in_all_files() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_instance_materials.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_instance_materials.py new file mode 100644 index 0000000000000000000000000000000000000000..be6d9a7844d37735a31245cc87589593a6f7d44a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_instance_materials.py @@ -0,0 +1,90 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import random +import re +import string +from collections import Counter, defaultdict + +import pymxs + +import b1k_pipeline.utils + +rt = pymxs.runtime + + +def fix_instance_materials(): + objs_by_model = defaultdict(list) + + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + objs_by_model[obj.baseObject].append(obj) + + for objs in objs_by_model.values(): + obj_names = ",".join([x.name for x in objs]) + assert ( + len( + { + ( + b1k_pipeline.utils.parse_name(obj.name).group("category"), + b1k_pipeline.utils.parse_name(obj.name).group("model_id"), + ) + for obj in objs + } + ) + == 1 + ), f"More than one cat/model found in {obj_names}." + count = Counter([x.material for x in objs]) + if len(count) == 1: + continue + elif len(count) > 2: + print( + f"More than two materials found for instance group including {obj_names}" + ) + continue + + if len(objs) == 2: + obj1, obj2 = objs + mtl1 = obj1.material + mtl2 = obj2.material + if (rt.classOf(mtl1) == rt.Multimaterial) == ( + rt.classOf(mtl2) == rt.Multimaterial + ): + # Either both are multi-material or neither. + print( + f"Cannot decide which material is right between 2 objects: {obj_names}. Do it manually." + ) + continue + elif rt.classOf(mtl1) == rt.Multimaterial: + # mtl1 is multi-material, mtl2 is not. + target_mtl = mtl1 + else: + # mtl2 is multi-material, mtl1 is not. + target_mtl = mtl2 + else: + target_mtl, least_seen_count = count.most_common()[-1] + assert ( + least_seen_count == 1 + ), f"More than one object with least common material found for instance group including {obj_names}." + + for obj in objs: + obj.material = target_mtl + print("Fixed", obj.name) + + +def fix_instance_materials_button(): + try: + fix_instance_materials() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Instance materials fixed!") + + +if __name__ == "__main__": + fix_instance_materials_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_legacy_obj_rots.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_legacy_obj_rots.py new file mode 100644 index 0000000000000000000000000000000000000000..e64200e84950c126de722707bcbd8b3c362b9e3d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_legacy_obj_rots.py @@ -0,0 +1,294 @@ +import re +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import glob +import json +import os +from typing import Dict, List + +import numpy as np +import pymxs +import tqdm +import yaml +from scipy.spatial.transform import Rotation as R + +import b1k_pipeline.utils +from b1k_pipeline.max.new_sanity_check import SanityCheck +from b1k_pipeline.urdfpy import URDF, Joint, Link + +rt = pymxs.runtime + +CONFIRM_EACH = False +INTERACTIVE_MODE = True +IN_DATASET_ROOT = r"C:\Users\Cem\research\iGibson-dev\igibson\data\ig_dataset" +OUTPUT_ROOT = r"D:\BEHAVIOR-1K\asset_pipeline\cad\objects" +RECORD_PATH = os.path.join( + r"D:\BEHAVIOR-1K\asset_pipeline\metadata\patched_rotations.json" +) +TRANSLATION_PATH = os.path.join(IN_DATASET_ROOT, "metadata", "model_rename.yaml") +with open(TRANSLATION_PATH, "r") as f: + TRANSLATION_DICT = yaml.load(f, Loader=yaml.SafeLoader) + + +class AutomationError(ValueError): + pass + + +def process_urdf(old_category_name, old_model_name): + model_dir = os.path.join( + IN_DATASET_ROOT, "objects", old_category_name, old_model_name + ) + intervention_request_msgs = [] + + # Convert to new model name. + new_category_name, new_model_name = TRANSLATION_DICT[ + old_category_name + "/" + old_model_name + ].split("/") + + # Load the URDF file into urdfpy + urdf_filename = old_model_name + ".urdf" + urdf_path = os.path.join(model_dir, "urdf", urdf_filename) + robot = URDF.load(urdf_path) + + # Get the base link base mesh transform, revert it + base_link = robot.base_link + + if len(base_link.visuals) >= 1: + assert np.allclose( + base_link.visuals[0].origin[:3, :3], np.eye(3) + ), "Rotational offsets are not allowed." + real_base_link_transform = np.linalg.inv(base_link.visuals[0].origin) + else: + intervention_request_msgs.append( + "Base link has no visual mesh. Check if the visuals are reasonable." + ) + real_base_link_transform = np.eye(4) + + def process_link(link, link_pose, is_upper_side): + visual = link.visuals[0] + assert ( + visual.geometry.mesh is not None + ), "Encountered link with primitive visuals." + + # Compute the pose + pose = real_base_link_transform @ link_pose @ visual.origin + if visual.geometry.mesh.scale is not None: + S = np.eye(4, dtype=np.float64) + S[:3, :3] = np.diag(visual.geometry.mesh.scale) + pose = pose @ S + + # Convert the pose to a 3ds Max transform + pose_formatted = pose[:3].T.tolist() + mat = rt.Matrix3( + rt.Point3(*pose_formatted[0]), + rt.Point3(*pose_formatted[1]), + rt.Point3(*pose_formatted[2]), + rt.Point3(*pose_formatted[3]), + ) + + # Get the name based on the joint type/side. + link_name = re.sub(r"[^a-z0-9_]", "", link.name.lower()) + joints: List[Joint] = robot.joints + (j,) = [j for j in joints if j.child == link.name] + + # Save this for use later. + parent_name = re.sub(r"[^a-z0-9_]", "", j.parent.lower()) + if parent_name == robot.base_link.name: + parent_name = "base_link" + obj_name = ( + f"{new_category_name}-{new_model_name}-0-{link_name}-{parent_name}-R-upper" + ) + + (obj,) = [ + x + for x in rt.objects + if b1k_pipeline.utils.parse_name(x.name).group("mesh_basename") == obj_name + ] + obj.transform = mat + + # Then, for each joint, add the upper limit. + joints: List[Joint] = robot.joints + for joint in joints: + if joint.joint_type != "revolute": + continue + + # Exclusively target joints that are more than 179 degrees + joint_range = np.abs(np.rad2deg(joint.limit.upper - joint.limit.lower)) + if joint_range <= 179: + continue + elif joint_range > 200: + intervention_request_msgs.append( + f"Large joint range of {joint_range}. Take a look." + ) + + # Get some joint info. + joint_name = joint.name + assert joint.limit.lower < joint.limit.upper, "Lower above upper" + joint_upper = joint.limit.lower + np.deg2rad(179) + child_link_name = joint.child + link = robot.link_map[child_link_name] + + # Apply FK with only this joint set to upper position. + joint_lfk = robot.link_fk(cfg={joint_name: joint_upper}) + link_pose = joint_lfk[link] + + # Process the child link with the joint's upper position. + process_link(link, link_pose, is_upper_side=True) + + return intervention_request_msgs + + +def process_object_dir(model_dir): + # Process the model name + old_category_name = os.path.basename(os.path.dirname(model_dir)) + old_model_name = os.path.basename(model_dir) + + # Convert to new model name. + new_category_name, new_model_name = TRANSLATION_DICT[ + old_category_name + "/" + old_model_name + ].split("/") + + # Get output path. + obj_output_dir = os.path.join( + OUTPUT_ROOT, f"legacy_{new_category_name}-{new_model_name}" + ) + + if not os.path.exists(obj_output_dir): + print(f"{obj_output_dir} doesn't exist!") + return + + # Reset the scene + filename = os.path.join(obj_output_dir, "processed.max") + assert rt.loadMaxFile(str(filename), useFileUnits=False) + + # Start processing. + try: + intervention_request_msgs = process_urdf(old_category_name, old_model_name) + + # Stop execution if the sanity check has failed. + sc = SanityCheck().run() + if sc["ERROR"]: + intervention_request_msgs.append( + "Sanitycheck issues:\n" + "\n".join(sc["ERROR"]) + ) + + # Finally, save the file. + max_path = os.path.join(obj_output_dir, "processed.max") + assert rt.saveMaxFile(max_path), "Could not save the file at {max_path}." + + # Update the done path record + done_paths = [] + if os.path.exists(RECORD_PATH): + with open(RECORD_PATH, "r") as f: + done_paths = json.load(f) + done_paths.append(os.path.normpath(obj_output_dir)) + with open(RECORD_PATH, "w") as f: + done_paths = json.dump(done_paths, f) + + print("Processed ", obj_output_dir) + + if CONFIRM_EACH: + intervention_request_msgs.append( + "Confirm this file - requested due to CONFIRM_EACH=True" + ) + + # If we are not silencing automation errors, raise now so that the user can examine the file. + if len(intervention_request_msgs) > 0: + if INTERACTIVE_MODE: + raise AutomationError("\n".join(intervention_request_msgs)) + else: + raise ValueError( + "Failed due to automation errors happening in headless mode. Retry in interactive." + ) + except AutomationError: + # No cleanup needed for automation errors. + raise + + +def fix_legacy_obj_rots(): + # Grab all the files from the dataset. + obj_dirs = sorted( + p + for p in glob.glob(os.path.join(IN_DATASET_ROOT, "objects/*/*")) + if os.path.isdir(p) + ) + + whitelist = { + "bottom_cabinet-immwzb", + "bottom_cabinet-hrdeys", + "bottom_cabinet-xiurwn", + "bottom_cabinet-plccav", + "bottom_cabinet_no_top-vdedzt", + "briefcase-rxvbea", + "briefcase-ohelib", + "briefcase-fdpjtj", + "carton-causya", + "dryer-wivnic", + "floor_lamp-pfuqec", + "fridge-hivvdf", + "jar-vzwhbg", + "laptop-nvulcs", + "package-msfzpz", + "stove-qbjiva", + "table_lamp-tggobp", + "table_lamp-zpqejt", + "trash_can-pdmzhv", + "trash_can-nuoypc", + "trash_can-mdojox", + "trash_can-ifzxzj", + "window-mjssrd", + } + + # Narrow down to objects that don't already exist. + split_names = [ + (os.path.basename(os.path.dirname(model_dir)), os.path.basename(model_dir)) + for model_dir in obj_dirs + ] + new_split_names = [ + TRANSLATION_DICT[old_category_name + "/" + old_model_name].split("/") + for old_category_name, old_model_name in split_names + ] + is_whitelisted = [f"{cat}-{model}" in whitelist for cat, model in new_split_names] + obj_output_dirs = [ + os.path.join(OUTPUT_ROOT, f"legacy_{new_category_name}-{new_model_name}") + for new_category_name, new_model_name in new_split_names + ] + + done_paths = [] + if os.path.exists(RECORD_PATH): + with open(RECORD_PATH, "r") as f: + done_paths = json.load(f) + + remaining_objs = [ + obj_dir + for obj_dir, obj_output_dir, obj_whitelisted in zip( + obj_dirs, obj_output_dirs, is_whitelisted + ) + if obj_whitelisted and not os.path.normpath(obj_output_dir) in done_paths + ] + + failures = {} + for obj_dir in tqdm.tqdm(remaining_objs): + try: + process_object_dir(obj_dir) + except AutomationError as e: + print( + f"Stopping after object {obj_dir} due to non-automatable fixes needed. Please correct these, save, and re-run script to continue." + ) + print(e) + break + except Exception as e: + failures[obj_dir] = str(e) # traceback.format_exc() + else: + # This means we finished iterating without stopping at an object due to a Sanitycheck Error. + print("Finished patching files.") + print(f"Failures: {len(failures)} / {len(remaining_objs)}") + sorted_failure_fns = sorted(failures.keys()) + for i, failure_fn in enumerate(sorted_failure_fns): + print(f"{i + 1} / {len(failures)} - {failure_fn}: {failures[failure_fn]}") + + +if __name__ == "__main__": + fix_legacy_obj_rots() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_map_paths_after_move.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_map_paths_after_move.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b68b6e27227c773ed2304c20e5c4ceab23e196 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/fix_map_paths_after_move.py @@ -0,0 +1,164 @@ +import hashlib +import json +import os +import pathlib +import shutil +import pymxs + +rt = pymxs.runtime + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name + + +def get_maps(root_mat): + maps = set() + + def _recursively_hash_materials_and_textures(mtl): + # print("Recursing into", mtl) + + # We can check for submtls for material instances + if rt.superClassOf(mtl) == rt.Material: + for i in range(rt.getNumSubMtls(mtl)): + sub_mtl = rt.getSubMtl(mtl, i + 1) + if sub_mtl is not None: + _recursively_hash_materials_and_textures(sub_mtl) + + # We can check for subtexmaps for texture maps and materials + if rt.superClassOf(mtl) == rt.textureMap or rt.superClassOf(mtl) == rt.Material: + found_subs = False + for i in range(rt.getNumSubTexmaps(mtl)): + sub_texmap = rt.getSubTexmap(mtl, i + 1) + if sub_texmap is not None: + _recursively_hash_materials_and_textures(sub_texmap) + found_subs = True + + # Only track the texture map if it has no subtexmaps + if rt.superClassOf(mtl) == rt.textureMap and not found_subs: + maps.add(mtl) + + _recursively_hash_materials_and_textures(root_mat) + return maps + + +def fix_maps(): + providers = { + k.split("-")[-1]: v + for k, v in json.loads( + pathlib.Path( + r"D:\BEHAVIOR-1K\asset_pipeline\artifacts\pipeline\object_inventory.json" + ).read_text() + )["providers"].items() + } + current_target = "/".join(pathlib.Path(rt.maxFilePath).parts[-2:]) + current_target_bakery = ( + pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline\cad") / current_target / "bakery" + ) + current_target_textures = ( + pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline\cad") / current_target / "textures" + ) + for obj in rt.objects: + all_texmaps = get_maps(obj.material) + + for texmap in all_texmaps: + if not hasattr(texmap, "filename") or not texmap.filename: + print( + f"Map {texmap} of type {rt.classOf(texmap)} has no filename. Skipping." + ) + continue + + # assert ( + # rt.classOf(texmap) == rt.Bitmaptexture + # ), f"Material map {texmap} has unexpected type {rt.classOf(texmap)}" + + # Check if the map is already under this target. + texmap_filename = pathlib.Path(texmap.filename) + if ( + current_target_bakery in texmap_filename.parents + or current_target_textures in texmap_filename.parents + ): + print( + f"Map {texmap_filename} is already under the target {current_target}. Skipping.", + ) + continue + + # If the map is not under the target, we need to move it. + # First, check if it's found exactly at the provided path, or some other available path. + if texmap_filename.exists(): + # If it's available at the provided path, use that. + orig_map_path = texmap_filename + elif ( + hasattr(texmap, "bitmap") + and texmap.bitmap is not None + and pathlib.Path(texmap.bitmap.filename).exists() + ): + # Otherwise, if the path was resolved somehow by 3ds Max, use that. + orig_map_path = pathlib.Path(texmap.bitmap.filename) + else: + # Otherwise, try to resolve in the original provider's directory. + # Get the original provider for the object + parsed_name = parse_name(obj.name) + if not parsed_name: + print( + f"Could not parse name for object {obj.name}. Skipping map {texmap_filename}." + ) + continue + + model_id = parsed_name.group("model_id") + original_provider = providers.get(model_id, None) + if not original_provider: + print( + f"Could not find original provider for model ID {model_id}. Skipping map {texmap_filename}." + ) + continue + + # Use os.path.abspath which normalizes + absolutifies the paths but does not resolve symlinks unlike pathlib (problem with dvc) + map_filename = texmap_filename.name + map_directory = ( + "bakery" if "bakery" in texmap_filename.parts else "textures" + ) + orig_map_path = ( + pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline\cad") + / original_provider + / map_directory + / map_filename + ) + if not orig_map_path.exists(): + print( + f"Map {texmap_filename} does not exist at {orig_map_path}. Skipping.", + ) + continue + + # Compute the hash of the map file + with open(orig_map_path, "rb") as f: + map_hash = hashlib.md5(f.read()).hexdigest() + + # Generate a brand new path for the map file. Prefix the filename with the hash if it's not in the bakery directory. + new_map_directory = ( + "bakery" if "bakery" in orig_map_path.parts else "textures" + ) + new_map_filename = ( + f"{map_hash}_{orig_map_path.name}" + if new_map_directory == "textures" + else orig_map_path.name + ) + new_map_path = ( + pathlib.Path(r"D:\BEHAVIOR-1K\asset_pipeline\cad") + / current_target + / new_map_directory + / new_map_filename + ) + + if not new_map_path.exists(): + print("Copying map from", orig_map_path, "to", new_map_path) + shutil.copyfile(orig_map_path, new_map_path) + + # Then update the path in the bitmap texture + texmap.filename = str(new_map_path) + + +if __name__ == "__main__": + fix_maps() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/flat_floor_to_cmesh.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/flat_floor_to_cmesh.py new file mode 100644 index 0000000000000000000000000000000000000000..15b2afb9498f1d5d241263bace90adf506455ac4 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/flat_floor_to_cmesh.py @@ -0,0 +1,119 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import b1k_pipeline.utils + +import pymxs +import numpy as np + +rt = pymxs.runtime + + +def flat_floor_to_cmesh(collision_objs, target): + # for obj in collision_objs: + # assert rt.classOf(obj) in [ + # rt.Line, + # rt.Plane, + # ], f"Object {obj.name} is not a line or plane" + + # Convert all the objects to editable poly + for obj in collision_objs: + rt.addmodifier(obj, rt.Edit_Poly()) + rt.maxOps.collapseNodeTo(obj, 1, True) + + # Attach all of them to the first obj + baseObj = collision_objs[0] + for obj in collision_objs[1:]: + rt.polyop.attach(baseObj, obj) + + # Decide which axis we're going to extrude along + points = np.array( + rt.polyop.getVerts( + baseObj.baseObject, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(baseObj)) + ) + ) + bbox_min, bbox_max = np.min(points, axis=0), np.max(points, axis=0) + bbox_extent = bbox_max - bbox_min + print("Bbox extents:", bbox_extent) + extrusion_axis = int(np.argmin(bbox_extent)) + + # Make the points planar + print("Planarizing along", "xyz"[extrusion_axis], "axis") + plane_normal = np.zeros(3) + plane_normal[extrusion_axis] = 1 + rt.polyop.moveVertsToPlane( + baseObj.baseObject, + list(range(1, len(points) + 1)), + rt.Point3(*plane_normal.tolist()), + float(np.mean(points[:, extrusion_axis])), + ) + + # Flip the faces' normals for extrusion + nm = rt.NormalModifier() + nm.flip = True + rt.addmodifier(baseObj, nm) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # Select all the faces + rt.polyop.setFaceSelection( + baseObj, list(range(1, rt.polyop.getNumFaces(baseObj) + 1)) + ) + + # Apply the Face Extrusion modifier + fe = rt.Face_Extrude() + fe.amount = 300 + rt.addmodifier(baseObj, fe) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # Convert to editable poly again + rt.addmodifier(baseObj, rt.Edit_Poly()) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # And then cap holes + rt.addmodifier(baseObj, rt.Cap_Holes()) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # Triangulate the faces + ttp = rt.Turn_To_Poly() + ttp.limitPolySize = True + ttp.maxPolySize = 3 + rt.addmodifier(baseObj, ttp) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # Parent the collision object to the target object + baseObj.parent = target + + # Rename the first object to match the selected object + baseObj.name = target.name + "-Mcollision" + + # Validate that the object name is valid + assert ( + b1k_pipeline.utils.parse_name(baseObj.name) is not None + ), f"Done, but please fix invalid name {baseObj.name} for collision object" + + return baseObj + + +def select_and_flat_floor_to_cmesh(): + collision_objs = list(rt.selection) + + # Ask the user to pick a target object + target = rt.pickobject() + + # Merge the collision objects + flat_floor_to_cmesh(collision_objs, target) + + +def flat_floor_to_cmesh_button(): + try: + select_and_flat_floor_to_cmesh() + # rt.messageBox("Success!") + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + flat_floor_to_cmesh_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_camera_images.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_camera_images.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec5381d54abf91c1415aeab18f791c87df25c42 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_camera_images.py @@ -0,0 +1,81 @@ +import json +import os +import re +from collections import Counter + +import pymxs + +rt = pymxs.runtime + +PATTERN = re.compile( + r"^(?PB-)?(?PF-)?(?PL-)?(?P[a-z_]+)-(?P[A-Za-z0-9_]+)-(?P[0-9]+)(?:-(?P[a-z0-9_]+))?(?:-(?P[A-Za-z0-9_]+)-(?P[RP])-(?Plower|upper))?(?:-L(?P[0-9]+))?(?:-M(?P[a-z]+)_(?P[0-9]+))?$" +) +OUTPUT_DIR = "camera_images" +OUTPUT_FILENAME = "{0}.png" +SUCCESS_FILENAME = "generate_camera_images.success" +RENDER_PRESET_FILENAME = os.path.abspath( + os.path.join( + os.path.dirname(os.path.dirname(__file__)), "render_presets", "scene_camera.rps" + ) +) + + +def main(): + success = False + + artifacts_dir = os.path.join(rt.maxFilePath, "artifacts") + output_dir = os.path.join(artifacts_dir, OUTPUT_DIR) + os.makedirs(output_dir, exist_ok=True) + + # Set the render preset + preset_categories = rt.renderpresets.LoadCategories(RENDER_PRESET_FILENAME) + assert rt.renderpresets.Load(0, RENDER_PRESET_FILENAME, preset_categories) + + # Unhide everything + # for x in rt.objects: + # x.isHidden = False + + # Hide the upper joints + for x in rt.objects: + match = PATTERN.fullmatch(x.name) + if match is not None and ( + match.group("joint_side") == "upper" or "light" in match.group("category") + ): + x.isHidden = True + + # Prepare the viewport + camera_id = "diag" # TODO: make this into a loop later. + (camera,) = [x for x in rt.objects if x.name == f"camera-{camera_id}"] + + assert rt.viewport.setLayout(rt.Name("layout_1")) + assert rt.viewport.setCamera(camera) + + # Set the exposure control + ec = rt.VRay_Exposure_Control() + ec.mode = 106 + ec.ev = -2 + # rt.SceneExposureControl.exposurecontrol = rt.Automatic_Exposure_Control() + # rt.lightLevel = 3.0 + # rt.lightTintColor = rt.Color(255, 227, 196) + + # Set the lights to be fixed for now + for light in rt.lights: + light.isHidden = True + # light.normalizeColor = 1 + # light.multiplier = 15000 + + # Render + image_path = os.path.abspath( + os.path.join(output_dir, OUTPUT_FILENAME.format(camera_id)) + ) + if os.path.exists(image_path): + os.remove(image_path) + print("Saving to", image_path) + assert pymxs.runtime.render(outputFile=image_path) + + with open(os.path.join(artifacts_dir, SUCCESS_FILENAME), "w") as f: + pass + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_containers.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_containers.py new file mode 100644 index 0000000000000000000000000000000000000000..0af2b0d0dd5542e02fc2536f4b1071831277f4d3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_containers.py @@ -0,0 +1,191 @@ +import collections +import os +import pymxs + +rt = pymxs.runtime + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import b1k_pipeline.utils + +import csv +import string +import random +from PIL import Image, ImageDraw, ImageFont +import textwrap +import tqdm + + +def generate_texture(label, path): + # create an image + out = Image.new("RGB", (1000, 500), (255, 255, 255)) + HEIGHT = out.height + WIDTH = out.width + + lines = textwrap.wrap(label, 12) + assert len(lines) <= 3 + text = "\n".join(lines) + FONT_SIZE = 172 + fnt = ImageFont.truetype("impact.ttf", FONT_SIZE, encoding="unic") + d = ImageDraw.Draw(out) + d.multiline_text( + (WIDTH // 2, HEIGHT // 2), + text, + font=fnt, + anchor="mm", + align="center", + fill=(30, 30, 30), + ) + + out.save(path) + + +def generate_container(cat, label, base_model, last_seen_id): + # Find the stuff belonging to the base + base_objs = [x for x in rt.objects if base_model in x.name] + children = [x for x in rt.objects if x not in base_objs and x.parent in base_objs] + assert base_objs, f"Could not find any objects with ID {base_model}" + + # Compile the basename for replacement + base_cat = b1k_pipeline.utils.parse_name(base_objs[0].name).group("category") + base_name = f"{base_cat}-{base_model}" + + # What will this object be called? + new_id = "".join(random.choices(string.ascii_lowercase, k=6)) + new_name = f"{cat}-{new_id}" + + # Generate the new objects. Everything that contains the base name will be copied. + # Everything that doesn't can get instanced. + base_copies = [] # (old, new, expectedparentname) + for base_obj in base_objs: + success, base_copy = rt.maxOps.cloneNodes( + base_obj, + cloneType=rt.name("copy"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {base_obj.name}" + (base_copy,) = base_copy + base_copy.name = base_obj.name.replace(base_name, new_name) + expected_parent_name = ( + base_obj.parent.name.replace(base_name, new_name) + if base_obj.parent is not None + else None + ) + base_copies.append((base_obj, base_copy, expected_parent_name)) + + children_copies = [] # (old, new, expectedparentname) + for child in children: + success, child_copy = rt.maxOps.cloneNodes( + child, + cloneType=rt.name("instance"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {child.name}" + (child_copy,) = child_copy + + # Compute the new model ID for the child + child_model = b1k_pipeline.utils.parse_name(child.name).group("model_id") + child_old_iid = b1k_pipeline.utils.parse_name(child.name).group("instance_id") + child_new_iid = last_seen_id[child_model] + 1 + last_seen_id[child_model] = child_new_iid + + # Update the name + child_copy.name = child.name.replace(f"-{child_old_iid}-", f"-{child_new_iid}-") + expected_parent_name = ( + child.parent.name.replace(base_name, new_name) + if child.parent is not None + else None + ) + children_copies.append((child, child_copy, expected_parent_name)) + + # Check that everything that shows up in the parent is appropriately parented + for _, item, parent_name in base_copies + children_copies: + if not parent_name: + continue + parent_candidates = [x for _, x, _ in base_copies if x.name == parent_name] + assert parent_candidates, f"Could not find parent {parent_name} for {item.name}" + (parent,) = parent_candidates + item.parent = parent + + # Replace any uppers with an instance of the lower + for i in range(len(base_copies)): + entry = base_copies[i] + item = entry[1] + if b1k_pipeline.utils.parse_name(item.name).group("joint_side") != "upper": + continue + lower_name = item.name.replace("upper", "lower") + lower_candidates = [ + x for _, x, _ in base_copies + children_copies if x.name == lower_name + ] + assert lower_candidates, f"Could not find lower {lower_name} for {item.name}" + (lower,) = lower_candidates + + success, lower_copy = rt.maxOps.cloneNodes( + lower, + cloneType=rt.name("instance"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {lower.name}" + (lower_copy,) = lower_copy + lower_copy.transform = item.transform + lower_copy.name = item.name + rt.delete(item) + + base_copies[i] = (entry[0], lower_copy, entry[2]) + + # Find the label object + for _, item, _ in base_copies + children_copies: + if "label" in item.name: + label_obj = item + break + else: + raise AssertionError("Could not find label object") + + # Generate the texture + texture_path = os.path.join(rt.maxFilePath, "textures", f"{cat}.png") + generate_texture(label, texture_path) + + # Create a material + mat = rt.VRayMtl() + label_obj.material = mat + + # Assign the bitmap + bmp = rt.VrayBitmap() + bmp.HDRIMapName = texture_path + mat.texmap_diffuse = bmp + + print("Created", cat) + return [obj for _, obj, _ in base_copies + children_copies] + + +def main(): + with open(r"D:\BEHAVIOR-1K\asset_pipeline\metadata\container_generation.csv") as f: + containers = [] + last_seen_id = collections.defaultdict(int) + for row in tqdm.tqdm(list(csv.DictReader(f))): + if row["Action"] != "GENERATE": + continue + containers.append( + ( + row["Actual Object"], + generate_container( + row["Category"], + row["Label"], + row["Actual Object"], + last_seen_id, + ), + ) + ) + + position_ctr = collections.Counter() + for kind, container_set in containers: + position_ctr[kind] += 1 + for container in container_set: + if container.parent is None: + container.position += rt.Point3(0, position_ctr[kind] * 400, 0) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_cooked_particles.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_cooked_particles.py new file mode 100644 index 0000000000000000000000000000000000000000..41ba4084cf6ad46c3cb79d9f293c6de38d14b9f8 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_cooked_particles.py @@ -0,0 +1,370 @@ +import pymxs + +rt = pymxs.runtime + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name + +SYSTEM_NAMES = [ + "cooked__allspice", + "cooked__almond", + "cooked__black_bean", + "cooked__black_pepper", + "cooked__blueberry", + "cooked__breadcrumb", + "cooked__brown_rice", + "cooked__brown_sugar", + "cooked__cake_mix", + "cooked__cashew", + "cooked__cayenne", + "cooked__chia_seed", + "cooked__chickpea", + "cooked__cinnamon", + "cooked__cinnamon_sugar", + "cooked__clove", + "cooked__cocoa_powder", + "cooked__coconut", + "cooked__coffee_bean", + "cooked__coffee_grounds", + "cooked__coriander", + "cooked__cornstarch", + "cooked__cranberry", + "cooked__crouton", + "cooked__cumin", + "cooked__curry_powder", + "cooked__diced__apple", + "cooked__diced__apricot", + "cooked__diced__arepa", + "cooked__diced__artichoke", + "cooked__diced__arugula", + "cooked__diced__asparagus", + "cooked__diced__auricularia", + "cooked__diced__avocado", + "cooked__diced__bacon", + "cooked__diced__bagel", + "cooked__diced__bagel_dough", + "cooked__diced__baguet", + "cooked__diced__banana", + "cooked__diced__banana_bread", + "cooked__diced__bay_leaf", + "cooked__diced__bean_curd", + "cooked__diced__beefsteak_tomato", + "cooked__diced__beet", + "cooked__diced__bell_pepper", + "cooked__diced__biscuit_dough", + "cooked__diced__blackberry", + "cooked__diced__bok_choy", + "cooked__diced__bratwurst", + "cooked__diced__brisket", + "cooked__diced__broccoli", + "cooked__diced__broccoli_rabe", + "cooked__diced__broccolini", + "cooked__diced__brownie", + "cooked__diced__brussels_sprouts", + "cooked__diced__burrito", + "cooked__diced__butter_cookie", + "cooked__diced__buttermilk_pancake", + "cooked__diced__butternut_squash", + "cooked__diced__cantaloup", + "cooked__diced__carne_asada", + "cooked__diced__carrot", + "cooked__diced__cauliflower", + "cooked__diced__celery", + "cooked__diced__chanterelle", + "cooked__diced__chard", + "cooked__diced__cheese_tart", + "cooked__diced__cheesecake", + "cooked__diced__cherry", + "cooked__diced__cherry_tomato", + "cooked__diced__chestnut", + "cooked__diced__chicken", + "cooked__diced__chicken_breast", + "cooked__diced__chicken_leg", + "cooked__diced__chicken_tender", + "cooked__diced__chicken_wing", + "cooked__diced__chili", + "cooked__diced__chives", + "cooked__diced__chocolate_biscuit", + "cooked__diced__chocolate_cake", + "cooked__diced__chocolate_chip_cookie", + "cooked__diced__chocolate_cookie_dough", + "cooked__diced__chorizo", + "cooked__diced__cinnamon_roll", + "cooked__diced__clove", + "cooked__diced__club_sandwich", + "cooked__diced__coconut", + "cooked__diced__cold_cuts", + "cooked__diced__cookie_dough", + "cooked__diced__crab", + "cooked__diced__crayfish", + "cooked__diced__crescent_roll", + "cooked__diced__cucumber", + "cooked__diced__danish", + "cooked__diced__date", + "cooked__diced__doughnut", + "cooked__diced__dried_apricot", + "cooked__diced__duck", + "cooked__diced__durian", + "cooked__diced__edible_cookie_dough", + "cooked__diced__eggplant", + "cooked__diced__enchilada", + "cooked__diced__fennel", + "cooked__diced__fillet", + "cooked__diced__frank", + "cooked__diced__frankfurter_bun", + "cooked__diced__french_fries", + "cooked__diced__french_toast", + "cooked__diced__fruitcake", + "cooked__diced__garlic_bread", + "cooked__diced__gelatin", + "cooked__diced__ginger", + "cooked__diced__gingerbread", + "cooked__diced__gooseberry", + "cooked__diced__gourd", + "cooked__diced__granola_bar", + "cooked__diced__grapefruit", + "cooked__diced__green_bean", + "cooked__diced__green_onion", + "cooked__diced__ham_hock", + "cooked__diced__hamburger", + "cooked__diced__hamburger_bun", + "cooked__diced__hard_boiled_egg", + "cooked__diced__hazelnut", + "cooked__diced__head_cabbage", + "cooked__diced__hip", + "cooked__diced__hotdog", + "cooked__diced__huitre", + "cooked__diced__kabob", + "cooked__diced__kale", + "cooked__diced__kielbasa", + "cooked__diced__kiwi", + "cooked__diced__lamb", + "cooked__diced__leek", + "cooked__diced__lemon", + "cooked__diced__lemon_peel", + "cooked__diced__lettuce", + "cooked__diced__lime", + "cooked__diced__lobster", + "cooked__diced__macaroon", + "cooked__diced__mango", + "cooked__diced__marshmallow", + "cooked__diced__meat_loaf", + "cooked__diced__meatball", + "cooked__diced__melon", + "cooked__diced__muffin", + "cooked__diced__mushroom", + "cooked__diced__mustard", + "cooked__diced__nectarine", + "cooked__diced__olive", + "cooked__diced__omelet", + "cooked__diced__onion", + "cooked__diced__orange", + "cooked__diced__papaya", + "cooked__diced__parsley", + "cooked__diced__parsnip", + "cooked__diced__pastry", + "cooked__diced__peach", + "cooked__diced__pear", + "cooked__diced__peppermint", + "cooked__diced__pepperoni", + "cooked__diced__pieplant", + "cooked__diced__pineapple", + "cooked__diced__pita", + "cooked__diced__pizza", + "cooked__diced__pizza_dough", + "cooked__diced__plum", + "cooked__diced__pomegranate", + "cooked__diced__pomelo", + "cooked__diced__pork", + "cooked__diced__porkchop", + "cooked__diced__potato", + "cooked__diced__prawn", + "cooked__diced__prosciutto", + "cooked__diced__pumpkin", + "cooked__diced__quail", + "cooked__diced__quiche", + "cooked__diced__radish", + "cooked__diced__ramen", + "cooked__diced__rib", + "cooked__diced__roast_beef", + "cooked__diced__roll_dough", + "cooked__diced__rutabaga", + "cooked__diced__salmon", + "cooked__diced__scone", + "cooked__diced__shiitake", + "cooked__diced__snapper", + "cooked__diced__sour_bread", + "cooked__diced__spice_cookie", + "cooked__diced__spice_cookie_dough", + "cooked__diced__spinach", + "cooked__diced__squid", + "cooked__diced__steak", + "cooked__diced__strawberry", + "cooked__diced__sugar_cookie", + "cooked__diced__sugar_cookie_dough", + "cooked__diced__sushi", + "cooked__diced__sweet_corn", + "cooked__diced__taco", + "cooked__diced__tenderloin", + "cooked__diced__toast", + "cooked__diced__tofu", + "cooked__diced__tomato", + "cooked__diced__tortilla", + "cooked__diced__tortilla_chip", + "cooked__diced__trout", + "cooked__diced__tuna", + "cooked__diced__turkey", + "cooked__diced__turkey_leg", + "cooked__diced__vanilla", + "cooked__diced__veal", + "cooked__diced__venison", + "cooked__diced__vidalia_onion", + "cooked__diced__virginia_ham", + "cooked__diced__waffle", + "cooked__diced__walnut", + "cooked__diced__watermelon", + "cooked__diced__white_turnip", + "cooked__diced__whole_garlic", + "cooked__diced__yam", + "cooked__diced__zucchini", + "cooked__dog_food", + "cooked__flour", + "cooked__ginger", + "cooked__granola", + "cooked__granulated_salt", + "cooked__green_tea", + "cooked__ground_beef", + "cooked__ground_coffee", + "cooked__instant_coffee", + "cooked__jelly_bean", + "cooked__jerk_seasoning", + "cooked__jimmies", + "cooked__kidney_bean", + "cooked__lemon_pepper_seasoning", + "cooked__marjoram", + "cooked__mustard_seed", + "cooked__noodle", + "cooked__nutmeg", + "cooked__oat", + "cooked__onion_powder", + "cooked__orzo", + "cooked__paprika", + "cooked__pea", + "cooked__peanut", + "cooked__pecan", + "cooked__penne", + "cooked__pine_nut", + "cooked__pistachio", + "cooked__popcorn", + "cooked__pumpkin_pie_spice", + "cooked__pumpkin_seed", + "cooked__quinoa", + "cooked__raisin", + "cooked__ravioli", + "cooked__saffron", + "cooked__sage", + "cooked__salt", + "cooked__scrambled_eggs", + "cooked__sesame_seed", + "cooked__soy", + "cooked__sunflower_seed", + "cooked__thyme", + "cooked__tomato_rice", + "cooked__white_rice", +] + + +def generate_for_particle(p): + # Get the old and new category names + pn = parse_name(p.name) + assert pn, f"Failed to parse name for {p.name}" + uncooked_system = pn.group("category") + cooked_system = "cooked__" + uncooked_system + assert ( + cooked_system in SYSTEM_NAMES + ), f"Cooked system {cooked_system} not in SYSTEM_NAMES" + + # Get the old and new model IDs + old_model_id = pn.group("model_id") + new_model_id = "cp" + old_model_id[:-2] # Prefix the old model ID with cp + + # Get the child collision mesh + assert ( + len(p.children) == 1 + ), f"Expected one child for {p.name}, found {len(p.children)}" + collision_mesh = p.children[0] + assert ( + "Mcollision" in collision_mesh.name + ), f"Expected collision mesh for {p.name} to have 'Mcollision' in its name, found {collision_mesh.name}" + + # Clone both the particle and the collision mesh + success, base_copy = rt.maxOps.cloneNodes( + p, + cloneType=rt.name("copy"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {p.name}" + (base_copy,) = base_copy + success, collision_copy = rt.maxOps.cloneNodes( + collision_mesh, + cloneType=rt.name("copy"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {p.name}" + (collision_copy,) = collision_copy + + # Update the names + base_copy.name = p.name.replace(uncooked_system, cooked_system).replace( + old_model_id, new_model_id + ) + collision_copy.name = collision_mesh.name.replace( + uncooked_system, cooked_system + ).replace(old_model_id, new_model_id) + + # Set the parent of the collision mesh to the particle + collision_copy.parent = base_copy + + # Find the tint material + tint_mtl = rt.sceneMaterials["cooked_tint"] + assert tint_mtl, "Could not find 'cooked_tint' material in scene materials" + + # Create a new blend material + mtl = rt.VRayBlendMtl() + mtl.name = f"{base_copy.name}-blend" + mtl.baseMtl = ( + base_copy.material.originalMaterial + if rt.classOf(base_copy.material) == rt.Shell_Material + else base_copy.material + ) + mtl.coatMtl[0] = tint_mtl + base_copy.material = mtl + + # Also slightly move the particle (up 1x its y size) + bbox_min, bbox_max = rt.nodeGetBoundingBox(base_copy, rt.Matrix3(1)) + y_size = bbox_max.y - bbox_min.y + base_copy.position += rt.Point3(0, y_size + 10, 0) + + +def main(): + for cooked_system in SYSTEM_NAMES: + # Find the particle + uncooked_system = cooked_system.replace("cooked__", "") + candidates = [ + x + for x in rt.objects + if ( + not x.parent + and parse_name(x.name) + and parse_name(x.name).group("category") == uncooked_system + ) + ] + for candidate in candidates: + print(f"Generating for {cooked_system} ({candidate.name})") + generate_for_particle(candidate) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_fillable_volume.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_fillable_volume.py new file mode 100644 index 0000000000000000000000000000000000000000..7877616b1ef693071e3e54320a9b92ac666d9c07 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_fillable_volume.py @@ -0,0 +1,509 @@ +import pymxs + +rt = pymxs.runtime + +import numpy as np +from scipy.spatial.transform import Rotation as R +import trimesh +from collections import defaultdict +from scipy.spatial import ConvexHull +import networkx as nx + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name +from b1k_pipeline.max.collision_vertex_reduction import reduce_mesh + +REQUIRE_ADDITIONAL_BASE_POINTS = False + + +def anorm(x, axis=None, keepdims=False): + """Compute L2 norms alogn specified axes.""" + return np.linalg.norm(x, axis=axis, keepdims=keepdims) + + +def normalize(v, axis=None, eps=1e-10): + """L2 Normalize along specified axes.""" + norm = anorm(v, axis=axis, keepdims=True) + return v / np.where(norm < eps, eps, norm) + + +def convert_to_trimesh(obj): + # Get vertices and faces into numpy arrays for conversion + verts = np.array( + [rt.polyop.getVert(obj, i + 1) for i in range(rt.polyop.GetNumVerts(obj))] + ) + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + m = trimesh.Trimesh(vertices=verts, faces=faces, process=False) + assert m.is_volume, f"{obj.name} element is not a volume" + + return m + + +def vecs2quat(vec0, vec1, normalized=False): + """ + Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into a quaternion representation of the angle + + Args: + vec0 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized + vec1 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized + normalized (bool): If True, @vec0 and @vec1 are assumed to already be normalized and we will skip the + normalization step (more efficient) + """ + # Normalize vectors if requested + if not normalized: + vec0 = normalize(vec0, axis=-1) + vec1 = normalize(vec1, axis=-1) + + # Half-way Quaternion Solution -- see https://stackoverflow.com/a/11741520 + cos_theta = np.sum(vec0 * vec1, axis=-1, keepdims=True) + quat_unnormalized = np.where( + cos_theta == -1, + np.array([1.0, 0, 0, 0]), + np.concatenate([np.cross(vec0, vec1), 1 + cos_theta], axis=-1), + ) + return quat_unnormalized / np.linalg.norm(quat_unnormalized, axis=-1, keepdims=True) + + +def sample_radial_rays(tm, point, normal, n=40, dist=4.0): + """ + Shoots @n rays radially from @point in directions orthogonal to @normal, returning any hits with @tm within @dist + + Args: + tm (Trimesh): mesh used to sample rays + point (3-array): (x,y,z) origin point of rays + normal (3-array): normal direction of the plane for sampling radial rays + n (int): number of rays to shoot + dist (float): max distance of rays + + Returns: + 2-tuple: + - float: Proportion of rays cast that returned a valid hit + - dict: Index-mapped hit (x,y,z) locations + """ + angles = np.arange(n) * 2 * np.pi / n + x = np.cos(angles) + y = np.sin(angles) + start_points = np.ones((n, 3)) * point.reshape(1, 3) + directions = np.array([x, y, np.zeros(n)]).T + + # Rotate points appropriately + rot = R.from_quat(vecs2quat(np.array([0, 0, 1.0]), np.array(normal))).as_matrix() + directions = directions @ rot.T + + # Run raytest + locations, index_ray, index_tri = tm.ray.intersects_location( + ray_origins=start_points, + ray_directions=directions, + ) + + results = defaultdict(list) + + # Loop through all hits, and add to results + for location, idx in zip(locations, index_ray): + results[idx].append(location) + + # Filter out for closest + pruned_results = dict() + for i in range(n): + if i in results: + result = results[i] + dist = np.linalg.norm(np.array(result) - point.reshape(1, 3), axis=-1) + min_idx = np.argmin(dist) + pruned_results[i] = result[min_idx] + + # Return pruned results + return len(pruned_results) / n, pruned_results + + +def shoot_ray(tm, point, direction): + """ + Shoots a single ray from @start_point in direction @direction + + Args: + tm (Trimesh): mesh used to shoot ray + point (3-array): (x,y,z) origin point of ray + direction (3-array): direction to shoot ray + + Returns: + None or np.ndarray: None if no hit, else (x,y,z) location of nearest hit + """ + # Run raytest + locations, index_ray, index_tri = tm.ray.intersects_location( + ray_origins=point.reshape(1, 3), + ray_directions=direction.reshape(1, 3), + ) + + if len(locations) == 0: + hit = None + else: + # Only keep closest + dists = np.linalg.norm(np.array(locations) - point.reshape(1, 3), axis=-1) + min_idx = np.argmin(dists) + hit = locations[min_idx] + + return hit + + +def sample_fillable_volume( + tm, + start_point, + direction=(0, 0, 1.0), + hit_threshold=0.75, + n_rays=100, +): + """ + Samples fillable volume within a given mesh @tm's cavity using raycasting + + Args: + tm (Trimesh): Trimesh mesh to within which to sample fillable + start_point (3-array): (x,y,z) value used as seed starting point within the mesh + direction (3-array): (x,y,z) direction vector determining which direction raycasting should occur + hit_threshold (float): Proportion of rays that should hit each iteration of the fillable volume generation + for generation to continue + n_rays (int): Number of radial rays to shoot during each iteration. Must be divisible by 4! + + Returns: + Trimesh: The sampled trimesh fillable volume + """ + n_rays_half = int(n_rays / 2) + n_rays_quarter = int(n_rays / 4) + + # Make sure n_rays is divisible by 4 + assert n_rays_half == n_rays / 2.0 + assert n_rays_quarter == n_rays / 4.0 + + # Shoot rays at the initial start point + direction = np.array(direction) + prop_hit, hits = sample_radial_rays( + tm=tm, point=start_point, normal=direction, n=n_rays + ) + all_points = np.array([hit for hit in hits.values()]) + if not prop_hit >= hit_threshold: + print( + f"Expected at least {hit_threshold} raycast hits, got {prop_hit} instead." + ) + # Plot the pruned results + sources = np.stack([start_point] * len(hits), axis=0) + rays = np.stack([sources, all_points], axis=1) + trimesh_path = trimesh.load_path(rays) + trimesh.Scene([tm, trimesh_path]).show() + + # Move point to centroid of all points of circle + center = all_points.mean(axis=0) + + # Shoot ray in downwards direction, make sure we hit some surface + bottom_hit = shoot_ray(tm=tm, point=center, direction=-direction) + assert ( + bottom_hit is not None + ), "Got no valid hit when trying to shoot ray towards opposite direction!" + + # Find top hit by shooting ray in positive @direction + top_hit = shoot_ray(tm=tm, point=center, direction=direction) + if top_hit is None: + # Only when shooting up, we are OK hitting the convex hull. try that + top_hit = shoot_ray(tm=tm.convex_hull, point=center, direction=direction) + assert ( + top_hit is not None + ), "Got no valid hit within convex hull when trying to shoot ray towards positive direction!" + + # Transform mesh to such that z points in @direction, and compute average diameter in this direction + tf = np.eye(4) + rot = R.from_quat(vecs2quat(np.array([0, 0, 1.0]), np.array(direction))).as_matrix() + tf[:3, :3] = rot + tm.apply_transform(tf) + bbox_min_rot, bbox_max_rot = tm.bounding_box.bounds + bbox_extent_rot = bbox_max_rot - bbox_min_rot + avg_diameter = np.mean(bbox_extent_rot[:2]) + min_diameter = avg_diameter / 5.0 + offset = min( + 0.005, avg_diameter / 20.0 + ) # Offset to prevent direct collisions. Defaults to 5mm + + # Make sure to rotate trimesh mesh back + tf_inv = np.eye(4) + tf_inv[:3, :3] = rot.T + tm.apply_transform(tf_inv) + + # Starting at the bottom, sample points radially and iteratively move in @direction + mesh_points = np.array([]).reshape(0, 3) + + total_distance = np.linalg.norm(top_hit - bottom_hit) - (offset / 2.0) + delta = 0.005 + delta = np.clip( + delta, total_distance / 20, total_distance / 3 + ) # between 3 and 20 entries + i = 0 + + cur_distance = offset / 2.0 + + while cur_distance <= total_distance: + point = bottom_hit + cur_distance * direction + prop_hit, hits = sample_radial_rays( + tm=tm, point=point, normal=direction, n=n_rays + ) + if prop_hit < hit_threshold: + if i == 0: + # Failed to sample at all, probably a degenerate mesh, so raise an error + raise ValueError("Failed to sample any valid points!") + # Terminate, this is assumed to be the end of a valid sampleable volume + break + + # Get all hit positions transformed into rotated direction + positions = np.array([hit for hit in hits.values()]) + positions_rot = positions @ rot.T + # If the distance between points is less than a threshold, also break + if len(mesh_points) > 0 and np.any( + (positions_rot.max(axis=0)[:2] - positions_rot.min(axis=0)[:2]) + < min_diameter + ): + break + + # Compute points -- slightly offset them by @offset so they don't directly collide with edge + layer_rays = positions - point.reshape(1, 3) + layer_points = positions - offset * layer_rays / np.linalg.norm(layer_rays) + mesh_points = np.concatenate([mesh_points, layer_points], axis=0) + cur_distance += delta + i += 1 + + # Prune previous layer + mesh_points = mesh_points[: -len(layer_points)] + + # Make sure we have nonzero set of points + assert ( + len(mesh_points) > 0 + ), "Got no valid mesh points for generating fillable mesh!" + + if REQUIRE_ADDITIONAL_BASE_POINTS: + # 5. Create fillable trimesh + tm_fillable_tmp = trimesh.Trimesh(vertices=np.array(mesh_points)) + + # Rotate it so that the z-axis points in @direction + tm_fillable_tmp.apply_transform(tf) + + # 6. Create convex hull + ctm_rot = tm_fillable_tmp.convex_hull + ctm_rot_unmerged = ctm_rot.copy() + ctm_rot_unmerged.unmerge_vertices() + + # 7. Take the projection of the convex hull with normal @direction (which, since already rotated, is simply + # [0, 0, 1]), and then sample rays shooting against that normal to compensate for the original offset + # We know the bounding box is [1, 1, 1], so sample points uniformly in XY plane + proj = ConvexHull(ctm_rot_unmerged.vertices[:, :2].copy()) + equations = np.array(proj.equations, dtype=np.float32) + + n_dim_samples = 10 + ctm_rot_min, ctm_rot_max = ctm_rot_unmerged.bounding_box.bounds + x_range = np.linspace(ctm_rot_min[0], ctm_rot_max[0], n_dim_samples) + y_range = np.linspace(ctm_rot_min[1], ctm_rot_max[1], n_dim_samples) + ray_grid = np.stack(np.meshgrid(x_range, y_range, indexing="ij"), axis=-1) + ray_grid_flattened = ray_grid.reshape(-1, 2) + + # Check which rays are within the polygon + # Each inequality is of the form Ax + By + C <= 0 + # We need to check if the point satisfies all inequalities + is_within = np.all( + (ray_grid_flattened @ equations[:, :-1].T) + equations[:, -1] <= 0, axis=1 + ) + xy_ray_positions = ray_grid_flattened[is_within] + + # Shoot these rays downwards and record their poses -- add them to the point set + z_range = np.linspace(bbox_min_rot[2], bbox_max_rot[2], n_dim_samples) + additional_points_rot = [] + for xy_ray_pos in xy_ray_positions: + # Find a corresponding z value within the convex hull to use as the start raycasting point + start_samples = np.zeros((n_dim_samples, 3)) + start_samples[:, :2] = xy_ray_pos + start_samples[:, 2] = z_range + is_contained = ctm_rot.contains(start_samples) + if not np.any(is_contained): + # Just skip this sample + continue + # Use the lowest point (i.e.: the first idx that is True) as the raycasting start point + z = z_range[np.where(is_contained)[0][0]] + + # Raycast downwards and record the hit point + start = np.array([*xy_ray_pos, z]) + hit = shoot_ray( + tm=ctm_rot_unmerged, point=start, direction=np.array([0, 0, -1.0]) + ) + + # If we have a valid hit, record this point + if hit is not None: + additional_points_rot.append(hit) + + assert ( + len(additional_points_rot) > 0 + ), "Failed to generate any additional points for the fillable mesh!" + + # Rotate the points back into the original frame + # Note: forward transform is points @ rot.T so inverse is points @ rot + additional_points = np.array(additional_points_rot) @ rot + + # Append all additional points to our existing set of points + mesh_points = np.concatenate([mesh_points, additional_points], axis=0) + + # Re-write to trimesh and take the finalized convex hull + tm_fillable = trimesh.Trimesh(vertices=np.array(mesh_points)) + + # Return the convex hull of this mesh + return reduce_mesh(tm_fillable.convex_hull) + + +def generate_fillable_mesh_from_seed(is_open): + # Assert that the currently selected object is a seed point + assert ( + len(rt.selection) == 1 + ), "Expected exactly one object (seed point) to be selected" + (seed,) = rt.selection + assert ( + seed.name == "fillable_seed" + ), "Expected the selected object to be the seed point" + assert ( + rt.classOf(seed) == rt.Point + ), "Expected the selected object to be the seed point" + + # Some checks about the target object + target_obj = seed.parent + assert target_obj is not None, "Expected the seed point to have a parent object" + parsed_name = parse_name(target_obj.name) + assert parsed_name, "Failed to parse the name of the target object" + assert not parsed_name.group("bad"), "Expected the target object to not be bad" + assert ( + parsed_name.group("instance_id") == "0" + ), "Expected the target object to be the 0 instance" + assert not parsed_name.group( + "meta_type" + ), "Expected the target object to not have a meta type" + assert ( + parsed_name.group("joint_side") != "upper" + ), "Expected the target object to not be an upper joint" + target_link_name = parsed_name.group("link_name") or "base_link" + + # Get the position and orientation info + start_point = np.array(seed.position) + up_dir = np.array(rt.Point3(0, 0, 1.0) * seed.rotation) + + # Browse the entire scene to find the articulation tree of the target object + articulation_tree = nx.DiGraph() + link_objs = {} + for obj in rt.objects: + candidate_parsed_name = parse_name(obj.name) + if not candidate_parsed_name: + continue + if candidate_parsed_name.group("model_id") != parsed_name.group("model_id"): + continue + if candidate_parsed_name.group("instance_id") != parsed_name.group( + "instance_id" + ): + continue + if candidate_parsed_name.group("bad"): + continue + if candidate_parsed_name.group("meta_type"): + continue + if candidate_parsed_name.group("joint_side") == "upper": + continue + link_name = candidate_parsed_name.group("link_name") or "base_link" + + # Assert that it has a collision mesh + collision_mesh_objects = [] + for child in obj.children: + if rt.classOf(child) == rt.Editable_Poly and "Mcollision" in child.name: + collision_mesh_objects.append(child) + assert ( + len(collision_mesh_objects) == 1 + ), f"Expected {obj.name} to have exactly one collision mesh" + collision_mesh_object = collision_mesh_objects[0] + + # Add it into the graph + articulation_tree.add_node(link_name) + link_objs[link_name] = collision_mesh_object + if link_name != "base_link": + parent_link_name = candidate_parsed_name.group("parent_link_name") + articulation_tree.add_edge(parent_link_name, link_name) + + # Get all the descendants of the target link. These will be used when computing the fillable volume + links_to_include = set(nx.descendants(articulation_tree, target_link_name)) | { + target_link_name + } + collision_mesh_objects_to_include = [ + link_objs[link_name] for link_name in links_to_include + ] + + # Convert to trimesh + tm = trimesh.util.concatenate( + [convert_to_trimesh(col_obj) for col_obj in collision_mesh_objects_to_include] + ) + + # Scale by 1/1000 to match canonical scale requirements + scale_mat = np.eye(4) + scale_mat[:3, :3] *= 1e-3 + tm.apply_transform(scale_mat) + + if is_open: + tm = trimesh.util.concatenate([tm, tm.convex_hull]) + + tm.export(r"D:\tmp\fillable.obj") + + fillable_hull = sample_fillable_volume( + tm=tm, + start_point=start_point / 1000.0, # Scale to meters + direction=up_dir, + hit_threshold=0.75, + n_rays=100, + ) + + # Scale back to original scale + scale_mat_inv = np.eye(4) + scale_mat_inv[:3, :3] *= 1e3 + fillable_hull.apply_transform(scale_mat_inv) + + # Check if the appropriate kind of fillable obj exists already, if not, create it + fillable_kind = "Mopenfillable" if is_open else "Mfillable" + fillable_obj = None + for candidate in target_obj.children: + if ( + rt.classOf(candidate) == rt.Editable_Poly + and fillable_kind in candidate.name + ): + fillable_obj = candidate + break + + if not fillable_obj: + fillable_obj = rt.Editable_Mesh() + rt.ConvertToPoly(fillable_obj) + fillable_obj.name = f"{parsed_name.group('mesh_basename')}-{fillable_kind}" + fillable_obj.rotation = target_obj.rotation + fillable_obj.position = target_obj.position + fillable_obj.wirecolor = rt.yellow + fillable_obj.parent = target_obj + + # Add the vertices + vertex_idxes = [] # map from trimesh vertex idxes to max vertex idxes + for v in fillable_hull.vertices: + vertex_idxes.append(rt.polyop.createVert(fillable_obj, rt.Point3(*v.tolist()))) + + # Add the faces + for f in fillable_hull.faces: + face = [vertex_idxes[v] for v in f] + rt.polyop.createPolygon(fillable_obj, face) + + # Update the mesh to reflect changes + rt.update(fillable_obj) + + return fillable_hull + + +if __name__ == "__main__": + generate_fillable_mesh_from_seed(is_open=False) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_images.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_images.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d364522ab5f5f732d310b6c44ddbf841e0c572 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_images.py @@ -0,0 +1,92 @@ +import json +import os +import re +from collections import Counter + +import pymxs + +rt = pymxs.runtime + +PATTERN = re.compile( + r"^(?PB-)?(?PF-)?(?PL-)?(?P[a-z_]+)-(?P[A-Za-z0-9_]+)-(?P[0-9]+)(?:-(?P[a-z0-9_]+))?(?:-(?P[A-Za-z0-9_]+)-(?P[RP])-(?Plower|upper))?(?:-L(?P[0-9]+))?(?:-M(?P[a-z]+)_(?P[0-9]+))?$" +) +OUTPUT_FILENAME = "top.png" +SUCCESS_FILENAME = "generate_images.success" + +HIDE_CATEGORIES = ["ceilings", "square_light", "room_light", "downlight"] +DONT_ZOOM_CATEGORIES = ["ceilings", "floors", "background", "lawn"] + + +def main(): + success = False + + output_dir = os.path.join(rt.maxFilePath, "artifacts") + os.makedirs(output_dir, exist_ok=True) + + try: + # Set the render preset + preset_path = ( + r"C:\Users\Cem\Documents\3ds Max 2022\renderpresets\imgrender_cpu.rps" + ) + preset_categories = rt.renderpresets.LoadCategories(preset_path) + assert rt.renderpresets.Load(0, preset_path, preset_categories) + + # Unhide everything + # for x in rt.objects: + # x.isHidden = False + + # Hide the ceilings + for x in rt.objects: + match = PATTERN.fullmatch(x.name) + if match is not None and match.group("category").lower() in HIDE_CATEGORIES: + x.isHidden = True + + # Go into top view + assert rt.viewport.setType(rt.Name("view_top")) + + # Center the camera on non-floor, non-ceiling, non-background, non-lawn objects + selection = [] + for x in rt.objects: + if x.isHidden: + continue + + match = PATTERN.fullmatch(x.name) + if ( + match is not None + and match.group("category").lower() not in DONT_ZOOM_CATEGORIES + ): + selection.append(x) + rt.select(selection) + # assert pymxs.runtime.execute('max tool zoomextents') + rt.select([]) + + # Set the exposure control + ec = rt.VRay_Exposure_Control() + ec.mode = 106 + ec.ev = -2 + rt.SceneExposureControl.exposurecontrol = ec + + # Set the lights to be fixed for now + for light in rt.lights: + light.isHidden = True + # light.normalizeColor = 1 + # light.multiplier = 15000 + + # Render + image_path = os.path.abspath(os.path.join(output_dir, OUTPUT_FILENAME)) + if os.path.exists(image_path): + os.remove(image_path) + print("Saving to", image_path) + assert pymxs.runtime.render(outputFile=image_path) + + success = True + except: + pass + + # if success: + # with open(os.path.join(output_dir, SUCCESS_FILENAME), "w") as f: + # pass + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_max_object_images.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_max_object_images.py new file mode 100644 index 0000000000000000000000000000000000000000..690195e0ddc723495aa5b0876c76873d9e4a1e65 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_max_object_images.py @@ -0,0 +1,149 @@ +import json +import os +import re +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from collections import Counter, defaultdict + +from fs.zipfs import ZipFS +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +import b1k_pipeline.utils + + +rt = pymxs.runtime + +SIDES = { + # Facing the object + # "front": R.from_euler("xy", [-np.pi / 2, np.pi / 2]), + # Top down + # "top": R.from_euler("Z", -np.pi / 2), + # Diagonal + "diagonal1": R.from_euler("xy", [-np.pi / 2, np.pi / 2]) + * R.from_euler("XYZ", [0, -np.pi / 6, np.pi / 6]), + "diagonal2": ( + R.from_euler("xy", [-np.pi / 2, np.pi / 2]) + * R.from_euler("XYZ", [0, -np.pi / 6, np.pi / 6]) + ).inv(), + # "top", "left", "right", "front", "back" +} +JSON_FILENAME = "generate_max_object_images.json" + + +# The camera somehow has different axes. +def main(): + output_dir = os.path.join(rt.maxFilePath, "artifacts") + os.makedirs(output_dir, exist_ok=True) + + with ZipFS(os.path.join(output_dir, "max_object_images.zip"), write=True) as zipfs: + # Set the render preset + preset_path = r"C:\Users\Cem\Documents\3ds Max 2022\renderpresets\imgrender.rps" + preset_categories = rt.renderpresets.LoadCategories(preset_path) + assert rt.renderpresets.Load(0, preset_path, preset_categories) + + # Set the exposure control + ec = rt.VRay_Exposure_Control() + ec.mode = 106 + ec.ev = -2 + rt.SceneExposureControl.exposurecontrol = ec + + # Group the objects + failed = [] + groups = defaultdict(list) + + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + + match = b1k_pipeline.utils.parse_name(obj.name) + if match is None: + continue + + if ( + int(match.group("instance_id")) != 0 + or match.group("bad") + or match.group("meta_type") + ): + continue + + groups[ + ( + match.group("category"), + match.group("model_id"), + match.group("instance_id"), + ) + ].append(obj) + + for group_key, group in groups.items(): + try: + # Find the base link obj + matches = [b1k_pipeline.utils.parse_name(obj.name) for obj in group] + bases = [ + obj + for obj, match in zip(group, matches) + if match is not None + and ( + not match.group("link_name") + or match.group("link_name") == "base_link" + ) + ] + (base,) = bases + + # Hide everything + for x in rt.objects: + x.isHidden = True + + # Set the lights to be fixed for now + for light in rt.lights: + light.isHidden = True + # light.normalizeColor = 1 + # light.multiplier = 15000 + + # Unhide the objects in the group + for x in group: + x.isHidden = False + + # Get the object rotation + obj_quat = base.rotation + obj_rot = R.from_quat([obj_quat.x, obj_quat.y, obj_quat.z, obj_quat.w]) + + # Render + for side_name, side_rot in SIDES.items(): + # Switch the side + assert rt.viewport.setType(rt.Name("view_top")) + + # Rotate the camera to match the object. + camera_rot = side_rot * obj_rot.inv() + rt.viewport.rotate( + rt.Quat(*[float(x) for x in camera_rot.as_quat()]) + ) + + # Set the zoom extent + rt.select([]) + rt.select(group) + assert pymxs.runtime.execute("max tool zoomextents") + rt.forceCompleteRedraw() + rt.windows.processPostedMessages() + + # Render the image + obj_name = "-".join(group_key) + output_filename = f"{obj_name}--{side_name}.png" + image_path = zipfs.getsyspath(output_filename) + if os.path.exists(image_path): + os.remove(image_path) + print("Saving to", image_path) + assert pymxs.runtime.render(outputFile=image_path) + except: + failed.append(group_key) + + success = len(failed) == 0 + with open(os.path.join(output_dir, JSON_FILENAME), "w") as f: + json.dump({"success": success, "failed_objs": sorted(failed)}, f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_open_fillable_volume.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_open_fillable_volume.py new file mode 100644 index 0000000000000000000000000000000000000000..29ff3b2543af64f6b82c8345b2b07110923cbdbb --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_open_fillable_volume.py @@ -0,0 +1,8 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.max.generate_fillable_volume import generate_fillable_mesh_from_seed + +if __name__ == "__main__": + generate_fillable_mesh_from_seed(is_open=True) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_particles.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_particles.py new file mode 100644 index 0000000000000000000000000000000000000000..16beb5a57dfe7a421a3f50b89c1734827cff7de9 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/generate_particles.py @@ -0,0 +1,92 @@ +import json +import pymxs + +rt = pymxs.runtime + +import csv +import string +import random +# from b1k_pipeline.max.convex_decomposition import generate_convex_decompositions + + +def get_shape(shape, size): + if shape == "cube": + obj = rt.Box() + obj.width = float(size) + obj.height = float(size) + obj.length = float(size) + elif shape == "sphere": + obj = rt.Sphere() + obj.radius = float(size) / 2 + else: + raise ValueError("Unknown shape " + shape) + + return obj + + +def generate_particle(name, shape, colors, size): + objs = [] + for color in colors.split(";"): + # Generate the object + obj = get_shape(shape, size) + + # Assign a name + model_id = "".join(random.choices(string.ascii_lowercase, k=6)) + obj.name = f"{name}-{model_id}-0" + + # Create the collision version + col_obj = get_shape(shape, size) + col_obj.name = obj.name + "-Mcollision" + col_obj.parent = obj + col_obj.isHidden = True + + # Create the material + r, g, b = [int(x) for x in color.split(",")] + mat = rt.VRayMtl() + mat.diffuse = rt.Color(r, g, b) + obj.material = mat + + objs.append(obj) + print("Created", obj.name) + return objs + + +def substance_generation_round_one(): + with open(r"D:\BEHAVIOR-1K\asset_pipeline\metadata\substance_generation.csv") as f: + particles = [] + for row in csv.DictReader(f): + if row["Request"] != "GENERATE" or row["Shape"] not in ("cube", "sphere"): + continue + particles.extend( + generate_particle( + row["Name"], row["Shape"], row["Color"], row["Diameter (mm)"] + ) + ) + + for i, particle in enumerate(particles): + particle.position = rt.Point3(i * 100, 0, 0) + + +def substance_generation_round_two(): + with open( + r"D:/BEHAVIOR-1K/asset_pipeline/metadata/diced_particle_systems_colors.json" + ) as f: + data = json.load(f) + + particles = [] + for particle_name, particle_info in data.items(): + hex_color = particle_info["color"] + rgb_color = tuple(int(hex_color[i : i + 2], 16) for i in (1, 3, 5)) + rgb_color_str = f"{rgb_color[0]},{rgb_color[1]},{rgb_color[2]}" + size_cm = particle_info["llm_size_cm"] + size_mm = size_cm * 10 + (particle,) = generate_particle(particle_name, "cube", rgb_color_str, size_mm) + # generate_convex_decompositions(particle, preferred_method="chull") + particles.append(particle) + + for i, particle in enumerate(particles): + particle.position = rt.Point3(i * 100, 3000, 0) + + +if __name__ == "__main__": + substance_generation_round_two() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/group_by_instance_id.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/group_by_instance_id.py new file mode 100644 index 0000000000000000000000000000000000000000..e060131967f97ca3cd0da761098dead1cf97435b --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/group_by_instance_id.py @@ -0,0 +1,38 @@ +from b1k_pipeline.utils import parse_name +from collections import defaultdict + + +def group_selection(): + groups = defaultdict(list) + for obj in rt.selection: + match = parse_name(obj.name) + if not match: + continue + + key = f"{match.group('category')}-{match.group('model_id')}-{match.group('instance_id')}" + groups[key].append(obj) + + for name, group_objs in groups.items(): + if len(group_objs) <= 1: + continue + + # Pick base link + base_links = [ + x + for x in group_objs + if parse_name(x.name).group("link_name") in (None, "base_link") + ] + assert len(base_links) == 1, base_links + (base_link,) = base_links + others = [x for x in group_objs if x != base_link] + + # Create group + group = rt.group([base_link], name=name) + for x in others: + x.parent = group + + assert np.allclose(group.position, base_link.position) + + +if __name__ == "__main__": + group_selection() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_by_id.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_by_id.py new file mode 100644 index 0000000000000000000000000000000000000000..974570664de51f1a8fd5de7d478116f3632a5c15 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_by_id.py @@ -0,0 +1,39 @@ +import glob +import sys +import tqdm + +import_list = [ + "gqtsam", + "heoxnw", + "hlqrxm", + "jocrsz", + "kfsxxl", + "nsxhvs", + "tehmzy", + "wegawe", + "ykujyn", +] + +for fn in tqdm.tqdm(glob.glob(r"D:\BEHAVIOR-1K\asset_pipeline\cad\*\*\processed.max")): + # Get the object list from the file + f_objects = rt.getMAXFileObjectNames(fn, quiet=True) + + # Check if anything from that file matches + matching_objects = [] + for obj in f_objects: + m = b1k_pipeline.utils.parse_name(obj) + if not m: + continue + if m.group("model_id") in import_list: + matching_objects.append(obj) + + # If there's anything to import, get it! + if matching_objects: + success = rt.mergeMaxFile( + fn, + matching_objects, + rt.Name("select"), + rt.Name("autoRenameDups"), + rt.Name("renameMtlDups"), + quiet=True, + ) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_collision_meshes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_collision_meshes.py new file mode 100644 index 0000000000000000000000000000000000000000..ee663a95ee3a22343dd6ced46f7e5955f8d07a22 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_collision_meshes.py @@ -0,0 +1,207 @@ +import pathlib +import re +import traceback +import numpy as np +import json +from fs.zipfs import ZipFS + +import pymxs + +rt = pymxs.runtime + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import PipelineFS, get_targets, parse_name, load_mesh + + +def import_collision_mesh(obj, collision_selections, collision_mesh_fs): + print("Importing collision mesh for", obj.name) + + if rt.classOf(obj) != rt.Editable_Poly: + return + + parsed_name = parse_name(obj.name) + if not parsed_name: + return + + category = parsed_name.group("category") + model_id = parsed_name.group("model_id") + instance_id = parsed_name.group("instance_id") + link_name = parsed_name.group("link_name") + link_name = link_name if link_name else "base_link" + node_key = (category, model_id, instance_id, link_name) + + # Does it already have a collision mesh? If so, move on. + for child in obj.children: + parsed_child_name = parse_name(child.name) + if not parsed_child_name: + continue + + # Skip parts etc. + if parsed_child_name.group("mesh_basename") != parsed_name.group( + "mesh_basename" + ): + continue + + if parsed_child_name.group("meta_type") == "collision": + print("Collision mesh already exists for", obj.name, ", skipping.") + return + + # Try to load a collision mesh selection + collision_key = (model_id, link_name) + if collision_key not in collision_selections: + print("No collision selection found for", obj.name) + return + + collision_selection = collision_selections[collision_key] + print("Collision selection for", obj.name, "is", collision_selection) + + if not collision_mesh_fs.exists(obj.name): + print("No collision mesh found for", obj.name) + return + + collision_fs = collision_mesh_fs.opendir(obj.name) + collision_filenames = collision_fs.listdir("/") + selection_matching_pattern = re.compile(collision_selection + r"-(\d+).obj$") + + # Match the files + if not collision_filenames: + print("No collision meshes found for", obj.name) + return + + selection_matches = [ + (selection_matching_pattern.fullmatch(x), x) for x in collision_filenames + ] + indexed_matches = { + int(match.group(1)): fn for match, fn in selection_matches if match + } + expected_keys = set(range(len(indexed_matches))) + found_keys = set(indexed_matches.keys()) + assert ( + expected_keys == found_keys + ), f"Missing collision meshes for {node_key}: {expected_keys - found_keys}" + ordered_collision_filenames = [ + indexed_matches[i] for i in range(len(indexed_matches)) + ] + + collision_meshes = [] + for collision_filename in ordered_collision_filenames: + collision_mesh = load_mesh( + collision_fs, collision_filename, force="mesh", skip_materials=True + ) + if not collision_mesh.is_volume: + collision_mesh = load_mesh( + collision_fs, + collision_filename, + force="mesh", + process=False, + skip_materials=True, + ) + collision_meshes.append(collision_mesh) + + # Get a flattened list of vertices and faces + all_vertices = [] + all_faces = [] + for split in collision_meshes: + vertices = [rt.Point3(*v.tolist()) for v in split.vertices] + # Offsetting here by the past vertex count + faces = [[v + len(all_vertices) + 1 for v in f.tolist()] for f in split.faces] + all_vertices.extend(vertices) + all_faces.extend(faces) + + # Create a new node for the collision mesh + collision_obj = rt.Editable_Mesh() + rt.ConvertToPoly(collision_obj) + collision_obj.name = f"{parsed_name.group('mesh_basename')}-Mcollision" + collision_obj.rotation = obj.rotation + collision_obj.position = obj.position + + # Add the vertices + for v in all_vertices: + rt.polyop.createVert(collision_obj, v) + + # Add the faces + for f in all_faces: + rt.polyop.createPolygon(collision_obj, f) + + # Optionally set its wire color + collision_obj.wirecolor = rt.yellow + + # Update the mesh to reflect changes + rt.update(collision_obj) + + # Parent the mesh + collision_obj.parent = obj + + # Check that the new element count is the same as the split count + elems = { + tuple(rt.polyop.GetElementsUsingFace(collision_obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(collision_obj)) + } + assert len(elems) == len( + collision_meshes + ), f"{obj.name} has different number of faces in collision mesh than in splits" + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + # Hide the mesh + collision_obj.isHidden = True + + +def process_target(pipeline_fs, target): + print("Processing", target) + filename = str(pipeline_fs.target(target).getsyspath("processed.max")) + assert rt.loadMaxFile(filename, useFileUnits=False, quiet=True) + + with pipeline_fs.target_output(target) as target_output_fs: + # If there are no collision selections, move on + if not target_output_fs.exists("collision_selection.json"): + print("No collision selections found for", target) + return + + # Load the collision selections + with target_output_fs.open("collision_selection.json", "r") as f: + mesh_to_collision = json.load(f) + match_to_collision = { + parse_name(k): v for k, v in mesh_to_collision.items() + } + collision_selections = { + ( + k.group("model_id"), + k.group("link_name") if k.group("link_name") else "base_link", + ): v + for k, v in match_to_collision.items() + if k is not None + } + + # Open the collision meshes ZIP + with ( + target_output_fs.open("collision_meshes.zip", "rb") as f, + ZipFS(f) as collision_mesh_fs, + ): + # Iterate over the objects in the scene + for obj in rt.objects: + import_collision_mesh(obj, collision_selections, collision_mesh_fs) + + rt.saveMaxFile(filename) + + +def main(): + with PipelineFS() as pipeline_fs: + # current_target_dir = pathlib.Path(rt.maxFilePath) + # current_target_rel = current_target_dir.relative_to(PIPELINE_ROOT) + # cad, target_type, target_name = current_target_rel.parts + # assert cad == "cad", f"Current file is not in the cad directory: {current_target_rel}" + # assert target_type in ("scenes", "objects"), f"Current file is not in the scenes or objects directory: {current_target_rel}" + # current_target = target_type + "/" + target_name + + for target in get_targets("combined"): + process_target(pipeline_fs, target) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_fillable_meshes.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_fillable_meshes.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2dce83d87a5dd3a406d57d46476638b21e599c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_fillable_meshes.py @@ -0,0 +1,231 @@ +from collections import defaultdict +import pathlib +import numpy as np +import json +from fs.osfs import OSFS + +import pymxs + +rt = pymxs.runtime + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name, load_mesh, PIPELINE_ROOT +from b1k_pipeline.max.replace_bad_object import ( + node_bounding_box_incl_children, + rotation_only_transform, +) + +FILLABLE_DIR = pathlib.Path(r"D:\fillable-10-21") +FILLABLE_ASSIGNMENTS = { + k: v + for k, v in json.loads( + (FILLABLE_DIR / "fillable_assignments_2.json").read_text() + ).items() + if v in {"dip", "ray", "combined", "generated"} +} +BOUNDING_BOX_DATA_PATH = FILLABLE_DIR / "fillable_bboxes.json" +BOUNDING_BOX_DATA = json.loads(BOUNDING_BOX_DATA_PATH.read_text()) +KEY_PATH = FILLABLE_DIR / "omnigibson.key" +LOG_PATH = FILLABLE_DIR / "import_fillable_meshes.log" +REMOVE_EXISTING = True +CHECK_MATCHING_SIZE = True + + +def get_bounding_box_from_usd(obj_dir): + offset, size = BOUNDING_BOX_DATA[obj_dir.parts[-1]] + return np.array(offset), np.array(size) + + +def import_fillable_volumes(model_id, object_links): + print("Importing fillable mesh for", model_id) + + # Remove any fillable volumes that this object already has + if REMOVE_EXISTING: + to_remove = [] + for cand_obj in rt.objects: + match = parse_name(cand_obj.name) + if not match: + continue + if match.group("model_id") != model_id: + continue + if match.group("meta_type") not in ("fillable", "openfillable"): + continue + to_remove.append(cand_obj) + + for obj in to_remove: + rt.delete(obj) + + # Find the directory corresponding to this object + (model_dir,) = list( + {x.parent for x in FILLABLE_DIR.glob(f"objects/*/{model_id}/bbox.json")} + ) + + # Find the fillable mesh files + fillable_files = list(model_dir.glob("fillable---*---*---*.obj")) + assert ( + len(fillable_files) >= 1 + ), f"Expected at least one fillable mesh for {model_id}" + by_link_and_kind = defaultdict(lambda: defaultdict(list)) + for fillable_file in fillable_files: + link, idx, kind = fillable_file.stem.split("---")[1:] + by_link_and_kind[link][kind].append(fillable_file) + + # From the USD read the bounding box info + usd_bbox_offset, usd_bbox_size = get_bounding_box_from_usd(model_dir) + + # Get information about the base link of the object + base_link = object_links["base_link"] + base_rot = base_link.rotation + base_link_rotation_transform = rotation_only_transform(base_link.transform) + + # Compute the full object bbox by looking at all the links + bbox_points = [] + for link_obj in object_links.values(): + bbox_points.extend( + node_bounding_box_incl_children( + link_obj, base_link_rotation_transform, only_canonical=True + ) + ) + bbox_min = np.min(bbox_points, axis=0) + bbox_max = np.max(bbox_points, axis=0) + bbox_ctr_rotated = (bbox_min + bbox_max) / 2 + base_link_rotated = bbox_ctr_rotated - usd_bbox_offset + base_link_world = ( + base_link_rotation_transform @ np.concatenate([base_link_rotated, [1]]) + )[:3] + bbox_size = bbox_max - bbox_min + + # Compare the bounding box sizes + if CHECK_MATCHING_SIZE and not np.allclose(bbox_size, usd_bbox_size, atol=10): + msg = f"Bounding box sizes do not match for {model_id}. USD has {usd_bbox_size}, max has {bbox_size}, skipping." + print(msg) + + # Append the message to the log file too + with open(LOG_PATH, "a") as f: + f.write(msg + "\n") + + return False + + for link_name, kind_files in by_link_and_kind.items(): + link_obj = object_links[link_name] + parsed_link_name = parse_name(link_obj.name) + for kind, files in kind_files.items(): + fillable_meshes = [] + for path in files: + fs = OSFS(str(path.parent)) + filename = path.name + fillable_mesh = load_mesh( + fs, filename, force="mesh", skip_materials=True + ) + if not fillable_mesh.is_volume: + fillable_mesh = load_mesh( + fs, filename, force="mesh", process=False, skip_materials=True + ) + fillable_meshes.append(fillable_mesh) + + # Get a flattened list of vertices and faces + all_vertices = [] + all_faces = [] + for split in fillable_meshes: + vertices = [rt.Point3(*(v * 1000).tolist()) for v in split.vertices] + # Offsetting here by the past vertex count + faces = [ + [v + len(all_vertices) + 1 for v in f.tolist()] for f in split.faces + ] + all_vertices.extend(vertices) + all_faces.extend(faces) + + # Create a new node for the fillable mesh + fillable_obj = rt.Editable_Mesh() + rt.ConvertToPoly(fillable_obj) + fillable_type = "Mfillable" if kind == "enclosed" else "Mopenfillable" + fillable_obj.name = ( + f"{parsed_link_name.group('mesh_basename')}-{fillable_type}" + ) + + # Add the vertices + for v in all_vertices: + rt.polyop.createVert(fillable_obj, v) + + # Add the faces + for f in all_faces: + rt.polyop.createPolygon(fillable_obj, f) + + # So far, everything is in the local coordinate system, e.g. where they would go if the + # object base link was at the origin and had no rotation. We need to move it to where we + # think the base link is (this is unknown in 3ds Max but we read it from the USD). + fillable_obj.rotation = base_rot + fillable_obj.position = rt.Point3(*base_link_world.tolist()) + + # Optionally set its wire color + fillable_obj.wirecolor = rt.yellow + + # Update the mesh to reflect changes + rt.update(fillable_obj) + + # Parent the mesh + fillable_obj.parent = link_obj + + # Check that the new element count is the same as the split count + elems = { + tuple(rt.polyop.GetElementsUsingFace(fillable_obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(fillable_obj)) + } + assert ( + len(elems) == len(fillable_meshes) + ), f"{fillable_obj.name} has different number of faces in fillable mesh than in splits" + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{fillable_obj.name} has same face appear in multiple elements" + + # Hide the mesh + fillable_obj.isHidden = True + + return True + + +def process_current_file(): + # Iterate through the objects in the file and build the link lists + object_links = defaultdict(dict) + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + + match = parse_name(obj.name) + if not match: + continue + + if match.group("instance_id") != "0": + continue + + if match.group("bad"): + continue + + if match.group("meta_type"): + continue + + if match.group("joint_side") == "upper": + continue + + link_name = ( + match.group("link_name") if match.group("link_name") else "base_link" + ) + object_links[match.group("model_id")][link_name] = obj + + # For each object, try to import the fillable volumes + availables = set(FILLABLE_ASSIGNMENTS.keys()) & set(object_links.keys()) + + return any( + [ + import_fillable_volumes(model_id, object_links[model_id]) + for model_id in availables + ] + ) + + +if __name__ == "__main__": + process_current_file() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_legacy_objs.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_legacy_objs.py new file mode 100644 index 0000000000000000000000000000000000000000..f40f727151661c65284224f29fc3eb191da53830 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_legacy_objs.py @@ -0,0 +1,540 @@ +import re +import sys +import traceback + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import collections +import glob +import json +import os +import random +import shutil +import string +from typing import Dict, List + +import numpy as np +import pymxs +import tqdm +import trimesh.transformations +import yaml +from scipy.spatial.transform import Rotation as R + +import b1k_pipeline.utils +from b1k_pipeline.max.new_sanity_check import SanityCheck +from b1k_pipeline.urdfpy import URDF, Joint, Link + +rt = pymxs.runtime + +CONFIRM_EACH = True +INTERACTIVE_MODE = True +JOINT_TYPES = {"prismatic": "P", "revolute": "R", "fixed": "F", "continuous": "R"} +IN_DATASET_ROOT = r"C:\Users\Cem\research\iGibson-dev\igibson\data\ig_dataset" +OUTPUT_ROOT = r"D:\BEHAVIOR-1K\asset_pipeline\cad\objects" +TRANSLATION_PATH = os.path.join(IN_DATASET_ROOT, "metadata", "model_rename.yaml") +with open(TRANSLATION_PATH, "r") as f: + TRANSLATION_DICT = yaml.load(f, Loader=yaml.SafeLoader) +RENDER_PRESET_FILENAME = str( + (b1k_pipeline.utils.PIPELINE_ROOT / "render_presets" / "objrender.rps").absolute() +) +BLACKLIST = { + ("door", "rrsovh"), + ("car", "takwdb"), +} + + +class AutomationError(ValueError): + pass + + +def get_maps_from_mat(mat): + results = set() + if mat: + for i in range(mat.numsubs): + submat = mat[i] + if submat: + if rt.classOf(submat) == rt.SubAnim: + if rt.isKindOf(submat.object, rt.textureMap): + results.add(submat.object) + results.update(get_maps_from_mat(submat)) + return results + + +def get_all_maps(): + materials = {x.material for x in rt.objects} + return {map for mat in materials for map in get_maps_from_mat(mat)} + + +def load_objs_from_urdf(fn, pose=None): + pass + + +def process_urdf(old_category_name, old_model_name): + model_dir = os.path.join( + IN_DATASET_ROOT, "objects", old_category_name, old_model_name + ) + intervention_request_msgs = [] + + # Convert to new model name. + new_category_name, new_model_name = TRANSLATION_DICT[ + old_category_name + "/" + old_model_name + ].split("/") + + # Load the URDF file into urdfpy + urdf_filename = old_model_name + ".urdf" + urdf_path = os.path.join(model_dir, "urdf", urdf_filename) + robot = URDF.load(urdf_path) + + # Load the metadata file too + metadata_path = os.path.join(model_dir, "misc", "metadata.json") + with open(metadata_path, "r") as metadata_file: + metadata = json.load(metadata_file) + + # Check the list of links that end at openable joints. + openable_joint_ids = metadata.get("openable_joint_ids", []) + openable_links = { + robot.link_map[robot.joint_map[openable_joint_data[1]].child] + for openable_joint_data in openable_joint_ids + } + + # Do FK with everything at the lower position + joint_cfg = { + joint.name: joint.limit.lower + for joint in robot.joints + if joint.joint_type in ("prismatic", "revolute") + } + lfk: Dict[Link, np.ndarray] = robot.link_fk(cfg=joint_cfg) + + # Get the base link base mesh transform, revert it + base_link = robot.base_link + + if len(base_link.visuals) >= 1: + assert np.allclose( + base_link.visuals[0].origin[:3, :3], np.eye(3) + ), "Rotational offsets are not allowed." + real_base_link_transform = np.linalg.inv(base_link.visuals[0].origin) + else: + intervention_request_msgs.append( + "Base link has no visual mesh. Check if the visuals are reasonable." + ) + real_base_link_transform = np.eye(4) + + # Start tracking objects per link + lower_objects_by_link = {} + + def process_link(link, link_pose, is_upper_side): + found_identity_transform = False + if len(link.visuals) == 0: + intervention_request_msgs.append( + f"Encountered link with no visual meshes: {link.name}" + ) + return None, found_identity_transform + + # Actually start the processing. + first_mesh = None + for visual in link.visuals: + assert ( + visual.geometry.mesh is not None + ), "Encountered link with primitive visuals." + filename = os.path.abspath( + os.path.join(model_dir, visual.geometry.mesh.filename) + ) + joint_type = None + + # Compute the pose + pose = real_base_link_transform @ link_pose @ visual.origin + if visual.geometry.mesh.scale is not None: + S = np.eye(4, dtype=np.float64) + S[:3, :3] = np.diag(visual.geometry.mesh.scale) + pose = pose @ S + + # Count this for check that at least one thing has trivial pose + if np.allclose(pose, trimesh.transformations.identity_matrix()): + found_identity_transform = True + + # Convert the pose to a 3ds Max transform + pose_formatted = pose[:3].T.tolist() + mat = rt.Matrix3( + rt.Point3(*pose_formatted[0]), + rt.Point3(*pose_formatted[1]), + rt.Point3(*pose_formatted[2]), + rt.Point3(*pose_formatted[3]), + ) + + # Compute the name + if link == robot.base_link: + obj_name = f"{new_category_name}-{new_model_name}-0-base_link" + else: + # Get the name based on the joint type/side. + link_name = re.sub(r"[^a-z0-9_]", "", link.name.lower()) + joints: List[Joint] = robot.joints + (j,) = [j for j in joints if j.child == link.name] + + # Save this for use later. + joint_type = j.joint_type + # if joint_type == "continuous": + # intervention_request_msgs.append("Continuous joint found. Check bounds.") + + if joint_type == "floating": + # Floating joints should get converted to plain objects. + obj_name = f"{new_category_name}_{link_name}-TODOfixme-0" + intervention_request_msgs.append( + f"{obj_name} needs a reasonable category / ID." + ) + else: + parent_name = re.sub(r"[^a-z0-9_]", "", j.parent.lower()) + if parent_name == robot.base_link.name: + parent_name = "base_link" + joint_type_str = JOINT_TYPES[joint_type] + side = "upper" if is_upper_side else "lower" + obj_name = f"{new_category_name}-{new_model_name}-0-{link_name}-{parent_name}-{joint_type_str}-{side}" + + # Add openable tag to relevant joints + if link in openable_links: + obj_name = obj_name + "-Topenable" + + # Check if we are processing the 2nd instance (upper) of a link. If so, just copy an instance and we can return now since we just need + # to process the first visual mesh in that case. + if link in lower_objects_by_link: + lower_obj = lower_objects_by_link[link] + instance_objs = [] + success, instance_objs = rt.maxOps.cloneNodes( + lower_obj, + cloneType=rt.name("instance"), + newNodes=pymxs.byref(instance_objs), + ) + assert success, "Could not clone object for upper end." + (obj,) = instance_objs + obj.transform = mat + obj.name = obj_name + return obj, found_identity_transform + + # Otherwise, import the object into 3ds Max + rt.importFile(filename, pymxs.runtime.Name("noPrompt")) + + # Are there multiple objects? Combine them. + obj_candidates = list(rt.selection) + obj = obj_candidates[0] + for extra_obj in obj_candidates[1:]: + intervention_request_msgs.append( + f"Found extra object during import when importing {obj_name}. Take a look." + ) + rt.polyop.attach(obj, extra_obj) + obj.transform = mat + obj.name = obj_name + + # If this is not the first mesh, we just attach it to the first mesh which is already fully processed. + if first_mesh is not None: + rt.polyop.attach(first_mesh, obj) + continue + + # Add meta-links. + if link == robot.base_link: + meta_links = metadata.get("links", {}) + for metalink_name, metalink_info in meta_links.items(): + printable_metalink_name = re.sub( + r"[^a-z0-9]", "", metalink_name.lower() + ) + + metalink_type = metalink_info["geometry"] + + # Get its position w.r.t. the URDF base link, transform it + metalink_orig_pos = np.array(metalink_info["xyz"]) + metalink_pos = trimesh.transformations.transform_points( + metalink_orig_pos[None, :], real_base_link_transform + ).flatten() + + if metalink_type is None: + # For point metalinks, we use a PointHelper. + point = rt.Point() + point.cross = False + point.name = f"{new_category_name}-{new_model_name}-0-base_link-M{printable_metalink_name}" + point.position = rt.Point3(*metalink_pos.tolist()) + point.rotation = obj.rotation + point.parent = obj + elif metalink_type == "box": + # For box metalinks, we use a Box. + box = rt.Box() + box.name = f"{new_category_name}-{new_model_name}-0-base_link-M{printable_metalink_name}" + box.rotation = obj.rotation * rt.Quat( + *R.from_euler("xyz", metalink_info["rpy"]) + .as_quat() + .tolist() + ) + box.position = rt.Point3(*metalink_pos.tolist()) + box.parent = obj + box.width, box.length, box.height = metalink_info["size"] + box.objectoffsetpos = rt.Point3(0, 0, box.height / 2.0) + intervention_request_msgs.append( + f"Found box metalink {box.name}. Take a look." + ) + else: + # We don't know how to handle anything else really. + raise ValueError(f"Unknown metalink type {metalink_type}") + + # If this is a floating link object let's toss it under the parent. + if joint_type == "floating": + parent_obj = lower_objects_by_link[robot.base_link] + obj.parent = parent_obj + + # Keep track of the first mesh we process for attachment of later meshes. + first_mesh = obj + + return first_mesh, found_identity_transform + + # First, get the lower range of everything based on the default lfk. + found_identity_transform = False + for link, link_pose in lfk.items(): + obj, any_identity_transform = process_link(link, link_pose, is_upper_side=False) + lower_objects_by_link[link] = obj + found_identity_transform = found_identity_transform or any_identity_transform + assert found_identity_transform, "No object has identity transform." + + # Then, for each joint, add the upper limit. + joints: List[Joint] = robot.joints + for joint in joints: + if joint.joint_type not in {"prismatic", "revolute", "continuous"}: + continue + + # Get some joint info. + joint_name = joint.name + if joint.joint_type == "continuous": + # Set a fixed 180 degree limit on continuous joints. Typically buttons. + joint_upper = np.pi - 0.01 + else: + joint_upper = joint.limit.upper + child_link_name = joint.child + link = robot.link_map[child_link_name] + + # Apply FK with only this joint set to upper position. + joint_lfk = robot.link_fk(cfg={joint_name: joint_upper}) + link_pose = joint_lfk[link] + + # Process the child link with the joint's upper position. + process_link(link, link_pose, is_upper_side=True) + + return intervention_request_msgs, lower_objects_by_link[base_link] + + +def process_object_dir(model_dir): + # Process the model name + old_category_name = os.path.basename(os.path.dirname(model_dir)) + old_model_name = os.path.basename(model_dir) + + # Convert to new model name. + new_category_name, new_model_name = TRANSLATION_DICT[ + old_category_name + "/" + old_model_name + ].split("/") + + if (new_category_name, new_model_name) in BLACKLIST: + return + + # Get output path. + obj_output_dir = os.path.join( + OUTPUT_ROOT, f"legacy_{new_category_name}-{new_model_name}" + ) + + # If the path already exists, assume the file has already been processed. + if os.path.exists(obj_output_dir): + print(f"{obj_output_dir} already exists!") + return + + # Reset the scene + rt.resetMaxFile(rt.name("noPrompt")) + + preset_categories = rt.renderpresets.LoadCategories(RENDER_PRESET_FILENAME) + assert rt.renderpresets.Load(0, RENDER_PRESET_FILENAME, preset_categories) + + # Start processing. + try: + intervention_request_msgs, base_obj = process_urdf( + old_category_name, old_model_name + ) + + # Add the parts + metadata_path = os.path.join(model_dir, "misc", "metadata.json") + with open(metadata_path, "r") as metadata_file: + metadata = json.load(metadata_file) + if "object_parts" in metadata: + part_type_instance_idx = collections.Counter() + for part in metadata["object_parts"]: + # Load the metadata + part_cat = part["category"] + part_model = part["model"] + expected_part_name = f"{part_cat}-{part_model}-0" + new_part_cat, new_part_model = TRANSLATION_DICT[ + part_cat + "/" + part_model + ].split("/") + part_pos = np.array(part["pos"]) + part_orn = R.from_quat(part["orn"]).as_matrix() + part_pose = np.zeros((3, 4)) + part_pose[:, :3] = part_orn + part_pose[:, 3] = part_pos + pose_formatted = part_pose.T.tolist() + pose_mat = rt.Matrix3( + rt.Point3(*pose_formatted[0]), + rt.Point3(*pose_formatted[1]), + rt.Point3(*pose_formatted[2]), + rt.Point3(*pose_formatted[3]), + ) + + # Keep track of the objects we already had + existing_objs = set(rt.objects) + + # Load the part + intervention_request_msgs.extend(process_urdf(part_cat, part_model)[0]) + + # Find the new objects + new_objs = set(rt.objects) - existing_objs + + for new_obj in new_objs: + # Update the name, transform and parent + part_idx = part_type_instance_idx[expected_part_name] + part_type_instance_idx[expected_part_name] += 1 + new_obj.name = ( + f"B-{new_part_cat}-{new_part_model}-{part_idx}-Tsubpart" + ) + new_obj.transform = new_obj.transform * pose_mat + new_obj.parent = base_obj + + if len(new_objs) != 1: + part_names = ",".join([x.name for x in new_objs]) + intervention_request_msgs.append( + f"Found new objects != 1 after importing part {part_cat}-{part_model}: {part_names}" + ) + + # Fix any bad materials, set the reflection color of the vray materials to be 0 + rt.select(rt.objects) + rt.convertToVRay(True) + for obj in rt.objects: + if obj.material: + obj.material.reflection = rt.Color(0, 0, 0) + + # Update the image paths. + texture_dir = os.path.join(obj_output_dir, "textures") + os.makedirs(texture_dir, exist_ok=True) + for map in get_all_maps(): + source_path = map.filename + assert os.path.exists( + source_path + ), f"Could not find texture map {source_path}" + source_name, source_ext = os.path.splitext(os.path.basename(source_path)) + + # Pick a semi-random target path + while True: + target_name = ( + source_name + + "-" + + "".join(random.choices(string.ascii_letters, k=6)) + ) + target_path = os.path.join(texture_dir, target_name + source_ext) + if not os.path.exists(target_path): + break + + # Copy the file to its new spot + shutil.copy2(source_path, target_path) + + # Update the bitmap to have the right reference. + print(target_path) + map.filename = target_path + + # Stop execution if the sanity check has failed. + sc = SanityCheck().run() + if sc["ERROR"]: + intervention_request_msgs.append( + "Sanitycheck issues:\n" + "\n".join(sc["ERROR"]) + ) + + # Finally, save the file. + max_path = os.path.join(obj_output_dir, "processed.max") + assert rt.saveMaxFile(max_path), "Could not save the file at {max_path}." + + print("Processed ", obj_output_dir) + + if CONFIRM_EACH: + intervention_request_msgs.append( + "Confirm this file - requested due to CONFIRM_EACH=True" + ) + + # If we are not silencing automation errors, raise now so that the user can examine the file. + if len(intervention_request_msgs) > 0: + if INTERACTIVE_MODE: + raise AutomationError("\n".join(intervention_request_msgs)) + else: + raise ValueError( + "Failed due to automation errors happening in headless mode. Retry in interactive." + ) + except AutomationError: + # No cleanup needed for automation errors. + raise + except: + # Otherwise, remove the incomplete file. + shutil.rmtree(obj_output_dir, ignore_errors=True) + raise + + +def import_legacy_objs(): + # Grab all the files from the dataset. + obj_dirs = sorted( + p + for p in glob.glob(os.path.join(IN_DATASET_ROOT, "objects/*/*")) + if os.path.isdir(p) + ) + + whitelist = {"pot_plant-jatssq", "washer-omeuop"} + + # Narrow down to objects that don't already exist. + split_names = [ + (os.path.basename(os.path.dirname(model_dir)), os.path.basename(model_dir)) + for model_dir in obj_dirs + ] + new_split_names = [ + TRANSLATION_DICT[old_category_name + "/" + old_model_name].split("/") + for old_category_name, old_model_name in split_names + ] + # is_whitelisted = [f"{cat}-{model}" in whitelist for cat, model in new_split_names] + is_whitelisted = [True for cat, model in new_split_names] + obj_output_dirs = [ + os.path.join(OUTPUT_ROOT, f"legacy_{new_category_name}-{new_model_name}") + for new_category_name, new_model_name in new_split_names + ] + + remaining_objs = [ + obj_dir + for obj_dir, obj_output_dir, obj_whitelisted in zip( + obj_dirs, obj_output_dirs, is_whitelisted + ) + if obj_whitelisted and not os.path.exists(obj_output_dir) + ] + + failures = {} + for obj_dir in tqdm.tqdm(remaining_objs): + try: + process_object_dir(obj_dir) + except AutomationError as e: + print( + f"Stopping after object {obj_dir} due to non-automatable fixes needed. Please correct these, save, and re-run script to continue." + ) + print(e) + break + except Exception as e: + failures[obj_dir] = str(e) # traceback.format_exc() + else: + # This means we finished iterating without stopping at an object due to a Sanitycheck Error. + print("Finished importing files.") + print(f"Failures: {len(failures)} / {len(remaining_objs)}") + sorted_failure_fns = sorted(failures.keys()) + for i, failure_fn in enumerate(sorted_failure_fns): + print(f"{i + 1} / {len(failures)} - {failure_fn}: {failures[failure_fn]}") + + +def import_legacy_objs_button(): + try: + import_legacy_objs() + except Exception as e: + # Print message + rt.messageBox(str(e)) + + +if __name__ == "__main__": + import_legacy_objs_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_scene_obj_orientations.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_scene_obj_orientations.py new file mode 100644 index 0000000000000000000000000000000000000000..500cf744c326a1f529f1ea9cbc184dcae710584e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_scene_obj_orientations.py @@ -0,0 +1,180 @@ +import pathlib +import sys +import traceback +from collections import defaultdict + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import os + +import numpy as np +import pymxs +import yaml +from scipy.spatial.transform import Rotation as R + +from b1k_pipeline.utils import parse_name + +rt = pymxs.runtime + +import xml.etree.ElementTree as ET + +IN_DATASET_ROOT = r"C:\Users\Cem\research\iGibson-dev\igibson\data\ig_dataset" + +TRANSLATION_PATH = os.path.join(IN_DATASET_ROOT, "metadata", "model_rename.yaml") +with open(TRANSLATION_PATH, "r") as f: + TRANSLATION_DICT = yaml.load(f, Loader=yaml.SafeLoader) + + +def fix(): + # Prepare a list of objects to position. + objs = [x for x in rt.objects if rt.classOf(x) == rt.Editable_Poly] + candidates = defaultdict(list) + for obj in objs: + match = parse_name(obj.name) + if not match: + continue + + if match.group("link_name") and match.group("link_name") != "base_link": + continue + + if match.group("category") in ( + "ceilings", + "floors", + "walls", + "electric_switch", + ): + continue + + q = obj.rotation + mag = R.from_quat([q.x, q.y, q.z, q.w]).magnitude() + assert np.isclose(mag, 0, atol=1e-3), f"{obj.name} has nonzero rotation." + assert np.all(obj.scale, 0), f"{obj.name} has unit scale." + assert np.all(obj.objectoffsetscale, 0), f"{obj.name} has unit scale." + + cat = match.group("category") + model = match.group("model_id") + com = ( + np.asarray(obj.position) / 1000 + ) # np.mean(np.array(rt.polyop.getVerts(obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj)))), axis=0) / 1000 + candidates[(cat, model)].append((obj, com)) + + scene_name = pathlib.Path(rt.maxFilePath).parts[-1] + file_path = ( + pathlib.Path(IN_DATASET_ROOT) + / "scenes" + / scene_name + / "urdf" + / f"{scene_name}_best.urdf" + ) + assert file_path.exists(), f"Could not find {str(file_path)}" + tree = ET.parse(file_path) + root = tree.getroot() + found = defaultdict(list) + for link in root.findall("link"): + if "category" not in link.attrib: + continue + + cat = link.attrib["category"] + model = link.attrib["model"] + name = link.attrib["name"] + + if cat in ("ceilings", "floors", "walls"): + continue + + new_category_name, new_model_name = TRANSLATION_DICT[cat + "/" + model].split( + "/" + ) + + joint_name = "j_" + name + joint_xpath = f"joint[@name='{joint_name}']" + # print("looking for ", joint_xpath) + (joint,) = root.findall(joint_xpath) + xyz = np.asarray( + [float(x) for x in joint.find("origin").attrib["xyz"].split(" ")] + ) + rpy = np.asarray( + [float(x) for x in joint.find("origin").attrib["rpy"].split(" ")] + ) + quat = R.from_euler("xyz", rpy).as_quat() + + found[(new_category_name, new_model_name)].append((name, xyz, quat)) + + missing_in_file = set(found.keys()) - set(candidates.keys()) + assert not missing_in_file, f"Missing in file: {missing_in_file}" + + missing_in_urdf = set(candidates.keys()) - set(found.keys()) + assert not missing_in_urdf, f"Missing in urdf: {missing_in_urdf}" + + # Check that the length is the same + problems = [] + for x in found.keys(): + count_in_urdf = len(found[x]) + count_in_file = len(candidates[x]) + if not count_in_file == count_in_urdf: + problems.append( + f"{x} has {count_in_file} in file but {count_in_urdf} in URDF." + ) + + assert not problems, "\n".join(problems) + + positions_from_file = np.asarray( + [com for objs in candidates.values() for _, com in objs] + ) + positions_from_urdf = np.asarray( + [xyz for objs in found.values() for _, xyz, _ in objs] + ) + + assert ( + len(positions_from_file) == len(positions_from_urdf) + ), f"File contains {len(positions_from_file)} things while URDF contains {len(positions_from_urdf)}" + file_mean = np.mean(positions_from_file, axis=0) + urdf_mean = np.mean(positions_from_urdf, axis=0) + displacement = file_mean - urdf_mean + + # Start mapping everything to the nearest + for x in found.keys(): + x_candidates = candidates[x] + cand_pos = np.asarray([com for _, com in x_candidates]) + x_found = found[x] + found_pos = np.asarray([xyz for _, xyz, _ in x_found]) + displacement + + # For each found pos, get the index of the closest + closest_candidates = [] + for f in found_pos: + dists = np.linalg.norm(cand_pos - f[None, :], axis=-1) + closest_candidate = np.argmin(dists) + closest_candidates.append(closest_candidate) + + if len(closest_candidates) != len(set(closest_candidates)): + for urdf_idx, file_idx in enumerate(closest_candidates): + print( + f"Closest object for {x_found[urdf_idx][0]} is {x_candidates[file_idx][0].name}" + ) + + # Now that everything has its closest candidate, set the orientations. + for i, (_, _, quat) in enumerate(x_found): + closest_idx = closest_candidates[i] + closest_obj = x_candidates[closest_idx][0] + + current_pos = closest_obj.position + current_rot = closest_obj.rotation + current_oor = closest_obj.objectoffsetrot + current_oop = closest_obj.objectoffsetpos + + target_rot = rt.Quat(*quat.tolist()) + diff_rot = rt.inverse(current_rot) * target_rot + inv_diff_rot = rt.inverse(diff_rot) + inv_diff_rot_R = R.from_quat( + [inv_diff_rot.x, inv_diff_rot.y, inv_diff_rot.z, inv_diff_rot.w] + ) + target_oop = inv_diff_rot_R.apply(current_oop) + closest_obj.rotation = current_rot * diff_rot + closest_obj.objectoffsetrot = current_oor * diff_rot + closest_obj.position = current_pos + closest_obj.objectoffsetpos = rt.Point3(*target_oop.tolist()) + + print("Fixed", closest_obj.name) + + +if __name__ == "__main__": + fix() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_scene_objs.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_scene_objs.py new file mode 100644 index 0000000000000000000000000000000000000000..726a97392d988e97acd67acd2e6ffb9c16fe7bbc --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/import_scene_objs.py @@ -0,0 +1,34 @@ +import glob +import os + +import pymxs + +ROOT_DIR = ( + r"C:\Users\cgokmen\research\iGibson\igibson\data\scene-conversion\Wainscott_1_int" +) +rt = pymxs.runtime + + +def get_layer(name): + if name == "": + name = "0" + + rt.LayerManager.NewLayerFromName(name) + layer = rt.LayerManager.GetLayerFromName(name) + assert layer is not None + return layer + + +objs = list(glob.glob(os.path.join(ROOT_DIR, "*", "*.obj"))) +for fullpath in objs: + file_name = os.path.split(os.path.split(fullpath)[0])[1] + obj_name, rooms = file_name.split("---") + rt.importFile(fullpath, pymxs.runtime.Name("noPrompt")) + obj = rt.selection[0] + obj.name = obj_name + + layer_name = rooms.replace("-", ",") + get_layer(layer_name).addNode(obj) + +# Set the reflection color of the vray materials to be 0 +# for obj in rt.objects: obj.material.reflection = rt.Color(0, 0, 0) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/instance_select.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/instance_select.py new file mode 100644 index 0000000000000000000000000000000000000000..cb5a5ac93b58c1fb10121a9811906edfb4d2c448 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/instance_select.py @@ -0,0 +1,13 @@ +import pymxs + +rt = pymxs.runtime + + +def instance_select(): + roots = set(x.baseObject for x in rt.selection) + objs = [x for x in rt.objects if x.baseObject in roots] + rt.select(objs) + + +if __name__ == "__main__": + instance_select() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/instanceify.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/instanceify.py new file mode 100644 index 0000000000000000000000000000000000000000..0035361667df7adebfbbe751965cf12ddda8ddcb --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/instanceify.py @@ -0,0 +1,195 @@ +import collections +import random + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +rt = pymxs.runtime +RMSD_THRESHOLD = 1e-3 + +local_coordsys = pymxs.runtime.Name("local") + + +def are_equal(target, base): + # Check with align_vectors' RMSD + pick_100 = random.sample(range(1, rt.polyop.getNumVerts(base) + 1), 100) + src_pc = np.array(rt.polyop.getVerts(base, list(pick_100))) + src_pc -= np.mean(src_pc, axis=0) + src_quat = base.rotation + src_rot = R.from_quat([src_quat.x, src_quat.y, src_quat.z, src_quat.w]) + src_pc = src_rot.inv().apply(src_pc) + src_pc /= np.array(base.scale) + + tgt_pc = np.array(rt.polyop.getVerts(target, list(pick_100))) + tgt_pc -= np.mean(tgt_pc, axis=0) + tgt_quat = target.rotation + tgt_rot = R.from_quat([tgt_quat.x, tgt_quat.y, tgt_quat.z, tgt_quat.w]) + tgt_pc = tgt_rot.inv().apply(tgt_pc) + tgt_pc /= np.array(target.scale) + assert src_pc.shape == tgt_pc.shape, "objects have different vertex counts" + + is_src_diff_scaled = not np.allclose(base.scale, base.scale[0]) + is_tgt_diff_scaled = not np.allclose(target.scale, target.scale[0]) + is_diff_scaled = is_src_diff_scaled or is_tgt_diff_scaled + + rmsd = R.align_vectors( + tgt_pc, + src_pc, + )[1] + + # print(rmsd) + + return rmsd < RMSD_THRESHOLD, is_diff_scaled + + +def align_pivots(tgt_obj, src_obj): + # Center pivot to object + src_obj.pivot = src_obj.center + pick_1000 = random.sample(range(1, rt.polyop.getNumVerts(src_obj) + 1), 100) + src_pc = np.array(rt.polyop.getVerts(src_obj, list(pick_1000))) + old_src_quat = [ + src_obj.rotation.x, + src_obj.rotation.y, + src_obj.rotation.z, + src_obj.rotation.w, + ] + old_src_R = R.from_quat(old_src_quat) + + # Center pivot to object + tgt_obj.pivot = tgt_obj.center + tgt_pc = np.array(rt.polyop.getVerts(tgt_obj, list(pick_1000))) + assert ( + src_pc.shape == tgt_pc.shape + ), "source object ({}) and target object ({}) are not instances of each other - they have different number of vertices.".format( + src_obj.name, tgt_obj.name + ) + + r = R.align_vectors( + tgt_pc - np.mean(tgt_pc, axis=0), + src_pc - np.mean(src_pc, axis=0), + )[0] + + new_rotation = r * old_src_R # desired orientation in the world frame + + old_target_quat = [ + tgt_obj.rotation.x, + tgt_obj.rotation.y, + tgt_obj.rotation.z, + tgt_obj.rotation.w, + ] + old_target_R = R.from_quat(old_target_quat) + + new_rotation_local = ( + old_target_R.inv() * new_rotation + ) # desired orientation in the local frame of the target object + delta_quat = rt.quat(*new_rotation_local.as_quat().tolist()) + + coordsys = getattr(pymxs.runtime, "%coordsys_context") + prev_coordsys = coordsys(local_coordsys, None) + tgt_obj.rotation *= delta_quat + tgt_obj.objectOffsetRot *= delta_quat + tgt_obj.objectOffsetPos *= delta_quat + coordsys(prev_coordsys, None) + + +def clone_and_align(target, base): + new_objs = [] + success, new_objs = rt.maxOps.cloneNodes( + base, cloneType=rt.name("instance"), newNodes=pymxs.byref(new_objs) + ) + assert success, "Could not clone." + (new_obj,) = new_objs + new_obj.transform = target.transform + new_obj.scale = target.scale + + return new_obj + + +def instanceify(): + message = "" + + # Group objects by vertex count and material + coarse_groups = collections.defaultdict(list) + for obj in rt.objects: + if rt.classOf(obj) == rt.Editable_Poly: + if len(obj.vertices) >= 1000: + coarse_groups[(obj.material, len(obj.vertices))].append(obj) + # else: + # message += f"Ignored low-vertex object {obj.name}\n" + # else: + # message += f"Ignored non-EP object {obj.name}\n" + print(message) + + # For each group, do narrower groups. + print("Finding object groups.") + real_groups = [] + for cg in coarse_groups.values(): + this_groups = [] + + # We will sort objects by whether or not they belong to the most populous instance group + bases = collections.Counter(obj.baseObject for obj in cg) + cg.sort(key=lambda x: -bases[x.baseObject]) + + for obj in cg: + # Check every object against every group's leader + found_group = False + for group in this_groups: + # TODO: Only check objects that are not already instances of the group's leader. + if are_equal(obj, group[0]): + found_group = True + # Only append if this is not already an instance. + if obj.baseObject != group[0].baseObject: + group.append(obj) + break + + # If we did not find a group, create a new one. + if not found_group: + this_groups.append([obj]) + + # Add these groups to the big list + real_groups.extend(this_groups) + + print("Filtering object groups.") + # Let's only do the 1+-member groups + real_groups = [x for x in real_groups if len(x) > 1] + real_groups.sort(key=lambda x: -sum(len(obj.vertices) for obj in x)) + + # For now we only do the top group. + if len(real_groups) == 0: + rt.messageBox("No groups of uninstanced objects found.") + return + + # Now select the objects for clone-and-align use. + # print("Selecting.") + # rt.select(group[1:]) + + # rt.messageBox(f"Objects are selected now and can be replaced with clone-and-align. Use object {head.name} as the cloning base.") + + # Now go through the groups and make everything an instance + replacements = 0 + for group in real_groups: + if len(group) == 1: + continue + + # Align the pivots if possible. + head = group[0] + any_diff_scaled = any(are_equal(head, obj)[1] for obj in group[1:]) + if not any_diff_scaled: + print("Aligning pivots.") + for other in group[1:]: + align_pivots(other, head) + + # Get ready to clone. + for other in group[1:]: + new_obj = clone_and_align(other, head) + new_obj.name = other.name + rt.delete(other) + replacements += 1 + + # Report the results. + rt.messageBox(f"Replaced {replacements} objects.") + + +if __name__ == "__main__": + instanceify() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/match_links.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/match_links.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d0c8ea622eb6b9c06de8c31d89095688db1f71 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/match_links.py @@ -0,0 +1,239 @@ +from collections import defaultdict +import sys + +import tqdm + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +from b1k_pipeline.utils import parse_name + + +def match_links_between_instances(obj): + # Parse the name and assert it's the base link of a non-bad object + parsed_name = parse_name(obj.name) + assert parsed_name, f"Object {obj.name} has no parsed name" + # assert not parsed_name.group("bad"), f"Object {obj.name} is a bad object" + assert not ( + parsed_name.group("link_name") and parsed_name.group("link_name") != "base_link" + ), f"Object {obj.name} is not the base link" + + # Get the model ID + loose = parsed_name.group("loose") + if not loose: + loose = "" + model_id = parsed_name.group("model_id") + instance_id = parsed_name.group("instance_id") + + # First, find all the parts of this object's model, across all of its instances. + all_same_model_id = [ + x + for x in rt.objects + if ( + parse_name(x.name) + and parse_name(x.name).group("model_id") == model_id + and parse_name(x.name).group("joint_side") != "upper" + and not parse_name(x.name).group("meta_type") + and rt.classOf(x) == rt.Editable_Poly + ) + ] + same_model_id_parsed_names = [parse_name(x.name) for x in all_same_model_id] + assert all( + same_model_id_parsed_names + ), "All same model ID objects should have a parsed name" + + # Check that they are all marked as non BAD + # assert all( + # not x.group("bad") for x in same_model_id_parsed_names + # ), "All instances of the same model ID should be marked as non-bad." + + # Check that once grouped by instance ID, they all have the same set of links + links_by_instance_id = defaultdict(dict) + for inst, inst_parsed_name in zip(all_same_model_id, same_model_id_parsed_names): + link_name = inst_parsed_name.group("link_name") + if not link_name: + link_name = "base_link" + links_by_instance_id[inst_parsed_name.group("instance_id")][link_name] = inst + + # Unroll to find all links + all_links = frozenset( + link + for instance_links_to_objs in links_by_instance_id.values() + for link in instance_links_to_objs + ) + print("Found links", sorted(all_links)) + + if all_links == {"base_link"}: + print("No links to match") + return + + # Check that the currently selected instance contains all the links + base_instance_id = instance_id + if frozenset(links_by_instance_id[base_instance_id].keys()) != all_links: + # Find a maximal instance as the base instance if the current one isnt + for inst_id, links_to_objs in links_by_instance_id.items(): + if frozenset(links_to_objs.keys()) == all_links: + base_instance_id = inst_id + break + base_obj = links_by_instance_id[base_instance_id]["base_link"] + assert ( + frozenset(links_by_instance_id[base_instance_id].keys()) == all_links + ), f"Instance {base_obj.name} does not contain all links some other instances have. Pick the maximal instance." + + # For this instance, store the relative transforms of all the links + relative_transforms = {} + inverse_base_link_transform = rt.inverse(base_obj.transform) + base_link_offset_scale = base_obj.objectoffsetscale + for link_name, link_obj in links_by_instance_id[base_instance_id].items(): + if link_name == "base_link": + continue + relative_transforms[link_name] = ( + link_obj.transform * inverse_base_link_transform + ) + # print(f"Relative transform for {link_name} is {relative_transforms[link_name]}") + + # Walk through the instances to find the links that are not present in all instances + for inst_id, links_to_objs in links_by_instance_id.items(): + if inst_id == base_instance_id: + continue + + # Assert that the base link exists and grab it + assert ( + "base_link" in links_to_objs + ), f"Instance {inst_id} does not have a base link" + instance_base_link = links_to_objs["base_link"] + instance_base_link_transform = instance_base_link.transform + instance_base_link_offset_scale = instance_base_link.objectoffsetscale + + # Iterate through all the links, copy missing ones, and match transforms. + for link_name in all_links: + if link_name == "base_link": + continue + link_obj = links_to_objs.get(link_name, None) + corresponding_link_on_base_instance = links_by_instance_id[ + base_instance_id + ][link_name] + if link_obj is None: + print(f"Copying link {link_name} for instance {inst_id}") + copy_name = corresponding_link_on_base_instance.name.replace( + f"-{base_instance_id}-", f"-{inst_id}-" + ) + success, copies = rt.maxOps.cloneNodes( + [corresponding_link_on_base_instance], + cloneType=rt.name("instance"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {link_name} for instance {inst_id}" + (link_obj,) = copies + link_obj.name = copy_name + link_obj.transform = ( + relative_transforms[link_name] * instance_base_link_transform + ) + scale_ratio = instance_base_link_offset_scale / base_link_offset_scale + link_obj.objectoffsetscale = ( + corresponding_link_on_base_instance.objectoffsetscale * scale_ratio + ) + link_obj.objectoffsetpos = ( + corresponding_link_on_base_instance.objectoffsetpos * scale_ratio + ) + + +def process_all_objects(): + # Get all non-bad, zeroth-instance, base-link editable polies and process them + MODEL_WHITELIST = { + "bamfsz", + "bkdxqa", + "bmsclc", + "ceddpg", + "dladgw", + "dmwxyl", + "dnyzym", + "dqnbsj", + "ehwmol", + "emeeke", + "eobsmt", + "fexqbj", + "fqhdne", + "fqvgny", + "fwstpx", + "gemgfz", + "gfrgkk", + "ggcyib", + "gjrero", + "gpkbiw", + "ijnwlp", + "immwzb", + "inmymj", + "ithrgo", + "jhymlr", + "jongdb", + "jrhgeu", + "kctcuj", + "kfmkbm", + "ktydvs", + "kubcdk", + "kwbnhy", + "lcrefl", + "lsyzkh", + "lvgliq", + "lwjdmj", + "mfocvp", + "nfrbch", + "nnvyol", + "ntlgsx", + "nwlbit", + "ohagsq", + "pluwfl", + "pwoerr", + "pxhbim", + "qohxjq", + "rgmujm", + "rsypfh", + "rvunhj", + "rxvopf", + "slgzfc", + "spojpj", + "taqzxq", + "ufhpbn", + "ulnafj", + "uztisk", + "vudhlc", + "wwhydr", + "xbfgjc", + "xiajyb", + "xxipyh", + "xyejdx", + "yfycfx", + "ykfcaz", + } + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + parsed_name = parse_name(obj.name) + if not parsed_name: + continue + if parsed_name.group("model_id") not in MODEL_WHITELIST: + continue + if parsed_name.group("instance_id") != "0": + continue + if ( + parsed_name.group("link_name") + and parsed_name.group("link_name") != "base_link" + ): + continue + if parsed_name.group("bad"): + continue + if parsed_name.group("meta_type"): + continue + match_links_between_instances(obj) + + +def main(): + match_links_between_instances(rt.selection[0]) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/merge_collision.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/merge_collision.py new file mode 100644 index 0000000000000000000000000000000000000000..58938317cac94cc11c84d045a6e55736732fb07e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/merge_collision.py @@ -0,0 +1,65 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import b1k_pipeline.utils + +import pymxs + +rt = pymxs.runtime + + +def merge_collision(collision_objs, target, metatype="collision"): + # Convert all the objects to editable poly + for obj in collision_objs: + rt.addmodifier(obj, rt.Edit_Poly()) + rt.maxOps.collapseNodeTo(obj, 1, True) + + # Attach all of them to the first obj + baseObj = collision_objs[0] + for obj in collision_objs[1:]: + rt.polyop.attach(baseObj, obj) + + # Triangulate the faces + ttp = rt.Turn_To_Poly() + ttp.limitPolySize = True + ttp.maxPolySize = 3 + rt.addmodifier(baseObj, ttp) + rt.maxOps.collapseNodeTo(baseObj, 1, True) + + # Parent the collision object to the target object + baseObj.parent = target + + # Rename the first object to match the selected object + baseObj.name = target.name + "-M" + metatype + + # Validate that the object name is valid + assert ( + b1k_pipeline.utils.parse_name(baseObj.name) is not None + ), f"Done, but please fix invalid name {baseObj.name} for collision object" + + return baseObj + + +def select_and_merge_collision(): + collision_objs = list(rt.selection) + + # Ask the user to pick a target object + target = rt.pickobject() + + # Merge the collision objects + merge_collision(collision_objs, target) + + +def merge_collision_button(): + try: + select_and_merge_collision() + # rt.messageBox("Success!") + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + merge_collision_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/move_pivot_to_base_link.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/move_pivot_to_base_link.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc145047e5166a23f7309d48fb9c116fdc66a41 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/move_pivot_to_base_link.py @@ -0,0 +1,41 @@ +from b1k_pipeline.utils import parse_name +from collections import defaultdict + + +def move_pivot_to_base_link(): + groups = defaultdict(list) + for obj in rt.selection: + match = parse_name(obj.name) + if not match: + continue + + key = f"{match.group('category')}-{match.group('model_id')}-{match.group('instance_id')}" + groups[key].append(obj) + + for name, group_objs in groups.items(): + if len(group_objs) <= 1: + continue + + # Pick base link + base_links = [ + x + for x in group_objs + if parse_name(x.name).group("link_name") in (None, "base_link") + ] + assert len(base_links) == 1, base_links + (base_link,) = base_links + others = [x for x in group_objs if x != base_link] + + # Match pivots + for other in others: + object_in_pivot_frame = other.objecttransform * rt.inverse( + base_link.transform + ) + other.transform = base_link.transform + other.objectoffsetpos = object_in_pivot_frame.position + other.objectoffsetrot = object_in_pivot_frame.rotation + other.objectoffsetscale = object_in_pivot_frame.scale + + +if __name__ == "__main__": + move_pivot_to_base_link() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/new_sanity_check.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/new_sanity_check.py new file mode 100644 index 0000000000000000000000000000000000000000..929db18b88443d2219dcf049434ba8960a668f6a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/new_sanity_check.py @@ -0,0 +1,1469 @@ +# Install bddl by doing +# pip install git+https://github.com/StanfordVL/bddl.git@develop + +import csv +import functools +import re +import sys +import time + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import collections +import json +import pathlib +import traceback + +import numpy as np +import pandas as pd +import pymxs +import trimesh +import trimesh.transformations +from scipy.spatial.transform import Rotation + +import b1k_pipeline.utils +from b1k_pipeline.max.prebake_textures import ( + get_recorded_uv_unwrapping_hash, + hash_object, +) + +from bddl.knowledge_base import KnowledgeBase + +kb = KnowledgeBase(populate=True) + +rt = pymxs.runtime + +MAX_VERTICES = 100000 +WARN_VERTICES = 20000 + +OUTPUT_FILENAME = "sanitycheck.json" + + +ALLOWED_TAGS = {"soft", "glass", "openable", "openablebothsides", "locked"} + +ALLOWED_PART_TAGS = { + "subpart", + "extrapart", + "connectedpart", +} + + +ALLOWED_META_TYPES = { + "fluidsource": "dimensionless", + "togglebutton": "primitive", + "attachment": "dimensionless", + "heatsource": "dimensionless", + "com": "dimensionless", + "particleapplier": "primitive", + "particleremover": "primitive", + "fluidsink": "primitive", + "slicer": "primitive", + "fillable": "convexmesh", + "openfillable": "convexmesh", + "collision": "convexmesh", +} +assert not ( + set(ALLOWED_META_TYPES.values()) - {"dimensionless", "primitive", "convexmesh"} +), "Found invalid meta type mapping" + + +# Objects that don't require these meta types should not have them +REQUIRED_ONLY_META_TYPES = { + "fluidsource", + "togglebutton", + "heatsource", + "particleapplier", + "particleremover", + "fluidsink", + "slicer", + "fillable", +} + + +RENAMES = {} +with open(b1k_pipeline.utils.PIPELINE_ROOT / "metadata/object_renames.csv") as f: + for row in csv.DictReader(f): + key = (row["Original category (auto)"], row["ID (auto)"]) + RENAMES[key] = row["New Category"] + + +DELETION_QUEUE = set() +with open(b1k_pipeline.utils.PIPELINE_ROOT / "metadata/deletion_queue.csv", "r") as f: + for row in csv.DictReader(f): + DELETION_QUEUE.add(row["Object"].strip().split("-")[1]) + + +def get_required_meta_links(category): + cat = kb.get_category(category) + if cat is not None: + return cat.synset.required_meta_links + + ps = kb.get_particle_system(category) + if ps is not None: + return set() + + raise ValueError(f"Category {category} not found in taxonomy.") + + +def is_light_required(category): + # TODO: Make this more robust. + return "light" in category or "lamp" in category + + +def compute_shear(obj): + # Check that object satisfies no-shear rule. + object_transform = np.hstack( + [b1k_pipeline.utils.mat2arr(obj.objecttransform), [[0], [0], [0], [1]]] + ).T + transform = np.hstack( + [b1k_pipeline.utils.mat2arr(obj.transform), [[0], [0], [0], [1]]] + ).T + obj_to_pivot = np.linalg.inv(transform) @ object_transform + shear = trimesh.transformations.decompose_matrix(np.linalg.inv(obj_to_pivot))[1] + return shear + + +def get_approved_categories(): + # gc = gspread.service_account(filename=KEY_FILE) + # sh = gc.open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME) + + exists = [] + approved = [] + + return exists, approved + + +def get_providers(): + inventory_path = ( + b1k_pipeline.utils.PIPELINE_ROOT + / "artifacts" + / "pipeline" + / "object_inventory.json" + ) + if not inventory_path.exists(): + return None + with open(inventory_path, "r") as f: + return {k.split("-")[-1]: v for k, v in json.load(f)["providers"].items()} + + +def quat2arr(q): + return np.array([q.x, q.y, q.z, q.w]) + + +class ObjectWrapper(object): + def __init__(self, obj): + self._obj = obj + + def __getattr__(self, attr): + if attr in ["__array__", "__array_struct__", "__array_interface__", "_typ"]: + raise AttributeError() + return getattr(self._obj, attr) + + +def classOf(obj_wrapper): + return rt.classOf(obj_wrapper._obj) + + +class SanityCheck: + def __init__(self): + self.reset() + self._existing_categories, self._approved_categories = get_approved_categories() + + self.providers = get_providers() + if self.providers is None: + self.expect( + False, + "Could not load providers because inventory file is missing. The provider-related errors you see may or may not be accurate. When run as part of the pipeline, this error will resolve, but other new errors may show up.", + ) + self.providers = {} + + def expect(self, condition, message, level="ERROR"): + if not condition: + self.errors[level].append(message) + + def reset(self): + self.errors = collections.defaultdict(list) + + @functools.lru_cache(maxsize=None) + def get_verts_for_obj(self, obj): + return np.array( + rt.polyop.getVerts( + obj.baseObject, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj)) + ) + ) + + @functools.lru_cache(maxsize=None) + def get_faces_for_obj(self, obj): + try: + return ( + np.array( + rt.polyop.getFacesVerts( + obj.baseObject, + rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)), + ) + ) + - 1 + ) + except: + raise ValueError( + f"Error getting faces for {obj.name}. Did you triangulate?" + ) + + def maybe_rename_category(self, cat, model): + if (cat, model) in RENAMES: + return RENAMES[(cat, model)] + elif any(m == model and RENAMES[(c, m)] != cat for c, m in RENAMES): + self.expect( + False, + f"Model {model} has category {cat} that is neither the from or to element in the rename file.", + ) + return cat + + def is_valid_object_type(self, row): + is_valid_type = row.type in [ + rt.Editable_Poly, + rt.VRayLight, + rt.VRayPhysicalCamera, + rt.Point, + rt.Box, + rt.Cylinder, + rt.Sphere, + rt.Cone, + rt.Physical_Camera, + rt.FreeCamera, + rt.Plane, + ] + + self.expect(is_valid_type, f"{row.object_name} has disallowed type {row.type}.") + if row.object.parent is None: + is_valid_root = row.type in [ + rt.Editable_Poly, + rt.VRayLight, + rt.VRayPhysicalCamera, + rt.Physical_Camera, + rt.FreeCamera, + rt.Plane, + ] + self.expect( + is_valid_root, + f"Root-level object {row.object_name} has disallowed type {row.type}.", + ) + return is_valid_type + + def is_valid_name(self, row): + is_valid_name = ( + not pd.isna(row.object_name) + and b1k_pipeline.utils.parse_name(row.object_name) is not None + ) + self.expect(is_valid_name, f"{row.object_name} has bad name.") + return is_valid_name + + def get_recorded_vertex_and_face_count(self, model_id): + # Look the provider up from the inventory file + provider = self.providers.get(model_id, None) + self.expect( + provider is not None, + f"{model_id} has no provider in the inventory file.", + ) + + if provider is None: + return + + # Get the vertex and edge count from the provider's object list file + object_list = ( + b1k_pipeline.utils.PIPELINE_ROOT + / "cad" + / provider + / "artifacts" + / "object_list.json" + ) + if not object_list.exists(): + self.expect( + False, + f"Cannot find object list file for provider {provider}. When run as part of the pipeline, this error will resolve, but other new errors may show up.", + ) + return + with open(object_list, "r") as f: + object_list_data = json.load(f) + vertex_and_face_counts = object_list_data["mesh_fingerprints"] + self.expect( + model_id in vertex_and_face_counts, + f"{model_id} has no vertex/face count in the object list file for provider {provider}.", + ) + + if model_id not in vertex_and_face_counts: + return + + recorded_vertex_count, recorded_face_count = vertex_and_face_counts[model_id][ + :2 + ] + return recorded_vertex_count, recorded_face_count + + def validate_object(self, row): + # Check that the category exists on the spreadsheet + # self.expect( + # row.name_category in self._existing_categories, + # f"Category {row.name_category} for object {row.object_name} does not exist on spreadsheet.", + # level="WARNING") + + # Check that the category is approved on the spreadsheet + # self.expect( + # row.name_category in self._existing_categories, + # f"Category {row.name_category} for object {row.object_name} is not approved on spreadsheet.", + # level="WARNING") + + # Check that it does not have too many vertices. + # self.expect( + # row.vertex_count <= MAX_VERTICES, + # f"{row.object_name} has too many vertices: {row.vertex_count} > {MAX_VERTICES}") + + # Unwrap OBJ for below cases. + obj = row.object._obj + + # Warn if it has too many but acceptable vertices. + if not row["name_bad"]: + self.expect( + row.vertex_count <= WARN_VERTICES, + f"{row.object_name} has too many vertices: {row.vertex_count} > {WARN_VERTICES}", + level="WARNING", + ) + + self.expect( + rt.classOf(obj.material) == rt.Shell_Material, + f"{row.object_name} has non-shell material. Run texture baking.", + ) + + self.expect( + rt.classOf(obj.material) == rt.Shell_Material + and obj.material.renderMtlIndex == 1, + f"{row.object_name} is not rendering the baked material. Select the baked material for rendering or rebake.", + ) + + self.expect( + rt.classOf(obj.material) == rt.Shell_Material + and obj.material.viewportMtlIndex == 1, + f"{row.object_name} is not rendering the baked material in the viewport. Select the baked material for viewport.", + ) + + self.expect( + rt.polyop.getMapSupport(obj, 99), + f"{row.object_name} does not have a UVW map in channel 99. Reunwrap the object.", + ) + + current_hash = hash_object( + obj, + verts=self.get_verts_for_obj(obj), + faces=self.get_faces_for_obj(obj), + ) + recorded_hash = get_recorded_uv_unwrapping_hash(obj) + self.expect( + recorded_hash == current_hash, + f"{row.object_name} has different UV unwrapping than recorded. Reunwrap the object.", + ) + + # Run cloth object checks + renamed_category = self.maybe_rename_category( + row.name_category, row.name_model_id + ) + cat_obj = kb.get_category(renamed_category) + synset = cat_obj.synset.name if cat_obj else None + ps_obj = kb.get_particle_system(renamed_category) + substance_synset = ps_obj.synset.name if ps_obj else None + self.expect( + synset is not None or substance_synset is not None, + f"Cannot perform cloth/particle checks: category {renamed_category} not found in taxonomy.", + ) + + if synset is not None: + obj_is_cloth = "cloth" in kb.get_synset(synset).abilities + if obj_is_cloth: + self.validate_cloth(row) + + if substance_synset is not None: + # Check that this file is one of the substances files + self.expect( + pathlib.Path(rt.maxFilePath).resolve().parts[-1] == "substances-01", + f"{row.object_name} is a substance particle but not in the substances-01 file.", + ) + + # Check that each object zeroth instance object actually has a collision mesh + if int(row.name_instance_id) == 0 and row.name_joint_side != "upper": + for child in obj.children: + if "Mcollision" in child.name: + break + else: + self.expect( + False, + f"{row.object_name} has no collision mesh. Create a collision mesh.", + ) + + # Validate materials + if obj.material is not None: + recursive_materials = set() + + def _recursively_get_materials(mtl): + recursive_materials.add(mtl) + for i in range(rt.getNumSubMtls(mtl)): + sub_mtl = rt.getSubMtl(mtl, i + 1) + if sub_mtl is not None: + _recursively_get_materials(sub_mtl) + + _recursively_get_materials(obj.material) + + # We should NOT find more than 1 multimaterial in the entire hierarchy. If we do, + # it means that a bad merge was done and thus the face material IDs overwritten. + # Sadly this means data loss and I'm not sure how we're going to get back from it. + multimaterials = [ + mat + for mat in recursive_materials + if rt.classOf(mat) == rt.MultiMaterial + ] + self.expect( + len(multimaterials) <= 1, + f"{row.object_name} has more than one MultiMaterial in its material hierarchy. This is a bad attachment and has resulted in face material assignment loss.", + level="WARNING", + ) + + # Check the found materials for any materials that are not VrayMtl or MultiMaterial + for mat in recursive_materials: + mat_type = rt.classOf(mat) + if mat == obj.material: + # The top level material can be vray, shell, or multi + self.expect( + mat_type in (rt.MultiMaterial, rt.Shell_Material) + or "vray" in str(mat).lower(), + f"Top level material {mat} of {row.object_name} is not a MultiMaterial, Shell_Material, or VrayMtl.", + ) + elif ( + rt.classOf(obj.material) == rt.Shell_Material + and mat == obj.material.bakedMaterial + ): + # If the top level material is a Shell_Material, then the baked material should be VrayMtl + self.expect( + mat_type == rt.VrayMtl, + f"Baked material {mat} of {row.object_name} is not a VrayMtl.", + ) + else: + # Everything that's not the top level material nor the baked material should be a vraymtl or multimaterial + self.expect( + mat_type == rt.MultiMaterial or "vray" in str(mat).lower(), + f"Non-top level material {mat} of {row.object_name} is not a MultiMaterial or some kind of VRay material: {rt.classOf(mat)}", + level="WARNING", + ) + + else: + # Bad object tasks + # Validate bad objects to make sure that they do NOT have upper meshes or meta links + # or lights. + self.expect( + row.name_joint_side != "upper", + f"Bad object {row.object_name} should not have upper side.", + ) + + self.expect( + len(row.object.children) == 0, + f"Bad object {row.object_name} should not have children.", + ) + + # Bad - nonbad common tasks. + + # Check that the object is renamed properly + category = row.name_category + model_id = row.name_model_id + renamed_category = self.maybe_rename_category(category, model_id) + self.expect( + category == renamed_category, + f"{row.object_name} has unapplied rename {renamed_category}.", + level="WARNING", + ) + if model_id in DELETION_QUEUE: + self.expect( + False, + f"{row.object_name} is in the deletion queue. Delete the object.", + ) + + # Check that the object does not have any modifiers + self.expect( + len(row.object.modifiers) == 0, f"{row.object_name} has modifiers attached." + ) + + # Check that there are no dead elements + self.expect( + rt.polyop.GetHasDeadStructs(obj) == 0, + f"{row.object_name} has dead structs. Apply the Triangulate script.", + ) + + self.expect( + all( + rt.polyop.getFaceDeg(obj, i + 1) == 3 + for i in range(rt.polyop.GetNumFaces(obj)) + ), + f"{row.object_name} has non-triangular faces. Apply the Triangulate script.", + ) + + # Check that the object does not have self-intersecting faces + faces = self.get_faces_for_obj(obj) + # A face is self-intersecting if a vertex shows up more than once in the face. + self_intersecting = np.any(np.unique(faces, return_counts=True, axis=-1)[1] > 1) + self.expect( + not self_intersecting, + f"{row.object_name} has self-intersecting faces. Apply the Triangulate script.", + ) + + # Check that object satisfies the scale condition. + scale = np.array(row.object.scale) + self.expect( + np.allclose(scale, 1), + f"{row.object_name} has scale that is not 1. Reset scale.", + ) + + # Check that object does not have negative object offset scale. + object_offset_scale = np.array(row.object.objectoffsetscale) + self.expect( + np.all(object_offset_scale > 0), + f"{row.object_name} has negative object offset scale. Try mirroring + resetting scale.", + ) + + # Check that object does not have a light ID. + self.expect( + pd.isna(row.name_light_id), + f"Non-light object {row.object_name} should not have light ID.", + ) + + # Check that object does not have any meta type. + self.expect( + pd.isna(row.name_meta_info), + f"Non-meta object {row.object_name} should not have meta info.", + ) + + # Check object name format. + self.expect( + len(row.name_model_id) == 6, + f"{row.object_name} does not have 6-digit model ID.", + ) + + # Check the tags + tags = set() + tags_str = row.name_tag + if tags_str: + tags = set([x[1:] for x in tags_str.split("-") if x]) + invalid_tags = tags - (ALLOWED_TAGS | ALLOWED_PART_TAGS) + self.expect( + not invalid_tags, f"{row.object_name} has invalid tags {invalid_tags}." + ) + + part_tags = tags & ALLOWED_PART_TAGS + if row.object.parent is None: + self.expect( + not part_tags, + f"{row.object_name} is not under another object but contains part tags {part_tags}.", + ) + else: + self.expect( + part_tags, + f"Part object {row.object_name} should be marked with a part tag, one of: {ALLOWED_PART_TAGS}.", + ) + + # Validate meta stuff + if int(row.name_instance_id) == 0: + self.validate_meta_links(row) + + def validate_cloth(self, row): + # A cloth object should consist of a single connected component + obj = row.object._obj + verts = self.get_verts_for_obj(obj) + faces = self.get_faces_for_obj(obj) + tm = trimesh.Trimesh(vertices=verts, faces=faces, process=False) + + # Split the faces into elements + self.expect( + tm.body_count == 1, + f"Cloth object {obj.name} should consist of exactly 1 element. Currently it has {tm.body_count} elements.", + ) + + # A cloth object should always be clutter. + if pathlib.Path(rt.maxFilePath).resolve().parts[-2] == "scenes": + self.expect( + row.name_loose == "C-", + f"Cloth object {obj.name} is fixed or loose. It should always be clutter.", + ) + + def validate_light(self, row): + # Validate that the object has a light ID + self.expect( + not pd.isna(row.name_light_id), + f"Light object {row.object_name} should have light ID.", + ) + + # Check that the type is one of plane, sphere, disk + self.expect( + row.object.type in (0, 2, 4), + f"Light object {row.object_name} type should be one of SPHERE, DISC, PLANE", + ) + + # Light should not be scaled or offset + self.expect( + np.allclose(row.object.scale, 1), + f"Light object {row.object_name} should not have scale.", + ) + self.expect( + np.allclose(row.object.objectoffsetscale, 1), + f"Light object {row.object_name} should not have scale.", + ) + self.expect( + np.allclose(row.object.objectoffsetpos, 0), + f"Light object {row.object_name} should not have object offset position. Reset pivot.", + ) + self.expect( + np.allclose(quat2arr(row.object.objectoffsetrot), [0, 0, 0, 1]), + f"Light object {row.object_name} should not have object offset rotation. Reset pivot.", + ) + + def validate_group_of_max_instances(self, rows): + # Pick an object as the base instance + rows_with_id_zero = rows[rows["name_instance_id"] == "0"] + obj_name = rows["object_name"].iloc[0] + self.expect( + len(rows_with_id_zero.index) > 0, + f"No instance ID 0 instance of {obj_name}.", + ) + base = ( + rows_with_id_zero.iloc[0] + if len(rows_with_id_zero.index) > 0 + else rows.iloc[0] + ) + base_object = base.object._obj + + # Check that they have the same model ID and same category + unique_model_ids = rows.groupby( + ["name_category", "name_model_id"], sort=False, dropna=False + ).ngroups + self.expect( + unique_model_ids == 1, + f"All instances of {base.object_name} do not share category/model ID.", + ) + + # Check that the keys start from 0 and are contiguous. + unique_instance_ids = rows.groupby( + ["name_category", "name_model_id", "name_instance_id"], + sort=False, + dropna=False, + ).ngroups + existing_instance_ids = set(rows["name_instance_id"]) + expected_instance_ids = set(str(x) for x in range(unique_instance_ids)) + self.expect( + existing_instance_ids == expected_instance_ids, + f"All instances of {base.object_name} do not have contiguous instance IDs. Missing: {sorted(expected_instance_ids - existing_instance_ids)}", + ) + + # Check that they all have the same object offset rotation and pos/scale and shear. + desired_offset_pos = np.array(base_object.objectOffsetPos) / np.array( + base_object.objectOffsetScale + ) + desired_offset_rot_inv = Rotation.from_quat( + quat2arr(base_object.objectOffsetRot) + ).inv() + desired_shear = compute_shear(base_object) + for _, row in rows.iterrows(): + row_object = row.object._obj + this_offset_pos = np.array(row_object.objectOffsetPos) / np.array( + row_object.objectOffsetScale + ) + pos_diff = this_offset_pos - desired_offset_pos + self.expect( + np.allclose(pos_diff, 0, atol=1e-1), + f"{row.object_name} has different pivot offset position (by {pos_diff}). Match pivots on each instance.", + ) + + this_offset_rot = Rotation.from_quat(quat2arr(row_object.objectOffsetRot)) + rot_diff = (this_offset_rot * desired_offset_rot_inv).magnitude() + self.expect( + np.allclose(rot_diff, 0, atol=1e-3), + f"{row.object_name} has different pivot offset rotation (by {rot_diff}). Match pivots on each instance.", + ) + + this_shear = compute_shear(row_object) + self.expect( + np.allclose(this_shear, desired_shear, atol=1e-3), + f"{row.object_name} has different shear. Match scaling axes on each instance.", + ) + + self.expect( + row_object.material == base_object.material, + f"{row.object_name} has different material. Match materials on each instance.", + ) + + def validate_convex_mesh(self, obj, max_elements=40, max_vertices_per_element=60): + try: + # For this case, unwrap the object + obj = obj._obj + + # Expect that collision meshes do not share instances in the scene + self.expect( + not [ + x for x in rt.objects if x.baseObject == obj.baseObject and x != obj + ], + f"{obj.name} should not have instances.", + ) + + # Check that there are no dead elements + self.expect( + rt.polyop.GetHasDeadStructs(obj) == 0, + f"{obj.name} has dead structs. Apply the Triangulate script.", + ) + + # Get vertices and faces into numpy arrays for conversion + verts = self.get_verts_for_obj(obj) + faces = self.get_faces_for_obj(obj) + self.expect(len(faces) > 0, f"{obj.name} has no faces.") + self.expect( + all(len(f) == 3 for f in faces), + f"{obj.name} has non-triangular faces. Apply the Triangulate script.", + ) + + # Split the faces into elements + faces_not_yet_found = np.zeros(faces.shape[0], dtype=bool) + elems = [] + while not np.all(faces_not_yet_found): + next_not_found_face = int(np.where(~faces_not_yet_found)[0][0]) + elem = np.array( + rt.polyop.GetElementsUsingFace(obj, [next_not_found_face + 1]) + ) + assert elem[next_not_found_face], "Searched face not found in element." + elems.append(elem) + faces_not_yet_found[elem] = True + elems = np.array(elems) + self.expect( + not np.any(np.sum(elems.astype(int), axis=0) > 1), + f"{obj.name} has same face appear in multiple elements", + ) + if max_elements is not None: + self.expect( + len(elems) <= max_elements, + f"{obj.name} should not have more than {max_elements} elements. Has {len(elems)} elements.", + ) + + # Iterate through the elements + for i, elem in enumerate(elems): + # Load the mesh into trimesh and assert convexity + relevant_faces = faces[elem] + m = trimesh.Trimesh(vertices=verts, faces=relevant_faces, process=False) + m.remove_unreferenced_vertices() + if max_vertices_per_element is not None: + self.expect( + len(m.vertices) <= max_vertices_per_element, + f"{obj.name} element {i} has too many vertices ({len(m.vertices)} > {max_vertices_per_element})", + ) + self.expect(m.is_volume, f"{obj.name} element {i} is not a volume") + self.expect( + len(m.split()) == 1, + f"{obj.name} element {i} has elements trimesh still finds splittable e.g. are not watertight / connected", + ) + + # Check that the volume of the mesh and the volume of the convex hull are close. + hull = m.convex_hull + self.expect( + hull.volume > 0, + f"{obj.name} element {i} has non-positive volume convex hull, which likely indicates a problem with the mesh.", + ) + if hull.volume > 0: + volume_ratio = m.volume / hull.volume + self.expect( + volume_ratio > 0.99, + f"{obj.name} element {i} has volume {m.volume} that is very different from the volume of its convex hull {hull.volume} (ratio {volume_ratio}), which indicates that the mesh is not close to convex.", + ) + + except Exception as e: + self.expect(False, str(e)) + + def validate_meta_links(self, row): + # Don't worry about bad objects or upper links. + if row.name_joint_side == "upper": + return + + # Get the children using the parent rows + children = [ObjectWrapper(x) for x in row.object.children] + + # Expect that all of the children are valid meta-links / lights + found_ml_types = set() + found_ml_subids_for_id = collections.defaultdict( + lambda: collections.defaultdict(list) + ) + found_convex_mesh_metas = collections.defaultdict(list) + for child in children: + # Otherwise, we can validate the individual meta link + match = b1k_pipeline.utils.parse_name(child.name) + if match is None: + self.expect( + False, + f"{child.name} is an invalid meta link under {row.object_name}.", + ) + continue + + # If it's an EditablePoly with no meta tag, then it will be processed as a root object too. Safe to skip. + if classOf(child) == rt.Editable_Poly and not match.group("meta_type"): + continue + + self.expect( + match.group("mesh_basename") == row.name_mesh_basename, + f"Meta link {child.name} base name doesnt match parent {row.object_name}", + ) + + # Keep track of the meta links we have + self.expect( + match.group("meta_type"), + f"Meta object {child.name} should have a meta link type in its name.", + ) + meta_link_type = match.group("meta_type") + if meta_link_type not in ALLOWED_META_TYPES: + self.expect( + False, + f"Meta link type {meta_link_type} not in list of allowed meta link types: {ALLOWED_META_TYPES.keys()}", + ) + continue + + found_ml_types.add(meta_link_type) + + # Keep track of subids for this meta ID + meta_id = "0" + if match.group("meta_id"): + meta_id = match.group("meta_id") + meta_subid = "0" + if match.group("meta_subid"): + meta_subid = match.group("meta_subid") + found_ml_subids_for_id[meta_link_type][meta_id].append(meta_subid) + + if ALLOWED_META_TYPES[meta_link_type] == "dimensionless": + self.expect( + classOf(child) == rt.Point, + f"Dimensionless {meta_link_type} meta link {child.name} should be of Point instead of {classOf(child)}", + ) + + # Check that the position and orientation are essentially identical between the transform and the objecttransform + transform_pos = child.transform.position + transform_rot = Rotation.from_quat(quat2arr(child.transform.rotation)) + object_transform_pos = child.objecttransform.position + object_transform_rot = Rotation.from_quat( + quat2arr(child.objecttransform.rotation) + ) + self.expect( + np.allclose(transform_pos, object_transform_pos, atol=1e-3), + f"Dimensionless {meta_link_type} meta link {child.name} has nonzero object offset position.", + ) + delta_rot = (transform_rot * object_transform_rot.inv()).magnitude() + self.expect( + np.isclose(delta_rot, 0, atol=1e-3), + f"Dimensionless {meta_link_type} meta link {child.name} has nonzero object offset rotation.", + ) + elif ALLOWED_META_TYPES[meta_link_type] == "primitive": + volumetric_allowed_types = { + rt.Box, + rt.Cylinder, + rt.Sphere, + rt.Cone, + } + self.expect( + classOf(child) in volumetric_allowed_types, + f"Volumetric {meta_link_type} meta link {child.name} should be one of {volumetric_allowed_types} instead of {classOf(child)}", + ) + + scale = np.array(list(child.objecttransform.scale)) + if classOf(child) == rt.Sphere: + size = np.array([child.radius, child.radius, child.radius]) * scale + elif classOf(child) == rt.Box: + size = np.array([child.width, child.length, child.height]) * scale + elif classOf(child) == rt.Cylinder: + size = np.array([child.radius, child.radius, child.height]) * scale + elif classOf(child) == rt.Cone: + # Cones should have radius1 as 0 and radius2 nonzero + self.expect( + np.isclose(child.radius1, 0), + f"Cone {child.name} radius1 should be zero.", + ) + self.expect( + not np.isclose(child.radius2, 0) and child.radius2 > 0, + f"Cone {child.name} radius2 should be nonzero.", + ) + size = ( + np.array([child.radius2, child.radius2, child.height]) * scale + ) + # self.expect(np.all(size > 0), f"Volumetric {meta_link_type} meta link {child.name} should have positive size/scale combo.") + + elif ALLOWED_META_TYPES[meta_link_type] == "convexmesh": + # TODO: Expect that each element is a convex mesh + self.expect( + classOf(child) == rt.Editable_Poly, + f"Convex mesh {meta_link_type} meta link {child.name} should be of Editable Poly instead of {classOf(child)}", + ) + else: + raise ValueError( + "Don't know how to process meta type " + + ALLOWED_META_TYPES[meta_link_type] + ) + + if ALLOWED_META_TYPES.get(meta_link_type, None) == "convexmesh": + found_convex_mesh_metas[meta_link_type].append(child) + self.validate_convex_mesh(child) + + if meta_link_type == "collision" and row.name_category not in ( + "floors", + "driveway", + "lawn", + "ceilings", + "rail_fence", + "roof", + "walls", + ): + # For collision meshes, get the AABB of the mesh and its collision mesh and check that + # their bounds are not more than 5cm different in any direction. + child_bbox_min, child_bbox_max = rt.NodeGetBoundingBox( + child._obj, rt.Matrix3(1) + ) + child_bbox_min = np.array(child_bbox_min) + child_bbox_max = np.array(child_bbox_max) + child_bbox_volume = np.prod(child_bbox_max - child_bbox_min) + + parent_bbox_min, parent_bbox_max = rt.NodeGetBoundingBox( + row.object._obj, rt.Matrix3(1) + ) + parent_bbox_min = np.array(parent_bbox_min) + parent_bbox_max = np.array(parent_bbox_max) + parent_bbox_volume = np.prod(parent_bbox_max - parent_bbox_min) + + # Check that the bounding boxes are not more than 5cm different in any direction + self.expect( + np.all(np.abs(child_bbox_min - parent_bbox_min) < 50), + f"Collision mesh {child.name} has bounding box min {child_bbox_min} that is more than 5cm different from parent {row.object_name} min {parent_bbox_min}.", + level="WARNING", + ) + self.expect( + np.all(np.abs(child_bbox_max - parent_bbox_max) < 50), + f"Collision mesh {child.name} has bounding box max {child_bbox_max} that is more than 5cm different from parent {row.object_name} max {parent_bbox_max}.", + level="WARNING", + ) + + # TODO: Reconsider this IOU logic. The problem with this is that it is really sensitive + # to the size of the bounding box. If the bounding box is very small along any dimension, + # just a few cm's difference in the bounding box will cause the IOU to be very small. + # This is true for a lot of glass/window meshes. + # inter_min = np.maximum(child_bbox_min, parent_bbox_min) + # inter_max = np.minimum(child_bbox_max, parent_bbox_max) + # # Clamp negative/zero dimensions to zero before multiplying + # clamped_side_lengths = np.maximum(0.0, inter_max - inter_min) + # intersection_volume = np.prod(clamped_side_lengths) + # union_volume = child_bbox_volume + parent_bbox_volume - intersection_volume + # iou = intersection_volume / union_volume + # self.expect( + # iou > 0.9, + # f"Collision mesh {child.name} has low IOU with parent {row.object_name}: {iou:.2f}.", + # level="WARNING", + # ) + + if meta_link_type == "attachment": + attachment_type = match.group("meta_id") + self.expect( + len(attachment_type) > 0, + f"Missing attachment type on object {row.object_name}", + ) + self.expect( + attachment_type[-1] in "MF", + f"Invalid attachment gender {attachment_type} on object {row.object_name}", + ) + attachment_type = attachment_type[:-1] + self.expect( + len(attachment_type) > 0, + f"Missing attachment type on object {row.object_name}", + ) + + # Validate that each object has no more than one of each kind of convexmesh meta. + for mesh_type, items in found_convex_mesh_metas.items(): + self.expect( + len(items) <= 1, + f"Object {row.object_name} has {len(items)} {mesh_type} meshes. Should have no more than one.", + ) + + # Check that meta subids are correct: + for meta_type, meta_ids_to_subids in found_ml_subids_for_id.items(): + for meta_id, meta_subids in meta_ids_to_subids.items(): + expected_subids = {str(x) for x in range(len(meta_subids))} + self.expect( + set(meta_subids) == expected_subids, + f"{row.name_mesh_basename} meta type {meta_type} ID {meta_id} has non-continuous subids {sorted(meta_subids)}", + ) + + def validate_model_instance_link_group(self, group): + # Check that each link that has is not the base link has a parent and a nonempty joint type + model_id = group["name_model_id"].iloc[0] + instance_id = group["name_instance_id"].iloc[0] + link_name = group["name_link_name"].iloc[0] + descriptor = f"{model_id}-{instance_id}-{link_name}" + if link_name != "base_link": + unique_values_for_joint_type = group["name_joint_type"].unique() + self.expect( + len(unique_values_for_joint_type) == 1 + and pd.notnull(unique_values_for_joint_type[0]), + f"{descriptor} should have exactly one nonempty joint type: {unique_values_for_joint_type}.", + ) + self.expect( + group["name_parent_link_name"].nunique() == 1 + and pd.notnull(group["name_parent_link_name"].iloc[0]), + f"{descriptor} should have exactly one nonempty parent link name: {group['name_parent_link_name'].unique()}.", + ) + + should_have_upper = ( + link_name != "base_link" + and instance_id == "0" + and not group["name_bad"].iloc[0] + and group["name_joint_type"].iloc[0] != "F" + ) + if should_have_upper: + self.expect( + "upper" in group["name_joint_side"].unique(), + f"{descriptor} should have an upper side.", + ) + else: + self.expect( + "upper" not in group["name_joint_side"].unique(), + f"{descriptor} should not have an upper side.", + ) + + def validate_model_instance_group(self, group): + # Check that the model instance group has a base link. + self.expect( + "base_link" in group["name_link_name"].unique(), + f"Model ID {group['name_model_id'].iloc[0]} is missing 'base_link'.", + ) + + # Get the model and instance ID + self.expect( + group["name_category"].nunique() == 1, + f"Model ID {group['name_model_id'].iloc[0]} has inconsistent categories.", + ) + category = group["name_category"].iloc[0] + assert group["name_model_id"].nunique() == 1 + model_id = group["name_model_id"].iloc[0] + assert group["name_instance_id"].nunique() == 1 + instance_id = group["name_instance_id"].iloc[0] + + # First assert that the group has exactly one value for name_bad + self.expect( + group["name_bad"].nunique() <= 1, + f"Model ID {group['name_model_id'].iloc[0]} has inconsistent bad values: {group['name_bad'].unique()}.", + ) + + # Validate the link groups + group.groupby("name_link_name").apply(self.validate_model_instance_link_group) + + # If the instance group belongs to a bad object, validate the bad object matches the + # total vertex and face count from the other file. + if group["name_bad"].iloc[0]: + # Compute the total vertex and face count for the model instance group + real_vertex_count = group["vertex_count"].sum() + real_face_count = group["face_count"].sum() + # Get the recorded vertex and face count for the model ID + recorded_counts = self.get_recorded_vertex_and_face_count(model_id) + if recorded_counts is None: + self.expect( + "False", + f"{model_id} has no recorded face and vertex counts. Make sure you run object list first.", + ) + else: + recorded_vertex_count, recorded_face_count = recorded_counts + # Check that the total vertex and face count matches the recorded vertex and face count + self.expect( + real_vertex_count == recorded_vertex_count, + f"{model_id}-{instance_id} has different vertex count than recorded in provider: {real_vertex_count} != {recorded_vertex_count}.", + ) + self.expect( + real_face_count == recorded_face_count, + f"{model_id}-{instance_id} has different face count than recorded in provider: {real_face_count} != {recorded_face_count}.", + ) + + # If this is the zeroth instance, check the object's meta links set + if instance_id == "0" and not group["name_bad"].iloc[0]: + try: + # First validate that if the object requires joints, it has them + renamed_category = self.maybe_rename_category(category, model_id) + required_meta_types = get_required_meta_links(renamed_category) + + requires_joints = "joint" in required_meta_types + if requires_joints: + # it should contain at least one revolute or prismatic joint + # TODO: Perhaps also assert the presence of an openable tag later. + self.expect( + set(group["name_joint_type"].unique()) & {"R", "P"}, + f"Model ID {model_id} requires joints but has no joints.", + ) + + # Then look at meta link types + def get_meta_type(o): + pn = b1k_pipeline.utils.parse_name(o.name) + return pn.group("meta_type") if pn else None + + found_ml_types = { + get_meta_type(child) + for group_obj in group["object"] + for child in group_obj.children + } + found_ml_types -= {None} + + required_meta_types -= { + "subpart", + "joint", + } + existing_meta_types = set(found_ml_types) + if "openfillable" in existing_meta_types: + existing_meta_types.add("fillable") + missing_meta_types = required_meta_types - existing_meta_types + if missing_meta_types: + for missing_meta_type in missing_meta_types: + self.expect( + False, + f"{model_id} is missing meta link: {missing_meta_type}.", + ) + + # Also make sure that things that don't require a meta link don't have one, + # for certain specific cases. + found_nonoptional_meta_types = ( + existing_meta_types & REQUIRED_ONLY_META_TYPES + ) + found_extra_nonoptional_meta_types = ( + found_nonoptional_meta_types - required_meta_types + ) + if found_extra_nonoptional_meta_types: + for extra_meta_type in found_extra_nonoptional_meta_types: + self.expect( + False, + f"{model_id} has meta link not required by its synset: {extra_meta_type}.", + level="WARNING", + ) + except ValueError as e: + self.expect( + False, + f"Cannot validate meta links and joints for model ID {model_id}: {e}", + ) + + def validate_model_group(self, group): + category = group["name_category"].iloc[0] + model_id = group["name_model_id"].iloc[0] + + # Check that the group's model ID does not contain the phrase "todo" + self.expect( + "todo" not in model_id, + f"Model ID {model_id} contains 'todo'.", + ) + + # Check that every instance of this model group has the same set of links. + self.expect( + group.groupby("name_instance_id")["name_link_name"] + .apply(frozenset) + .nunique() + == 1, + f"Inconsistent link sets within model ID {model_id}.", + ) + + # Then individually validate each of the model instances + group.groupby("name_instance_id").apply(self.validate_model_instance_group) + + # For each instance, record the scale of the base link, and the positional offset of the + # child links in the base link's frame. Assert that after scaling these numbers are close. + links_relative_transforms = {} + + def record_links(group): + instance_id = group["name_instance_id"].iloc[0] + # Check that there is a base link row + assert ( + "base_link" in group["name_link_name"].unique() + ), f"Model ID {model_id} instance {instance_id} is missing base link. Found: {group['name_link_name'].unique()}" + base_link_row = group[group["name_link_name"] == "base_link"].iloc[0] + base_link_transform = base_link_row.object.objecttransform + inverse_base_link_transform = rt.inverse(base_link_transform) + + links_relative_transforms[instance_id] = {} + for _, row in group.iterrows(): + link_name = row["name_link_name"] + + # Skip the base link + if link_name == "base_link": + continue + + # Skip upper sides + if row["name_joint_side"] == "upper": + continue + + # Compute the relative transform + child_link_transform = row.object.objecttransform + relative_transform = child_link_transform * inverse_base_link_transform + links_relative_transforms[instance_id][link_name] = relative_transform + + group.groupby("name_instance_id").apply(record_links) + + # Go through all the available links + for link_name in group["name_link_name"].unique(): + # Skip base link + if link_name == "base_link": + continue + + # Get the relative transform of the first object + if link_name not in links_relative_transforms["0"]: + self.expect( + False, + f"{model_id} link {link_name} is missing in instance 0, so relative transform check cannot be completed. Found zeroth instance links: {links_relative_transforms['0']}.", + ) + continue + instance_zero_relative_transform = links_relative_transforms["0"].get( + link_name + ) + inverse_instance_zero_relative_transform = rt.inverse( + instance_zero_relative_transform + ) + + # For each instance, check that the relative transform is the same + for instance_id, link_transforms in links_relative_transforms.items(): + if link_name not in link_transforms: + self.expect( + False, + f"{model_id} link {link_name} is missing in instance {instance_id}, so relative transform check cannot be completed.", + ) + continue + relative_transform = link_transforms[link_name] + + # Check that the relative transform is the same + if instance_id != "0": + transform_difference = ( + relative_transform * inverse_instance_zero_relative_transform + ) + + # Decompose the transform difference into position, rotation and scale + scale_difference = np.array(transform_difference.scale) + position_difference = np.array(transform_difference.position) + rotation_difference = Rotation.from_quat( + quat2arr(transform_difference.rotation) + ) + + self.expect( + np.allclose(scale_difference, 1, atol=0.02), + f"{model_id} link {link_name} has different scale in instance {instance_id} compared to instance 0. Scale difference: {scale_difference}.", + ) + self.expect( + np.allclose( + position_difference, 0, atol=5 + ), # Up to 5mm is fine + f"{model_id} link {link_name} has different position in instance {instance_id} compared to instance 0. Position difference: {position_difference}.", + ) + self.expect( + np.isclose( + rotation_difference.magnitude(), 0, atol=np.deg2rad(2) + ), + f"{model_id} link {link_name} has different rotation in instance {instance_id} compared to instance 0. Rotation difference: {rotation_difference.magnitude()}.", + ) + + # Additionally, if the model group has more than one link, check warn if the base links of different instances + # have different scale, because this might have broken things during runs of the match links script. + if group["name_link_name"].nunique() > 1: + one_base_link_scale = np.array( + group[group["name_link_name"] == "base_link"] + .iloc[0] + .object.objectoffsetscale + ) + base_link_rows = group[group["name_link_name"] == "base_link"] + + self.expect( + all( + np.allclose( + one_base_link_scale, np.array(x.object.objectoffsetscale) + ) + for _, x in base_link_rows.iterrows() + ), + f"Articulated object {group['name_model_id'].iloc[0]} instances have different scales for base links. This may have broken things during the match links script.", + level="WARNING", + ) + + def run(self): + self.reset() + + # current_path = pathlib.Path(rt.maxFilePath).resolve() / rt.maxFileName + # try: + # cad_path = b1k_pipeline.utils.PIPELINE_ROOT / "cad" + # path_relative_to_cad = current_path.relative_to(cad_path) + # self.expect(path_relative_to_cad.parts[0] in ('scenes', 'objects'), f"Cad file should be in 'scenes' or 'objects' directory, not in {path_relative_to_cad.parts[0]}.") + # directory = path_relative_to_cad.parts[1] + # self.expect(re.fullmatch(r"^[a-z0-9_]+-[a-z0-9]{2}$", directory), f"Cad file should be in a directory with lowercase alphanumeric characters and a two-character suffix, not {directory}.") + # self.expect(path_relative_to_cad.name == "processed.max", f"Cad file should be called processed.max, not {path_relative_to_cad.name}.") + # self.expect(len(path_relative_to_cad.parts) == 3, f"Cad file should be directly in the target directory, not {len(path_relative_to_cad.parts)}. Expected format: scenes/[target]/processed.max") + # except ValueError: + # self.expect(False, f"The cad file should be placed under the BEHAVIOR_1K/asset_pipeline/cad directory, within one of the scenes/ or objects/ directories, in a subdirectory named with lowercase alphanumeric characters and a two-character suffix, and named processed.max. Current path: {current_path}") + + self.expect(rt.units.systemScale == 1, "System scale not set to 1mm.") + + self.expect( + rt.units.systemType == rt.Name("millimeters"), + "System scale not set to 1mm.", + ) + + # First get all of the objects + df = pd.DataFrame(data={"object": [ObjectWrapper(x) for x in rt.objects]}) + + # Add some helpful data + df["object_name"] = df["object"].map(lambda x: x.name) + df["base_object"] = df["object"].map(lambda x: x.baseObject) + df["type"] = df["object"].map(lambda x: classOf(x)) + + # Complain about and remove objects that are the wrong type. + good_type = df.apply(self.is_valid_object_type, axis="columns") + df = df[good_type] + + # Additionally filter out the cameras + df = df[df["type"].isin([rt.Editable_Poly, rt.VRayLight])] + + # Complain about and remove objects that have unmatching name. + good_name = df.apply(self.is_valid_name, axis="columns") + df = df[good_name] + + if df.size == 0: + return self.errors + + # Check that the object names are unique. + duplicate_named_objs = df[df.duplicated(subset=["object_name"], keep="first")] + duplicate_named_objs.apply( + lambda row: self.expect(False, f"{row.object_name} is not unique."), axis=1 + ) + + # Unwrap the name into its columns + col_to_name = { + v - 1: "name_" + k + for k, v in b1k_pipeline.utils.NAME_PATTERN.groupindex.items() + } + applied_df = df.apply( + lambda row: list(b1k_pipeline.utils.parse_name(row.object_name).groups()), + axis="columns", + result_type="expand", + ) + applied_df.rename(columns=col_to_name, inplace=True) + df = pd.concat([df, applied_df], axis="columns") + # no-link-name objects are matched with the base link. + df["name_link_name"] = df["name_link_name"].fillna("base_link") + + # Check that meta links are not at root level + meta_links = df[df["name_meta_type"].notnull()] + meta_links.apply( + lambda row: self.expect( + row.object.parent is not None, + f"{row.object_name} is a meta link at root level. Place it under the appropriate object.", + ), + axis="columns", + ) + + non_meta_polies = df[ + (df["type"] == rt.Editable_Poly) & df["name_meta_type"].isnull() + ] + non_meta_polies["vertex_count"] = non_meta_polies["object"].map( + lambda x: rt.polyop.getNumVerts(x._obj) + ) + non_meta_polies["face_count"] = non_meta_polies["object"].map( + lambda x: rt.polyop.getNumFaces(x._obj) + ) + + # Check that when grouped by model ID, the instances all have the same set + # of links, and that "base_link" is included. + grouped_by_model = non_meta_polies.groupby("name_model_id") + grouped_by_model.apply(self.validate_model_group) + + # Run the single-object validation checks. + non_meta_polies.apply(self.validate_object, axis="columns") + + # Check that instance name-based grouping is equal to instance-based grouping. + groups_by_base_object = non_meta_polies.groupby( + ["base_object"], sort=False, dropna=False + ) + groups_by_base_object.apply( + lambda group: self.expect( + group.groupby( + ["name_category", "name_model_id", "name_link_name"], + sort=False, + dropna=False, + ).ngroups + == 1, + f"{group.iloc[0].object_name} has instances that are named differently. If this is a link, note that different links should not be instances of each other.", + ) + ) + + # Here make groups that we EXPECT to all be instances of the same object. + groups_by_max_instance_expectation = non_meta_polies.groupby( + ["name_category", "name_model_id", "name_link_name"], + sort=False, + dropna=False, + ) + groups_by_max_instance_expectation.apply( + lambda group: self.expect( + group.groupby(["base_object"], sort=False, dropna=False).ngroups == 1, + f"{group.iloc[0].object_name} has objects that are expected to be instances upon looking at their name (e.g. same model ID and link name) but are not actually instances in 3ds Max.", + ) + ) + + # Let's use the base-object grouping for the instance group validation: + groups_by_base_object.apply(self.validate_group_of_max_instances) + + lights = df[df["type"] == rt.VRayLight] + lights.apply(self.validate_light, axis="columns") + + # TODO: Check that the lights are all non-bad + # TODO: Check that each light object has a valid base. + # TODO: Check that each light object is numbered consecutively. + # TODO: Check that light-named objects have lights on them. + + return self.errors + + +def sanity_check_safe(batch=False): + success = False + errors = [] + warnings = [] + + start_time = time.time() + try: + results = SanityCheck().run() + errors = results["ERROR"] + warnings = results["WARNING"] + success = len(errors) == 0 + except Exception as e: + t = traceback.format_exc() + errors.append("Exception occurred:" + t) + + end_time = time.time() + total_time = end_time - start_time + + # Print results in interactive mode. + if not batch: + print(f"Sanity check completed in {total_time:.2f} seconds.") + if success: + print("No errors found!") + else: + print("Errors found:") + print("\n".join(errors)) + + if warnings: + print("Warnings:") + print("\n".join(warnings)) + + if batch: + output_dir = pathlib.Path(rt.maxFilePath) / "artifacts" + output_dir.mkdir(parents=True, exist_ok=True) + with open(output_dir / OUTPUT_FILENAME, "w") as f: + json.dump( + { + "success": success, + "errors": errors, + "warnings": warnings, + "total_time": total_time, + }, + f, + indent=4, + ) + + +if __name__ == "__main__": + opts = rt.maxops.mxsCmdLineArgs + + batch = opts[rt.name("batch")] == "true" + sanity_check_safe(batch=batch) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/next_failed.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/next_failed.py new file mode 100644 index 0000000000000000000000000000000000000000..8a5b0543939b88755d7d840655339bcbec21e30e --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/next_failed.py @@ -0,0 +1,90 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import glob +import json +import pathlib +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +import b1k_pipeline.utils + +rt = pymxs.runtime + +file_name = "sanitycheck.json" +# file_name = "object_list.json" +# file_name = "export_meshes.json" + + +def file_eligible(objdir): + sanitycheck = objdir / "artifacts" / file_name + + if not sanitycheck.exists(): + print( + f"{str(objdir)} is missing object list or sanitycheck. Unsure if it failed." + ) + return False + + with open(sanitycheck, "r") as f: + x = json.load(f) + if not x["success"]: + return True + + return False + + +def next_failed(): + eligible_max = [] + for target in b1k_pipeline.utils.get_targets("combined"): + objdir = b1k_pipeline.utils.PIPELINE_ROOT / "cad" / target + if objdir.exists() and file_eligible(objdir): + eligible_max.append(objdir / "processed.max") + + eligible_max.sort() + print(len(eligible_max), "files remaining.") + print("\n".join(str(x) for x in eligible_max)) + if eligible_max: + # Find current file in the list + current_max_dir = pathlib.Path(rt.maxFilePath).resolve() + next_idx = 0 + try: + next_idx = ( + next( + i + for i, max in enumerate(eligible_max) + if max.parent.resolve() == current_max_dir + ) + + 1 + ) % len(eligible_max) + except: + pass + + print(f"File {next_idx} of {len(eligible_max)}") + scene_file = eligible_max[next_idx] + assert ( + not scene_file.is_symlink() + ), f"File {scene_file} should not be a symlink." + assert rt.loadMaxFile( + str(scene_file), useFileUnits=False, quiet=True + ), f"Could not load {scene_file}" + + sanitycheck_file = eligible_max[next_idx].parent / "artifacts" / file_name + print(sanitycheck_file.read_text()) + + +def next_failed_button(): + try: + next_failed() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + next_failed_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/object_list.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/object_list.py new file mode 100644 index 0000000000000000000000000000000000000000..19d2f1445feba902f5960980102898c743e039ee --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/object_list.py @@ -0,0 +1,493 @@ +import sys + +import numpy as np + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import json +import pathlib +from collections import Counter, defaultdict + +import pymxs + +import b1k_pipeline.utils +import trimesh.transformations + +rt = pymxs.runtime + +OUTPUT_FILENAME = "object_list.json" +COMPLEX_FINGERPRINT = False +MUST_HAVE_ROOM_ASSIGNMENT_CATEGORIES = {"wall_nail"} + + +def quat2arr(q): + return np.array([q.x, q.y, q.z, q.w]) + + +def compute_moment_of_inertia(triangles, reference_point=None): + """ + Compute the moment of inertia matrix for a triangle mesh around a reference point. + + Parameters: + triangles: numpy array of shape (n, 3, 3) where n is the number of triangles, + and each triangle is defined by 3 points with x,y,z coordinates + reference_point: point around which to compute the moment of inertia (default: mesh centroid) + + Returns: + numpy array of shape (3, 3) representing the moment of inertia matrix + """ + + assert ( + triangles.ndim == 3 and triangles.shape[1] == 3 and triangles.shape[2] == 3 + ), f"Bad triangle shape {triangles.shape}" + + def triangle_area(triangle): + """Compute area of a single triangle using cross product.""" + v1 = triangle[1] - triangle[0] + v2 = triangle[2] - triangle[0] + return 0.5 * np.linalg.norm(np.cross(v1, v2)) + + def triangle_centroid(triangle): + """Compute centroid of a triangle.""" + return np.mean(triangle, axis=0) + + # Compute areas and total surface area + areas = np.array([triangle_area(tri) for tri in triangles]) + total_area = np.sum(areas) + + # Compute surface mass density + surface_density = 1.0 / total_area + + # Compute centroids + centroids = np.array([triangle_centroid(tri) for tri in triangles]) + assert centroids.shape == ( + triangles.shape[0], + 3, + ), f"Bad centroids shape {centroids.shape}" + + # If no reference point provided, use mesh centroid + if reference_point is None: + reference_point = np.average(centroids, weights=areas, axis=0) + assert reference_point.shape == ( + 3, + ), f"Bad reference point shape {reference_point.shape}" + + # Initialize moment of inertia matrix + I = np.zeros((3, 3)) + + # For each triangle + for triangle, area, centroid in zip(triangles, areas, centroids): + # Translate triangle to reference point + translated_points = triangle - reference_point + + # Compute local moment of inertia around triangle centroid + local_I = np.zeros((3, 3)) + + # For each point in the triangle + for point in translated_points: + x, y, z = point + # Contribution to moment of inertia matrix + local_I[0, 0] += y * y + z * z + local_I[1, 1] += x * x + z * z + local_I[2, 2] += x * x + y * y + local_I[0, 1] -= x * y + local_I[0, 2] -= x * z + local_I[1, 2] -= y * z + + # Make matrix symmetric + local_I[1, 0] = local_I[0, 1] + local_I[2, 0] = local_I[0, 2] + local_I[2, 1] = local_I[1, 2] + + # Scale by area and surface density + local_I *= area * surface_density / 12 + + # Apply parallel axis theorem + r = centroid - reference_point + parallel_axis_term = ( + area * surface_density * (np.eye(3) * np.dot(r, r) - np.outer(r, r)) + ) + + # Add to total moment of inertia + I += local_I + parallel_axis_term + + return I, reference_point + + +def main(): + object_names = [x.name for x in rt.objects if rt.classOf(x) == rt.Editable_Poly] + matches = [b1k_pipeline.utils.parse_name(name) for name in object_names] + nomatch = [name for name, match in zip(object_names, matches) if match is None] + + success = len(nomatch) == 0 + needed = sorted( + { + x.group("category") + "-" + x.group("model_id") + for x in matches + if x is not None and not x.group("meta_type") + } + ) + provided = sorted( + { + x.group("category") + "-" + x.group("model_id") + for x in matches + if x is not None and not x.group("bad") and not x.group("meta_type") + } + ) + counts = Counter( + [ + x.group("category") + "-" + x.group("model_id") + for x in matches + if x is not None and not x.group("meta_type") + ] + ) + max_tree = [ + (x.name, str(rt.classOf(x)), x.parent.name if x.parent else None) + for x in rt.objects + ] + + meshes = sorted( + name + for match, name in zip(matches, object_names) + if match is not None and not match.group("meta_type") + ) + + meta_links = defaultdict(set) + + attachment_pairs = defaultdict( + lambda: defaultdict(set) + ) # attachment_pairs[model_id][F/M] = {attachment_type1, attachment_type2} + bad_attachments = [] + + # Store vertex/face counts for bad model matching + pivots_and_mesh_parts = defaultdict(list) + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + + # It needs to be a name-matching object + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + + # Check if this is the 0th instance and the lower mesh and not a meta link and not bad + if match.group("joint_side") == "upper" or match.group("meta_type"): + continue + + # Otherwise store the vertex and face info for the model ID + model_id = match.group("model_id") + instance_id = int(match.group("instance_id")) + + # Record the orientation of the base link + pivot = ( + None + if match.group("link_name") and match.group("link_name") != "base_link" + else obj.transform + ) + + # Get vertices and faces into numpy arrays for conversion + num_verts = rt.polyop.GetNumVerts(obj) + num_faces = rt.polyop.GetNumFaces(obj) + verts = None + faces = None + if COMPLEX_FINGERPRINT: + verts = np.array([rt.polyop.getVert(obj, i + 1) for i in range(num_verts)]) + faces = ( + np.array( + rt.polyop.getFacesVerts(obj, rt.execute("#{1..%d}" % num_faces)) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + pivots_and_mesh_parts[(model_id, instance_id)].append( + (pivot, obj, verts, faces, num_verts, num_faces) + ) + + # Accumulate bounding boxes for each instance + bounding_boxes = defaultdict(dict) + for (model_id, instance_id), parts in pivots_and_mesh_parts.items(): + # Find the pivot and get a copy that's position and rotation only. + (possibly_scaled_pivot,) = [x[0] for x in parts if x[0] is not None] + pivot = rt.Matrix3(1) + pivot.rotation = possibly_scaled_pivot.rotation + pivot.position = possibly_scaled_pivot.position + + # Walk through the objs and get their bounding box w.r.t. the pivot + mins = [] + maxes = [] + for _, obj, _, _, _, _ in parts: + bbox_min, bbox_max = rt.NodeGetBoundingBox(obj, pivot) + mins.append(np.array(bbox_min)) + maxes.append(np.array(bbox_max)) + bbox_min = np.min(mins, axis=0) + bbox_max = np.max(maxes, axis=0) + bbox_extent = bbox_max - bbox_min + bbox_center_in_pivot = rt.Point3(*((bbox_max + bbox_min) / 2.0).tolist()) + + bbox_position_in_world = np.array(pivot.position) + np.array( + bbox_center_in_pivot * pivot.rotation + ) + bbox_rotation_in_world = quat2arr(pivot.rotation) + + bounding_boxes[model_id][instance_id] = { + "layer": obj.layer.name, + "position": bbox_position_in_world.tolist(), + "rotation": bbox_rotation_in_world.tolist(), + "extent": bbox_extent.tolist(), + } + + # Accumulate the vertex and face counts and the moments of inertia + mesh_fingerprints = {} + for (model_id, instance_id), parts in pivots_and_mesh_parts.items(): + if instance_id != 0: + continue + + # Flatten the faces into a single array of triangles (keeping track of original vertex counts) + vertex_count = 0 + face_count = 0 + triangle_subs = [] + pivots = [] + for orientation, _, verts, faces, num_verts, num_faces in parts: + vertex_count += num_verts + face_count += num_faces + if COMPLEX_FINGERPRINT: + triangle_subs.append(verts[faces]) + if orientation is not None: + pivots.append(orientation) + + # Grab the orientation + assert ( + len(pivots) == 1 + ), f"Expected 1 orientation for {model_id}, got {len(pivots)}" + max_pivot = pivots[0] + pivot = np.hstack( + [b1k_pipeline.utils.mat2arr(max_pivot), [[0], [0], [0], [1]]] + ).T + + flattened_moment_of_inertia = None + pivot_to_centroid = None + if COMPLEX_FINGERPRINT: + triangles = np.concatenate(triangle_subs, axis=0) # Flatten the triangles + + # Orient the mesh such that it is in the frame of the orientation + world_to_pivot = np.linalg.inv(pivot) + oriented_triangles = trimesh.transformations.transform_points( + triangles.reshape(-1, 3), world_to_pivot + ).reshape(triangles.shape) + + # Rescale the mesh around its bounding box to exactly fit the unit cube. + min_bound = np.min(triangles.reshape(-1, 3), axis=0) + max_bound = np.max(triangles.reshape(-1, 3), axis=0) + center = (min_bound + max_bound) / 2 + assert center.shape == (3,), f"Bad center shape {center.shape}" + scale = max_bound - min_bound + assert scale.shape == (3,), f"Bad scale shape {scale.shape}" + scale[np.isclose(scale, 0)] = 1.0 # avoid degenerate cases + scaled_triangles = (oriented_triangles - center) / scale + + # Compute the moment of inertia + I, centroid = compute_moment_of_inertia(scaled_triangles) + assert centroid.shape == (3,), f"Bad centroid shape {centroid.shape}" + assert I.shape == (3, 3), f"Bad moment of inertia shape {I.shape}" + + # Where would the pivot be in the scaled frame? + pivot_scaled = -center / scale + assert pivot_scaled.shape == ( + 3, + ), f"Bad scaled pivot shape {pivot_scaled.shape}" + + # Compute the pivot-to-centroid vector in the scaled frame + pivot_to_centroid = (centroid - pivot_scaled).tolist() + flattened_moment_of_inertia = I.flatten().tolist() + + # Store the vertex count, face count, moment of inertia and pivot-to-centroid vector as the mesh fingerprint + mesh_fingerprints[model_id] = ( + vertex_count, + face_count, + flattened_moment_of_inertia, + pivot_to_centroid, + ) + + # Find meta links + for obj, _, parent in max_tree: + if not parent: + continue + parent_match = b1k_pipeline.utils.parse_name(parent) + obj_match = b1k_pipeline.utils.parse_name(obj) + if not parent_match or not obj_match: + continue + if not obj_match.group("meta_type") or parent_match.group("bad"): + continue + parent_id = ( + parent_match.group("category") + "-" + parent_match.group("model_id") + ) + meta_type = obj_match.group("meta_type") + meta_links[parent_id].add(meta_type) + + if meta_type == "attachment": + attachment_type = obj_match.group("meta_id") + if not attachment_type: + bad_attachments.append( + f"Missing attachment type/gender on object {obj}" + ) + if attachment_type[-1] not in "MF": + bad_attachments.append( + f"Invalid attachment gender {attachment_type} on object {obj}" + ) + attachment_side = attachment_type[-1] + attachment_type = attachment_type[:-1] + if not attachment_type: + bad_attachments.append(f"Missing attachment type on object {obj}") + attachment_pairs[parent_id][attachment_side].add(attachment_type) + + # Find connected parts and add them into the attachment pairs + for obj, _, parent in max_tree: + if not parent: + continue + parent_match = b1k_pipeline.utils.parse_name(parent) + obj_match = b1k_pipeline.utils.parse_name(obj) + if not parent_match or not obj_match: + continue + tags_str = obj_match.group("tag") + if not tags_str or parent_match.group("bad"): + continue + tags = {x[1:] for x in tags_str.split("-") if x} + if "connectedpart" not in tags: + continue + + # Generate the attachment pair name + part_model = obj_match.group("model_id") + attachment_pair = f"{part_model}parent" + + # Add the male side on the part + part_id = obj_match.group("category") + "-" + part_model + attachment_pairs[part_id]["M"].add(attachment_pair) + + # Add the female side on the parent + parent_id = ( + parent_match.group("category") + "-" + parent_match.group("model_id") + ) + attachment_pairs[parent_id]["F"].add(attachment_pair) + + # Find joints + for obj, _, _ in max_tree: + obj_match = b1k_pipeline.utils.parse_name(obj) + if not obj_match: + continue + if obj_match.group("joint_type") not in ["R", "P"]: + continue + parent_id = obj_match.group("category") + "-" + obj_match.group("model_id") + meta_links[parent_id].add("joint") + + meta_links = {k: sorted(v) for k, v in sorted(meta_links.items())} + attachment_pairs = { + k: {kk: sorted(vv) for kk, vv in sorted(v.items())} + for k, v in sorted(attachment_pairs.items()) + } + + # Start storing the data + results = { + "success": success, + "needed_objects": needed, + "provided_objects": provided, + "meshes": meshes, + "meta_links": meta_links, + "attachment_pairs": attachment_pairs, + "max_tree": max_tree, + "object_counts": counts, + "bounding_boxes": bounding_boxes, + "mesh_fingerprints": mesh_fingerprints, + "error_invalid_name": sorted(nomatch), + "error_bad_attachment": bad_attachments, + } + + # For scenes, do this stuff that used to be in room_object_list only + is_scene = pathlib.Path(rt.maxFilePath).parts[-2] == "scenes" + if is_scene: + object_instances_by_room = defaultdict(lambda: defaultdict(set)) + missing_room_assignment = set() + + for obj in rt.objects: + if rt.classOf(obj) != rt.Editable_Poly: + continue + + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + + model = match.group("category") + "-" + match.group("model_id") + + room_strs = obj.layer.name + for room_str in room_strs.split(","): + room_str = room_str.strip() + if room_str == "0": + if match.group("category") in MUST_HAVE_ROOM_ASSIGNMENT_CATEGORIES: + missing_room_assignment.add(obj.name) + continue + object_instances_by_room[room_str][model].add( + int(match.group("instance_id")) + ) + + objects_by_room = { + room: {mid: len(instances) for mid, instances in models.items()} + for room, models in object_instances_by_room.items() + } + + # Separately process portals + portals = [x for x in rt.objects if rt.classOf(x) == rt.Plane] + incoming_portal = None + outgoing_portals = {} + portal_nomatch = [] + for portal in portals: + portal_match = b1k_pipeline.utils.parse_portal_name(portal.name) + if not portal_match: + portal_nomatch.append(portal.name) + continue + + # Get portal info + position = np.array(portal.position) + rotation = portal.rotation + quat = quat2arr(rotation) + scale = np.array(list(portal.scale)) + size = np.array([portal.width, portal.length]) * scale[:2] + + portal_info = [position.tolist(), quat.tolist(), size.tolist()] + + # Process incoming portal + if portal_match.group("partial_scene") is None: + assert incoming_portal is None, "Duplicate incoming portal" + incoming_portal = portal_info + else: + scene_name = portal_match.group("partial_scene") + assert ( + scene_name not in outgoing_portals + ), f"Duplicate outgoing portal for scene {scene_name}" + outgoing_portals[scene_name] = portal_info + + success = ( + success and len(portal_nomatch) == 0 and len(missing_room_assignment) == 0 + ) + results.update( + { + "success": success, + "objects_by_room": objects_by_room, + "incoming_portal": incoming_portal, + "outgoing_portals": outgoing_portals, + "error_invalid_name_portal": sorted(portal_nomatch), + "error_missing_room_assignment": sorted(missing_room_assignment), + } + ) + + output_dir = pathlib.Path(rt.maxFilePath) / "artifacts" + output_dir.mkdir(parents=True, exist_ok=True) + + filename = output_dir / OUTPUT_FILENAME + with open(filename, "w") as f: + json.dump(results, f, indent=4) + + print("success:", success) + print("error_invalid_name:", sorted(nomatch)) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/object_qa.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/object_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..0fe107f3470bddb208b54335a52f9c770341862d --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/object_qa.py @@ -0,0 +1,131 @@ +import csv +import json +import os +import sys +import textwrap + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +import nltk + +nltk.download("wordnet") +nltk.download("omw-1.4") +from nltk.corpus import wordnet as wn + +from b1k_pipeline.utils import parse_name, PIPELINE_ROOT + +IGNORE_CATEGORIES = {"walls", "floors", "ceilings"} + +PASS_NAME = "benjamin-scene-looseness" +RECORD_PATH = PIPELINE_ROOT / "qa-logs" / f"{PASS_NAME}.json" + +CATEGORY_TO_SYNSET = {} +with open(PIPELINE_ROOT / "metadata/category_mapping.csv", "r") as f: + r = csv.DictReader(f) + for row in r: + CATEGORY_TO_SYNSET[row["category"].strip()] = row["synset"].strip() + + +def get_synset(category): + if category not in CATEGORY_TO_SYNSET: + return "", "" + + synset = CATEGORY_TO_SYNSET[category] + + # Read the custom synsets from the CSV file + custom_synsets = [] + with open(PIPELINE_ROOT / "metadata/custom_synsets.csv", "r") as csvfile: + reader = csv.reader(csvfile) + for row in reader: + if synset == row[1]: + return row[1] + " (custom synset)", row[2] + "(hypernyms): " + ( + wn.synset(row[2]) + ).definition() + try: + synset = wn.synset(synset) + except: + return "", "" + return synset.name(), synset.definition() + + +def main(): + # Read completed groups record + completed_groups = set() + if os.path.exists(RECORD_PATH): + with open(RECORD_PATH) as f: + completed_groups = set(json.load(f)) + + # Find incomplete groups + parsed_names = [parse_name(x.name) for x in rt.objects] + available_groups = { + x.group("category") + "-" + x.group("model_id") + for x in parsed_names + if x is not None + and int(x.group("instance_id")) == 0 + and x.group("category") not in IGNORE_CATEGORIES + } + remaining_groups = sorted(available_groups - completed_groups) + if not remaining_groups: + rt.messageBox("Scene complete.") + return + + # Find objects corresponding to the next remaining group's instance zero + next_group = remaining_groups[0] + next_group_objects = [] + has_loose = False + has_fixed = False + has_clutter = False + for obj in rt.objects: + n = parse_name(obj.name) + if n is None: + continue + if int(n.group("instance_id")) != 0: + continue + if n.group("category") + "-" + n.group("model_id") != next_group: + continue + next_group_objects.append(obj) + obj.isHidden = False + if n.group("loose") == "L-": + has_loose = True + elif n.group("loose") == "C-": + has_clutter = True + else: + has_fixed = True + + # Select that object and print + rt.select(next_group_objects) + rt.IsolateSelection.EnterIsolateSelectionMode() + rt.execute("max tool zoomextents") + print( + f"{len(available_groups) - len(remaining_groups) + 1} / {len(available_groups)}: {next_group}" + ) + + if has_loose and not has_fixed and not has_clutter: + print("Used as loose") + elif has_fixed and not has_loose and not has_clutter: + print("Used as fixed") + elif has_clutter and not has_loose and not has_fixed: + print("Used as clutter") + else: + print( + textwrap.fill( + f"Used as loose: {has_loose}. Used as fixed: {has_fixed}. Used as clutter: {has_clutter}" + ) + ) + + # Show a popup with the synset info + # category_name = next_group.split("-")[0] + # synset_name, synset_desc = get_synset(category_name) + # print(textwrap.fill(f"Category {category_name} is currently mapped to synset {synset_name} ({synset_desc})")) + + # Record that object as completed + with open(RECORD_PATH, "w") as f: + json.dump(list(completed_groups | {next_group}), f) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/prebake_textures.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/prebake_textures.py new file mode 100644 index 0000000000000000000000000000000000000000..8a01cada5c1ece148dfdf4cca3340e87faf12172 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/prebake_textures.py @@ -0,0 +1,450 @@ +import pathlib +import sys +import traceback +import hashlib + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import os +import traceback +import numpy as np +from pymxs import runtime as rt +import time +import re +import b1k_pipeline.utils + +_prebake_data_str = """attributes "prebakeData" attribID:#(0x6c7ac544, 0x36f63a5f) version:1 +( + parameters main rollout:params + ( + hashDigest type:#string ui:hashDigest default:"" + ) + + rollout params "Prebake Data" + ( + edittext hashDigest "Mesh hash digest from last unwrap:" fieldWidth:300 labelOnTop:true + ) +)""" +PrebakeDataAttr = rt.execute(_prebake_data_str) + +btt = rt.BakeToTexture + +BATCH_MODE = False +USE_UNWRELLA = True +IMG_SIZE = 1024 +HQ_IMG_SIZE = 4096 +HQ_IMG_CATEGORIES = {"floors", "lawn", "driveway", "walls"} +NEW_UV_CHANNEL = 99 +USE_NATIVE_UNWRAPPING_ON_ERROR = True + +# PBRMetalRough +# CHANNEL_MAPPING = { +# "VRayRawDiffuseFilterMap": "Base Color Map", +# "VRayBumpNormalsMap": "Normal Map", +# # "VRayMtlReflectGlossinessBake": "Roughness Map", +# } + +# PhysicalMaterial +CHANNEL_MAPPING = { + "VRayRawDiffuseFilterMap": "Diffuse map", # or VRayDiffuseFilter + "VRayNormalsMap": "Bump map", # or VRayBumpNormals + "VRayMtlReflectGlossinessBake": "Refl. gloss.", # iGibson/Omniverse renderer expects we flip the glossiness map + "VRayRawReflectionFilterMap": "Reflect map", + "VRayRawRefractionFilterMap": "Refract map", + "VRayMetalnessMap": "Metalness", # requires V-ray 5, update 2.3 + "VRayMtlReflectIORBake": "Fresnel IOR", +} + +CHANNEL_DATA_FORMAT_OVERRIDES = { + "VRayMtlReflectIORBake": "exr", +} + +# CHANNEL_MAPPING = { +# "Color": "Base Color Map", +# "Normal": "Bump Map", +# } + +RENDER_PRESET_FILENAME = str( + ( + b1k_pipeline.utils.PIPELINE_ROOT / "render_presets" / "no_sampler_no_gi.rps" + ).absolute() +) + +allow_list = [] +black_list = [] + + +def unlight_mats_recursively(mat): + if mat: + if hasattr(mat, "selfIllumination_multiplier"): + mat.selfIllumination_multiplier = 0.0 + for i in range(mat.numsubs): + submat = mat[i] + unlight_mats_recursively(submat) + + +def unlight_all_mats(): + materials = {x.material for x in rt.objects} + for mat in materials: + unlight_mats_recursively(mat) + + +def hash_object(obj, verts=None, faces=None): + # This optionally takes verts and faces so that the precached ones from sanitycheck can be used. + + if verts is None: + # Create a numpy array containing the vertex positions and the faces + # Notice by getting this from the baseObject we get them in the object's local space + # which is NOT the pivot space. + verts = np.array( + rt.polyop.getVerts( + obj.baseObject, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj)) + ) + ) + + if faces is None: + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + + # Notice that we are adding 0. here. That is to avoid an absolutely INSANE bug where + # 3ds Max returns -0. sometimes and 0. other times, causing the hash to be different + # for very few objects because very few bytes differ. Adding zero makes all zeros positive. + verts = verts + 0.0 + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + # Hash the vertices and faces + return hashlib.sha256(verts.tobytes() + faces.tobytes()).hexdigest() + + +def get_recorded_uv_unwrapping_hash(obj): + prebake_data_attr = rt.custAttributes.get(obj, PrebakeDataAttr) + if not prebake_data_attr: + return None + + hash_digest = prebake_data_attr.hashDigest + if not hash_digest: + return None + + return hash_digest + + +def set_recorded_uv_unwrapping_hash(obj, hash_digest): + if not rt.custAttributes.get(obj, PrebakeDataAttr): + rt.custAttributes.add(obj, PrebakeDataAttr) + + prebake_data_attr = rt.custAttributes.get(obj, PrebakeDataAttr) + prebake_data_attr.hashDigest = hash_digest + + +class TextureBaker: + def __init__(self, bakery): + self.MAP_NAME_TO_IDS = self.get_map_name_to_ids() + + self.unwrap_times = {} + + self.bakery = bakery + os.makedirs(bakery, exist_ok=True) + + @staticmethod + def get_map_name_to_ids(): + map_name_to_ids = {} + for item in btt.getCompatibleMapTypes(): + map_name = item.split(" : ")[0] + class_id_str = item[item.rindex("(") + 1 : item.rindex(")")] + id_tuples = tuple([int(item) for item in class_id_str.split(", ")]) + map_name_to_ids[map_name] = id_tuples + return map_name_to_ids + + def get_process_objs(self): + objs = [] + candidates = rt.objects if len(rt.selection) == 0 else rt.selection + for obj in candidates: + if rt.classOf(obj) != rt.Editable_Poly: + continue + if allow_list and all( + re.fullmatch(p, obj.name) is None for p in allow_list + ): + continue + if black_list and any( + re.fullmatch(p, obj.name) is not None for p in black_list + ): + continue + parsed_name = b1k_pipeline.utils.parse_name(obj.name) + if parsed_name.group("meta_type"): + continue + if parsed_name.group("instance_id") != "0": + continue + if parsed_name.group("bad"): + continue + if parsed_name.group("joint_side") == "upper": + continue + + objs.append(obj) + + return objs + + def uv_unwrapping_unwrella(self, obj): + u = rt.Unwrella() + rt.addmodifier(obj, u) + u.stretch = 1 # We allow for any amount of stretching. This was originally 0.15. + u.rescale = True + u.combine = False + u.prerotate = True + u.packmode = 0 # Classic. Go 1 for Efficient and 2 for High Quality. + u.map_channel = NEW_UV_CHANNEL + u.keep_seams = False + u.unwrap_mode = 1 # 0 for organic. 1 is for hard-edge objects which most of ours are. + + u.padding = 2 + u.width = 1024 + u.height = 1024 + u.preview = False + + rt.modPanel.setCurrentObject(u) + rt.completeRedraw() + rt.windows.processPostedMessages() + time.sleep(3) + + u.unwrap() + time.sleep(3) + assert u.success, f"Unwrapping error w/ {obj.name}: {u.error}" + + def uv_unwrapping_native(self, obj): + modifier = rt.unwrap_uvw() + rt.addmodifier(obj, modifier) + + modifier.unwrap2.setApplyToWholeObject(True) + + # In case the object is already uv unwrapped, we will need to assign to a new UV channel + modifier.setMapChannel(NEW_UV_CHANNEL) + modifier.unwrap2.flattenMapNoParams() + + def uv_unwrapping(self, obj): + rt.select(obj) + + # Select all faces in preparation for uv unwrap + rt.polyop.setFaceSelection(obj, rt.name("all")) + + # Check if the object is already unwrapped with the same geometry + current_hash = hash_object(obj) + recorded_hash = get_recorded_uv_unwrapping_hash(obj) + if rt.polyop.getMapSupport(obj, 99) and recorded_hash == current_hash: + # print(f"Skipping unwrapping for {obj.name} as it has not changed.") + return + + start_time = time.time() + + print("uv_unwrapping", obj.name) + + rt.polyop.setMapSupport(obj, 99, False) + assert not rt.polyop.getMapSupport( + obj, 99 + ), f"Failed to clear UV channel 99 for {obj.name} prior to unwrapping" + if USE_UNWRELLA: + try: + self.uv_unwrapping_unwrella(obj) + if not rt.polyop.getMapSupport(obj, 99): + raise ValueError("Unwrella failed to unwrap the object.") + except Exception as e: + if USE_NATIVE_UNWRAPPING_ON_ERROR: + print( + f"Unwrella failed for {obj.name} with error {e}, falling back to native unwrapping." + ) + self.uv_unwrapping_native(obj) + else: + raise e + else: + self.uv_unwrapping_native(obj) + assert rt.polyop.getMapSupport( + obj, 99 + ), f"Could not unwrap UVs for object {obj.name}" + rt.polyop.setFaceSelection(obj, rt.name("all")) + + # Flatten the modifier stack + rt.maxOps.collapseNodeTo(obj, 1, True) + + # Record metadata about the hash at the time of the unwrapping. + post_unwrap_hash = hash_object(obj) + assert ( + post_unwrap_hash == current_hash + ), f"Hash mismatch before and after unwrapping: {post_unwrap_hash} != {current_hash}" + set_recorded_uv_unwrapping_hash(obj, current_hash) + + # If it's assigned to a baked material, switch back to the unbaked material. + if rt.classOf(obj.material) == rt.Shell_Material: + obj.material = obj.material.originalMaterial + + rt.update(obj) + + end_time = time.time() + self.unwrap_times[obj.name] = end_time - start_time + + def prepare_texture_baking(self, obj): + # If the object is already connected to a baked material, skip the baking process + if ( + rt.classOf(obj.material) == rt.Shell_Material + and obj.material.renderMtlIndex == 1 + ): + # print(f"Skipping baking for {obj.name} as it is already baked.") + return + + # Also skip objects whose material is not some kind of a Vray material + # if "vray" not in str(rt.classOf(obj.material)).lower(): + # print(f"Skipping baking for {obj.name} as it is not a Vray material.") + # return + + # Get the existing baseobject children that use the same material as this one + siblings = [] + for candidate in rt.objects: + if candidate.baseObject == obj.baseObject: + siblings.append(candidate) + + # Disconnect the existing baked material + if rt.classOf(obj.material) == rt.Shell_Material: + obj.material = obj.material.originalMaterial + + # print("prepare_texture_baking", obj.name) + + for i, map_name in enumerate(CHANNEL_MAPPING.keys()): + texture_map = btt.addMapByClassId(obj, self.MAP_NAME_TO_IDS[map_name]) + + # Only the first channel requires creating the new PhysicalMaterial + if i == 0: + btt.setOutputTo(obj, "CreateNewMaterial", material=rt.VrayMtl()) + # btt.setOutputTo(obj, "CreateNewMaterial", material=rt.PBRMetalRough()) + + # Make sure the new UV channel is selected + texture_map.uvChannel = NEW_UV_CHANNEL + img_size = IMG_SIZE + if ( + b1k_pipeline.utils.parse_name(obj.name).group("category") + in HQ_IMG_CATEGORIES + ): + img_size = HQ_IMG_SIZE + texture_map.imageWidth = img_size + texture_map.imageHeight = img_size + texture_map.edgePadding = 4 + texture_map.fileType = CHANNEL_DATA_FORMAT_OVERRIDES.get(map_name, "png") + + # Set the apply color mapping option + if ( + texture_map.getOptionsCount() > 0 + and texture_map.getOptionName(1) == "Apply color mapping" + ): + texture_map.setOptionValue(1, False) + + # Mapping from the original channel (of VRay, Corona, etc) to the new channel of PhysicalMaterial + texture_map.setTargetMapSlot(CHANNEL_MAPPING[map_name]) + + return siblings + + def postprocess_texture_baking(self, obj, siblings): + # Set the object to render the baked material + obj.material.renderMtlIndex = 1 + + new_mtl = obj.material.bakedMaterial + new_mtl.name = obj.name + "__baked" + new_mtl.reflection_lockIOR = False + for map_idx in range(rt.getNumSubTexmaps(new_mtl)): + channel_name = rt.getSubTexmapSlotName(new_mtl, map_idx + 1) + texmap = rt.getSubTexmap(new_mtl, map_idx + 1) + if texmap: + texmap.name = f"{obj.name}__baked__{channel_name}" + + # Update everything that has the same baseobject to use the same material + for sibling in siblings: + sibling.material = obj.material + rt.update(sibling) + + rt.update(obj) + + def texture_baking(self): + # vray = rt.renderers.current + # vray.camera_autoExposure = False + # vray.options_lights = False + # vray.options_hiddenLights = False + rt.sceneexposurecontrol.exposurecontrol = None + + # Bake textures + btt.outputPath = self.bakery + btt.autoCloseProgressDialog = True + btt.showFrameBuffer = False + btt.alwaysOverwriteExistingFiles = True + + # Do the actual baking + start_time = time.time() + print("start baking") + assert btt.bake(), "baking failed" + end_time = time.time() + print(f"finish baking. baking took {end_time - start_time} seconds") + + # Clear the baking list again. + btt.deleteAllMaps() + + def run(self): + # assert rt.classOf(rt.renderers.current) == rt.V_Ray_5__update_2_3, f"Renderer should be set to V-Ray 5.2.3 CPU instead of {rt.classOf(rt.renderers.current)}" + assert rt.execute("max modify mode") + + # Remove lights from all materials + # unlight_all_mats() + + # Remove the texture baking list + btt.deleteAllMaps() + + objs = self.get_process_objs() + print(f"Found {len(objs)} objects to process.") + postprocessing = [] # (obj, siblings) + for i, obj in enumerate(objs): + # print(f"{(i + 1)} / {len(objs)}: {obj.name}") + + rt.select([obj]) + rt.IsolateSelection.EnterIsolateSelectionMode() + + obj.isHidden = False + for child in obj.children: + child.isHidden = False + + # TODO: Can we bake all at once? + self.uv_unwrapping(obj) + siblings = self.prepare_texture_baking(obj) + if siblings is None: # not baking this object! + continue + + if not BATCH_MODE: + # If we're not in batch mode, bake now. + self.texture_baking() + self.postprocess_texture_baking(obj, siblings) + else: + # Otherwise, queue for postprocessing for after baking. + postprocessing.append((obj, siblings)) + + if BATCH_MODE: + # Bake + self.texture_baking() + + # Postprocessing + for obj, siblings in postprocessing: + self.postprocess_texture_baking(obj, siblings) + + +def process_open_file(): + preset_categories = rt.renderpresets.LoadCategories(RENDER_PRESET_FILENAME) + assert rt.renderpresets.Load(0, RENDER_PRESET_FILENAME, preset_categories) + + rt.setvraysilentmode(True) + + # TODO: Assert that the bakery path is unprotected + bakery_path = pathlib.Path(rt.maxFilePath) / "bakery" + bakery_path.mkdir(exist_ok=True) + exp = TextureBaker(str(bakery_path)) + exp.run() + + +if __name__ == "__main__": + process_open_file() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/prereduce.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/prereduce.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce22e613bc50025119fa2a97bf7cd044772f227 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/prereduce.py @@ -0,0 +1,75 @@ +import pymxs + +rt = pymxs.runtime + +VERTEX_COUNT = 20000 + +STOP_AFTER_EVERY_OBJECT = True + + +def prereduce(): + done_bases = set() + for obj in rt.objects: + # Once per set of instances. + if obj.baseObject in done_bases: + continue + + # Only for complex objects. + if len(obj.vertices) <= VERTEX_COUNT: + continue + + # Only do objects that don't already have multires on them. + if any( + [ + rt.classOf(x) == rt.multiRes or rt.classOf(x) == rt.ProOptimizer + for x in obj.modifiers + ] + ): + continue + + print(f"Processing object {obj.name}.") + + # multires = rt.multiRes() + # rt.addModifier(obj, multires) + + # rt.windows.ProcessPostedMessages() + + # multires.reqGenerate = True + + # # For some reason this needs to be called twice + # rt.windows.ProcessPostedMessages() + + # multires.vertexCount = VERTEX_COUNT + + rt.select(obj) + + optimizer = rt.ProOptimizer() + rt.addModifier(obj, optimizer) + optimizer.KeepTextures = True + optimizer.Calculate = True + + # Nasty hack to force Calculate to be executed + rt.completeRedraw() + + optimizer.vertexCount = VERTEX_COUNT + + edit_poly = rt.edit_poly() + rt.addModifier(obj, edit_poly) + + if STOP_AFTER_EVERY_OBJECT: + rt.select(obj) + rt.IsolateSelection.EnterIsolateSelectionMode() + return + + done_bases.add(obj.baseObject) + + print("Prereduce done.") + rt.IsolateSelection.ExitIsolateSelectionMode() + if not STOP_AFTER_EVERY_OBJECT: + rt.messageBox( + f"{len(done_bases)} objects processed. Please confirm visually reasonable vertex count (and reduce as necessary)." + ) + + +if __name__ == "__main__": + prereduce() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/qa_next_failed.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/qa_next_failed.py new file mode 100644 index 0000000000000000000000000000000000000000..017d333ce2bef31b1b4c018c036ea7050dfbaa7a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/qa_next_failed.py @@ -0,0 +1,96 @@ +import re +import sys +import bisect + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import json +import pathlib + +import pymxs + +import b1k_pipeline.utils + +rt = pymxs.runtime + +type_re = re.compile(r"([A-Z\-]+):") +ignore_messages = ["SYNSET", "CATEGORY", "ABILITIES", "SUBSTANCE", "STRUCTURE-UNCLOSED"] + + +def file_eligible(objdir): + complaint_path = objdir / "complaints.json" + + if not complaint_path.exists(): + return False + + with open(complaint_path, "r") as f: + x = json.load(f) + for complaint in x: + if complaint["processed"]: + continue + + complaint_type = "PREVIOUS PASS" + m = type_re.match(complaint["message"]) + if m: + complaint_type = m.group(1) + + if complaint_type in ignore_messages: + continue + + return True + + return False + + +def next_failed(): + eligible_max = [] + for target in b1k_pipeline.utils.get_targets("objects"): + objdir = b1k_pipeline.utils.PIPELINE_ROOT / "cad" / target + if objdir.exists() and file_eligible(objdir): + eligible_max.append(objdir / "processed.max") + + eligible_max.sort() + symlinks = [x for x in eligible_max if x.is_symlink()] + # If there are any symlinks, print dvc unprotect command and stop + if symlinks: + print("There are symlinks! Run the following commands:") + for start in range(0, len(symlinks), 50): + batch = symlinks[start : start + 50] + print( + "dvc unprotect", + " ".join( + str(x.relative_to(b1k_pipeline.utils.PIPELINE_ROOT)) for x in batch + ), + ) + return + + print(len(eligible_max), "files remaining.") + print("\n".join(str(x) for x in eligible_max)) + if eligible_max: + current_max = pathlib.Path(rt.maxFilePath).resolve() / "processed.max" + next_idx = 0 + try: + next_idx = bisect.bisect(eligible_max, current_max) % len(eligible_max) + except Exception as e: + print(e) + + scene_file = eligible_max[next_idx] + assert ( + not scene_file.is_symlink() + ), f"File {scene_file} should not be a symlink." + assert rt.loadMaxFile( + str(scene_file), useFileUnits=False, quiet=True + ), f"Could not load {scene_file}" + + +def next_failed_button(): + try: + next_failed() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + next_failed_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/qa_next_failed_task_required.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/qa_next_failed_task_required.py new file mode 100644 index 0000000000000000000000000000000000000000..cc832767696d7cbb0f932a174f234f273759cce0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/qa_next_failed_task_required.py @@ -0,0 +1,109 @@ +import bisect +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") +import csv +import json +import pathlib +from collections import defaultdict + +import pymxs + +import b1k_pipeline.utils + +rt = pymxs.runtime + +ignore_messages = [ + "Confirm reasonable bounding box size:", + "Confirm object synset assignment.", +] + + +def file_eligible(objdir): + complaint_path = objdir / "complaints.json" + + if not complaint_path.exists(): + return False + + with open(complaint_path, "r") as f: + x = json.load(f) + if any( + not y["processed"] + for y in x + if not any(y["message"].startswith(ign) for ign in ignore_messages) + ): + return True + + return False + + +def next_failed(): + with open(rf"C:\Users\Vince\Downloads\task_required_objects.csv", "r") as f: + reader = csv.reader(f) + task_required_objects = {row[0].split("-")[-1] for row in reader} + + with open( + b1k_pipeline.utils.PIPELINE_ROOT / "artifacts/pipeline/object_inventory.json", + "r", + ) as f: + providers = json.load(f)["providers"] + provided = defaultdict(set) + for object, provider in providers.items(): + provided[provider].add(object.split("-")[-1]) + + eligible_max = [] + for target in b1k_pipeline.utils.get_targets("objects"): + # Get the objects from this target + target_provided = provided[target] + + if target_provided & task_required_objects: + objdir = b1k_pipeline.utils.PIPELINE_ROOT / "cad" / target + if objdir.exists() and file_eligible(objdir): + eligible_max.append(objdir / "processed.max") + + eligible_max.sort() + symlinks = [x for x in eligible_max if x.is_symlink()] + # If there are any symlinks, print dvc unprotect command and stop + if symlinks: + print("There are symlinks! Run the following commands:") + for start in range(0, len(symlinks), 50): + batch = symlinks[start : start + 50] + print( + "dvc unprotect", + " ".join( + str(x.relative_to(b1k_pipeline.utils.PIPELINE_ROOT)) for x in batch + ), + ) + return + + print(len(eligible_max), "files remaining.") + print("\n".join(str(x) for x in eligible_max)) + if eligible_max: + # Find current file in the list + current_max = pathlib.Path(rt.maxFilePath).resolve() / "processed.max" + next_idx = 0 + try: + next_idx = bisect.bisect(eligible_max, current_max) % len(eligible_max) + except Exception as e: + print(e) + + scene_file = eligible_max[next_idx] + assert ( + not scene_file.is_symlink() + ), f"File {scene_file} should not be a symlink." + assert rt.loadMaxFile( + str(scene_file), useFileUnits=False, quiet=True + ), f"Could not load {scene_file}" + + +def next_failed_button(): + try: + next_failed() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + next_failed_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/randomize_obj_names.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/randomize_obj_names.py new file mode 100644 index 0000000000000000000000000000000000000000..0bde05a1d9bd29a8f30e7db845131cd6224ac705 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/randomize_obj_names.py @@ -0,0 +1,83 @@ +import os +import random +import re +import string +from collections import defaultdict + +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs +import yaml +import b1k_pipeline.utils + +rt = pymxs.runtime + +TRANSLATION_PATH = b1k_pipeline.utils.PIPELINE_ROOT / "b1k_pipeline/model_rename.yml" +with open(TRANSLATION_PATH, "r") as f: + TRANSLATION_DICT = yaml.load(f, Loader=yaml.SafeLoader) + +PATTERN = re.compile( + r"^(?PB-)?(?PF-)?(?PL-)?(?P[a-z_]+)-(?P[a-zA-Z0-9_]+)-(?P[0-9]+)(?:-(?P[a-z0-9_]+))?(?:-(?P[A-Za-z0-9_]+)-(?P[RPF])-(?Plower|upper))?(?:-L(?P[0-9]+))?(?:-M(?P[a-z_]+)(_(?P[0-9]+))?)?(?P(?:-T[a-z]+)*)$" +) + + +def parse_name(name): + return PATTERN.fullmatch(name) + + +def randomize_names(): + objs = list(rt.selection) + + # Start by grouping objects by category / model. + objs_by_model = defaultdict(list) + for obj in objs: + if obj in rt.cameras: + continue + + result = parse_name(obj.name) + assert result is not None, "{} does not match naming convention".format( + obj.name + ) + category, model_id = result.group("category"), result.group("model_id") + if result.group("bad"): + # For bad objects we can process directly. We simply perform necessary translations. + translation_key = category + "/" + model_id + if translation_key in TRANSLATION_DICT: + new_cat, new_model = TRANSLATION_DICT[translation_key].split("/") + old_str = "-".join([category, model_id]) + new_str = "-".join([new_cat, new_model]) + obj.name = obj.name.replace(old_str, new_str) + + objs_by_model[(category, model_id)].append(obj) + + # Then for each group, we assign a new random model ID. + for category, model_id in objs_by_model: + # if re.fullmatch(r"^[a-z]{6}$", model_id): + # continue + + new_cat = category + new_model = "".join(random.choice(string.ascii_lowercase) for _ in range(6)) + + old_str = "-".join([category, model_id]) + new_str = "-".join([new_cat, new_model]) + print(f"renaming {old_str} to {new_str}") + for obj in objs_by_model[(category, model_id)]: + obj.name = obj.name.replace(old_str, new_str) + + +def randomize_names_safe(): + try: + randomize_names() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Names randomized!") + + +if __name__ == "__main__": + randomize_names_safe() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_and_rescale.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_and_rescale.py new file mode 100644 index 0000000000000000000000000000000000000000..08b51536292b5b3f935d4a495e2d12e312eea5d3 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_and_rescale.py @@ -0,0 +1,232 @@ +from collections import defaultdict +import csv +import json +import sys +import tqdm + +import numpy as np + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pathlib + +import pymxs +from trimesh.transformations import transform_points + + +import b1k_pipeline.utils +from b1k_pipeline.max.new_sanity_check import SanityCheck + +rt = pymxs.runtime + + +RECORD_RELPATH = "rename_and_rescale.success" + + +def compute_bounding_box(objs): + objs = [x for x in objs if rt.classOf(x) == rt.Editable_Poly] + (base,) = [ + x + for x in objs + if b1k_pipeline.utils.parse_name(x.name).group("link_name") + in (None, "", "base_link") + and not b1k_pipeline.utils.parse_name(x.name).group("meta_type") + ] + transform = np.eye(4) + transform[:3] = b1k_pipeline.utils.mat2arr(base.transform).T + invt = np.linalg.inv(transform) + + all_pts = [] + for obj in objs: + # Skip non-lower ends + if b1k_pipeline.utils.parse_name(obj.name).group("joint_side") == "upper": + continue + + # Get all the vertices + X = np.array( + rt.polyop.getVerts(obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(obj))) + ) + + # Convert them into the base frame + pts = transform_points(X, invt) + + # Add them into the list + all_pts.append(pts.min(axis=0)) + all_pts.append(pts.max(axis=0)) + + # Now fit a bounding box in that space + all_pts = np.array(all_pts) + bb_min = all_pts.min(axis=0) + bb_max = all_pts.max(axis=0) + return np.abs(bb_max - bb_min) + + +def processFile(pipeline_fs, target, renames, deletions, avg_dims): + # Load file, fixing the units + max_path = pipeline_fs.target(target).getsyspath("processed.max") + assert rt.loadMaxFile(max_path, useFileUnits=False, quiet=True) + assert rt.units.systemScale == 1, "System scale not set to 1mm." + assert rt.units.systemType == rt.Name("millimeters"), "System scale not set to 1mm." + + # Take care of resizing. + if False: # "objects/legacy_" in target: + # First, group things by object ID + objs_by_model = defaultdict(list) + for obj in rt.objects: + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + cat = match.group("category") + model_id = match.group("model_id") + instance_id = match.group("instance_id") + objs_by_model[(cat, model_id, instance_id)].append(obj) + + # Identify the base object. + # This is the object that has the same ID as the file name. + base_key = next( + k for k in objs_by_model.keys() if k[1] == target.split("-")[-1] + ) + base_objs = objs_by_model[base_key] + bb_ext = np.sort(compute_bounding_box(base_objs)) + avg_cat_dims = np.sort(avg_dims[base_key[0]]) + scale_factors = avg_cat_dims / bb_ext + + # Make sure that the max scale is not more than x times the min scale + if scale_factors.max() / scale_factors.min() > 10: + raise ValueError( + f"Object {base_key} has scales that vary by too much: {scale_factors}" + ) + scale_factor = float(scale_factors.min()) + + # Apply the scale + for obj in rt.objects: + # Multiply everything + obj.position *= scale_factor + obj.objectoffsetpos *= scale_factor + obj.objectoffsetscale *= scale_factor + + # Now take care of renames and deletions + objects = list(rt.objects) + for obj in objects: + match = b1k_pipeline.utils.parse_name(obj.name) + if not match: + continue + + # Check if it's on the deletion queue + model_id = match.group("model_id") + assert len(model_id) == 6, f"Object ID {model_id} is not 6 digits long." + # if match.group("model_id") in deletions: + # rt.delete(obj) + # continue + + # Otherwise check if it's in the rename list + category = match.group("category") + rename_key = f"{category}-{model_id}" + if model_id in renames: + old_name, new_name = renames[model_id] + # assert rename_key == old_name, f"Rename key {rename_key} does not match old name {old_name}." + obj.name = obj.name.replace(rename_key, new_name) + + # Run a final sanity check + sc = SanityCheck().run() + if sc["ERROR"]: + raise ValueError(f"Sanity check failed for {target}:\n{sc['ERROR']}") + + # Save again. + rt.saveMaxFile(max_path) + + # Touch file to record the file as processed + pipeline_fs.target_output(target).touch(RECORD_RELPATH) + + +def rename_and_rescale_all_files(): + pipeline_fs = b1k_pipeline.utils.PipelineFS() + targets = b1k_pipeline.utils.get_targets("combined") + + # Load data for renames + with pipeline_fs.open("metadata/object_renames.csv", "r") as f: + reader = csv.DictReader(f) + renames = {} + for row in reader: + obj_id = row["ID (auto)"] + old_cat = row["Original category (auto)"] + new_cat = row["New Category"] + in_name = f"{old_cat}-{obj_id}" + out_name = f"{new_cat}-{obj_id}" + renames[obj_id] = (in_name, out_name) + + # Load files for deletion + with pipeline_fs.open("metadata/deletion_queue.csv", "r") as f: + reader = csv.DictReader(f) + deletions = set() + # for row in reader: + # obj_name = row["Object"] + # obj_id = obj_name.split("-")[1] + # assert len(obj_id) == 6, f"Deletion object ID {obj_id} is not 6 digits long." + # deletions.add(obj_id) + + # Load the scale needed for each category + # with open(r"C:\Users\Cem\research\iGibson-dev\igibson\data\ig_dataset\metadata\avg_category_specs.json", "r") as f: + # avg_specs = json.load(f) + # avg_dims = {cat: np.array(spec["size"]) * 1000 for cat, spec in avg_specs.items()} + avg_dims = {} + + # Find the targets that contain these objects + selected_targets = [] + print("Preprocessing targets...") + for target in tqdm.tqdm(targets): + # See if the target was already processed + # if pipeline_fs.target_output(target).exists(RECORD_RELPATH): + # continue + + # Open the target's object list + # with pipeline_fs.target_output(target).open("object_list.json", "r") as f: + # object_list = set(json.load(f)["needed_objects"]) + mesh_list = rt.getMAXFileObjectNames( + pipeline_fs.target(target).getsyspath("processed.max"), quiet=True + ) + match_list = [b1k_pipeline.utils.parse_name(mesh) for mesh in mesh_list] + object_list = { + match.group("category") + "-" + match.group("model_id") + for match in match_list + if match + } + ids = {x.split("-")[1] for x in object_list} + + # See if the target needs any of the operations + has_rename = ids & set(renames.keys()) + has_deletion = ids & deletions + has_scale = False # "objects/legacy_" in target + if has_rename or has_deletion or has_scale: + selected_targets.append(target) + + print("Remaining files:", len(selected_targets)) + + # Before processing, check if any of the remaining targets are symlinks, and unprotect them + paths = [ + pathlib.Path(pipeline_fs.target(target).getsyspath("processed.max")) + for target in selected_targets + ] + symlinks = [p for p in paths if p.is_symlink()] + if symlinks: + print("Found symlinks. Run below commands to unprotect them in DVC.") + for batch_start in range(0, len(symlinks), 50): + print( + "dvc unprotect", + " ".join( + str(p.relative_to(b1k_pipeline.utils.PIPELINE_ROOT)) + for p in symlinks[batch_start : batch_start + 50] + ), + ) + return + + for i, f in enumerate(sorted(selected_targets)): + print(f"Processing file {i + 1}/{len(selected_targets)}: {f}") + try: + processFile(pipeline_fs, f, renames, deletions, avg_dims) + except Exception as e: + print(f, e) + + +if __name__ == "__main__": + rename_and_rescale_all_files() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_joint_objects.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_joint_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..16c16ed08450261007a07bcdf780610f8cb3fa46 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_joint_objects.py @@ -0,0 +1,23 @@ +from b1k_pipeline.utils import parse_name +from collections import defaultdict + + +def fix_group_names(): + groups = defaultdict(list) + for obj in rt.selection: + match = parse_name(obj.name) + if not match: + continue + + key = f"{match.group('category')}-{match.group('model_id')}-{match.group('instance_id')}" + groups[key].append(obj) + + for i, (name, group_objs) in enumerate(groups.items()): + cat, model, _ = name.split("-") + new_name = f"{cat}-{model}-{i}" + for x in group_objs: + x.name = x.name.replace(name, new_name) + + +if __name__ == "__main__": + fix_group_names() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_multiple_provided.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_multiple_provided.py new file mode 100644 index 0000000000000000000000000000000000000000..e89c36e4deb96c2247c89a7a79597b6a8c5875b0 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rename_multiple_provided.py @@ -0,0 +1,61 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name, PIPELINE_ROOT + +import json + +import random +import string + +import pymxs + +rt = pymxs.runtime + +objs_inv_path = PIPELINE_ROOT / "artifacts/pipeline/object_inventoty.json" +current_file = rt.maxFilePath.split("cad", 1)[1][1:-1] +current_file = current_file.replace("\\", "/") + +# get error objects and objects in scene +with open(objs_inv_path, "r") as f: + all_inv = json.load(f) + +repeated_objs = [] # list of dictionaries, key is obj name, value is list of scenes where obj is repeated +for obj in all_inv["error_multiple_provided"]: + repeated_objs.append(obj) + +all_objs = {} # dictionary of lists, key is obj base_name e.g. 'trophy-id', value is list of obj instances +for obj in rt.objects: + n = parse_name(obj.name) + if not n: # assume objs have correct names + continue + name = obj.name[n.start("category") : n.end("model_id")] + if name not in all_objs: + all_objs[name] = [] + all_objs[name].append(obj) + + +# rename necessary objs +for obj_base_name in repeated_objs: + # do not rename if obj not in scene or if file doesn't have error with this object + if ( + obj_base_name not in all_objs + or current_file not in all_inv["error_multiple_provided"][obj_base_name] + ): + continue + first_token = obj_base_name.split("-")[0] + obj_instances = all_objs[obj_base_name] + if first_token == "walls" or first_token == "ceilings" or first_token == "floors": + # rename id + old_id = parse_name(obj_instances[0].name).group("model_id") + new_id = "".join(random.choices(string.ascii_lowercase, k=6)) + # two instances - obj and manual cmesh + for obj in obj_instances: + obj.name = obj.name.replace(old_id, new_id) + else: + # only rename instances when not last file in repeated-list + if current_file != all_inv["error_multiple_provided"][obj_base_name][-1]: + for obj in obj_instances: + assert not obj.name.startswith("B-"), obj.name + obj.name = "B-" + obj.name diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/renumber.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/renumber.py new file mode 100644 index 0000000000000000000000000000000000000000..953e8a173fc1da0e109921d11fc555d18671c37c --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/renumber.py @@ -0,0 +1,58 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name + +import pymxs + +rt = pymxs.runtime + +from collections import defaultdict + +objs_by_id = defaultdict(set) +for obj in rt.objects: + m = parse_name(obj.name) + if m: + objs_by_id[m.group("model_id")].add(obj) + +# Check if model 0 is here. If not, add B +for objs in objs_by_id.values(): + if not any(int(parse_name(obj.name).group("instance_id")) == 0 for obj in objs): + for obj in objs: + if not obj.name.startswith("B-"): + obj.name = "B-" + obj.name + +# Now renumber each group of objects. +for m, objs in objs_by_id.items(): + i = 0 + while len(objs) != 0: + # if it has a 0 instance id then keep it at 0 so that its metalinks remain id 0 + obj = None + objs_id_0 = [ + ob for ob in objs if int(parse_name(ob.name).group("instance_id")) == 0 + ] + if objs_id_0: + obj = objs_id_0[0] + objs.remove(obj) + else: + obj = objs.pop() + + # renumber + existing_id = parse_name(obj.name).group("instance_id") + key_from = f"{m}-{existing_id}" + assert key_from in obj.name, f"{key_from} not in {obj.name}" + key_to = f"{m}-{i}" + obj.name = obj.name.replace(key_from, key_to) + + # if there is a duplicate name. e.g. light, metalinks then process it now to keep id same as parent and remove from iterable + duplicates = set() + for ob in objs: + if parse_name(ob.name).group("instance_id") == existing_id: + duplicates.add(ob) + + for duplicate in duplicates: + objs.remove(duplicate) + duplicate.name = duplicate.name.replace(key_from, key_to) + + i += 1 diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/renumber_instance_ids.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/renumber_instance_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..b30e96f2319ce2c59998fe3943d3e9246a6be6c5 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/renumber_instance_ids.py @@ -0,0 +1,40 @@ +import re +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name + +import pymxs + +rt = pymxs.runtime + +from collections import defaultdict + +objs_by_model_and_instance = defaultdict(lambda: defaultdict(set)) +for obj in rt.objects: + m = parse_name(obj.name) + if m: + objs_by_model_and_instance[m.group("model_id")][ + int(m.group("instance_id")) + ].add(obj) + +# Now renumber each group of objects. +for m, objs_by_instance in objs_by_model_and_instance.items(): + # Check if the instance keys are complete + instance_keys = set(objs_by_instance.keys()) + if instance_keys == set(range(len(instance_keys))): + continue + + print("Found discontinuous model", m) + + # Renumber the instances + old_instance_ids = sorted(objs_by_instance.keys()) + new_instance_ids = list(range(len(old_instance_ids))) + for oin, nin in zip(old_instance_ids, new_instance_ids): + print("Renaming", m, oin, "to", nin) + find_regex = re.compile(f"{m}-{oin}(-|$)") + replace_regex = lambda match: f"{m}-{nin}{match.group(1)}" + for obj in objs_by_instance[oin]: + assert find_regex.search(obj.name), f"{m}-{oin} not in {obj.name}" + obj.name = find_regex.sub(replace_regex, obj.name) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/replace_bad_object.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/replace_bad_object.py new file mode 100644 index 0000000000000000000000000000000000000000..09d7539201c2453b1fc687f15b38c0f413325c2f --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/replace_bad_object.py @@ -0,0 +1,633 @@ +from collections import defaultdict +import json +import sys + +import tqdm + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import pymxs + +rt = pymxs.runtime + +from b1k_pipeline.utils import mat2arr, parse_name, PIPELINE_ROOT + +import numpy as np +from scipy.spatial.transform import Rotation as R + +SET_VIA_TRANSFORM = False +_EPS = np.finfo(float).eps * 4.0 + +inventory_path = PIPELINE_ROOT / "artifacts" / "pipeline" / "object_inventory.json" +with open(inventory_path, "r") as f: + providers = {k.split("-")[-1]: v for k, v in json.load(f)["providers"].items()} + + +def quat2arr(q): + return np.array([q.x, q.y, q.z, q.w], dtype=np.float64) + + +def transform2mat(transform): + # Transpose the rotation/scale part to go from right hand to left hand + transform_copy = transform.copy() + # transform_copy[:3, :3] = transform_copy[:3, :3].T + + # Convert a 4x4 numpy transform in our right-hand multiplication system to a 4x3 matrix in 3ds Max's left-hand multiplication system + return rt.Matrix3( + *[ + rt.Point3(*row) + for row in transform_copy[:3, :].T.astype(np.float32).tolist() + ] + ) + + +def mat2transform(mat): + transform = np.hstack([mat2arr(mat, dtype=np.float64), [[0], [0], [0], [1]]]).T + + # Transpose the rotation/scale part to go from left hand to right hand + # transform[:3, :3] = transform[:3, :3].T + + return transform + + +def get_vert_sets_including_children(node, only_canonical_parts_of=None): + if only_canonical_parts_of is not None: + parsed_name = parse_name(node.name) + if not parsed_name: + return [] + + if parsed_name.group("model_id") != only_canonical_parts_of: + return [] + + if parsed_name.group("meta_type") or parsed_name.group("joint_side") == "upper": + return [] + vert_sets = [] + if rt.classOf(node) == rt.Editable_Poly: + vert_sets.append( + np.array( + [ + rt.polyop.getVert(node, i + 1) + for i in range(rt.polyop.GetNumVerts(node)) + ], + dtype=np.float64, + ) + ) + for child in node.children: + vert_sets.extend( + get_vert_sets_including_children( + child, only_canonical_parts_of=only_canonical_parts_of + ) + ) + return vert_sets + + +def bounding_box_from_verts(verts): + return np.min(verts, axis=0), np.max(verts, axis=0) + + +def node_bounding_box_incl_children(node, transform=None, only_canonical=None): + if only_canonical: + parsed_name = parse_name(node.name) + if not parsed_name: + return None + only_canonical = parsed_name.group("model_id") + verts_world = np.concatenate( + get_vert_sets_including_children(node, only_canonical_parts_of=only_canonical), + axis=0, + ) + if transform is None or np.allclose(transform, np.eye(4)): + verts = verts_world + else: + inv_transform = np.linalg.inv(transform) + verts = np.concatenate( + [verts_world, np.ones((verts_world.shape[0], 1))], axis=1 + ) + verts = (inv_transform @ verts.T).T[:, :3] + return bounding_box_from_verts(verts) + + +def get_rotation_from_transform(matrix): + M = np.array(matrix, dtype=np.float64).T + if abs(M[3, 3]) < _EPS: + raise ValueError("M[3, 3] is zero") + M /= M[3, 3] + P = M.copy() + P[:, 3] = 0.0, 0.0, 0.0, 1.0 + if not np.linalg.det(P): + raise ValueError("matrix is singular") + + scale = np.zeros((3,)) + shear = [0.0, 0.0, 0.0] + + if any(abs(M[:3, 3]) > _EPS): + M[:, 3] = 0.0, 0.0, 0.0, 1.0 + + M[3, :3] = 0.0 + + row = M[:3, :3].copy() + scale[0] = np.linalg.norm(row[0]) + row[0] /= scale[0] + shear[0] = np.dot(row[0], row[1]) + row[1] -= row[0] * shear[0] + scale[1] = np.linalg.norm(row[1]) + row[1] /= scale[1] + shear[0] /= scale[1] + shear[1] = np.dot(row[0], row[2]) + row[2] -= row[0] * shear[1] + shear[2] = np.dot(row[1], row[2]) + row[2] -= row[1] * shear[2] + scale[2] = np.linalg.norm(row[2]) + row[2] /= scale[2] + shear[1:] /= scale[2] + + if np.dot(row[0], np.cross(row[1], row[2])) < 0: + np.negative(scale, scale) + np.negative(row, row) + + return row.T, scale + + +def rotation_only_transform(mat): + transform = mat2transform(mat) + rotation, _ = get_rotation_from_transform( + transform + ) # R.from_quat(quat2arr(mat.rotation)).as_matrix() + result = np.eye(4, dtype=np.float64) + result[:3, :3] = rotation + return result + + +def apply_transform(points, transform): + with_ones = np.concatenate([points, np.ones((points.shape[0], 1))], axis=1) + return np.dot(transform, with_ones.T).T[:, :3] + + +def import_bad_model_originals(model_id): + # Get the provider file + provider = providers[model_id] + filename = str(PIPELINE_ROOT / "cad" / provider / "processed.max") + + # Get the right object names from the file + f_objects = rt.getMAXFileObjectNames(filename, quiet=True) + visual_objects = {} + for obj in f_objects: + m = parse_name(obj) + if not m: + continue + if ( + m.group("model_id") != model_id + or m.group("instance_id") != "0" + or m.group("joint_side") == "upper" + ): + continue + + # We have no way of checking if the object is an editable poly so we just apply some heuristics + if m.group("meta_type") and m.group("meta_type") != "collision": + continue + if m.group("light_id"): + continue + + # If we get here this is a lower link of an instance zero + assert not m.group("bad"), "Bad objects should not be in the inventory" + + link_name = m.group("link_name") if m.group("link_name") else "base_link" + joint_type = m.group("joint_type") + if "Mcollision" in obj: + continue + + visual_objects[(link_name, m.group("parent_link_name"), joint_type)] = obj + + objects_to_import = sorted(set(visual_objects.values())) + + success, imported_meshes = rt.mergeMaxFile( + filename, + objects_to_import, + rt.Name("select"), + rt.Name("autoRenameDups"), + rt.Name("useSceneMtlDups"), + rt.Name("neverReparent"), + rt.Name("noRedraw"), + quiet=True, + mergedNodes=pymxs.byref(None), + ) + assert success, f"Failed to import {model_id}." + imported_objs_by_name = {obj.name: obj for obj in imported_meshes} + assert set(objects_to_import) == set( + imported_objs_by_name.keys() + ), "Not all objects were imported. Missing: " + str( + set(objects_to_import) - set(imported_objs_by_name.keys()) + ) + + zero_layer = rt.LayerManager.getLayer(0) + zero_layer.current = True + for mesh in imported_meshes: + zero_layer.addNode(mesh) + + return {k: imported_objs_by_name[v] for k, v in visual_objects.items()} + + +def replace_object_instances(obj, respect_aspect_ratio=False): + # Parse the name and assert it's the base link of a bad object and instance 0 + parsed_name = parse_name(obj.name) + assert parsed_name, f"Object {obj.name} has no parsed name" + assert parsed_name.group("bad"), f"Object {obj.name} is not a bad object" + assert ( + parsed_name.group("instance_id") == "0" + ), f"Object {obj.name} is not instance 0" + assert not ( + parsed_name.group("link_name") and parsed_name.group("link_name") != "base_link" + ), f"Object {obj.name} is not the base link" + + # Get the model ID + loose = parsed_name.group("loose") + if not loose: + loose = "" + category = parsed_name.group("category") + model_id = parsed_name.group("model_id") + tags = parsed_name.group("tag") + if ( + not tags + ): # This is for retaining any part tag on the base link. Other tags dont care. + tags = "" + + # First, find all the instances of this object and validate that their pivots are the same + all_same_model_id = [ + x + for x in rt.objects + if parse_name(x.name) and parse_name(x.name).group("model_id") == model_id + ] + all_base_links = [ + x + for x in all_same_model_id + if parse_name(x.name).group("link_name") == parsed_name.group("link_name") + ] + same_model_id_parsed_names = [parse_name(x.name) for x in all_same_model_id] + assert all( + same_model_id_parsed_names + ), "All same model ID objects should have a parsed name" + + links_by_instance_id = defaultdict(dict) + for inst, inst_parsed_name in zip(all_same_model_id, same_model_id_parsed_names): + link_name = inst_parsed_name.group("link_name") + if not link_name: + link_name = "base_link" + links_by_instance_id[inst_parsed_name.group("instance_id")][link_name] = inst + + # # Check that once grouped by instance ID, they all have the same set of links + # all_links = set(frozenset(x.keys()) for x in links_by_instance_id.values()) + # assert ( + # len(all_links) == 1 + # ), f"All instances of {obj.name} do not share the same set of links: {links_by_instance_id}" + + # Check that they are all marked as BAD + assert all( + x.group("bad") for x in same_model_id_parsed_names + ), "All instances of the same model ID should be marked as bad." + + # Check that they do NOT have any children + assert not any( + len(x.children) > 0 for x in all_same_model_id + ), "Instances of the same model ID should not have children: {all_same_model_id}" + + # Parent all links under their bases for efficient computation of the bounding box + all_parented = set() + for instance, links in links_by_instance_id.items(): + imported_base_link = links.pop("base_link") + for link in links.values(): + link.parent = imported_base_link + all_parented.add(imported_base_link) + assert all_parented == set(all_base_links), "Not all instances were parented." + + # Record the transforms of all of the instances as well as their local and world BBs + dimensionless_map = {rt.Editable_Poly: False, rt.Point: True} + instance_infos = [] + for inst in all_base_links: + dimensionless = dimensionless_map[rt.classOf(inst)] + localbb = ( + node_bounding_box_incl_children( + inst, rotation_only_transform(inst.transform) + ) + if not dimensionless + else None + ) + worldbb = node_bounding_box_incl_children(inst) if not dimensionless else None + instance_infos.append( + { + "parent": inst.parent, + "transform": inst.transform, + "rotation": inst.rotation, + "layer": inst.layer, + "dimensionless": dimensionless, + "localbb": localbb, + "worldbb": worldbb, + } + ) + + # Delete all the objects + for same_model_id in all_same_model_id: + rt.delete(same_model_id) + + # Import the original mesh for just the zero instance + imported = import_bad_model_originals(model_id) + print("Imported originals for", model_id) + + # Parent all the imported meshes under the base link + imported_base_link = imported[("base_link", None, None)] + for (link_name, parent_link, joint_type), link in imported.items(): + if link_name == "base_link": + continue + link.parent = imported_base_link + + # Set the rotation of the imported base link to be the identity rotation + imported_base_link.transform = rt.Matrix3(1) + + # Flatten the copyables into a list + copyables = [("base_link", None, None, imported_base_link)] + [ + (*k, v) for k, v in imported.items() if k[0] != "base_link" + ] + copyable_meshes = [x[-1] for x in copyables] + + comparison_data = {} + + # Now for each of the original bozos make a copy of the whole thing, scale it up, rotate it, and shift it into place + for instance_id, instance_info in enumerate(instance_infos): + # First copy the object. + success, child_copy = rt.maxOps.cloneNodes( + copyable_meshes, + cloneType=rt.name("instance"), + newNodes=pymxs.byref(None), + ) + assert success, f"Could not clone {imported_base_link.name}" + print("Cloned", model_id, instance_id) + + # Move everything to the correct layer + for mesh in child_copy: + instance_info["layer"].addNode(mesh) + + # Find the base link in the child copies. It's the one whose parent is not one of the child copies + (base_copy,) = [x for x in child_copy if x.parent not in child_copy] + assert ( + base_copy == child_copy[0] + ), "The base link should be the first element in the list of child" + + if instance_info["dimensionless"]: + # Set the object transform here, no scaling. + base_copy.transform = instance_info["transform"] + + else: + # Get the points + base_copy_points = np.concatenate( + get_vert_sets_including_children(base_copy), axis=0 + ) + + # Scale the imported mesh to match the instance + # The target bounding box is the instance's local bounding box + instance_localbb_size = ( + instance_info["localbb"][1] - instance_info["localbb"][0] + ) + + # The current world bounding box is equal to the local bounding box, since we start + # with an identity transform (e.g. the points are the same in world + # and local frame) + base_copy_localbb = bounding_box_from_verts(base_copy_points) + base_copy_localbb_size = base_copy_localbb[1] - base_copy_localbb[0] + + # The target scale is the ratio of the two sizes + if respect_aspect_ratio: + relative_scale_from_now = np.min( + instance_localbb_size / base_copy_localbb_size + ) * np.ones(3) + else: + relative_scale_from_now = instance_localbb_size / base_copy_localbb_size + + # This scale needs to be applied BEFORE the rotation since it's in local frame + scale_transform = np.diag(relative_scale_from_now.tolist() + [1]) + + # Combine the scale with the rotation + rotation_transform = rotation_only_transform(instance_info["transform"]) + combined_transform = rotation_transform @ scale_transform + + # Assert the validity of the rotation and scale + print("Rotation transform", rotation_transform) + print("Scale transform", scale_transform) + print( + "Combined transform components", + get_rotation_from_transform(combined_transform), + ) + target_orn = R.from_quat(quat2arr(instance_info["transform"].rotation)) + current_orn = R.from_matrix( + get_rotation_from_transform(combined_transform)[0] + ) + delta_orn = target_orn * current_orn + delta_mag = delta_orn.magnitude() + print("Delta orientation", delta_orn.as_rotvec(), "magnitude", delta_mag) + + # Position it to match bottom face center (this allows for the object to not be floating + # if respect_aspect_ratio is True) + base_copy_world_bb = bounding_box_from_verts( + apply_transform(base_copy_points, combined_transform) + ) + base_copy_world_bb_bottom_center = ( + base_copy_world_bb[0] + base_copy_world_bb[1] + ) / 2 + base_copy_world_bb_bottom_center[2] = base_copy_world_bb[0][2] + instance_world_bb_bottom_center = ( + instance_info["worldbb"][0] + instance_info["worldbb"][1] + ) / 2 + instance_world_bb_bottom_center[2] = instance_info["worldbb"][0][2] + move_center_by = ( + instance_world_bb_bottom_center - base_copy_world_bb_bottom_center + ) + combined_transform[:3, 3] = move_center_by + + # Convert and apply the transform to the 3ds Max object + if SET_VIA_TRANSFORM: + base_copy.transform = transform2mat(combined_transform) + else: + quat = R.from_matrix(rotation_transform[:3, :3]).as_quat() + base_copy.scale = rt.Point3(*relative_scale_from_now.tolist()) + base_copy.rotation = rt.Quat(*quat.tolist()) + base_copy.position = rt.Point3(*move_center_by.tolist()) + + max_orn = R.from_quat(quat2arr(base_copy.rotation)) + numpy_rot, numpy_scale = get_rotation_from_transform(combined_transform) + numpy_orn = R.from_matrix(numpy_rot) + delta_orn = max_orn.inv() * numpy_orn + delta_mag = delta_orn.magnitude() + print("Max orientation differs from local orientation by", delta_mag) + print( + "Max scale", + base_copy.transform.scale, + "vs Numpy scale", + numpy_scale, + "vs Relative scale", + relative_scale_from_now, + ) + + # Assert the new world bb is the same as the original world bb and the numpy bb + # Compute the transformed bb via numpy + computed_world_bb = bounding_box_from_verts( + apply_transform(base_copy_points, combined_transform) + ) + computed_size = computed_world_bb[1] - computed_world_bb[0] + computed_center = (computed_world_bb[0] + computed_world_bb[1]) / 2 + computed_min, computed_max = computed_world_bb + + # Decompose the original bb + orig_min, orig_max = instance_info["worldbb"] + orig_center = (orig_min + orig_max) / 2 + orig_size = orig_max - orig_min + + # Decompose the new 3ds Max bb + base_copy_world_bb = node_bounding_box_incl_children(base_copy) + new_min, new_max = base_copy_world_bb + new_center = (new_min + new_max) / 2 + new_size = new_max - new_min + + print("Bounding box info") + print( + " Original min", + orig_min, + "vs New min", + new_min, + "vs Computed min", + computed_world_bb[0], + ) + print( + " Original max", + orig_max, + "vs New max", + new_max, + "vs Computed max", + computed_world_bb[1], + ) + print( + " Original size", + orig_size, + "vs New size", + new_size, + "vs Computed size", + computed_size, + ) + print( + " Original center", + orig_center, + "vs New center", + new_center, + "vs Computed center", + computed_center, + ) + + # Note the much higher tolerance due to rotation errors :( + if not respect_aspect_ratio: + assert np.allclose( + orig_center, computed_center, atol=100 + ), "Computed center is not the same as the original center" + assert np.allclose( + orig_size, computed_size, atol=100 + ), "Computed size is not the same as the original size" + + assert np.allclose( + orig_center, new_center, atol=100 + ), "New center is not the same as the original center" + assert np.allclose( + orig_size, + new_size, + atol=100, + ), "New size is not the same as the original size" + + # Record the comparison data + comparison_data[instance_id] = { + "original_transform": mat2transform( + instance_info["transform"] + ).tolist(), + "calculated_transform": combined_transform.tolist(), + "current_transform": mat2transform(base_copy.transform).tolist(), + "original_world_bb": [x.tolist() for x in instance_info["worldbb"]], + "computed_world_bb": [x.tolist() for x in computed_world_bb], + "current_world_bb": [x.tolist() for x in base_copy_world_bb], + "original_localbb": [x.tolist() for x in instance_info["localbb"]], + "current_localbb": [x.tolist() for x in base_copy_localbb], + "respect_aspect_ratio": respect_aspect_ratio, + } + + # Name each of the children correctly, and parent them to the original owner's parents + for (link_name, parent_link, joint_type, _), link in zip(copyables, child_copy): + link.parent = instance_info["parent"] + if link_name == "base_link": + link.name = ( + f"B-{loose}{category}-{model_id}-{instance_id}-{link_name}{tags}" + ) + else: + link.name = f"B-{loose}{category}-{model_id}-{instance_id}-{link_name}-{parent_link}-{joint_type}-lower" + print("Replaced", model_id, instance_id) + + # Finally, after all is done, remove all of the copyables + rt.delete(copyable_meshes) + + return comparison_data + + +def replace_all_bad_legacy_objects_in_open_file(): + bad_objects_to_remove = {} + for obj in rt.objects: + # Check that it's an editable poly + if rt.classOf(obj) != rt.Editable_Poly: + continue + + # Check that the parsed name contains the B- tag + parsed_name = parse_name(obj.name) + if not parsed_name or not parsed_name.group("bad"): + continue + + # Check that the link is the base link + if ( + parsed_name.group("link_name") + and parsed_name.group("link_name") != "base_link" + ): + continue + + # Check that the instance ID is 0 + if parsed_name.group("instance_id") != "0": + continue + + # Check that its not a meta link + if parsed_name.group("meta_type"): + continue + + # Check that the provider is legacy_ + model_id = parsed_name.group("model_id") + provider = providers[model_id] + + # Check that we havent picked an object for this model ID yet. + assert ( + model_id not in bad_objects_to_remove + ), f"Found multiple base objects for {model_id}. First: {bad_objects_to_remove[model_id].name}, Second: {obj.name}" + + # Add to the list of bad objects to remove + bad_objects_to_remove[model_id] = obj + + print( + "Found", + len(bad_objects_to_remove), + "bad objects to remove:", + ", ".join(bad_objects_to_remove.keys()), + ) + + # Go through all the bad objects to remove + comparison_data = {} + for model_id, example_obj in tqdm.tqdm(bad_objects_to_remove.items()): + comparison_data[model_id] = replace_object_instances(example_obj) + + print("\nDon't forget to reset scale!") + + return comparison_data + + +def main(): + replace_object_instances(rt.selection[0], respect_aspect_ratio=False) + # replace_all_bad_legacy_objects_in_open_file() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/require_rebake.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/require_rebake.py new file mode 100644 index 0000000000000000000000000000000000000000..dc1c239c9c7e766b175d2673b64451ff6b71a779 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/require_rebake.py @@ -0,0 +1,20 @@ +from pymxs import runtime as rt + + +def require_rebake(obj): + if not obj.material or rt.classOf(obj.material) != rt.Shell_Material: + return + + # Switch the material to the shell's original material + obj.material = obj.material.originalMaterial + + print("Successfully removed baked material from", obj.name) + + +def main(): + for obj in rt.selection: + require_rebake(obj) + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/resolve_complaints.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/resolve_complaints.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba2eca597f32f199a537a08525e423c5b4763be --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/resolve_complaints.py @@ -0,0 +1,71 @@ +import re +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +import b1k_pipeline.utils + +import json +import pathlib +import pymxs + +rt = pymxs.runtime + + +def should_get_complaint(complaint): + if complaint["processed"]: + return False + + if complaint["type"] in ("material", "clothappearance"): + return False + + return True + + +def main(): + current_max_dir = pathlib.Path(rt.maxFilePath).resolve() + complaint_path = current_max_dir / "complaints.json" + + if not complaint_path.exists(): + print("No complaints found!") + return + + with open(complaint_path, "r") as f: + x = json.load(f) + + selected_objs = list( + rt.selection + ) # if len(rt.selection) > 0 else list(rt.objects) + selected_names = [obj.name for obj in selected_objs] + selected_obj_matches = [ + b1k_pipeline.utils.parse_name(name) for name in selected_names + ] + selected_keys = { + match.group("model_id") for match in selected_obj_matches if match is not None + } + + # Stop if all processed + if not any( + not c["processed"] for c in x if c["object"].split("-")[-1] in selected_keys + ): + print("No unresolved complaints found!") + return + + # Mark as processed + for complaint in x: + if complaint["object"].split("-")[ + -1 + ] not in selected_keys or not should_get_complaint(complaint): + continue + + complaint["processed"] = True + + # Save + with open(complaint_path, "w") as f: + json.dump(x, f, indent=4) + + print("Complaints resolved!") + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rpc_server.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rpc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6f3472523b8486f75413d6adb3b6bc51a3a775 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/rpc_server.py @@ -0,0 +1,34 @@ +from xmlrpc.server import SimpleXMLRPCServer + +import pymxs + +rt = pymxs.runtime + + +def run_script(scene_file, script_path, args): + # Load the file. + rt.resetMaxFile(rt.name("noPrompt")) + assert rt.loadMaxFile( + scene_file, useFileUnits=False, quiet=True + ), f"Could not load {scene_file}" + + # Set the arguments. + rt.maxops.mxsCmdLineArgs = rt.Dictionary() + for arg_key, arg_value in args: + rt.maxops.mxsCmdLineArgs[rt.name(arg_key)] = arg_value + + # Execute the script + rt.python.ExecuteFile(script_path) + + return True + + +def main(): + server = SimpleXMLRPCServer(("localhost", 8000)) + print("Listening on port 8000...") + server.register_function(run_script, "run_script") + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/save_unique_class_info.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/save_unique_class_info.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3248d39f16629bce202a3c725db171cf315e1a --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/save_unique_class_info.py @@ -0,0 +1,105 @@ +import sys + +sys.path.append(r"D:\BEHAVIOR-1K\asset_pipeline") + +from b1k_pipeline.utils import parse_name + +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R +import json + +rt = pymxs.runtime +local_coordsys = pymxs.runtime.Name("local") + + +def get_object_key(obj): + """ + Get a unique key for an object. + """ + return parse_name(obj.name).group("model_id") + + +def get_object_category(obj): + """ + Get a unique key for an object. + """ + return parse_name(obj.name).group("category") + + +def save_unique_class_infos(): + class_infos = {} + for obj in rt.objects: + # Skip everything that's not an editable poly + if rt.classOf(obj) != rt.editable_poly: + continue + + # Skip if object is not the base link + link_name = parse_name(obj.name).group("link_name") + if link_name is not None and link_name != "basename": + continue + + model_id, category, material_name, eigvals = get_unique_class_info(obj) + class_infos[model_id] = { + "category": category, + "material_name": material_name, + "eigvals": eigvals.tolist(), + } + + json.dump(class_infos, open("unique_class_info.json", "w")) + + +def get_unique_class_info(src_obj): + """ + Uniquely identify a class by its material name and the eigenvalues of its covariance matrix. + """ + X = np.array( + rt.polyop.getVerts( + src_obj, rt.execute("#{1..%d}" % rt.polyop.getNumVerts(src_obj)) + ) + ) + n, m = X.shape + u = np.mean(X, axis=0) + # rt.messageBox("u: {}".format(u)) + B = X - u + # rt.messageBox("B: {}".format(B)) + C = 1 / (n - 1) * B.T @ B + eigvals, V = np.linalg.eig(C) + sorted_idxs = np.argsort(eigvals)[::-1] + eigvals = eigvals[sorted_idxs] + V = V[:, sorted_idxs] + # rt.messageBox("eigvals: {}".format(eigvals)) + # rt.messageBox("V: {}".format(V)) + + model_id = get_object_key(src_obj) + category = get_object_category(src_obj) + material_name = src_obj.material.name if src_obj.material else None + + return model_id, category, material_name, eigvals + # json.dump( + # { + # "model_id": model_id, + # "material_name": material_name, + # "eigvals": eigvals.tolist(), + # }, + # open("unique_class_info.json", "a"), + # ) + + +def save_unique_class_info_button(): + try: + save_unique_class_infos() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + # Print message + rt.messageBox("Unique class info saved") + + +if __name__ == "__main__": + save_unique_class_info_button() diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/select_bad_element.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/select_bad_element.py new file mode 100644 index 0000000000000000000000000000000000000000..873931a8683053add0fbda1d749a5fb5abdd58db --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/select_bad_element.py @@ -0,0 +1,47 @@ +def select_bad_element(obj): + # Assert that collision meshes do not share instances in the scene + assert not [ + x for x in rt.objects if x.baseObject == obj.baseObject and x != obj + ], f"{obj.name} should not have instances." + + # Get vertices and faces into numpy arrays for conversion + verts = np.array( + [rt.polyop.getVert(obj, i + 1) for i in range(rt.polyop.GetNumVerts(obj))] + ) + faces = ( + np.array( + rt.polyop.getFacesVerts( + obj, rt.execute("#{1..%d}" % rt.polyop.GetNumFaces(obj)) + ) + ) + - 1 + ) + assert faces.shape[1] == 3, f"{obj.name} has non-triangular faces" + + # Split the faces into elements + elems = { + tuple(rt.polyop.GetElementsUsingFace(obj, i + 1)) + for i in range(rt.polyop.GetNumFaces(obj)) + } + assert len(elems) <= 32, f"{obj.name} should not have more than 32 elements." + elems = np.array(list(elems)) + assert not np.any( + np.sum(elems, axis=0) > 1 + ), f"{obj.name} has same face appear in multiple elements" + + # Iterate through the elements + for i, elem in enumerate(elems): + # Load the mesh into trimesh and assert convexity + relevant_faces = faces[elem] + m = trimesh.Trimesh(vertices=verts, faces=relevant_faces, process=False) + m.remove_unreferenced_vertices() + if not m.is_volume: + rt.polyop.SetFaceSelection(obj, (elem + 1).tolist()) + print("Selected element", i) + return + + print("No bad elements found!") + + +if __name__ == "__main__": + select_bad_element(rt.selection[0]) diff --git a/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/select_mismatched_pivot.py b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/select_mismatched_pivot.py new file mode 100644 index 0000000000000000000000000000000000000000..a72a73cf2e1cd5bdb2949775c6550f401cc25780 --- /dev/null +++ b/source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/b1k_pipeline/max/select_mismatched_pivot.py @@ -0,0 +1,76 @@ +import re +from collections import defaultdict + +import numpy as np +import pymxs +from scipy.spatial.transform import Rotation as R + +rt = pymxs.runtime + + +def quat2arr(q): + return np.array([q.x, q.y, q.z, q.w]) + + +def find_base_candidate(bases): + for baseobject, objs in bases.items(): + base = objs[0] + desired_offset_pos = np.array(base.objectOffsetPos) / np.array( + base.objectOffsetScale + ) + desired_offset_rot_inv = R.from_quat(quat2arr(base.objectOffsetRot)).inv() + # desired_shear = compute_shear(base.object) + for obj in objs[1:]: + this_offset_pos = np.array(obj.objectOffsetPos) / np.array( + obj.objectOffsetScale + ) + pos_diff = this_offset_pos - desired_offset_pos + if not np.allclose(pos_diff, 0, atol=1e-2): + return baseobject + + this_offset_rot = R.from_quat(quat2arr(obj.objectOffsetRot)) + rot_diff = (this_offset_rot * desired_offset_rot_inv).magnitude() + if not np.allclose(rot_diff, 0, atol=1e-2): + return baseobject + + # this_shear = compute_shear(obj) + # self.expect( + # np.allclose(this_shear, desired_shear, atol=1e-3), + # f"{obj_name} has different shear. Match scaling axes on each instance." + # ) + + return None + + +def select_mismatched_pivot(): + objects = rt.objects + + # First, find all the qualifying objects. + bases = defaultdict(list) + for obj in objects: + bases[obj.baseObject].append(obj) + + # Check which bases have mismatched pivots. + base_candidate = find_base_candidate(bases) + assert base_candidate is not None, "No objects have mismatched pivots!" + + # Select, unhide and isolate. + objs = bases[base_candidate] + rt.select(objs) + for obj in objs: + obj.hidden = False + rt.IsolateSelection.EnterIsolateSelectionMode() + print("Selected ", ",".join([x.name for x in objs])) + + +def select_mismatched_pivot_button(): + try: + select_mismatched_pivot() + except AssertionError as e: + # Print message + rt.messageBox(str(e)) + return + + +if __name__ == "__main__": + select_mismatched_pivot_button()