file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
StanfordVL/OmniGibson/omnigibson/object_states/burnt.py
from omnigibson.macros import create_module_macros from omnigibson.object_states.max_temperature import MaxTemperature from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin # Create settings for this module m = create_module_macros(module_path=__file__) m.DEFAULT_BURN_TEMPERATURE = 200 class Burnt(AbsoluteObjectState, BooleanStateMixin): def __init__(self, obj, burn_temperature=m.DEFAULT_BURN_TEMPERATURE): super(Burnt, self).__init__(obj) self.burn_temperature = burn_temperature @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(MaxTemperature) return deps def _set_value(self, new_value): current_max_temp = self.obj.states[MaxTemperature].get_value() if new_value: # Set at exactly the burnt temperature (or higher if we have it in history) desired_max_temp = max(current_max_temp, self.burn_temperature) else: # Set at exactly one below burnt temperature (or lower if in history). desired_max_temp = min(current_max_temp, self.burn_temperature - 1.0) return self.obj.states[MaxTemperature].set_value(desired_max_temp) def _get_value(self): return self.obj.states[MaxTemperature].get_value() >= self.burn_temperature @staticmethod def get_texture_change_params(): # Decrease all channels by 0.3 (to make it black) albedo_add = -0.3 # No final scaling diffuse_tint = (1.0, 1.0, 1.0) return albedo_add, diffuse_tint # Nothing needs to be done to save/load Burnt since it will happen due to # MaxTemperature caching.
1,709
Python
35.382978
93
0.67993
StanfordVL/OmniGibson/omnigibson/object_states/cooked.py
from omnigibson.macros import create_module_macros from omnigibson.object_states.max_temperature import MaxTemperature from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin # Create settings for this module m = create_module_macros(module_path=__file__) m.DEFAULT_COOK_TEMPERATURE = 70 class Cooked(AbsoluteObjectState, BooleanStateMixin): def __init__(self, obj, cook_temperature=m.DEFAULT_COOK_TEMPERATURE): super(Cooked, self).__init__(obj) self.cook_temperature = cook_temperature @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(MaxTemperature) return deps def _set_value(self, new_value): current_max_temp = self.obj.states[MaxTemperature].get_value() if new_value: # Set at exactly the cook temperature (or higher if we have it in history) desired_max_temp = max(current_max_temp, self.cook_temperature) else: # Set at exactly one below cook temperature (or lower if in history). desired_max_temp = min(current_max_temp, self.cook_temperature - 1.0) return self.obj.states[MaxTemperature].set_value(desired_max_temp) def _get_value(self): return self.obj.states[MaxTemperature].get_value() >= self.cook_temperature @staticmethod def get_texture_change_params(): # Increase all channels by 0.1 albedo_add = 0.1 # Then scale up "brown" color and scale down others diffuse_tint = (1.5, 0.75, 0.25) return albedo_add, diffuse_tint # Nothing needs to be done to save/load Burnt since it will happen due to # MaxTemperature caching.
1,723
Python
35.68085
93
0.68195
StanfordVL/OmniGibson/omnigibson/object_states/on_fire.py
from omnigibson.macros import create_module_macros from omnigibson.object_states.temperature import Temperature from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink # Create settings for this module m = create_module_macros(module_path=__file__) # TODO: Delete default values for this and make them required. m.DEFAULT_IGNITION_TEMPERATURE = 250 m.DEFAULT_FIRE_TEMPERATURE = 1000 m.DEFAULT_HEATING_RATE = 0.04 m.DEFAULT_DISTANCE_THRESHOLD = 0.2 class OnFire(HeatSourceOrSink): """ This state indicates the heat source is currently on fire. Once the temperature is above ignition_temperature, OnFire will become True and stay True. Its temperature will further raise to fire_temperature, and start heating other objects around it. It may include a heatsource_link annotation (e.g. candle wick), in which case the fire visualization will be placed under that meta link. Otherwise (e.g. charcoal), the fire visualization will be placed under the root link. """ def __init__( self, obj, ignition_temperature=m.DEFAULT_IGNITION_TEMPERATURE, fire_temperature=m.DEFAULT_FIRE_TEMPERATURE, heating_rate=m.DEFAULT_HEATING_RATE, distance_threshold=m.DEFAULT_DISTANCE_THRESHOLD, ): """ Args: obj (StatefulObject): The object with the heat source ability. ignition_temperature (float): The temperature threshold above which on fire will become true. fire_temperature (float): The temperature of the fire (heat source) once on fire is true. heating_rate (float): Fraction in [0, 1] of the temperature difference with the heat source temperature should be received every step, per second. distance_threshold (float): The distance threshold which an object needs to be closer than in order to receive heat from this heat source. """ assert fire_temperature > ignition_temperature, "fire temperature should be higher than ignition temperature." super().__init__( obj, temperature=fire_temperature, heating_rate=heating_rate, distance_threshold=distance_threshold, requires_toggled_on=False, requires_closed=False, requires_inside=False, ) self.ignition_temperature = ignition_temperature @classmethod def requires_metalink(cls, **kwargs): # Does not require metalink to be specified return False @property def _default_link(self): # Fallback to root link return self.obj.root_link @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(Temperature) return deps def _update(self): # Call super first super()._update() # If it's on fire, maintain the fire temperature if self.get_value(): self.obj.states[Temperature].set_value(self.temperature) def _get_value(self): return self.obj.states[Temperature].get_value() >= self.ignition_temperature def _set_value(self, new_value): if new_value: return self.obj.states[Temperature].set_value(self.temperature) else: # We'll set the temperature just one degree below ignition. return self.obj.states[Temperature].set_value(self.ignition_temperature - 1) # Nothing needs to be done to save/load OnFire
3,508
Python
37.141304
119
0.670468
StanfordVL/OmniGibson/omnigibson/object_states/heated.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin from omnigibson.object_states.temperature import Temperature # Create settings for this module m = create_module_macros(module_path=__file__) m.DEFAULT_HEAT_TEMPERATURE = 40 # When an object is set as heated, we will sample it between # the heat temperature and these offsets. m.HEATED_SAMPLING_RANGE_MIN = 10.0 m.HEATED_SAMPLING_RANGE_MAX = 20.0 class Heated(AbsoluteObjectState, BooleanStateMixin): def __init__(self, obj, heat_temperature=m.DEFAULT_HEAT_TEMPERATURE): super(Heated, self).__init__(obj) self.heat_temperature = heat_temperature @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(Temperature) return deps def _set_value(self, new_value): if new_value: temperature = np.random.uniform( self.heat_temperature + m.HEATED_SAMPLING_RANGE_MIN, self.heat_temperature + m.HEATED_SAMPLING_RANGE_MAX, ) return self.obj.states[Temperature].set_value(temperature) else: # We'll set the temperature just one degree below heating. return self.obj.states[Temperature].set_value(self.heat_temperature - 1.0) def _get_value(self): return self.obj.states[Temperature].get_value() >= self.heat_temperature # Nothing needs to be done to save/load Heated since it will happen due to temperature caching.
1,587
Python
34.288888
99
0.693132
StanfordVL/OmniGibson/omnigibson/object_states/particle_source_or_sink.py
import numpy as np import omnigibson as og from omnigibson.macros import create_module_macros from omnigibson.object_states.particle_modifier import ParticleApplier, ParticleRemover from omnigibson.systems.system_base import is_physical_particle_system from omnigibson.utils.constants import ParticleModifyMethod from omnigibson.utils.python_utils import classproperty # Create settings for this module m = create_module_macros(module_path=__file__) # Metalink naming prefixes m.SOURCE_LINK_PREFIX = "particlesource" m.SINK_LINK_PREFIX = "particlesink" # Default radius and height m.DEFAULT_SOURCE_RADIUS = 0.0125 m.DEFAULT_SOURCE_HEIGHT = 0.05 m.DEFAULT_SINK_RADIUS = 0.05 m.DEFAULT_SINK_HEIGHT = 0.05 # Maximum number of particles that can be sourced / sunk per step m.MAX_SOURCE_PARTICLES_PER_STEP = 1000 m.MAX_SINK_PARTICLES_PER_STEP = 1000 # How many steps between sinking particles m.N_STEPS_PER_SINK = 5 # Upper limit to number of particles that can be sourced / sunk globally by a single object m.SOURCE_PARTICLES_LIMIT = 1e6 m.SINK_PARTICLES_LIMIT = 1e6 class ParticleSource(ParticleApplier): """ ParticleApplier where physical particles are spawned continuously in a cylindrical fashion from the metalink pose. Args: obj (StatefulObject): Object to which this state will be applied conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of (ParticleModifyCondition, value) necessary in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the form above -- if all of its conditions evaluate to True and particles are detected within this particle modifier area, then we potentially modify those particles source_radius (None or float): Radius of the cylinder representing particles' spawning volume, if specified. If both @source_radius and @source_height are None, values will be inferred directly from the underlying object asset, otherwise, it will be set to a default value source_height (None or float): Height of the cylinder representing particles' spawning volume, if specified. If both @source_radius and @source_height are None, values will be inferred directly from the underlying object asset, otherwise, it will be set to a default value initial_speed (float): The initial speed for generated particles. Note that the direction of the velocity is inferred from the particle sampling process """ def __init__( self, obj, conditions, source_radius=None, source_height=None, initial_speed=0.0, ): # Initialize variables that will be filled in at runtime self._n_steps_per_modification = None # Define projection mesh params based on input kwargs if source_radius is not None or source_height is not None: source_radius = m.DEFAULT_SOURCE_RADIUS if source_radius is None else source_radius source_height = m.DEFAULT_SOURCE_HEIGHT if source_height is None else source_height projection_mesh_params = { "type": "Cylinder", "extents": [source_radius * 2, source_radius * 2, source_height], } else: projection_mesh_params = None # Convert inputs into arguments to pass to particle applier class super().__init__( obj=obj, conditions=conditions, method=ParticleModifyMethod.PROJECTION, projection_mesh_params=projection_mesh_params, sample_with_raycast=False, initial_speed=initial_speed, ) def _initialize(self): # Run super first super()._initialize() # Calculate how many steps we need in between particle cluster spawnings # This is equivalent to the time it takes for a generated particle to travel @source_height distance # Note that object state steps are discretized by og.sim.render_step # Note: t derived from quadratic formula: height = 0.5 g t^2 + v0 t # Note: height must be considered in the world frame, so we convert the distance from local into world frame # Extents are in local frame, so we need to convert to world frame using link scale distance = self.link.scale[2] * self._projection_mesh_params["extents"][2] t = (-self._initial_speed + np.sqrt(self._initial_speed ** 2 + 2 * og.sim.gravity * distance)) / og.sim.gravity self._n_steps_per_modification = np.ceil(1 + t / og.sim.get_rendering_dt()).astype(int) def _get_max_particles_limit_per_step(self, system): # Check the system assert is_physical_particle_system(system_name=system.name), \ "ParticleSource only supports PhysicalParticleSystem" return m.MAX_SOURCE_PARTICLES_PER_STEP @classmethod def requires_metalink(cls, **kwargs): # Always requires metalink since projection is used return True @property def visualize(self): # Don't visualize this source return False @classproperty def metalink_prefix(cls): return m.SOURCE_LINK_PREFIX @property def n_steps_per_modification(self): return self._n_steps_per_modification @property def physical_particle_modification_limit(self): return m.SOURCE_PARTICLES_LIMIT class ParticleSink(ParticleRemover): """ ParticleRemover where physical particles are removed continuously within a cylindrical volume located at the metalink pose. Args: obj (StatefulObject): Object to which this state will be applied conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of (ParticleModifyCondition, value) necessary in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the form above -- if all of its conditions evaluate to True and particles are detected within this particle modifier area, then we potentially modify those particles sink_radius (None or float): Radius of the cylinder representing particles' sinking volume, if specified. If both @sink_radius and @sink_height are None, values will be inferred directly from the underlying object asset, otherwise, it will be set to a default value sink_height (None or float): Height of the cylinder representing particles' sinking volume, if specified. If both @sink_radius and @sink_height are None, values will be inferred directly from the underlying object asset, otherwise, it will be set to a default value default_fluid_conditions (None or list): Condition(s) needed to remove any fluid particles not explicitly specified in @conditions. If None, then it is assumed that no other physical particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) 2-tuples default_non_fluid_conditions (None or list): Condition(s) needed to remove any physical (excluding fluid) particles not explicitly specified in @conditions. If None, then it is assumed that no other physical particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) 2-tuples default_visual_conditions (None or list): Condition(s) needed to remove any visual particles not explicitly specified in @conditions. If None, then it is assumed that no other visual particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) 2-tuples """ def __init__( self, obj, conditions, sink_radius=None, sink_height=None, default_fluid_conditions=None, default_non_fluid_conditions=None, default_visual_conditions=None, ): # Initialize variables that will be filled in at runtime self._n_steps_per_modification = None # Define projection mesh params based on input kwargs if sink_radius is not None or sink_height is not None: sink_radius = m.DEFAULT_SINK_RADIUS if sink_radius is None else sink_radius sink_height = m.DEFAULT_SINK_HEIGHT if sink_height is None else sink_height projection_mesh_params = { "type": "Cylinder", "extents": [sink_radius * 2, sink_radius * 2, sink_height], } else: projection_mesh_params = None # Convert inputs into arguments to pass to particle remover class super().__init__( obj=obj, conditions=conditions, method=ParticleModifyMethod.PROJECTION, projection_mesh_params=projection_mesh_params, default_fluid_conditions=default_fluid_conditions, default_non_fluid_conditions=default_non_fluid_conditions, default_visual_conditions=default_visual_conditions, ) def _get_max_particles_limit_per_step(self, system): # Check the system assert is_physical_particle_system(system_name=system.name), \ "ParticleSink only supports PhysicalParticleSystem" return m.MAX_PHYSICAL_PARTICLES_SOURCED_PER_STEP @property def requires_overlap(self): # Not required, always sink particles return False @classmethod def requires_metalink(cls, **kwargs): # Always requires metalink since projection is used return True @classproperty def metalink_prefix(cls): return m.SINK_LINK_PREFIX @property def n_steps_per_modification(self): return m.N_STEPS_PER_SINK @property def physical_particle_modification_limit(self): return m.SINK_PARTICLES_LIMIT
11,733
Python
46.314516
136
0.67911
StanfordVL/OmniGibson/omnigibson/object_states/under.py
import omnigibson as og from omnigibson.object_states.adjacency import VerticalAdjacency from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.utils.object_state_utils import sample_kinematics from omnigibson.utils.object_state_utils import m as os_m from omnigibson.utils.constants import PrimType class Under(RelativeObjectState, KinematicsMixin, BooleanStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(VerticalAdjacency) return deps def _set_value(self, other, new_value, reset_before_sampling=False): if not new_value: raise NotImplementedError("Under does not support set_value(False)") if other.prim_type == PrimType.CLOTH: raise ValueError("Cannot set an object under a cloth object.") state = og.sim.dump_state(serialized=False) # Possibly reset this object if requested if reset_before_sampling: self.obj.reset() for _ in range(os_m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS): if sample_kinematics("under", self.obj, other) and self.get_value(other): return True else: og.sim.load_state(state, serialized=False) return False def _get_value(self, other): if other.prim_type == PrimType.CLOTH: raise ValueError("Cannot detect if an object is under a cloth object.") adjacency = self.obj.states[VerticalAdjacency].get_value() other_adjacency = other.states[VerticalAdjacency].get_value() return other not in adjacency.negative_neighbors and other in adjacency.positive_neighbors and self.obj not in other_adjacency.positive_neighbors
1,850
Python
40.133332
153
0.704324
StanfordVL/OmniGibson/omnigibson/object_states/contact_particles.py
import omnigibson as og from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import RelativeObjectState from omnigibson.object_states.aabb import AABB from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.systems.system_base import PhysicalParticleSystem, is_physical_particle_system # Create settings for this module m = create_module_macros(module_path=__file__) # Distance tolerance for detecting contact m.CONTACT_AABB_TOLERANCE = 2.5e-2 m.CONTACT_TOLERANCE = 5e-3 class ContactParticles(RelativeObjectState, KinematicsMixin): """ Object state that handles contact checking between rigid bodies and individual particles. """ def _get_value(self, system, link=None): """ Args: system (PhysicalParticleSystem): System whose contact particle info should be aggregated link (None or RigidPrim): If specified, the specific link to check for particles' contact Returns: set of int: Set of particle IDs in contact """ # Make sure system is valid assert is_physical_particle_system(system_name=system.name), \ "Can only get ContactParticles for a PhysicalParticleSystem!" # Variables to update mid-iteration contacts = set() idx = 0 # Define callback function to use for omni's overlap_sphere() call def report_hit(hit): nonlocal link, idx link_name = None if link is None else link.prim_path.split("/")[-1] base, body = "/".join(hit.rigid_body.split("/")[:-1]), hit.rigid_body.split("/")[-1] continue_traversal = True # If no links are specified, then we assume checking contact with any link owned by this object # Otherwise, we check for exact match of link name if (link is None and base == self.obj.prim_path) or (link is not None and link_name == body): # Add to contacts and terminate early contacts.add(idx) continue_traversal = False return continue_traversal # Grab the relaxed AABB of this object or its link for coarse filtering of particles to ignore checking lower, upper = self.obj.states[AABB].get_value() if link is None else link.visual_aabb # Add margin for filtering inbound lower = lower - (system.particle_radius + m.CONTACT_AABB_TOLERANCE) upper = upper + (system.particle_radius + m.CONTACT_AABB_TOLERANCE) # Iterate over all particles and aggregate contacts positions = system.get_particles_position_orientation()[0] # Only check positions that are within the relaxed AABB of this object inbound_idxs = ((lower < positions) & (positions < upper)).all(axis=-1).nonzero()[0] dist = system.particle_contact_radius + m.CONTACT_TOLERANCE for idx in inbound_idxs: og.sim.psqi.overlap_sphere(dist, positions[idx], report_hit, False) # Return contacts return contacts def _set_value(self, system, new_value): raise NotImplementedError("ContactParticles state currently does not support setting.") def _cache_is_valid(self, get_value_args): # Cache is never valid since particles always change poses return False
3,360
Python
43.813333
111
0.673214
StanfordVL/OmniGibson/omnigibson/object_states/slicer_active.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import BooleanStateMixin from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.object_states.tensorized_value_state import TensorizedValueState import omnigibson as og from omnigibson.utils.python_utils import classproperty from omnigibson.utils.usd_utils import RigidContactAPI # Create settings for this module m = create_module_macros(module_path=__file__) m.REACTIVATION_DELAY = 0.5 # number of seconds to wait before reactivating the slicer class SlicerActive(TensorizedValueState, BooleanStateMixin): # int: Keep track of how many steps each object is waiting for STEPS_TO_WAIT = None # np.ndarray: Keep track of the current delay for a given slicer DELAY_COUNTER = None # np.ndarray: Keep track of whether we touched a sliceable in the previous timestep PREVIOUSLY_TOUCHING = None # list of list of str: Body prim paths belonging to each slicer obj SLICER_LINK_PATHS = None @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(ContactBodies) return deps @classmethod def global_initialize(cls): # Call super first super().global_initialize() # Initialize other global variables cls.STEPS_TO_WAIT = max(1, int(np.ceil(m.REACTIVATION_DELAY / og.sim.get_rendering_dt()))) cls.DELAY_COUNTER = np.array([], dtype=int) cls.PREVIOUSLY_TOUCHING = np.array([], dtype=bool) cls.SLICER_LINK_PATHS = [] @classmethod def global_clear(cls): # Call super first super().global_clear() # Clear other internal state cls.STEPS_TO_WAIT = None cls.DELAY_COUNTER = None cls.PREVIOUSLY_TOUCHING = None cls.SLICER_LINK_PATHS = None @classmethod def _add_obj(cls, obj): # Call super first super()._add_obj(obj=obj) # Add to previously touching and delay counter cls.DELAY_COUNTER = np.concatenate([cls.DELAY_COUNTER, [0]]) cls.PREVIOUSLY_TOUCHING = np.concatenate([cls.PREVIOUSLY_TOUCHING, [False]]) # Add this object's prim paths to slicer paths cls.SLICER_LINK_PATHS.append([link.prim_path for link in obj.links.values()]) @classmethod def _remove_obj(cls, obj): # Grab idx we'll delete before the object is deleted deleted_idx = cls.OBJ_IDXS[obj.name] # Remove from all internal tracked arrays cls.DELAY_COUNTER = np.delete(cls.DELAY_COUNTER, [deleted_idx]) cls.PREVIOUSLY_TOUCHING = np.delete(cls.PREVIOUSLY_TOUCHING, [deleted_idx]) del cls.SLICER_LINK_PATHS[deleted_idx] # Call super super()._remove_obj(obj=obj) @classmethod def _update_values(cls, values): # If we were slicing in the past step, deactivate now previously_touching_idxs = np.nonzero(cls.PREVIOUSLY_TOUCHING)[0] values[previously_touching_idxs] = False cls.DELAY_COUNTER[previously_touching_idxs] = 0 # Reset the counter when we stop touching a sliceable object # Are we currently touching any sliceables? currently_touching_sliceables = cls._currently_touching_sliceables() # If any of our values are False, we need to consider reverting back. if not np.all(values): not_active_not_touching = ~values & ~currently_touching_sliceables not_active_is_touching = ~values & currently_touching_sliceables not_active_not_touching_idxs = np.where(not_active_not_touching)[0] not_active_is_touching_idxs = np.where(not_active_is_touching)[0] # If we are not touching any sliceable objects, we increment the delay "cooldown" counter that will # eventually re-activate the slicer cls.DELAY_COUNTER[not_active_not_touching_idxs] += 1 # If we are touching a sliceable object, reset the counter cls.DELAY_COUNTER[not_active_is_touching_idxs] = 0 # If the delay counter is greater than steps to wait, set to True values = np.where(cls.DELAY_COUNTER >= cls.STEPS_TO_WAIT, True, values) # Record if we were touching anything previously cls.PREVIOUSLY_TOUCHING = currently_touching_sliceables return values @classmethod def _currently_touching_sliceables(cls): # Initialize return value as all falses currently_touching = np.zeros_like(cls.PREVIOUSLY_TOUCHING) # Grab all sliceable objects sliceable_objs = og.sim.scene.object_registry("abilities", "sliceable", []) # If there's no sliceables, then obviously no slicer is touching any sliceable so immediately return all Falses if len(sliceable_objs) == 0: return currently_touching # Aggregate all link prim path indices all_slicer_idxs = [[RigidContactAPI.get_body_row_idx(prim_path) for prim_path in link_paths] for link_paths in cls.SLICER_LINK_PATHS] sliceable_idxs = [RigidContactAPI.get_body_col_idx(link.prim_path) for obj in sliceable_objs for link in obj.links.values()] impulses = RigidContactAPI.get_all_impulses() # Batch check each slicer against all sliceables for i, slicer_idxs in enumerate(all_slicer_idxs): if np.any(impulses[slicer_idxs][:, sliceable_idxs]): # We are touching at least one sliceable currently_touching[i] = True return currently_touching @classproperty def value_name(cls): return "value" @classproperty def value_type(cls): return bool def __init__(self, obj): # Run super first super(SlicerActive, self).__init__(obj) # Set value to be default (True) self._set_value(True) @property def state_size(self): # Call super first size = super().state_size # Add additional 2 to keep track of previously touching and delay counter return size + 2 # For this state, we simply store its value. def _dump_state(self): state = super()._dump_state() state["previously_touching"] = bool(self.PREVIOUSLY_TOUCHING[self.OBJ_IDXS[self.obj.name]]) state["delay_counter"] = int(self.DELAY_COUNTER[self.OBJ_IDXS[self.obj.name]]) return state def _load_state(self, state): super()._load_state(state=state) self.PREVIOUSLY_TOUCHING[self.OBJ_IDXS[self.obj.name]] = state["previously_touching"] self.DELAY_COUNTER[self.OBJ_IDXS[self.obj.name]] = state["delay_counter"] def _serialize(self, state): state_flat = super()._serialize(state=state) return np.concatenate([ state_flat, [state["previously_touching"], state["delay_counter"]], ], dtype=float) def _deserialize(self, state): state_dict, idx = super()._deserialize(state=state) state_dict[f"{self.value_name}"] = bool(state_dict[f"{self.value_name}"]) state_dict["previously_touching"] = bool(state[idx]) state_dict["delay_counter"] = int(state[idx + 1]) return state_dict, idx + 2
7,258
Python
37.407407
141
0.659686
StanfordVL/OmniGibson/omnigibson/object_states/robot_related_states.py
import numpy as np import omnigibson as og from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin, RelativeObjectState from omnigibson.sensors import VisionSensor _IN_REACH_DISTANCE_THRESHOLD = 2.0 _IN_FOV_PIXEL_FRACTION_THRESHOLD = 0.05 class RobotStateMixin: @property def robot(self): from omnigibson.robots.robot_base import BaseRobot assert isinstance(self.obj, BaseRobot), "This state only works with robots." return self.obj class IsGrasping(RelativeObjectState, BooleanStateMixin, RobotStateMixin): def _get_value(self, obj): # TODO: Make this work with non-assisted grasping return any( self.robot._ag_obj_in_hand[arm] == obj for arm in self.robot.arm_names ) # class InReachOfRobot(AbsoluteObjectState, BooleanStateMixin): # def _compute_value(self): # robot = _get_robot(self.simulator) # if not robot: # return False # robot_pos = robot.get_position() # object_pos = self.obj.get_position() # return np.linalg.norm(object_pos - np.array(robot_pos)) < _IN_REACH_DISTANCE_THRESHOLD # class InFOVOfRobot(AbsoluteObjectState, BooleanStateMixin): # @staticmethod # def get_optional_dependencies(): # return AbsoluteObjectState.get_optional_dependencies() + [ObjectsInFOVOfRobot] # def _get_value(self): # robot = _get_robot(self.simulator) # if not robot: # return False # body_ids = set(self.obj.get_body_ids()) # return not body_ids.isdisjoint(robot.states[ObjectsInFOVOfRobot].get_value()) class ObjectsInFOVOfRobot(AbsoluteObjectState, RobotStateMixin): def _get_value(self): """ Gets all objects in the robot's field of view. Returns: list: List of objects in the robot's field of view """ if not any(isinstance(sensor, VisionSensor) for sensor in self.robot.sensors.values()): raise ValueError("No vision sensors found on robot.") obj_names = [] names_to_exclude = set(['background', 'unlabelled']) for sensor in self.robot.sensors.values(): if isinstance(sensor, VisionSensor): _, info = sensor.get_obs() obj_names.extend([name for name in info['seg_instance'].values() if name not in names_to_exclude]) return [x for x in [og.sim.scene.object_registry("name", x) for x in obj_names] if x is not None]
2,529
Python
34.633802
114
0.653223
StanfordVL/OmniGibson/omnigibson/object_states/__init__.py
from omnigibson.object_states.object_state_base import REGISTERED_OBJECT_STATES from omnigibson.object_states.aabb import AABB from omnigibson.object_states.adjacency import HorizontalAdjacency, VerticalAdjacency from omnigibson.object_states.attached_to import AttachedTo from omnigibson.object_states.burnt import Burnt from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.object_states.contact_particles import ContactParticles from omnigibson.object_states.contains import ContainedParticles, Contains from omnigibson.object_states.cooked import Cooked from omnigibson.object_states.covered import Covered from omnigibson.object_states.frozen import Frozen from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink from omnigibson.object_states.heated import Heated from omnigibson.object_states.inside import Inside from omnigibson.object_states.max_temperature import MaxTemperature from omnigibson.object_states.next_to import NextTo from omnigibson.object_states.on_fire import OnFire from omnigibson.object_states.on_top import OnTop from omnigibson.object_states.open_state import Open from omnigibson.object_states.overlaid import Overlaid from omnigibson.object_states.particle_modifier import ParticleRemover, ParticleApplier from omnigibson.object_states.particle_source_or_sink import ParticleSource, ParticleSink from omnigibson.object_states.particle import ParticleRequirement from omnigibson.object_states.pose import Pose from omnigibson.object_states.robot_related_states import IsGrasping, ObjectsInFOVOfRobot from omnigibson.object_states.saturated import Saturated from omnigibson.object_states.slicer_active import SlicerActive from omnigibson.object_states.sliceable import SliceableRequirement from omnigibson.object_states.temperature import Temperature from omnigibson.object_states.toggle import ToggledOn from omnigibson.object_states.touching import Touching from omnigibson.object_states.under import Under from omnigibson.object_states.filled import Filled from omnigibson.object_states.folded import Folded, Unfolded, FoldedLevel from omnigibson.object_states.draped import Draped
2,161
Python
59.055554
89
0.869968
StanfordVL/OmniGibson/omnigibson/object_states/heat_source_or_sink.py
import omnigibson as og from omnigibson.macros import create_module_macros, macros from omnigibson.object_states.aabb import AABB from omnigibson.object_states.inside import Inside from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin from omnigibson.object_states.object_state_base import AbsoluteObjectState from omnigibson.object_states.open_state import Open from omnigibson.object_states.toggle import ToggledOn from omnigibson.object_states.update_state_mixin import UpdateStateMixin from omnigibson.utils.python_utils import classproperty from omnigibson.utils.constants import PrimType import numpy as np # Create settings for this module m = create_module_macros(module_path=__file__) m.HEATSOURCE_LINK_PREFIX = "heatsource" m.HEATING_ELEMENT_MARKER_SCALE = [1.0] * 3 # TODO: Delete default values for this and make them required. m.DEFAULT_TEMPERATURE = 200 m.DEFAULT_HEATING_RATE = 0.04 m.DEFAULT_DISTANCE_THRESHOLD = 0.2 class HeatSourceOrSink(AbsoluteObjectState, LinkBasedStateMixin, UpdateStateMixin): """ This state indicates the heat source or heat sink state of the object. Currently, if the object is not an active heat source/sink, this returns (False, None). Otherwise, it returns True and the position of the heat source element, or (True, None) if the heat source has no heating element / only checks for Inside. E.g. on a stove object, True and the coordinates of the heating element will be returned. on a microwave object, True and None will be returned. """ def __init__( self, obj, temperature=m.DEFAULT_TEMPERATURE, heating_rate=m.DEFAULT_HEATING_RATE, distance_threshold=m.DEFAULT_DISTANCE_THRESHOLD, requires_toggled_on=False, requires_closed=False, requires_inside=False, ): """ Args: obj (StatefulObject): The object with the heat source ability. temperature (float): The temperature of the heat source. heating_rate (float): Fraction in [0, 1] of the temperature difference with the heat source temperature should be received every step, per second. distance_threshold (float): The distance threshold which an object needs to be closer than in order to receive heat from this heat source. requires_toggled_on (bool): Whether the heat source object needs to be toggled on to emit heat. Requires toggleable ability if set to True. requires_closed (bool): Whether the heat source object needs to be closed (e.g. in terms of the joints) to emit heat. Requires openable ability if set to True. requires_inside (bool): Whether an object needs to be `inside` the heat source to receive heat. See the Inside state for details. This will mean that the "heating element" link for the object will be ignored. """ super(HeatSourceOrSink, self).__init__(obj) self._temperature = temperature self._heating_rate = heating_rate self.distance_threshold = distance_threshold # If the heat source needs to be toggled on, we assert the presence # of that ability. if requires_toggled_on: assert ToggledOn in self.obj.states self.requires_toggled_on = requires_toggled_on # If the heat source needs to be closed, we assert the presence # of that ability. if requires_closed: assert Open in self.obj.states self.requires_closed = requires_closed # If the heat source needs to contain an object inside to heat it, # we record that for use in the heat transfer process. self.requires_inside = requires_inside # Internal state that gets cached self._affected_objects = None @classmethod def is_compatible(cls, obj, **kwargs): # Run super first compatible, reason = super().is_compatible(obj, **kwargs) if not compatible: return compatible, reason # Check whether this state has toggledon if required or open if required for kwarg, state_type in zip(("requires_toggled_on", "requires_closed"), (ToggledOn, Open)): if kwargs.get(kwarg, False) and state_type not in obj.states: return False, f"{cls.__name__} has {kwarg} but obj has no {state_type.__name__} state!" return True, None @classmethod def is_compatible_asset(cls, prim, **kwargs): # Run super first compatible, reason = super().is_compatible_asset(prim, **kwargs) if not compatible: return compatible, reason # Check whether this state has toggledon if required or open if required for kwarg, state_type in zip(("requires_toggled_on", "requires_closed"), (ToggledOn, Open)): if kwargs.get(kwarg, False) and not state_type.is_compatible_asset(prim=prim, **kwargs)[0]: return False, f"{cls.__name__} has {kwarg} but obj has no {state_type.__name__} state!" return True, None @classproperty def metalink_prefix(cls): return m.HEATSOURCE_LINK_PREFIX @classmethod def requires_metalink(cls, **kwargs): # No metalink required if inside return not kwargs.get("requires_inside", False) @property def _default_link(self): # Only supported if we require inside return self.obj.root_link if self.requires_inside else super()._default_link @property def heating_rate(self): """ Returns: float: Temperature changing rate of this heat source / sink """ return self._heating_rate @property def temperature(self): """ Returns: float: Temperature of this heat source / sink """ return self._temperature @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.update({AABB, Inside}) return deps @classmethod def get_optional_dependencies(cls): deps = super().get_optional_dependencies() deps.update({ToggledOn, Open}) return deps def _initialize(self): # Run super first super()._initialize() self.initialize_link_mixin() def _get_value(self): # Check the toggle state. if self.requires_toggled_on and not self.obj.states[ToggledOn].get_value(): return False # Check the open state. if self.requires_closed and self.obj.states[Open].get_value(): return False return True def affects_obj(self, obj): """ Computes whether this heat source or sink object is affecting object @obj Computes the temperature delta that may be applied to object @obj. NOTE: This value is agnostic to simulation stepping speed, and should be scaled accordingly Args: obj (StatefulObject): Object whose temperature delta should be computed Returns: bool: Whether this heat source or sink is currently affecting @obj's temperature """ # No change if we're not on if not self.get_value(): return False # If the object is not affected, we return False if obj not in self._affected_objects: return False # If all checks pass, we're actively influencing the object! return True def _update(self): # Avoid circular imports from omnigibson.object_states.temperature import Temperature from omnigibson.objects.stateful_object import StatefulObject # Update the internally tracked nearby objects to accelerate filtering for affects_obj affected_objects = set() # Only update if we're valid if self.get_value(): def overlap_callback(hit): nonlocal affected_objects # global affected_objects obj = og.sim.scene.object_registry("prim_path", "/".join(hit.rigid_body.split("/")[:-1])) if obj is not None: affected_objects.add(obj) # Always continue traversal return True if self.requires_inside: # Use overlap_box check to check for objects inside the box! aabb_lower, aabb_upper = self.obj.states[AABB].get_value() half_extent = (aabb_upper - aabb_lower) / 2.0 aabb_center = (aabb_upper + aabb_lower) / 2.0 og.sim.psqi.overlap_box( halfExtent=half_extent, pos=aabb_center, rot=np.array([0, 0, 0, 1.0]), reportFn=overlap_callback, ) # Cloth isn't subject to overlap checks, so we also have to manually check their poses as well cloth_objs = tuple(og.sim.scene.object_registry("prim_type", PrimType.CLOTH, [])) n_cloth_objs = len(cloth_objs) if n_cloth_objs > 0: cloth_positions = np.zeros((n_cloth_objs, 3)) for i, obj in enumerate(cloth_objs): cloth_positions[i] = obj.get_position() for idx in np.where(np.all((aabb_lower.reshape(1, 3) < cloth_positions) & (cloth_positions < aabb_upper.reshape(1, 3)), axis=-1))[0]: affected_objects.add(cloth_objs[idx]) # Additionally prune objects based on Inside requirement -- cast to avoid in-place operations for obj in tuple(affected_objects): if not obj.states[Inside].get_value(self.obj): affected_objects.remove(obj) else: # Position is either the AABB center of the default link or the metalink position itself heat_source_pos = self.link.aabb_center if self.link == self._default_link else self.link.get_position() # Use overlap_sphere check! og.sim.psqi.overlap_sphere( radius=self.distance_threshold, pos=heat_source_pos, reportFn=overlap_callback, ) # Cloth isn't subject to overlap checks, so we also have to manually check their poses as well cloth_objs = tuple(og.sim.scene.object_registry("prim_type", PrimType.CLOTH, [])) n_cloth_objs = len(cloth_objs) if n_cloth_objs > 0: cloth_positions = np.zeros((n_cloth_objs, 3)) for i, obj in enumerate(cloth_objs): cloth_positions[i] = obj.get_position() for idx in np.where(np.linalg.norm(heat_source_pos.reshape(1, 3) - cloth_positions, axis=-1) <= self.distance_threshold)[0]: affected_objects.add(cloth_objs[idx]) # Remove self (we cannot affect ourselves) and update the internal set of objects, and remove self if self.obj in affected_objects: affected_objects.remove(self.obj) self._affected_objects = {obj for obj in affected_objects if isinstance(obj, StatefulObject) and Temperature in obj.states} # Propagate the affected objects' temperatures if len(self._affected_objects) > 0: Temperature.update_temperature_from_heatsource_or_sink( objs=self._affected_objects, temperature=self.temperature, rate=self.heating_rate, ) # Nothing needs to be done to save/load HeatSource
11,739
Python
40.779359
153
0.620411
StanfordVL/OmniGibson/omnigibson/object_states/factory.py
import networkx as nx from collections import namedtuple from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states import * # states: list of ObjectBaseState # requirements: list of ObjectBaseRequirement AbilityDependencies = namedtuple("AbilityDependencies", ("states", "requirements")) # Maps ability name to list of Object States and / or Ability Requirements that determine # whether the given ability can be instantiated for a requested object _ABILITY_DEPENDENCIES = { "robot": AbilityDependencies(states=[IsGrasping, ObjectsInFOVOfRobot], requirements=[]), "attachable": AbilityDependencies(states=[AttachedTo], requirements=[]), "particleApplier": AbilityDependencies(states=[ParticleApplier], requirements=[ParticleRequirement]), "particleRemover": AbilityDependencies(states=[ParticleRemover], requirements=[ParticleRequirement]), "particleSource": AbilityDependencies(states=[ParticleSource], requirements=[ParticleRequirement]), "particleSink": AbilityDependencies(states=[ParticleSink], requirements=[ParticleRequirement]), "coldSource": AbilityDependencies(states=[HeatSourceOrSink], requirements=[]), "cookable": AbilityDependencies(states=[Cooked, Burnt], requirements=[]), "coverable": AbilityDependencies(states=[Covered], requirements=[]), "freezable": AbilityDependencies(states=[Frozen], requirements=[]), "heatable": AbilityDependencies(states=[Heated], requirements=[]), "heatSource": AbilityDependencies(states=[HeatSourceOrSink], requirements=[]), "meltable": AbilityDependencies(states=[MaxTemperature], requirements=[]), "mixingTool": AbilityDependencies(states=[], requirements=[]), "openable": AbilityDependencies(states=[Open], requirements=[]), "flammable": AbilityDependencies(states=[OnFire], requirements=[]), "saturable": AbilityDependencies(states=[Saturated], requirements=[]), "sliceable": AbilityDependencies(states=[], requirements=[SliceableRequirement]), "slicer": AbilityDependencies(states=[SlicerActive], requirements=[]), "toggleable": AbilityDependencies(states=[ToggledOn], requirements=[]), "cloth": AbilityDependencies(states=[Folded, Unfolded, Overlaid, Draped], requirements=[]), "fillable": AbilityDependencies(states=[Filled, Contains], requirements=[]), } _DEFAULT_STATE_SET = frozenset( [ Inside, NextTo, OnTop, Touching, Under, Covered, ] ) _KINEMATIC_STATE_SET = frozenset( [state for state in REGISTERED_OBJECT_STATES.values() if issubclass(state, KinematicsMixin)] ) _FIRE_STATE_SET = frozenset( [ HeatSourceOrSink, OnFire, ] ) _STEAM_STATE_SET = frozenset( [ Heated, ] ) _TEXTURE_CHANGE_STATE_SET = frozenset( [ Frozen, Burnt, Cooked, Saturated, ToggledOn, ] ) _SYSTEM_STATE_SET = frozenset( [ Covered, Saturated, Filled, Contains, ] ) _VISUAL_STATE_SET = frozenset(_FIRE_STATE_SET | _STEAM_STATE_SET | _TEXTURE_CHANGE_STATE_SET) _TEXTURE_CHANGE_PRIORITY = { Frozen: 4, Burnt: 3, Cooked: 2, Saturated: 1, ToggledOn: 0, } def get_system_states(): return _SYSTEM_STATE_SET def get_fire_states(): return _FIRE_STATE_SET def get_steam_states(): return _STEAM_STATE_SET def get_texture_change_states(): return _TEXTURE_CHANGE_STATE_SET def get_texture_change_priority(): return _TEXTURE_CHANGE_PRIORITY def get_visual_states(): return _VISUAL_STATE_SET def get_default_states(): return _DEFAULT_STATE_SET def get_state_name(state): # Get the name of the class. return state.__name__ def get_states_for_ability(ability): if ability not in _ABILITY_DEPENDENCIES: return [] return _ABILITY_DEPENDENCIES[ability].states def get_requirements_for_ability(ability): if ability not in _ABILITY_DEPENDENCIES: return [] return _ABILITY_DEPENDENCIES[ability].requirements def get_state_dependency_graph(states=None): """ Args: states (None or Iterable): If specified, specific state(s) to sort. Otherwise, will generate dependency graph over all states Returns: nx.DiGraph: State dependency graph of supported object states """ states = REGISTERED_OBJECT_STATES.values() if states is None else states dependencies = {state: set.union(state.get_dependencies(), state.get_optional_dependencies()) for state in states} return nx.DiGraph(dependencies) def get_states_by_dependency_order(states=None): """ Args: states (None or Iterable): If specified, specific state(s) to sort. Otherwise, will generate dependency graph over all states Returns: list: all states in topological order of dependency """ return list(reversed(list(nx.algorithms.topological_sort(get_state_dependency_graph(states)))))
4,984
Python
29.582822
118
0.700241
StanfordVL/OmniGibson/omnigibson/object_states/filled.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.contains import ContainedParticles from omnigibson.object_states.object_state_base import RelativeObjectState, BooleanStateMixin from omnigibson.systems.system_base import PhysicalParticleSystem, is_physical_particle_system from omnigibson.systems.macro_particle_system import MacroParticleSystem # Create settings for this module m = create_module_macros(module_path=__file__) # Proportion of object's volume that must be filled for object to be considered filled m.VOLUME_FILL_PROPORTION = 0.2 m.N_MAX_MACRO_PARTICLE_SAMPLES = 500 m.N_MAX_MICRO_PARTICLE_SAMPLES = 100000 class Filled(RelativeObjectState, BooleanStateMixin): def _get_value(self, system): # Sanity check to make sure system is valid assert is_physical_particle_system(system_name=system.name), \ "Can only get Filled state with a valid PhysicalParticleSystem!" # Check what volume is filled if system.n_particles > 0: # Treat particles as cubes particle_volume = (system.particle_radius * 2) ** 3 n_particles = self.obj.states[ContainedParticles].get_value(system).n_in_volume prop_filled = particle_volume * n_particles / self.obj.states[ContainedParticles].volume # If greater than threshold, then the volume is filled # Explicit bool cast needed here because the type is bool_ instead of bool which is not JSON-Serializable # This has to do with numpy, see https://stackoverflow.com/questions/58408054/typeerror-object-of-type-bool-is-not-json-serializable value = bool(prop_filled > m.VOLUME_FILL_PROPORTION) else: # No particles exists, so we're obviously empty value = False return value def _set_value(self, system, new_value): # Sanity check to make sure system is valid assert is_physical_particle_system(system_name=system.name), \ "Can only set Filled state with a valid PhysicalParticleSystem!" # First, check our current state current_state = self.get_value(system) # Only do something if we're changing state if current_state != new_value: contained_particles_state = self.obj.states[ContainedParticles] if new_value: # Going from False --> True, sample volume with particles system.generate_particles_from_link( obj=self.obj, link=contained_particles_state.link, check_contact=True, max_samples=m.N_MAX_MACRO_PARTICLE_SAMPLES if issubclass(system, MacroParticleSystem) else m.N_MAX_MICRO_PARTICLE_SAMPLES ) else: # Cannot set False raise NotImplementedError(f"{self.__class__.__name__} does not support set_value(system, False)") return True @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(ContainedParticles) return deps
3,156
Python
43.464788
144
0.665082
StanfordVL/OmniGibson/omnigibson/object_states/draped.py
from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.object_states.cloth_mixin import ClothStateMixin from omnigibson.utils.constants import PrimType from omnigibson.utils.object_state_utils import sample_cloth_on_rigid import omnigibson as og import numpy as np class Draped(RelativeObjectState, KinematicsMixin, BooleanStateMixin, ClothStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(ContactBodies) return deps def _set_value(self, other, new_value): if not new_value: raise NotImplementedError("DrapedOver does not support set_value(False)") if not (self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): raise ValueError("DrapedOver state requires obj1 is cloth and obj2 is rigid.") state = og.sim.dump_state(serialized=False) if sample_cloth_on_rigid(self.obj, other, randomize_xy=True) and self.get_value(other): return True else: og.sim.load_state(state, serialized=False) return False def _get_value(self, other): """ Check whether the (cloth) object is draped on the other (rigid) object. The cloth object should touch the rigid object and its CoM should be below the average position of the contact points. """ if not (self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): raise ValueError("Draped state requires obj1 is cloth and obj2 is rigid.") # Find the links of @other that are in contact with @self.obj contact_links = self.obj.states[ContactBodies].get_value() & set(other.links.values()) if len(contact_links) == 0: return False contact_link_prim_paths = {contact_link.prim_path for contact_link in contact_links} # Filter the contact points to only include the ones that are on the contact links contact_positions = [] for contact in self.obj.contact_list(): if len({contact.body0, contact.body1} & contact_link_prim_paths) > 0: contact_positions.append(contact.position) # The center of mass of the cloth needs to be below the average position of the contact points mean_contact_position = np.mean(contact_positions, axis=0) center_of_mass = np.mean(self.obj.root_link.keypoint_particle_positions, axis=0) return center_of_mass[2] < mean_contact_position[2]
2,692
Python
45.431034
126
0.693908
StanfordVL/OmniGibson/omnigibson/object_states/attached_to.py
import numpy as np from collections import defaultdict import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import create_module_macros import omnigibson.utils.transform_utils as T from omnigibson.object_states.contact_subscribed_state_mixin import ContactSubscribedStateMixin from omnigibson.object_states.joint_break_subscribed_state_mixin import JointBreakSubscribedStateMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.utils.constants import JointType from omnigibson.utils.usd_utils import create_joint from omnigibson.utils.ui_utils import create_module_logger from omnigibson.utils.python_utils import classproperty from omnigibson.utils.usd_utils import CollisionAPI # Create module logger log = create_module_logger(module_name=__name__) # Create settings for this module m = create_module_macros(module_path=__file__) m.ATTACHMENT_LINK_PREFIX = "attachment" m.DEFAULT_POSITION_THRESHOLD = 0.05 # 5cm m.DEFAULT_ORIENTATION_THRESHOLD = np.deg2rad(5.0) # 5 degrees m.DEFAULT_JOINT_TYPE = JointType.JOINT_FIXED m.DEFAULT_BREAK_FORCE = 1000 # Newton m.DEFAULT_BREAK_TORQUE = 1000 # Newton-Meter # TODO: Make AttachedTo into a global state that manages all the attachments in the scene. # When an attachment of a child and a parent is about to happen: # 1. stop the sim # 2. remove all existing attachment joints (and save information to restore later) # 3. disable collision between the child and the parent # 4. play the sim # 5. reload the state # 6. restore all existing attachment joints # 7. create the joint class AttachedTo(RelativeObjectState, BooleanStateMixin, ContactSubscribedStateMixin, JointBreakSubscribedStateMixin, LinkBasedStateMixin): """ Handles attachment between two rigid objects, by creating a fixed/spherical joint between self.obj (child) and other (parent). At any given moment, an object can only be attached to at most one other object, i.e. a parent can have multiple children, but a child can only have one parent. Note that generally speaking only child.states[AttachedTo].get_value(parent) will return True. One of the child's male meta links will be attached to one of the parent's female meta links. Subclasses ContactSubscribedStateMixin, JointBreakSubscribedStateMixin on_contact function attempts to attach self.obj to other when a CONTACT_FOUND event happens on_joint_break function breaks the current attachment """ # This is to force the __init__ args to be "self" and "obj" only. # Otherwise, it will inherit from LinkBasedStateMixin and the __init__ args will be "self", "args", "kwargs". def __init__(self, obj): # Run super method super().__init__(obj=obj) def initialize(self): super().initialize() og.sim.add_callback_on_stop(name=f"{self.obj.name}_detach", callback=self._detach) self.parents_disabled_collisions = set() def remove(self): super().remove() og.sim.remove_callback_on_stop(name=f"{self.obj.name}_detach") @classproperty def metalink_prefix(cls): """ Returns: str: Unique keyword that defines the metalink associated with this object state """ return m.ATTACHMENT_LINK_PREFIX @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(ContactBodies) return deps def _initialize(self): super()._initialize() self.initialize_link_mixin() # Reference to the parent object (DatasetObject) self.parent = None # Reference to the female meta link of the parent object (RigidPrim) self.parent_link = None # Mapping from the female meta link names of self.obj to their children (Dict[str, Optional[DatasetObject] = None]) self.children = {link_name: None for link_name in self.links if link_name.split("_")[1].endswith("F")} # Cache of parent link candidates for other objects (Dict[DatasetObject, Dict[str, str]]) # @other -> (the male meta link names of @self.obj -> the correspounding female meta link names of @other)) self.parent_link_candidates = dict() def on_joint_break(self, joint_prim_path): # Note that when this function is invoked when a joint break event happens, @self.obj is the parent of the # attachment joint, not the child. We access the child of the broken joint, and call the setter with False child = self.children[joint_prim_path.split("/")[-2]] child.states[AttachedTo].set_value(self.obj, False) # Attempts to attach two objects when a CONTACT_FOUND event happens def on_contact(self, other, contact_headers, contact_data): for contact_header in contact_headers: if contact_header.type == lazy.omni.physx.bindings._physx.ContactEventType.CONTACT_FOUND: # If it has successfully attached to something, break. if self.set_value(other, True): break def _set_value(self, other, new_value, bypass_alignment_checking=False, check_physics_stability=False, can_joint_break=True): """ Args: other (DatasetObject): parent object to attach to. new_value (bool): whether to attach or detach. bypass_alignment_checking (bool): whether to bypass alignment checking when finding attachment links. Normally when finding attachment links, we check if the child and parent links have aligned positions or poses. This flag allows users to bypass this check and find attachment links solely based on the attachment meta link types. Default is False. check_physics_stability (bool): whether to check if the attachment is stable after attachment. If True, it will check if the child object is not colliding with other objects except the parent object. If False, it will not check the stability and simply attach the child to the parent. Default is False. can_joint_break (bool): whether the joint can break or not. Returns: bool: whether the attachment setting was successful or not. """ # Attempt to attach if new_value: if self.parent == other: # Already attached to this object. Do nothing. return True elif self.parent is not None: log.debug(f"Trying to attach object {self.obj.name} to object {other.name}," f"but it is already attached to object {self.parent.name}. Try detaching first.") return False else: # Find attachment links that satisfy the proximity requirements child_link, parent_link = self._find_attachment_links(other, bypass_alignment_checking) if child_link is None: return False else: if check_physics_stability: state = og.sim.dump_state() self._attach(other, child_link, parent_link, can_joint_break=can_joint_break) if not check_physics_stability: return True else: og.sim.step_physics() # self.obj should not collide with other objects except the parent success = len(self.obj.states[ContactBodies].get_value(ignore_objs=(other,))) == 0 if success: return True else: self._detach() og.sim.load_state(state) return False # Attempt to detach else: if self.parent == other: self._detach() # Wake up objects so that passive forces like gravity can be applied. self.obj.wake() other.wake() return True def _get_value(self, other): # Simply return if the current parent matches other return other == self.parent def _find_attachment_links(self, other, bypass_alignment_checking=False, pos_thresh=m.DEFAULT_POSITION_THRESHOLD, orn_thresh=m.DEFAULT_ORIENTATION_THRESHOLD): """ Args: other (DatasetObject): parent object to find potential attachment links. bypass_alignment_checking (bool): whether to bypass alignment checking when finding attachment links. Normally when finding attachment links, we check if the child and parent links have aligned positions or poses. This flag allows users to bypass this check and find attachment links solely based on the attachment meta link types. Default is False. pos_thresh (float): position difference threshold to activate attachment, in meters. orn_thresh (float): orientation difference threshold to activate attachment, in radians. Returns: 2-tuple: - RigidPrim or None: link belonging to @self.obj that should be aligned to that corresponding link of @other - RigidPrim or None: the corresponding link of @other """ parent_candidates = self._get_parent_candidates(other) if not parent_candidates: return None, None for child_link_name, parent_link_names in parent_candidates.items(): child_link = self.links[child_link_name] for parent_link_name in parent_link_names: parent_link = other.states[AttachedTo].links[parent_link_name] if other.states[AttachedTo].children[parent_link_name] is None: if bypass_alignment_checking: return child_link, parent_link pos_diff = np.linalg.norm(child_link.get_position() - parent_link.get_position()) orn_diff = T.get_orientation_diff_in_radian(child_link.get_orientation(), parent_link.get_orientation()) if pos_diff < pos_thresh and orn_diff < orn_thresh: return child_link, parent_link return None, None def _get_parent_candidates(self, other): """ Helper function to return the parent link candidates for @other Returns: Dict[str, str] or None: mapping from the male meta link names of self.obj to the correspounding female meta link names of @other. Returns None if @other does not have the AttachedTo state. """ if AttachedTo not in other.states: return None if other not in self.parent_link_candidates: parent_link_names = defaultdict(set) for child_link_name, child_link in self.links.items(): child_category = child_link_name.split("_")[1] if child_category.endswith("F"): continue assert child_category.endswith("M") parent_category = child_category[:-1] + "F" for parent_link_name, parent_link in other.states[AttachedTo].links.items(): if parent_category in parent_link_name: parent_link_names[child_link_name].add(parent_link_name) self.parent_link_candidates[other] = parent_link_names return self.parent_link_candidates[other] @property def attachment_joint_prim_path(self): return f"{self.parent_link.prim_path}/{self.obj.name}_attachment_joint" if self.parent_link is not None else None def _attach(self, other, child_link, parent_link, joint_type=m.DEFAULT_JOINT_TYPE, can_joint_break=True): """ Creates a fixed or spherical joint between a male meta link of self.obj (@child_link) and a female meta link of @other (@parent_link) with a given @joint_type, @break_force and @break_torque Args: other (DatasetObject): parent object to attach to. child_link (RigidPrim): male meta link of @self.obj. parent_link (RigidPrim): female meta link of @other. joint_type (JointType): joint type of the attachment, {JointType.JOINT_FIXED, JointType.JOINT_SPHERICAL} can_joint_break (bool): whether the joint can break or not. """ assert joint_type in {JointType.JOINT_FIXED, JointType.JOINT_SPHERICAL}, f"Unsupported joint type {joint_type}" # Set pose for self.obj so that child_link and parent_link align (6dof alignment for FixedJoint and 3dof alignment for SphericalJoint) parent_pos, parent_quat = parent_link.get_position_orientation() child_pos, child_quat = child_link.get_position_orientation() child_root_pos, child_root_quat = self.obj.get_position_orientation() if joint_type == JointType.JOINT_FIXED: # For FixedJoint: find the relation transformation of the two frames and apply it to self.obj. rel_pos, rel_quat = T.mat2pose(T.pose2mat((parent_pos, parent_quat)) @ T.pose_inv(T.pose2mat((child_pos, child_quat)))) new_child_root_pos, new_child_root_quat = T.pose_transform(rel_pos, rel_quat, child_root_pos, child_root_quat) else: # For SphericalJoint: move the position of self.obj to align the two frames and keep the rotation unchanged. new_child_root_pos = child_root_pos + (parent_pos - child_pos) new_child_root_quat = child_root_quat # Actually move the object and also keep it still for stability purposes. self.obj.set_position_orientation(new_child_root_pos, new_child_root_quat) self.obj.keep_still() other.keep_still() if joint_type == JointType.JOINT_FIXED: # FixedJoint: the parent link, the child link and the joint frame all align. parent_local_quat = np.array([0.0, 0.0, 0.0, 1.0]) else: # SphericalJoint: the same except that the rotation of the parent link doesn't align with the joint frame. # The child link and the joint frame still align. _, parent_local_quat = T.relative_pose_transform([0, 0, 0], child_quat, [0, 0, 0], parent_quat) # Disable collision between the parent and child objects self._disable_collision_between_child_and_parent(child=self.obj, parent=other) # Set the parent references self.parent = other self.parent_link = parent_link # Set the child reference for @other other.states[AttachedTo].children[parent_link.body_name] = self.obj kwargs = {"break_force": m.DEFAULT_BREAK_FORCE, "break_torque": m.DEFAULT_BREAK_TORQUE} if can_joint_break else dict() # Create the joint create_joint( prim_path=self.attachment_joint_prim_path, joint_type=joint_type, body0=f"{parent_link.prim_path}", body1=f"{child_link.prim_path}", joint_frame_in_parent_frame_pos=np.zeros(3), joint_frame_in_parent_frame_quat=parent_local_quat, joint_frame_in_child_frame_pos=np.zeros(3), joint_frame_in_child_frame_quat=np.array([0.0, 0.0, 0.0, 1.0]), **kwargs ) def _disable_collision_between_child_and_parent(self, child, parent): """ Disables collision between the child and parent objects """ if parent in self.parents_disabled_collisions: return self.parents_disabled_collisions.add(parent) was_playing = og.sim.is_playing() if was_playing: state = og.sim.dump_state() og.sim.stop() for child_link in child.links.values(): for parent_link in parent.links.values(): child_link.add_filtered_collision_pair(parent_link) if parent.category == "wall_nail": # Temporary hack to disable collision between the attached child object and all walls/floors so that objects # attached to the wall_nails do not collide with the walls/floors. for wall in og.sim.scene.object_registry("category", "walls", set()): for wall_link in wall.links.values(): for child_link in child.links.values(): child_link.add_filtered_collision_pair(wall_link) for wall in og.sim.scene.object_registry("category", "floors", set()): for floor_link in wall.links.values(): for child_link in child.links.values(): child_link.add_filtered_collision_pair(floor_link) # Temporary hack to disable gravity for the attached child object if the parent is kinematic_only # Otherwise, the parent metalink will oscillate due to the gravity force of the child. if parent.kinematic_only: child.disable_gravity() if was_playing: og.sim.play() og.sim.load_state(state) def _detach(self): """ Removes the current attachment joint """ if self.parent_link is not None: # Remove the attachment joint prim from the stage og.sim.stage.RemovePrim(self.attachment_joint_prim_path) # Remove child reference from the parent object self.parent.states[AttachedTo].children[self.parent_link.body_name] = None # Remove reference to the parent object and link self.parent = None self.parent_link = None @property def settable(self): return True @property def state_size(self): return 1 def _dump_state(self): return dict(attached_obj_uuid=-1 if self.parent is None else self.parent.uuid) def _load_state(self, state): uuid = state["attached_obj_uuid"] if uuid == -1: attached_obj = None else: attached_obj = og.sim.scene.object_registry("uuid", uuid) assert attached_obj is not None, "attached_obj_uuid does not match any object in the scene." if self.parent != attached_obj: # If it's currently attached to something else, detach. if self.parent is not None: self.set_value(self.parent, False) # assert self.parent is None, "parent reference is not cleared after detachment" if self.parent is not None: log.warning(f"parent reference is not cleared after detachment") # If the loaded state requires attachment, attach. if attached_obj is not None: self.set_value(attached_obj, True, bypass_alignment_checking=True, check_physics_stability=False, can_joint_break=True) # assert self.parent == attached_obj, "parent reference is not updated after attachment" if self.parent != attached_obj: log.warning(f"parent reference is not updated after attachment") def _serialize(self, state): return np.array([state["attached_obj_uuid"]], dtype=float) def _deserialize(self, state): return dict(attached_obj_uuid=int(state[0])), 1
19,625
Python
47.459259
142
0.63358
StanfordVL/OmniGibson/omnigibson/object_states/contains.py
import numpy as np from collections import namedtuple from omnigibson.macros import create_module_macros from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin from omnigibson.object_states.object_state_base import RelativeObjectState, BooleanStateMixin from omnigibson.systems.system_base import VisualParticleSystem, PhysicalParticleSystem, is_visual_particle_system, \ is_physical_particle_system from omnigibson.utils.geometry_utils import generate_points_in_volume_checker_function from omnigibson.utils.python_utils import classproperty import omnigibson.utils.transform_utils as T # Create settings for this module m = create_module_macros(module_path=__file__) m.CONTAINER_LINK_PREFIX = "container" m.VISUAL_PARTICLE_OFFSET = 0.01 # Offset to visual particles' poses when checking overlaps with container volume """ ContainedParticlesData contains the following fields: n_in_volume (int): number of particles in the container volume positions (np.array): (N, 3) array representing the raw global particle positions in_volume (np.array): (N,) boolean array representing whether each particle is inside the container volume or not """ ContainedParticlesData = namedtuple("ContainedParticlesData", ("n_in_volume", "positions", "in_volume")) class ContainedParticles(RelativeObjectState, LinkBasedStateMixin): """ Object state for computing the number of particles of a given system contained in this object's container volume """ def __init__(self, obj): super().__init__(obj) self.check_in_volume = None # Function to check whether particles are in volume for this container self._volume = None # Volume of this container self._compute_info = None # Intermediate computation information to store @classproperty def metalink_prefix(cls): return m.CONTAINER_LINK_PREFIX def _get_value(self, system): """ Args: system (VisualParticleSystem or PhysicalParticleSystem): System whose number of particles will be checked inside this object's container volume Returns: ContainedParticlesData: namedtuple with the following keys: - n_in_volume (int): Number of @system's particles inside this object's container volume - positions (np.array): (N, 3) Particle positions of all @system's particles - in_volume (np.array): (N,) boolean array, True if the corresponding particle is inside this object's container volume, else False """ # Value is false by default n_particles_in_volume, raw_positions, checked_positions, particles_in_volume = 0, np.array([]), np.array([]), np.array([]) # Only run additional computations if there are any particles if system.n_particles > 0: # First, we check what type of system # Currently, we support VisualParticleSystems and PhysicalParticleSystems if is_visual_particle_system(system_name=system.name): # Grab global particle poses and offset them in the direction of their orientation raw_positions, quats = system.get_particles_position_orientation() unit_z = np.zeros((len(raw_positions), 3, 1)) unit_z[:, -1, :] = m.VISUAL_PARTICLE_OFFSET checked_positions = (T.quat2mat(quats) @ unit_z).reshape(-1, 3) + raw_positions elif is_physical_particle_system(system_name=system.name): raw_positions = system.get_particles_position_orientation()[0] checked_positions = raw_positions else: raise ValueError(f"Invalid system {system} received for getting ContainedParticles state!" f"Currently, only VisualParticleSystems and PhysicalParticleSystems are supported.") # Only calculate if we have valid positions if len(checked_positions) > 0: particles_in_volume = self.check_in_volume(checked_positions) n_particles_in_volume = particles_in_volume.sum() return ContainedParticlesData(n_particles_in_volume, raw_positions, particles_in_volume) def _initialize(self): super()._initialize() self.initialize_link_mixin() # Generate volume checker function for this object self.check_in_volume, calculate_volume = \ generate_points_in_volume_checker_function(obj=self.obj, volume_link=self.link) # Calculate volume self._volume = calculate_volume() @property def volume(self): """ Returns: float: Total volume for this container """ return self._volume class Contains(RelativeObjectState, BooleanStateMixin): def _get_value(self, system): # Grab value from Contains state; True if value is greater than 0 return self.obj.states[ContainedParticles].get_value(system=system).n_in_volume > 0 def _set_value(self, system, new_value): if new_value: # Cannot set contains = True, only False raise NotImplementedError(f"{self.__class__.__name__} does not support set_value(system, True)") else: # Remove all particles from inside the volume system.remove_particles(idxs=self.obj.states[ContainedParticles].get_value(system).in_volume.nonzero()[0]) return True @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(ContainedParticles) return deps
5,642
Python
45.254098
138
0.673166
StanfordVL/OmniGibson/omnigibson/object_states/contact_bodies.py
import omnigibson as og from omnigibson.object_states.object_state_base import AbsoluteObjectState from omnigibson.utils.sim_utils import prims_to_rigid_prim_set class ContactBodies(AbsoluteObjectState): def _get_value(self, ignore_objs=None): # Compute bodies in contact, minus the self-owned bodies bodies = set() for contact in self.obj.contact_list(): bodies.update({contact.body0, contact.body1}) bodies -= set(self.obj.link_prim_paths) rigid_prims = set() for body in bodies: tokens = body.split("/") obj_prim_path = "/".join(tokens[:-1]) link_name = tokens[-1] obj = og.sim.scene.object_registry("prim_path", obj_prim_path) if obj is not None: rigid_prims.add(obj.links[link_name]) # Ignore_objs should either be None or tuple (CANNOT be list because we need to hash these inputs) assert ignore_objs is None or isinstance(ignore_objs, tuple), \ "ignore_objs must either be None or a tuple of objects to ignore!" return rigid_prims if ignore_objs is None else rigid_prims - prims_to_rigid_prim_set(ignore_objs)
1,196
Python
45.03846
106
0.648829
StanfordVL/OmniGibson/omnigibson/object_states/aabb.py
from omnigibson.object_states.object_state_base import AbsoluteObjectState class AABB(AbsoluteObjectState): def _get_value(self): return self.obj.aabb # Nothing needs to be done to save/load AABB since it will happen due to pose caching.
257
Python
27.666664
90
0.750973
StanfordVL/OmniGibson/omnigibson/object_states/saturated.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import RelativeObjectState, BooleanStateMixin from omnigibson.systems.system_base import UUID_TO_SYSTEMS, REGISTERED_SYSTEMS from omnigibson.utils.python_utils import get_uuid # Create settings for this module m = create_module_macros(module_path=__file__) # Default saturation limit m.DEFAULT_SATURATION_LIMIT = 1e6 class ModifiedParticles(RelativeObjectState): """ Object state tracking number of modified particles for a given object """ def __init__(self, obj): # Run super first super().__init__(obj=obj) # Set internal values self.particle_counts = None def _initialize(self): super()._initialize() # Set internal variables self.particle_counts = dict() def _get_value(self, system): # If system isn't stored, return 0, otherwise, return the actual value return self.particle_counts.get(system, 0) def _set_value(self, system, new_value): assert new_value >= 0, "Cannot set ModifiedParticles value to be less than 0!" # Remove the value from the dictionary if we're setting it to zero (save memory) if new_value == 0 and system in self.particle_counts: self.particle_counts.pop(system) else: self.particle_counts[system] = new_value def _sync_systems(self, systems): """ Helper function for forcing internal systems to be synchronized with external list of @systems. NOTE: This may override internal state Args: systems (list of BaseSystem): List of system(s) that should be actively tracked internally """ self.particle_counts = {system: -1 for system in systems} @property def state_size(self): # Two entries per system (name + count) + number of systems return len(self.particle_counts) * 2 + 1 def _dump_state(self): state = dict(n_systems=len(self.particle_counts)) for system, val in self.particle_counts.items(): state[system.name] = val return state def _load_state(self, state): self.particle_counts = {REGISTERED_SYSTEMS[system_name]: val for system_name, val in state.items() if system_name != "n_systems" and val > 0} def _serialize(self, state): state_flat = np.array([state["n_systems"]], dtype=float) if state["n_systems"] > 0: system_names = tuple(state.keys())[1:] state_flat = np.concatenate( [state_flat, np.concatenate([(get_uuid(system_name), state[system_name]) for system_name in system_names])] ).astype(float) return state_flat def _deserialize(self, state): n_systems = int(state[0]) state_shaped = state[1:1 + n_systems * 2].reshape(-1, 2) state_dict = dict(n_systems=n_systems) systems = [] for uuid, val in state_shaped: system = UUID_TO_SYSTEMS[int(uuid)] state_dict[system.name] = int(val) systems.append(system) # Sync systems so that state size sanity check succeeds self._sync_systems(systems=systems) return state_dict, n_systems * 2 + 1 class Saturated(RelativeObjectState, BooleanStateMixin): def __init__(self, obj, default_limit=m.DEFAULT_SATURATION_LIMIT): # Run super first super().__init__(obj=obj) # Limits self._default_limit = default_limit self._limits = None def _initialize(self): super()._initialize() # Set internal variables self._limits = dict() @property def limits(self): """ Returns: dict: Maps system to limit count for that system, if it exists """ return self._limits def get_limit(self, system): """ Grabs the internal particle limit for @system Args: system (BaseSystem): System to limit Returns: init: Number of particles representing limit for the given @system """ return self._limits.get(system, self._default_limit) def set_limit(self, system, limit): """ Sets internal particle limit @limit for @system Args: system (BaseSystem): System to limit limit (int): Number of particles representing limit for the given @system """ self._limits[system] = limit def _get_value(self, system): limit = self.get_limit(system=system) # If requested, run sanity check to make sure we're not over the limit with this system's particles count = self.obj.states[ModifiedParticles].get_value(system) assert count <= limit, f"{self.__class__.__name__} should not be over the limit! Max: {limit}, got: {count}" return count == limit def _set_value(self, system, new_value): # Only set the value if it's different than what currently exists if new_value != self.get_value(system): self.obj.states[ModifiedParticles].set_value(system, self.get_limit(system=system) if new_value else 0) return True def get_texture_change_params(self): colors = [] for system in self._limits.keys(): if self.get_value(system): colors.append(system.color) if len(colors) == 0: # If no fluid system has Soaked=True, keep the default albedo value albedo_add = 0.0 diffuse_tint = [1.0, 1.0, 1.0] else: albedo_add = 0.1 avg_color = np.mean(colors, axis=0) # Add a tint of avg_color # We want diffuse_tint to sum to 2.5 to result in the final RGB to sum to 1.5 on average # This is because an average RGB color sum to 1.5 (i.e. [0.5, 0.5, 0.5]) # (0.5 [original avg RGB per channel] + 0.1 [albedo_add]) * 2.5 = 1.5 diffuse_tint = np.array([0.5, 0.5, 0.5]) + avg_color / np.sum(avg_color) diffuse_tint = diffuse_tint.tolist() return albedo_add, diffuse_tint @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(ModifiedParticles) return deps def _sync_systems(self, systems): """ Helper function for forcing internal systems to be synchronized with external list of @systems. NOTE: This may override internal state Args: systems (list of BaseSystem): List of system(s) that should be actively tracked internally """ self._limits = {system: m.DEFAULT_SATURATION_LIMIT for system in systems} @property def state_size(self): # Limit per entry * 2 (UUID, value) + default limit + n limits return len(self._limits) * 2 + 2 def _dump_state(self): state = dict(n_systems=len(self._limits), default_limit=self._default_limit) for system, limit in self._limits.items(): state[system.name] = limit return state def _load_state(self, state): self._limits = dict() for k, v in state.items(): if k == "n_systems": continue elif k == "default_limit": self._default_limit = v # TODO: Make this an else once fresh round of sampling occurs (i.e.: no more outdated systems stored) elif k in REGISTERED_SYSTEMS: self._limits[REGISTERED_SYSTEMS[k]] = v def _serialize(self, state): state_flat = np.array([state["n_systems"], state["default_limit"]], dtype=float) if state["n_systems"] > 0: system_names = tuple(state.keys())[2:] state_flat = np.concatenate( [state_flat, np.concatenate([(get_uuid(system_name), state[system_name]) for system_name in system_names])] ).astype(float) return state_flat def _deserialize(self, state): n_systems = int(state[0]) state_dict = dict(n_systems=n_systems, default_limit=int(state[1])) state_shaped = state[2:2 + n_systems * 2].reshape(-1, 2) systems = [] for uuid, val in state_shaped: system = UUID_TO_SYSTEMS[int(uuid)] state_dict[system.name] = int(val) systems.append(system) # Sync systems so that state size sanity check succeeds self._sync_systems(systems=systems) return state_dict, 2 + n_systems * 2
8,582
Python
34.614108
149
0.60289
StanfordVL/OmniGibson/omnigibson/object_states/link_based_state_mixin.py
import numpy as np from omnigibson.object_states.object_state_base import BaseObjectState from omnigibson.utils.ui_utils import create_module_logger from omnigibson.utils.python_utils import classproperty from omnigibson.prims.cloth_prim import ClothPrim # Create module logger log = create_module_logger(module_name=__name__) class LinkBasedStateMixin(BaseObjectState): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._links = dict() @classmethod def is_compatible(cls, obj, **kwargs): # Run super first compatible, reason = super().is_compatible(obj, **kwargs) if not compatible: return compatible, reason # Check whether this state requires metalink if not cls.requires_metalink(**kwargs): return True, None metalink_prefix = cls.metalink_prefix for link in obj.links.values(): if metalink_prefix in link.name: return True, None return False, f"LinkBasedStateMixin {cls.__name__} requires metalink with prefix {cls.metalink_prefix} " \ f"for obj {obj.name} but none was found! To get valid compatible object models, please use " \ f"omnigibson.utils.asset_utils.get_all_object_category_models_with_abilities(...)" @classmethod def is_compatible_asset(cls, prim, **kwargs): # Run super first compatible, reason = super().is_compatible_asset(prim, **kwargs) if not compatible: return compatible, reason # Check whether this state requires metalink if not cls.requires_metalink(**kwargs): return True, None metalink_prefix = cls.metalink_prefix for child in prim.GetChildren(): if child.GetTypeName() == "Xform": if metalink_prefix in child.GetName(): return True, None return False, f"LinkBasedStateMixin {cls.__name__} requires metalink with prefix {cls.metalink_prefix} " \ f"for asset prim {prim.GetName()} but none was found! To get valid compatible object models, " \ f"please use omnigibson.utils.asset_utils.get_all_object_category_models_with_abilities(...)" @classproperty def metalink_prefix(cls): """ Returns: str: Unique keyword that defines the metalink associated with this object state """ NotImplementedError() @classmethod def requires_metalink(cls, **kwargs): """ Returns: Whether an object state instantiated with constructor arguments **kwargs will require a metalink or not """ # True by default return True @property def link(self): """ Returns: None or RigidPrim: The link associated with this link-based state, if it exists """ assert self.links, f"LinkBasedStateMixin link not found for {self.obj.name}" return next(iter(self.links.values())) @property def links(self): """ Returns: dict: mapping from link names to links that match the metalink_prefix """ return self._links @property def _default_link(self): """ Returns: None or RigidPrim: If supported, the fallback link associated with this link-based state if no valid metalink is found """ # No default link by default return None def initialize_link_mixin(self): assert not self._initialized # TODO: Extend logic to account for multiple instances of the same metalink? e.g: _0, _1, ... suffixes for name, link in self.obj.links.items(): if self.metalink_prefix in name or (self._default_link is not None and link.name == self._default_link.name): self._links[name] = link # Make sure the scale is similar if the link is not a cloth prim if not isinstance(link, ClothPrim): assert np.allclose(link.scale, self.obj.scale), \ f"the meta link {name} has a inconsistent scale with the object {self.obj.name}" @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("LinkBasedStateMixin") return classes
4,501
Python
36.831932
121
0.614752
StanfordVL/OmniGibson/omnigibson/object_states/pose.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import AbsoluteObjectState # Create settings for this module m = create_module_macros(module_path=__file__) m.POSITIONAL_VALIDATION_EPSILON = 1e-10 m.ORIENTATION_VALIDATION_EPSILON = 0.003 # ~5 degrees error tolerance class Pose(AbsoluteObjectState): def _get_value(self): pos = self.obj.get_position() orn = self.obj.get_orientation() return np.array(pos), np.array(orn) def _has_changed(self, get_value_args, value, info): # Only changed if the squared distance between old position and current position has # changed above some threshold old_pos, old_quat = value # Get current pose current_pos, current_quat = self.get_value() # Check position and orientation -- either changing means we've changed poses dist_squared = np.sum(np.square(current_pos - old_pos)) if dist_squared > m.POSITIONAL_VALIDATION_EPSILON: return True # Calculate quat distance simply as the dot product # A * B = |A||B|cos(theta) quat_cos_angle = np.abs(np.dot(old_quat, current_quat)) if (1 - quat_cos_angle) > m.ORIENTATION_VALIDATION_EPSILON: return True return False
1,341
Python
35.270269
92
0.668158
StanfordVL/OmniGibson/omnigibson/object_states/covered.py
from omnigibson.macros import create_module_macros from omnigibson.object_states import AABB from omnigibson.object_states.object_state_base import RelativeObjectState, BooleanStateMixin from omnigibson.object_states.contact_particles import ContactParticles from omnigibson.systems.system_base import VisualParticleSystem, is_visual_particle_system, is_physical_particle_system from omnigibson.utils.constants import PrimType # Create settings for this module m = create_module_macros(module_path=__file__) # Number of visual particles needed in order for Covered --> True m.VISUAL_PARTICLE_THRESHOLD = 1 # Maximum number of visual particles to sample when setting an object to be covered = True m.MAX_VISUAL_PARTICLES = 20 # Number of physical particles needed in order for Covered --> True m.PHYSICAL_PARTICLE_THRESHOLD = 1 # Maximum number of physical particles to sample when setting an object to be covered = True m.MAX_PHYSICAL_PARTICLES = 5000 class Covered(RelativeObjectState, BooleanStateMixin): def __init__(self, obj): # Run super first super().__init__(obj) # Set internal values self._visual_particle_group = None @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.update({AABB, ContactParticles}) return deps def remove(self): if self._initialized: self._clear_attachment_groups() def _clear_attachment_groups(self): """ Utility function to destroy all corresponding attachment groups for this object """ for system in VisualParticleSystem.get_active_systems().values(): if self._visual_particle_group in system.groups: system.remove_attachment_group(self._visual_particle_group) def _initialize(self): super()._initialize() # Grab group name self._visual_particle_group = VisualParticleSystem.get_group_name(obj=self.obj) def _get_value(self, system): # Value is false by default value = False # First, we check what type of system # Currently, we support VisualParticleSystems and PhysicalParticleSystems if system.n_particles > 0: if is_visual_particle_system(system_name=system.name): if self._visual_particle_group in system.groups: # check whether the current number of particles assigned to the group is greater than the threshold value = system.num_group_particles(group=self._visual_particle_group) >= m.VISUAL_PARTICLE_THRESHOLD elif is_physical_particle_system(system_name=system.name): # Make sure we're not cloth -- not supported yet assert self.obj.prim_type != PrimType.CLOTH, \ "Cloth objects currently cannot be Covered by physical particles!" # We've already cached particle contacts, so we merely search through them to see if any particles are # touching the object and are visible (the non-visible ones are considered already "removed") n_near_particles = len(self.obj.states[ContactParticles].get_value(system)) # Heuristic: If the number of near particles is above the threshold, we consdier this covered value = n_near_particles >= m.PHYSICAL_PARTICLE_THRESHOLD else: raise ValueError(f"Invalid system {system} received for getting Covered state!" f"Currently, only VisualParticleSystems and PhysicalParticleSystems are supported.") return value def _set_value(self, system, new_value): # Default success value is True success = True # First, we check what type of system # Currently, we support VisualParticleSystems and PhysicalParticleSystems if is_visual_particle_system(system_name=system.name): # Create the group if it doesn't exist already if self._visual_particle_group not in system.groups: system.create_attachment_group(obj=self.obj) # Check current state and only do something if we're changing state if self.get_value(system) != new_value: if new_value: # Generate particles success = system.generate_group_particles_on_object( group=self._visual_particle_group, max_samples=m.MAX_VISUAL_PARTICLES, min_samples_for_success=m.VISUAL_PARTICLE_THRESHOLD, ) else: # We remove all of this group's particles system.remove_all_group_particles(group=self._visual_particle_group) elif is_physical_particle_system(system_name=system.name): # Make sure we're not cloth -- not supported yet assert self.obj.prim_type != PrimType.CLOTH, \ "Cloth objects currently cannot be Covered by physical particles!" # Check current state and only do something if we're changing state if self.get_value(system) != new_value: if new_value: # Sample particles on top of the object success = system.generate_particles_on_object( obj=self.obj, max_samples=m.MAX_PHYSICAL_PARTICLES, min_samples_for_success=m.PHYSICAL_PARTICLE_THRESHOLD, ) else: # We remove all particles touching this object system.remove_particles(idxs=list(self.obj.states[ContactParticles].get_value(system))) else: raise ValueError(f"Invalid system {system} received for setting Covered state!" f"Currently, only VisualParticleSystems and PhysicalParticleSystems are supported.") return success
5,994
Python
46.579365
120
0.639139
StanfordVL/OmniGibson/omnigibson/object_states/max_temperature.py
from omnigibson.object_states.temperature import Temperature from omnigibson.object_states.tensorized_value_state import TensorizedValueState import numpy as np from omnigibson.utils.python_utils import classproperty class MaxTemperature(TensorizedValueState): """ This state remembers the highest temperature reached by an object. """ # np.ndarray: Array of Temperature.VALUE indices that correspond to the internally tracked MaxTemperature objects TEMPERATURE_IDXS = None @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(Temperature) return deps @classmethod def global_initialize(cls): # Call super first super().global_initialize() # Initialize other global variables cls.TEMPERATURE_IDXS = np.array([], dtype=int) # Add global callback to Temperature state so that temperature idxs will be updated def _update_temperature_idxs(obj): # Decrement all remaining temperature idxs -- they're strictly increasing so we can simply # subtract 1 from all downstream indices deleted_idx = Temperature.OBJ_IDXS[obj.name] cls.TEMPERATURE_IDXS = np.where(cls.TEMPERATURE_IDXS >= deleted_idx, cls.TEMPERATURE_IDXS - 1, cls.TEMPERATURE_IDXS) Temperature.add_callback_on_remove(name="MaxTemperature_temperature_idx_update", callback=_update_temperature_idxs) @classmethod def global_clear(cls): # Call super first super().global_clear() # Clear other internal state cls.TEMPERATURE_IDXS = None @classmethod def _add_obj(cls, obj): # Call super first super()._add_obj(obj=obj) # Add to temperature index cls.TEMPERATURE_IDXS = np.concatenate([cls.TEMPERATURE_IDXS, [Temperature.OBJ_IDXS[obj.name]]]) @classmethod def _remove_obj(cls, obj): # Grab idx we'll delete before the object is deleted deleted_idx = cls.OBJ_IDXS[obj.name] # Remove from temperature index cls.TEMPERATURE_IDXS = np.delete(cls.TEMPERATURE_IDXS, [deleted_idx]) # Decrement all remaining temperature idxs -- they're strictly increasing so we can simply # subtract 1 from all downstream indices if deleted_idx < len(cls.TEMPERATURE_IDXS): cls.TEMPERATURE_IDXS[deleted_idx:] -= 1 # Call super super()._remove_obj(obj=obj) @classmethod def _update_values(cls, values): # Value is max between stored values and current temperature values return np.maximum(values, Temperature.VALUES[cls.TEMPERATURE_IDXS]) @classproperty def value_name(cls): return "max_temperature" def __init__(self, obj): super(MaxTemperature, self).__init__(obj) # Set value to be default self._set_value(-np.inf)
2,897
Python
33.5
128
0.670694
StanfordVL/OmniGibson/omnigibson/object_states/next_to.py
import numpy as np from omnigibson.object_states.aabb import AABB from omnigibson.object_states.adjacency import HorizontalAdjacency, flatten_planes from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState class NextTo(KinematicsMixin, RelativeObjectState, BooleanStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(HorizontalAdjacency) return deps def _get_value(self, other): objA_states = self.obj.states objB_states = other.states assert AABB in objA_states assert AABB in objB_states objA_aabb = objA_states[AABB].get_value() objB_aabb = objB_states[AABB].get_value() objA_lower, objA_upper = objA_aabb objB_lower, objB_upper = objB_aabb distance_vec = [] for dim in range(3): glb = max(objA_lower[dim], objB_lower[dim]) lub = min(objA_upper[dim], objB_upper[dim]) distance_vec.append(max(0, glb - lub)) distance = np.linalg.norm(np.array(distance_vec)) objA_dims = objA_upper - objA_lower objB_dims = objB_upper - objB_lower avg_aabb_length = np.mean(objA_dims + objB_dims) # If the distance is longer than acceptable, return False. if distance > avg_aabb_length * (1.0 / 6.0): return False # Otherwise, check if the other object shows up in the adjacency list. adjacency_this = self.obj.states[HorizontalAdjacency].get_value() in_any_horizontal_adjacency_of_this = any( ( other in adjacency_list.positive_neighbors or other in adjacency_list.negative_neighbors ) for adjacency_list in flatten_planes(adjacency_this) ) if in_any_horizontal_adjacency_of_this: return True # If not, check in the adjacency lists of `other`. Maybe it's shorter than us etc. adjacency_other = other.states[HorizontalAdjacency].get_value() in_any_horizontal_adjacency_of_other = any( ( self.obj in adjacency_list.positive_neighbors or self.obj in adjacency_list.negative_neighbors ) for adjacency_list in flatten_planes(adjacency_other) ) return in_any_horizontal_adjacency_of_other
2,470
Python
36.439393
93
0.639271
StanfordVL/OmniGibson/omnigibson/object_states/folded.py
import numpy as np from collections import namedtuple from scipy.spatial import ConvexHull, distance_matrix, QhullError from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import BooleanStateMixin, AbsoluteObjectState from omnigibson.object_states.cloth_mixin import ClothStateMixin # Create settings for this module m = create_module_macros(module_path=__file__) # Criterion #1: the threshold on the area ratio of the convex hull of the projection on the XY plane m.FOLDED_AREA_THRESHOLD = 0.75 m.UNFOLDED_AREA_THRESHOLD = 0.9 # Criterion #2: the threshold on the diagonal ratio of the convex hull of the projection on the XY plane m.FOLDED_DIAGONAL_THRESHOLD = 0.85 m.UNFOLDED_DIAGONAL_THRESHOLD = 0.9 # Criterion #3: the percentage of face normals that need to be close to the z-axis m.NORMAL_Z_PERCENTAGE = 0.5 # Whether to visualize the convex hull of the projection on the XY plane m.DEBUG_CLOTH_PROJ_VIS = False # Angle threshold for checking smoothness of the cloth; surface normals need to be close enough to the z-axis m.NORMAL_Z_ANGLE_DIFF = np.deg2rad(45.0) """ FoldedLevelData contains the following fields: smoothness (float): percentage of surface normals that are sufficiently close to the z-axis area (float): the area of the convex hull of the projected points compared to the initial unfolded state diagonal (float): the diagonal of the convex hull of the projected points compared to the initial unfolded state """ FoldedLevelData = namedtuple("FoldedLevelData", ("smoothness", "area", "diagonal")) class FoldedLevel(AbsoluteObjectState, ClothStateMixin): """ State representing the object's folded level. Value is a FoldedLevelData object. """ def _initialize(self): super()._initialize() # Assume the initial state is unfolded self.area_unfolded, self.diagonal_unfolded = self.calculate_projection_area_and_diagonal_maximum() def _get_value(self): smoothness = self.calculate_smoothness() area, diagonal = self.calculate_projection_area_and_diagonal([0, 1]) return FoldedLevelData(smoothness, area / self.area_unfolded, diagonal / self.diagonal_unfolded) def calculate_smoothness(self): """ Calculate the percantage of surface normals that are sufficiently close to the z-axis. """ cloth = self.obj.root_link normals = cloth.compute_face_normals(face_ids=cloth.keyface_idx) # projection onto the z-axis proj = np.abs(np.dot(normals, np.array([0.0, 0.0, 1.0]))) percentage = np.mean(proj > np.cos(m.NORMAL_Z_ANGLE_DIFF)) return percentage def calculate_projection_area_and_diagonal_maximum(self): """ Calculate the maximum projection area and the diagonal length along different axes Returns: area_max (float): area of the convex hull of the projected points diagonal_max (float): diagonal of the convex hull of the projected points """ # use the largest projection area as the unfolded area area_max = 0.0 diagonal_max = 0.0 dims_list = [[0, 1], [0, 2], [1, 2]] # x-y plane, x-z plane, y-z plane for dims in dims_list: area, diagonal = self.calculate_projection_area_and_diagonal(dims) if area > area_max: area_max = area diagonal_max = diagonal return area_max, diagonal_max def calculate_projection_area_and_diagonal(self, dims): """ Calculate the projection area and the diagonal length when projecting to the plane defined by the input dims E.g. if dims is [0, 1], the points will be projected onto the x-y plane. Args: dims (2-array): Global axes to project area onto. Options are {0, 1, 2}. E.g. if dims is [0, 1], project onto the x-y plane. Returns: area (float): area of the convex hull of the projected points diagonal (float): diagonal of the convex hull of the projected points """ cloth = self.obj.root_link points = cloth.keypoint_particle_positions[:, dims] try: hull = ConvexHull(points) # The points may be 2D-degenerate, so catch the error and return 0 if so except QhullError: # This is a degenerate hull, so return 0 area and diagonal return 0.0, 0.0 # When input points are 2-dimensional, this is the area of the convex hull. # Ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html area = hull.volume diagonal = distance_matrix(points[hull.vertices], points[hull.vertices]).max() if m.DEBUG_CLOTH_PROJ_VIS: import matplotlib.pyplot as plt ax = plt.gca() ax.set_aspect('equal') plt.plot(points[:, dims[0]], points[:, dims[1]], 'o') for simplex in hull.simplices: plt.plot(points[simplex, dims[0]], points[simplex, dims[1]], 'k-') plt.plot(points[hull.vertices, dims[0]], points[hull.vertices, dims[1]], 'r--', lw=2) plt.plot(points[hull.vertices[0], dims[0]], points[hull.vertices[0], dims[1]], 'ro') plt.show() return area, diagonal class Folded(AbsoluteObjectState, BooleanStateMixin, ClothStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(FoldedLevel) return deps def _get_value(self): # Check the smoothness of the cloth folded_level = self.obj.states[FoldedLevel].get_value() return folded_level.smoothness >= m.NORMAL_Z_PERCENTAGE and \ folded_level.area < m.FOLDED_AREA_THRESHOLD and \ folded_level.diagonal < m.FOLDED_DIAGONAL_THRESHOLD def _set_value(self, new_value): if not new_value: raise NotImplementedError("Folded does not support set_value(False)") # TODO (eric): add this support raise NotImplementedError("Folded does not support set_value(True)") # We don't need to dump / load anything since the cloth objects should handle it themselves class Unfolded(AbsoluteObjectState, BooleanStateMixin, ClothStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(FoldedLevel) return deps def _get_value(self): # Check the smoothness of the cloth folded_level = self.obj.states[FoldedLevel].get_value() return folded_level.smoothness >= m.NORMAL_Z_PERCENTAGE and \ folded_level.area >= m.UNFOLDED_AREA_THRESHOLD and \ folded_level.diagonal >= m.UNFOLDED_DIAGONAL_THRESHOLD def _set_value(self, new_value): if not new_value: raise NotImplementedError("Unfolded does not support set_value(False)") self.obj.root_link.reset() return True # We don't need to dump / load anything since the cloth objects should handle it themselves
7,106
Python
39.380682
116
0.663805
StanfordVL/OmniGibson/omnigibson/object_states/toggle.py
import numpy as np import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import create_module_macros from omnigibson.prims.geom_prim import VisualGeomPrim from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin from omnigibson.object_states.update_state_mixin import UpdateStateMixin, GlobalUpdateStateMixin from omnigibson.utils.python_utils import classproperty from omnigibson.utils.usd_utils import create_primitive_mesh, RigidContactAPI from omnigibson.utils.constants import PrimType # Create settings for this module m = create_module_macros(module_path=__file__) m.TOGGLE_LINK_PREFIX = "togglebutton" m.DEFAULT_SCALE = 0.1 m.CAN_TOGGLE_STEPS = 5 class ToggledOn(AbsoluteObjectState, BooleanStateMixin, LinkBasedStateMixin, UpdateStateMixin, GlobalUpdateStateMixin): # Set of prim paths defining robot finger links belonging to any manipulation robots _robot_finger_paths = None # Set of objects that are contacting any manipulation robots _finger_contact_objs = None def __init__(self, obj, scale=None): self.scale = scale self.value = False self.robot_can_toggle_steps = 0 self.visual_marker = None # We also generate the function for checking overlaps at runtime self._check_overlap = None super().__init__(obj) @classmethod def global_update(cls): # Avoid circular imports from omnigibson.robots.manipulation_robot import ManipulationRobot # Clear finger contact objects since it will be refreshed now cls._finger_contact_objs = set() # detect marker and hand interaction robot_finger_links = set(link for robot in og.sim.scene.robots if isinstance(robot, ManipulationRobot) for finger_links in robot.finger_links.values() for link in finger_links) cls._robot_finger_paths = set(link.prim_path for link in robot_finger_links) # If there aren't any valid robot link paths, immediately return if len(cls._robot_finger_paths) == 0: return finger_idxs = [RigidContactAPI.get_body_col_idx(prim_path) for prim_path in cls._robot_finger_paths] finger_impulses = RigidContactAPI.get_all_impulses()[:, finger_idxs, :] n_bodies = len(finger_impulses) touching_bodies = np.any(finger_impulses.reshape(n_bodies, -1), axis=-1) touching_bodies_idxs = np.where(touching_bodies)[0] if len(touching_bodies_idxs) > 0: for idx in touching_bodies_idxs: body_prim_path = RigidContactAPI.get_row_idx_prim_path(idx=idx) obj = og.sim.scene.object_registry("prim_path", "/".join(body_prim_path.split("/")[:-1])) if obj is not None: cls._finger_contact_objs.add(obj) @classproperty def metalink_prefix(cls): return m.TOGGLE_LINK_PREFIX def _get_value(self): return self.value def _set_value(self, new_value): self.value = new_value # Choose which color to apply to the toggle marker self.visual_marker.color = np.array([0, 1.0, 0]) if self.value else np.array([1.0, 0, 0]) return True def _initialize(self): super()._initialize() self.initialize_link_mixin() # Make sure this object is not cloth assert self.obj.prim_type != PrimType.CLOTH, f"Cannot create ToggledOn state for cloth object {self.obj.name}!" mesh_prim_path = f"{self.link.prim_path}/mesh_0" pre_existing_mesh = lazy.omni.isaac.core.utils.prims.get_prim_at_path(mesh_prim_path) # Create a primitive mesh if it doesn't already exist if not pre_existing_mesh: self.scale = m.DEFAULT_SCALE if self.scale is None else self.scale # Note: We have to create a mesh (instead of a sphere shape) because physx complains about non-uniform # scaling for non-meshes mesh = create_primitive_mesh( prim_path=mesh_prim_path, primitive_type="Sphere", extents=1.0, ) else: # Infer radius from mesh if not specified as an input lazy.omni.isaac.core.utils.bounds.recompute_extents(prim=pre_existing_mesh) self.scale = np.array(pre_existing_mesh.GetAttribute("xformOp:scale").Get()) # Create the visual geom instance referencing the generated mesh prim self.visual_marker = VisualGeomPrim(prim_path=mesh_prim_path, name=f"{self.obj.name}_visual_marker") self.visual_marker.scale = self.scale self.visual_marker.initialize() self.visual_marker.visible = True # Store the projection mesh's IDs projection_mesh_ids = lazy.pxr.PhysicsSchemaTools.encodeSdfPath(self.visual_marker.prim_path) # Define function for checking overlap valid_hit = False def overlap_callback(hit): nonlocal valid_hit valid_hit = hit.rigid_body in self._robot_finger_paths # Continue traversal only if we don't have a valid hit yet return not valid_hit # Set this value to be False by default self._set_value(False) def check_overlap(): nonlocal valid_hit valid_hit = False if self.visual_marker.prim.GetTypeName() == "Mesh": og.sim.psqi.overlap_mesh(*projection_mesh_ids, reportFn=overlap_callback) else: og.sim.psqi.overlap_shape(*projection_mesh_ids, reportFn=overlap_callback) return valid_hit self._check_overlap = check_overlap def _update(self): # If we're not nearby any fingers, we automatically can't toggle if self.obj not in self._finger_contact_objs: robot_can_toggle = False else: # Check to make sure fingers are actually overlapping the toggle button mesh robot_can_toggle = self._check_overlap() if robot_can_toggle: self.robot_can_toggle_steps += 1 else: self.robot_can_toggle_steps = 0 if self.robot_can_toggle_steps == m.CAN_TOGGLE_STEPS: self.set_value(not self.value) @staticmethod def get_texture_change_params(): # By default, it keeps the original albedo unchanged. albedo_add = 0.0 diffuse_tint = (1.0, 1.0, 1.0) return albedo_add, diffuse_tint @property def state_size(self): return 2 # For this state, we simply store its value and the robot_can_toggle steps. def _dump_state(self): return dict(value=self.value, hand_in_marker_steps=self.robot_can_toggle_steps) def _load_state(self, state): # Nothing special to do here when initialized vs. uninitialized self._set_value(state["value"]) self.robot_can_toggle_steps = state["hand_in_marker_steps"] def _serialize(self, state): return np.array([state["value"], state["hand_in_marker_steps"]], dtype=float) def _deserialize(self, state): return dict(value=bool(state[0]), hand_in_marker_steps=int(state[1])), 2
7,349
Python
38.72973
119
0.647027
StanfordVL/OmniGibson/omnigibson/object_states/joint_break_subscribed_state_mixin.py
from omnigibson.object_states.object_state_base import BaseObjectState from abc import abstractmethod from omnigibson.utils.python_utils import classproperty class JointBreakSubscribedStateMixin(BaseObjectState): """ Handles JOINT_BREAK event. The subclass should implement its own on_joint_break method """ @abstractmethod def on_joint_break(self, joint_prim_path): raise NotImplementedError("Subclasses of JointBreakSubscribedStateMixin should implement the on_joint_break method.") @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("JointBreakSubscribedStateMixin") return classes
775
Python
34.272726
125
0.747097
StanfordVL/OmniGibson/omnigibson/object_states/particle_modifier.py
from abc import abstractmethod from collections import defaultdict import numpy as np import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import create_module_macros, macros, gm from omnigibson.prims.geom_prim import VisualGeomPrim from omnigibson.object_states.aabb import AABB from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.object_states.contact_particles import ContactParticles from omnigibson.object_states.covered import Covered from omnigibson.object_states.link_based_state_mixin import LinkBasedStateMixin from omnigibson.object_states.object_state_base import IntrinsicObjectState from omnigibson.object_states.saturated import ModifiedParticles, Saturated from omnigibson.object_states.toggle import ToggledOn from omnigibson.object_states.update_state_mixin import UpdateStateMixin from omnigibson.prims.prim_base import BasePrim from omnigibson.systems.system_base import BaseSystem, VisualParticleSystem, PhysicalParticleSystem, get_system, \ is_visual_particle_system, is_physical_particle_system, is_fluid_system, is_system_active, REGISTERED_SYSTEMS from omnigibson.utils.constants import ParticleModifyMethod, ParticleModifyCondition, PrimType from omnigibson.utils.geometry_utils import generate_points_in_volume_checker_function, \ get_particle_positions_in_frame, get_particle_positions_from_frame from omnigibson.utils.python_utils import classproperty from omnigibson.utils.ui_utils import suppress_omni_log from omnigibson.utils.usd_utils import create_primitive_mesh, FlatcacheAPI import omnigibson.utils.transform_utils as T from omnigibson.utils.sampling_utils import sample_cuboid_on_object # Create settings for this module m = create_module_macros(module_path=__file__) m.APPLICATION_LINK_PREFIX = "particleapplier" m.REMOVAL_LINK_PREFIX = "particleremover" # How many samples within the application area to generate per update step m.MAX_VISUAL_PARTICLES_APPLIED_PER_STEP = 2 m.MAX_PHYSICAL_PARTICLES_APPLIED_PER_STEP = 10 # How many steps between generating particle samples m.N_STEPS_PER_APPLICATION = 5 m.N_STEPS_PER_REMOVAL = 1 # Application thresholds -- maximum number of particles that can be applied by a ParticleApplier m.VISUAL_PARTICLES_APPLICATION_LIMIT = 1000000 m.PHYSICAL_PARTICLES_APPLICATION_LIMIT = 1000000 # Saturation thresholds -- maximum number of particles that can be removed ("absorbed") by a ParticleRemover m.VISUAL_PARTICLES_REMOVAL_LIMIT = 40 m.PHYSICAL_PARTICLES_REMOVAL_LIMIT = 400 # Fallback particle visualization radius for visualizing projected visual particles m.VISUAL_PARTICLE_PROJECTION_PARTICLE_RADIUS = 0.01 # The margin (> 0) to add to the remover area's AABB when detecting overlaps with other objects m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN = 0.05 # Settings for determining how the projection particles are visualized as they're projected m.PROJECTION_VISUALIZATION_CONE_TIP_RADIUS = 0.001 m.PROJECTION_VISUALIZATION_RATE = 200 m.PROJECTION_VISUALIZATION_SPEED = 2.0 m.PROJECTION_VISUALIZATION_ORIENTATION_BIAS = 1e6 m.PROJECTION_VISUALIZATION_SPREAD_FACTOR = 0.8 def create_projection_visualization( prim_path, shape, projection_name, projection_radius, projection_height, particle_radius, parent_scale, material=None, ): """ Helper function to generate a projection visualization using Omniverse's particle visualization system Args: prim_path (str): Stage location for where to generate the projection visualization shape (str): Shape of the projection to generate. Valid options are: {Sphere, Cone} projection_name (str): Name associated with this projection visualization. Should be unique! projection_radius (float): Radius of the generated projection visualization overall volume (specified in local frame) projection_height (float): Height of the generated projection visualization overall volume (specified in local frame) particle_radius (float): Radius of the particles composing the projection visualization parent_scale (3-array): If specified, specifies the (x,y,z) scale of the parent Xform prim of the generated source sphere prim at @prim_path. This will be used to scale the visualization accordingly material (None or MaterialPrim): If specified, specifies the material to associate with the generated particles within the projection visualization Returns: 2-tuple: - UsdPrim: Generated ParticleSystem (ComputeGraph) prim generated - UsdPrim: Generated Emitter (ComputeGraph) prim generated """ # Create the desired shape which will be used as the source input prim into the generated projection visualization source = lazy.pxr.UsdGeom.Sphere.Define(og.sim.stage, lazy.pxr.Sdf.Path(prim_path)) # Modify the radius according to the desired @shape (and also infer the desired spread values) if shape == "Cylinder": source_radius = projection_radius spread = np.zeros(3) elif shape == "Cone": # Default to close to singular point otherwise source_radius = m.PROJECTION_VISUALIZATION_CONE_TIP_RADIUS spread_ratio = projection_radius * 2.0 / projection_height spread = np.ones(3) * spread_ratio * m.PROJECTION_VISUALIZATION_SPREAD_FACTOR else: raise ValueError(f"Invalid shape specified for projection visualization! Valid options are: [Cone, Cylinder], got: {shape}") # Set the radius source.GetRadiusAttr().Set(source_radius) # Also make the prim invisible lazy.pxr.UsdGeom.Imageable(source.GetPrim()).MakeInvisible() # Generate the ComputeGraph nodes to render the projection # Import now to avoid too-eager load of Omni classes due to inheritance from omnigibson.utils.deprecated_utils import Core core = Core(lambda val: None, particle_system_name=projection_name) # Scale radius and height by the parent scale -- projection always points in the negative-z direction of the # parent frame # We do this AFTER we create the source sphere because the actual projection is scaled in the world frame, whereas # the source sphere is already scaled by its own parent frame # NOTE: The generated projection visualization will NOT match the underlying projection mesh if the parent link is # scaled non-uniformly!! projection_radius *= np.mean(parent_scale[:2]) projection_height *= parent_scale[2] # Suppress omni warnings here -- we don't have control over this API, but omni likes to complain about this with suppress_omni_log(channels=["omni.graph.core.plugin", "omni.usd", "rtx.neuraylib.plugin"]): system_path, _, emitter_path, vis_path, instancer_path, sprite_path, mat_path, output_path = \ core.create_particle_system(display="point_instancer", paths=[prim_path]) # Override the prototype with our own sphere with optional material prototype_path = "/".join(sprite_path.split("/")[:-1]) + "/prototype" create_primitive_mesh(prototype_path, primitive_type="Sphere") prototype = VisualGeomPrim(prim_path=prototype_path, name=f"{projection_name}_prototype") prototype.initialize() # Set the scale (native scaling --> radius 0.5) and possibly update the material prototype.scale = particle_radius * 2.0 if material is not None: prototype.material = material # Override the prototype used by the instancer instancer_prim = lazy.omni.isaac.core.utils.prims.get_prim_at_path(instancer_path) instancer_prim.GetProperty("inputs:prototypes").SetTargets([prototype_path]) # Destroy the old mat path since we don't use the sprites lazy.omni.isaac.core.utils.prims.delete_prim(mat_path) # Modify the settings of the emitter to match the desired shape from inputs emitter_prim = lazy.omni.isaac.core.utils.prims.get_prim_at_path(emitter_path) emitter_prim.GetProperty("inputs:active").Set(True) emitter_prim.GetProperty("inputs:rate").Set(m.PROJECTION_VISUALIZATION_RATE) emitter_prim.GetProperty("inputs:lifespan").Set(projection_height / m.PROJECTION_VISUALIZATION_SPEED) emitter_prim.GetProperty("inputs:speed").Set(m.PROJECTION_VISUALIZATION_SPEED) emitter_prim.GetProperty("inputs:alongAxis").Set(m.PROJECTION_VISUALIZATION_ORIENTATION_BIAS) emitter_prim.GetProperty("inputs:scale").Set(lazy.pxr.Gf.Vec3f(1.0, 1.0, 1.0)) emitter_prim.GetProperty("inputs:directionRandom").Set(lazy.pxr.Gf.Vec3f(*spread)) emitter_prim.GetProperty("inputs:addSourceVelocity").Set(1.0) # Make sure we render 4 times to fully propagate changes (validated empirically) # Omni likes to complain here again, but we have no control over the low-level information, so we suppress warnings with suppress_omni_log(channels=["omni.particle.system.core.plugin", "omni.hydra.scene_delegate.plugin", "omni.usd"]): for i in range(4): og.sim.render() # Return the particle system prim which "owns" everything return lazy.omni.isaac.core.utils.prims.get_prim_at_path(system_path), emitter_prim class ParticleModifier(IntrinsicObjectState, LinkBasedStateMixin, UpdateStateMixin): """ Object state representing an object that has the ability to modify visual and / or physical particles within the active simulation. Args: obj (StatefulObject): Object to which this state will be applied conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of (ParticleModifyCondition, value) necessary in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the form above -- if all of its conditions evaluate to True and particles are detected within this particle modifier area, then we potentially modify those particles method (ParticleModifyMethod): Method to modify particles. Current options supported are ADJACENCY (i.e.: "touching" particles) or PROJECTION (i.e.: "spraying" particles) projection_mesh_params (None or dict): If specified and @method is ParticleModifyMethod.PROJECTION, manually overrides any data inferred directly from this object to infer what projection volume to generate for this particle modifier. Expected entries are as follows: "type": (str), one of {"Cylinder", "Cone", "Cube", "Sphere"} "extents": (3-array), the (x,y,z) extents of the generated volume (specified in local link frame!) If None, information found from @obj.metadata will be used instead. NOTE: x-direction should align with the projection mesh's height (i.e.: z) parameter in @extents! """ def __init__(self, obj, conditions, method=ParticleModifyMethod.ADJACENCY, projection_mesh_params=None): # Store internal variables self.method = method self.projection_source_sphere = None self.projection_mesh = None self._check_in_mesh = None self._check_overlap = None self._link_prim_paths = None self._current_step = None self._projection_mesh_params = projection_mesh_params # Parse conditions self._conditions = self._parse_conditions(conditions=conditions) # Run super method super().__init__(obj) @property def conditions(self): """ dict: Dictionary mapping the names of ParticleSystem (str) to a list of function calls that must evaluate to True in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. The list of functions at least contains the limit condition, which is a function that checks whether the applier has applied or the remover has removed the maximum number of particles allowed. If the systen name is not in the dictionary, then the modifier cannot modify particles of that system. """ return self._conditions @classmethod def is_compatible(cls, obj, **kwargs): # Run super first compatible, reason = super().is_compatible(obj, **kwargs) if not compatible: return compatible, reason # Check whether this state has toggledon if required or saturated if required for any condition conditions = kwargs.get("conditions", dict()) cond_types = {cond[0] for _, conds in conditions.items() if conds is not None for cond in conds} for cond_type, state_type in zip((ParticleModifyCondition.TOGGLEDON,), (ToggledOn,)): if cond_type in cond_types and state_type not in obj.states: return False, f"{cls.__name__} requires {state_type.__name__} state!" return True, None @classmethod def is_compatible_asset(cls, prim, **kwargs): # Run super first compatible, reason = super().is_compatible_asset(prim, **kwargs) if not compatible: return compatible, reason # Check whether this state has toggledon if required or saturated if required for any condition conditions = kwargs.get("conditions", dict()) cond_types = {cond[0] for _, conds in conditions.items() if conds is not None for cond in conds} for cond_type, state_type in zip((ParticleModifyCondition.TOGGLEDON,), (ToggledOn,)): if cond_type in cond_types and not state_type.is_compatible_asset(prim=prim, **kwargs): return False, f"{cls.__name__} requires {state_type.__name__} state!" return True, None @classmethod def postprocess_ability_params(cls, params): """ Post-processes ability parameters to ensure the system names (rather than synsets) are used for conditions. """ # Import here to avoid circular imports from omnigibson.utils.bddl_utils import get_system_name_by_synset for sys in list(params["conditions"].keys()): # The original key can be either a system name or a system synset. If it's a synset, we need to convert it. system_name = sys if sys in REGISTERED_SYSTEMS.keys() else get_system_name_by_synset(sys) params["conditions"][system_name] = params["conditions"].pop(sys) conds = params["conditions"][system_name] if conds is None: continue for cond in conds: cond_type, cond_sys = cond if cond_type == ParticleModifyCondition.SATURATED: cond[1] = cond_sys if cond_sys in REGISTERED_SYSTEMS.keys() else get_system_name_by_synset(cond_sys) return params def _initialize(self): super()._initialize() # Run link initialization self.initialize_link_mixin() # Sanity check scale if requested if self.requires_overlap: # Run sanity check to make sure compatibility with omniverse physx if self.method == ParticleModifyMethod.PROJECTION and not np.isclose(self.obj.scale.max(), self.obj.scale.min(), atol=1e-04): raise ValueError(f"{self.__class__.__name__} for obj {self.obj.name} using PROJECTION method cannot be " f"created with non-uniform scale and requires_overlap! Got scale: {self.obj.scale}") # Initialize internal variables self._current_step = 0 # Grab link prim paths and potentially update projection mesh params self._link_prim_paths = set(self.obj.link_prim_paths) # Define callback used during overlap method # We want to ignore any hits that are with this object itself valid_hit = False def overlap_callback(hit): nonlocal valid_hit valid_hit = hit.rigid_body not in self._link_prim_paths # Continue traversal only if we don't have a valid hit yet return not valid_hit # Possibly create a projection volume if we're using the projection method if self.method == ParticleModifyMethod.PROJECTION: # Construct naming prefix to apply to generated prims name_prefix = f"{self.obj.name}_{self.__class__.__name__}" shape_defaults = { "radius": 0.5, "height": 1.0, "size": 1.0, } mesh_prim_path = f"{self.link.prim_path}/mesh_0" # Create a primitive shape if it doesn't already exist pre_existing_mesh = lazy.omni.isaac.core.utils.prims.get_prim_at_path(mesh_prim_path) if not pre_existing_mesh: # Projection mesh params must be specified in order to determine scalings assert self._projection_mesh_params is not None, \ f"Must specify projection_mesh_params for {self.obj.name}'s {self.__class__.__name__} " \ f"since it has no pre-existing projection mesh!" mesh = getattr(lazy.pxr.UsdGeom, self._projection_mesh_params["type"]).Define(og.sim.stage, mesh_prim_path).GetPrim() property_names = set(mesh.GetPropertyNames()) for shape_attr, default_val in shape_defaults.items(): if shape_attr in property_names: mesh.GetAttribute(shape_attr).Set(default_val) else: # Potentially populate projection mesh params if the prim exists mesh_type = pre_existing_mesh.GetTypeName() if self._projection_mesh_params is None: self._projection_mesh_params = { "type": mesh_type, "extents": np.array(pre_existing_mesh.GetAttribute("xformOp:scale").Get()), } # Otherwise, make sure we don't have a mismatch between the pre-existing shape type and the # desired type since we can't delete the original mesh else: assert self._projection_mesh_params["type"] == mesh_type, \ f"Got mismatch in requested projection mesh type ({self._projection_mesh_params['type']}) and " \ f"pre-existing mesh type ({mesh_type})" # Create the visual geom instance referencing the generated mesh prim, and then hide it self.projection_mesh = VisualGeomPrim(prim_path=mesh_prim_path, name=f"{name_prefix}_projection_mesh") self.projection_mesh.initialize() self.projection_mesh.visible = False # Make sure the shape-based attributes are not set, and only the scaling is set property_names = set(self.projection_mesh.prim.GetPropertyNames()) for shape_attr, default_val in shape_defaults.items(): if shape_attr in property_names: val = self.projection_mesh.get_attribute(shape_attr) assert val == default_val, \ f"Projection mesh should have shape-based attribute {shape_attr} == {default_val}! Got: {val}" # Set the scale based on projection mesh params self.projection_mesh.scale = np.array(self._projection_mesh_params["extents"]) # Make sure the object updates its meshes, and assert that there's only a single visual mesh self.link.update_meshes() assert len(self.link.visual_meshes) == 1, \ f"Expected only a single projection mesh for {self.link}, got: {len(self.link.visual_meshes)}" # Make sure the mesh is translated so that its tip lies at the metalink origin, and rotated so the vector # from tip to tail faces the positive x axis z_offset = 0.0 if self._projection_mesh_params["type"] == "Sphere" else self._projection_mesh_params["extents"][2] / 2 self.projection_mesh.set_local_pose( position=np.array([0, 0, -z_offset]), orientation=T.euler2quat([0, 0, 0]), ) # Generate the function for checking whether points are within the projection mesh self._check_in_mesh, _ = generate_points_in_volume_checker_function(obj=self.obj, volume_link=self.link) # Store the projection mesh's IDs projection_mesh_ids = lazy.pxr.PhysicsSchemaTools.encodeSdfPath(self.projection_mesh.prim_path) # We also generate the function for checking overlaps at runtime def check_overlap(): nonlocal valid_hit valid_hit = False og.sim.psqi.overlap_shape(*projection_mesh_ids, reportFn=overlap_callback) return valid_hit elif self.method == ParticleModifyMethod.ADJACENCY: # Define the function for checking whether points are within the adjacency mesh def check_in_adjacency_mesh(particle_positions): # Define the AABB bounds lower, upper = self.link.visual_aabb # Add the margin lower -= m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN upper += m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN return ((lower < particle_positions) & (particle_positions < upper)).all(axis=-1) self._check_in_mesh = check_in_adjacency_mesh # Define the function for checking overlaps at runtime def check_overlap(): nonlocal valid_hit valid_hit = False aabb = self.link.visual_aabb og.sim.psqi.overlap_box( halfExtent=(aabb[1] - aabb[0]) / 2.0 + m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN, pos=(aabb[1] + aabb[0]) / 2.0, rot=np.array([0, 0, 0, 1.0]), reportFn=overlap_callback, ) return valid_hit else: raise ValueError(f"Unsupported ParticleModifyMethod: {self.method}!") # Store check overlap function self._check_overlap = check_overlap # We abuse the Saturated state to store the limit for particle modifier (including both applier and remover) for system_name in self.conditions.keys(): system = get_system(system_name, force_active=False) limit = self.visual_particle_modification_limit \ if is_visual_particle_system(system_name=system.name) \ else self.physical_particle_modification_limit self.obj.states[Saturated].set_limit(system=system, limit=limit) def _generate_condition(self, condition_type, value): """ Generates a valid condition function given @condition_type and its corresponding @value Args: condition_type (ParticleModifyCondition): Type of condition to generate value (any): Corresponding value whose type depends on @condition_type: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. Returns: function: Condition function whose signature is identical to FUNCTION listed above """ # Avoid circular imports from omnigibson.object_states.saturated import Saturated if condition_type == ParticleModifyCondition.FUNCTION: cond = value elif condition_type == ParticleModifyCondition.SATURATED: cond = lambda obj: is_system_active(value) and obj.states[Saturated].get_value(get_system(value)) elif condition_type == ParticleModifyCondition.TOGGLEDON: cond = lambda obj: obj.states[ToggledOn].get_value() == value elif condition_type == ParticleModifyCondition.GRAVITY: # Particles spawn in negative z-axis direction, so check positive dot product of link frame with global cond = lambda obj: (np.dot(T.quat2mat(obj.states[self.__class__].link.get_orientation()) @ np.array([0, 0, 1]), np.array([0, 0, 1])) > 0) == value else: raise ValueError(f"Got invalid ParticleModifyCondition: {condition_type}") return cond def _parse_conditions(self, conditions): """ Parse conditions and store them internally Args: conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of (ParticleModifyCondition, value) necessary in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the form above -- if all of its conditions evaluate to True and particles are detected within this particle modifier area, then we potentially modify those particles Returns: dict: Dictionary mapping the names of ParticleSystem (str) to list of condition functions """ parsed_conditions = dict() # Standardize the conditions (make sure every system has at least one condition, which to make sure # the particle modifier isn't already limited with the specific number of particles) for system_name, conds in conditions.items(): # Make sure the system is supported assert is_visual_particle_system(system_name) or is_physical_particle_system(system_name), \ f"Unsupported system for ParticleModifier: {system_name}" # Make sure conds isn't empty and is a list if conds is None: continue assert type(conds) == list, f"Expected list of conditions for system {system_name}, got {conds}" system_conditions = [] for cond_type, cond_val in conds: cond = self._generate_condition(condition_type=cond_type, value=cond_val) system_conditions.append(cond) # Always add limit condition at the end system_conditions.append(self._generate_limit_condition(system_name)) parsed_conditions[system_name] = system_conditions return parsed_conditions @abstractmethod def _modify_particles(self, system): """ Helper function to modify any particles belonging to @system. NOTE: This should handle both cases for @self.method: ParticleModifyMethod.ADJACENCY: modify any particles that are overlapping within the relaxed AABB defining adjacency to this object's modification link. ParticleModifyMethod.PROJECTION: modify any particles that are overlapping within the projection mesh. Must be implemented by subclass. Args: system (BaseSystem): Particle system whose corresponding particles will be checked for modification """ raise NotImplementedError() def _generate_limit_condition(self, system_name): """ Generates a limit function condition for specific system of name @system_name Args: system_name (str): Name of the particle system for which to generate a limit checker function Returns: function: Limit checker function, with signature condition(obj) --> bool, where @obj is the specific object that this ParticleModifier state belongs to """ system = get_system(system_name, force_active=False) def condition(obj): return not self.obj.states[Saturated].get_value(system=system) return condition def supports_system(self, system_name): """ Checks whether this particle modifier supports adding/removing a particle from the specified system, e.g. whether there exists any configuration (toggled on, etc.) in which this modifier can be used to interact with any particles of this system. Args: system_name (str): Name of the particle system to check Returns: bool: Whether this particle modifier can add or remove a particle from the specified system """ return system_name in self.conditions def check_conditions_for_system(self, system_name): """ Checks whether this particle modifier can add or remove a particle from the specified system in its current configuration, e.g. all of the conditions for addition/removal other than physical position are met. Args: system_name (str): Name of the particle system to check Returns: bool: Whether this particle modifier can add or remove a particle from the specified system """ if not self.supports_system(system_name): return False return all(condition(self.obj) for condition in self.conditions[system_name]) def _update(self): # If we're using projection method and flatcache, we need to manually update this object's transforms on the USD # so the corresponding visualization and overlap meshes are updated properly # This is expensive, so only do it if the object is not a fixed object and we have an active projection if ( self.method == ParticleModifyMethod.PROJECTION and gm.ENABLE_FLATCACHE and not self.obj.fixed_base and self.projection_is_active ): FlatcacheAPI.sync_raw_object_transforms_in_usd(prim=self.obj) # Check if there's any overlap and if we're at the correct step if self._current_step == 0: # Iterate over all systems to check for system_name in self.systems_to_check: if system_name in self.conditions: # Check if all conditions are met if self.check_conditions_for_system(system_name): system = get_system(system_name) # Sanity check to see if the modifier has reached its limit for this system if self.obj.states[Saturated].get_value(system=system): continue # Potentially modify particles within the volume self._modify_particles(system=system) # Update the current step self._current_step = (self._current_step + 1) % self.n_steps_per_modification @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.update({AABB, Saturated, ModifiedParticles}) return deps @classmethod def get_optional_dependencies(cls): deps = super().get_optional_dependencies() deps.update({Covered, ToggledOn, ContactBodies, ContactParticles}) return deps @classproperty def requires_overlap(self): """ Returns: bool: Whether overlap checks should be executed as a guard condition against modifying particles """ raise NotImplementedError() @classproperty def supported_active_systems(cls): """ Returns: dict: Maps system names to corresponding systems used in this state that are active, dynamic across time """ return dict(**VisualParticleSystem.get_active_systems(), **PhysicalParticleSystem.get_active_systems()) @property def systems_to_check(self): """ Returns: tuple of str: System names that should be actively checked for particle modification at the current timestep """ # Default is all supported active systems return tuple(self.supported_active_systems.keys()) @property def projection_is_active(self): """ Returns: bool: If using ParticleModifyMethod.PROJECTION, should return whether the projection mesh is currently active or not (e.g.: whether all conditions are met for a projection modification to potentially occur) """ # Return True by default return True @property def n_steps_per_modification(self): """ Returns: int: How many steps to take in between potentially modifying particles within the simulation """ raise NotImplementedError() @property def visual_particle_modification_limit(self): """ Returns: int: Maximum number of visual particles from a specific system that can be modified by this object """ raise NotImplementedError() @property def physical_particle_modification_limit(self): """ Returns: int: Maximum number of physical particles from a specific system that can be modified by this object """ raise NotImplementedError() @property def state_size(self): # Only store the current_step return 1 def _dump_state(self): return dict(current_step=int(self._current_step)) def _load_state(self, state): self._current_step = state["current_step"] def _serialize(self, state): return np.array([state["current_step"]], dtype=float) def _deserialize(self, state): current_step = int(state[0]) state_dict = dict(current_step=current_step) return state_dict, 1 @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("ParticleModifier") return classes class ParticleRemover(ParticleModifier): """ ParticleModifier where the modification results in potentially removing particles from the simulation. Args: obj (StatefulObject): Object to which this state will be applied conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of (ParticleModifyCondition, value) necessary in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the form above -- if all of its conditions evaluate to True and particles are detected within this particle modifier area, then we potentially modify those particles method (ParticleModifyMethod): Method to modify particles. Current options supported are ADJACENCY (i.e.: "touching" particles) or PROJECTION (i.e.: "spraying" particles) projection_mesh_params (None or dict): If specified and @method is ParticleModifyMethod.PROJECTION, manually overrides any data inferred directly from this object to infer what projection volume to generate for this particle modifier. Expected entries are as follows: "type": (str), one of {"Cylinder", "Cone", "Cube", "Sphere"} "extents": (3-array), the (x,y,z) extents of the generated volume (specified in local link frame!) If None, information found from @obj.metadata will be used instead. NOTE: x-direction should align with the projection mesh's height (i.e.: z) parameter in @extents! default_fluid_conditions (None or list): Condition(s) needed to remove any fluid particles not explicitly specified in @conditions. If None, then it is assumed that no other physical particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) 2-tuples default_non_fluid_conditions (None or list): Condition(s) needed to remove any physical (excluding fluid) particles not explicitly specified in @conditions. If None, then it is assumed that no other physical particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) 2-tuples default_visual_conditions (None or list): Condition(s) needed to remove any visual particles not explicitly specified in @conditions. If None, then it is assumed that no other visual particles can be removed. If not None, should be in same format as an entry in @conditions, i.e.: list of (ParticleModifyCondition, val) 2-tuples """ def __init__( self, obj, conditions, method=ParticleModifyMethod.ADJACENCY, projection_mesh_params=None, default_fluid_conditions=None, default_non_fluid_conditions=None, default_visual_conditions=None, ): # Store values self._default_fluid_conditions = default_fluid_conditions if default_fluid_conditions is None else \ [self._generate_condition(cond_type, cond_val) for cond_type, cond_val in default_fluid_conditions] self._default_non_fluid_conditions = default_non_fluid_conditions if default_non_fluid_conditions is None else \ [self._generate_condition(cond_type, cond_val) for cond_type, cond_val in default_non_fluid_conditions] self._default_visual_conditions = default_visual_conditions if default_visual_conditions is None else \ [self._generate_condition(cond_type, cond_val) for cond_type, cond_val in default_visual_conditions] # Run super super().__init__(obj=obj, conditions=conditions, method=method, projection_mesh_params=projection_mesh_params) def _parse_conditions(self, conditions): # Run super first parsed_conditions = super()._parse_conditions(conditions=conditions) # Create set of default system to condition mappings based on settings all_conditions = dict() for system_name in REGISTERED_SYSTEMS.keys(): # If the system is already explicitly specified in conditions, continue if system_name in conditions: continue # Since fluid system is a subclass of physical system, we need to check for fluid first elif is_fluid_system(system_name): default_system_conditions = self._default_fluid_conditions elif is_physical_particle_system(system_name): default_system_conditions = self._default_non_fluid_conditions elif is_visual_particle_system(system_name): default_system_conditions = self._default_visual_conditions else: # Don't process any other systems, continue continue if default_system_conditions is not None: # Always make sure to add on condition for checking count of particles (can't remove any particles if # there are 0 particles of the given system!) all_conditions[system_name] = ( [self._generate_nonempty_system_condition(system_name), self._generate_limit_condition(system_name)] + default_system_conditions ) # Overwrite conditions based on manually-specified ones all_conditions.update(parsed_conditions) return all_conditions def _modify_particles(self, system): # If the system has no particles, return if system.n_particles == 0: return # Check the system if is_visual_particle_system(system_name=system.name): # Iterate over all particles and remove any that are within the relaxed AABB of the remover volume particle_positions = system.get_particles_position_orientation()[0] inbound_idxs = self._check_in_mesh(particle_positions).nonzero()[0] modification_limit = self.visual_particle_modification_limit # Physical system else: # If the object is a cloth, we have to use check_in_mesh with the relaxed AABB since we can't detect # collisions via scene query interface. Alternatively, if we're using the projection method, # we also need to use check_in_mesh to check for overlap with the projection mesh. inbound_idxs = self._check_in_mesh(system.get_particles_position_orientation()[0]).nonzero()[0] \ if self.obj.prim_type == PrimType.CLOTH or self.method == ParticleModifyMethod.PROJECTION else \ np.array(list(self.obj.states[ContactParticles].get_value(system, self.link))) modification_limit = self.physical_particle_modification_limit n_modified_particles = self.obj.states[ModifiedParticles].get_value(system) n_particles_absorbed = min(len(inbound_idxs), modification_limit - n_modified_particles) system.remove_particles(inbound_idxs[:n_particles_absorbed]) self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + n_particles_absorbed) def _generate_nonempty_system_condition(self, system_name): """ Internal helper function to programatically generate a condition checker to make sure that at least one particle exists in a given system Args: system_name (str): Name of the system Returns: function: Generated condition function with signature fcn(obj) --> bool, returning True if there is at least one particle in the given system @system_name """ system = get_system(system_name, force_active=False) return lambda obj: system.initialized and system.n_particles > 0 @property def requires_overlap(self): # No overlap check needed for particle removers return False @classproperty def metalink_prefix(cls): return m.REMOVAL_LINK_PREFIX @classmethod def requires_metalink(cls, **kwargs): # No metalink required for adjacency return kwargs.get("method", ParticleModifyMethod.ADJACENCY) != ParticleModifyMethod.ADJACENCY @property def _default_link(self): # Only supported for adjacency, NOT projection return self.obj.root_link if self.method == ParticleModifyMethod.ADJACENCY else None @property def n_steps_per_modification(self): return m.N_STEPS_PER_REMOVAL @property def visual_particle_modification_limit(self): return m.VISUAL_PARTICLES_REMOVAL_LIMIT @property def physical_particle_modification_limit(self): return m.PHYSICAL_PARTICLES_REMOVAL_LIMIT class ParticleApplier(ParticleModifier): """ ParticleModifier where the modification results in potentially adding particles into the simulation. Args: obj (StatefulObject): Object to which this state will be applied conditions (dict): Dictionary mapping the names of ParticleSystem (str) to None or list of 2-tuples, where None represents "never", empty list represents "always", or each 2-tuple is interpreted as a single condition in the form of (ParticleModifyCondition, value) necessary in order for this particle modifier to be able to modify particles belonging to @ParticleSystem. Expected types of val are as follows: SATURATED: string name of the desired system that this modifier must be saturated by, e.g., "water" TOGGLEDON: boolean T/F; whether this modifier must be toggled on or not GRAVITY: boolean T/F; whether this modifier must be pointing downwards (T) or upwards (F) FUNCTION: a function, whose signature is as follows: def condition(obj) --> bool Where @obj is the specific object that this ParticleModifier state belongs to. For a given ParticleSystem, the list of 2-tuples will be converted into a list of function calls of the form above -- if all of its conditions evaluate to True and particles are detected within this particle modifier area, then we potentially modify those particles method (ParticleModifyMethod): Method to modify particles. Current options supported are ADJACENCY (i.e.: "touching" particles) or PROJECTION (i.e.: "spraying" particles) projection_mesh_params (None or dict): If specified and @method is ParticleModifyMethod.PROJECTION, manually overrides any data inferred directly from this object to infer what projection volume to generate for this particle modifier. Expected entries are as follows: "type": (str), one of {"Cylinder", "Cone", "Cube", "Sphere"} "extents": (3-array), the (x,y,z) extents of the generated volume (specified in local link frame!) If None, information found from @obj.metadata will be used instead. sample_with_raycast (bool): If True, will only sample particles at raycast hits. Otherwise, will bypass sampling and immediately sample particles at the sampled particle locations. Note that this will only work for PhysicalParticleSystem-based ParticleAppliers that use the Projection method! initial_speed (float): For physical particles, the initial speed for generated particles. Note that the direction of the velocity is inferred from the particle sampling process. """ def __init__( self, obj, conditions, method=ParticleModifyMethod.ADJACENCY, projection_mesh_params=None, sample_with_raycast=True, initial_speed=0.0, ): # Store internal value self._sample_particle_locations = None self._sample_with_raycast = sample_with_raycast self._initial_speed = initial_speed # Pre-cached values for where particles should be spawned, and in what direction, when this state is # initialized so we can quickly spawn them at runtime self._in_mesh_local_particle_positions = None self._in_mesh_local_particle_directions = None self.projection_system = None self.projection_system_prim = None self.projection_emitter = None # Run super super().__init__(obj=obj, method=method, conditions=conditions, projection_mesh_params=projection_mesh_params) def _initialize(self): # Run super super()._initialize() system_name = list(self.conditions.keys())[0] # get_system will initialize the system if it's not initialized already. system = get_system(system_name) if self.visualize: assert self._projection_mesh_params["type"] in {"Cylinder", "Cone"}, \ f"{self.__class__.__name__} visualization only supports Cylinder and Cone types!" radius, height = np.mean(self._projection_mesh_params["extents"][:2]) / 2.0, self._projection_mesh_params["extents"][2] # Generate the projection visualization particle_radius = m.VISUAL_PARTICLE_PROJECTION_PARTICLE_RADIUS if \ is_visual_particle_system(system_name=system.name) else system.particle_radius name_prefix = f"{self.obj.name}_{self.__class__.__name__}" # Create the projection visualization if it doesn't already exist, otherwise we reference it directly projection_name = f"{name_prefix}_projection_visualization" projection_path = f"/OmniGraph/{projection_name}" projection_visualization_path = f"{self.link.prim_path}/projection_visualization" if lazy.omni.isaac.core.utils.prims.is_prim_path_valid(projection_path): self.projection_system = lazy.omni.isaac.core.utils.prims.get_prim_at_path(projection_path) self.projection_emitter = lazy.omni.isaac.core.utils.prims.get_prim_at_path(f"{projection_path}/emitter") else: self.projection_system, self.projection_emitter = create_projection_visualization( prim_path=projection_visualization_path, shape=self._projection_mesh_params["type"], projection_name=projection_name, projection_radius=radius, projection_height=height, particle_radius=particle_radius, parent_scale=self.link.scale, material=system.material, ) self.projection_system_prim = BasePrim(prim_path=self.projection_system.GetPrimPath().pathString, name=projection_name) # Create the visual geom instance referencing the generated source mesh prim, and then hide it self.projection_source_sphere = VisualGeomPrim(prim_path=projection_visualization_path, name=f"{name_prefix}_projection_source_sphere") self.projection_source_sphere.initialize() self.projection_source_sphere.visible = False # Rotate by 90 degrees in y-axis so that the projection visualization aligns with the projection mesh self.projection_source_sphere.set_local_pose(orientation=T.euler2quat([0, np.pi / 2, 0])) # Make sure the meta mesh is aligned with the meta link if visualizing # This corresponds to checking (a) position of tip of projection mesh should align with origin of # metalink, and (b) zero relative orientation between the metalink and the projection mesh local_pos, local_quat = self.projection_mesh.get_local_pose() assert np.all(np.isclose(local_pos + np.array([0, 0, height / 2.0]), 0.0)), \ "Projection mesh tip should align with metalink position!" assert np.all(np.isclose(T.quat2euler(local_quat), 0.0)), \ "Projection mesh orientation should align with metalink orientation!" # Store which method to use for sampling particle locations if self._sample_with_raycast: if self.method == ParticleModifyMethod.PROJECTION: self._sample_particle_locations = self._sample_particle_locations_from_projection_volume elif self.method == ParticleModifyMethod.ADJACENCY: self._sample_particle_locations = self._sample_particle_locations_from_adjacency_area else: raise ValueError(f"Unsupported ParticleModifyMethod: {self.method}!") else: # Make sure we're only using a physical particle system and the projection method assert issubclass(system, PhysicalParticleSystem), \ "If not sampling with raycast, ParticleApplier only supports PhysicalParticleSystems!" assert self.method == ParticleModifyMethod.PROJECTION, \ "If not sampling with raycast, ParticleApplier only supports ParticleModifyMethod.PROJECTION method!" # Compute particle spawning information once self._compute_particle_spawn_information(system=system) def _parse_conditions(self, conditions): # Run super first parsed_conditions = super()._parse_conditions(conditions=conditions) # sanity check to make sure only one system is being applied, since unlike a ParticleRemover, which # can potentially remove multiple types of particles, a ParticleApplier should only apply one type of particle assert len(parsed_conditions) == 1, f"A ParticleApplier can only have a single ParticleSystem associated " \ f"with it! Got: {[system_name for system_name in self.conditions.keys()]}" # Append an additional condition for checking overlaps if required if self.requires_overlap: system_name = next(iter(parsed_conditions)) parsed_conditions[system_name].append(lambda obj: self._check_overlap()) return parsed_conditions def _compute_particle_spawn_information(self, system): """ Helper function to compute where particles should be spawned. This is to save computation time at runtime if @self._sample_with_raycast is False, meaning that we were deterministically sample particles. Args: system (BaseSystem): Particle system whose particles will be spawned from this ParticleApplier """ # We now pre-compute local particle positions that are within the projection mesh used to infer spawn pos # We sample over the entire object AABB, assuming most will be filtered out sampling_distance = 2 * system.particle_radius extent = np.array(self._projection_mesh_params["extents"]) h = extent[2] low, high = self.obj.aabb n_particles_per_axis = ((high - low) / sampling_distance).astype(int) assert np.all(n_particles_per_axis), f"link {self.link.name} is too small to sample any particle of radius {system.particle_radius}." # 1e-10 is added because the extent might be an exact multiple of particle radius arrs = [np.arange(l + system.particle_radius, h - system.particle_radius + 1e-10, system.particle_radius * 2) for l, h, n in zip(low, high, n_particles_per_axis)] # Generate 3D-rectangular grid of points, and only keep the ones inside the mesh points = np.stack([arr.flatten() for arr in np.meshgrid(*arrs)]).T pos, quat = self.link.get_position_orientation() points = points[np.where(self._check_in_mesh(points))[0]] # Convert the points into local frame points_in_local_frame = get_particle_positions_in_frame( pos=pos, quat=quat, scale=self.obj.scale, particle_positions=points, ) n_max_particles = self._get_max_particles_limit_per_step(system=system) # Potentially sub-sample points based on max particle limit per step self._in_mesh_local_particle_positions = points_in_local_frame if n_max_particles > len(points) else \ points_in_local_frame[np.random.choice(len(points_in_local_frame), n_max_particles, replace=False)] # Also programmatically compute the directions of each particle position -- this is the normalized # vector pointing from source to the particle projection_type = self._projection_mesh_params["type"] if projection_type == "Cone": # Particles point from source ([0, 0, 0]) to point location directions = np.copy(self._in_mesh_local_particle_positions) elif projection_type == "Cylinder": # All particle points in the same parallel direction towards the -z direction directions = np.zeros_like(self._in_mesh_local_particle_positions) directions[:, 2] = -h else: raise ValueError( "If not sampling with raycast, ParticleApplier only supports `Cone` or `Cylinder` projection types!") self._in_mesh_local_particle_directions = directions / np.linalg.norm(directions, axis=-1).reshape(-1, 1) def _update(self): # If we're about to check for modification, update whether it the visualization should be active or not if self.visualize and self._current_step == 0: # Only one system in our conditions, so next(iter()) suffices # is_active = bool(np.all([condition(self.obj) for condition in next(iter(self.conditions.values()))])) is_active = all(condition(self.obj) for condition in next(iter(self.conditions.values()))) self.projection_emitter.GetProperty("inputs:active").Set(is_active) # Run super super()._update() def remove(self): # We need to remove the projection visualization if it exists if self.projection_system_prim is not None: og.sim.remove_prim(self.projection_system_prim) def _modify_particles(self, system): if self._sample_with_raycast: # Sample potential locations to apply particles, and then apply them start_points, end_points = self._sample_particle_locations(system=system) n_samples = len(start_points) is_visual = is_visual_particle_system(system_name=system.name) if is_visual: group = system.get_group_name(obj=self.obj) # Create an attachment group if necessary if group not in system.groups: system.create_attachment_group(obj=self.obj) avg_scale = np.cbrt(np.product(self.obj.scale)) scales = system.sample_scales_by_group(group=group, n=len(start_points)) cuboid_dimensions = scales * system.particle_object.aabb_extent.reshape(1, 3) * avg_scale else: scales = None cuboid_dimensions = np.zeros(3) # Sample the rays to see where particle can be generated results = sample_cuboid_on_object( obj=None, start_points=start_points.reshape(n_samples, 1, 3), end_points=end_points.reshape(n_samples, 1, 3), cuboid_dimensions=cuboid_dimensions, ignore_objs=[self.obj], hit_proportion=0.0, # We want all hits cuboid_bottom_padding=macros.utils.sampling_utils.DEFAULT_CUBOID_BOTTOM_PADDING if is_visual else system.particle_radius, undo_cuboid_bottom_padding=is_visual, # micro particles have zero cuboid dimensions so we need to maintain padding verify_cuboid_empty=False, ) hits = [result for result in results if result[0] is not None] scales = [scale for scale, result in zip(scales, results) if result[0] is not None] if scales is not None else scales self._apply_particles_at_raycast_hits(system=system, hits=hits, scales=scales) else: self._apply_particles_in_projection_volume(system=system) def _apply_particles_at_raycast_hits(self, system, hits, scales=None): """ Helper function to apply particles from system @system given raycast hits @hits, which are the filtered results from omnigibson.utils.sampling_utils.raytest_batch that include only the results with a valid hit Args: system (BaseSystem): System to apply particles from hits (list of dict): Valid hit results from a batched raycast representing locations for sampling particles scales (list of numpy arrays or None): None or scales of the particles that should be sampled, same length as hits """ assert system.name in self.conditions, f"System {system.name} is not defined in the conditions." # Check the system n_modified_particles = self.obj.states[ModifiedParticles].get_value(system) if is_visual_particle_system(system_name=system.name): assert scales is not None, "applying visual particles at raycast hits requires scales." assert len(hits) == len(scales), "length of hits and scales are different when spawning visual particles." # Sample potential application points z_up = np.zeros(3) z_up[-1] = 1.0 n_particles = min(len(hits), m.VISUAL_PARTICLES_APPLICATION_LIMIT - n_modified_particles) # Generate particle info -- maps group name to particle info for that group, # i.e.: positions, orientations, and link_prim_paths particles_info = defaultdict(lambda: defaultdict(lambda: [])) modifier_avg_scale = np.cbrt(np.product(self.obj.scale)) for hit, scale in zip(hits[:n_particles], scales[:n_particles]): # Infer which object was hit hit_obj = og.sim.scene.object_registry("prim_path", "/".join(hit[3].split("/")[:-1]), None) if hit_obj is not None: # Create an attachment group if necessary group = system.get_group_name(obj=hit_obj) if group not in system.groups: system.create_attachment_group(obj=hit_obj) # Add to info particles_info[group]["positions"].append(hit[0]) particles_info[group]["orientations"].append(hit[2]) # Since particles' scales are sampled with respect to the modifier object, but are being placed # (in the USD hierarchy) underneath the in_contact object, we need to compensate for the relative # scale differences between the two objects, so that "moving" the particle to the new object won't # cause it to unexpectedly shrink / grow based on that parent's (potentially) different scale particles_info[group]["scales"].append(scale * modifier_avg_scale / np.cbrt(np.product(hit_obj.scale))) particles_info[group]["link_prim_paths"].append(hit[3]) # Generate all the particles for each group for group, particle_info in particles_info.items(): # Generate particles for this group system.generate_group_particles( group=group, positions=np.array(particle_info["positions"]), orientations=np.array(particle_info["orientations"]), scales=np.array(particles_info[group]["scales"]), link_prim_paths=particle_info["link_prim_paths"], ) # Update our particle count self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + len(particle_info["link_prim_paths"])) # Physical system else: # Compile the particle poses to generate and sample the particles n_particles = min(len(hits), m.PHYSICAL_PARTICLES_APPLICATION_LIMIT - n_modified_particles) # Generate particles if n_particles > 0: velocities = None if self._initial_speed == 0 else -self._initial_speed * np.array([hit[1] for hit in hits[:n_particles]]) system.generate_particles( positions=np.array([hit[0] for hit in hits[:n_particles]]), velocities=velocities, ) # Update our particle count self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + n_particles) def _apply_particles_in_projection_volume(self, system): """ Helper function to apply particles form system @system within the projection volume owned by this ParticleApplier. NOTE: This function only supports PhysicalParticleSystems and ParticleModifyMethod.PROJECTION method, which should have been asserted during this ParticleApplier's initialize() call Args: system (BaseSystem): System to apply particles from """ assert self.method == ParticleModifyMethod.PROJECTION, \ "Can only apply particles within projection volume if ParticleModifyMethod.PROJECTION method is used!" assert is_physical_particle_system(system_name=system.name), \ "Can only apply particles within projection volume if system is PhysicalParticleSystem!" # Transform pre-cached particle positions into the world frame pos, quat = self.link.get_position_orientation() points = get_particle_positions_from_frame( pos=pos, quat=quat, scale=self.obj.scale, particle_positions=self._in_mesh_local_particle_positions, ) directions = self._in_mesh_local_particle_directions @ T.quat2mat(quat).T # Compile the particle poses to generate and sample the particles n_modified_particles = self.obj.states[ModifiedParticles].get_value(system) n_particles = min(len(points), m.PHYSICAL_PARTICLES_APPLICATION_LIMIT - n_modified_particles) # Generate particles if n_particles > 0: velocities = None if self._initial_speed == 0 else self._initial_speed * directions[:n_particles] system.generate_particles( positions=points[:n_particles], velocities=velocities, ) # Update our particle count self.obj.states[ModifiedParticles].set_value(system, n_modified_particles + n_particles) def _sample_particle_locations_from_projection_volume(self, system): """ Helper function for generating potential particle locations from projection volume Args: system (BaseSystem): System to sample potential particle positions for Returns: 2-tuple: - (n, 3) array: Ray start points to sample - (n, 3) array: Ray end points to sample """ # Randomly sample end points from the base of the cone / cylinder n_samples = self._get_max_particles_limit_per_step(system=system) r, h = self._projection_mesh_params["extents"][0] / 2, self._projection_mesh_params["extents"][2] sampled_r_theta = np.random.rand(n_samples, 2) sampled_r_theta = sampled_r_theta * np.array([r, np.pi * 2]).reshape(1, 2) # Get start, end points in local link frame, start points to end points along the -z direction end_points = np.stack([ sampled_r_theta[:, 0] * np.cos(sampled_r_theta[:, 1]), sampled_r_theta[:, 0] * np.sin(sampled_r_theta[:, 1]), -h * np.ones(n_samples), ], axis=1) projection_type = self._projection_mesh_params["type"] if projection_type == "Cone": # All start points are the cone tip, which is the local link origin start_points = np.zeros((n_samples, 3)) elif projection_type == "Cylinder": # All start points are the parallel point for their corresponding end point # i.e.: (x, y, 0) start_points = end_points + np.array([0, 0, h]).reshape(1, 3) else: # Other types not supported raise ValueError(f"Unsupported projection mesh type: {projection_type}!") # Convert sampled normalized radius and angle into 3D points # We convert r, theta --> 3D point in local link frame --> 3D point in global world frame # We also combine start and end points for efficiency when doing the transform, then split them up again points = np.concatenate([start_points, end_points], axis=0) pos, quat = self.link.get_position_orientation() points = get_particle_positions_from_frame( pos=pos, quat=quat, scale=self.obj.scale, particle_positions=points, ) return points[:n_samples, :], points[n_samples:, :] def _sample_particle_locations_from_adjacency_area(self, system): """ Helper function for generating potential particle locations from adjacency area Args: system (BaseSystem): System to sample potential particle positions for Returns: 2-tuple: - (n, 3) array: Ray start points to sample - (n, 3) array: Ray end points to sample """ # Randomly sample end points from within the object's AABB n_samples = self._get_max_particles_limit_per_step(system=system) lower, upper = self.link.visual_aabb lower = lower.reshape(1, 3) - m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN upper = upper.reshape(1, 3) + m.PARTICLE_MODIFIER_ADJACENCY_AREA_MARGIN lower_upper = np.concatenate([lower, upper], axis=0) # Sample in all directions, shooting from the center of the link / object frame pos = self.link.get_position() start_points = np.ones((n_samples, 3)) * pos.reshape(1, 3) end_points = np.random.uniform(low=lower, high=upper, size=(n_samples, 3)) sides, axes = np.random.randint(2, size=(n_samples,)), np.random.randint(3, size=(n_samples,)) end_points[np.arange(n_samples), axes] = lower_upper[sides, axes] return start_points, end_points def _get_max_particles_limit_per_step(self, system): """ Helper function for grabbing the maximum particle limit per step Args: system (BaseSystem): System for which to get max particle limit per step Returns: int: Maximum particles to apply per step for the given system @system """ assert system.name in self.conditions, f"System {system.name} is not defined in the conditions." return m.MAX_VISUAL_PARTICLES_APPLIED_PER_STEP if is_visual_particle_system(system_name=system.name) else \ m.MAX_PHYSICAL_PARTICLES_APPLIED_PER_STEP @property def requires_overlap(self): # Overlap required only if sampling with raycast return self._sample_with_raycast @property def visualize(self): """ Returns: bool: Whether this Applier should be visualized or not """ # Visualize if projection method is used return self.method == ParticleModifyMethod.PROJECTION @property def systems_to_check(self): # Only should check the systems in the owned conditions return tuple(self.conditions.keys()) @property def projection_is_active(self): # Only active if the projection mesh is enabled return self.projection_emitter.GetProperty("inputs:active").Get() @classproperty def metalink_prefix(cls): return m.APPLICATION_LINK_PREFIX @classmethod def requires_metalink(cls, **kwargs): # No metalink required for adjacency return kwargs.get("method", ParticleModifyMethod.ADJACENCY) != ParticleModifyMethod.ADJACENCY @classmethod def is_compatible(cls, obj, **kwargs): # Run super first compatible, reason = super().is_compatible(obj, **kwargs) if not compatible: return compatible, reason # Check whether GPU dynamics are enabled (necessary for this object state) if not gm.USE_GPU_DYNAMICS: return False, f"gm.USE_GPU_DYNAMICS must be True in order to use object state {cls.__name__}." return True, None @property def _default_link(self): # Only supported for adjacency, NOT projection return self.obj.root_link if self.method == ParticleModifyMethod.ADJACENCY else None @property def n_steps_per_modification(self): return m.N_STEPS_PER_APPLICATION @property def visual_particle_modification_limit(self): return m.VISUAL_PARTICLES_APPLICATION_LIMIT @property def physical_particle_modification_limit(self): return m.PHYSICAL_PARTICLES_APPLICATION_LIMIT
73,493
Python
51.123404
158
0.655899
StanfordVL/OmniGibson/omnigibson/object_states/open_state.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.object_state_base import BooleanStateMixin, AbsoluteObjectState from omnigibson.utils.constants import JointType 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__) # Joint position threshold before a joint is considered open. # Should be a number in the range [0, 1] which will be transformed # to a position in the joint's min-max range. m.JOINT_THRESHOLD_BY_TYPE = { JointType.JOINT_REVOLUTE: 0.05, JointType.JOINT_PRISMATIC: 0.05, } m.OPEN_SAMPLING_ATTEMPTS = 5 m.METADATA_FIELD = "openable_joint_ids" m.BOTH_SIDES_METADATA_FIELD = "openable_both_sides" def _compute_joint_threshold(joint, joint_direction): """ Computes the joint threshold for opening and closing Args: joint (JointPrim): Joint to calculate threshold for joint_direction (int): If 1, assumes opening direction is positive angle change. Otherwise, assumes opening direction is negative angle change. Returns: 3-tuple: - float: Joint value at which closed <--> open - float: Extreme joint value for being opened - float: Extreme joint value for being closed """ global m # Convert fractional threshold to actual joint position. f = m.JOINT_THRESHOLD_BY_TYPE[joint.joint_type] closed_end = joint.lower_limit if joint_direction == 1 else joint.upper_limit open_end = joint.upper_limit if joint_direction == 1 else joint.lower_limit threshold = (1 - f) * closed_end + f * open_end return threshold, open_end, closed_end def _is_in_range(position, threshold, range_end): """ Calculates whether a joint's position @position is in its opening / closing range Args: position (float): Joint value threshold (float): Joint value at which closed <--> open range_end (float): Extreme joint value for being opened / closed Returns: bool: Whether the joint position is past @threshold in the direction of @range_end """ # Note that we are unable to do an actual range check here because the joint positions can actually go # slightly further than the denoted joint limits. return position > threshold if range_end > threshold else position < threshold def _get_relevant_joints(obj): """ Grabs the relevant joints for object @obj Args: obj (StatefulObject): Object to grab relevant joints for Returns: 3-tuple: - bool: If True, check open/closed state for objects whose joints can switch positions - list of JointPrim: Relevant joints for determining whether @obj is open or closed - list of int: Joint directions for each corresponding relevant joint """ global m default_both_sides = False default_relevant_joints = list(obj.joints.values()) # 1 means the open direction corresponds to positive joint angle change and -1 means the opposite default_joint_directions = [1] * len(default_relevant_joints) if not hasattr(obj, "metadata") or obj.metadata is None: log.debug("No openable joint metadata found for object %s" % obj.name) return default_both_sides, default_relevant_joints, default_joint_directions # Get joint IDs and names from metadata annotation. If not, return default values. if m.METADATA_FIELD not in obj.metadata or len(obj.metadata[m.METADATA_FIELD]) == 0: log.debug(f"No openable joint metadata found for object {obj.name}") return default_both_sides, default_relevant_joints, default_joint_directions both_sides = obj.metadata[m.BOTH_SIDES_METADATA_FIELD] if m.BOTH_SIDES_METADATA_FIELD in obj.metadata else False joint_metadata = obj.metadata[m.METADATA_FIELD].items() # The joint metadata is in the format of [(joint_id, joint_name), ...] for legacy annotations and # [(joint_id, joint_name, joint_direction), ...] for direction-annotated objects. joint_names = [m[1] for m in joint_metadata] joint_directions = [m[2] if len(m) > 2 else 1 for m in joint_metadata] relevant_joints = [] for key in joint_names: assert key in obj.joints, f"Unexpected joint name from Open metadata for object {obj.name}: {key}" relevant_joints.append(obj.joints[key]) assert all(joint.joint_type in m.JOINT_THRESHOLD_BY_TYPE.keys() for joint in relevant_joints) return both_sides, relevant_joints, joint_directions class Open(AbsoluteObjectState, BooleanStateMixin): def __init__(self, obj): self.relevant_joints_info = None # Run super method super().__init__(obj=obj) def _initialize(self): # Run super first super()._initialize() # Check the metadata info to get relevant joints information self.relevant_joints_info = _get_relevant_joints(self.obj) assert self.relevant_joints_info[1], f"No relevant joints for Open state found for object {self.obj.name}" @classmethod def is_compatible(cls, obj, **kwargs): # Run super first compatible, reason = super().is_compatible(obj, **kwargs) if not compatible: return compatible, reason # Check whether this object has any openable joints return (True, None) if obj.n_joints > 0 else \ (False, f"No relevant joints for Open state found for object {obj.name}") @classmethod def is_compatible_asset(cls, prim, **kwargs): # Run super first compatible, reason = super().is_compatible_asset(prim, **kwargs) if not compatible: return compatible, reason def _find_articulated_joints(prim): for child in prim.GetChildren(): child_type = child.GetTypeName().lower() if "joint" in child_type and "fixed" not in child_type: return True for gchild in child.GetChildren(): gchild_type = gchild.GetTypeName().lower() if "joint" in gchild_type and "fixed" not in gchild_type: return True return False # Check whether this object has any openable joints return (True, None) if _find_articulated_joints(prim=prim) else \ (False, f"No relevant joints for Open state found for asset prim {prim.GetName()}") def _get_value(self): both_sides, relevant_joints, joint_directions = self.relevant_joints_info if not relevant_joints: return False # The "sides" variable is used to check open/closed state for objects whose joints can switch # positions. These objects are annotated with the both_sides annotation and the idea is that switching # the directions of *all* of the joints results in a similarly valid checkable state. As a result, to check # each "side", we multiply *all* of the joint directions with the coefficient belonging to that side, which # may be 1 or -1. sides = [1, -1] if both_sides else [1] sides_openness = [] for side in sides: # Compute a boolean openness state for each joint by comparing positions to thresholds. joint_thresholds = ( _compute_joint_threshold(joint, joint_direction * side) for joint, joint_direction in zip(relevant_joints, joint_directions) ) joint_positions = [joint.get_state()[0] for joint in relevant_joints] joint_openness = ( _is_in_range(position, threshold, open_end) for position, (threshold, open_end, closed_end) in zip(joint_positions, joint_thresholds) ) # Looking from this side, the object is open if any of its joints is open. sides_openness.append(any(joint_openness)) # The object is open only if it's open from all of its sides. return all(sides_openness) def _set_value(self, new_value, fully=False): """ Set the openness state, either to a random joint position satisfying the new value, or fully open/closed. Args: new_value (bool): The new value for the openness state of the object. fully (bool): Whether the object should be fully opened/closed (e.g. all relevant joints to 0/1). Returns: bool: A boolean indicating the success of the setter. Failure may happen due to unannotated objects. """ both_sides, relevant_joints, joint_directions = self.relevant_joints_info if not relevant_joints: return False # The "sides" variable is used to check open/closed state for objects whose joints can switch # positions. These objects are annotated with the both_sides annotation and the idea is that switching # the directions of *all* of the joints results in a similarly valid checkable state. We want our object to be # open from *both* of the two sides, and I was too lazy to implement the logic for this without rejection # sampling, so that's what we do. # TODO: Implement a sampling method that's guaranteed to be correct, ditch the rejection method. sides = [1, -1] if both_sides else [1] for _ in range(m.OPEN_SAMPLING_ATTEMPTS): side = np.random.choice(sides) # All joints are relevant if we are closing, but if we are opening let's sample a subset. if new_value and not fully: num_to_open = np.random.randint(1, len(relevant_joints) + 1) random_indices = np.random.choice(range(len(relevant_joints)), size=num_to_open, replace=False) relevant_joints = [relevant_joints[i] for i in random_indices] joint_directions = [joint_directions[i] for i in random_indices] # Go through the relevant joints & set random positions. for joint, joint_direction in zip(relevant_joints, joint_directions): threshold, open_end, closed_end = _compute_joint_threshold(joint, joint_direction * side) # Get the range if new_value: joint_range = (threshold, open_end) else: joint_range = (threshold, closed_end) if fully: joint_pos = joint_range[1] else: # Convert the range to the format numpy accepts. low = min(joint_range) high = max(joint_range) # Sample a position. joint_pos = np.random.uniform(low, high) # Save sampled position. joint.set_pos(joint_pos) # If we succeeded, return now. if self._get_value() == new_value: return True # We exhausted our attempts and could not find a working sample. return False # We don't need to load / save anything since the joints are saved elsewhere
11,225
Python
42.343629
118
0.646325
StanfordVL/OmniGibson/omnigibson/object_states/update_state_mixin.py
from omnigibson.object_states.object_state_base import BaseObjectState from omnigibson.utils.python_utils import classproperty class UpdateStateMixin(BaseObjectState): """ A state-mixin that allows for per-sim-step updates via the update() call """ def update(self): """ Updates the object state. This function will be called for every simulator step """ assert self._initialized, "Cannot update uninitialized state." return self._update() def _update(self): """ This function will be called once for every simulator step. Must be implemented by subclass. """ # Explicitly raise not implemented error to avoid silent bugs -- update should never be called otherwise 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("UpdateStateMixin") return classes class GlobalUpdateStateMixin(BaseObjectState): """ A state-mixin that allows for per-sim-step global updates via the global_update() call """ @classmethod def global_initialize(cls): """ Executes a global initialization sequence for this state. Default is no-op """ pass @classmethod def global_update(cls): """ Executes a global update for this object state. Default is no-op """ pass @classmethod def global_clear(cls): """ Executes a global clear sequence for this object state. Default is no-op """ pass @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("GlobalUpdateStateMixin") return classes
1,926
Python
30.080645
112
0.65109
StanfordVL/OmniGibson/omnigibson/object_states/kinematics_mixin.py
from omnigibson.object_states.aabb import AABB from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.object_states.object_state_base import BaseObjectState from omnigibson.object_states.pose import Pose from omnigibson.utils.python_utils import classproperty class KinematicsMixin(BaseObjectState): """ This class is a subclass of BaseObjectState that adds dependencies on the default kinematics states. """ @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.update({Pose, AABB, ContactBodies}) return deps def cache_info(self, get_value_args): # Import here to avoid circular imports from omnigibson.objects.stateful_object import StatefulObject # Run super first info = super().cache_info(get_value_args=get_value_args) # Store this object as well as any other objects from @get_value_args info[self.obj] = self.obj.states[Pose].get_value() for arg in get_value_args: if isinstance(arg, StatefulObject): info[arg] = arg.states[Pose].get_value() return info def _cache_is_valid(self, get_value_args): # Import here to avoid circular imports from omnigibson.objects.stateful_object import StatefulObject # Cache is valid if and only if all of our cached objects have not changed t = self._cache[get_value_args]["t"] for obj, pose in self._cache[get_value_args]["info"].items(): if isinstance(obj, StatefulObject): if obj.states[Pose].has_changed(get_value_args=(), value=pose, info={}, t=t): return False 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("KinematicsMixin") return classes
1,966
Python
36.113207
93
0.667345
StanfordVL/OmniGibson/omnigibson/object_states/contact_subscribed_state_mixin.py
from abc import abstractmethod from omnigibson.object_states.object_state_base import BaseObjectState from omnigibson.utils.python_utils import classproperty class ContactSubscribedStateMixin(BaseObjectState): """ Handles contact events (including CONTACT_FOUND, CONTACT_PERSIST, and CONTACT_LOST). The subclass should implement its own on_contact method """ @abstractmethod def on_contact(self, other, contact_headers, contact_data): raise NotImplementedError("Subclasses of ContactSubscribedStateMixin should implement the on_contact method.") @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("ContactSubscribedStateMixin") return classes
832
Python
38.666665
118
0.751202
StanfordVL/OmniGibson/omnigibson/object_states/particle.py
import numpy as np from omnigibson.object_states.object_state_base import BaseObjectRequirement class ParticleRequirement(BaseObjectRequirement): """ Class for sanity checking objects that requires particle systems """ @classmethod def is_compatible(cls, obj, **kwargs): from omnigibson.macros import gm if not gm.USE_GPU_DYNAMICS: return False, f"Particle systems are not enabled when GPU dynamics is off." return True, None
486
Python
27.647057
87
0.709877
StanfordVL/OmniGibson/omnigibson/object_states/touching.py
from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.utils.constants import PrimType from omnigibson.utils.usd_utils import RigidContactAPI class Touching(KinematicsMixin, RelativeObjectState, BooleanStateMixin): @staticmethod def _check_contact(obj_a, obj_b): return len(set(obj_a.links.values()) & obj_b.states[ContactBodies].get_value()) > 0 def _get_value(self, other): if self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.CLOTH: raise ValueError("Cannot detect contact between two cloth objects.") # If one of the objects is the cloth object, the contact will be asymmetrical. # The rigid object will appear in the ContactBodies of the cloth object, but not the other way around. elif self.obj.prim_type == PrimType.CLOTH: return self._check_contact(other, self.obj) elif other.prim_type == PrimType.CLOTH: return self._check_contact(self.obj, other) # elif not self.obj.kinematic_only and not other.kinematic_only: # # Use optimized check for rigid bodies # # TODO: Use once NVIDIA fixes their absolutely broken API # return RigidContactAPI.in_contact( # prim_paths_a=[link.prim_path for link in self.obj.links.values()], # prim_paths_b=[link.prim_path for link in other.links.values()], # ) else: return self._check_contact(other, self.obj) and self._check_contact(self.obj, other)
1,709
Python
52.437498
110
0.691047
StanfordVL/OmniGibson/omnigibson/object_states/on_top.py
import omnigibson as og from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.adjacency import VerticalAdjacency from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.object_states.touching import Touching from omnigibson.utils.object_state_utils import sample_kinematics from omnigibson.utils.object_state_utils import m as os_m from omnigibson.utils.constants import PrimType class OnTop(KinematicsMixin, RelativeObjectState, BooleanStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.update({Touching, VerticalAdjacency}) return deps def _set_value(self, other, new_value, reset_before_sampling=False): if not new_value: raise NotImplementedError("OnTop does not support set_value(False)") if other.prim_type == PrimType.CLOTH: raise ValueError("Cannot set an object on top of a cloth object.") state = og.sim.dump_state(serialized=False) # Possibly reset this object if requested if reset_before_sampling: self.obj.reset() for _ in range(os_m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS): if sample_kinematics("onTop", self.obj, other) and self.get_value(other): return True else: og.sim.load_state(state, serialized=False) return False def _get_value(self, other): if other.prim_type == PrimType.CLOTH: raise ValueError("Cannot detect if an object is on top of a cloth object.") touching = self.obj.states[Touching].get_value(other) if not touching: return False adjacency = self.obj.states[VerticalAdjacency].get_value() return other in adjacency.negative_neighbors and other not in adjacency.positive_neighbors
1,917
Python
37.359999
98
0.696922
StanfordVL/OmniGibson/omnigibson/object_states/cloth_mixin.py
from omnigibson.macros import gm from omnigibson.object_states.object_state_base import BaseObjectState from omnigibson.utils.constants import PrimType from omnigibson.utils.python_utils import classproperty class ClothStateMixin(BaseObjectState): """ This class is a subclass of BaseObjectState that adds dependencies assuming the owned object is PrimType.CLOTH """ @classmethod def is_compatible(cls, obj, **kwargs): # Only compatible with cloth objects compatible, reason = super().is_compatible(obj, **kwargs) if not compatible: return compatible, reason # Check for cloth type if obj.prim_type != PrimType.CLOTH: return False, f"Cannot use ClothStateMixin {cls.__name__} with rigid object, make sure object is created " \ f"with prim_type=PrimType.CLOTH!" # Check for GPU dynamics if not gm.USE_GPU_DYNAMICS: return False, f"gm.USE_GPU_DYNAMICS must be True in order to use object state {cls.__name__}." return True, None @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("ClothStateMixin") return classes
1,319
Python
35.666666
120
0.670963
StanfordVL/OmniGibson/omnigibson/object_states/object_state_base.py
from abc import ABC import inspect import omnigibson as og from omnigibson.utils.python_utils import classproperty, Serializable, Registerable, Recreatable # Global dicts that will contain mappings REGISTERED_OBJECT_STATES = dict() class BaseObjectRequirement: """ Base ObjectRequirement class. This allows for sanity checking a given asset / BaseObject to check whether a set of conditions are met or not. This can be useful for sanity checking dependencies for properties such as requested abilities or object states. """ @classmethod def is_compatible(cls, obj, **kwargs): """ Determines whether this requirement is compatible with object @obj or not (i.e.: whether this requirement is satisfied by @obj given other constructor arguments **kwargs). NOTE: Must be implemented by subclass. Args: obj (StatefulObject): Object whose compatibility with this state should be checked Returns: 2-tuple: - bool: Whether the given object is compatible with this requirement or not - None or str: If not compatible, the reason why it is not compatible. Otherwise, None """ raise NotImplementedError @classmethod def is_compatible_asset(cls, prim, **kwargs): """ Determines whether this requirement is compatible with prim @prim or not (i.e.: whether this requirement is satisfied by @prim given other constructor arguments **kwargs). This is a useful check to evaluate an object's USD that hasn't been explicitly imported into OmniGibson yet. NOTE: Must be implemented by subclass Args: prim (Usd.Prim): Object prim whose compatibility with this requirement should be checked Returns: 2-tuple: - bool: Whether the given prim is compatible with this requirement or not - None or str: If not compatible, the reason why it is not compatible. Otherwise, None """ raise NotImplementedError class BaseObjectState(BaseObjectRequirement, Serializable, Registerable, Recreatable, ABC): """ Base ObjectState class. Do NOT inherit from this class directly - use either AbsoluteObjectState or RelativeObjectState. """ @classmethod def get_dependencies(cls): """ Get the dependency states for this state, e.g. states that need to be explicitly enabled on the current object before the current state is usable. States listed here will be enabled for all objects that have this current state, and all dependency states will be processed on *all* objects prior to this state being processed on *any* object. Returns: set of str: Set of strings corresponding to state keys. """ return set() @classmethod def get_optional_dependencies(cls): """ Get states that should be processed prior to this state if they are already enabled. These states will not be enabled because of this state's dependency on them, but if they are already enabled for another reason (e.g. because of an ability or another state's dependency etc.), they will be processed on *all* objects prior to this state being processed on *any* object. Returns: set of str: Set of strings corresponding to state keys. """ return set() def __init__(self, obj): super().__init__() self.obj = obj self._initialized = False self._cache = None self._changed = None self._last_t_updated = -1 # Last timestep when this state was updated @classmethod def is_compatible(cls, obj, **kwargs): # Make sure all required dependencies are included in this object's state dictionary for dep in cls.get_dependencies(): if dep not in obj.states: return False, f"Missing required dependency state {dep.__name__}" # Make sure all required kwargs are specified default_kwargs = inspect.signature(cls.__init__).parameters for kwarg, val in default_kwargs.items(): if val.default == inspect._empty and kwarg not in kwargs and kwarg not in {"obj", "self", "args", "kwargs"}: return False, f"Missing required kwarg '{kwarg}'" # Default is True if all kwargs are met return True, None @classmethod def is_compatible_asset(cls, prim, **kwargs): # Make sure all required kwargs are specified default_kwargs = inspect.signature(cls.__init__).parameters for kwarg, val in default_kwargs.items(): if val.default == inspect._empty and kwarg not in kwargs and kwarg not in {"obj", "self"}: return False, f"Missing required kwarg '{kwarg}'" # Default is True if all kwargs are met return True, None @classmethod def postprocess_ability_params(cls, params): """ Post-processes ability parameters if needed. The default implementation is a simple passthrough. """ return params @property def stateful(self): """ Returns: bool: True if this object has a state that can be directly dumped / loaded via dump_state() and load_state(), otherwise, returns False. Note that any sub object states that are NOT stateful do not need to implement any of _dump_state(), _load_state(), _serialize(), or _deserialize()! """ # Default is whether state size > 0 return self.state_size > 0 @property def state_size(self): return 0 @property def cache(self): """ Returns: dict: Dictionary mapping specific argument combinations from @self.get_value() to cached values and information stored for that specific combination """ return self._cache def _initialize(self): """ This function will be called once; should be used for any object state-related objects have been loaded. """ pass def initialize(self): """ Initialize this object state """ assert not self._initialized, "State is already initialized." # Validate compatibility with the created object init_args = {k: v for k, v in self.get_init_info()["args"].items() if k != "obj"} assert self.is_compatible(obj=self.obj, **init_args), \ f"ObjectState {self.__class__.__name__} is not compatible with object {self.obj.name}." # Clear cache self.clear_cache() self._initialize() self._initialized = True def clear_cache(self): """ Clears the internal cache """ # Clear all entries self._cache = dict() self._changed = dict() self._last_t_updated = -1 def update_cache(self, get_value_args): """ Updates the internal cached value based on the evaluation of @self._get_value(*get_value_args) Args: get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into @self.get_value / @self._get_value """ t = og.sim.current_time_step_index # Compute value and update cache val = self._get_value(*get_value_args) self._cache[get_value_args] = dict(value=val, info=self.cache_info(get_value_args=get_value_args), t=t) def cache_info(self, get_value_args): """ Helper function to cache relevant information at the current timestep. Stores it under @self._cache[<KEY>]["info"] Args: get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into @self.get_value whose caching information should be computed Returns: dict: Any caching information to include at the current timestep when this state's value is computed """ # Default is an empty dictionary return dict() def cache_is_valid(self, get_value_args): """ Helper function to check whether the current cached value is valid or not at the current timestep. Default is False unless we're at the current timestep. Args: get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into @self.get_value whose cached values should be validated Returns: bool: True if the cache is valid, else False """ # If t == the current timestep, then our cache is obviously valid otherwise we assume it isn't return True if self._cache[get_value_args]["t"] == og.sim.current_time_step_index else \ self._cache_is_valid(get_value_args=get_value_args) def _cache_is_valid(self, get_value_args): """ Helper function to check whether the current cached value is valid or not at the current timestep. Default is False. Subclasses should implement special logic otherwise. Args: get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into @self.get_value whose cached values should be validated Returns: bool: True if the cache is valid, else False """ return False def has_changed(self, get_value_args, value, info, t): """ A helper function to query whether this object state has changed between the current timestep and an arbitrary previous timestep @t with the corresponding cached value @value and cache information @info Note that this may require some non-trivial compute, so we leverage @t, in addition to @get_value_args, as a unique key into an internal dictionary, such that specific @t will result in a computation conducted exactly once. This is done for performance reasons; so that multiple states relying on the same state dependency can all query whether that state has changed between the same timesteps with only a single computation. Args: get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into @self.get_value value (any): Cached value computed at timestep @t for this object state info (dict): Information calculated at timestep @t when computing this state's value t (int): Initial timestep to compare against. This should be an index of the steps taken, i.e. a value queried from og.sim.current_time_step_index at some point in time. It is assumed @value and @info were computed at this timestep Returns: bool: Whether this object state has changed between @t and the current timestep index for the specific @get_value_args """ # Check current sim step index; if it doesn't match the internal value, we need to clear the changed history current_t = og.sim.current_time_step_index if self._last_t_updated != current_t: self._changed = dict() self._last_t_updated = current_t # Compile t, args, and kwargs deterministically history_key = (t, *get_value_args) # If t == the current timestep, then we obviously haven't changed so our value is False if t == current_t: val = False # Otherwise, check if it already exists in our has changed dictionary; we return that value if so elif history_key in self._changed: val = self._changed[history_key] # Otherwise, we calculate the value and store it in our changed dictionary else: val = self._has_changed(get_value_args=get_value_args, value=value, info=info) self._changed[history_key] = val return val def _has_changed(self, get_value_args, value, info): """ Checks whether the previous value evaluated at time @t has changed with the current timestep. By default, it returns True. Any custom checks should be overridden by subclass. Args: get_value_args (tuple): Specific argument combinations (usually tuple of objects) passed into @self.get_value value (any): Cached value computed at timestep @t for this object state info (dict): Information calculated at timestep @t when computing this state's value Returns: bool: Whether the value has changed between @value and @info and the coresponding value and info computed at the current timestep """ return True def get_value(self, *args, **kwargs): """ Get this state's value Returns: any: Object state value given input @args and @kwargs """ assert self._initialized # Compile args and kwargs deterministically key = (*args, *tuple(kwargs.values())) # We need to see if we need to update our cache -- we do so if and only if one of the following conditions are met: # (a) key is NOT in the cache # (b) Our cache is not valid if key not in self._cache or not self.cache_is_valid(get_value_args=key): # Update the cache self.update_cache(get_value_args=key) # Value is the cached value val = self._cache[key]["value"] return val def _get_value(self, *args, **kwargs): raise NotImplementedError(f"_get_value not implemented for {self.__class__.__name__} state.") def set_value(self, *args, **kwargs): """ Set this state's value Returns: bool: True if setting the value was successful, otherwise False """ assert self._initialized # Clear cache because the state may be changed self.clear_cache() # Set the value val = self._set_value(*args, **kwargs) return val def _set_value(self, *args, **kwargs): raise NotImplementedError(f"_set_value not implemented for {self.__class__.__name__} state.") def remove(self): """ Any cleanup functionality to deploy when @self.obj is removed from the simulator """ pass def dump_state(self, serialized=False): assert self._initialized assert self.stateful return super().dump_state(serialized=serialized) @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("BaseObjectState") return classes @classproperty def _cls_registry(cls): # Global registry global REGISTERED_OBJECT_STATES return REGISTERED_OBJECT_STATES class AbsoluteObjectState(BaseObjectState): """ This class is used to track object states that are absolute, e.g. do not require a second object to compute the value. """ def _get_value(self): raise NotImplementedError(f"_get_value not implemented for {self.__class__.__name__} state.") def _set_value(self, new_value): raise NotImplementedError(f"_set_value not implemented for {self.__class__.__name__} state.") @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("AbsoluteObjectState") return classes class RelativeObjectState(BaseObjectState): """ This class is used to track object states that are relative, e.g. require two objects to compute a value. Note that subclasses will typically compute values on-the-fly. """ def _get_value(self, other): raise NotImplementedError(f"_get_value not implemented for {self.__class__.__name__} state.") def _set_value(self, other, new_value): raise NotImplementedError(f"_set_value not implemented for {self.__class__.__name__} state.") @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("RelativeObjectState") return classes class IntrinsicObjectState(BaseObjectState): """ This class is used to track object states that should NOT have getters / setters implemented, since the associated ability / state is intrinsic to the state """ def _get_value(self): raise NotImplementedError(f"_get_value not implemented for IntrinsicObjectState {self.__class__.__name__} state.") def _set_value(self, new_value): raise NotImplementedError(f"_set_value not implemented for IntrinsicObjectState {self.__class__.__name__} state.") @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("IntrinsicObjectState") return classes class BooleanStateMixin(BaseObjectState): """ This class is a mixin used to indicate that a state has a boolean value. """ pass
17,376
Python
38.673516
123
0.640021
StanfordVL/OmniGibson/omnigibson/object_states/overlaid.py
from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.object_states.touching import Touching from omnigibson.utils.constants import PrimType import omnigibson.utils.transform_utils as T from omnigibson.utils.object_state_utils import sample_cloth_on_rigid from omnigibson.macros import create_module_macros import omnigibson as og from scipy.spatial import ConvexHull, HalfspaceIntersection, QhullError import numpy as np import trimesh import itertools # Create settings for this module m = create_module_macros(module_path=__file__) # Percentage of xy-plane of the object's base aligned bbox that needs to covered by the cloth m.OVERLAP_AREA_PERCENTAGE = 0.5 # z-offset for sampling m.SAMPLING_Z_OFFSET = 0.01 class Overlaid(KinematicsMixin, RelativeObjectState, BooleanStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(Touching) return deps def _set_value(self, other, new_value): if not new_value: raise NotImplementedError("Overlaid does not support set_value(False)") state = og.sim.dump_state(serialized=False) if sample_cloth_on_rigid(self.obj, other, randomize_xy=False) and self.get_value(other): return True else: og.sim.load_state(state, serialized=False) return False def _get_value(self, other): """ Check whether the (cloth) object is overlaid on the other (rigid) object. First, the cloth object needs to be touching the rigid object. Then, the convex hull of the particles of the cloth object needs to cover a decent percentage of the base aligned bounding box of the other rigid object. """ if not (self.obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID): raise ValueError("Overlaid state requires obj1 is cloth and obj2 is rigid.") if not self.obj.states[Touching].get_value(other): return False # Compute the convex hull of the particles of the cloth object. points = self.obj.root_link.keypoint_particle_positions[:, :2] cloth_hull = ConvexHull(points) # Compute the base aligned bounding box of the rigid object. bbox_center, bbox_orn, bbox_extent, _ = other.get_base_aligned_bbox(xy_aligned=True) vertices_local = np.array(list(itertools.product((1, -1), repeat=3))) * (bbox_extent / 2) vertices = trimesh.transformations.transform_points(vertices_local, T.pose2mat((bbox_center, bbox_orn))) rigid_hull = ConvexHull(vertices[:, :2]) # The goal is to find the intersection of the convex hull and the bounding box. # We can do so with HalfspaceIntersection, which takes as input a list of equations that define the half spaces, # and an interior point. We assume the center of the bounding box is an interior point. interior_pt = vertices.mean(axis=0)[:2] half_spaces = np.vstack((cloth_hull.equations, rigid_hull.equations)) try: half_space_intersection = HalfspaceIntersection(half_spaces, interior_pt) except QhullError: # The bbox center of the rigid body does not lie in the intersection, return False. return False # Compute the ratio between the intersection area and the bounding box area in the x-y plane. # When input points are 2-dimensional, this is the area of the convex hull. # Ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html intersection_area = ConvexHull(half_space_intersection.intersections).volume rigid_xy_area = bbox_extent[0] * bbox_extent[1] return (intersection_area / rigid_xy_area) > m.OVERLAP_AREA_PERCENTAGE
3,916
Python
44.022988
120
0.701992
StanfordVL/OmniGibson/omnigibson/object_states/tensorized_value_state.py
from omnigibson.object_states.object_state_base import AbsoluteObjectState from omnigibson.object_states.update_state_mixin import GlobalUpdateStateMixin from omnigibson.utils.python_utils import classproperty import numpy as np class TensorizedValueState(AbsoluteObjectState, GlobalUpdateStateMixin): """ A state-mixin that implements optimized global value updates across all object state instances of this type, i.e.: all values across all object state instances are updated at once, rather than per individual instance update() call. """ # Numpy array of raw internally tracked values # Shape is (N, ...), where the ith entry in the first dimension corresponds to the ith object state instance's value VALUES = None # Dictionary mapping object name to index in VALUES OBJ_IDXS = None # Dict of callbacks that can be added to when an object is removed CALLBACKS_ON_REMOVE = None @classmethod def global_initialize(cls): # Call super first super().global_initialize() # Initialize the global variables cls.VALUES = np.array([], dtype=cls.value_type).reshape(0, *cls.value_shape) cls.OBJ_IDXS = dict() cls.CALLBACKS_ON_REMOVE = dict() @classmethod def global_update(cls): # Call super first super().global_update() # This should be globally update all values. If there are no values, we skip by default since there is nothing # being tracked currently if len(cls.VALUES) == 0: return cls.VALUES = cls._update_values(values=cls.VALUES) @classmethod def global_clear(cls): # Call super first super().global_clear() # Clear internal state cls.VALUES = None cls.OBJ_IDXS = None cls.CALLBACKS_ON_REMOVE = None @classmethod def _update_values(cls, values): """ Updates all internally tracked @values for this object state. Should be implemented by subclass. Args: values (np.array): Tensorized value array Returns: np.array: Updated tensorized value array """ raise NotImplementedError @classmethod def _add_obj(cls, obj): """ Adds object @obj to be tracked internally in @VALUES array. Args: obj (StatefulObject): Object to add """ assert obj.name not in cls.OBJ_IDXS, \ f"Tried to add object {obj.name} to the global tensorized value array but the object already exists!" # Add this object to the tracked global state cls.OBJ_IDXS[obj.name] = len(cls.VALUES) cls.VALUES = np.concatenate([cls.VALUES, np.zeros((1, *cls.value_shape), dtype=cls.value_type)], axis=0) @classmethod def _remove_obj(cls, obj): """ Removes object @obj from the internally tracked @VALUES array. This also removes the corresponding tracking idx in @OBJ_IDXS Args: obj (StatefulObject): Object to remove """ # Removes this tracked object from the global value array assert obj.name in cls.OBJ_IDXS, \ f"Tried to remove object {obj.name} from the global tensorized value array but the object does not exist!" deleted_idx = cls.OBJ_IDXS.pop(obj.name) # Re-standardize the indices for i, name in enumerate(cls.OBJ_IDXS.keys()): cls.OBJ_IDXS[name] = i cls.VALUES = np.delete(cls.VALUES, [deleted_idx]) @classmethod def add_callback_on_remove(cls, name, callback): """ Adds a callback that will be triggered when @self.remove is called Args: name (str): Name of the callback to trigger callback (function): Function to execute. Should have signature callback(obj: BaseObject) --> None """ cls.CALLBACKS_ON_REMOVE[name] = callback @classmethod def remove_callback_on_remove(cls, name): """ Removes callback with name @name from the internal set of callbacks Args: name (str): Name of the callback to remove """ cls.CALLBACKS_ON_REMOVE.pop(name) @classproperty def value_shape(cls): """ Returns: tuple: Expected shape of the per-object state instance value. If empty (), this assumes that each entry is a single (non-array) value. Default is () """ return () @classproperty def value_type(cls): """ Returns: type: Type of the internal value array, e.g., bool, np.uint, float, etc. Default is float """ return float @classproperty def value_name(cls): """ Returns: str: Name of the value key to assign when dumping / loading the state. Should be implemented by subclass """ raise NotImplementedError def __init__(self, *args, **kwargs): # Run super first super().__init__(*args, **kwargs) self._add_obj(obj=self.obj) def remove(self): # Execute all callbacks for callback in self.CALLBACKS_ON_REMOVE.values(): callback(self.obj) # Removes this tracked object from the global value array self._remove_obj(obj=self.obj) def _get_value(self): # Directly access value from global register return self.value_type(self.VALUES[self.OBJ_IDXS[self.obj.name]]) def _set_value(self, new_value): # Directly set value in global register self.VALUES[self.OBJ_IDXS[self.obj.name]] = new_value return True @property def state_size(self): # This is the flattened size of @self.value_shape # Note that np.product(()) returns 1, which is also correct for a non-arrayed value return int(np.product(self.value_shape)) # For this state, we simply store its value. def _dump_state(self): return {self.value_name: self._get_value()} def _load_state(self, state): self._set_value(state[self.value_name]) def _serialize(self, state): # If the state value is not an iterable, wrap it in a numpy array val = state[self.value_name] if isinstance(state[self.value_name], np.ndarray) else np.array([state[self.value_name]]) return val.flatten().astype(float) def _deserialize(self, state): value_length = int(np.product(self.value_shape)) value = state[:value_length].reshape(self.value_shape) if len(self.value_shape) > 0 else state[0] return {self.value_name: value}, value_length @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("TensorizedValueState") return classes
6,878
Python
33.395
126
0.631288
StanfordVL/OmniGibson/omnigibson/object_states/inside.py
import numpy as np import omnigibson as og from omnigibson.object_states.aabb import AABB from omnigibson.object_states.adjacency import HorizontalAdjacency, VerticalAdjacency, flatten_planes from omnigibson.object_states.kinematics_mixin import KinematicsMixin from omnigibson.object_states.object_state_base import BooleanStateMixin, RelativeObjectState from omnigibson.utils.object_state_utils import sample_kinematics from omnigibson.utils.constants import PrimType from omnigibson.utils.object_state_utils import m as os_m class Inside(RelativeObjectState, KinematicsMixin, BooleanStateMixin): @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.update({AABB, HorizontalAdjacency, VerticalAdjacency}) return deps def _set_value(self, other, new_value, reset_before_sampling=False): if not new_value: raise NotImplementedError("Inside does not support set_value(False)") if other.prim_type == PrimType.CLOTH: raise ValueError("Cannot set an object inside a cloth object.") state = og.sim.dump_state(serialized=False) # Possibly reset this object if requested if reset_before_sampling: self.obj.reset() for _ in range(os_m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS): if sample_kinematics("inside", self.obj, other) and self.get_value(other): return True else: og.sim.load_state(state, serialized=False) return False def _get_value(self, other): if other.prim_type == PrimType.CLOTH: raise ValueError("Cannot detect if an object is inside a cloth object.") # First check that the inner object's position is inside the outer's AABB. # Since we usually check for a small set of outer objects, this is cheap aabb_lower, aabb_upper = self.obj.states[AABB].get_value() inner_object_pos = (aabb_lower + aabb_upper) / 2.0 outer_object_aabb_lo, outer_object_aabb_hi = other.states[AABB].get_value() if not (np.less_equal(outer_object_aabb_lo, inner_object_pos).all() and np.less_equal(inner_object_pos, outer_object_aabb_hi).all()): return False # Our definition of inside: an object A is inside an object B if there # exists a 3-D coordinate space in which object B can be found on both # sides of object A in at least 2 out of 3 of the coordinate axes. To # check this, we sample a bunch of coordinate systems (for the sake of # simplicity, all have their 3rd axes aligned with the Z axis but the # 1st and 2nd axes are free. vertical_adjacency = self.obj.states[VerticalAdjacency].get_value() horizontal_adjacency = self.obj.states[HorizontalAdjacency].get_value() # First, check if the body can be found on both sides in Z on_both_sides_Z = other in vertical_adjacency.negative_neighbors and other in vertical_adjacency.positive_neighbors if on_both_sides_Z: # If the object is on both sides of Z, we already found 1 axis, so just # find another axis where the object is on both sides. on_both_sides_in_any_axis = any( other in adjacency_list.positive_neighbors and other in adjacency_list.negative_neighbors for adjacency_list in flatten_planes(horizontal_adjacency) ) return on_both_sides_in_any_axis # If the object was not on both sides of Z, then we need to look at each # plane and try to find one where the object is on both sides of both # axes in that plane. on_both_sides_of_both_axes_in_any_plane = any( other in adjacency_list_by_axis[0].positive_neighbors and other in adjacency_list_by_axis[0].negative_neighbors and other in adjacency_list_by_axis[1].positive_neighbors and other in adjacency_list_by_axis[1].negative_neighbors for adjacency_list_by_axis in horizontal_adjacency ) return on_both_sides_of_both_axes_in_any_plane
4,157
Python
47.917646
141
0.674044
StanfordVL/OmniGibson/omnigibson/object_states/temperature.py
import numpy as np from omnigibson.macros import create_module_macros from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink from omnigibson.object_states.aabb import AABB from omnigibson.object_states.tensorized_value_state import TensorizedValueState import omnigibson as og from omnigibson.utils.python_utils import classproperty # Create settings for this module m = create_module_macros(module_path=__file__) # TODO: Consider sourcing default temperature from scene # Default ambient temperature. m.DEFAULT_TEMPERATURE = 23.0 # degrees Celsius # What fraction of the temperature difference with the default temperature should be decayed every step. m.TEMPERATURE_DECAY_SPEED = 0.02 # per second. We'll do the conversion to steps later. class Temperature(TensorizedValueState): def __init__(self, obj): # Run super first super(Temperature, self).__init__(obj) # Set value to be default self._set_value(m.DEFAULT_TEMPERATURE) @classmethod def update_temperature_from_heatsource_or_sink(cls, objs, temperature, rate): """ Updates @objs' internal temperatures based on @temperature and @rate Args: objs (Iterable of StatefulObject): Objects whose temperatures should be updated temperature (float): Heat source / sink temperature rate (float): Heating rate of the source / sink """ # Get idxs for objs idxs = [cls.OBJ_IDXS[obj.name] for obj in objs] cls.VALUES[idxs] += (temperature - cls.VALUES[idxs]) * rate * og.sim.get_rendering_dt() @classmethod def get_dependencies(cls): deps = super().get_dependencies() deps.add(AABB) return deps @classmethod def get_optional_dependencies(cls): deps = super().get_optional_dependencies() deps.add(HeatSourceOrSink) return deps @classmethod def _update_values(cls, values): # Apply temperature decay return values + (m.DEFAULT_TEMPERATURE - values) * m.TEMPERATURE_DECAY_SPEED * og.sim.get_rendering_dt() @classproperty def value_name(cls): return "temperature"
2,179
Python
33.603174
112
0.692061
StanfordVL/OmniGibson/omnigibson/objects/usd_object.py
import os import tempfile import omnigibson as og from omnigibson.objects.stateful_object import StatefulObject from omnigibson.utils.constants import PrimType from omnigibson.utils.usd_utils import add_asset_to_stage from omnigibson.utils.asset_utils import decrypt_file class USDObject(StatefulObject): """ USDObjects are instantiated from a USD file. They can be composed of one or more links and joints. They may or may not be passive. """ def __init__( self, name, usd_path, encrypted=False, prim_path=None, category="object", uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, kinematic_only=None, self_collisions=False, prim_type=PrimType.RIGID, load_config=None, abilities=None, include_default_states=True, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene usd_path (str): global path to the USD file to load encrypted (bool): whether this file is encrypted (and should therefore be decrypted) or not prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria are satisfied (see object_base.py post_load function), else False. self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. include_default_states (bool): whether to include the default object states from @get_default_states kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). Note that this base object does NOT pass kwargs down into the Prim-type super() classes, and we assume that kwargs are only shared between all SUBclasses (children), not SUPERclasses (parents). """ self._usd_path = usd_path self._encrypted = encrypted super().__init__( prim_path=prim_path, name=name, category=category, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, kinematic_only=kinematic_only, self_collisions=self_collisions, prim_type=prim_type, include_default_states=include_default_states, load_config=load_config, abilities=abilities, **kwargs, ) def _load(self): """ Load the object into pybullet and set it to the correct pose """ usd_path = self._usd_path if self._encrypted: # Create a temporary file to store the decrytped asset, load it, and then delete it encrypted_filename = self._usd_path.replace(".usd", ".encrypted.usd") usd_path = self._usd_path.replace(".usd", f".{self.uuid}.usd") decrypt_file(encrypted_filename, usd_path) prim = add_asset_to_stage(asset_path=usd_path, prim_path=self._prim_path) if self._encrypted: # On Windows, Isaac Sim won't let go of the file until the prim is removed, so we can't delete it. if os.name == "posix": os.remove(usd_path) return prim def _create_prim_with_same_kwargs(self, prim_path, name, load_config): # Add additional kwargs return self.__class__( prim_path=prim_path, usd_path=self._usd_path, name=name, category=self.category, scale=self.scale, visible=self.visible, fixed_base=self.fixed_base, visual_only=self._visual_only, prim_type=self._prim_type, load_config=load_config, abilities=self._abilities, ) @property def usd_path(self): """ Returns: str: absolute path to this model's USD file. By default, this is the loaded usd path passed in as an argument """ return self._usd_path
5,930
Python
43.593985
120
0.615683
StanfordVL/OmniGibson/omnigibson/objects/stateful_object.py
import sys from collections import defaultdict import numpy as np from bddl.object_taxonomy import ObjectTaxonomy import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import create_module_macros, gm from omnigibson.object_states.factory import ( get_default_states, get_state_name, get_requirements_for_ability, get_states_for_ability, get_states_by_dependency_order, get_texture_change_states, get_fire_states, get_steam_states, get_visual_states, get_texture_change_priority, ) from omnigibson.object_states.object_state_base import REGISTERED_OBJECT_STATES from omnigibson.object_states.heat_source_or_sink import HeatSourceOrSink from omnigibson.object_states.on_fire import OnFire from omnigibson.object_states.particle_modifier import ParticleRemover from omnigibson.objects.object_base import BaseObject from omnigibson.renderer_settings.renderer_settings import RendererSettings from omnigibson.utils.constants import PrimType, EmitterType from omnigibson.utils.python_utils import classproperty, extract_class_init_kwargs_from_dict from omnigibson.object_states import Saturated from omnigibson.utils.ui_utils import create_module_logger # Create module logger log = create_module_logger(module_name=__name__) OBJECT_TAXONOMY = ObjectTaxonomy() # Create settings for this module m = create_module_macros(module_path=__file__) m.STEAM_EMITTER_SIZE_RATIO = [0.8, 0.8, 0.4] # (x,y,z) scale of generated steam relative to its object, range [0, inf) m.STEAM_EMITTER_DENSITY_CELL_RATIO = 0.1 # scale of steam density relative to its object, range [0, inf) m.STEAM_EMITTER_HEIGHT_RATIO = 0.6 # z-height of generated steam relative to its object's native height, range [0, inf) m.FIRE_EMITTER_HEIGHT_RATIO = 0.4 # z-height of generated fire relative to its object's native height, range [0, inf) class FlowEmitterLayerRegistry: """ Registry for flow emitter layers. This is used to ensure that all flow emitters are placed on unique layers, so that they do not interfere with each other. """ def __init__(self): self._layer = 0 def __call__(self): self._layer += 1 return self._layer LAYER_REGISTRY = FlowEmitterLayerRegistry() class StatefulObject(BaseObject): """Objects that support object states.""" def __init__( self, name, prim_path=None, category="object", uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, kinematic_only=None, self_collisions=False, prim_type=PrimType.RIGID, load_config=None, abilities=None, include_default_states=True, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria are satisfied (see object_base.py post_load function), else False. self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. include_default_states (bool): whether to include the default object states from @get_default_states kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Values that will be filled later self._states = None self._emitters = dict() self._visual_states = None self._current_texture_state = None self._include_default_states = include_default_states # Load abilities from taxonomy if needed & possible if abilities is None: abilities = {} taxonomy_class = OBJECT_TAXONOMY.get_synset_from_category(category) if taxonomy_class is not None: abilities = OBJECT_TAXONOMY.get_abilities(taxonomy_class) assert isinstance(abilities, dict), "Object abilities must be in dictionary form." self._abilities = abilities # Run super init super().__init__( prim_path=prim_path, name=name, category=category, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, kinematic_only=kinematic_only, self_collisions=self_collisions, prim_type=prim_type, load_config=load_config, **kwargs, ) def _post_load(self): # Run super first super()._post_load() # Prepare the object states self._states = {} self.prepare_object_states() def _initialize(self): # Run super first super()._initialize() # Initialize all states for state in self._states.values(): state.initialize() # Check whether this object requires any visual updates states_set = set(self.states) self._visual_states = states_set & get_visual_states() # If we require visual updates, possibly create additional APIs if len(self._visual_states) > 0: if len(states_set & get_steam_states()) > 0: self._create_emitter_apis(EmitterType.STEAM) if len(states_set & get_fire_states()) > 0: self._create_emitter_apis(EmitterType.FIRE) def add_state(self, state): """ Adds state @state with name @name to self.states. Args: state (ObjectStateBase): Object state instance to add to this object """ assert self._states is not None, "Cannot add state since states have not been initialized yet!" assert state.__class__ not in self._states, f"State {state.__class__.__name__} " \ f"has already been added to this object!" self._states[state.__class__] = state @property def states(self): """ Get the current states of this object. Returns: dict: Keyword-mapped states for this object """ return self._states @property def abilities(self): """ Returns: dict: Dictionary mapping ability name to ability arguments for this object """ return self._abilities def prepare_object_states(self): """ Prepare the state dictionary for an object by generating the appropriate object state instances. This uses the abilities of the object and the state dependency graph to find & instantiate all relevant states. """ states_info = {state_type: {"ability": None, "params": dict()} for state_type in get_default_states()} if \ self._include_default_states else dict() # Map the state type (class) to ability name and params if gm.ENABLE_OBJECT_STATES: for ability in tuple(self._abilities.keys()): # First, sanity check all ability requirements compatible = True for requirement in get_requirements_for_ability(ability): compatible, reason = requirement.is_compatible(obj=self) if not compatible: # Print out warning and pop ability log.warning(f"Ability '{ability}' is incompatible with obj {self.name}, " f"because requirement {requirement.__name__} was not met. Reason: {reason}") self._abilities.pop(ability) break if compatible: params = self._abilities[ability] for state_type in get_states_for_ability(ability): states_info[state_type] = {"ability": ability, "params": state_type.postprocess_ability_params(params)} # Add the dependencies into the list, too, and sort based on the dependency chain # Must iterate over explicit tuple since dictionary changes size mid-iteration for state_type in tuple(states_info.keys()): # Add each state's dependencies, too. Note that only required dependencies are explicitly added, but both # required AND optional dependencies are checked / sorted for dependency in state_type.get_dependencies(): if dependency not in states_info: states_info[dependency] = {"ability": None, "params": dict()} # Iterate over all sorted state types, generating the states in topological order. self._states = dict() for state_type in get_states_by_dependency_order(states=states_info): # Skip over any types that are not in our info dict -- these correspond to optional dependencies if state_type not in states_info: continue relevant_params = extract_class_init_kwargs_from_dict(cls=state_type, dic=states_info[state_type]["params"], copy=False) compatible, reason = state_type.is_compatible(obj=self, **relevant_params) if compatible: self._states[state_type] = state_type(obj=self, **relevant_params) else: log.warning(f"State {state_type.__name__} is incompatible with obj {self.name}. Reason: {reason}") # Remove the ability if it exists # Note that the object may still have some of the states related to the desired ability. In this way, # we guarantee that the existence of a certain ability in self.abilities means at ALL corresponding # object state dependencies are met by the underlying object asset ability = states_info[state_type]["ability"] if ability in self._abilities: self._abilities.pop(ability) def _create_emitter_apis(self, emitter_type): """ Create necessary prims and apis for steam effects. Args: emitter_type (EmitterType): Emitter to create """ # Make sure that flow setting is enabled. renderer_setting = RendererSettings() renderer_setting.common_settings.flow_settings.enable() # Specify emitter config. emitter_config = {} bbox_extent_local = self.native_bbox if hasattr(self, "native_bbox") else self.aabb_extent / self.scale if emitter_type == EmitterType.FIRE: fire_at_metalink = True if OnFire in self.states: # Note whether the heat source link is explicitly set link = self.states[OnFire].link fire_at_metalink = link != self.root_link elif HeatSourceOrSink in self.states: # Only apply fire to non-root-link (i.e.: explicitly specified) heat source links # Otherwise, immediately return link = self.states[HeatSourceOrSink].link if link == self.root_link: return else: raise ValueError("Unknown fire state") emitter_config["name"] = "flowEmitterSphere" emitter_config["type"] = "FlowEmitterSphere" emitter_config["position"] = (0.0, 0.0, 0.0) if fire_at_metalink \ else (0.0, 0.0, bbox_extent_local[2] * m.FIRE_EMITTER_HEIGHT_RATIO) emitter_config["fuel"] = 0.6 emitter_config["coupleRateFuel"] = 1.2 emitter_config["buoyancyPerTemp"] = 0.04 emitter_config["burnPerTemp"] = 4 emitter_config["gravity"] = (0, 0, -60.0) emitter_config["constantMask"] = 5.0 emitter_config["attenuation"] = 0.5 elif emitter_type == EmitterType.STEAM: link = self.root_link emitter_config["name"] = "flowEmitterBox" emitter_config["type"] = "FlowEmitterBox" emitter_config["position"] = (0.0, 0.0, bbox_extent_local[2] * m.STEAM_EMITTER_HEIGHT_RATIO) emitter_config["fuel"] = 1.0 emitter_config["coupleRateFuel"] = 0.5 emitter_config["buoyancyPerTemp"] = 0.05 emitter_config["burnPerTemp"] = 0.5 emitter_config["gravity"] = (0, 0, -50.0) emitter_config["constantMask"] = 10.0 emitter_config["attenuation"] = 1.5 else: raise ValueError("Currently, only EmitterTypes FIRE and STEAM are supported!") # Define prim paths. # The flow system is created under the root link so that it automatically updates its pose as the object moves flowEmitter_prim_path = f"{link.prim_path}/{emitter_config['name']}" flowSimulate_prim_path = f"{link.prim_path}/flowSimulate" flowOffscreen_prim_path = f"{link.prim_path}/flowOffscreen" flowRender_prim_path = f"{link.prim_path}/flowRender" # Define prims. stage = og.sim.stage emitter = stage.DefinePrim(flowEmitter_prim_path, emitter_config["type"]) simulate = stage.DefinePrim(flowSimulate_prim_path, "FlowSimulate") offscreen = stage.DefinePrim(flowOffscreen_prim_path, "FlowOffscreen") renderer = stage.DefinePrim(flowRender_prim_path, "FlowRender") advection = stage.DefinePrim(flowSimulate_prim_path + "/advection", "FlowAdvectionCombustionParams") smoke = stage.DefinePrim(flowSimulate_prim_path + "/advection/smoke", "FlowAdvectionCombustionParams") vorticity = stage.DefinePrim(flowSimulate_prim_path + "/vorticity", "FlowVorticityParams") rayMarch = stage.DefinePrim(flowRender_prim_path + "/rayMarch", "FlowRayMarchParams") colormap = stage.DefinePrim(flowOffscreen_prim_path + "/colormap", "FlowRayMarchColormapParams") self._emitters[emitter_type] = emitter layer_number = LAYER_REGISTRY() # Update emitter general settings. emitter.CreateAttribute("enabled", lazy.pxr.Sdf.ValueTypeNames.Bool, False).Set(False) emitter.CreateAttribute("position", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set(emitter_config["position"]) emitter.CreateAttribute("fuel", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["fuel"]) emitter.CreateAttribute("coupleRateFuel", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["coupleRateFuel"]) emitter.CreateAttribute("coupleRateVelocity", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(2.0) emitter.CreateAttribute("velocity", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set((0, 0, 0)) emitter.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) simulate.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) offscreen.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) renderer.CreateAttribute("layer", lazy.pxr.Sdf.ValueTypeNames.Int, False).Set(layer_number) advection.CreateAttribute("buoyancyPerTemp", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["buoyancyPerTemp"]) advection.CreateAttribute("burnPerTemp", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["burnPerTemp"]) advection.CreateAttribute("gravity", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set(emitter_config["gravity"]) vorticity.CreateAttribute("constantMask", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["constantMask"]) rayMarch.CreateAttribute("attenuation", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(emitter_config["attenuation"]) # Update emitter unique settings. if emitter_type == EmitterType.FIRE: # Radius is in the absolute world coordinate even though the fire is under the link frame. # In other words, scaling the object doesn't change the fire radius. if fire_at_metalink: # TODO: get radius of heat_source_link from metadata. radius = 0.05 else: bbox_extent_world = self.native_bbox * self.scale if hasattr(self, "native_bbox") else self.aabb_extent # Radius is the average x-y half-extent of the object radius = float(np.mean(bbox_extent_world[:2]) / 2.0) emitter.CreateAttribute("radius", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(radius) simulate.CreateAttribute("densityCellSize", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(radius*0.2) smoke.CreateAttribute("fade", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(2.0) # Set fire colormap. rgbaPoints = [] rgbaPoints.append(lazy.pxr.Gf.Vec4f(0.0154, 0.0177, 0.0154, 0.004902)) rgbaPoints.append(lazy.pxr.Gf.Vec4f(0.03575, 0.03575, 0.03575, 0.504902)) rgbaPoints.append(lazy.pxr.Gf.Vec4f(0.03575, 0.03575, 0.03575, 0.504902)) rgbaPoints.append(lazy.pxr.Gf.Vec4f(1, 0.1594, 0.0134, 0.8)) rgbaPoints.append(lazy.pxr.Gf.Vec4f(13.53, 2.99, 0.12599, 0.8)) rgbaPoints.append(lazy.pxr.Gf.Vec4f(78, 39, 6.1, 0.7)) colormap.CreateAttribute("rgbaPoints", lazy.pxr.Sdf.ValueTypeNames.Float4Array, False).Set(rgbaPoints) elif emitter_type == EmitterType.STEAM: emitter.CreateAttribute("halfSize", lazy.pxr.Sdf.ValueTypeNames.Float3, False).Set( tuple(bbox_extent_local * np.array(m.STEAM_EMITTER_SIZE_RATIO) / 2.0)) simulate.CreateAttribute("densityCellSize", lazy.pxr.Sdf.ValueTypeNames.Float, False).Set(bbox_extent_local[2] * m.STEAM_EMITTER_DENSITY_CELL_RATIO) def set_emitter_enabled(self, emitter_type, value): """ Enable/disable the emitter prim for fire/steam effect. Args: emitter_type (EmitterType): Emitter to set value (bool): Value to set """ if emitter_type not in self._emitters: return if value != self._emitters[emitter_type].GetAttribute("enabled").Get(): self._emitters[emitter_type].GetAttribute("enabled").Set(value) def get_textures(self): """ Gets prim's texture files. Returns: list of str: List of texture file paths """ return [material.diffuse_texture for material in self.materials if material.diffuse_texture is not None] def update_visuals(self): """ Update the prim's visuals (texture change, steam/fire effects, etc). Should be called after all the states are updated. """ if len(self._visual_states) > 0: texture_change_states = [] emitter_enabled = defaultdict(bool) for state_type in self._visual_states: state = self.states[state_type] if state_type in get_texture_change_states(): if state_type == Saturated: for particle_system in ParticleRemover.supported_active_systems.values(): if state.get_value(particle_system): texture_change_states.append(state) # Only need to do this once, since soaked handles all fluid systems break elif state.get_value(): texture_change_states.append(state) if state_type in get_steam_states(): emitter_enabled[EmitterType.STEAM] |= state.get_value() if state_type in get_fire_states(): emitter_enabled[EmitterType.FIRE] |= state.get_value() for emitter_type in emitter_enabled: self.set_emitter_enabled(emitter_type, emitter_enabled[emitter_type]) texture_change_states.sort(key=lambda s: get_texture_change_priority()[s.__class__]) object_state = texture_change_states[-1] if len(texture_change_states) > 0 else None # Only update our texture change if it's a different object state than the one we already have if object_state != self._current_texture_state: self._update_texture_change(object_state) self._current_texture_state = object_state def _update_texture_change(self, object_state): """ Update the texture based on the given object_state. E.g. if object_state is Frozen, update the diffuse color to match the frozen state. If object_state is None, update the diffuse color to the default value. It modifies the current albedo map by adding and scaling the values. See @self._update_albedo_value for details. Args: object_state (BooleanStateMixin or None): the object state that the diffuse color should match to """ for material in self.materials: self._update_albedo_value(object_state, material) @staticmethod def _update_albedo_value(object_state, material): """ Update the albedo value based on the given object_state. The final albedo value is albedo_value = diffuse_tint * (albedo_value + albedo_add) Args: object_state (BooleanStateMixin or None): the object state that the diffuse color should match to material (MaterialPrim): the material to use to update the albedo value """ if object_state is None: # This restore the albedo map to its original value albedo_add = 0.0 diffuse_tint = (1.0, 1.0, 1.0) else: # Query the object state for the parameters albedo_add, diffuse_tint = object_state.get_texture_change_params() if material.is_glass: if not np.allclose(material.glass_color, diffuse_tint): material.glass_color = diffuse_tint else: if material.albedo_add != albedo_add: material.albedo_add = albedo_add if not np.allclose(material.diffuse_tint, diffuse_tint): material.diffuse_tint = diffuse_tint def remove(self): # Run super super().remove() # Iterate over all states and run their remove call for state_instance in self._states.values(): state_instance.remove() def _dump_state(self): # Grab state from super class state = super()._dump_state() # Also add non-kinematic states non_kin_states = dict() for state_type, state_instance in self._states.items(): if state_instance.stateful: non_kin_states[get_state_name(state_type)] = state_instance.dump_state(serialized=False) state["non_kin"] = non_kin_states return state def _load_state(self, state): # Call super method first super()._load_state(state=state) # Load non-kinematic states self.load_non_kin_state(state) def load_non_kin_state(self, state): # Load all states that are stateful for state_type, state_instance in self._states.items(): state_name = get_state_name(state_type) if state_instance.stateful: if state_name in state["non_kin"]: state_instance.load_state(state=state["non_kin"][state_name], serialized=False) else: log.warning(f"Missing object state [{state_name}] in the state dump for obj {self.name}") # Clear cache after loading state self.clear_states_cache() def _serialize(self, state): # Call super method first state_flat = super()._serialize(state=state) # Iterate over all states and serialize them individually non_kin_state_flat = np.concatenate([ self._states[REGISTERED_OBJECT_STATES[state_name]].serialize(state_dict) for state_name, state_dict in state["non_kin"].items() ]) if len(state["non_kin"]) > 0 else np.array([]) # Combine these two arrays return np.concatenate([state_flat, non_kin_state_flat]).astype(float) def _deserialize(self, state): # Call super method first state_dic, idx = super()._deserialize(state=state) # Iterate over all states and deserialize their states if they're stateful non_kin_state_dic = dict() for state_type, state_instance in self._states.items(): state_name = get_state_name(state_type) if state_instance.stateful: non_kin_state_dic[state_name] = state_instance.deserialize(state[idx:idx+state_instance.state_size]) idx += state_instance.state_size state_dic["non_kin"] = non_kin_state_dic return state_dic, idx def clear_states_cache(self): """ Clears the internal cache from all owned states """ # Check self._states just in case states have not been initialized yet. if not self._states: return for _, obj_state in self._states.items(): obj_state.clear_cache() def set_position_orientation(self, position=None, orientation=None): super().set_position_orientation(position=position, orientation=orientation) self.clear_states_cache() @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("StatefulObject") return classes
27,486
Python
46.970332
160
0.625446
StanfordVL/OmniGibson/omnigibson/objects/light_object.py
import omnigibson as og import omnigibson.lazy as lazy from omnigibson.objects.stateful_object import StatefulObject from omnigibson.prims.xform_prim import XFormPrim from omnigibson.utils.python_utils import assert_valid_key from omnigibson.utils.constants import PrimType from omnigibson.utils.ui_utils import create_module_logger import numpy as np # Create module logger log = create_module_logger(module_name=__name__) class LightObject(StatefulObject): """ LightObjects are objects that generate light in the simulation """ LIGHT_TYPES = { "Cylinder", "Disk", "Distant", "Dome", "Geometry", "Rect", "Sphere", } def __init__( self, name, light_type, prim_path=None, category="light", uuid=None, scale=None, fixed_base=False, load_config=None, abilities=None, include_default_states=True, radius=1.0, intensity=50000.0, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene light_type (str): Type of light to create. Valid options are LIGHT_TYPES prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. fixed_base (bool): whether to fix the base of this object or not load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. include_default_states (bool): whether to include the default object states from @get_default_states radius (float): Radius for this light. intensity (float): Intensity for this light. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Compose load config and add rgba values load_config = dict() if load_config is None else load_config load_config["scale"] = scale load_config["intensity"] = intensity load_config["radius"] = radius if light_type in {"Cylinder", "Disk", "Sphere"} else None # Make sure primitive type is valid assert_valid_key(key=light_type, valid_keys=self.LIGHT_TYPES, name="light_type") self.light_type = light_type # Other attributes to be filled in at runtime self._light_link = None # Run super method super().__init__( prim_path=prim_path, name=name, category=category, uuid=uuid, scale=scale, visible=True, fixed_base=fixed_base, visual_only=True, self_collisions=False, prim_type=PrimType.RIGID, include_default_states=include_default_states, load_config=load_config, abilities=abilities, **kwargs, ) def _load(self): # Define XForm and base link for this light prim = og.sim.stage.DefinePrim(self._prim_path, "Xform") base_link = og.sim.stage.DefinePrim(f"{self._prim_path}/base_link", "Xform") # Define the actual light link light_prim = getattr(lazy.pxr.UsdLux, f"{self.light_type}Light").Define(og.sim.stage, f"{self._prim_path}/base_link/light").GetPrim() return prim def _post_load(self): # run super first super()._post_load() # Grab reference to light link self._light_link = XFormPrim(prim_path=f"{self._prim_path}/base_link/light", name=f"{self.name}:light_link") # Apply Shaping API and set default cone angle attribute shaping_api = lazy.pxr.UsdLux.ShapingAPI.Apply(self._light_link.prim).GetShapingConeAngleAttr().Set(180.0) # Optionally set the intensity if self._load_config.get("intensity", None) is not None: self.intensity = self._load_config["intensity"] # Optionally set the radius if self._load_config.get("radius", None) is not None: self.radius = self._load_config["radius"] def _initialize(self): # Run super super()._initialize() # Initialize light link self._light_link.initialize() @property def aabb(self): # This is a virtual object (with no associated visual mesh), so omni returns an invalid AABB. # Therefore we instead return a hardcoded small value return np.ones(3) * -0.001, np.ones(3) * 0.001 @property def light_link(self): """ Returns: XFormPrim: Link corresponding to the light prim itself """ return self._light_link @property def radius(self): """ Gets this light's radius Returns: float: radius for this light """ return self._light_link.get_attribute("inputs:radius") @radius.setter def radius(self, radius): """ Sets this light's radius Args: radius (float): radius to set """ self._light_link.set_attribute("inputs:radius", radius) @property def intensity(self): """ Gets this light's intensity Returns: float: intensity for this light """ return self._light_link.get_attribute("inputs:intensity") @intensity.setter def intensity(self, intensity): """ Sets this light's intensity Args: intensity (float): intensity to set """ self._light_link.set_attribute( "inputs:intensity", intensity) @property def color(self): """ Gets this light's color Returns: float: color for this light """ return tuple(float(x) for x in self._light_link.get_attribute("inputs:color")) @color.setter def color(self, color): """ Sets this light's color Args: color ([float, float, float]): color to set, each value in range [0, 1] """ self._light_link.set_attribute( "inputs:color", lazy.pxr.Gf.Vec3f(color)) @property def texture_file_path(self): """ Gets this light's texture file path. Only valid for dome lights. Returns: str: texture file path for this light """ return str(self._light_link.get_attribute("inputs:texture:file")) @texture_file_path.setter def texture_file_path(self, texture_file_path): """ Sets this light's texture file path. Only valid for dome lights. Args: texture_file_path (str): path of texture file that should be used for this light """ self._light_link.set_attribute( "inputs:texture:file", lazy.pxr.Sdf.AssetPath(texture_file_path)) def _create_prim_with_same_kwargs(self, prim_path, name, load_config): # Add additional kwargs (bounding_box is already captured in load_config) return self.__class__( prim_path=prim_path, light_type=self.light_type, name=name, intensity=self.intensity, load_config=load_config, )
8,319
Python
32.821138
141
0.597548
StanfordVL/OmniGibson/omnigibson/objects/object_base.py
from abc import ABCMeta import numpy as np from collections.abc import Iterable import trimesh from scipy.spatial.transform import Rotation import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import create_module_macros, gm from omnigibson.utils.usd_utils import create_joint, CollisionAPI from omnigibson.prims.entity_prim import EntityPrim from omnigibson.utils.python_utils import Registerable, classproperty, get_uuid from omnigibson.utils.constants import PrimType, semantic_class_name_to_id from omnigibson.utils.ui_utils import create_module_logger, suppress_omni_log import omnigibson.utils.transform_utils as T # Global dicts that will contain mappings REGISTERED_OBJECTS = dict() # Create module logger log = create_module_logger(module_name=__name__) # Create settings for this module m = create_module_macros(module_path=__file__) # Settings for highlighting objects m.HIGHLIGHT_RGB = [1.0, 0.1, 0.92] # Default highlighting (R,G,B) color when highlighting objects m.HIGHLIGHT_INTENSITY = 10000.0 # Highlight intensity to apply, range [0, 10000) # Physics settings for objects -- see https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/RigidBodyDynamics.html?highlight=velocity%20iteration#solver-iterations m.DEFAULT_SOLVER_POSITION_ITERATIONS = 32 m.DEFAULT_SOLVER_VELOCITY_ITERATIONS = 1 class BaseObject(EntityPrim, Registerable, metaclass=ABCMeta): """This is the interface that all OmniGibson objects must implement.""" def __init__( self, name, prim_path=None, category="object", uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, kinematic_only=None, self_collisions=False, prim_type=PrimType.RIGID, load_config=None, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria are satisfied (see object_base.py post_load function), else False. self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). Note that this base object does NOT pass kwargs down into the Prim-type super() classes, and we assume that kwargs are only shared between all SUBclasses (children), not SUPERclasses (parents). """ # Generate default prim path if none is specified prim_path = f"/World/{name}" if prim_path is None else prim_path # Store values self.uuid = get_uuid(name) if uuid is None else uuid assert len(str(self.uuid)) <= 8, f"UUID for this object must be at max 8-digits, got: {self.uuid}" self.category = category self.fixed_base = fixed_base # Values to be created at runtime self._highlight_cached_values = None self._highlighted = None # Create load config from inputs load_config = dict() if load_config is None else load_config load_config["scale"] = np.array(scale) if isinstance(scale, Iterable) else scale load_config["visible"] = visible load_config["visual_only"] = visual_only load_config["kinematic_only"] = kinematic_only load_config["self_collisions"] = self_collisions load_config["prim_type"] = prim_type # Run super init super().__init__( prim_path=prim_path, name=name, load_config=load_config, ) # TODO: Super hacky, think of a better way to preserve this info # Update init info for this self._init_info["args"]["name"] = self.name self._init_info["args"]["uuid"] = self.uuid def load(self): # Run super method ONLY if we're not loaded yet if self.loaded: prim = self._prim else: prim = super().load() log.info(f"Loaded {self.name} at {self.prim_path}") return prim def remove(self): # Run super first super().remove() # Notify user that the object was removed log.info(f"Removed {self.name} from {self.prim_path}") def _post_load(self): # Add fixed joint or make object kinematic only if we're fixing the base kinematic_only = False if self.fixed_base: # For optimization purposes, if we only have a single rigid body that has either # (no custom scaling OR no fixed joints), we assume this is not an articulated object so we # merely set this to be a static collider, i.e.: kinematic-only # The custom scaling / fixed joints requirement is needed because omniverse complains about scaling that # occurs with respect to fixed joints, as omni will "snap" bodies together otherwise scale = np.ones(3) if self._load_config["scale"] is None else np.array(self._load_config["scale"]) if self.n_joints == 0 and (np.all(np.isclose(scale, 1.0, atol=1e-3)) or self.n_fixed_joints == 0) and (self._load_config["kinematic_only"] != False) and not self.has_attachment_points: kinematic_only = True # Validate that we didn't make a kinematic-only decision that does not match assert self._load_config["kinematic_only"] is None or kinematic_only == self._load_config["kinematic_only"], \ f"Kinematic only decision does not match! Got: {kinematic_only}, expected: {self._load_config['kinematic_only']}" # Actually apply the kinematic-only decision self._load_config["kinematic_only"] = kinematic_only # Run super first super()._post_load() # If the object is fixed_base but kinematic only is false, create the joint if self.fixed_base and not self.kinematic_only: # Create fixed joint, and set Body0 to be this object's root prim # This renders, which causes a material lookup error since we're creating a temp file, so we suppress # the error explicitly here with suppress_omni_log(channels=["omni.hydra"]): create_joint( prim_path=f"{self._prim_path}/rootJoint", joint_type="FixedJoint", body1=f"{self._prim_path}/{self._root_link_name}", ) # Delete n_fixed_joints cached property if it exists since the number of fixed joints has now changed # See https://stackoverflow.com/questions/59899732/python-cached-property-how-to-delete and # https://docs.python.org/3/library/functools.html#functools.cached_property if "n_fixed_joints" in self.__dict__: del self.n_fixed_joints # Set visibility if "visible" in self._load_config and self._load_config["visible"] is not None: self.visible = self._load_config["visible"] # First, remove any articulation root API that already exists at the object-level or root link level prim if self._prim.HasAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI): self._prim.RemoveAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI) self._prim.RemoveAPI(lazy.pxr.PhysxSchema.PhysxArticulationAPI) if self.root_prim.HasAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI): self.root_prim.RemoveAPI(lazy.pxr.UsdPhysics.ArticulationRootAPI) self.root_prim.RemoveAPI(lazy.pxr.PhysxSchema.PhysxArticulationAPI) # Potentially add articulation root APIs and also set self collisions root_prim = None if self.articulation_root_path is None else lazy.omni.isaac.core.utils.prims.get_prim_at_path(self.articulation_root_path) if root_prim is not None: lazy.pxr.UsdPhysics.ArticulationRootAPI.Apply(root_prim) lazy.pxr.PhysxSchema.PhysxArticulationAPI.Apply(root_prim) self.self_collisions = self._load_config["self_collisions"] # Set position / velocity solver iterations if we're not cloth if self._prim_type != PrimType.CLOTH: self.solver_position_iteration_count = m.DEFAULT_SOLVER_POSITION_ITERATIONS self.solver_velocity_iteration_count = m.DEFAULT_SOLVER_VELOCITY_ITERATIONS # Add semantics lazy.omni.isaac.core.utils.semantics.add_update_semantics( prim=self._prim, semantic_label=self.category, type_label="class", ) def _initialize(self): # Run super first super()._initialize() # Iterate over all links and grab their relevant material info for highlighting (i.e.: emissivity info) self._highlighted = False self._highlight_cached_values = dict() for material in self.materials: self._highlight_cached_values[material] = { "enable_emission": material.enable_emission, "emissive_color": material.emissive_color, "emissive_intensity": material.emissive_intensity, } @property def articulation_root_path(self): has_articulated_joints, has_fixed_joints = self.n_joints > 0, self.n_fixed_joints > 0 if self.kinematic_only or ((not has_articulated_joints) and (not has_fixed_joints)): # Kinematic only, or non-jointed single body objects return None elif not self.fixed_base and has_articulated_joints: # This is all remaining non-fixed objects # This is a bit hacky because omniverse is buggy # Articulation roots mess up the joint order if it's on a non-fixed base robot, e.g. a # mobile manipulator. So if we have to move it to the actual root link of the robot instead. # See https://forums.developer.nvidia.com/t/inconsistent-values-from-isaacsims-dc-get-joint-parent-child-body/201452/2 # for more info return f"{self._prim_path}/{self.root_link_name}" else: # Fixed objects that are not kinematic only, or non-fixed objects that have no articulated joints but do # have fixed joints return self._prim_path @property def mass(self): """ Returns: float: Cumulative mass of this potentially articulated object. """ mass = 0.0 for link in self._links.values(): mass += link.mass return mass @mass.setter def mass(self, mass): raise NotImplementedError("Cannot set mass directly for an object!") @property def volume(self): """ Returns: float: Cumulative volume of this potentially articulated object. """ return sum(link.volume for link in self._links.values()) @volume.setter def volume(self, volume): raise NotImplementedError("Cannot set volume directly for an object!") @property def scale(self): # Just super call return super().scale @scale.setter def scale(self, scale): # call super first # A bit esoteric -- see https://gist.github.com/Susensio/979259559e2bebcd0273f1a95d7c1e79 super(BaseObject, type(self)).scale.fset(self, scale) # Update init info for scale self._init_info["args"]["scale"] = scale @property def link_prim_paths(self): return [link.prim_path for link in self._links.values()] @property def highlighted(self): """ Returns: bool: Whether the object is highlighted or not """ return self._highlighted @highlighted.setter def highlighted(self, enabled): """ Iterates over all owned links, and modifies their materials with emissive colors so that the object is highlighted (magenta by default) Args: enabled (bool): whether the object should be highlighted or not """ # Return early if the set value matches the internal value if enabled == self._highlighted: return for material in self.materials: if enabled: # Store values before swapping self._highlight_cached_values[material] = { "enable_emission": material.enable_emission, "emissive_color": material.emissive_color, "emissive_intensity": material.emissive_intensity, } material.enable_emission = True if enabled else self._highlight_cached_values[material]["enable_emission"] material.emissive_color = m.HIGHLIGHT_RGB if enabled else self._highlight_cached_values[material]["emissive_color"] material.emissive_intensity = m.HIGHLIGHT_INTENSITY if enabled else self._highlight_cached_values[material]["emissive_intensity"] # Update internal value self._highlighted = enabled def get_base_aligned_bbox(self, link_name=None, visual=False, xy_aligned=False): """ Get a bounding box for this object that's axis-aligned in the object's base frame. Args: link_name (None or str): If specified, only get the bbox for the given link visual (bool): Whether to aggregate the bounding boxes from the visual meshes. Otherwise, will use collision meshes xy_aligned (bool): Whether to align the bounding box to the global XY-plane Returns: 4-tuple: - 3-array: (x,y,z) bbox center position in world frame - 3-array: (x,y,z,w) bbox quaternion orientation in world frame - 3-array: (x,y,z) bbox extent in desired frame - 3-array: (x,y,z) bbox center in desired frame """ # Get the base position transform. pos, orn = self.get_position_orientation() base_frame_to_world = T.pose2mat((pos, orn)) # Prepare the desired frame. if xy_aligned: # If the user requested an XY-plane aligned bbox, convert everything to that frame. # The desired frame is same as the base_com frame with its X/Y rotations removed. translate = trimesh.transformations.translation_from_matrix(base_frame_to_world) # To find the rotation that this transform does around the Z axis, we rotate the [1, 0, 0] vector by it # and then take the arctangent of its projection onto the XY plane. rotated_X_axis = base_frame_to_world[:3, 0] rotation_around_Z_axis = np.arctan2(rotated_X_axis[1], rotated_X_axis[0]) xy_aligned_base_com_to_world = trimesh.transformations.compose_matrix( translate=translate, angles=[0, 0, rotation_around_Z_axis] ) # Finally update our desired frame. desired_frame_to_world = xy_aligned_base_com_to_world else: # Default desired frame is base CoM frame. desired_frame_to_world = base_frame_to_world # Compute the world-to-base frame transform. world_to_desired_frame = np.linalg.inv(desired_frame_to_world) # Grab all the world-frame points corresponding to the object's visual or collision hulls. points_in_world = [] if self.prim_type == PrimType.CLOTH: particle_contact_offset = self.root_link.cloth_system.particle_contact_offset particle_positions = self.root_link.compute_particle_positions() particles_in_world_frame = np.concatenate([ particle_positions - particle_contact_offset, particle_positions + particle_contact_offset ], axis=0) points_in_world.extend(particles_in_world_frame) else: links = {link_name: self._links[link_name]} if link_name is not None else self._links for link_name, link in links.items(): if visual: hull_points = link.visual_boundary_points_world else: hull_points = link.collision_boundary_points_world if hull_points is not None: points_in_world.extend(hull_points) # Move the points to the desired frame points = trimesh.transformations.transform_points(points_in_world, world_to_desired_frame) # All points are now in the desired frame: either the base CoM or the xy-plane-aligned base CoM. # Now fit a bounding box to all the points by taking the minimum/maximum in the desired frame. aabb_min_in_desired_frame = np.amin(points, axis=0) aabb_max_in_desired_frame = np.amax(points, axis=0) bbox_center_in_desired_frame = (aabb_min_in_desired_frame + aabb_max_in_desired_frame) / 2 bbox_extent_in_desired_frame = aabb_max_in_desired_frame - aabb_min_in_desired_frame # Transform the center to the world frame. bbox_center_in_world = trimesh.transformations.transform_points( [bbox_center_in_desired_frame], desired_frame_to_world )[0] bbox_orn_in_world = Rotation.from_matrix(desired_frame_to_world[:3, :3]).as_quat() return bbox_center_in_world, bbox_orn_in_world, bbox_extent_in_desired_frame, bbox_center_in_desired_frame @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("BaseObject") return classes @classproperty def _cls_registry(cls): # Global robot registry global REGISTERED_OBJECTS return REGISTERED_OBJECTS
19,397
Python
45.742169
196
0.637985
StanfordVL/OmniGibson/omnigibson/objects/__init__.py
from omnigibson.objects.object_base import REGISTERED_OBJECTS, BaseObject from omnigibson.objects.controllable_object import ControllableObject from omnigibson.objects.dataset_object import DatasetObject from omnigibson.objects.light_object import LightObject from omnigibson.objects.primitive_object import PrimitiveObject from omnigibson.objects.stateful_object import StatefulObject from omnigibson.objects.usd_object import USDObject
439
Python
47.888884
73
0.879271
StanfordVL/OmniGibson/omnigibson/objects/primitive_object.py
import numpy as np from omnigibson.objects.stateful_object import StatefulObject from omnigibson.utils.python_utils import assert_valid_key import omnigibson as og import omnigibson.lazy as lazy from omnigibson.utils.constants import PrimType, PRIMITIVE_MESH_TYPES from omnigibson.utils.usd_utils import create_primitive_mesh from omnigibson.utils.render_utils import create_pbr_material 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__) # Define valid objects that can be created VALID_RADIUS_OBJECTS = {"Cone", "Cylinder", "Disk", "Sphere"} VALID_HEIGHT_OBJECTS = {"Cone", "Cylinder"} VALID_SIZE_OBJECTS = {"Cube", "Torus"} class PrimitiveObject(StatefulObject): """ PrimitiveObjects are objects defined by a single geom, e.g: sphere, mesh, cube, etc. """ def __init__( self, name, primitive_type, prim_path=None, category="object", uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, kinematic_only=None, self_collisions=False, prim_type=PrimType.RIGID, load_config=None, abilities=None, include_default_states=True, rgba=(0.5, 0.5, 0.5, 1.0), radius=None, height=None, size=None, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene primitive_type (str): type of primitive object to create. Should be one of: {"Cone", "Cube", "Cylinder", "Disk", "Plane", "Sphere", "Torus"} prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria are satisfied (see object_base.py post_load function), else False. self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor.rgba (4-array): (R, G, B, A) values to set for this object include_default_states (bool): whether to include the default object states from @get_default_states radius (None or float): If specified, sets the radius for this object. This value is scaled by @scale Note: Should only be specified if the @primitive_type is one of {"Cone", "Cylinder", "Disk", "Sphere"} height (None or float): If specified, sets the height for this object. This value is scaled by @scale Note: Should only be specified if the @primitive_type is one of {"Cone", "Cylinder"} size (None or float): If specified, sets the size for this object. This value is scaled by @scale Note: Should only be specified if the @primitive_type is one of {"Cube", "Torus"} kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Compose load config and add rgba values load_config = dict() if load_config is None else load_config load_config["color"] = np.array(rgba[:3]) load_config["opacity"] = rgba[3] load_config["radius"] = radius load_config["height"] = height load_config["size"] = size # Initialize other internal variables self._vis_geom = None self._col_geom = None self._extents = np.ones(3) # (x,y,z extents) # Make sure primitive type is valid assert_valid_key(key=primitive_type, valid_keys=PRIMITIVE_MESH_TYPES, name="primitive mesh type") self._primitive_type = primitive_type super().__init__( prim_path=prim_path, name=name, category=category, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, kinematic_only=kinematic_only, self_collisions=self_collisions, prim_type=prim_type, include_default_states=include_default_states, load_config=load_config, abilities=abilities, **kwargs, ) def _load(self): # Define an Xform at the specified path prim = og.sim.stage.DefinePrim(self._prim_path, "Xform") # Define a nested mesh corresponding to the root link for this prim base_link = og.sim.stage.DefinePrim(f"{self._prim_path}/base_link", "Xform") self._vis_geom = create_primitive_mesh(prim_path=f"{self._prim_path}/base_link/visuals", primitive_type=self._primitive_type) self._col_geom = create_primitive_mesh(prim_path=f"{self._prim_path}/base_link/collisions", primitive_type=self._primitive_type) # Add collision API to collision geom lazy.pxr.UsdPhysics.CollisionAPI.Apply(self._col_geom.GetPrim()) lazy.pxr.UsdPhysics.MeshCollisionAPI.Apply(self._col_geom.GetPrim()) lazy.pxr.PhysxSchema.PhysxCollisionAPI.Apply(self._col_geom.GetPrim()) # Create a material for this object for the base link og.sim.stage.DefinePrim(f"{self._prim_path}/Looks", "Scope") mat_path = f"{self._prim_path}/Looks/default" mat = create_pbr_material(prim_path=mat_path) bind_material(prim_path=self._vis_geom.GetPrim().GetPrimPath().pathString, material_path=mat_path) return prim def _post_load(self): # Possibly set scalings (only if the scale value is not set) if self._load_config["scale"] is not None: log.warning("Custom scale specified for primitive object, so ignoring radius, height, and size arguments!") else: if self._load_config["radius"] is not None: self.radius = self._load_config["radius"] if self._load_config["height"] is not None: self.height = self._load_config["height"] if self._load_config["size"] is not None: self.size = self._load_config["size"] # This step might will perform cloth remeshing if self._prim_type == PrimType.CLOTH. # Therefore, we need to apply size, radius, and height before this to scale the points properly. super()._post_load() # Cloth primitive does not have collision meshes if self._prim_type != PrimType.CLOTH: # Set the collision approximation appropriately if self._primitive_type == "Sphere": col_approximation = "boundingSphere" elif self._primitive_type == "Cube": col_approximation = "boundingCube" else: col_approximation = "convexHull" self.root_link.collision_meshes["collisions"].set_collision_approximation(col_approximation) def _initialize(self): # Run super first super()._initialize() # Set color and opacity if self._prim_type == PrimType.RIGID: visual_geom_prim = list(self.root_link.visual_meshes.values())[0] elif self._prim_type == PrimType.CLOTH: visual_geom_prim = self.root_link else: raise ValueError("Prim type must either be PrimType.RIGID or PrimType.CLOTH for loading a primitive object") visual_geom_prim.color = self._load_config["color"] visual_geom_prim.opacity = self._load_config["opacity"] @property def radius(self): """ Gets this object's radius, if it exists. Note: Can only be called if the primitive type is one of {"Cone", "Cylinder", "Disk", "Sphere"} Returns: float: radius for this object """ assert_valid_key(key=self._primitive_type, valid_keys=VALID_RADIUS_OBJECTS, name="primitive object with radius") return self._extents[0] / 2.0 @radius.setter def radius(self, radius): """ Sets this object's radius Note: Can only be called if the primitive type is one of {"Cone", "Cylinder", "Disk", "Sphere"} Args: radius (float): radius to set """ assert_valid_key(key=self._primitive_type, valid_keys=VALID_RADIUS_OBJECTS, name="primitive object with radius") # Update the extents variable original_extent = np.array(self._extents) self._extents = np.ones(3) * radius * 2.0 if self._primitive_type == "Sphere" else \ np.array([radius * 2.0, radius * 2.0, self._extents[2]]) attr_pairs = [] for geom in self._vis_geom, self._col_geom: if geom is not None: for attr in (geom.GetPointsAttr(), geom.GetNormalsAttr()): vals = np.array(attr.Get()).astype(np.float64) attr_pairs.append([attr, vals]) geom.GetExtentAttr().Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*(-self._extents / 2.0)), lazy.pxr.Gf.Vec3f(*(self._extents / 2.0))])) # Calculate how much to scale extents by and then modify the points / normals accordingly scaling_factor = 2.0 * radius / original_extent[0] for attr, vals in attr_pairs: # If this is a sphere, modify all 3 axes if self._primitive_type == "Sphere": vals = vals * scaling_factor # Otherwise, just modify the first two dimensions else: vals[:, :2] = vals[:, :2] * scaling_factor # Set the value attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*v) for v in vals])) @property def height(self): """ Gets this object's height, if it exists. Note: Can only be called if the primitive type is one of {"Cone", "Cylinder"} Returns: float: height for this object """ assert_valid_key(key=self._primitive_type, valid_keys=VALID_HEIGHT_OBJECTS, name="primitive object with height") return self._extents[2] @height.setter def height(self, height): """ Sets this object's height Note: Can only be called if the primitive type is one of {"Cone", "Cylinder"} Args: height (float): height to set """ assert_valid_key(key=self._primitive_type, valid_keys=VALID_HEIGHT_OBJECTS, name="primitive object with height") # Update the extents variable original_extent = np.array(self._extents) self._extents[2] = height # Calculate the correct scaling factor and scale the points and normals appropriately scaling_factor = height / original_extent[2] for geom in self._vis_geom, self._col_geom: if geom is not None: for attr in (geom.GetPointsAttr(), geom.GetNormalsAttr()): vals = np.array(attr.Get()).astype(np.float64) # Scale the z axis by the scaling factor vals[:, 2] = vals[:, 2] * scaling_factor attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*v) for v in vals])) geom.GetExtentAttr().Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*(-self._extents / 2.0)), lazy.pxr.Gf.Vec3f(*(self._extents / 2.0))])) @property def size(self): """ Gets this object's size, if it exists. Note: Can only be called if the primitive type is one of {"Cube", "Torus"} Returns: float: size for this object """ assert_valid_key(key=self._primitive_type, valid_keys=VALID_SIZE_OBJECTS, name="primitive object with size") return self._extents[0] @size.setter def size(self, size): """ Sets this object's size Note: Can only be called if the primitive type is one of {"Cube", "Torus"} Args: size (float): size to set """ assert_valid_key(key=self._primitive_type, valid_keys=VALID_SIZE_OBJECTS, name="primitive object with size") # Update the extents variable original_extent = np.array(self._extents) self._extents = np.ones(3) * size # Calculate the correct scaling factor and scale the points and normals appropriately scaling_factor = size / original_extent[0] for geom in self._vis_geom, self._col_geom: if geom is not None: for attr in (geom.GetPointsAttr(), geom.GetNormalsAttr()): # Scale all three axes by the scaling factor vals = np.array(attr.Get()).astype(np.float64) * scaling_factor attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*v) for v in vals])) geom.GetExtentAttr().Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*(-self._extents / 2.0)), lazy.pxr.Gf.Vec3f(*(self._extents / 2.0))])) def _create_prim_with_same_kwargs(self, prim_path, name, load_config): # Add additional kwargs (bounding_box is already captured in load_config) return self.__class__( prim_path=prim_path, primitive_type=self._primitive_type, name=name, category=self.category, scale=self.scale, visible=self.visible, fixed_base=self.fixed_base, prim_type=self._prim_type, load_config=load_config, abilities=self._abilities, visual_only=self._visual_only, ) def _dump_state(self): state = super()._dump_state() # state["extents"] = self._extents state["radius"] = self.radius if self._primitive_type in VALID_RADIUS_OBJECTS else -1 state["height"] = self.height if self._primitive_type in VALID_HEIGHT_OBJECTS else -1 state["size"] = self.size if self._primitive_type in VALID_SIZE_OBJECTS else -1 return state def _load_state(self, state): super()._load_state(state=state) # self._extents = np.array(state["extents"]) if self._primitive_type in VALID_RADIUS_OBJECTS: self.radius = state["radius"] if self._primitive_type in VALID_HEIGHT_OBJECTS: self.height = state["height"] if self._primitive_type in VALID_SIZE_OBJECTS: self.size = state["size"] def _deserialize(self, state): state_dict, idx = super()._deserialize(state=state) # state_dict["extents"] = state[idx: idx + 3] state_dict["radius"] = state[idx] state_dict["height"] = state[idx + 1] state_dict["size"] = state[idx + 2] return state_dict, idx + 3 def _serialize(self, state): # Run super first state_flat = super()._serialize(state=state) return np.concatenate([ state_flat, np.array([state["radius"], state["height"], state["size"]]), ]).astype(float)
16,539
Python
44.690608
153
0.612673
StanfordVL/OmniGibson/omnigibson/objects/dataset_object.py
import math import os import numpy as np import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import gm from omnigibson.objects.usd_object import USDObject from omnigibson.utils.constants import AVERAGE_CATEGORY_SPECS, DEFAULT_JOINT_FRICTION, SPECIAL_JOINT_FRICTIONS, JointType import omnigibson.utils.transform_utils as T from omnigibson.utils.asset_utils import get_all_object_category_models from omnigibson.utils.constants import PrimType from omnigibson.macros import gm, create_module_macros 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__) # A lower bound is needed in order to consistently trigger contacts m.MIN_OBJ_MASS = 0.4 class DatasetObject(USDObject): """ DatasetObjects are instantiated from a USD file. It is an object that is assumed to come from an iG-supported dataset. These objects should contain additional metadata, including aggregate statistics across the object's category, e.g., avg dims, bounding boxes, masses, etc. """ def __init__( self, name, prim_path=None, category="object", model=None, uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, kinematic_only=None, self_collisions=False, prim_type=PrimType.RIGID, load_config=None, abilities=None, include_default_states=True, bounding_box=None, in_rooms=None, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". model (None or str): If specified, this is used in conjunction with @category to infer the usd filepath to load for this object, which evaluates to the following: {og_dataset_path}/objects/{category}/{model}/usd/{model}.usd Otherwise, will randomly sample a model given @category uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) kinematic_only (None or bool): Whether this object should be kinematic only (and not get affected by any collisions). If None, then this value will be set to True if @fixed_base is True and some other criteria are satisfied (see object_base.py post_load function), else False. self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. include_default_states (bool): whether to include the default object states from @get_default_states bounding_box (None or 3-array): If specified, will scale this object such that it fits in the desired (x,y,z) object-aligned bounding box. Note that EITHER @bounding_box or @scale may be specified -- not both! in_rooms (None or str or list): If specified, sets the room(s) that this object should belong to. Either a list of room type(s) or a single room type kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Store variables if isinstance(in_rooms, str): assert "," not in in_rooms self._in_rooms = [in_rooms] if isinstance(in_rooms, str) else in_rooms # Make sure only one of bounding_box and scale are specified if bounding_box is not None and scale is not None: raise Exception("You cannot define both scale and bounding box size for an DatasetObject") # Add info to load config load_config = dict() if load_config is None else load_config load_config["bounding_box"] = bounding_box # Infer the correct usd path to use if model is None: available_models = get_all_object_category_models(category=category) assert len(available_models) > 0, f"No available models found for category {category}!" model = np.random.choice(available_models) # If the model is in BAD_CLOTH_MODELS, raise an error for now -- this is a model that's unstable and needs to be fixed # TODO: Remove this once the asset is fixed! from omnigibson.utils.bddl_utils import BAD_CLOTH_MODELS if prim_type == PrimType.CLOTH and model in BAD_CLOTH_MODELS.get(category, dict()): raise ValueError(f"Cannot create cloth object category: {category}, model: {model} because it is " f"currently broken ): This will be fixed in the next release!") self._model = model usd_path = self.get_usd_path(category=category, model=model) # Run super init super().__init__( prim_path=prim_path, usd_path=usd_path, encrypted=True, name=name, category=category, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, kinematic_only=kinematic_only, self_collisions=self_collisions, prim_type=prim_type, include_default_states=include_default_states, load_config=load_config, abilities=abilities, **kwargs, ) @classmethod def get_usd_path(cls, category, model): """ Grabs the USD path for a DatasetObject corresponding to @category and @model. NOTE: This is the unencrypted path, NOT the encrypted path Args: category (str): Category for the object model (str): Specific model ID of the object Returns: str: Absolute filepath to the corresponding USD asset file """ return os.path.join(gm.DATASET_PATH, "objects", category, model, "usd", f"{model}.usd") def sample_orientation(self): """ Samples an orientation in quaternion (x,y,z,w) form Returns: 4-array: (x,y,z,w) sampled quaternion orientation for this object, based on self.orientations """ if self.orientations is None: raise ValueError("No orientation probabilities set") if len(self.orientations) == 0: # Set default value chosen_orientation = np.array([0, 0, 0, 1.0]) else: probabilities = [o["prob"] for o in self.orientations.values()] probabilities = np.array(probabilities) / np.sum(probabilities) chosen_orientation = np.array(np.random.choice(list(self.orientations.values()), p=probabilities)["rotation"]) # Randomize yaw from -pi to pi rot_num = np.random.uniform(-1, 1) rot_matrix = np.array( [ [math.cos(math.pi * rot_num), -math.sin(math.pi * rot_num), 0.0], [math.sin(math.pi * rot_num), math.cos(math.pi * rot_num), 0.0], [0.0, 0.0, 1.0], ] ) rotated_quat = T.mat2quat(rot_matrix @ T.quat2mat(chosen_orientation)) return rotated_quat def _initialize(self): # Run super method first super()._initialize() # Apply any forced light intensity updates. if gm.FORCE_LIGHT_INTENSITY is not None: def recursive_light_update(child_prim): if "Light" in child_prim.GetPrimTypeInfo().GetTypeName(): child_prim.GetAttribute("inputs:intensity").Set(gm.FORCE_LIGHT_INTENSITY) for child_child_prim in child_prim.GetChildren(): recursive_light_update(child_child_prim) recursive_light_update(self._prim) # Apply any forced roughness updates for material in self.materials: if ("reflection_roughness_texture_influence" in material.shader_input_names and "reflection_roughness_constant" in material.shader_input_names): material.reflection_roughness_texture_influence = 0.0 material.reflection_roughness_constant = gm.FORCE_ROUGHNESS # Set the joint frictions based on category friction = SPECIAL_JOINT_FRICTIONS.get(self.category, DEFAULT_JOINT_FRICTION) for joint in self._joints.values(): if joint.joint_type != JointType.JOINT_FIXED: joint.friction = friction def _post_load(self): # If manual bounding box is specified, scale based on ratio between that and the native bbox if self._load_config["bounding_box"] is not None: scale = np.ones(3) valid_idxes = self.native_bbox > 1e-4 scale[valid_idxes] = np.array(self._load_config["bounding_box"])[valid_idxes] / self.native_bbox[valid_idxes] else: scale = np.ones(3) if self._load_config["scale"] is None else np.array(self._load_config["scale"]) # Assert that the scale does not have too small dimensions assert np.all(scale > 1e-4), f"Scale of {self.name} is too small: {scale}" # Set this scale in the load config -- it will automatically scale the object during self.initialize() self._load_config["scale"] = scale # Run super last super()._post_load() # The loaded USD is from an already-deleted temporary file, so the asset paths for texture maps are wrong. # We explicitly provide the root_path to update all the asset paths: the asset paths are relative to the # original USD folder, i.e. <category>/<model>/usd. root_path = os.path.dirname(self._usd_path) for material in self.materials: material.shader_update_asset_paths_with_root_path(root_path) # Assign realistic density and mass based on average object category spec, or fall back to a default value if self.avg_obj_dims is not None and self.avg_obj_dims["density"] is not None: density = self.avg_obj_dims["density"] else: density = 1000.0 if self._prim_type == PrimType.RIGID: for link in self._links.values(): # If not a meta (virtual) link, set the density based on avg_obj_dims and a zero mass (ignored) if link.has_collision_meshes: link.mass = 0.0 link.density = density elif self._prim_type == PrimType.CLOTH: self.root_link.mass = density * self.root_link.volume def _update_texture_change(self, object_state): """ Update the texture based on the given object_state. E.g. if object_state is Frozen, update the diffuse color to match the frozen state. If object_state is None, update the diffuse color to the default value. It attempts to load the cached texture map named DIFFUSE/albedo_[STATE_NAME].png. If the cached texture map does not exist, it modifies the current albedo map by adding and scaling the values. See @self._update_albedo_value for details. Args: object_state (BooleanStateMixin or None): the object state that the diffuse color should match to """ # TODO: uncomment these once our dataset has the object state-conditioned texture maps # DEFAULT_ALBEDO_MAP_SUFFIX = frozenset({"DIFFUSE", "COMBINED", "albedo"}) # state_name = object_state.__class__.__name__ if object_state is not None else None for material in self.materials: # texture_path = material.diffuse_texture # assert texture_path is not None, f"DatasetObject [{self.prim_path}] has invalid diffuse texture map." # # # Get updated texture file path for state. # texture_path_split = texture_path.split("/") # filedir, filename = "/".join(texture_path_split[:-1]), texture_path_split[-1] # assert filename[-4:] == ".png", f"Texture file {filename} does not end with .png" # # filename_split = filename[:-4].split("_") # # Check all three file names for backward compatibility. # if len(filename_split) > 0 and filename_split[-1] not in DEFAULT_ALBEDO_MAP_SUFFIX: # filename_split.pop() # target_texture_path = f"{filedir}/{'_'.join(filename_split)}" # target_texture_path += f"_{state_name}.png" if state_name is not None else ".png" # # if os.path.exists(target_texture_path): # # Since we are loading a pre-cached texture map, we need to reset the albedo value to the default # self._update_albedo_value(None, material) # if material.diffuse_texture != target_texture_path: # material.diffuse_texture = target_texture_path # else: # print(f"Warning: DatasetObject [{self.prim_path}] does not have texture map: " # f"[{target_texture_path}]. Falling back to directly updating albedo value.") self._update_albedo_value(object_state, material) def set_bbox_center_position_orientation(self, position=None, orientation=None): """ Sets the center of the object's bounding box with respect to the world's frame. Args: position (None or 3-array): The desired global (x,y,z) position. None means it will not be changed orientation (None or 4-array): The desired global (x,y,z,w) quaternion orientation. None means it will not be changed """ if orientation is None: orientation = self.get_orientation() if position is not None: rotated_offset = T.pose_transform([0, 0, 0], orientation, self.scaled_bbox_center_in_base_frame, [0, 0, 0, 1])[0] position = position + rotated_offset self.set_position_orientation(position, orientation) @property def model(self): """ Returns: str: Unique model ID for this object """ return self._model @property def in_rooms(self): """ Returns: None or list of str: If specified, room(s) that this object should belong to """ return self._in_rooms @in_rooms.setter def in_rooms(self, rooms): """ Sets which room(s) this object should belong to. If no rooms, then should set to None Args: rooms (None or list of str): If specified, the room(s) this object should belong to """ # Store the value to the internal variable and also update the init kwargs accordingly self._init_info["args"]["in_rooms"] = rooms self._in_rooms = rooms @property def native_bbox(self): """ Get this object's native bounding box Returns: 3-array: (x,y,z) bounding box """ assert "ig:nativeBB" in self.property_names, \ f"This dataset object '{self.name}' is expected to have native_bbox specified, but found none!" return np.array(self.get_attribute(attr="ig:nativeBB")) @property def base_link_offset(self): """ Get this object's native base link offset Returns: 3-array: (x,y,z) base link offset if it exists """ return np.array(self.get_attribute(attr="ig:offsetBaseLink")) @property def metadata(self): """ Gets this object's metadata, if it exists Returns: None or dict: Nested dictionary of object's metadata if it exists, else None """ return self.get_custom_data().get("metadata", None) @property def orientations(self): """ Returns: None or dict: Possible orientation information for this object, if it exists. Otherwise, returns None """ metadata = self.metadata return None if metadata is None else metadata.get("orientations", None) @property def scale(self): # Just super call return super().scale @scale.setter def scale(self, scale): # call super first # A bit esoteric -- see https://gist.github.com/Susensio/979259559e2bebcd0273f1a95d7c1e79 super(DatasetObject, type(self)).scale.fset(self, scale) # Remove bounding_box from scale if it's in our args if "bounding_box" in self._init_info["args"]: self._init_info["args"].pop("bounding_box") @property def scaled_bbox_center_in_base_frame(self): """ where the base_link origin is wrt. the bounding box center. This allows us to place the model correctly since the joint transformations given in the scene USD are wrt. the bounding box center. We need to scale this offset as well. Returns: 3-array: (x,y,z) location of bounding box, with respet to the base link's coordinate frame """ return -self.scale * self.base_link_offset @property def scales_in_link_frame(self): """ Returns: dict: Keyword-mapped relative scales for each link of this object """ scales = {self.root_link.body_name: self.scale} # We iterate through all links in this object, and check for any joint prims that exist # We traverse manually this way instead of accessing the self._joints dictionary, because # the dictionary only includes articulated joints and not fixed joints! for link in self._links.values(): for prim in link.prim.GetChildren(): if "joint" in prim.GetTypeName().lower(): # Grab relevant joint information parent_name = prim.GetProperty("physics:body0").GetTargets()[0].pathString.split("/")[-1] child_name = prim.GetProperty("physics:body1").GetTargets()[0].pathString.split("/")[-1] if parent_name in scales and child_name not in scales: scale_in_parent_lf = scales[parent_name] # The location of the joint frame is scaled using the scale in the parent frame quat0 = lazy.omni.isaac.core.utils.rotations.gf_quat_to_np_array(prim.GetAttribute("physics:localRot0").Get())[[1, 2, 3, 0]] quat1 = lazy.omni.isaac.core.utils.rotations.gf_quat_to_np_array(prim.GetAttribute("physics:localRot1").Get())[[1, 2, 3, 0]] # Invert the child link relationship, and multiply the two rotations together to get the final rotation local_ori = T.quat_multiply(quaternion1=T.quat_inverse(quat1), quaternion0=quat0) jnt_frame_rot = T.quat2mat(local_ori) scale_in_child_lf = np.absolute(jnt_frame_rot.T @ np.array(scale_in_parent_lf)) scales[child_name] = scale_in_child_lf return scales @property def avg_obj_dims(self): """ Get the average object dimensions for this object, based on its category Returns: None or dict: Average object information based on its category """ return AVERAGE_CATEGORY_SPECS.get(self.category, None) def _create_prim_with_same_kwargs(self, prim_path, name, load_config): # Add additional kwargs (bounding_box is already captured in load_config) return self.__class__( prim_path=prim_path, name=name, category=self.category, scale=self.scale, visible=self.visible, fixed_base=self.fixed_base, visual_only=self._visual_only, prim_type=self._prim_type, load_config=load_config, abilities=self._abilities, in_rooms=self.in_rooms, )
21,486
Python
45.109442
148
0.618356
StanfordVL/OmniGibson/omnigibson/objects/controllable_object.py
from abc import abstractmethod from copy import deepcopy import numpy as np import gym import omnigibson as og from omnigibson.objects.object_base import BaseObject from omnigibson.controllers import create_controller from omnigibson.controllers.controller_base import ControlType from omnigibson.utils.python_utils import assert_valid_key, merge_nested_dicts, CachedFunctions 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__) class ControllableObject(BaseObject): """ Simple class that extends object functionality for controlling joints -- this assumes that at least some joints are motorized (i.e.: non-zero low-level simulator joint motor gains) and intended to be controlled, e.g.: a conveyor belt or a robot agent """ def __init__( self, name, prim_path=None, category="object", uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, self_collisions=False, prim_type=PrimType.RIGID, load_config=None, control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the object with a different rese joint position. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Store inputs self._control_freq = control_freq self._controller_config = controller_config self._reset_joint_pos = None if reset_joint_pos is None else np.array(reset_joint_pos) # Make sure action type is valid, and also save assert_valid_key(key=action_type, valid_keys={"discrete", "continuous"}, name="action type") self._action_type = action_type self._action_normalize = action_normalize # Store internal placeholders that will be filled in later self._dof_to_joints = None # dict that will map DOF indices to JointPrims self._last_action = None self._controllers = None self.dof_names_ordered = None self._control_enabled = True # Run super init super().__init__( prim_path=prim_path, name=name, category=category, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, prim_type=prim_type, load_config=load_config, **kwargs, ) def _initialize(self): # Run super first super()._initialize() # Fill in the DOF to joint mapping self._dof_to_joints = dict() idx = 0 for joint in self._joints.values(): for _ in range(joint.n_dof): self._dof_to_joints[idx] = joint idx += 1 # Update the reset joint pos if self._reset_joint_pos is None: self._reset_joint_pos = self._default_joint_pos # Load controllers self._load_controllers() # Setup action space self._action_space = self._create_discrete_action_space() if self._action_type == "discrete" \ else self._create_continuous_action_space() # Reset the object and keep all joints still after loading self.reset() self.keep_still() # If we haven't already created a physics callback, do so now so control gets updated every sim step callback_name = f"{self.name}_controller_callback" if not og.sim.physics_callback_exists(callback_name=callback_name): og.sim.add_physics_callback( callback_name=callback_name, callback_fn=lambda x: self.step(), ) def load(self): # Run super first prim = super().load() # Set the control frequency if one was not provided. expected_control_freq = 1.0 / og.sim.get_rendering_dt() if self._control_freq is None: log.info( "Control frequency is None - being set to default of render_frequency: %.4f", expected_control_freq ) self._control_freq = expected_control_freq else: assert np.isclose( expected_control_freq, self._control_freq ), "Stored control frequency does not match environment's render timestep." return prim def _load_controllers(self): """ Loads controller(s) to map inputted actions into executable (pos, vel, and / or effort) signals on this object. Stores created controllers as dictionary mapping controller names to specific controller instances used by this object. """ # Generate the controller config self._controller_config = self._generate_controller_config(custom_config=self._controller_config) # Store dof idx mapping to dof name self.dof_names_ordered = list(self._joints.keys()) # Initialize controllers to create self._controllers = dict() # Loop over all controllers, in the order corresponding to @action dim for name in self.controller_order: assert_valid_key(key=name, valid_keys=self._controller_config, name="controller name") cfg = self._controller_config[name] # If we're using normalized action space, override the inputs for all controllers if self._action_normalize: cfg["command_input_limits"] = "default" # default is normalized (-1, 1) # Create the controller controller = create_controller(**cfg) # Verify the controller's DOFs can all be driven for idx in controller.dof_idx: assert self._joints[self.dof_names_ordered[idx]].driven, "Controllers should only control driveable joints!" self._controllers[name] = controller self.update_controller_mode() def update_controller_mode(self): """ Helper function to force the joints to use the internal specified control mode and gains """ # Update the control modes of each joint based on the outputted control from the controllers for name in self._controllers: for dof in self._controllers[name].dof_idx: control_type = self._controllers[name].control_type self._joints[self.dof_names_ordered[dof]].set_control_type( control_type=control_type, kp=self.default_kp if control_type == ControlType.POSITION else None, kd=self.default_kd if control_type == ControlType.VELOCITY else None, ) def _generate_controller_config(self, custom_config=None): """ Generates a fully-populated controller config, overriding any default values with the corresponding values specified in @custom_config Args: custom_config (None or Dict[str, ...]): nested dictionary mapping controller name(s) to specific custom controller configurations for this object. This will override any default values specified by this class Returns: dict: Fully-populated nested dictionary mapping controller name(s) to specific controller configurations for this object """ controller_config = {} if custom_config is None else deepcopy(custom_config) # Update the configs for group in self.controller_order: group_controller_name = ( controller_config[group]["name"] if group in controller_config and "name" in controller_config[group] else self._default_controllers[group] ) controller_config[group] = merge_nested_dicts( base_dict=self._default_controller_config[group][group_controller_name], extra_dict=controller_config.get(group, {}), ) return controller_config def reload_controllers(self, controller_config=None): """ Reloads controllers based on the specified new @controller_config Args: controller_config (None or Dict[str, ...]): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. """ self._controller_config = {} if controller_config is None else controller_config # (Re-)load controllers self._load_controllers() # (Re-)create the action space self._action_space = self._create_discrete_action_space() if self._action_type == "discrete" \ else self._create_continuous_action_space() def reset(self): # Call super first super().reset() # Override the reset joint state based on reset values self.set_joint_positions(positions=self._reset_joint_pos, drive=False) @abstractmethod def _create_discrete_action_space(self): """ Create a discrete action space for this object. Should be implemented by the subclass (if a subclass does not support this type of action space, it should raise an error). Returns: gym.space: Object-specific discrete action space """ raise NotImplementedError def _create_continuous_action_space(self): """ Create a continuous action space for this object. By default, this loops over all controllers and appends their respective input command limits to set the action space. Any custom behavior should be implemented by the subclass (e.g.: if a subclass does not support this type of action space, it should raise an error). Returns: gym.space.Box: Object-specific continuous action space """ # Action space is ordered according to the order in _default_controller_config control low, high = [], [] for controller in self._controllers.values(): limits = controller.command_input_limits low.append(np.array([-np.inf] * controller.command_dim) if limits is None else limits[0]) high.append(np.array([np.inf] * controller.command_dim) if limits is None else limits[1]) return gym.spaces.Box(shape=(self.action_dim,), low=np.concatenate(low), high=np.concatenate(high), dtype=float) def apply_action(self, action): """ Converts inputted actions into low-level control signals NOTE: This does NOT deploy control on the object. Use self.step() instead. Args: action (n-array): n-DOF length array of actions to apply to this object's internal controllers """ # Store last action as the current action being applied self._last_action = action # If we're using discrete action space, we grab the specific action and use that to convert to control if self._action_type == "discrete": action = np.array(self.discrete_action_list[action]) # Check if the input action's length matches the action dimension assert len(action) == self.action_dim, "Action must be dimension {}, got dim {} instead.".format( self.action_dim, len(action) ) # First, loop over all controllers, and update the desired command idx = 0 for name, controller in self._controllers.items(): # Set command, then take a controller step controller.update_goal(command=action[idx : idx + controller.command_dim], control_dict=self.get_control_dict()) # Update idx idx += controller.command_dim @property def control_enabled(self): return self._control_enabled @control_enabled.setter def control_enabled(self, value): self._control_enabled = value def step(self): """ Takes a controller step across all controllers and deploys the computed control signals onto the object. """ # Skip if we don't have control enabled if not self.control_enabled: return # Skip this step if our articulation view is not valid if self._articulation_view_direct is None or not self._articulation_view_direct.initialized: return # First, loop over all controllers, and calculate the computed control control = dict() idx = 0 # Compose control_dict control_dict = self.get_control_dict() for name, controller in self._controllers.items(): control[name] = { "value": controller.step(control_dict=control_dict), "type": controller.control_type, } # Update idx idx += controller.command_dim # Compose controls u_vec = np.zeros(self.n_dof) # By default, the control type is None and the control value is 0 (np.zeros) - i.e. no control applied u_type_vec = np.array([ControlType.NONE] * self.n_dof) for group, ctrl in control.items(): idx = self._controllers[group].dof_idx u_vec[idx] = ctrl["value"] u_type_vec[idx] = ctrl["type"] u_vec, u_type_vec = self._postprocess_control(control=u_vec, control_type=u_type_vec) # Deploy control signals self.deploy_control(control=u_vec, control_type=u_type_vec, indices=None, normalized=False) def _postprocess_control(self, control, control_type): """ Runs any postprocessing on @control with corresponding @control_type on this entity. Default is no-op. Deploys control signals @control with corresponding @control_type on this entity. Args: control (k- or n-array): control signals to deploy. This should be n-DOF length if all joints are being set, or k-length (k < n) if specific indices are being set. In this case, the length of @control must be the same length as @indices! control_type (k- or n-array): control types for each DOF. Each entry should be one of ControlType. This should be n-DOF length if all joints are being set, or k-length (k < n) if specific indices are being set. In this case, the length of @control must be the same length as @indices! Returns: 2-tuple: - n-array: raw control signals to send to the object's joints - list: control types for each joint """ return control, control_type def deploy_control(self, control, control_type, indices=None, normalized=False): """ Deploys control signals @control with corresponding @control_type on this entity. Note: This is DIFFERENT than self.set_joint_positions/velocities/efforts, because in this case we are only setting target values (i.e.: we subject this entity to physical dynamics in order to reach the desired @control setpoints), compared to set_joint_XXXX which manually sets the actual state of the joints. This function is intended to be used with motorized entities, e.g.: robot agents or machines (e.g.: a conveyor belt) to simulation physical control of these entities. In contrast, use set_joint_XXXX for simulation-specific logic, such as simulator resetting or "magic" action implementations. Args: control (k- or n-array): control signals to deploy. This should be n-DOF length if all joints are being set, or k-length (k < n) if specific indices are being set. In this case, the length of @control must be the same length as @indices! control_type (k- or n-array): control types for each DOF. Each entry should be one of ControlType. This should be n-DOF length if all joints are being set, or k-length (k < n) if specific indices are being set. In this case, the length of @control must be the same length as @indices! indices (None or k-array): If specified, should be k (k < n) length array of specific DOF controls to deploy. Default is None, which assumes that all joints are being set. normalized (bool): Whether the inputted joint controls should be interpreted as normalized values. Expects a single bool for the entire @control. Default is False. """ # Run sanity check if indices is None: assert len(control) == len(control_type) == self.n_dof, ( "Control signals, control types, and number of DOF should all be the same!" "Got {}, {}, and {} respectively.".format(len(control), len(control_type), self.n_dof) ) # Set indices manually so that we're standardized indices = np.arange(self.n_dof) else: assert len(control) == len(control_type) == len(indices), ( "Control signals, control types, and indices should all be the same!" "Got {}, {}, and {} respectively.".format(len(control), len(control_type), len(indices)) ) # Standardize normalized input n_indices = len(indices) # Loop through controls and deploy # We have to use delicate logic to account for the edge cases where a single joint may contain > 1 DOF # (e.g.: spherical joint) pos_vec, pos_idxs, using_pos = [], [], False vel_vec, vel_idxs, using_vel = [], [], False eff_vec, eff_idxs, using_eff = [], [], False cur_indices_idx = 0 while cur_indices_idx != n_indices: # Grab the current DOF index we're controlling and find the corresponding joint joint = self._dof_to_joints[indices[cur_indices_idx]] cur_ctrl_idx = indices[cur_indices_idx] joint_dof = joint.n_dof if joint_dof > 1: # Run additional sanity checks since the joint has more than one DOF to make sure our controls, # control types, and indices all match as expected # Make sure the indices are mapped correctly assert indices[cur_indices_idx + joint_dof] == cur_ctrl_idx + joint_dof, \ "Got mismatched control indices for a single joint!" # Check to make sure all joints, control_types, and normalized as all the same over n-DOF for the joint for group_name, group in zip( ("joints", "control_types", "normalized"), (self._dof_to_joints, control_type, normalized), ): assert len({group[indices[cur_indices_idx + i]] for i in range(joint_dof)}) == 1, \ f"Not all {group_name} were the same when trying to deploy control for a single joint!" # Assuming this all passes, we grab the control subvector, type, and normalized value accordingly ctrl = control[cur_ctrl_idx: cur_ctrl_idx + joint_dof] else: # Grab specific control. No need to do checks since this is a single value ctrl = control[cur_ctrl_idx] # Deploy control based on type ctrl_type = control_type[cur_ctrl_idx] # In multi-DOF joint case all values were already checked to be the same if ctrl_type == ControlType.EFFORT: eff_vec.append(ctrl) eff_idxs.append(cur_ctrl_idx) using_eff = True elif ctrl_type == ControlType.VELOCITY: vel_vec.append(ctrl) vel_idxs.append(cur_ctrl_idx) using_vel = True elif ctrl_type == ControlType.POSITION: pos_vec.append(ctrl) pos_idxs.append(cur_ctrl_idx) using_pos = True elif ctrl_type == ControlType.NONE: # Set zero efforts eff_vec.append(0) eff_idxs.append(cur_ctrl_idx) using_eff = True else: raise ValueError("Invalid control type specified: {}".format(ctrl_type)) # Finally, increment the current index based on how many DOFs were just controlled cur_indices_idx += joint_dof # set the targets for joints if using_pos: self.set_joint_positions(positions=np.array(pos_vec), indices=np.array(pos_idxs), drive=True, normalized=normalized) if using_vel: self.set_joint_velocities(velocities=np.array(vel_vec), indices=np.array(vel_idxs), drive=True, normalized=normalized) if using_eff: self.set_joint_efforts(efforts=np.array(eff_vec), indices=np.array(eff_idxs), normalized=normalized) def get_control_dict(self): """ Grabs all relevant information that should be passed to each controller during each controller step. This automatically caches information Returns: CachedFunctions: Keyword-mapped control values for this object, mapping names to n-arrays. By default, returns the following (can be queried via [] or get()): - joint_position: (n_dof,) joint positions - joint_velocity: (n_dof,) joint velocities - joint_effort: (n_dof,) joint efforts - root_pos: (3,) (x,y,z) global cartesian position of the object's root link - root_quat: (4,) (x,y,z,w) global cartesian orientation of ths object's root link - mass_matrix: (n_dof, n_dof) mass matrix - gravity_force: (n_dof,) per-joint generalized gravity forces - cc_force: (n_dof,) per-joint centripetal and centrifugal forces """ fcns = CachedFunctions() fcns["_root_pos_quat"] = self.get_position_orientation fcns["root_pos"] = lambda: fcns["_root_pos_quat"][0] fcns["root_quat"] = lambda: fcns["_root_pos_quat"][1] fcns["root_lin_vel"] = self.get_linear_velocity fcns["root_ang_vel"] = self.get_angular_velocity fcns["root_rel_lin_vel"] = self.get_relative_linear_velocity fcns["root_rel_ang_vel"] = self.get_relative_angular_velocity fcns["joint_position"] = lambda: self.get_joint_positions(normalized=False) fcns["joint_velocity"] = lambda: self.get_joint_velocities(normalized=False) fcns["joint_effort"] = lambda: self.get_joint_efforts(normalized=False) fcns["mass_matrix"] = lambda: self.get_mass_matrix(clone=False) fcns["gravity_force"] = lambda: self.get_generalized_gravity_forces(clone=False) fcns["cc_force"] = lambda: self.get_coriolis_and_centrifugal_forces(clone=False) return fcns def dump_action(self): """ Dump the last action applied to this object. For use in demo collection. """ return self._last_action def set_joint_positions(self, positions, indices=None, normalized=False, drive=False): # Call super first super().set_joint_positions(positions=positions, indices=indices, normalized=normalized, drive=drive) # If we're not driving the joints, reset the controllers so that the goals are updated wrt to the new state if not drive: for controller in self._controllers.values(): controller.reset() def _dump_state(self): # Grab super state state = super()._dump_state() # Add in controller states controller_states = dict() for controller_name, controller in self._controllers.items(): controller_states[controller_name] = controller.dump_state() state["controllers"] = controller_states return state def _load_state(self, state): # Run super first super()._load_state(state=state) # Load controller states controller_states = state["controllers"] for controller_name, controller in self._controllers.items(): controller.load_state(state=controller_states[controller_name]) def _serialize(self, state): # Run super first state_flat = super()._serialize(state=state) # Serialize the controller states sequentially controller_states_flat = np.concatenate([ c.serialize(state=state["controllers"][c_name]) for c_name, c in self._controllers.items() ]) # Concatenate and return return np.concatenate([state_flat, controller_states_flat]).astype(float) def _deserialize(self, state): # Run super first state_dict, idx = super()._deserialize(state=state) # Deserialize the controller states sequentially controller_states = dict() for c_name, c in self._controllers.items(): state_size = c.state_size controller_states[c_name] = c.deserialize(state=state[idx: idx + state_size]) idx += state_size state_dict["controllers"] = controller_states return state_dict, idx @property def action_dim(self): """ Returns: int: Dimension of action space for this object. By default, is the sum over all controller action dimensions """ return sum([controller.command_dim for controller in self._controllers.values()]) @property def action_space(self): """ Action space for this object. Returns: gym.space: Action space, either discrete (Discrete) or continuous (Box) """ return deepcopy(self._action_space) @property def discrete_action_list(self): """ Discrete choices for actions for this object. Only needs to be implemented if the object supports discrete actions. Returns: dict: Mapping from single action identifier (e.g.: a string, or a number) to array of continuous actions to deploy via this object's controllers. """ raise NotImplementedError() @property def controllers(self): """ Returns: dict: Controllers owned by this object, mapping controller name to controller object """ return self._controllers @property @abstractmethod def controller_order(self): """ Returns: list: Ordering of the actions, corresponding to the controllers. e.g., ["base", "arm", "gripper"], to denote that the action vector should be interpreted as first the base action, then arm command, then gripper command """ raise NotImplementedError @property def controller_action_idx(self): """ Returns: dict: Mapping from controller names (e.g.: head, base, arm, etc.) to corresponding indices (list) in the action vector """ dic = {} idx = 0 for controller in self.controller_order: cmd_dim = self._controllers[controller].command_dim dic[controller] = np.arange(idx, idx + cmd_dim) idx += cmd_dim return dic @property def controller_joint_idx(self): """ Returns: dict: Mapping from controller names (e.g.: head, base, arm, etc.) to corresponding indices (list) of the joint state vector controlled by each controller """ dic = {} for controller in self.controller_order: dic[controller] = self._controllers[controller].dof_idx return dic @property def control_limits(self): """ Returns: dict: Keyword-mapped limits for this object. Dict contains: position: (min, max) joint limits, where min and max are N-DOF arrays velocity: (min, max) joint velocity limits, where min and max are N-DOF arrays effort: (min, max) joint effort limits, where min and max are N-DOF arrays has_limit: (n_dof,) array where each element is True if that corresponding joint has a position limit (otherwise, joint is assumed to be limitless) """ return { "position": (self.joint_lower_limits, self.joint_upper_limits), "velocity": (-self.max_joint_velocities, self.max_joint_velocities), "effort": (-self.max_joint_efforts, self.max_joint_efforts), "has_limit": self.joint_has_limits, } @property def default_kp(self): """ Returns: float: Default kp gain to apply to any DOF when switching control modes (e.g.: switching from a velocity control mode to a position control mode) """ return 1e7 @property def default_kd(self): """ Returns: float: Default kd gain to apply to any DOF when switching control modes (e.g.: switching from a position control mode to a velocity control mode) """ return 1e5 @property def reset_joint_pos(self): """ Returns: n-array: reset joint positions for this robot """ return self._reset_joint_pos @reset_joint_pos.setter def reset_joint_pos(self, value): """ Args: value: the new reset joint positions for this robot """ self._reset_joint_pos = value @property @abstractmethod def _default_joint_pos(self): """ Returns: n-array: Default joint positions for this robot """ raise NotImplementedError @property @abstractmethod def _default_controller_config(self): """ Returns: dict: default nested dictionary mapping controller name(s) to specific controller configurations for this object. Note that the order specifies the sequence of actions to be received from the environment. Expected structure is as follows: group1: controller_name1: controller_name1_params ... controller_name2: ... group2: ... The @group keys specify the control type for various aspects of the object, e.g.: "head", "arm", "base", etc. @controller_name keys specify the supported controllers for that group. A default specification MUST be specified for each controller_name. e.g.: IKController, DifferentialDriveController, JointController, etc. """ return {} @property @abstractmethod def _default_controllers(self): """ Returns: dict: Maps object group (e.g. base, arm, etc.) to default controller class name to use (e.g. IKController, JointController, etc.) """ return {}
34,103
Python
43.522193
130
0.614052
StanfordVL/OmniGibson/omnigibson/utils/deprecated_utils.py
""" A set of utility functions slated to be deprecated once Omniverse bugs are fixed """ import carb from typing import List, Optional, Tuple, Union, Callable import omni.usd as ou from omni.particle.system.core.scripts.core import Core as OmniCore from omni.particle.system.core.scripts.utils import Utils as OmniUtils from pxr import Sdf, UsdShade, PhysxSchema, Usd, UsdGeom, UsdPhysics import omni import omni.graph.core as ogc from omni.kit.primitive.mesh.command import _get_all_evaluators from omni.kit.primitive.mesh.command import CreateMeshPrimWithDefaultXformCommand as CMPWDXC import omni.timeline from omni.isaac.core.utils.prims import get_prim_at_path import numpy as np import torch import warp as wp import math from omni.isaac.core.articulations import ArticulationView as _ArticulationView from omni.isaac.core.prims import RigidPrimView as _RigidPrimView from PIL import Image, ImageDraw from omni.replicator.core import random_colours 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 Utils(OmniUtils): def create_material(self, name): material_url = carb.settings.get_settings().get("/exts/omni.particle.system.core/material") # TODO: THIS IS THE ONLY LINE WE CHANGE! "/" SHOULD BE "" material_path = "" default_prim = self.stage.GetDefaultPrim() if default_prim: material_path = default_prim.GetPath().pathString if not self.stage.GetPrimAtPath(material_path + "/Looks"): self.stage.DefinePrim(material_path + "/Looks", "Scope") material_path += "/Looks/" + name material_path = ou.get_stage_next_free_path( self.stage, material_path, False ) prim = self.stage.DefinePrim(material_path, "Material") if material_url: prim.GetReferences().AddReference(material_url) else: carb.log_error("Failed to find material URL in settings") return [material_path] class Core(OmniCore): """ Subclass that overrides a specific function within Omni's Core class to fix a bug """ def __init__(self, popup_callback: Callable[[str], None], particle_system_name: str): self._popup_callback = popup_callback self.utils = Utils() self.context = ou.get_context() self.stage = self.context.get_stage() self.selection = self.context.get_selection() self.particle_system_name = particle_system_name self.sub_stage_update = self.context.get_stage_event_stream().create_subscription_to_pop(self.on_stage_update) self.on_stage_update() def get_compute_graph(self, selected_paths, create_new_graph=True, created_paths=None): """ Returns the first ComputeGraph found in selected_paths. If no graph is found and create_new_graph is true, a new graph will be created and its path appended to created_paths (if provided). """ graph = None graph_paths = [path for path in selected_paths if self.stage.GetPrimAtPath(path).GetTypeName() in ["ComputeGraph", "OmniGraph"] ] if len(graph_paths) > 0: graph = ogc.get_graph_by_path(graph_paths[0]) if len(graph_paths) > 1: carb.log_warn(f"Multiple ComputeGraph prims selected. Only the first will be used: {graph.get_path_to_graph()}") elif create_new_graph: # If no graph was found in the selected prims, we'll make a new graph. # TODO: THIS IS THE ONLY LINE THAT WE CHANGE! ONCE FIXED, REMOVE THIS graph_path = Sdf.Path(f"/OmniGraph/{self.particle_system_name}").MakeAbsolutePath(Sdf.Path.absoluteRootPath) graph_path = ou.get_stage_next_free_path(self.stage, graph_path, True) # prim = self.stage.GetDefaultPrim() # path = str(prim.GetPath()) if prim else "" self.stage.DefinePrim("/OmniGraph", "Scope") container_graphs = ogc.get_global_container_graphs() # FIXME: container_graphs[0] should be the simulation orchestration graph, but this may change in the future. container_graph = container_graphs[0] result, wrapper_node = ogc.cmds.CreateGraphAsNode( graph=container_graph, node_name=Sdf.Path(graph_path).name, graph_path=graph_path, evaluator_name="push", is_global_graph=True, backed_by_usd=True, fc_backing_type=ogc.GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED, pipeline_stage=ogc.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION ) graph = wrapper_node.get_wrapped_graph() if created_paths is not None: created_paths.append(graph.get_path_to_graph()) carb.log_info(f"No ComputeGraph selected. A new graph has been created at {graph.get_path_to_graph()}") return graph 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 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: COMMENT OUT THE BELOW LINE AND SET TARGETS INSTEAD # 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: COMMENT OUT THE BELOW LINE AND SET TARGETS INSTEAD # 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 class RigidPrimView(_RigidPrimView): 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 omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: 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). """ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu") if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None: 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 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['semanticId']) 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()), True, num_channels) for bbox_2d in bbox_2d_list: index = np.where(semantic_id_list_np == bbox_2d['semanticId'])[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['x_min'], bbox_2d['y_min']), (bbox_2d['x_max'], bbox_2d['y_max'])], outline=outline, width=2) bboxes_2d_rgb = np.array(rgb_img) return bboxes_2d_rgb
39,722
Python
56.65312
155
0.557474
StanfordVL/OmniGibson/omnigibson/utils/profiling_utils.py
import gym import omnigibson as og import os import psutil from pynvml.smi import nvidia_smi from time import time class ProfilingEnv(og.Environment): def step(self, action): try: start = time() # If the action is not a dictionary, convert into a dictionary if not isinstance(action, dict) and not isinstance(action, gym.spaces.Dict): action_dict = dict() idx = 0 for robot in self.robots: action_dim = robot.action_dim action_dict[robot.name] = action[idx: idx + action_dim] idx += action_dim else: # Our inputted action is the action dictionary action_dict = action # Iterate over all robots and apply actions for robot in self.robots: robot.apply_action(action_dict[robot.name]) # Run simulation step sim_start = time() if len(og.sim._objects_to_initialize) > 0: og.sim.render() super(type(og.sim), og.sim).step(render=True) omni_time = (time() - sim_start) * 1e3 # Additionally run non physics things og.sim._non_physics_step() # Grab observations obs, obs_info = self.get_obs() # Step the scene graph builder if necessary if self._scene_graph_builder is not None: self._scene_graph_builder.step(self.scene) # Grab reward, done, and info, and populate with internal info reward, done, info = self.task.step(self, action) self._populate_info(info) if done and self._automatic_reset: # Add lost observation to our information dict, and reset info["last_observation"] = obs info["last_observation_info"] = obs_info obs, obs_info = self.reset() # Increment step self._current_step += 1 # collect profiling data total_frame_time = (time() - start) * 1e3 og_time = total_frame_time - omni_time # memory usage in GB memory_usage = psutil.Process(os.getpid()).memory_info().rss / 1024 ** 3 # VRAM usage in GB for gpu in nvidia_smi.getInstance().DeviceQuery()['gpu']: found = False for process in gpu['processes']: if process['pid'] == os.getpid(): vram_usage = process['used_memory'] / 1024 found = True break if found: break ret = [total_frame_time, omni_time, og_time, memory_usage, vram_usage] if self._current_step % 100 == 0: print("total time: {:.3f} ms, Omni time: {:.3f} ms, OG time: {:.3f} ms, memory: {:.3f} GB, vram: {:.3f} GB.".format(*ret)) return obs, reward, done, info, ret except: raise ValueError(f"Failed to execute environment step {self._current_step} in episode {self._current_episode}")
3,191
Python
37.926829
138
0.525541
StanfordVL/OmniGibson/omnigibson/utils/python_utils.py
""" A set of utility functions for general python usage """ import inspect import re from abc import ABCMeta from copy import deepcopy from collections.abc import Iterable from functools import wraps, cache from importlib import import_module import numpy as np # 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 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: not_equal = base_dict[k] != v if isinstance(not_equal, np.ndarray): not_equal = not_equal.any() if not_equal and verbose: print(f"Different values for key {k}: {base_dict[k]}, {v}\n") base_dict[k] = np.array(v) if isinstance(v, list) else 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 """ 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): """ 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 Returns: int: uuid """ return abs(hash(name)) % (10 ** n_digits) def camel_case_to_snake_case(camel_case_text): """ Helper function to convert a camel case text to snake case, e.g. "StrawberrySmoothie" -> "strawberry_smoothie" Args: camel_case_text (str): Text in camel case Returns: str: snake case text """ return re.sub(r'(?<!^)(?=[A-Z])', '_', camel_case_text).lower() def snake_case_to_camel_case(snake_case_text): """ Helper function to convert a snake case text to camel case, e.g. "strawberry_smoothie" -> "StrawberrySmoothie" Args: snake_case_text (str): Text in snake case Returns: str: camel case text """ return ''.join(item.title() for item in snake_case_text.split('_')) 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 UniquelyNamed: """ Simple class that implements a name property, that must be implemented by a subclass. Note that any @Named entity must be UNIQUE! """ def __init__(self, *args, **kwargs): global NAMES # Register this object, making sure it's name is unique assert self.name not in NAMES, \ f"UniquelyNamed object with name {self.name} already exists!" NAMES.add(self.name) def remove_names(self): """ Checks if self.name exists in the global NAMES registry, and deletes it if so. Possibly also iterates through all owned member variables and checks for their corresponding names if @include_all_owned is True. Args: include_all_owned (bool): If True, will iterate through all owned members of this instance and remove their names as well, if they are UniquelyNamed skip_ids (None or set of int): If specified, will skip over any ids in the specified set that are matched to any attributes found (this compares id(attr) to @skip_ids). """ # Check for this name, possibly remove it if it exists if self.name in NAMES: NAMES.remove(self.name) @property def name(self): """ Returns: str: Name of this instance. Must be unique! """ raise NotImplementedError class UniquelyNamedNonInstance: """ Identical to UniquelyNamed, but intended for non-instanceable classes """ def __init_subclass__(cls, **kwargs): global CLASS_NAMES # Register this object, making sure it's name is unique assert cls.name not in CLASS_NAMES, \ f"UniquelyNamed class with name {cls.name} already exists!" CLASS_NAMES.add(cls.name) @classproperty def name(cls): """ Returns: str: Name of this instance. Must be unique! """ raise NotImplementedError 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. """ @property def state_size(self): """ Returns: int: Size of this object's serialized state """ raise NotImplementedError() 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 np.array capturing this object's state, where n is @self.state_size """ 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 np.array capturing this object's state, where n is @self.state_size 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 """ state = self.deserialize(state=state) if serialized else state 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 np.array capturing this object's state """ raise NotImplementedError() 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 np.array capturing this object's state """ # Simply returns self._serialize() for now. this is for future proofing return self._serialize(state=state) 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 np.array 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 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 np.array capturing this object's state Returns: dict: Keyword-mapped states of this object. Should match structure of output from self._dump_state() """ # Sanity check the idx with the expected state size state_dict, idx = self._deserialize(state=state) assert idx == self.state_size, f"Invalid state deserialization occurred! Expected {self.state_size} total " \ f"values to be deserialized, only {idx} were." return state_dict class SerializableNonInstance: """ Identical to Serializable, but intended for non-instanceable classes """ @classproperty def state_size(cls): """ Returns: int: Size of this object's serialized state """ raise NotImplementedError() @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 np.array capturing this object's state, where n is @self.state_size """ 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 np.array capturing this object's state, where n is @self.state_size 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 """ state = cls.deserialize(state=state) if serialized else state 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 np.array capturing this object's state """ raise NotImplementedError() @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 np.array capturing this object's state """ # Simply returns self._serialize() for now. this is for future proofing return cls._serialize(state=state) @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 np.array 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 @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 np.array capturing this object's state Returns: dict: Keyword-mapped states of this object. Should match structure of output from self._dump_state() """ # Sanity check the idx with the expected state size state_dict, idx = cls._deserialize(state=state) assert idx == cls.state_size, f"Invalid state deserialization occurred! Expected {cls.state_size} total " \ f"values to be deserialized, only {idx} were." return state_dict 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() 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) @cache def get(self, name, *args, **kwargs): """ 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 *args (tuple): Positional arguments to pass into the function call **kwargs (tuple): Keyword arguments to pass into the function call Returns: any: Output of the function referenced by @name """ return self._fcns[name](*args, **kwargs) 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 nums2array(nums, dim, dtype=float): """ 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 = np.array(nums, dtype=dtype) if isinstance(nums, Iterable) else np.ones(dim, dtype=dtype) * nums return out def clear(): """ Clear state tied to singleton classes """ NAMES.clear() CLASS_NAMES.clear()
32,190
Python
35.580682
121
0.629605
StanfordVL/OmniGibson/omnigibson/utils/object_state_utils.py
import cv2 import numpy as np from IPython import embed from scipy.spatial.transform import Rotation as R from scipy.spatial import ConvexHull, distance_matrix import omnigibson as og from omnigibson.macros import create_module_macros, Dict, macros from omnigibson.object_states.aabb import AABB from omnigibson.object_states.contact_bodies import ContactBodies from omnigibson.utils import sampling_utils from omnigibson.utils.constants import PrimType from omnigibson.utils.ui_utils import debug_breakpoint import omnigibson.utils.transform_utils as T # Create settings for this module m = create_module_macros(module_path=__file__) m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS = 10 m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS = 10 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 sample_kinematics( predicate, objA, objB, max_trials=m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS, z_offset=0.05, skip_falling=False, ): """ 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 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()}" # 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 for i in range(max_trials): pos = None if hasattr(objA, "orientations") and objA.orientations is not None: orientation = objA.sample_orientation() else: orientation = np.array([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 = np.array([100, 100, 10]) objA.set_position_orientation(old_pos, 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.states[AABB].get_value() parallel_bbox_center = (aabb_lower + aabb_upper) / 2.0 parallel_bbox_orn = np.array([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 parallel_bbox_rotation = R.from_quat(parallel_bbox_orn) sample_rotation = R.from_quat(sampled_quaternion) original_rotation = R.from_quat(orientation) # The additional orientation to be applied should be the delta orientation # between the parallel bbox orientation and the sample orientation additional_rotation = sample_rotation * parallel_bbox_rotation.inv() combined_rotation = additional_rotation * original_rotation orientation = combined_rotation.as_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 = additional_rotation.apply(diff) pos = sampled_vector + rotated_diff if pos is None: success = False else: pos[2] += z_offset objA.set_position_orientation(pos, orientation) objA.keep_still() og.sim.step_physics() objA.keep_still() success = len(objA.states[ContactBodies].get_value()) == 0 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, try last-ditch effort if not success and predicate in {"onTop", "inside"}: 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.states[AABB].get_value() aabb_lower_b, aabb_upper_b = objB.states[AABB].get_value() bbox_to_obj = objA.get_position() - (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(pos, 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 len(objA.states[ContactBodies].get_value()) == 0 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 np.linalg.norm(objA.get_linear_velocity()) > 1e-3 and i < n_steps_max: og.sim.step_physics() i += 1 # Render at the end og.sim.render() 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 obj.root_link.reset() obj_aabb_low, obj_aabb_high = obj.states[AABB].get_value() other_aabb_low, other_aabb_high = other.states[AABB].get_value() # 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 = np.array([other_aabb_low[0], other_aabb_low[1], z_value]) high = np.array([other_aabb_high[0], other_aabb_high[1], z_value]) else: # Always sample the center of the other object's AABB low = np.array([(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 = np.random.uniform(low, high) # Sample a random orientation in the z-axis orn = T.euler2quat(np.array([0., 0., np.random.uniform(0, np.pi * 2)])) obj.set_position_orientation(pos, orn) obj.root_link.reset() obj.keep_still() og.sim.step_physics() success = len(obj.states[ContactBodies].get_value()) == 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
12,251
Python
38.019108
119
0.625173
StanfordVL/OmniGibson/omnigibson/utils/physx_utils.py
import numpy as np from omnigibson.macros import gm, create_module_macros from omnigibson.utils.ui_utils import suppress_omni_log import omnigibson as og import omnigibson.lazy as lazy # 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 """ # TODO: Add sanity check to make sure GPU dynamics are enabled # Create particle system stage = lazy.omni.isaac.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 lazy.pxr.PhysxSchema.PhysxParticleAnisotropyAPI.Apply(particle_system.GetPrim()) if smoothing: # apply api and use all defaults lazy.pxr.PhysxSchema.PhysxParticleSmoothingAPI.Apply(particle_system.GetPrim()) if isosurface: # apply api and use all defaults lazy.pxr.PhysxSchema.PhysxParticleIsosurfaceAPI.Apply(particle_system.GetPrim()) # 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 = lazy.pxr.PhysxSchema.PhysxParticleAnisotropyAPI.Apply(particle_system.GetPrim()) 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 """ 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 np.array): 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 np.array): 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 np.array): 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 np.array): 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 np.array): 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 """ stage = og.sim.stage n_particles = len(positions) particle_system = lazy.omni.isaac.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.omni.isaac.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 = np.zeros((n_particles, 4)) orientations[:, -1] = 1.0 orientations = np.array(orientations)[:, [3, 0, 1, 2]] # x,y,z,w --> w,x,y,z velocities = np.zeros((n_particles, 3)) if velocities is None else velocities angular_velocities = np.zeros((n_particles, 3)) if angular_velocities is None else angular_velocities scales = np.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.FromNumpy(positions)) instancer.GetOrientationsAttr().Set(lazy.pxr.Vt.QuathArray.FromNumpy(orientations)) instancer.GetVelocitiesAttr().Set(lazy.pxr.Vt.Vec3fArray.FromNumpy(velocities)) instancer.GetAngularVelocitiesAttr().Set(lazy.pxr.Vt.Vec3fArray.FromNumpy(angular_velocities)) instancer.GetScalesAttr().Set(lazy.pxr.Vt.Vec3fArray.FromNumpy(scales)) # 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): 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): 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)
13,178
Python
49.688461
142
0.711716
StanfordVL/OmniGibson/omnigibson/utils/sampling_utils.py
import itertools from collections import Counter, defaultdict import numpy as np import time import trimesh from scipy.spatial.transform import Rotation as R from scipy.stats import truncnorm import omnigibson as og from omnigibson.macros import create_module_macros, gm import omnigibson.utils.transform_utils as T 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.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 * np.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): np.array 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(axis=0) x = points - ctr normal = np.linalg.svd(np.dot(x.T, x))[0][:, -1] normal /= np.linalg.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): np.array 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 np.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): np.array 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 np.abs(np.dot(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): np.array 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 - np.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 """ # Import here to avoid circular imports from omnigibson.objects.primitive_object import PrimitiveObject color = np.concatenate([np.random.rand(3), [1]]) for vec in hit_positions: time_str = str(time.time()) cur_time = time_str[(time_str.index(".") + 1):] obj = PrimitiveObject( prim_path=f"/World/debug_marker_{cur_time}", name=f"debug_marker_{cur_time}", primitive_type="Sphere", visual_only=True, rgba=color, radius=radius, ) og.sim.import_object(obj) obj.set_position(vec) 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 = np.random.rand(3) orthogonal_vector_1 = np.cross(ray_direction, random_vector) orthogonal_vector_1 /= np.linalg.norm(orthogonal_vector_1) # Get a second vector orthogonal to both the ray and the first vector. orthogonal_vector_2 = -np.cross(ray_direction, orthogonal_vector_1) orthogonal_vector_2 /= np.linalg.norm(orthogonal_vector_2) orthogonal_vectors = np.array([orthogonal_vector_1, orthogonal_vector_2]) assert np.all(np.isfinite(orthogonal_vectors)) # Convert the offset into a 2-vector if it already isn't one. offset = np.array([1, 1]) * offset # Compute the grid of rays steps = (offset / new_ray_per_horizontal_distance).astype(int) * 2 + 1 steps = np.maximum(steps, 3) x_range = np.linspace(-offset[0], offset[0], steps[0]) y_range = np.linspace(-offset[1], offset[1], steps[1]) ray_grid = np.dstack(np.meshgrid(x_range, y_range, indexing="ij")) 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 + np.dot(offsets, orthogonal_vectors) for offsets in ray_grid_flattened] destinations = [destination + np.dot(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 = np.random.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 = np.random.choice([0, 1, 2], p=axis_probabilities) # 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 = np.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 numpy arrays start_point, end_point = np.array(start_point), np.array(end_point) point_diff = end_point - start_point distance = np.linalg.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: return og.sim.psqi.raycast_closest( origin=start_point, dir=direction, distance=distance, ) 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": np.array(hit.position), "normal": np.array(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, dir=direction, distance=distance, 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=m.DEFAULT_AABB_OFFSET_FRACTION, max_sampling_attempts=m.DEFAULT_MAX_SAMPLING_ATTEMPTS, ): """ 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 """ 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 start_points = np.zeros((num_samples, max_sampling_attempts, 3)) end_points = np.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 = trimesh.transformations.transform_points(start_points.reshape(-1, 3), to_wf_transform).reshape(orig_shape) end_points = trimesh.transformations.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=m.DEFAULT_AABB_OFFSET_FRACTION, ): """ 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 """ 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 = np.linspace(-half_extent_with_offset[0], half_extent_with_offset[0], int(half_extent_with_offset[0] * 2 / ray_spacing) + 1) y = np.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 = np.stack([ np.tile(x, len(y)), np.repeat(y, len(x)), np.ones(n_rays) * half_extent_with_offset[2], ]).T end_points = np.copy(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 = trimesh.transformations.transform_points(start_points, to_wf_transform) end_points = trimesh.transformations.transform_points(end_points, to_wf_transform) start_points = np.expand_dims(start_points, axis=1) end_points = np.expand_dims(end_points, axis=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=m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE, hit_proportion=m.DEFAULT_HIT_PROPORTION, aabb_offset=None, aabb_offset_fraction=m.DEFAULT_AABB_OFFSET_FRACTION, max_sampling_attempts=m.DEFAULT_MAX_SAMPLING_ATTEMPTS, max_angle_with_z_axis=m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS, parallel_ray_normal_angle_tolerance=m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE, hit_to_plane_threshold=m.DEFAULT_HIT_TO_PLANE_THRESHOLD, cuboid_bottom_padding=m.DEFAULT_CUBOID_BOTTOM_PADDING, 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. """ 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=m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE, hit_proportion=m.DEFAULT_HIT_PROPORTION, aabb_offset=None, aabb_offset_fraction=m.DEFAULT_AABB_OFFSET_FRACTION, max_angle_with_z_axis=m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS, parallel_ray_normal_angle_tolerance=m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE, hit_to_plane_threshold=m.DEFAULT_HIT_TO_PLANE_THRESHOLD, cuboid_bottom_padding=m.DEFAULT_CUBOID_BOTTOM_PADDING, 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. """ 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=m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE, hit_proportion=m.DEFAULT_HIT_PROPORTION, max_angle_with_z_axis=m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS, parallel_ray_normal_angle_tolerance=m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE, hit_to_plane_threshold=m.DEFAULT_HIT_TO_PLANE_THRESHOLD, cuboid_bottom_padding=m.DEFAULT_CUBOID_BOTTOM_PADDING, 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. """ 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] cuboid_dimensions = np.array(cuboid_dimensions) if np.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, ) sources = np.array(sources) destinations = np.array(destinations) else: sources = np.array([start_pos]) destinations = np.array([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 = np.array([ray_res["position"] for ray_res in filtered_cast_results]) hit_normals = np.array([ray_res["normal"] for ray_res in filtered_cast_results]) hit_normals /= np.linalg.norm(hit_normals, axis=1, keepdims=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 *= np.sign(np.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 = np.array([ray_res.get("position", np.zeros(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_positions = cuboid_centroid[None, :] + ( rotation.apply( 0.5 * this_cuboid_dimensions * np.array( [ [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1], ] ) ) ) # 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 = np.zeros(3) rotation = R.from_quat([0, 0, 0, 1]) # We've found a nice attachment point. Continue onto next point to sample. results[i] = (cuboid_centroid, plane_normal, rotation.as_quat(), 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 np.sum(hits) < 3: if m.DEBUG_SAMPLING: refusal_log.append(f"insufficient hits to compute the rotation of the grid: needs 3, has {np.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 = np.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, _ = R.align_vectors(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 = np.clip( np.dot(hit_normals, center_hit_normal) / (np.linalg.norm(hit_normals, axis=1) * np.linalg.norm(center_hit_normal)), -1.0, 1.0, ) parallel_hit_normal_angles_to_hit_normal = np.arccos(parallel_hit_main_hit_dot_products) all_rays_hit_with_similar_normal = np.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" % (np.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 = np.arccos(np.clip(np.dot(hit_normal, np.array([0, 0, 1])), -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 = np.array([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 = np.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 = np.min(multiple_to_face_on_each_axis[np.isfinite(multiple_to_face_on_each_axis)]) # 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 np.any(np.isnan(point_on_face)) and not np.any(np.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. all_pairs = np.array(top_to_bottom_pairs + bottom_pairs + top_pairs) check_cast_results = raytest_batch(start_points=all_pairs[:, 0, :], end_points=all_pairs[:, 1, :]) 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
56,403
Python
48.60774
163
0.663511
StanfordVL/OmniGibson/omnigibson/utils/usd_utils.py
import math from collections.abc import Iterable import os import omnigibson.lazy as lazy import numpy as np import trimesh import omnigibson as og from omnigibson.macros import gm from omnigibson.utils.constants import JointType, PRIMITIVE_MESH_TYPES, PrimType from omnigibson.utils.python_utils import assert_valid_key from omnigibson.utils.ui_utils import suppress_omni_log import omnigibson.utils.transform_utils as T 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.omni.isaac.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, 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): """ 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. joint_frame_in_parent_frame_pos (np.ndarray or None): relative position of the joint frame to the parent frame (body0). joint_frame_in_parent_frame_quat (np.ndarray or None): relative orientation of the joint frame to the parent frame (body0). joint_frame_in_child_frame_pos (np.ndarray or None): relative position of the joint frame to the child frame (body1). joint_frame_in_child_frame_quat (np.ndarray 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. Returns: Usd.Prim: Created joint prim """ # 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, \ f"At least either body0 or body1 must be specified when creating a joint!" # Create the joint joint = getattr(lazy.pxr.UsdPhysics, joint_type).Define(og.sim.stage, prim_path) # Possibly add body0, body1 targets if body0 is not None: assert lazy.omni.isaac.core.utils.prims.is_prim_path_valid(body0), f"Invalid body0 path specified: {body0}" joint.GetBody0Rel().SetTargets([lazy.pxr.Sdf.Path(body0)]) if body1 is not None: assert lazy.omni.isaac.core.utils.prims.is_prim_path_valid(body1), f"Invalid body1 path specified: {body1}" joint.GetBody1Rel().SetTargets([lazy.pxr.Sdf.Path(body1)]) # Get the prim pointed to at this path joint_prim = lazy.omni.isaac.core.utils.prims.get_prim_at_path(prim_path) # Apply joint API interface lazy.pxr.PhysxSchema.PhysxJointAPI.Apply(joint_prim) # 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. og.sim.render() 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)) 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]])) 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)) 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]])) 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) # We update the simulation now without stepping physics if sim is playing so we can bypass the snapping warning from PhysicsUSD if og.sim.is_playing(): with suppress_omni_log(channels=["omni.physx.plugin"]): og.sim.pi.update_simulation(elapsedStep=0, currentTime=og.sim.current_time) # Return this joint return joint_prim class RigidContactAPI: """ Class containing class methods to aggregate rigid body contacts across all rigid bodies in the simulator """ # Dictionary mapping rigid body prim path to corresponding index in the contact view matrix _PATH_TO_ROW_IDX = None _PATH_TO_COL_IDX = None # Numpy array of rigid body prim paths where its array index directly corresponds to the corresponding # index in the contact view matrix _ROW_IDX_TO_PATH = None _COL_IDX_TO_PATH = None # Contact view for generating contact matrices at each timestep _CONTACT_VIEW = None # Current aggregated contacts over all rigid bodies at the current timestep. Shape: (N, N, 3) _CONTACT_MATRIX = None # Current cache, mapping 2-tuple (prim_paths_a, prim_paths_b) to contact values _CONTACT_CACHE = None @classmethod def initialize_view(cls): """ 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!" # Compile deterministic mapping from rigid body path to idx # Note that omni's ordering is based on the top-down object ordering path on the USD stage, which coincidentally # matches the same ordering we store objects in our registry. So the mapping we generate from our registry # mapping aligns with omni's ordering! i = 0 cls._PATH_TO_COL_IDX = dict() for obj in og.sim.scene.objects: if obj.prim_type == PrimType.RIGID: for link in obj.links.values(): if not link.kinematic_only: cls._PATH_TO_COL_IDX[link.prim_path] = i i += 1 # If there are no valid objects, clear the view and terminate early if i == 0: cls._CONTACT_VIEW = None return # Generate rigid body view, making sure to update the simulation first (without physics) so that the physx # backend is synchronized with any newly added objects # We also suppress the omni tensor plugin from giving warnings we expect og.sim.pi.update_simulation(elapsedStep=0, currentTime=og.sim.current_time) with suppress_omni_log(channels=["omni.physx.tensors.plugin"]): cls._CONTACT_VIEW = og.sim.physics_sim_view.create_rigid_contact_view( pattern="/World/*/*", filter_patterns=list(cls._PATH_TO_COL_IDX.keys()), ) # Create deterministic mapping from path to row index cls._PATH_TO_ROW_IDX = {path: i for i, path in enumerate(cls._CONTACT_VIEW.sensor_paths)} # Store the reverse mappings as well. This can just be a numpy array since the mapping uses integer indices cls._ROW_IDX_TO_PATH = np.array(list(cls._PATH_TO_ROW_IDX.keys())) cls._COL_IDX_TO_PATH = np.array(list(cls._PATH_TO_COL_IDX.keys())) # Sanity check generated view -- this should generate square matrices of shape (N, N, 3) n_bodies = len(cls._PATH_TO_COL_IDX) assert cls._CONTACT_VIEW.filter_count == n_bodies, \ f"Got unexpected contact view shape. Expected: (N, {n_bodies}); " \ f"got: (N, {cls._CONTACT_VIEW.filter_count})" @classmethod def get_body_row_idx(cls, prim_path): """ Returns: int: row idx assigned to the rigid body defined by @prim_path """ return cls._PATH_TO_ROW_IDX[prim_path] @classmethod def get_body_col_idx(cls, prim_path): """ Returns: int: col idx assigned to the rigid body defined by @prim_path """ return cls._PATH_TO_COL_IDX[prim_path] @classmethod def get_row_idx_prim_path(cls, idx): """ Returns: str: @prim_path corresponding to the row idx @idx in the contact matrix """ return cls._ROW_IDX_TO_PATH[idx] @classmethod def get_col_idx_prim_path(cls, idx): """ Returns: str: @prim_path corresponding to the column idx @idx in the contact matrix """ return cls._COL_IDX_TO_PATH[idx] @classmethod def get_all_impulses(cls): """ Grab all impulses at the current timestep Returns: n-array: (N, M, 3) impulse array defining current impulses between all N contact-sensor enabled rigid bodies in the simulator and M tracked rigid bodies """ # Generate the contact matrix if it doesn't already exist if cls._CONTACT_MATRIX is None: cls._CONTACT_MATRIX = cls._CONTACT_VIEW.get_contact_force_matrix(dt=1.0) return cls._CONTACT_MATRIX @classmethod def get_impulses(cls, prim_paths_a, prim_paths_b): """ Grabs the matrix representing all impulse forces between rigid prims from @prim_paths_a and rigid prims from @prim_paths_b Args: prim_paths_a (list of str): Rigid body prim path(s) with which to grab contact impulses against any of the rigid body prim path(s) defined by @prim_paths_b prim_paths_b (list of str): Rigid body prim path(s) with which to grab contact impulses against any of the rigid body prim path(s) defined by @prim_paths_a Returns: n-array: (N, M, 3) impulse array defining current impulses between N bodies from @prim_paths_a and M bodies from @prim_paths_b """ # Compute subset of matrix and return idxs_a = [cls._PATH_TO_ROW_IDX[path] for path in prim_paths_a] idxs_b = [cls._PATH_TO_COL_IDX[path] for path in prim_paths_b] return cls.get_all_impulses()[idxs_a][:, idxs_b] @classmethod def in_contact(cls, prim_paths_a, prim_paths_b): """ Check if any rigid prim from @prim_paths_a is in contact with any rigid prim from @prim_paths_b Args: prim_paths_a (list of str): Rigid body prim path(s) with which to check contact against any of the rigid body prim path(s) defined by @prim_paths_b prim_paths_b (list of str): Rigid body prim path(s) with which to check contact against any of the rigid body prim path(s) defined by @prim_paths_a Returns: bool: Whether any body from @prim_paths_a is in contact with any body from @prim_paths_b """ # Check if the contact tuple already exists in the cache; if so, return the value key = (tuple(prim_paths_a), tuple(prim_paths_b)) if key not in cls._CONTACT_CACHE: # In contact if any of the matrix values representing the interaction between the two groups is non-zero cls._CONTACT_CACHE[key] = np.any(cls.get_impulses(prim_paths_a=prim_paths_a, prim_paths_b=prim_paths_b)) return cls._CONTACT_CACHE[key] @classmethod def clear(cls): """ Clears the internal contact matrix and cache """ cls._CONTACT_MATRIX = None cls._CONTACT_CACHE = dict() 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 """ # Can only be done when sim is stopped assert 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 """ # 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 """ # 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 """ cls.ACTIVE_COLLISION_GROUPS = {} class FlatcacheAPI: """ Monolithic class for leveraging functionality meant to be used EXCLUSIVELY with flatcache. """ # Modified prims since transition from sim being stopped to sim being played occurred # This should get cleared every time og.sim.stop() gets called MODIFIED_PRIMS = set() @classmethod def sync_raw_object_transforms_in_usd(cls, prim): """ Manually synchronizes the per-link local raw transforms per-joint raw states from entity prim @prim using dynamic control interface as the ground truth. NOTE: This slightly abuses the dynamic control - usd integration, and should ONLY be used if flatcache is active, since the USD is not R/W at runtime and so we can write directly to child link poses on the USD without breaking the simulation! Args: prim (EntityPrim): prim whose owned links and joints should have their raw local states updated to match the "true" values found from the dynamic control interface """ # Make sure flatcache is enabled -- this should NEVER be called otherwise!! assert gm.ENABLE_FLATCACHE, "Syncing raw object transforms should only occur if flatcache is being used!" # We're somewhat abusing low-level dynamic control - physx - usd integration, but we (supposedly) know # what we're doing so we suppress logging so we don't see any error messages :D with suppress_omni_log(["omni.physx.plugin"]): # Import here to avoid circular imports from omnigibson.prims.xform_prim import XFormPrim # 1. For every link, update its xformOp properties based on the delta_tf between object frame and link frame obj_pos, obj_quat = XFormPrim.get_local_pose(prim) for link in prim.links.values(): rel_pos, rel_quat = T.relative_pose_transform(*link.get_position_orientation(), obj_pos, obj_quat) XFormPrim.set_local_pose(link, rel_pos, rel_quat) # 2. For every joint, update its linear / angular joint state if prim.n_joints > 0: joints_pos = prim.get_joint_positions() for joint, joint_pos in zip(prim.joints.values(), joints_pos): state_name = "linear" if joint.joint_type == JointType.JOINT_PRISMATIC else "angular" joint_pos = joint_pos if joint.joint_type == JointType.JOINT_PRISMATIC else joint_pos * 180.0 / np.pi joint.set_attribute(f"state:{state_name}:physics:position", float(joint_pos)) # Update the simulation without taking any time # This is needed because physx complains that we're manually writing to child links' poses, and will # subsequently not respect any additional writes to the object pose before an additional step is taken. # So we take a "zero" length step so that any additional writes to the object's pose at the current # timestep are respected og.sim.pi.update_simulation(elapsedStep=0, currentTime=og.sim.current_time) # Add this prim to the set of modified prims cls.MODIFIED_PRIMS.add(prim) @classmethod def reset_raw_object_transforms_in_usd(cls, prim): """ Manually resets the per-link local raw transforms and per-joint raw states from entity prim @prim to be zero. NOTE: This slightly abuses the dynamic control - usd integration, and should ONLY be used if flatcache is active, since the USD is not R/W at runtime and so we can write directly to child link poses on the USD without breaking the simulation! Args: prim (EntityPrim): prim whose owned links and joints should have their local values reset to be zero """ # Make sure flatcache is enabled -- this should NEVER be called otherwise!! assert gm.ENABLE_FLATCACHE, "Resetting raw object transforms should only occur if flatcache is being used!" # We're somewhat abusing low-level dynamic control - physx - usd integration, but we (supposedly) know # what we're doing so we suppress logging so we don't see any error messages :D with suppress_omni_log(["omni.physx.plugin"]): # Import here to avoid circular imports from omnigibson.prims.xform_prim import XFormPrim # 1. For every link, update its xformOp properties to be 0 for link in prim.links.values(): XFormPrim.set_local_pose(link, np.zeros(3), np.array([0, 0, 0, 1.0])) # 2. For every joint, update its linear / angular joint state to be 0 if prim.n_joints > 0: for joint in prim.joints.values(): state_name = "linear" if joint.joint_type == JointType.JOINT_PRISMATIC else "angular" joint.set_attribute(f"state:{state_name}:physics:position", 0.0) # Update the simulation without taking any time # This is needed because physx complains that we're manually writing to child links' poses, and will # subsequently not respect any additional writes to the object pose before an additional step is taken. # So we take a "zero" length step so that any additional writes to the object's pose at the current # timestep are respected og.sim.pi.update_simulation(elapsedStep=0, currentTime=og.sim.current_time) @classmethod def reset(cls): """ Resets the internal state of this FlatcacheAPI.This should only occur when the simulator is stopped """ # For any prim transforms that were manually updated, we need to restore their original transforms for prim in cls.MODIFIED_PRIMS: cls.reset_raw_object_transforms_in_usd(prim) cls.MODIFIED_PRIMS = set() class PoseAPI: """ This is a singleton class for getting world poses. Whenever we directly set the pose of a prim, we should call PoseAPI.invalidate(). After that, if we need to access the pose of a prim without stepping physics, this class will refresh the poses by syncing across USD-fabric-PhysX depending on the flatcache setting. """ VALID = False @classmethod def invalidate(cls): cls.VALID = False @classmethod def mark_valid(cls): cls.VALID = True @classmethod def _refresh(cls): if og.sim is not None and not cls.VALID: # when flatcache is on if og.sim._physx_fabric_interface: # no time step is taken here og.sim._physx_fabric_interface.update(og.sim.get_physics_dt(), og.sim.current_time) # when flatcache is off else: # no time step is taken here og.sim.psi.fetch_results() cls.mark_valid() @classmethod def get_world_pose(cls, prim_path): cls._refresh() position, orientation = lazy.omni.isaac.core.utils.xforms.get_world_pose(prim_path) return np.array(position), np.array(orientation)[[1, 2, 3, 0]] @classmethod def get_world_pose_with_scale(cls, 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. """ cls._refresh() return np.array(lazy.omni.isaac.core.utils.xforms._get_world_pose_transform_w_scale(prim_path)).T def clear(): """ Clear state tied to singleton classes """ PoseAPI.invalidate() CollisionAPI.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 """ 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 = np.array(mesh_prim.GetAttribute("faceVertexCounts").Get()) vertices = np.array(mesh_prim.GetAttribute("points").Get()) face_indices = np.array(mesh_prim.GetAttribute("faceVertexIndices").Get()) 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"] = np.array(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=np.array(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(PoseAPI.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: np.random.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 = tm.faces.flatten() n_vertices = len(faces_flat) # Sample vertices unique_vertices = np.unique(faces_flat) assert len(unique_vertices) == n_unique_vertices keypoint_idx = np.random.choice(unique_vertices, size=n_keypoints, replace=False) if \ n_unique_vertices > n_keypoints else unique_vertices # Sample faces keyface_idx = np.random.choice(n_unique_faces, size=n_keyfaces, replace=False) if \ n_unique_faces > n_keyfaces else np.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, np.array]: 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 = 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 = 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 = np.zeros(3) return volume, com def check_extent_radius_ratio(mesh_prim): """ Checks if the min extent in world frame and the extent radius ratio in local frame of @mesh_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: mesh_prim (Usd.Prim): Mesh prim to check Returns: bool: True if the min extent (world) and the extent radius ratio (local frame) is acceptable, False otherwise """ mesh_type = mesh_prim.GetPrimTypeInfo().GetTypeName() # Non-mesh prims are always considered to be within the acceptable range if mesh_type != "Mesh": return True trimesh_mesh_world = mesh_prim_to_trimesh_mesh(mesh_prim, include_normals=False, include_texcoord=False, world_frame=True) min_extent = trimesh_mesh_world.extents.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 trimesh_mesh = mesh_prim_to_trimesh_mesh(mesh_prim, include_normals=False, include_texcoord=False, world_frame=False) if not trimesh_mesh.is_volume: trimesh_mesh = trimesh_mesh.convex_hull max_radius = trimesh_mesh.extents.max() / 2.0 min_radius = trimesh.proximity.closest_point(trimesh_mesh, np.array([trimesh_mesh.center_mass]))[1][0] 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) 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 = np.ones(3) * extents if isinstance(extents, float) else np.array(extents) for attr in (mesh.GetPointsAttr(), mesh.GetNormalsAttr()): vals = np.array(attr.Get()).astype(np.float64) attr.Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*(val * extents * 50.0)) for val in vals])) mesh.GetExtentAttr().Set(lazy.pxr.Vt.Vec3fArray([lazy.pxr.Gf.Vec3f(*(-extents / 2.0)), lazy.pxr.Gf.Vec3f(*(extents / 2.0))])) 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 """ # Make sure this is actually a supported asset type assert asset_path[-4:].lower() in {".usd", ".obj"}, f"Cannot load a non-USD or non-OBJ file as a USD prim!" asset_type = asset_path[-3:] # 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.omni.isaac.core.utils.stage.add_reference_to_stage(usd_path=asset_path, prim_path=prim_path) prim = lazy.omni.isaac.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.omni.isaac.core.utils.prims.get_prim_at_path("/World")
40,894
Python
45.209039
159
0.665208
StanfordVL/OmniGibson/omnigibson/utils/config_utils.py
import collections.abc import json import os import numpy as np 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 NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj)
1,691
Python
20.974026
143
0.628622
StanfordVL/OmniGibson/omnigibson/utils/constants.py
""" Constant Definitions """ from functools import cache import hashlib import os import numpy as np from enum import Enum, IntEnum import omnigibson as og from omnigibson.macros import gm from omnigibson.utils.asset_utils import get_og_avg_category_specs, get_all_object_categories MAX_INSTANCE_COUNT = np.iinfo(np.uint32).max MAX_CLASS_COUNT = np.iinfo(np.uint32).max MAX_VIEWER_SIZE = 2048 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" # Structure categories that need to always be loaded for stability purposes STRUCTURE_CATEGORIES = frozenset({"floors", "walls", "ceilings", "lawn", "driveway", "fence", "roof", "background"}) # Joint friction magic values to assign to objects based on their category DEFAULT_JOINT_FRICTION = 10.0 SPECIAL_JOINT_FRICTIONS = { "oven": 30.0, "dishwasher": 30.0, "toilet": 3.0, } 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 AVERAGE_CATEGORY_SPECS = get_og_avg_category_specs() def get_collision_group_mask(groups_to_exclude=[]): """Get a collision group mask that has collisions enabled for every group except those in groups_to_exclude.""" collision_mask = ALL_COLLISION_GROUPS_MASK for group in groups_to_exclude: collision_mask &= ~(1 << group) return collision_mask 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 """ categories = get_all_object_categories() from omnigibson.systems.system_base import REGISTERED_SYSTEMS systems = sorted(REGISTERED_SYSTEMS) all_semantics = sorted(set(categories + systems + ["background", "unlabelled", "object", "light", "agent"])) # Assign a unique class id to each class name with hashing class_name_to_class_id = {s: int(hashlib.md5(s.encode()).hexdigest(), 16) % (2 ** 32) 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()}
5,031
Python
23.546341
116
0.659113
StanfordVL/OmniGibson/omnigibson/utils/teleop_utils.py
import numpy as np import time from typing import Iterable, Optional, Tuple 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.objects import USDObject from omnigibson.robots.robot_base import BaseRobot try: from telemoma.human_interface.teleop_core import TeleopAction, TeleopObservation from telemoma.human_interface.teleop_policy import TeleopPolicy from telemoma.utils.general_utils import AttrDict from telemoma.configs.base_config import teleop_config except ImportError as e: raise e from ValueError("For teleoperation, install telemoma by running 'pip install telemoma'") m = create_module_macros(module_path=__file__) m.movement_speed = 0.2 # the speed of the robot base movement class TeleopSystem(TeleopPolicy): """ Base class for teleop policy """ def __init__(self, config: AttrDict, robot: BaseRobot, show_control_marker: bool = False) -> None: """ Initializes the Teleoperation System Args: config (AttrDict): configuration dictionary robot (BaseRobot): the robot that will be controlled. 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 = TeleopAction() self.robot_obs: TeleopObservation = TeleopObservation() self.robot = robot self.robot_arms = ["left", "right"] if self.robot.n_arms == 2 else ["right"] # robot parameters self.movement_speed = m.movement_speed self.show_control_marker = show_control_marker self.control_markers = {} if show_control_marker: for arm in robot.arm_names: arm_name = "right" if arm == robot.default_arm else "left" self.control_markers[arm_name] = USDObject(name=f"target_{arm_name}", usd_path=robot.eef_usd_path[arm], visual_only=True) og.sim.import_object(self.control_markers[arm_name]) def get_obs(self) -> TeleopObservation: """ Retrieve observation data from robot Returns: TeleopObservation: dataclass containing robot observations """ robot_obs = TeleopObservation() base_pos, base_orn = self.robot.get_position_orientation() robot_obs.base = np.r_[base_pos[:2], [T.quat2euler(base_orn)[2]]] 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 = np.mean( self.robot.get_joint_positions(normalized=True)[self.robot.gripper_control_idx[self.robot.arm_names[i]]] ) # if we are grasping, we manually set the gripper position to be at most 0.5 if self.robot.controllers[f"gripper_{self.robot.arm_names[i]}"].is_grasping(): gripper_pos = min(gripper_pos, 0.5) robot_obs[arm] = np.r_[ rel_cur_pos, rel_cur_orn, gripper_pos ] return robot_obs def get_action(self, robot_obs: TeleopObservation) -> np.ndarray: """ Generate action data from VR input for robot teleoperation Args: robot_obs (TeleopObservation): dataclass containing robot observations Returns: np.ndarray: array of action data """ # get teleop action self.teleop_action = super().get_action(robot_obs) # optionally update control marker if self.show_control_marker: for arm_name in self.control_markers: delta_pos, delta_orn = self.teleop_action[arm_name][:3], T.euler2quat(self.teleop_action[arm_name][3:6]) rel_target_pos = robot_obs[arm_name][:3] + delta_pos rel_target_orn = T.quat_multiply(delta_orn, robot_obs[arm_name][3:7]) base_pos, base_orn = self.robot.get_position_orientation() target_pos, target_orn = T.pose_transform(base_pos, base_orn, rel_target_pos, rel_target_orn) self.control_markers[arm_name].set_position_orientation(target_pos, target_orn) 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: BaseRobot, show_control_marker: bool = False, system: str = "SteamVR", disable_display_output: bool = False, enable_touchpad_movement: bool = False, align_anchor_to_robot_base: bool = False, use_hand_tracking: bool = False, ) -> None: """ Initializes the VR system Args: robot (BaseRobot): 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. enable_touchpad_movement (bool): whether to enable VR system anchor movement by controller, default is False. align_anchor_to_robot_base (bool): whether to align VR anchor to robot base, default is False. use_hand_tracking (bool): whether to use hand tracking instead of controllers, default is False. show_controller (bool): whether to show the controller model in the scene, default is False. NOTE: enable_touchpad_movement and align_anchor_to_robot_base cannot be enabled at the same time. The former is to enable free movement of the VR system (i.e. the user), while the latter is constraining the VR system to the robot pose. """ self.raw_data = {} # enable xr extension lazy.omni.isaac.core.utils.extensions.enable_extension("omni.kit.xr.profile.vr") self.xr_device_class = lazy.omni.kit.xr.core.XRDeviceClass # run super method super().__init__(teleop_config, robot, show_control_marker) # we want to further slow down the movement speed if we are using touchpad movement if enable_touchpad_movement: self.movement_speed *= 0.3 # 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 self.enable_touchpad_movement = enable_touchpad_movement self.align_anchor_to_robot_base = align_anchor_to_robot_base assert not (self.enable_touchpad_movement and self.align_anchor_to_robot_base), \ "enable_touchpad_movement and align_anchor_to_robot_base cannot be True at the same time!" # set avatar if self.show_control_marker: self.vr_profile.set_avatar(lazy.omni.kit.xr.ui.stage.common.XRAvatarManager.get_singleton().create_avatar("basic_avatar", {})) else: self.vr_profile.set_avatar(lazy.omni.kit.xr.ui.stage.common.XRAvatarManager.get_singleton().create_avatar("empty_avatar", {})) # set anchor mode to be custom anchor lazy.carb.settings.get_settings().set(self.vr_profile.get_scene_persistent_path() + "anchorMode", "scene origin") # 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 = {} self.xr2og_orn_offset = np.array([0.5, -0.5, -0.5, -0.5]) self.og2xr_orn_offset = np.array([-0.5, 0.5, 0.5, -0.5]) # setup event subscriptions self.reset() self.use_hand_tracking = use_hand_tracking if use_hand_tracking: self.raw_data["hand_data"] = {} self.teleop_action.hand_data = {} self._hand_tracking_subscription = self.xr_core.get_event_stream().create_subscription_to_pop_by_type( lazy.omni.kit.xr.core.XRCoreEventType.hand_joints, self._update_hand_tracking_data, name="hand tracking" ) def xr2og(self, transform: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ 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 (np.ndarray): the transform matrix in the Omniverse XR coordinate system Returns: tuple(np.ndarray, np.ndarray): the position and orientation in the OmniGibson coordinate system """ pos, orn = T.mat2pose(np.array(transform).T) orn = T.quat_multiply(orn, self.xr2og_orn_offset) return pos, orn def og2xr(self, pos: np.ndarray, orn: np.ndarray) -> np.ndarray: """ Apply the orientation offset from the OmniGibson coordinate system to the Omniverse XR coordinate system Args: pos (np.ndarray): the position in the OmniGibson coordinate system orn (np.ndarray): the orientation in the OmniGibson coordinate system Returns: np.ndarray: the transform matrix in the Omniverse XR coordinate system """ orn = T.quat_multiply(self.og2xr_orn_offset, orn) return T.pose2mat((pos, orn)).T.astype(np.float64) def reset(self) -> None: """ Reset the teleop policy """ super().reset() self.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 = np.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.step() 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 to become active...") self._update_devices() if self.hmd is not None: break time.sleep(1) og.sim.step() 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) -> None: """ Steps the VR system and update self.teleop_action """ # update raw data self._update_devices() self._update_device_transforms() self._update_button_data() # Update teleop data based on controller input if not using hand tracking if not self.use_hand_tracking: self.teleop_action.base = np.zeros(3) self.teleop_action.torso = 0.0 # update right hand related info for arm_name, arm in zip(["left", "right"], self.robot_arms): if arm in self.controllers: self.teleop_action[arm_name] = np.concatenate(( self.raw_data["transforms"]["controllers"][arm][0], T.quat2euler(T.quat_multiply( self.raw_data["transforms"]["controllers"][arm][1], self.robot.teleop_rotation_offset[self.robot.arm_names[self.robot_arms.index(arm)]] )), [self.raw_data["button_data"][arm]["axis"]["trigger"]] )) 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 and reset info if "right" in self.controllers: self.teleop_action.reset["right"] = self.raw_data["button_data"]["right"]["press"]["grip"] right_axis = self.raw_data["button_data"]["right"]["axis"] self.teleop_action.base[0] = right_axis["touchpad_y"] * self.movement_speed self.teleop_action.torso = -right_axis["touchpad_x"] * self.movement_speed if "left" in self.controllers: self.teleop_action.reset["left"] = self.raw_data["button_data"]["left"]["press"]["grip"] left_axis = self.raw_data["button_data"]["left"]["axis"] self.teleop_action.base[1] = -left_axis["touchpad_x"] * self.movement_speed self.teleop_action.base[2] = left_axis["touchpad_y"] * self.movement_speed # update head related info self.teleop_action.head = np.r_[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"]) # Optionally move anchor if self.enable_touchpad_movement: # we use x, y from right controller for 2d movement and y from left controller for z movement self._move_anchor(pos_offset=np.r_[[self.teleop_action.torso], self.teleop_action.base[[0, 2]]]) if self.align_anchor_to_robot_base: robot_base_pos, robot_base_orn = self.robot.get_position_orientation() self.vr_profile.set_virtual_world_anchor_transform(self.og2xr(robot_base_pos, robot_base_orn[[0, 2, 1, 3]])) def teleop_data_to_action(self) -> np.ndarray: """ Generate action data from VR input for robot teleoperation Returns: np.ndarray: array of action data """ # optionally update control marker if self.show_control_marker: self.update_control_marker() return self.robot.teleop_data_to_action(self.teleop_action) def reset_transform_mapping(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". """ robot_base_orn = self.robot.get_orientation() robot_eef_pos = self.robot.eef_links[self.robot.arm_names[self.robot_arms.index(arm)]].get_position() 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, self.controllers[arm]) def set_initial_transform(self, pos: Iterable[float], orn: Iterable[float]=[0, 0, 0, 1]) -> None: """ Function that sets the initial transform of the VR system (w.r.t.) head Note that stepping the vr system multiple times is necessary here due to a bug in OVXR plugin Args: pos(Iterable[float]): initial position of the vr system orn(Iterable[float]): initial orientation of the vr system """ for _ in range(10): self.update() og.sim.step() self.vr_profile.set_physical_world_to_world_anchor_transform_to_match_xr_device(self.og2xr(pos, orn), self.hmd) 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 = np.array([-pos_offset[0], pos_offset[2], -pos_offset[1]]).astype(np.float64) self.vr_profile.add_move_physical_world_relative_to_device(pos_offset) if rot_offset is not None: rot_offset = np.array(rot_offset).astype(np.float64) self.vr_profile.add_rotate_physical_world_around_device(rot_offset) def _is_valid_transform(self, transform: Tuple[np.ndarray, np.ndarray]) -> bool: """ Determine whether the transform is valid (ovxr plugin will return a zero position and rotation if not valid) """ return np.any(np.not_equal(transform[0], np.zeros(3))) \ and np.any(np.not_equal(transform[1], self.og2xr_orn_offset)) def _update_devices(self) -> None: """ Update the VR device list """ for device in self.vr_profile.get_device_list(): if device.get_class() == self.xr_device_class.xrdisplaydevice: self.hmd = device elif device.get_class() == self.xr_device_class.xrcontroller: # we want the first 2 controllers to be corresponding to the left and right hand d_idx = device.get_index() controller_name = ["left", "right"][d_idx] if d_idx < 2 else f"controller_{d_idx+1}" self.controllers[controller_name] = device elif device.get_class() == self.xr_device_class.xrtracker: self.trackers[device.get_index()] = device def _update_device_transforms(self) -> None: """ Get the transform matrix of each VR device *in world frame* and store in self.raw_data """ transforms = {} transforms["head"] = self.xr2og(self.hmd.get_virtual_world_pose()) transforms["controllers"] = {} transforms["trackers"] = {} for controller_name in self.controllers: transforms["controllers"][controller_name] = self.xr2og( self.controllers[controller_name].get_virtual_world_pose()) for tracker_index in self.trackers: transforms["trackers"][tracker_index] = self.xr2og(self.trackers[tracker_index].get_virtual_world_pose()) self.raw_data["transforms"] = transforms def _update_button_data(self): """ Get the button data for each controller and store in self.raw_data Returns: dict: a dictionary of whether each button is pressed or touched, and the axis state for touchpad and joysticks """ button_data = {} for controller_name in self.controllers: button_data[controller_name] = {} button_data[controller_name]["press"] = self.controllers[controller_name].get_button_press_state() button_data[controller_name]["touch"] = self.controllers[controller_name].get_button_touch_state() button_data[controller_name]["axis"] = self.controllers[controller_name].get_axis_state() self.raw_data["button_data"] = button_data 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 hand_name, hand in zip(["left, right"], self.robot_arms): if data_dict[f"joint_count_{hand}"] != 0: self.teleop_action.is_valid[hand_name] = 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 i in range(26): # extract the pose from the flattened transform matrix pos, orn = self.xr2og(np.reshape(hand_joint_matrices[16 * i: 16 * (i + 1)], (4, 4))) self.raw_data["hand_data"][hand]["pos"].append(pos) self.raw_data["hand_data"][hand]["orn"].append(orn) self.teleop_action[hand_name] = np.r_[ 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[self.robot.arm_names[self.robot_arms.index(hand)]] )), [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 = np.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 /= np.linalg.norm(v1) v2 /= np.linalg.norm(v2) joint_angles[i, j] = np.arccos(v1 @ v2) self.teleop_action.hand_data[hand_name] = joint_angles
23,087
Python
50.079646
149
0.602157
StanfordVL/OmniGibson/omnigibson/utils/render_utils.py
""" Set of rendering utility functions when working with Omni """ import numpy as np import omnigibson as og from omnigibson.prims import EntityPrim, RigidPrim, VisualGeomPrim from omnigibson.utils.physx_utils import bind_material import omnigibson.utils.transform_utils as T import omnigibson.lazy as lazy def make_glass(prim): """ Links the OmniGlass material with EntityPrim, RigidPrim, or VisualGeomPrim @obj, and procedurally generates the necessary OmniGlass material prim if necessary. Args: prim (EntityPrim or RigidPrim or VisualGeomPrim): Desired prim to convert into glass """ # 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, VisualGeomPrim): # Just use this visual mesh visual_meshes = [prim] else: raise ValueError(f"Inputted prim must an instance of EntityPrim, RigidPrim, or VisualGeomPrim " f"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.omni.isaac.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 = [] 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.omni.isaac.core.utils.prims.get_prim_at_path(material_path) def create_skylight(intensity=500, color=(1.0, 1.0, 1.0)): """ Creates a skylight object with the requested @color Args: intensity (float): Intensity of the generated skylight color (3-array): Desired (R,G,B) color to assign to the skylight Returns: LightObject: Generated skylight object """ # Avoid circular imports from omnigibson.objects.light_object import LightObject light = LightObject(prim_path="/World/skylight", name="skylight", light_type="Dome", intensity=intensity) og.sim.import_object(light) light.set_orientation(T.euler2quat([0, 0, -np.pi / 4])) light_prim = light.light_link.prim light_prim.GetAttribute("color").Set(lazy.pxr.Gf.Vec3f(*color)) return light
3,476
Python
35.6
111
0.682969
StanfordVL/OmniGibson/omnigibson/utils/control_utils.py
""" Set of utilities for helping to execute robot control """ import omnigibson.lazy as lazy import numpy as np from numba import jit 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 = pose3_lula.translation # get orientation rotation_lula = pose3_lula.rotation link_orientation = ( rotation_lula.x(), rotation_lula.y(), rotation_lula.z(), rotation_lula.w(), ) 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, max_iterations=150, 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 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 = np.array(target_pos, dtype=np.float64).reshape(3, 1) rot = np.array(T.quat2mat(np.array([0, 0, 0, 1.0]) if target_quat is None else target_quat), dtype=np.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 np.array(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.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 np.array(ik_results.cspace_position) else: return None @jit(nopython=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
6,400
Python
37.793939
118
0.634844
StanfordVL/OmniGibson/omnigibson/utils/ui_utils.py
""" Helper classes and functions for streamlining user interactions """ import contextlib import logging import numpy as np import sys import datetime from pathlib import Path from PIL import Image from termcolor import colored import omnigibson as og from omnigibson.macros import gm import omnigibson.utils.transform_utils as T import omnigibson.lazy as lazy from scipy.spatial.transform import Rotation as R from scipy.interpolate import CubicSpline from scipy.integrate import quad import imageio from IPython import embed 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 = [ (" ___ _", " ____ _ _ "), (" / _ \ _ __ ___ _ __ (_)", "/ ___(_) |__ ___ ___ _ __ "), (" | | | | '_ ` _ \| '_ \| |", " | _| | '_ \/ __|/ _ \| '_ \ "), (" | |_| | | | | | | | | | |", " |_| | | |_) \__ \ (_) | | | |"), (" \___/|_| |_| |_|_| |_|_|", "\____|_|_.__/|___/\___/|_| |_|"), ] 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 @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): """ 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 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 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: k = np.random.choice(range(len(options))) # 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 <OMNIGIBSON_PATH>/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.omni.isaac.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("intensity").Set(intensity) def print_info(self): """ Prints keyboard command info out to the user """ print("*" * 40) print("CameraMover! Commands:") print() print(f"\t Right Click + Drag: Rotate camera") print(f"\t W / S : Move camera forward / backward") print(f"\t A / D : Move camera left / right") print(f"\t T / G : Move camera up / down") print(f"\t 9 / 0 : Increase / decrease the lights") print(f"\t P : Print current camera pose") print(f"\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: np.array: (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()).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()) # 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 (np.array): (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 np.sqrt(np.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 = np.zeros((path_length, 3)) for i in range(path_length): curr_step = step + (i / path_length) interpolated_points[i, :] = np.array([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 / np.linalg.norm(direction) # Infer tilt and pan angles from this direction xy_direction = direction[:2] / np.linalg.norm(direction[:2]) z = direction[2] pan_angle = np.arctan2(-xy_direction[0], xy_direction[1]) tilt_angle = np.arcsin(z) # Infer global quat orientation from these angles quat = T.euler2quat([np.pi / 2 - tilt_angle, 0.0, pan_angle]) 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: np.array([self.delta, 0, 0]), lazy.carb.input.KeyboardInput.A: np.array([-self.delta, 0, 0]), lazy.carb.input.KeyboardInput.W: np.array([0, 0, -self.delta]), lazy.carb.input.KeyboardInput.S: np.array([0, 0, self.delta]), lazy.carb.input.KeyboardInput.T: np.array([0, self.delta, 0]), lazy.carb.input.KeyboardInput.G: np.array([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 transform = T.quat2mat(self.cam.get_orientation()) delta_pos_global = transform @ command self.cam.set_position(self.cam.get_position() + 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_controller = dict() idx = 0 for name, controller in robot._controllers.items(): self.controller_info[name] = { "name": type(controller).__name__, "start_idx": idx, "dofs": controller.dof_idx, "command_dim": controller.command_dim, } idx += controller.command_dim for i in controller.dof_idx: self.joint_idx_to_controller[i] = controller # 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.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() sub_keyboard = 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.5} mapping[lazy.carb.input.KeyboardInput.DOWN] = {"idx": controller_info["start_idx"] + 0, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.RIGHT] = {"idx": controller_info["start_idx"] + 1, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.LEFT] = {"idx": controller_info["start_idx"] + 1, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.P] = {"idx": controller_info["start_idx"] + 2, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.SEMICOLON] = {"idx": controller_info["start_idx"] + 2, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.N] = {"idx": controller_info["start_idx"] + 3, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.B] = {"idx": controller_info["start_idx"] + 3, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.O] = {"idx": controller_info["start_idx"] + 4, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.U] = {"idx": controller_info["start_idx"] + 4, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.V] = {"idx": controller_info["start_idx"] + 5, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.C] = {"idx": controller_info["start_idx"] + 5, "val": -0.5} 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.5} mapping[lazy.carb.input.KeyboardInput.DOWN] = {"idx": controller_info["start_idx"] + 0, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.RIGHT] = {"idx": controller_info["start_idx"] + 1, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.LEFT] = {"idx": controller_info["start_idx"] + 1, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.P] = {"idx": controller_info["start_idx"] + 2, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.SEMICOLON] = {"idx": controller_info["start_idx"] + 2, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.N] = {"idx": controller_info["start_idx"] + 3, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.B] = {"idx": controller_info["start_idx"] + 3, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.O] = {"idx": controller_info["start_idx"] + 4, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.U] = {"idx": controller_info["start_idx"] + 4, "val": -0.5} mapping[lazy.carb.input.KeyboardInput.V] = {"idx": controller_info["start_idx"] + 5, "val": 0.5} mapping[lazy.carb.input.KeyboardInput.C] = {"idx": controller_info["start_idx"] + 5, "val": -0.5} return mapping def populate_keypress_mapping(self): """ Populates the mapping @self.keypress_mapping, which maps keypresses to action info: keypress: idx: <int> val: <float> """ 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"] == "JointController": 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} with IK") 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, clear the active action and keypress elif event.type == lazy.carb.input.KeyboardEventType.KEY_RELEASE: self.active_action = None self.current_keypress = None # Callback always needs to return True return True def get_random_action(self): """ Returns: n-array: Generated random action vector (normalized) """ return np.random.uniform(-1, 1, self.action_dim) def get_teleop_action(self): """ Returns: n-array: Generated action vector based on received user inputs from the keyboard """ action = np.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 controller = self.joint_idx_to_controller[joint_idx] if (self.joint_types[joint_idx] == JointType.JOINT_PRISMATIC and controller.use_delta_commands and controller.motor_type == "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] # 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)) sys.stdout.write("\033[F") # 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("i, k", "turn left, right") print_command("l, j", "move forward, backwards") print() print("Inverse Kinematics Control") print_command("3, 4", "toggle between the different arm(s) to control") print_command(u"\u2190, \u2192", "translate arm eef along x-axis") print_command(u"\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_line(start, end, color=(1., 0., 0., 1.), size=1.): """ Draws a single line between two points. """ from omni.isaac.debug_draw import _debug_draw draw = _debug_draw.acquire_debug_draw_interface() draw.draw_lines([start], [end], [color], [size]) def draw_box(center, extents, color=(1., 0., 0., 1.), size=1.): """ 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. """ from omni.isaac.debug_draw import _debug_draw draw = _debug_draw.acquire_debug_draw_interface() draw.clear_lines()
44,222
Python
43.896447
144
0.600018
StanfordVL/OmniGibson/omnigibson/utils/transform_utils.py
""" Utility functions of matrix and vector transformations. NOTE: convention for quaternions is (x, y, z, w) """ import math import numpy as np 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 ewma_vectorized(data, alpha, offset=None, dtype=None, order="C", out=None): """ Calculates the exponential moving average over a vector. Will fail for large inputs. Args: data (Iterable): Input data alpha (float): scalar in range (0,1) The alpha parameter for the moving average. offset (None or float): If specified, the offset for the moving average. None defaults to data[0]. dtype (None or type): Data type used for calculations. If None, defaults to float64 unless data.dtype is float32, then it will use float32. order (None or str): Order to use when flattening the data. Valid options are {'C', 'F', 'A'}. None defaults to 'C'. out (None or np.array): If specified, the location into which the result is stored. If provided, it must have the same shape as the input. If not provided or `None`, a freshly-allocated array is returned. Returns: np.array: Exponential moving average from @data """ data = np.array(data, copy=False) if dtype is None: if data.dtype == np.float32: dtype = np.float32 else: dtype = np.float64 else: dtype = np.dtype(dtype) if data.ndim > 1: # flatten input data = data.reshape(-1, order) if out is None: out = np.empty_like(data, dtype=dtype) else: assert out.shape == data.shape assert out.dtype == dtype if data.size < 1: # empty input, return empty array return out if offset is None: offset = data[0] alpha = np.array(alpha, copy=False).astype(dtype, copy=False) # scaling_factors -> 0 as len(data) gets large # this leads to divide-by-zeros below scaling_factors = np.power(1.0 - alpha, np.arange(data.size + 1, dtype=dtype), dtype=dtype) # create cumulative sum array np.multiply(data, (alpha * scaling_factors[-2]) / scaling_factors[:-1], dtype=dtype, out=out) np.cumsum(out, dtype=dtype, out=out) # cumsums / scaling out /= scaling_factors[-2::-1] if offset != 0: offset = np.array(offset, copy=False).astype(dtype, copy=False) # add offsets out += offset * scaling_factors[1:] return out 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): """ 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 = quaternion0 x1, y1, z1, w1 = quaternion1 return np.array( ( 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, ), dtype=np.float32, ) 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 """ return np.array( (-quaternion[0], -quaternion[1], -quaternion[2], quaternion[3]), dtype=np.float32, ) 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.dot(quaternion, quaternion) def quat_distance(quaternion1, quaternion0): """ Returns distance between two quaternions, such that distance * quaternion0 = quaternion1 Args: quaternion1 (np.array): (x,y,z,w) quaternion quaternion0 (np.array): (x,y,z,w) quaternion Returns: np.array: (x,y,z,w) quaternion distance """ 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 def random_quat(rand=None): """ Return uniform random unit quaternion. E.g.: >>> q = random_quat() >>> np.allclose(1.0, vector_norm(q)) True >>> q = random_quat(np.random.random(3)) >>> q.shape (4,) Args: rand (3-array or None): If specified, must be three independent random variables that are uniformly distributed between 0 and 1. Returns: np.array: (x,y,z,w) random quaternion """ if rand is None: rand = np.random.rand(3) else: assert len(rand) == 3 r1 = np.sqrt(1.0 - rand[0]) r2 = np.sqrt(rand[0]) pi2 = math.pi * 2.0 t1 = pi2 * rand[1] t2 = pi2 * rand[2] return np.array( (np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2, np.cos(t2) * r2), dtype=np.float32, ) 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 vec(values): """ Converts value tuple into a numpy vector. Args: values (n-array): a tuple of numbers Returns: np.array: vector of given values """ return np.array(values, dtype=np.float32) def mat4(array): """ Converts an array to 4x4 matrix. Args: array (n-array): the array in form of vec, list, or tuple Returns: np.array: a 4x4 numpy matrix """ return np.array(array, dtype=np.float32).reshape((4, 4)) def mat2pose(hmat): """ Converts a homogeneous 4x4 matrix into pose. Args: hmat (np.array): a 4x4 homogeneous matrix Returns: 2-tuple: - (np.array) (x,y,z) position array in cartesian coordinates - (np.array) (x,y,z,w) orientation array in quaternion form """ pos = hmat[:3, 3] orn = mat2quat(hmat[:3, :3]) return pos, orn 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() 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 euler2mat(euler): """ Converts 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 euler angles in radian. Args: rmat (np.array): 3x3 rotation matrix Returns: np.array: (r,p,y) converted 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") 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] = np.array(pose[0], dtype=np.float32) homo_pose_mat[3, 3] = 1.0 return homo_pose_mat def quat2mat(quaternion): """ Converts given quaternion to matrix. Args: quaternion (np.array): (..., 4) (x,y,z,w) float quaternion angles Returns: np.array: (..., 3, 3) rotation matrix """ return R.from_quat(quaternion).as_matrix() 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 euler2quat(euler): """ Converts 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 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 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): """ 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)) 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: (x,y,z) position to transform quat1: (x,y,z,w) orientation to transform pos0: (x,y,z) initial position quat0: (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: (x,y,z) position to transform quat: (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: (x,y,z) position to transform quat1: (x,y,z,w) orientation to transform pos0: (x,y,z) initial position quat0: (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., 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 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 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 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 l2_distance(v1, v2): """Returns the L2 distance between vector v1 and v2.""" return np.linalg.norm(np.array(v1) - np.array(v2)) def frustum(left, right, bottom, top, znear, zfar): """Create view frustum matrix.""" assert right != left assert bottom != top assert znear != zfar M = np.zeros((4, 4), dtype=np.float32) M[0, 0] = +2.0 * znear / (right - left) M[2, 0] = (right + left) / (right - left) M[1, 1] = +2.0 * znear / (top - bottom) # TODO: Put this back to 3,1 # M[3, 1] = (top + bottom) / (top - bottom) M[2, 1] = (top + bottom) / (top - bottom) M[2, 2] = -(zfar + znear) / (zfar - znear) M[3, 2] = -2.0 * znear * zfar / (zfar - znear) M[2, 3] = -1.0 return M def ortho(left, right, bottom, top, znear, zfar): """Create orthonormal projection matrix.""" assert right != left assert bottom != top assert znear != zfar M = np.zeros((4, 4), dtype=np.float32) M[0, 0] = 2.0 / (right - left) M[1, 1] = 2.0 / (top - bottom) M[2, 2] = -2.0 / (zfar - znear) M[3, 0] = -(right + left) / (right - left) M[3, 1] = -(top + bottom) / (top - bottom) M[3, 2] = -(zfar + znear) / (zfar - znear) M[3, 3] = 1.0 return M def perspective(fovy, aspect, znear, zfar): """Create perspective projection matrix.""" # fovy is in degree assert znear != zfar h = np.tan(fovy / 360.0 * np.pi) * znear w = h * aspect return frustum(-w, w, -h, h, znear, zfar) 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 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. def rad2deg(rad): return rad * 180. / 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 z_rotation_from_quat(quat): """Get the quaternion for the rotation around the Z axis produced by the quaternion.""" return R.from_euler("z", z_angle_from_quat(quat)).as_quat()
34,011
Python
28.524306
139
0.591191
StanfordVL/OmniGibson/omnigibson/utils/vision_utils.py
import colorsys import numpy as np from PIL import Image, ImageDraw try: import accimage except ImportError: accimage = None 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 = np.random.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 = np.array([], dtype=np.uint32) # Initialize the key_array as empty self.known_ids = set() def clear(self): """Resets the key_array to empty.""" self.key_array = np.array([], dtype=np.uint32) self.known_ids = set() def remap(self, old_mapping, new_mapping, image): """ 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 (np.ndarray): The 2D image to remap, e.g. [[1, 3], [1, 2]]. Returns: np.ndarray: 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 uint32 doesn't match any value in the new mapping assert np.all(np.array(list(new_mapping.keys())) != np.iinfo(np.uint32).max), "New mapping contains default unmapped value!" image_max_key = np.max(image) key_array_max_key = len(self.key_array) - 1 if image_max_key > key_array_max_key: prev_key_array = self.key_array.copy() # We build a new key array and use max uint32 as the default value. self.key_array = np.full(image_max_key + 1, np.iinfo(np.uint32).max, dtype=np.uint32) # Copy the previous key array into the new key array self.key_array[:len(prev_key_array)] = prev_key_array 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 # 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 np.unique(image): if key 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, f"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 np.all(remapped_img != np.iinfo(np.uint32).max), "Not all keys in the image are in the key array!" remapped_labels = {} for key in np.unique(remapped_img): remapped_labels[key] = new_mapping[key] return remapped_img, remapped_labels def remap_bbox(self, semantic_id): """ Remaps a semantic id to a new id using the key_array. Args: semantic_id (int): The semantic id to remap. Returns: int: The remapped id. """ assert semantic_id < len(self.key_array), f"Semantic id {semantic_id} is out of range!" return self.key_array[semantic_id] 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 = np.array(list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))) rstate = np.random.RandomState(seed=20) np.random.shuffle(colors) colors[0] = [0, 0, 0] # 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 = np.mod(seg_im, N) 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]).astype(np.uint8) else: return (use_colors[seg_im]).astype(np.float) 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 (np.ndarray): 3D bounding box data rgb_image (np.ndarray): RGB image camera_params (dict): Camera parameters Returns: np.ndarray: 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 = np.dot(view_mat, proj_mat) world_points_homo = np.pad(world_points, ((0, 0), (0, 1)), constant_values=1.0) tf_points = np.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 *= np.array([[width, height]]) # Now, draw all bounding boxes draw_lines_and_points_for_boxes(rgb, corners_2d) return np.array(rgb)
10,880
Python
39.752809
141
0.598805
StanfordVL/OmniGibson/omnigibson/utils/lazy_import_utils.py
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
1,701
Python
34.458333
104
0.586714
StanfordVL/OmniGibson/omnigibson/utils/sim_utils.py
import numpy as np from collections import namedtuple from collections.abc import Iterable import omnigibson as og from omnigibson.macros import gm from omnigibson.utils import python_utils import omnigibson.utils.transform_utils as T import omnigibson.lazy as lazy from omnigibson.utils.ui_utils import create_module_logger # Create module logger log = create_module_logger(module_name=__name__) # Raw Body Contact Information # See https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.contact_sensor/docs/index.html?highlight=contact%20sensor#omni.isaac.contact_sensor._contact_sensor.CsRawData for more info. CsRawData = namedtuple("RawBodyData", ["time", "dt", "body0", "body1", "position", "normal", "impulse"]) def set_carb_setting(carb_settings, setting, value): """ Convenience function to set settings. Args: setting (str): Name of setting to change. value (Any): New value for the setting. Raises: TypeError: If the type of value does not match setting type. """ if isinstance(value, str): carb_settings.set_string(setting, value) elif isinstance(value, bool): carb_settings.set_bool(setting, value) elif isinstance(value, int): carb_settings.set_int(setting, value) elif isinstance(value, float): carb_settings.set_float(setting, value) elif isinstance(value, Iterable) and not isinstance(value, dict): if len(value) == 0: raise TypeError(f"Array of type {type(value)} must be nonzero.") if isinstance(value[0], str): carb_settings.set_string_array(setting, value) elif isinstance(value[0], bool): carb_settings.set_bool_array(setting, value) elif isinstance(value[0], int): carb_settings.set_int_array(setting, value) elif isinstance(value[0], float): carb_settings.set_float_array(setting, value) else: raise TypeError(f"Value of type {type(value)} is not supported.") else: raise TypeError(f"Value of type {type(value)} is not supported.") def check_deletable_prim(prim_path): """ Checks whether the prim defined at @prim_path can be deleted. Args: prim_path (str): Path defining which prim should be checked for deletion Returns: bool: Whether the prim can be deleted or not """ if not lazy.omni.isaac.core.utils.prims.is_prim_path_valid(prim_path): return False if lazy.omni.isaac.core.utils.prims.is_prim_no_delete(prim_path): return False if lazy.omni.isaac.core.utils.prims.is_prim_ancestral(prim_path): return False if lazy.omni.isaac.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 return True def prims_to_rigid_prim_set(inp_prims): """ Converts prims @inp_prims into its corresponding set of rigid prims Args: inp_prims (list of RigidPrim or EntityPrim): Arbitrary prims Returns: set of RigidPrim: Aggregated set of RigidPrims from @inp_prims """ # Avoid circular imports from omnigibson.prims.entity_prim import EntityPrim from omnigibson.prims.rigid_prim import RigidPrim out = set() for prim in inp_prims: if isinstance(prim, EntityPrim): out.update({link for link in prim.links.values()}) elif isinstance(prim, RigidPrim): out.add(prim) else: raise ValueError(f"Inputted prims must be either EntityPrim or RigidPrim instances " f"when getting collisions! Type: {type(prim)}") return out def get_collisions(prims=None, prims_check=None, prims_exclude=None, step_physics=False): """ Grab collisions that occurred during the most recent physics timestep associated with prims @prims Args: prims (None or EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): Prim(s) to check for collision. If None, will check against all objects currently in the scene. prims_check (None or EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): If specified, will only check for collisions with these specific prim(s) prims_exclude (None or EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): If specified, will explicitly ignore any collisions with these specific prim(s) step_physics (bool): Whether to step the physics first before checking collisions. Default is False Returns: set of 2-tuple: Unique collision pairs occurring in the simulation at the current timestep between the specified prim(s), represented by their prim_paths """ # Make sure sim is playing assert og.sim.is_playing(), "Cannot get collisions while sim is not playing!" # Optionally step physics and then update contacts if step_physics: og.sim.step_physics() # Standardize inputs prims = og.sim.scene.objects if prims is None else prims if isinstance(prims, Iterable) else [prims] prims_check = [] if prims_check is None else prims_check if isinstance(prims_check, Iterable) else [prims_check] prims_exclude = [] if prims_exclude is None else prims_exclude if isinstance(prims_exclude, Iterable) else [prims_exclude] # Convert into prim paths to check for collision def get_paths_from_rigid_prims(inp_prims): return {prim.prim_path for prim in inp_prims} def get_contacts(inp_prims): return {(c.body0, c.body1) for prim in inp_prims for c in prim.contact_list()} rprims = prims_to_rigid_prim_set(prims) rprims_check = prims_to_rigid_prim_set(prims_check) rprims_exclude = prims_to_rigid_prim_set(prims_exclude) paths = get_paths_from_rigid_prims(rprims) paths_check = get_paths_from_rigid_prims(rprims_check) paths_exclude = get_paths_from_rigid_prims(rprims_exclude) # Run sanity checks assert paths_check.isdisjoint(paths_exclude), \ f"Paths to check and paths to ignore collisions for should be mutually exclusive! " \ f"paths_check: {paths_check}, paths_exclude: {paths_exclude}" # Determine whether we're checking / filtering any collision from collision set A should_check_collisions = len(paths_check) > 0 should_filter_collisions = len(paths_exclude) > 0 # Get all collisions from the objects set collisions = get_contacts(rprims) # Only run the following (expensive) code if we are actively using filtering criteria if should_check_collisions or should_filter_collisions: # First filter out unnecessary collisions if should_filter_collisions: # First filter pass, remove the intersection of the main contacts and the contacts from the exclusion set minus # the intersection between the exclusion and normal set # This filters out any matching collisions in the exclusion set that are NOT an overlap # between @rprims and @rprims_exclude rprims_exclude_intersect = rprims_exclude.intersection(rprims) exclude_disjoint_collisions = get_contacts(rprims_exclude - rprims_exclude_intersect) collisions.difference_update(exclude_disjoint_collisions) # Second filter pass, we remove collisions that may include self-collisions # This is a bit more tricky because we need to actually look at the individual contact pairs to determine # whether it's a collision (which may include a self-collision) that should be filtered # We do this by grabbing the contacts of the intersection between the exclusion and normal rprims sets, # and then making sure the resulting contact pair sets are completely disjoint from the paths intersection exclude_intersect_collisions = get_contacts(rprims_exclude_intersect) collisions.difference_update({pair for pair in exclude_intersect_collisions if paths.issuperset(set(pair))}) # Now, we additionally check for explicit collisions, filtering out any that do not meet this criteria # This is essentially the inverse of the filter collision process, where we do two passes again, but for each # case we look at the union rather than the subtraction of the two sets if should_check_collisions: # First check pass, keep the intersection of the main contacts and the contacts from the check set minus # the intersection between the check and normal set # This keeps any matching collisions in the check set that overlap between @rprims and @rprims_check rprims_check_intersect = rprims_check.intersection(rprims) check_disjoint_collisions = get_contacts(rprims_check - rprims_check_intersect) valid_other_collisions = collisions.intersection(check_disjoint_collisions) # Second check pass, we additionally keep collisions that may include self-collisions # This is a bit more tricky because we need to actually look at the individual contact pairs to determine # whether it's a collision (which may include a self-collision) that should be kept # We do this by grabbing the contacts of the intersection between the check and normal rprims sets, # and then making sure the resulting contact pair sets is strictly a subset of the original set # Lastly, we only keep the intersection of this resulting set with the original collision set, so that # any previously filtered collisions are respected check_intersect_collisions = get_contacts(rprims_check_intersect) valid_intersect_collisions = collisions.intersection({pair for pair in check_intersect_collisions if paths.issuperset(set(pair))}) # Collisions is union of valid other and valid self collisions collisions = valid_other_collisions.union(valid_intersect_collisions) # Only going into this if it is for logging --> efficiency if gm.DEBUG: for item in collisions: log.debug("linkA:{}, linkB:{}".format(item[0], item[1])) return collisions def check_collision(prims=None, prims_check=None, prims_exclude=None, step_physics=False): """ Checks if any valid collisions occurred during the most recent physics timestep associated with prims @prims Args: prims (None or EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): Prim(s) to check for collision. If None, will check against all objects currently in the scene. prims_check (None or EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): If specified, will only check for collisions with these specific prim(s) prims_exclude (None or EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): If specified, will explicitly ignore any collisions with these specific prim(s) step_physics (bool): Whether to step the physics first before checking collisions. Default is False Returns: bool: True if a valid collision has occurred, else False """ return len(get_collisions( prims=prims, prims_check=prims_check, prims_exclude=prims_exclude, step_physics=step_physics)) > 0 def filter_collisions(collisions, filter_prims): """ Filters collision pairs @collisions based on a set of prims @filter_prims. Args: collisions (set of 2-tuple): Collision pairs that should be filtered filter_prims (EntityPrim or RigidPrim or tuple of EntityPrim or RigidPrim): Prim(s) specifying which collisions to filter for. Any collisions that include prims from this filter set will be removed Returns: set of 2-tuple: Filtered collision pairs """ paths = prims_to_rigid_prim_set(filter_prims) filtered_collisions = set() for pair in collisions: if set(pair).isdisjoint(paths): filtered_collisions.add(pair) return filtered_collisions def place_base_pose(obj, pos, quat=None, z_offset=None): """ Place the object so that its base (z-min) rests at the location of @pos Args: obj (BaseObject): Object to place in the environment pos (3-array): Global (x,y,z) location to place the base of the robot quat (None or 4-array): Optional (x,y,z,w) quaternion orientation when placing the object. If None, the object's current orientation will be used z_offset (None or float): Optional additional z_offset to apply """ # avoid circular dependency from omnigibson.object_states import AABB lower, _ = obj.states[AABB].get_value() cur_pos = obj.get_position() z_diff = cur_pos[2] - lower[2] obj.set_position_orientation(pos + np.array([0, 0, z_diff if z_offset is None else z_diff + z_offset]), quat) def test_valid_pose(obj, pos, quat=None, z_offset=None): """ Test if the object can be placed with no collision. Args: obj (BaseObject): Object to place in the environment pos (3-array): Global (x,y,z) location to place the object quat (None or 4-array): Optional (x,y,z,w) quaternion orientation when placing the object. If None, the object's current orientation will be used z_offset (None or float): Optional additional z_offset to apply Returns: bool: Whether the placed object position is valid """ # Make sure sim is playing assert og.sim.is_playing(), "Cannot test valid pose while sim is not playing!" # Store state before checking object position state = og.sim.scene.dump_state(serialized=False) # Set the pose of the object place_base_pose(obj, pos, quat, z_offset) obj.keep_still() # Check whether we're in collision after taking a single physics step in_collision = check_collision(prims=obj, step_physics=True) # Restore state after checking the collision og.sim.load_state(state, serialized=False) # Valid if there are no collisions return not in_collision def land_object(obj, pos, quat=None, z_offset=None): """ Land the object at the specified position @pos, given a valid position and orientation. Args: obj (BaseObject): Object to place in the environment pos (3-array): Global (x,y,z) location to place the object quat (None or 4-array): Optional (x,y,z,w) quaternion orientation when placing the object. If None, a random orientation about the z-axis will be sampled z_offset (None or float): Optional additional z_offset to apply """ # Make sure sim is playing assert og.sim.is_playing(), "Cannot land object while sim is not playing!" # Set the object's pose quat = T.euler2quat([0, 0, np.random.uniform(0, np.pi * 2)]) if quat is None else quat place_base_pose(obj, pos, quat, z_offset) obj.keep_still() # Check to make sure we landed successfully # land for maximum 1 second, should fall down ~5 meters land_success = False max_simulator_step = int(1.0 / og.sim.get_rendering_dt()) for _ in range(max_simulator_step): # Run a sim step and see if we have any contacts og.sim.step() land_success = check_collision(prims=obj) if land_success: # Once we're successful, we can break immediately log.info(f"Landed object {obj.name} successfully!") break # Print out warning in case we failed to land the object successfully if not land_success: log.warning(f"Object {obj.name} failed to land.") obj.keep_still() def meets_minimum_isaac_version(minimum_version): return python_utils.meets_minimum_version(lazy.omni.isaac.version.get_version()[0], minimum_version)
16,079
Python
43.666667
205
0.687232
StanfordVL/OmniGibson/omnigibson/utils/motion_planning_utils.py
import numpy as np from math import ceil import heapq import omnigibson as og from omnigibson.macros import create_module_macros from omnigibson.object_states import ContactBodies import omnigibson.utils.transform_utils as T from omnigibson.utils.control_utils import IKSolver import omnigibson.lazy as lazy m = create_module_macros(module_path=__file__) m.ANGLE_DIFF = 0.3 m.DIST_DIFF = 0.1 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 + np.pi) % (2 * np.pi) - np.pi 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 = np.array([s1.getX(), s1.getY(), s1.getYaw()]) goal = np.array([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 = np.linalg.norm(goal[:2] - start[:2]) num_points = ceil(dist / m.DIST_DIFF) + 1 nav_x = np.linspace(start[0], goal[0], num_points).tolist() nav_y = np.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 = np.sign(diff) diff = abs(diff) num_points = ceil(diff / m.ANGLE_DIFF) + 1 nav_angle = np.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]) return np.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): x = q.getX() y = q.getY() yaw = q.getYaw() pose = ([x, y, 0.0], T.euler2quat((0, 0, yaw))) return not set_base_and_detect_collision(context, pose) 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 = robot.get_position() yaw = T.quat2euler(robot.get_orientation())[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", og.sim.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]) print(start) goal = create_state(space, end_conf[0], end_conf[1], end_conf[2]) print(goal) ss.setStartAndGoalStates(start, goal) if not state_valid_fn(start()) or not state_valid_fn(goal()): 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 = np.array(robot.get_joint_positions()[joint_control_idx]) control_idx_in_joint_pos = np.arange(dim) else: joint_control_idx = np.concatenate([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 = np.concatenate([robot.trunk_control_idx, robot.arm_control_idx["combined"]]) initial_joint_pos = np.array(robot.get_joint_positions()[joint_combined_idx]) control_idx_in_joint_pos = np.where(np.in1d(joint_combined_idx, joint_control_idx))[0] else: initial_joint_pos = np.array(robot.get_joint_positions()[joint_control_idx]) control_idx_in_joint_pos = np.arange(dim) def state_valid_fn(q): joint_pos = initial_joint_pos joint_pos[control_idx_in_joint_pos] = [q[i] for i in range(dim)] return not set_arm_and_detect_collision(context, joint_pos) # create an SE2 state space space = ob.RealVectorStateSpace(dim) # set lower and upper bounds bounds = ob.RealVectorBounds(dim) joints = np.array([joint for joint in robot.joints.values()]) arm_joints = joints[joint_control_idx] 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 not state_valid_fn(start) or not state_valid_fn(goal): 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 = [sol_path.getState(i)[j] for j in range(dim)] 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: Array of arrays: Array of end effector pose that the robot should navigate to """ 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 = np.array(robot.get_joint_positions()[joint_control_idx]) control_idx_in_joint_pos = np.arange(dim) robot_description_path = robot.robot_arm_descriptor_yamls["left_fixed"] else: joint_control_idx = np.concatenate([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 = np.concatenate([robot.trunk_control_idx, robot.arm_control_idx["combined"]]) initial_joint_pos = np.array(robot.get_joint_positions()[joint_combined_idx]) control_idx_in_joint_pos = np.where(np.in1d(joint_combined_idx, joint_control_idx))[0] else: initial_joint_pos = np.array(robot.get_joint_positions()[joint_control_idx]) control_idx_in_joint_pos = np.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): joint_pos = initial_joint_pos eef_pose = [q[i] for i in range(6)] 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) # 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, -np.pi) bounds.setHigh(i, np.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 = np.append(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) or not state_valid_fn(goal): 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 = [sol_path.getState(i)[j] for j in range(DOF)] return_path.append(eef_pose) return return_path return None def set_base_and_detect_collision(context, pose): """ 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 Returns: bool: Whether the robot is in collision """ robot_copy = context.robot_copy robot_copy_type = context.robot_copy_type translation = lazy.pxr.Gf.Vec3d(*np.array(pose[0], dtype=float)) robot_copy.prims[robot_copy_type].GetAttribute("xformOp:translate").Set(translation) orientation = np.array(pose[1], dtype=float)[[3, 0, 1, 2]] robot_copy.prims[robot_copy_type].GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*orientation)) return detect_robot_collision(context) def set_arm_and_detect_collision(context, joint_pos): """ 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 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(*np.array(mesh_pose[0], dtype=float)) mesh.GetAttribute("xformOp:translate").Set(translation) orientation = np.array(mesh_pose[1], dtype=float)[[3, 0, 1, 2]] mesh.GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*orientation)) return detect_robot_collision(context) def detect_robot_collision(context): """ Detects robot collisions Args: context (PlanningContext): Context to plan in that includes the robot copy Returns: 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] 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=[], ignore_obj_in_hand=True): """ Detects robot collisions with the environment, but not with itself using the ContactBodies API Args: robot (BaseRobot): Robot object to detect collisions for filter_objs (Array of StatefulObject): 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 """ filter_categories = ["floors"] obj_in_hand = robot._ag_obj_in_hand[robot.default_arm] if obj_in_hand is not None and ignore_obj_in_hand: filter_objs.append(obj_in_hand) collision_prims = list(robot.states[ContactBodies].get_value(ignore_objs=tuple(filter_objs))) for col_prim in collision_prims: tokens = col_prim.prim_path.split("/") obj_prim_path = "/".join(tokens[:-1]) col_obj = og.sim.scene.object_registry("prim_path", obj_prim_path) if col_obj.category in filter_categories: collision_prims.remove(col_prim) return len(collision_prims) > 0 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 np.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 np.sqrt(2) open_set = [(0, start)] came_from = {} visited = set() g_score = {cell: float('inf') for cell in np.ndindex(search_map.shape)} 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 np.array(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
22,689
Python
35.420546
152
0.61294
StanfordVL/OmniGibson/omnigibson/utils/registry_utils.py
""" A set of utility functions for registering and tracking objects """ from inspect import isclass import numpy as np from collections.abc import Iterable from omnigibson.macros import create_module_macros from omnigibson.utils.python_utils import Serializable, SerializableNonInstance, UniquelyNamed 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__) # Token identifier for default values if a key doesn't exist in a given object m.DOES_NOT_EXIST = "DOES_NOT_EXIST" class Registry(UniquelyNamed): """ 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=m.DOES_NOT_EXIST, ): """ 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): 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 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 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.<key> 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 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)]), \ f"Added object must be either an instance or subclass of Serializable or SerializableNonInstance!" # Run super like normal super().add(obj=obj) @property def state_size(self): return sum(obj.state_size for obj in self.objects) def _dump_state(self): # Iterate over all objects and grab their states state = dict() for obj in self.objects: 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 obj.name not in state: log.warning(f"Object '{obj.name}' is not in the state dict to load from. Skip loading its state.") continue obj.load_state(state[obj.name], serialized=False) def _serialize(self, state): # Iterate over the entire dict and flatten return np.concatenate([obj.serialize(state[obj.name]) for obj in self.objects]) if \ len(self.objects) > 0 else np.array([]) def _deserialize(self, state): state_dict = dict() # Iterate over all the objects and deserialize their individual states, incrementing the index counter # along the way idx = 0 for obj in self.objects: log.debug(f"obj: {obj.name}, state size: {obj.state_size}, 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] = obj.deserialize(state[idx:]) idx += obj.state_size return state_dict, idx
15,260
Python
41.391667
140
0.613434
StanfordVL/OmniGibson/omnigibson/utils/git_utils.py
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), }
646
Python
21.310344
60
0.605263
StanfordVL/OmniGibson/omnigibson/utils/geometry_utils.py
""" A set of helper utility functions for dealing with 3D geometry """ import numpy as np import omnigibson.utils.transform_utils as T from omnigibson.utils.usd_utils import mesh_prim_mesh_to_trimesh_mesh 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 = np.tile(np.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 = np.tile(np.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, pos, quat, scale, 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 pos (3-array): (x,y,z) local location of the cube quat (4-array): (x,y,z,w) local orientation of the cube scale (3-array): (x,y,z) local scale 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. """ particle_positions = get_particle_positions_in_frame( pos=pos, quat=quat, scale=scale, particle_positions=particle_positions, ) return ((-size / 2.0 < particle_positions) & (particle_positions < size / 2.0)).sum(axis=-1) == 3 def check_points_in_cone(size, pos, quat, scale, 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 pos (3-array): (x,y,z) local location of the cone quat (4-array): (x,y,z,w) local orientation of the cone scale (3-array): (x,y,z) local scale 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. """ particle_positions = get_particle_positions_in_frame( pos=pos, quat=quat, scale=scale, particle_positions=particle_positions, ) radius, height = size in_height = (-height / 2.0 < particle_positions[:, -1]) & (particle_positions[:, -1] < height / 2.0) in_radius = np.linalg.norm(particle_positions[:, :-1], axis=-1) < \ (radius * (1 - (particle_positions[:, -1] + height / 2.0) / height )) return in_height & in_radius def check_points_in_cylinder(size, pos, quat, scale, 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 pos (3-array): (x,y,z) local location of the cylinder quat (4-array): (x,y,z,w) local orientation of the cylinder scale (3-array): (x,y,z) local scale of the cube, 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. """ particle_positions = get_particle_positions_in_frame( pos=pos, quat=quat, scale=scale, particle_positions=particle_positions, ) radius, height = size in_height = (-height / 2.0 < particle_positions[:, -1]) & (particle_positions[:, -1] < height / 2.0) in_radius = np.linalg.norm(particle_positions[:, :-1], axis=-1) < radius return in_height & in_radius def check_points_in_sphere(size, pos, quat, scale, 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 pos (3-array): (x,y,z) local location of the sphere quat (4-array): (x,y,z,w) local orientation of the sphere scale (3-array): (x,y,z) local scale of the sphere, specified in its local frame 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 """ particle_positions = get_particle_positions_in_frame( pos=pos, quat=quat, scale=scale, particle_positions=particle_positions, ) return np.linalg.norm(particle_positions, axis=-1) < size def check_points_in_convex_hull_mesh(mesh_face_centroids, mesh_face_normals, pos, quat, scale, 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 pos (3-array): (x,y,z) local location of the mesh quat (4-array): (x,y,z,w) local orientation of the mesh scale (3-array): (x,y,z) local scale of the cube, specified 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 """ particle_positions = get_particle_positions_in_frame( pos=pos, quat=quat, scale=scale, particle_positions=particle_positions, ) # 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 = np.tile(mesh_face_centroids.reshape(1, D, 3), (N, 1, 1)) mesh_normals = np.tile(mesh_face_normals.reshape(1, D, 3), (N, 1, 1)) particle_positions = np.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(axis=-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(axis=-1) == D return in_range def _generate_convex_hull_volume_checker_functions(convex_hull_mesh): """ An internal helper function used to programmatically generate lambda funtions to check for particle points within a convex hull mesh defined by face centroids @mesh_face_centroids and @mesh_face_normals. Note that this is needed as an EXTERNAL helper function to @generate_points_in_volume_checker_function because we "bake" certain arguments as part of the lambda internal scope, and directly generating functions in a for loop results in these local variables being overwritten each time (meaning that all the generated lambda functions reference the SAME variables!!) Args: convex_hull_mesh (Usd.Prim): Raw USD convex hull mesh to generate the volume checker functions Returns: 2-tuple: - function: Generated lambda function with signature: in_range = check_in_volume(mesh, particle_positions) where @in_range is a N-array boolean numpy array, (True where the particle is in the convex hull mesh volume), @mesh is the raw USD mesh, and @particle_positions is a (N, 3) array specifying the particle positions in the SAME coordinate frame as @mesh - function: Function for grabbing real-time LOCAL scale volume of the container. Signature: vol = calc_volume(mesh) where @vol is the total volume being checked (expressed in the mesh's LOCAL scale), and @mesh is the raw USD mesh """ # For efficiency, we pre-compute the mesh using trimesh and find its corresponding faces and normals trimesh_mesh = mesh_prim_mesh_to_trimesh_mesh(convex_hull_mesh, include_normals=False, include_texcoord=False).convex_hull assert trimesh_mesh.is_convex, \ f"Trying to generate a volume checker function for a non-convex mesh {convex_hull_mesh.GetPath().pathString}" face_centroids = trimesh_mesh.vertices[trimesh_mesh.faces].mean(axis=1) face_normals = trimesh_mesh.face_normals # This function assumes that: # 1. @particle_positions are in the local container_link frame # 2. the @check_points_in_[...] function will convert them into the local @mesh frame in_volume = lambda mesh, particle_positions: check_points_in_convex_hull_mesh( mesh_face_centroids=face_centroids, mesh_face_normals=face_normals, pos=np.array(mesh.GetAttribute("xformOp:translate").Get()), quat=np.array( [*(mesh.GetAttribute("xformOp:orient").Get().imaginary), mesh.GetAttribute("xformOp:orient").Get().real]), scale=np.array(mesh.GetAttribute("xformOp:scale").Get()), particle_positions=particle_positions, ) calc_volume = lambda mesh: trimesh_mesh.volume if trimesh_mesh.is_volume else trimesh_mesh.convex_hull.volume return in_volume, calc_volume def generate_points_in_volume_checker_function(obj, volume_link, use_visual_meshes=True, mesh_name_prefixes=None): """ Generates a function for quickly checking which of a group of points are contained within any container volumes. Four volume types are supported: "Cylinder" - Cylinder volume "Cube" - Cube volume "Sphere" - Sphere volume "Mesh" - Convex hull volume @volume_link should have any number of nested, visual-only meshes of types {Sphere, Cylinder, Cube, Mesh} with naming prefix "container[...]" Args: obj (EntityPrim): Object which contains @volume_link as one of its links volume_link (RigidPrim): Link to use to grab container volumes composing the values for checking the points use_visual_meshes (bool): Whether to use @volume_link's visual or collision meshes to generate points fcn mesh_name_prefixes (None or str): If specified, specifies the substring that must exist in @volume_link's mesh names in order for that mesh to be included in the volume checker function. If None, no filtering will be used. Returns: 2-tuple: - function: Function with signature: in_range = check_in_volumes(particle_positions) where @in_range is a N-array boolean numpy array, (True where the particle is in the volume), and @particle_positions is a (N, 3) array specifying the particle positions in global coordinates - function: Function for grabbing real-time global scale volume of the container. Signature: vol = total_volume() where @vol is the total volume being checked (expressed in global scale) aggregated across all container sub-volumes """ # Iterate through all visual meshes and keep track of any that are prefixed with container container_meshes = [] meshes = volume_link.visual_meshes if use_visual_meshes else volume_link.collision_meshes for container_mesh_name, container_mesh in meshes.items(): if mesh_name_prefixes is None or mesh_name_prefixes in container_mesh_name: container_meshes.append(container_mesh) # Programmatically define the volume checker functions based on each container found volume_checker_fcns = [] for sub_container_mesh in container_meshes: mesh_type = sub_container_mesh.prim.GetTypeName() if mesh_type == "Mesh": fcn, vol_fcn = _generate_convex_hull_volume_checker_functions(convex_hull_mesh=sub_container_mesh.prim) elif mesh_type == "Sphere": fcn = lambda mesh, particle_positions: check_points_in_sphere( size=mesh.GetAttribute("radius").Get(), pos=np.array(mesh.GetAttribute("xformOp:translate").Get()), quat=np.array([*(mesh.GetAttribute("xformOp:orient").Get().imaginary), mesh.GetAttribute("xformOp:orient").Get().real]), scale=np.array(mesh.GetAttribute("xformOp:scale").Get()), particle_positions=particle_positions, ) elif mesh_type == "Cylinder": fcn = lambda mesh, particle_positions: check_points_in_cylinder( size=[mesh.GetAttribute("radius").Get(), mesh.GetAttribute("height").Get()], pos=np.array(mesh.GetAttribute("xformOp:translate").Get()), quat=np.array([*(mesh.GetAttribute("xformOp:orient").Get().imaginary), mesh.GetAttribute("xformOp:orient").Get().real]), scale=np.array(mesh.GetAttribute("xformOp:scale").Get()), particle_positions=particle_positions, ) elif mesh_type == "Cone": fcn = lambda mesh, particle_positions: check_points_in_cone( size=[mesh.GetAttribute("radius").Get(), mesh.GetAttribute("height").Get()], pos=np.array(mesh.GetAttribute("xformOp:translate").Get()), quat=np.array([*(mesh.GetAttribute("xformOp:orient").Get().imaginary), mesh.GetAttribute("xformOp:orient").Get().real]), scale=np.array(mesh.GetAttribute("xformOp:scale").Get()), particle_positions=particle_positions, ) elif mesh_type == "Cube": fcn = lambda mesh, particle_positions: check_points_in_cube( size=mesh.GetAttribute("size").Get(), pos=np.array(mesh.GetAttribute("xformOp:translate").Get()), quat=np.array([*(mesh.GetAttribute("xformOp:orient").Get().imaginary), mesh.GetAttribute("xformOp:orient").Get().real]), scale=np.array(mesh.GetAttribute("xformOp:scale").Get()), particle_positions=particle_positions, ) else: raise ValueError(f"Cannot create volume checker function for mesh of type: {mesh_type}") volume_checker_fcns.append(fcn) # Define the actual volume checker function def check_points_in_volumes(particle_positions): # Algo # 1. Particles in global frame --> particles in volume link frame (including scaling) # 2. For each volume checker function, apply volume checking # 3. Aggregate across all functions with OR condition (any volume satisfied for that point) ###### n_particles = len(particle_positions) # Get pose of origin (global frame) in frame of volume link # NOTE: This assumes there is no relative scaling between obj and volume link volume_link_pos, volume_link_quat = volume_link.get_position_orientation() particle_positions = get_particle_positions_in_frame( pos=volume_link_pos, quat=volume_link_quat, scale=obj.scale, particle_positions=particle_positions, ) in_volumes = np.zeros(n_particles).astype(bool) for checker_fcn, mesh in zip(volume_checker_fcns, container_meshes): in_volumes |= checker_fcn(mesh.prim, particle_positions) return in_volumes # Define the actual volume calculator function def calculate_volume(precision=1e-5): # We use monte-carlo sampling to approximate the voluem up to @precision # NOTE: precision defines the RELATIVE precision of the volume computation -- i.e.: the relative error with # respect to the volume link's global AABB # Convert precision to minimum number of particles to sample min_n_particles = int(np.ceil(1. / precision)) # Make sure container meshes are visible so AABB computation is correct for mesh in container_meshes: mesh.visible = True # Determine equally-spaced sampling distance to achieve this minimum particle count aabb_volume = np.product(volume_link.visual_aabb_extent) sampling_distance = np.cbrt(aabb_volume / min_n_particles) low, high = volume_link.visual_aabb n_particles_per_axis = ((high - low) / sampling_distance).astype(int) + 1 assert np.all(n_particles_per_axis), "Must increase precision for calculate_volume -- too coarse for sampling!" # 1e-10 is added because the extent might be an exact multiple of particle radius arrs = [np.arange(l, h, sampling_distance) for l, h, n in zip(low, high, n_particles_per_axis)] # Generate 3D-rectangular grid of points, and only keep the ones inside the mesh points = np.stack([arr.flatten() for arr in np.meshgrid(*arrs)]).T # Re-hide container meshes for mesh in container_meshes: mesh.visible = False # Return the fraction of the link AABB's volume based on fraction of points enclosed within it return aabb_volume * np.mean(check_points_in_volumes(points)) return check_points_in_volumes, calculate_volume
19,995
Python
48.130221
136
0.663766
StanfordVL/OmniGibson/omnigibson/utils/gym_utils.py
import gym from abc import ABCMeta, abstractmethod import numpy as np 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 compatibel with Gym spaces -- in particular, the Sequence and Tuple types for np.ndarray / np.void 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, np.ndarray) and len(v.dtype) > 0: # Map to list of tuples out[k] = list(map(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=np.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
4,700
Python
34.345864
120
0.640851
StanfordVL/OmniGibson/omnigibson/utils/object_utils.py
""" Helper utility functions for computing relevant object information """ import omnigibson as og import numpy as np import omnigibson.utils.transform_utils as T from scipy.spatial.transform import Rotation as R 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 (BaseObject): 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 np.all(obj.scale == 1.0) aabb_extent = obj.aabb_extent radius = np.linalg.norm(aabb_extent) / 2.0 drop_pos = np.array([0, 0, radius + drop_aabb_offset]) center_offset = obj.get_position() - obj.aabb_center drop_orientations = R.random(n_samples).as_quat() stable_orientations = np.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(pos, drop_orientation) obj.keep_still() for j in range(25): og.sim.step() stable_orientations[i] = obj.get_orientation() 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 (BaseObject): 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 np.all(obj.scale == 1.0) obj.set_position_orientation(np.zeros(3), np.array([0, 0, 0, 1.0])) return obj.aabb_center - obj.get_position() 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 (BaseObject): Object whose native bbox extent will be computed Returns: n-array: (x,y,z) native bounding box extent """ og.sim.stop() assert np.all(obj.scale == 1.0) obj.set_position_orientation(np.zeros(3), np.array([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_local_pose() pts_in_link_frame.append(get_particle_positions_from_frame(local_pos, local_orn, mesh.scale, pts)) pts_in_link_frame = np.concatenate(pts_in_link_frame, axis=0) max_pt = np.max(pts_in_link_frame, axis=0) min_pt = np.min(pts_in_link_frame, axis=0) extent = max_pt - min_pt center = (max_pt + min_pt) / 2.0 transform = T.pose2mat((center, np.array([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 (BaseObject): 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 og.sim.scene is not None assert og.sim.scene.floor_plane is not None, "An empty scene must be used in order to compute kinematic metadata!" assert np.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), }
5,156
Python
38.976744
118
0.651668
StanfordVL/OmniGibson/omnigibson/utils/processing_utils.py
import numpy as np from omnigibson.utils.python_utils import Serializable class Filter(Serializable): """ A base class for filtering a noisy data stream in an online fashion. """ def estimate(self, observation): """ Takes an observation and returns a de-noised estimate. Args: observation (n-array): A current observation. Returns: n-array: De-noised estimate. """ raise NotImplementedError def reset(self): """ Resets this filter. Default is no-op. """ pass @property def state_size(self): # No state by default return 0 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 np.array([]) def _deserialize(self, state): # Default is no state, so do nothing return dict(), 0 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. """ def __init__(self, obs_dim, filter_width): """ 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. """ 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.past_samples = np.zeros((filter_width, obs_dim)) self.current_idx = 0 self.fully_filled = False # Whether the entire filter buffer is filled or not super().__init__() def estimate(self, observation): """ Do an online hold for state estimation given a recent observation. Args: observation (n-array): New observation to hold internal estimate of state. Returns: n-array: New estimate of state. """ # Write the newest observation at the appropriate index self.past_samples[self.current_idx, :] = np.array(observation) # Compute value based on whether we're fully filled or not if not self.fully_filled: val = self.past_samples[:self.current_idx + 1, :].mean(axis=0) # Denote that we're fully filled if we're at the end of the buffer if self.current_idx == self.filter_width - 1: self.fully_filled = True else: val = self.past_samples.mean(axis=0) # Increment the index to write the next sample to self.current_idx = (self.current_idx + 1) % self.filter_width return val def reset(self): # Clear internal state self.past_samples *= 0.0 self.current_idx = 0 self.fully_filled = False @property def state_size(self): return super().state_size + self.filter_width * self.obs_dim + 2 def _dump_state(self): # Run super init first state = super()._dump_state() # Add info from this filter state["past_samples"] = np.array(self.past_samples) state["current_idx"] = self.current_idx state["fully_filled"] = self.fully_filled return state def _load_state(self, state): # Run super first super()._load_state(state=state) # Load relevant info for this filter self.past_samples = np.array(state["past_samples"]) self.current_idx = state["current_idx"] self.fully_filled = state["fully_filled"] def _serialize(self, state): # Run super first state_flat = super()._serialize(state=state) # Serialize state for this filter return np.concatenate([ state_flat, state["past_samples"].flatten(), [state["current_idx"]], [state["fully_filled"]], ]).astype(float) def _deserialize(self, state): # Run super first state_dict, idx = super()._deserialize(state=state) # Deserialize state for this filter samples_len = self.filter_width * self.obs_dim state_dict["past_samples"] = state[idx: idx + samples_len] state_dict["current_idx"] = int(state[idx + samples_len]) state_dict["fully_filled"] = bool(state[idx + samples_len + 1]) return state_dict, idx + 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 = np.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 (n-array): New observation to hold internal estimate of state. Returns: n-array: New estimate of state. """ self.avg = self.alpha * observation + (1.0 - self.alpha) * self.avg self.num_samples += 1 return np.array(self.avg) def reset(self): # Clear internal state self.avg *= 0.0 self.num_samples = 0 @property def state_size(self): return super().state_size + self.obs_dim + 1 def _dump_state(self): # Run super init first state = super()._dump_state() # Add info from this filter state["avg"] = np.array(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 = np.array(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 np.concatenate([ state_flat, state["avg"], [state["num_samples"]], ]).astype(float) 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 if __name__ == "__main__": f = MovingAverageFilter(3, 10) a = np.array([1, 1, 1]) for i in range(500): print(f.estimate(a + np.random.normal(scale=0.1)))
8,427
Python
27.962199
102
0.576718
StanfordVL/OmniGibson/omnigibson/utils/grasping_planning_utils.py
import numpy as np from scipy.spatial.transform import Rotation as R, Slerp from math import ceil from omnigibson.macros import create_module_macros import omnigibson.utils.transform_utils as T from omnigibson.object_states.open_state import _get_relevant_joints from omnigibson.utils.constants import JointType, JointAxis import omnigibson.lazy as lazy 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. Args: target_object (StatefulObject): Object to get a grasp pose for Returns: 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 ) grasp_center_pos = bbox_center_in_world + np.array([0, 0, np.max(bbox_extent_in_base_frame) + 0.05]) towards_object_in_world_frame = bbox_center_in_world - grasp_center_pos towards_object_in_world_frame /= np.linalg.norm(towards_object_in_world_frame) grasp_quat = T.euler2quat([0, np.pi/2, 0]) grasp_pose = (grasp_center_pos, grasp_quat) grasp_candidate = [(grasp_pose, towards_object_in_world_frame)] return grasp_candidate 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_object (StatefulObject): Object to get a grasp pose for Returns: 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 = np.random.choice([0, 1, 2]) approach_direction = np.random.choice([-1, 1]) if approach_axis != 2 else 1 constant_dimension_in_base_frame = approach_direction * bbox_extent_in_base_frame * np.eye(3)[approach_axis] randomizable_dimensions_in_base_frame = bbox_extent_in_base_frame - np.abs(constant_dimension_in_base_frame) random_dimensions_in_base_frame = np.random.uniform([-1, -1, 0], [1, 1, 1]) # 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] + np.array([0, 0, 0.02]) towards_object_in_world_frame = bbox_center_in_world - grasp_center_pos towards_object_in_world_frame /= np.linalg.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 = np.random.rand(3) rand_vec /= np.linalg.norm(rand_vec) grasp_x = towards_object_in_world_frame grasp_y = np.cross(rand_vec, grasp_x) grasp_y /= np.linalg.norm(grasp_y) grasp_z = np.cross(grasp_x, grasp_y) grasp_z /= np.linalg.norm(grasp_z) grasp_mat = np.array([grasp_x, grasp_y, grasp_z]).T grasp_quat = R.from_matrix(grasp_mat).as_quat() 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: the robot object target_obj: the object to open/close a joint of should_open: a boolean indicating whether we are opening or closing relevant_joint: the joint to open/close if we want to do a particular one in advance num_waypoints: 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. np.random.shuffle(relevant_joints) 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: the robot object target_obj: the object to open relevant_joint: the prismatic joint to open should_open: a boolean indicating whether we are opening or closing num_waypoints: 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.omni.isaac.core.utils.rotations.gf_quat_to_np_array(relevant_joint.get_attribute("physics:localRot0"))[[1, 2, 3, 0]] push_axis = R.from_quat(joint_orientation).apply([1, 0, 0]) assert np.isclose(np.max(np.abs(push_axis)), 1.0) # Make sure we're aligned with a bb axis. push_axis_idx = np.argmax(np.abs(push_axis)) canonical_push_axis = np.eye(3)[push_axis_idx] # TODO: Need to figure out how to get the correct push direction. push_direction = np.sign(push_axis[push_axis_idx]) if should_open else -1 * np.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 = ( np.array([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() ) 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 = np.eye(3)[x_axis_idx] canonical_y_axis = np.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 sampled_lateral_pos_wrt_min = np.random.uniform( 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, ) 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. dist_from_grasp_pos = robot.finger_lengths[robot.default_arm] + 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 = R.from_quat(bbox_quat_in_world).apply(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 = np.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 waypoint_start_pose = (grasp_pose_in_world_frame[0] + -1 * approach_direction_in_world_frame * (robot.finger_lengths[robot.default_arm] + 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 * (robot.finger_lengths[robot.default_arm]), 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 = np.linalg.norm(end_pose[0] - start_pos) if num_waypoints == "default": num_waypoints = np.max([2, int(travel_distance / 0.01) + 1]) pos_waypoints = np.linspace(start_pos, end_pose[0], num_waypoints) # Also interpolate the rotations combined_rotation = R.from_quat(np.array([start_orn, end_pose[1]])) slerp = Slerp([0, 1], combined_rotation) orn_waypoints = slerp(np.linspace(0, 1, num_waypoints)) 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: the robot object target_obj: the object to open relevant_joint: the revolute joint to open should_open: 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_orientation() bbox_extent_in_link_frame = np.array(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.omni.isaac.core.utils.rotations.gf_quat_to_np_array(relevant_joint.get_attribute("physics:localRot0"))[[1, 2, 3, 0]] joint_axis = R.from_quat(joint_orientation).apply([1, 0, 0]) joint_axis /= np.linalg.norm(joint_axis) origin_towards_bbox = np.array(bbox_wrt_origin[0]) open_direction = np.cross(joint_axis, origin_towards_bbox) open_direction /= np.linalg.norm(open_direction) lateral_axis = np.cross(open_direction, joint_axis) # Match the axes to the canonical axes of the link bb. lateral_axis_idx = np.argmax(np.abs(lateral_axis)) open_axis_idx = np.argmax(np.abs(open_direction)) joint_axis_idx = np.argmax(np.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 = np.eye(3)[open_axis_idx] points_along_open_axis = ( np.array([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() ) 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 = np.eye(3)[joint_axis_idx] lateral_away_from_origin = np.eye(3)[lateral_axis_idx] * np.sign(origin_towards_bbox[lateral_axis_idx]) min_lateral_pos_wrt_surface_center = ( lateral_away_from_origin * -np.array(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 sampled_lateral_pos_wrt_min = np.random.uniform( 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, ) 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. dist_from_grasp_pos = robot.finger_lengths[robot.default_arm] + 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) * np.linalg.norm(grasp_pose_in_origin_frame[0]) turn_steps = int(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 = R.from_quat(bbox_quat_in_world).apply(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 = np.array(targets[-1][0]) - np.array(offset_grasp_pose_in_world_frame[0]) grasp_required = np.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 (np.ndarray): The vector to face. Returns: np.ndarray: A quaternion representing the orientation. """ forward = vector / np.linalg.norm(vector) rand_vec = np.random.rand(3) rand_vec /= np.linalg.norm(3) side = np.cross(rand_vec, forward) side /= np.linalg.norm(3) up = np.cross(forward, side) # assert np.isclose(np.linalg.norm(up), 1, atol=1e-3) rotmat = np.array([forward, side, up]).T return R.from_matrix(rotmat).as_quat() 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 (np.ndarray): The axis to rotate around. yaw_change (float): The amount to rotate by. Returns: tuple: The rotated point in the arbitrary frame. """ rotation = R.from_rotvec(joint_axis * yaw_change).as_quat() 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 = np.array( [ 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 = np.linalg.norm(vectors_in_world - np.array(point_in_world)[None, :], axis=1) closer_option_idx = np.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
24,988
Python
49.687627
195
0.699416
StanfordVL/OmniGibson/omnigibson/utils/bddl_utils.py
import json import bddl import os import random import numpy as np import networkx as nx from collections import defaultdict from bddl.activity import ( get_goal_conditions, get_ground_goal_state_options, get_initial_conditions, ) from bddl.backend_abc import BDDLBackend from bddl.condition_evaluation import Negation from bddl.logic_base import BinaryAtomicFormula, UnaryAtomicFormula, AtomicFormula from bddl.object_taxonomy import ObjectTaxonomy import omnigibson as og from omnigibson.macros import gm, create_module_macros from omnigibson.utils.constants import PrimType from omnigibson.utils.asset_utils import get_attachment_metalinks, get_all_object_categories, get_all_object_category_models_with_abilities from omnigibson.utils.ui_utils import create_module_logger from omnigibson.utils.python_utils import Wrapper from omnigibson.objects.dataset_object import DatasetObject from omnigibson.robots import BaseRobot from omnigibson import object_states from omnigibson.object_states.object_state_base import AbsoluteObjectState, RelativeObjectState from omnigibson.object_states.factory import _KINEMATIC_STATE_SET, get_system_states from omnigibson.systems.system_base import is_system_active, get_system from omnigibson.scenes.interactive_traversable_scene import InteractiveTraversableScene # 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], }, } BAD_CLOTH_MODELS = { "bandana": {"wbhliu"}, "curtain": {"ohvomi"}, "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"}, "curtain": {"shbakk"} } class UnsampleablePredicate: def _sample(self, *args, **kwargs): raise NotImplementedError() class ObjectStateInsourcePredicate(UnsampleablePredicate, BinaryAtomicFormula): def _evaluate(self, entity, **kwargs): # Always returns True return True class ObjectStateFuturePredicate(UnsampleablePredicate, UnaryAtomicFormula): STATE_NAME = "future" def _evaluate(self, entity, **kwargs): return not entity.exists class ObjectStateRealPredicate(UnsampleablePredicate, UnaryAtomicFormula): STATE_NAME = "real" def _evaluate(self, entity, **kwargs): return entity.exists class ObjectStateUnaryPredicate(UnaryAtomicFormula): STATE_CLASS = None STATE_NAME = None def _evaluate(self, entity, **kwargs): return entity.get_state(self.STATE_CLASS, **kwargs) def _sample(self, entity, binary_state, **kwargs): return entity.set_state(self.STATE_CLASS, binary_state, **kwargs) class ObjectStateBinaryPredicate(BinaryAtomicFormula): STATE_CLASS = None STATE_NAME = None def _evaluate(self, entity1, entity2, **kwargs): return entity1.get_state(self.STATE_CLASS, entity2.wrapped_obj, **kwargs) if entity2.exists else False def _sample(self, entity1, entity2, binary_state, **kwargs): return entity1.set_state(self.STATE_CLASS, entity2.wrapped_obj, binary_state, **kwargs) if entity2.exists else None def get_unary_predicate_for_state(state_class, state_name): return type( state_class.__name__ + "StateUnaryPredicate", (ObjectStateUnaryPredicate,), {"STATE_CLASS": state_class, "STATE_NAME": state_name}, ) def get_binary_predicate_for_state(state_class, state_name): return type( state_class.__name__ + "StateBinaryPredicate", (ObjectStateBinaryPredicate,), {"STATE_CLASS": state_class, "STATE_NAME": state_name}, ) def is_substance_synset(synset): return "substance" in OBJECT_TAXONOMY.get_abilities(synset) def get_system_name_by_synset(synset): system_names = OBJECT_TAXONOMY.get_subtree_substances(synset) assert len(system_names) == 1, f"Got zero or multiple systems for {synset}: {system_names}" return system_names[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], AtomicFormula): log.debug(("Skipping over sampling of predicate that is not a negation or an atomic formula")) 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 # TODO: Add remaining predicates. SUPPORTED_PREDICATES = { "inside": get_binary_predicate_for_state(object_states.Inside, "inside"), "nextto": get_binary_predicate_for_state(object_states.NextTo, "nextto"), "ontop": get_binary_predicate_for_state(object_states.OnTop, "ontop"), "under": get_binary_predicate_for_state(object_states.Under, "under"), "touching": get_binary_predicate_for_state(object_states.Touching, "touching"), "covered": get_binary_predicate_for_state(object_states.Covered, "covered"), "contains": get_binary_predicate_for_state(object_states.Contains, "contains"), "saturated": get_binary_predicate_for_state(object_states.Saturated, "saturated"), "filled": get_binary_predicate_for_state(object_states.Filled, "filled"), "cooked": get_unary_predicate_for_state(object_states.Cooked, "cooked"), "burnt": get_unary_predicate_for_state(object_states.Burnt, "burnt"), "frozen": get_unary_predicate_for_state(object_states.Frozen, "frozen"), "hot": get_unary_predicate_for_state(object_states.Heated, "hot"), "open": get_unary_predicate_for_state(object_states.Open, "open"), "toggled_on": get_unary_predicate_for_state(object_states.ToggledOn, "toggled_on"), "on_fire": get_unary_predicate_for_state(object_states.OnFire, "on_fire"), "attached": get_binary_predicate_for_state(object_states.AttachedTo, "attached"), "overlaid": get_binary_predicate_for_state(object_states.Overlaid, "overlaid"), "folded": get_unary_predicate_for_state(object_states.Folded, "folded"), "unfolded": get_unary_predicate_for_state(object_states.Unfolded, "unfolded"), "draped": get_binary_predicate_for_state(object_states.Draped, "draped"), "future": ObjectStateFuturePredicate, "real": ObjectStateRealPredicate, "insource": ObjectStateInsourcePredicate, } KINEMATIC_STATES_BDDL = frozenset([state.__name__.lower() for state in _KINEMATIC_STATE_SET] + ["attached"]) # BEHAVIOR-related OBJECT_TAXONOMY = ObjectTaxonomy() BEHAVIOR_ACTIVITIES = sorted(os.listdir(os.path.join(os.path.dirname(bddl.__file__), "activity_definitions"))) 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 OBJECT_TAXONOMY.is_leaf(synset), 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 = OBJECT_TAXONOMY.get_categories(synset) 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 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, states 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 OBJECT_TAXONOMY.is_leaf(first_synset), 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 = OBJECT_TAXONOMY.get_categories(first_synset) 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: # Unary states for the first synset for state_type, state_value in states: state_class = SUPPORTED_PREDICATES[state_type].STATE_CLASS assert issubclass(state_class, AbsoluteObjectState), f"Input/output state type {state_type} must be a unary state!" # Example: (Cooked, True) og_recipe[states_key][first_obj_category]["unary"].append((state_class, state_value)) else: assert OBJECT_TAXONOMY.is_leaf(second_synset), f"Input/output state synset {second_synset} must be a leaf node in the taxonomy!" obj_categories = OBJECT_TAXONOMY.get_categories(second_synset) if is_substance_synset(second_synset): second_obj_category = get_system_name_by_synset(second_synset) is_substance = True else: obj_categories = OBJECT_TAXONOMY.get_categories(second_synset) 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 state_type, state_value in states: state_class = SUPPORTED_PREDICATES[state_type].STATE_CLASS assert issubclass(state_class, RelativeObjectState), f"Input/output state type {state_type} must be a binary state!" assert is_substance == (state_class in get_system_states()), f"Input/output state type {state_type} system state inconsistency found!" if is_substance: # Non-kinematic binary states, e.g. Covered, Saturated, Filled, Contains. # Example: (Covered, "sesame_seed", True) og_recipe[states_key][first_obj_category]["binary_system"].append( (state_class, second_obj_category, state_value)) else: # Kinematic binary states w.r.t. the second object. # Example: (OnTop, "raw_egg", True) assert states_key != "output_states", f"Output state type {state_type} can only be used in input states!" og_recipe[states_key][first_obj_category]["binary_object"].append( (state_class, second_obj_category, state_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 OBJECT_TAXONOMY.is_leaf(synset), 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 OBJECT_TAXONOMY.get_categories(synset): og_recipe[f"{filter_name}_categories"].add(category) def translate_bddl_recipe_to_og_recipe( name, input_synsets, output_synsets, input_states=None, output_states=None, fillable_synsets=None, heatsource_synsets=None, timesteps=None, ): """ Translate a BDDL recipe to an OG recipe. Args: name (str): Name of the recipe input_synsets (dict): Maps synsets to number of instances required for the recipe output_synsets (dict): Maps synsets to number of instances to be spawned in the container when the recipe executes input_states (dict or None): Maps input synsets to states that must be satisfied for the recipe to execute, or None if no states are required otuput_states (dict or None): Map output synsets to states that should be set when spawned when the recipe executes, or None if no states are required fillable_synsets (None or set of str): If specified, set of fillable synsets which are allowed for this recipe. If None, any fillable is allowed heatsource_synsets (None or set of str): If specified, set of heatsource synsets 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 """ og_recipe = { "name": name, # Maps object categories to number of instances required for the recipe "input_objects": dict(), # List of system names required for the recipe "input_systems": list(), # Maps object categories to number of instances to be spawned in the container when the recipe executes "output_objects": dict(), # List of system names to be spawned in the container when the recipe executes. Currently the length is 1. "output_systems": list(), # Maps object categories to ["unary", "bianry_system", "binary_object"] to a list of states that must be satisfied for the recipe to execute "input_states": 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 "output_states": defaultdict(lambda: defaultdict(list)), # Set of fillable categories which are allowed for this recipe "fillable_categories": None, # Set of heatsource categories which are allowed for this recipe "heatsource_categories": None, # Number of subsequent heating steps required for the recipe to execute "timesteps": timesteps if timesteps is not None else 1, } _populate_input_output_objects_systems(og_recipe=og_recipe, input_synsets=input_synsets, output_synsets=output_synsets) _populate_input_output_states(og_recipe=og_recipe, input_states=input_states, output_states=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(conditions): """ Translate BDDL washer rule to OG washer rule. Args: conditions (dict): Dictionary mapping the synset of ParticleSystem (str) to None or list of synsets of ParticleSystem (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.n.01" -> None: "never remove rust.n.01 from the washer" E.g. "dust.n.01" -> []: "always remove dust.n.01 from the washer" E.g. "cooking_oil.n.01" -> ["sodium_carbonate.n.01", "vinegar.n.01"]: "remove cooking_oil.n.01 from the washer if either sodium_carbonate.n.01 or vinegar.n.01 is present" For keys not present in the dictionary, the default is []: "always remove" Returns: dict: Dictionary 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. """ og_washer_rule = dict() for solute, solvents in conditions.items(): assert OBJECT_TAXONOMY.is_leaf(solute), 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 OBJECT_TAXONOMY.is_leaf(solvent), 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 OmniGibsonBDDLBackend(BDDLBackend): def get_predicate_class(self, predicate_name): return SUPPORTED_PREDICATES[predicate_name] class BDDLEntity(Wrapper): """ Thin wrapper class that wraps an object or system if it exists, or nothing if it does not exist. Will dynamically reference an object / system as they become real in the sim """ def __init__( self, bddl_inst, entity=None, ): """ Args: bddl_inst (str): BDDL synset instance of the entity, e.g.: "almond.n.01_1" entity (None or DatasetObject or BaseSystem): If specified, the BDDL entity to wrap. If not specified, will initially wrap nothing, but may dynamically reference an actual object or system if it exists in the future """ # Store synset and other info, and pass entity internally self.bddl_inst = bddl_inst self.synset = "_".join(self.bddl_inst.split("_")[:-1]) self.is_system = is_substance_synset(self.synset) # Infer the correct category to assign self.og_categories = OBJECT_TAXONOMY.get_subtree_substances(self.synset) \ if self.is_system else OBJECT_TAXONOMY.get_subtree_categories(self.synset) super().__init__(obj=entity) @property def name(self): """ Returns: None or str: Name of this entity, if it exists, else None """ if self.exists: return self.og_categories[0] if self.is_system else self.wrapped_obj.name else: return None @property def exists(self): """ Checks whether the entity referenced by @synset exists Returns: bool: Whether the entity referenced by @synset exists """ return self.wrapped_obj is not None def set_entity(self, entity): """ Sets the internal entity, overriding any if it already exists Args: entity (BaseSystem or BaseObject): Entity to set internally """ self.wrapped_obj = entity def clear_entity(self): """ Clears the internal entity, if any """ self.wrapped_obj = None def get_state(self, state, *args, **kwargs): """ Helper function to grab wrapped entity's state @state Args: state (BaseObjectState): State whose get_value() should be called *args (tuple): Any arguments to pass to getter, in order **kwargs (dict): Any keyword arguments to pass to getter, in order Returns: any: Returned value(s) from @state if self.wrapped_obj exists (i.e.: not None), else False """ return self.wrapped_obj.states[state].get_value(*args, **kwargs) if self.exists else False def set_state(self, state, *args, **kwargs): """ Helper function to set wrapped entity's state @state. Note: Should only be called if the entity exists! Args: state (BaseObjectState): State whose set_value() should be called *args (tuple): Any arguments to pass to getter, in order **kwargs (dict): Any keyword arguments to pass to getter, in order Returns: any: Returned value(s) from @state if self.wrapped_obj exists (i.e.: not None) """ assert self.exists, \ f"Cannot call set_state() for BDDLEntity {self.synset} when the entity does not exist!" return self.wrapped_obj.states[state].set_value(*args, **kwargs) class BDDLSampler: def __init__( self, env, activity_conditions, object_scope, backend, debug=False, ): # Store internal variables from inputs self._env = env self._scene_model = self._env.scene.scene_model if isinstance(self._env.scene, InteractiveTraversableScene) else None self._agent = self._env.robots[0] if debug: gm.DEBUG = True self._backend = backend 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._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 BaseObject 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 BDDLEntity self._attached_objects = defaultdict(set) # dict mapping str to set of str def sample(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 """ log.info("Sampling task...") # Reject scenes with missing non-sampleable objects # Populate object_scope with sampleable objects and the robot accept_scene, feedback = self._prepare_scene_for_sampling() if not accept_scene: return accept_scene, feedback # Sample objects to satisfy initial conditions 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 with og.sim.playing(): self._env.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._env.scene.update_initial_state() return True, None def _prepare_scene_for_sampling(self): """ Runs sanity checks for the current scene for the given BEHAVIOR task Returns: 2-tuple: - bool: Whether the generated scene activity should be accepted or not - dict: Any feedback from the sampling / initialization process """ 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_sampling_order() 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"] = BDDLEntity(bddl_inst="agent.n.01_1", entity=self._agent) return True, None 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 = OBJECT_TAXONOMY.get_abilities(obj_synset) 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 og.sim.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 get_initial_conditions(self._activity_conditions, self._backend, self._object_scope): 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 isinstance(condition, UnsampleablePredicate): 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, ObjectStateFuturePredicate)} 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] # 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 categories = OBJECT_TAXONOMY.get_subtree_categories(obj_synset) # Grab all models that fully support all abilities for the corresponding category valid_models = {cat: set(get_all_object_category_models_with_abilities( cat, OBJECT_TAXONOMY.get_abilities(OBJECT_TAXONOMY.get_synset_from_category(cat)))) 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()} room_insts = [None] if self._scene_model is None else og.sim.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 = og.sim.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] = BDDLEntity(bddl_inst=scene_obj, entity=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_obj.states[ContactBodies] # 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: np.product(x[2].aabb_extent)))) + list(reversed(sorted(cloth_conditions, key=lambda x: np.product(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 elif condition.STATE_NAME in {"attached"}: kwargs["bypass_alignment_checking"] = True kwargs["check_physics_stability"] = True kwargs["can_joint_break"] = False success = condition.sample(binary_state=positive, **kwargs) log_msg = " ".join( [ f"{condition_type} kinematic condition sampling", room_type, scene_obj, room_inst, parent_obj_name, condition.STATE_NAME, str(condition.body), str(success), ] ) log.info(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[np.mean(list(parent_obj_names.values()))].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 metalinks. 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].wrapped_obj]) # 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 = child_link_name.split("_")[1] if child_category.endswith("F"): continue assert child_category.endswith("M") parent_category = child_category[:-1] + "F" for parent_link_name in parent_attachment_links: if parent_category in parent_link_name: 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_metalinks(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_metalinks(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_metalinks(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([300, 300, 300], [0, 0, 0, 1]) 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] # 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] system_name = OBJECT_TAXONOMY.get_subtree_substances(obj_synset)[0] self._object_scope[obj_inst] = BDDLEntity( bddl_inst=obj_inst, entity=None if obj_inst in self._future_obj_instances else get_system(system_name), ) else: valid_categories = set(OBJECT_TAXONOMY.get_subtree_categories(obj_synset)) 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] = BDDLEntity(bddl_inst=obj_inst) 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 np.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=OBJECT_TAXONOMY.get_abilities(OBJECT_TAXONOMY.get_synset_from_category(category)), )) 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) 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 = np.random.choice(list(model_choices)) # Potentially add additional kwargs obj_kwargs = dict() obj_kwargs["bounding_box"] = GOOD_BBOXES.get(category, dict()).get(model, None) # create the object simulator_obj = DatasetObject( name=f"{category}_{len(og.sim.scene.objects)}", category=category, model=model, prim_type=PrimType.CLOTH if "cloth" in OBJECT_TAXONOMY.get_abilities(obj_synset) else PrimType.RIGID, **obj_kwargs, ) num_new_obj += 1 # Load the object into the simulator assert og.sim.scene.loaded, "Scene is not loaded" og.sim.import_object(simulator_obj) # Set these objects to be far-away locations simulator_obj.set_position(np.array([100.0, 100.0, -100.0]) + np.ones(3) * num_new_obj * 5.0) self._sampled_objects.add(simulator_obj) self._object_scope[obj_inst] = BDDLEntity(bddl_inst=obj_inst, entity=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 """ activity_goal_conditions = get_goal_conditions(self._activity_conditions, self._backend, self._object_scope) ground_goal_state_options = get_ground_goal_state_options(self._activity_conditions, self._backend, self._object_scope, activity_goal_conditions) np.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): """ 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: np.product(x[2].aabb_extent)))) + list(reversed(sorted(cloth_conditions, key=lambda x: np.product(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 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 = 1 for _ in range(num_trials): success = condition.sample(binary_state=positive, **kwargs) 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 = parent.in_rooms.copy() # 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 any scales are equal or less than the lower threshold, terminate immediately new_scale = entity.scale - m.DYNAMIC_SCALE_INCREMENT if np.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() if not success: # Update object registry because we just assigned in_rooms to newly imported objects og.sim.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 og.sim.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 np.any([np.any(self._object_scope[obj_inst].scale < m.MIN_DYNAMIC_SCALE) 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 np.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] = BDDLEntity(bddl_inst=obj_inst, entity=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 )
72,214
Python
49.429469
337
0.597945
StanfordVL/OmniGibson/omnigibson/renderer_settings/post_processing_settings.py
import omnigibson.lazy as lazy from omnigibson.renderer_settings.settings_base import SettingItem, SettingsBase, SubSettingsBase class PostProcessingSettings(SettingsBase): """ Post-Processing setting group that handles a variety of sub-settings, including: - Tone Mapping - Auto Exposure - Color Correction - Color Grading - XR Compositing - Chromatic Aberration - Depth Of Field Camera Overrides - Motion Blur - FTT Bloom - TV Noise & Film Grain - Reshade """ def __init__(self): self.tone_mapping_settings = ToneMappingSettings() self.auto_exposure_settings = AutoExposureSettings() self.color_correction_settings = ColorCorrectionSettings() self.color_grading_settings = ColorGradingSettings() self.xr_compositing_settings = XRCompositingSettings() self.chromatic_aberration_settings = ChromaticAberrationSettings() self.depth_of_field_settings = DepthOfFieldSettings() self.motion_blur_settings = MotionBlurSettings() self.ftt_bloom_settings = FTTBloomSettings() self.tv_noise_grain_settings = TVNoiseGrainSettings() self.reshade_settings = ReshadeSettings() @property def settings(self): settings = {} settings.update(self.tone_mapping_settings.settings) settings.update(self.auto_exposure_settings.settings) settings.update(self.color_correction_settings.settings) settings.update(self.color_grading_settings.settings) settings.update(self.xr_compositing_settings.settings) settings.update(self.chromatic_aberration_settings.settings) settings.update(self.depth_of_field_settings.settings) settings.update(self.motion_blur_settings.settings) settings.update(self.ftt_bloom_settings.settings) settings.update(self.tv_noise_grain_settings.settings) settings.update(self.reshade_settings.settings) return settings class ToneMappingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() # The main tonemapping layout contains only the combo box. All the other options # are saved in a different layout which can be swapped out in case the tonemapper changes. tonemapper_ops = [ "Clamp", "Linear", "Reinhard", "Reinhard (modified)", "HejiHableAlu", "HableUc2", "Aces", "Iray", ] self.tomemap_op = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Tone Mapping Operator", "/rtx/post/tonemap/op", range_list=tonemapper_ops ) # tonemap_op_idx = self._carb_settings.get("/rtx/post/tonemap/op") # Modified Reinhard # tonemap_op_idx == 3 self.max_white_luminance = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max White Luminance", "/rtx/post/tonemap/maxWhiteLuminance", range_from=0, range_to=100, ) # HableUc2 # tonemap_op_idx == 5 self.white_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "White Scale Value", "/rtx/post/tonemap/whiteScale", range_from=0, range_to=100 ) self.cm2_factor = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "cm^2 Factor", "/rtx/post/tonemap/cm2Factor", range_from=0, range_to=2 ) self.white_point = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "White Point", "/rtx/post/tonemap/whitepoint") self.film_iso = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Film ISO", "/rtx/post/tonemap/filmIso", range_from=50, range_to=1600 ) self.camera_shutter = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Camera Shutter", "/rtx/post/tonemap/cameraShutter", range_from=1, range_to=5000 ) self.f_number = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "f-Number / f-Stop", "/rtx/post/tonemap/fNumber", range_from=1, range_to=20 ) # Iray # tonemap_op_idx == 7 self.crush_blacks = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Crush Blacks", "/rtx/post/tonemap/irayReinhard/crushBlacks", range_from=0, range_to=1, ) self.burn_highlights = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Burn Highlights", "/rtx/post/tonemap/irayReinhard/burnHighlights", range_from=0, range_to=1, ) self.burn_highlights_per_component = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Burn Highlights per Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsPerComponent", ) self.burn_highlights_max_component = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Burn Highlights max Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsMaxComponent", ) self.saturation = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Saturation", "/rtx/post/tonemap/irayReinhard/saturation", range_from=0, range_to=1 ) # Clamp is never using srgb conversion # tonemap_op_idx != 0 self.enable_srgb_to_gamma = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable SRGB To Gamma Conversion", "/rtx/post/tonemap/enableSrgbToGamma" ) tonemapColorMode = ["sRGBLinear", "ACEScg"] self.color_mode = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Tonemapping Color Space", "/rtx/post/tonemap/colorMode", range_list=tonemapColorMode, ) self.wrapvalue = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Wrap Value", "/rtx/post/tonemap/wrapValue", range_from=0, range_to=100000 ) @property def settings(self): settings = { "/rtx/post/tonemap/op": self.tomemap_op, "/rtx/post/tonemap/cm2Factor": self.cm2_factor, "/rtx/post/tonemap/whitepoint": self.white_point, "/rtx/post/tonemap/filmIso": self.film_iso, "/rtx/post/tonemap/cameraShutter": self.camera_shutter, "/rtx/post/tonemap/fNumber": self.f_number, "/rtx/post/tonemap/colorMode": self.color_mode, "/rtx/post/tonemap/wrapValue": self.wrapvalue, } tonemap_op_idx = self._carb_settings.get("/rtx/post/tonemap/op") if tonemap_op_idx == 3: # Modified Reinhard settings.update( {"/rtx/post/tonemap/maxWhiteLuminance": self.max_white_luminance,} ) if tonemap_op_idx == 5: # HableUc2 settings.update( {"/rtx/post/tonemap/whiteScale": self.white_scale,} ) if tonemap_op_idx == 7: # Iray settings.update( { "/rtx/post/tonemap/irayReinhard/crushBlacks": self.crush_blacks, "/rtx/post/tonemap/irayReinhard/burnHighlights": self.burn_highlights, "/rtx/post/tonemap/irayReinhard/burnHighlightsPerComponent": self.burn_highlights_per_component, "/rtx/post/tonemap/irayReinhard/burnHighlightsMaxComponent": self.burn_highlights_max_component, "/rtx/post/tonemap/irayReinhard/saturation": self.saturation, } ) if tonemap_op_idx != 0: # Clamp is never using srgb conversion settings.update( {"/rtx/post/tonemap/enableSrgbToGamma": self.enable_srgb_to_gamma,} ) return settings class AutoExposureSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() histFilter_types = ["Median", "Average"] self.filter_type = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Histogram Filter", "/rtx/post/histogram/filterType", range_list=histFilter_types ) self.tau = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Adaptation Speed", "/rtx/post/histogram/tau", range_from=0.5, range_to=10.0 ) self.white_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "White Point Scale", "/rtx/post/histogram/whiteScale", range_from=0.01, range_to=80.0, ) self.use_exposure_clamping = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Use Exposure Clamping", "/rtx/post/histogram/useExposureClamping" ) self.min_ev = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Min EV", "/rtx/post/histogram/minEV", range_from=0.0, range_to=1000000.0 ) self.max_ev = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max EV", "/rtx/post/histogram/maxEV", range_from=0.0, range_to=1000000.0 ) @property def settings(self): return { "/rtx/post/histogram/filterType": self.filter_type, "/rtx/post/histogram/tau": self.tau, "/rtx/post/histogram/whiteScale": self.white_scale, "/rtx/post/histogram/useExposureClamping": self.use_exposure_clamping, "/rtx/post/histogram/minEV": self.min_ev, "/rtx/post/histogram/maxEV": self.max_ev, } @property def enabled_setting_path(self): return "/rtx/post/histogram/enabled" class ColorCorrectionSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"] self.mode = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.STRING, "Mode", "/rtx/post/colorcorr/mode", range_list=mode) # ccMode = self._carb_settings.get("/rtx/post/colorcorr/mode") # ccMode == 0 color_correction_mode = ["sRGBLinear", "ACEScg"] self.outputMode = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Output Color Space", "/rtx/post/colorcorr/outputMode", range_list=color_correction_mode, ) self.saturation = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Saturation", "/rtx/post/colorcorr/saturation") self.contrast = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Contrast", "/rtx/post/colorcorr/contrast") self.gamma = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Gamma", "/rtx/post/colorcorr/gamma") self.gain = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Gain", "/rtx/post/colorcorr/gain") self.offset = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Offset", "/rtx/post/colorcorr/offset") @property def settings(self): settings = { "/rtx/post/colorcorr/mode": self.mode, "/rtx/post/colorcorr/saturation": self.saturation, "/rtx/post/colorcorr/contrast": self.contrast, "/rtx/post/colorcorr/gamma": self.gamma, "/rtx/post/colorcorr/gain": self.gain, "/rtx/post/colorcorr/offset": self.offset, } cc_mode = self._carb_settings.get("/rtx/post/colorcorr/mode") if cc_mode == 0: settings.update( {"/rtx/post/colorcorr/outputMode": self.outputMode,} ) return settings @property def enabled_setting_path(self): return "/rtx/post/colorcorr/enabled" class ColorGradingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"] self.mode = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.STRING, "Mode", "/rtx/post/colorgrad/mode", range_list=mode) cg_mode = self._carb_settings.get("/rtx/post/colorgrad/mode") if cg_mode == 0: colorGradingMode = ["sRGBLinear", "ACEScg"] self.output_mode = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Output Color Space", "/rtx/post/colorgrad/outputMode", range_list=colorGradingMode, ) self.blackpoint = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Black Point", "/rtx/post/colorgrad/blackpoint") self.whitepoint = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "White Point", "/rtx/post/colorgrad/whitepoint") self.contrast = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Contrast", "/rtx/post/colorgrad/contrast") self.lift = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Lift", "/rtx/post/colorgrad/lift") self.gain = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Gain", "/rtx/post/colorgrad/gain") self.multiply = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Multiply", "/rtx/post/colorgrad/multiply") self.offset = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Offset", "/rtx/post/colorgrad/offset") self.gamma = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Gamma", "/rtx/post/colorgrad/gamma") @property def settings(self): settings = { "/rtx/post/colorgrad/mode": self.mode, "/rtx/post/colorgrad/blackpoint": self.blackpoint, "/rtx/post/colorgrad/whitepoint": self.whitepoint, "/rtx/post/colorgrad/contrast": self.contrast, "/rtx/post/colorgrad/lift": self.lift, "/rtx/post/colorgrad/gain": self.gain, "/rtx/post/colorgrad/multiply": self.multiply, "/rtx/post/colorgrad/offset": self.offset, "/rtx/post/colorgrad/gamma": self.gamma, } cg_mode = self._carb_settings.get("/rtx/post/colorgrad/mode") if cg_mode == 0: settings.update( {"/rtx/post/colorgrad/outputMode": self.output_mode,} ) return settings @property def enabled_setting_path(self): return "/rtx/post/colorgrad/enabled" class XRCompositingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.apply_alpha_zero_pass_first = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Composite in Linear Space", "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst" ) self.backgroundComposite = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Composite in Editor", "/rtx/post/backgroundZeroAlpha/backgroundComposite" ) # self.backplate_texture = SettingItem(self, "ASSET", "Default Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture") self.background_default_color = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Default Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor" ) self.enable_lens_distortion_correction = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Lens Distortion", "/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection", ) # self.distortion_map = SettingItem(self, "ASSET", "Lens Distortion Map", "/rtx/post/lensDistortion/distortionMap") # self.undistortion_map = SettingItem(self, "ASSET", "Lens Undistortion Map", "/rtx/post/lensDistortion/undistortionMap") @property def settings(self): return { "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst": self.apply_alpha_zero_pass_first, "/rtx/post/backgroundZeroAlpha/backgroundComposite": self.backgroundComposite, "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor": self.background_default_color, "/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection": self.enable_lens_distortion_correction, } @property def enabled_setting_path(self): return "/rtx/post/backgroundZeroAlpha/enabled" class ChromaticAberrationSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.strength_r = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Strength Red", "/rtx/post/chromaticAberration/strengthR", -1.0, 1.0, 0.01 ) self.strength_g = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Strength Green", "/rtx/post/chromaticAberration/strengthG", -1.0, 1.0, 0.01 ) self.strength_b = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Strength Blue", "/rtx/post/chromaticAberration/strengthB", -1.0, 1.0, 0.01 ) chromatic_aberration_ops = ["Radial", "Barrel"] self.mode_r = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Algorithm Red", "/rtx/post/chromaticAberration/modeR", chromatic_aberration_ops ) self.mode_g = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Algorithm Green", "/rtx/post/chromaticAberration/modeG", chromatic_aberration_ops ) self.mode_b = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Algorithm Blue", "/rtx/post/chromaticAberration/modeB", chromatic_aberration_ops ) self.enable_lanczos = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Use Lanczos Sampler", "/rtx/post/chromaticAberration/enableLanczos" ) @property def settings(self): return { "/rtx/post/chromaticAberration/strengthR": self.strength_r, "/rtx/post/chromaticAberration/strengthG": self.strength_g, "/rtx/post/chromaticAberration/strengthB": self.strength_b, "/rtx/post/chromaticAberration/modeR": self.mode_r, "/rtx/post/chromaticAberration/modeG": self.mode_g, "/rtx/post/chromaticAberration/modeB": self.mode_b, "/rtx/post/chromaticAberration/enableLanczos": self.enable_lanczos, } @property def enabled_setting_path(self): return "/rtx/post/chromaticAberration/enabled" class DepthOfFieldSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.dof_enabled = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable DOF", "/rtx/post/dof/enabled") self.subject_distance = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Subject Distance", "/rtx/post/dof/subjectDistance", range_from=-10000, range_to=10000.0, ) self.focal_length = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Focal Length (mm)", "/rtx/post/dof/focalLength", range_from=0, range_to=1000 ) self.f_number = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "f-Number / f-Stop", "/rtx/post/dof/fNumber", range_from=0, range_to=1000 ) self.anisotropy = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Anisotropy", "/rtx/post/dof/anisotropy", range_from=-1, range_to=1 ) @property def settings(self): return { "/rtx/post/dof/enabled": self.dof_enabled, "/rtx/post/dof/subjectDistance": self.subject_distance, "/rtx/post/dof/focalLength": self.focal_length, "/rtx/post/dof/fNumber": self.f_number, "/rtx/post/dof/anisotropy": self.anisotropy, } @property def enabled_setting_path(self): return "/rtx/post/dof/overrideEnabled" class MotionBlurSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.max_blur_diameter_fraction = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Blur Diameter Fraction", "/rtx/post/motionblur/maxBlurDiameterFraction", range_from=0, range_to=0.5, ) self.num_samples = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Number of Samples", "/rtx/post/motionblur/numSamples", range_from=4, range_to=32 ) self.exposure_fraction = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Exposure Fraction", "/rtx/post/motionblur/exposureFraction", range_from=0, range_to=5.0, ) @property def settings(self): return { "/rtx/post/motionblur/maxBlurDiameterFraction": self.max_blur_diameter_fraction, "/rtx/post/motionblur/numSamples": self.num_samples, "/rtx/post/motionblur/exposureFraction": self.exposure_fraction, } @property def enabled_setting_path(self): return "/rtx/post/motionblur/enabled" class FTTBloomSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.flare_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Scale", "/rtx/post/lensFlares/flareScale", range_from=-1000, range_to=1000 ) self.cutoff_point = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.DOUBLE3, "Cutoff Point", "/rtx/post/lensFlares/cutoffPoint") self.cutoff_fuzziness = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Cutoff Fuzziness", "/rtx/post/lensFlares/cutoffFuzziness", range_from=0.0, range_to=1.0, ) self.energy_constraining_blend = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Energy Constrained", "/rtx/post/lensFlares/energyConstrainingBlend" ) self.physical_settings = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Physical Settings", "/rtx/post/lensFlares/physicalSettings" ) # fftbloom_use_physical_settings = self._carb_settings.get("/rtx/post/lensFlares/physicalSettings") # Physical settings self.blades = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Blades", "/rtx/post/lensFlares/blades", range_from=0, range_to=10 ) self.aperture_rotation = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Aperture Rotation", "/rtx/post/lensFlares/apertureRotation", range_from=-1000, range_to=1000, ) self.sensor_diagonal = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Sensor Diagonal", "/rtx/post/lensFlares/sensorDiagonal", range_from=-1000, range_to=1000, ) self.sensor_aspect_ratio = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Sensor Aspect Ratio", "/rtx/post/lensFlares/sensorAspectRatio", range_from=-1000, range_to=1000, ) self.f_number = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "f-Number / f-Stop", "/rtx/post/lensFlares/fNumber", range_from=-1000, range_to=1000, ) self.focal_length = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Focal Length (mm)", "/rtx/post/lensFlares/focalLength", range_from=-1000, range_to=1000, ) # Non-physical settings self.halo_flare_radius = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.DOUBLE3, "Halo Radius", "/rtx/post/lensFlares/haloFlareRadius" ) self.halo_flare_falloff = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.DOUBLE3, "Halo Flare Falloff", "/rtx/post/lensFlares/haloFlareFalloff" ) self.halo_flare_weight = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Halo Flare Weight", "/rtx/post/lensFlares/haloFlareWeight", range_from=-1000, range_to=1000, ) self.aniso_flare_falloff_y = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.DOUBLE3, "Aniso Falloff Y", "/rtx/post/lensFlares/anisoFlareFalloffY" ) self.aniso_flare_falloff_x = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.DOUBLE3, "Aniso Falloff X", "/rtx/post/lensFlares/anisoFlareFalloffX" ) self.aniso_flare_weight = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Aniso Flare Weight", "/rtx/post/lensFlares/anisoFlareWeight", range_from=-1000, range_to=1000, ) self.isotropic_flare_falloff = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.DOUBLE3, "Isotropic Flare Falloff", "/rtx/post/lensFlares/isotropicFlareFalloff" ) self.isotropic_flare_weight = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Isotropic Flare Weight", "/rtx/post/lensFlares/isotropicFlareWeight", range_from=-1000, range_to=1000, ) @property def settings(self): settings = { "/rtx/post/lensFlares/flareScale": self.flare_scale, "/rtx/post/lensFlares/cutoffPoint": self.cutoff_point, "/rtx/post/lensFlares/cutoffFuzziness": self.cutoff_fuzziness, "/rtx/post/lensFlares/energyConstrainingBlend": self.energy_constraining_blend, "/rtx/post/lensFlares/physicalSettings": self.physical_settings, } fftbloom_use_physical_settings = self._carb_settings.get("/rtx/post/lensFlares/physicalSettings") if fftbloom_use_physical_settings: settings.update( { "/rtx/post/lensFlares/blades": self.blades, "/rtx/post/lensFlares/apertureRotation": self.aperture_rotation, "/rtx/post/lensFlares/sensorDiagonal": self.sensor_diagonal, "/rtx/post/lensFlares/sensorAspectRatio": self.sensor_aspect_ratio, "/rtx/post/lensFlares/fNumber": self.f_number, "/rtx/post/lensFlares/focalLength": self.focal_length, } ) else: settings.update( { "/rtx/post/lensFlares/haloFlareRadius": self.halo_flare_radius, "/rtx/post/lensFlares/haloFlareFalloff": self.halo_flare_falloff, "/rtx/post/lensFlares/haloFlareWeight": self.halo_flare_weight, "/rtx/post/lensFlares/anisoFlareFalloffY": self.aniso_flare_falloff_y, "/rtx/post/lensFlares/anisoFlareFalloffX": self.aniso_flare_falloff_x, "/rtx/post/lensFlares/anisoFlareWeight": self.aniso_flare_weight, "/rtx/post/lensFlares/isotropicFlareFalloff": self.isotropic_flare_falloff, "/rtx/post/lensFlares/isotropicFlareWeight": self.isotropic_flare_weight, } ) return settings @property def enabled_setting_path(self): return "/rtx/post/lensFlares/enabled" class TVNoiseGrainSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.enable_scanlines = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Scanlines", "/rtx/post/tvNoise/enableScanlines" ) self.scanline_spread = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Scanline Spreading", "/rtx/post/tvNoise/scanlineSpread", range_from=0.0, range_to=2.0, ) self.enable_scroll_bug = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Scroll Bug", "/rtx/post/tvNoise/enableScrollBug" ) self.enable_vignetting = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Vignetting", "/rtx/post/tvNoise/enableVignetting" ) self.vignetting_size = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Vignetting Size", "/rtx/post/tvNoise/vignettingSize", range_from=0.0, range_to=255 ) self.vignetting_strength = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Vignetting Strength", "/rtx/post/tvNoise/vignettingStrength", range_from=0.0, range_to=2.0, ) self.enable_vignetting_flickering = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Vignetting Flickering", "/rtx/post/tvNoise/enableVignettingFlickering" ) self.enable_ghost_flickering = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Ghost Flickering", "/rtx/post/tvNoise/enableGhostFlickering" ) self.enable_wave_distortion = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Wavy Distortion", "/rtx/post/tvNoise/enableWaveDistortion" ) self.enable_vertical_lines = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Vertical Lines", "/rtx/post/tvNoise/enableVerticalLines" ) self.enable_random_splotches = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Random Splotches", "/rtx/post/tvNoise/enableRandomSplotches" ) self.enable_film_grain = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Film Grain", "/rtx/post/tvNoise/enableFilmGrain" ) # Filmgrain is a subframe in TV Noise # self._carb_settings.get("/rtx/post/tvNoise/enableFilmGrain"): self.grain_amount = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Grain Amount", "/rtx/post/tvNoise/grainAmount", range_from=0, range_to=0.2 ) self.color_amount = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Color Amount", "/rtx/post/tvNoise/colorAmount", range_from=0, range_to=1.0 ) self.lum_amount = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Luminance Amount", "/rtx/post/tvNoise/lumAmount", range_from=0, range_to=1.0 ) self.grain_size = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Grain Size", "/rtx/post/tvNoise/grainSize", range_from=1.5, range_to=2.5 ) @property def settings(self): settings = { "/rtx/post/tvNoise/enableScanlines": self.enable_scanlines, "/rtx/post/tvNoise/scanlineSpread": self.scanline_spread, "/rtx/post/tvNoise/enableScrollBug": self.enable_scroll_bug, "/rtx/post/tvNoise/enableVignetting": self.enable_vignetting, "/rtx/post/tvNoise/vignettingSize": self.vignetting_size, "/rtx/post/tvNoise/vignettingStrength": self.vignetting_strength, "/rtx/post/tvNoise/enableVignettingFlickering": self.enable_vignetting_flickering, "/rtx/post/tvNoise/enableGhostFlickering": self.enable_ghost_flickering, "/rtx/post/tvNoise/enableWaveDistortion": self.enable_wave_distortion, "/rtx/post/tvNoise/enableVerticalLines": self.enable_vertical_lines, "/rtx/post/tvNoise/enableRandomSplotches": self.enable_random_splotches, "/rtx/post/tvNoise/enableFilmGrain": self.enable_film_grain, } if self._carb_settings.get("/rtx/post/tvNoise/enableFilmGrain"): settings.update( { "/rtx/post/tvNoise/grainAmount": self.grain_amount, "/rtx/post/tvNoise/colorAmount": self.color_amount, "/rtx/post/tvNoise/lumAmount": self.lum_amount, "/rtx/post/tvNoise/grainSize": self.grain_size, } ) return settings @property def enabled_setting_path(self): return "/rtx/post/tvNoise/enabled" class ReshadeSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() # self._add_setting("ASSET", "Preset path", "/rtx/reshade/presetFilePath") # widget = self._add_setting("ASSET", "Effect search dir path", "/rtx/reshade/effectSearchDirPath") # widget.is_folder=True # widget = self._add_setting("ASSET", "Texture search dir path", "/rtx/reshade/textureSearchDirPath") # widget.is_folder=True @property def settings(self): return {} @property def enabled_setting_path(self): return "/rtx/reshade/enable"
34,472
Python
44.240157
150
0.625348
StanfordVL/OmniGibson/omnigibson/renderer_settings/common_settings.py
import omnigibson.lazy as lazy from omnigibson.renderer_settings.settings_base import SettingItem, SettingsBase, SubSettingsBase class CommonSettings(SettingsBase): """ Common setting group that handles a variety of sub-settings, including: - Rendering - Geometry - Materials - Lighting - Simple Fog - Flow - Debug View """ def __init__(self): self.render_settings = RenderSettings() self.geometry_settings = GeometrySettings() self.materials_settings = MaterialsSettings() self.lighting_settings = LightingSettings() self.simple_fog_setting = SimpleFogSettings() self.flow_settings = FlowSettings() self.debug_view_settings = DebugViewSettings() @property def settings(self): settings = {} settings.update(self.render_settings.settings) settings.update(self.geometry_settings.settings) settings.update(self.materials_settings.settings) settings.update(self.lighting_settings.settings) settings.update(self.simple_fog_setting.settings) settings.update(self.flow_settings.settings) settings.update(self.debug_view_settings.settings) return settings class RenderSettings(SubSettingsBase): def __init__(self): self.multi_threading_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled" ) @property def settings(self): return { "/rtx/multiThreading/enabled": self.multi_threading_enabled, } class GeometrySettings(SubSettingsBase): def __init__(self): # Basic geometry settings. tbnMode = ["AUTO", "CPU", "GPU", "Force GPU"] self.tbn_frame_mode = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Normal & Tangent Space Generation Mode", "/rtx/hydra/TBNFrameMode", range_list=tbnMode, ) self.face_culling_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Back Face Culling", "/rtx/hydra/faceCulling/enabled" ) # Wireframe settings. self.wireframe_thickness = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Wireframe Thickness", "/rtx/wireframe/wireframeThickness", range_from=0.1, range_to=100, ) self.wireframe_thickness_world_space = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Wireframe World Space Thickness", "/rtx/wireframe/wireframeThicknessWorldSpace" ) self.wireframe_shading_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Shaded Wireframe", "/rtx/wireframe/shading/enabled" ) # Subdivision settings. self.subdivision_refinement_level = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Subdivision Global Refinement Level", "/rtx/hydra/subdivision/refinementLevel", range_from=0, range_to=2, ) self.subdivision_adaptive_refinement = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Subdivision Feature-adaptive Refinement", "/rtx/hydra/subdivision/adaptiveRefinement", ) # if set to zero, override to scene unit, which means the scale factor would be 1 self.renderMeterPerUnit = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Renderer-internal meters per unit ", "/rtx/scene/renderMeterPerUnit" ) self.only_opaque_ray_flags = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Hide geometry that uses opacity (debug)", "/rtx/debug/onlyOpaqueRayFlags" ) @property def settings(self): return { "/rtx/hydra/TBNFrameMode": self.tbn_frame_mode, "/rtx/hydra/faceCulling/enabled": self.face_culling_enabled, "/rtx/wireframe/wireframeThickness": self.wireframe_thickness, "/rtx/wireframe/wireframeThicknessWorldSpace": self.wireframe_thickness_world_space, "/rtx/wireframe/shading/enabled": self.wireframe_shading_enabled, "/rtx/hydra/subdivision/refinementLevel": self.subdivision_refinement_level, "/rtx/hydra/subdivision/adaptiveRefinement": self.subdivision_adaptive_refinement, "/rtx/scene/renderMeterPerUnit": self.renderMeterPerUnit, "/rtx/debug/onlyOpaqueRayFlags": self.only_opaque_ray_flags, } class MaterialsSettings(SubSettingsBase): def __init__(self): self.skip_material_loading = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Disable Material Loading", "/app/renderer/skipMaterialLoading" ) self.max_mip_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Textures: Mipmap Levels to Load", "/rtx-transient/resourcemanager/maxMipCount", range_from=2, range_to=15, ) self.compression_mip_size_threshold = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Textures: Compression Mipmap Size Threshold (0 to disable) ", "/rtx-transient/resourcemanager/compressionMipSizeThreshold", 0, 8192, ) self.enable_texture_streaming = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Textures: on-demand streaming (toggling requires scene reload)", "/rtx-transient/resourcemanager/enableTextureStreaming", ) self.memory_budget = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Texture streaming memory budget (fraction of GPU memory)", "/rtx-transient/resourcemanager/texturestreaming/memoryBudget", 0.01, 1, ) self.animation_time = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "MDL Animation Time Override", "/rtx/animationTime") self.animation_time_use_wallclock = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "MDL Animation Time Use Wallclock", "/rtx/animationTimeUseWallclock" ) @property def settings(self): return { "/app/renderer/skipMaterialLoading": self.skip_material_loading, "/rtx-transient/resourcemanager/maxMipCount": self.max_mip_count, "/rtx-transient/resourcemanager/compressionMipSizeThreshold": self.compression_mip_size_threshold, "/rtx-transient/resourcemanager/enableTextureStreaming": self.enable_texture_streaming, "/rtx-transient/resourcemanager/texturestreaming/memoryBudget": self.memory_budget, "/rtx/animationTime": self.animation_time, "/rtx/animationTimeUseWallclock": self.animation_time_use_wallclock, } class LightingSettings(SubSettingsBase): def __init__(self): # Basic light settings. show_lights_settings = {"Per-Light Enable": 0, "Force Enable": 1, "Force Disable": 2} self.show_lights = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Show Area Lights In Primary Rays", "/rtx/raytracing/showLights", range_dict=show_lights_settings, ) self.shadow_bias = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Shadow Bias", "/rtx/raytracing/shadowBias", range_from=0.0, range_to=5.0 ) self.skip_most_lights = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Use First Distant Light & First Dome Light Only", "/rtx/scenedb/skipMostLights" ) # Demo light. dome_lighting_sampling_type = { "Upper & Lower Hemisphere": 0, # "Upper Visible & Sampled, Lower Is Black": 1, "Upper Hemisphere Visible & Sampled, Lower Is Only Visible": 2, "Use As Env Map": 3, } self.upper_lower_strategy = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Hemisphere Sampling", "/rtx/domeLight/upperLowerStrategy", range_dict=dome_lighting_sampling_type, ) dome_texture_resolution_items = { "16": 16, "32": 32, "64": 64, "128": 128, "256": 256, "512": 512, "1024": 1024, "2048": 2048, "4096": 4096, "8192": 8192, } self.baking_resolution = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Baking Resolution", "/rtx/domeLight/baking/resolution", range_dict=dome_texture_resolution_items, ) self.resolution_factor = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Dome Light Texture Resolution Factor", "/rtx/domeLight/resolutionFactor", range_from=0.01, range_to=4.0, ) self.baking_spp = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Dome Light Material Baking SPP", "/rtx/domeLight/baking/spp", range_from=1, range_to=32, ) @property def settings(self): return { "/rtx/raytracing/showLights": self.show_lights, "/rtx/raytracing/shadowBias": self.shadow_bias, "/rtx/scenedb/skipMostLights": self.skip_most_lights, "/rtx/domeLight/upperLowerStrategy": self.upper_lower_strategy, "/rtx/domeLight/baking/resolution": self.baking_resolution, "/rtx/domeLight/resolutionFactor": self.resolution_factor, "/rtx/domeLight/baking/spp": self.baking_spp, } class SimpleFogSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.fog_color = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Color", "/rtx/fog/fogColor") self.fog_color_intensity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Intensity", "/rtx/fog/fogColorIntensity", range_from=1, range_to=1000000 ) self.fog_z_up_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Height-based Fog - Use +Z Axis", "/rtx/fog/fogZup/enabled" ) self.fog_start_height = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Height-based Fog - Plane Height", "/rtx/fog/fogStartHeight", range_from=-1000000, range_to=1000000, ) self.fog_height_density = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Height Density", "/rtx/fog/fogHeightDensity", range_from=0, range_to=1 ) self.fog_height_falloff = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Height Falloff", "/rtx/fog/fogHeightFalloff", range_from=0, range_to=1000 ) self.fog_distance_density = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Distance Density", "/rtx/fog/fogDistanceDensity", range_from=0, range_to=1 ) self.fog_start_dist = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Start Distance to Camera", "/rtx/fog/fogStartDist", range_from=0, range_to=1000000 ) self.fog_end_dist = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "End Distance to Camera", "/rtx/fog/fogEndDist", range_from=0, range_to=1000000 ) @property def settings(self): return { "/rtx/fog/fogColor": self.fog_color, "/rtx/fog/fogColorIntensity": self.fog_color_intensity, "/rtx/fog/fogZup/enabled": self.fog_z_up_enabled, "/rtx/fog/fogStartHeight": self.fog_height_density, "/rtx/fog/fogHeightDensity": self.fog_height_density, "/rtx/fog/fogHeightFalloff": self.fog_height_falloff, "/rtx/fog/fogDistanceDensity": self.fog_distance_density, "/rtx/fog/fogStartDist": self.fog_start_dist, "/rtx/fog/fogEndDist": self.fog_end_dist, } @property def enabled_setting_path(self): return "/rtx/fog/enabled" class FlowSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.ray_traced_shadows_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Flow in Real-Time Ray Traced Shadows", "/rtx/flow/rayTracedShadowsEnabled" ) self.ray_traced_reflections_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Flow in Real-Time Ray Traced Reflections", "/rtx/flow/rayTracedReflectionsEnabled" ) self.path_tracing_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Flow in Path-Traced Mode", "/rtx/flow/pathTracingEnabled" ) self.path_tracing_shadows_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Flow in Path-Traced Mode Shadows", "/rtx/flow/pathTracingShadowsEnabled" ) self.composite_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Composite with Flow Library Renderer", "/rtx/flow/compositeEnabled" ) self.use_flow_library_self_shadow = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Use Flow Library Self Shadow", "/rtx/flow/useFlowLibrarySelfShadow" ) self.max_blocks = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Blocks", "/rtx/flow/maxBlocks") @property def settings(self): return { "/rtx/flow/rayTracedShadowsEnabled": self.ray_traced_shadows_enabled, "/rtx/flow/rayTracedReflectionsEnabled": self.ray_traced_reflections_enabled, "/rtx/flow/pathTracingEnabled": self.path_tracing_enabled, "/rtx/flow/pathTracingShadowsEnabled": self.path_tracing_shadows_enabled, "/rtx/flow/compositeEnabled": self.composite_enabled, "/rtx/flow/useFlowLibrarySelfShadow": self.use_flow_library_self_shadow, "/rtx/flow/maxBlocks": self.max_blocks, } @property def enabled_setting_path(self): return "/rtx/flow/enabled" class DebugViewSettings(SubSettingsBase): def __init__(self): debug_view_items = { "Off": "", "Beauty Before Tonemap": "beautyPreTonemap", "Beauty After Tonemap": "beautyPostTonemap", "Timing Heat Map": "TimingHeatMap", "Depth": "depth", "World Position": "worldPosition", "Wireframe": "wire", "Barycentrics": "barycentrics", "Texture Coordinates 0": "texcoord0", "Tangent U": "tangentu", "Tangent V": "tangentv", "Interpolated Normal": "normal", "Triangle Normal": "triangleNormal", "Material Normal": "materialGeometryNormal", "Instance ID": "instanceId", "3D Motion Vectors": "targetMotion", "Shadow (last light)": "shadow", "Diffuse Reflectance": "diffuseReflectance", "Specular Reflectance": "reflectance", "Roughness": "roughness", "Ambient Occlusion": "ao", "Reflections": "reflections", "Reflections 3D Motion Vectors": "reflectionsMotion", "Translucency": "translucency", "Radiance": "radiance", "Diffuse GI": "indirectDiffuse", "Caustics": "caustics", "PT Noisy Result": "pathTracerNoisy", "PT Denoised Result": "pathTracerDenoised", "RT Noisy Sampled Lighting": "rtNoisySampledLighting", "RT Denoised Sampled Lighting": "rtDenoisedSampledLighting", "Developer Debug Texture": "developerDebug", "Noisy Dome Light": "noisyDomeLightingTex", "Denoised Dome Light": "denoisedDomeLightingTex", "RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only "RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only "RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only "RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only "Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only "Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only # Targets not using RT accumulation "RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum", "RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum", "RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum", "Reflections (Not Accumulated)": "reflectionsNonAccum", "Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum", } self.target = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Render Target", "/rtx/debugView/target", range_dict=debug_view_items ) self.scaling = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Output Value Scaling", "/rtx/debugView/scaling", range_from=-1000000, range_to=1000000, ) @property def settings(self): return { "/rtx/debugView/target": self.target, "/rtx/debugView/scaling": self.scaling, }
18,494
Python
43.352518
150
0.621229
StanfordVL/OmniGibson/omnigibson/renderer_settings/real_time_settings.py
import omnigibson.lazy as lazy from omnigibson.renderer_settings.settings_base import SettingItem, SettingsBase, SubSettingsBase class RealTimeSettings(SettingsBase): """ Real-Time setting group that handles a variety of sub-settings, including: - Eco Mode - Anti Aliasing - Direct Lighting - Reflections - Translucency - Global Volumetric Effects - Caustics - Indirect Diffuse Lighting - RTMulti GPU (if multiple GPUs available) """ def __init__(self): self.eco_mode_settings = EcoModeSettings() self.anti_aliasing_settings = AntiAliasingSettings() self.direct_lighting_settings = DirectLightingSettings() self.reflections_settings = ReflectionsSettings() self.translucency_settings = TranslucencySettings() self.global_volumetric_effects_settings = GlobalVolumetricEffectsSettings() self.caustics_settings = CausticsSettings() self.indirect_diffuse_lighting_settings = IndirectDiffuseLightingSettings() gpu_count = lazy.carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") if gpu_count and gpu_count > 1: self.rt_multi_gpu_settings = RTMultiGPUSettings() @property def settings(self): settings = {} settings.update(self.eco_mode_settings.settings) settings.update(self.anti_aliasing_settings.settings) settings.update(self.direct_lighting_settings.settings) settings.update(self.reflections_settings.settings) settings.update(self.translucency_settings.settings) settings.update(self.global_volumetric_effects_settings.settings) settings.update(self.caustics_settings.settings) settings.update(self.indirect_diffuse_lighting_settings.settings) gpu_count = lazy.carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") if gpu_count and gpu_count > 1: settings.update(self.rt_multi_gpu_settings.settings) return settings class EcoModeSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.max_frames_without_change = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Stop Rendering After This Many Frames Without Changes", "/rtx/ecoMode/maxFramesWithoutChange", range_from=0, range_to=100, ) @property def settings(self): return { "/rtx/ecoMode/maxFramesWithoutChange": self.max_frames_without_change, } @property def enabled_setting_path(self): return "/rtx/ecoMode/enabled" class AntiAliasingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() antialiasing_ops = ["Off", "TAA", "FXAA"] if self._carb_settings.get("/ngx/enabled") is True: antialiasing_ops.append("DLSS") antialiasing_ops.append("RTXAA") self.algorithm = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.STRING, "Algorithm", "/rtx/post/aa/op", antialiasing_ops) # antialiasing_op_idx == 1 # TAA self.static_ratio = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Static scaling", "/rtx/post/scaling/staticRatio", range_from=0.33, range_to=1 ) self.samples = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "TAA Samples", "/rtx/post/taa/samples", range_from=1, range_to=16 ) self.alpha = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "TAA history scale", "/rtx/post/taa/alpha", range_from=0, range_to=1 ) # antialiasing_op_idx == 2 # FXAA self.quality_sub_pix = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Subpixel Quality", "/rtx/post/fxaa/qualitySubPix", range_from=0.0, range_to=1.0 ) self.quality_edge_threshold = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Edge Threshold", "/rtx/post/fxaa/qualityEdgeThreshold", range_from=0.0, range_to=1.0, ) self.quality_edge_threshold_min = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Edge Threshold Min", "/rtx/post/fxaa/qualityEdgeThresholdMin", range_from=0.0, range_to=1.0, ) # antialiasing_op_idx == 3 or antialiasing_op_idx == 4 # DLSS and RTXAA # if antialiasing_op_idx == 3 dlss_opts = ["Performance", "Balanced", "Quality"] self.exec_mode = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.STRING, "Execution mode", "/rtx/post/dlss/execMode", dlss_opts) self.sharpness = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Sharpness", "/rtx/post/aa/sharpness", range_from=0.0, range_to=1.0 ) exposure_ops = ["Force self evaluated", "PostProcess Autoexposure", "Fixed"] self.auto_exposure_mode = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Exposure mode", "/rtx/post/aa/autoExposureMode", exposure_ops ) # auto_exposure_idx = self._carb_settings.get("/rtx/post/aa/autoExposureMode") # if auto_exposure_idx == 1 self.exposure_multiplier = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Auto Exposure Multiplier", "/rtx/post/aa/exposureMultiplier", range_from=0.00001, range_to=10.0, ) # if auto_exposure_idx == 2 self.exposure = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Fixed Exposure Value", "/rtx/post/aa/exposure", range_from=0.00001, range_to=1.0 ) @property def settings(self): settings = { "/rtx/post/aa/op": self.algorithm, } antialiasing_op_idx = self._carb_settings.get("/rtx/post/aa/op") if antialiasing_op_idx == 1: # TAA settings.update( { "/rtx/post/scaling/staticRatio": self.static_ratio, "/rtx/post/taa/samples": self.samples, "/rtx/post/taa/alpha": self.alpha, } ) elif antialiasing_op_idx == 2: # FXAA settings.update( { "/rtx/post/fxaa/qualitySubPix": self.quality_sub_pix, "/rtx/post/fxaa/qualityEdgeThreshold": self.quality_edge_threshold, "/rtx/post/fxaa/qualityEdgeThresholdMin": self.quality_edge_threshold_min, } ) elif antialiasing_op_idx == 3 or antialiasing_op_idx == 4: # DLSS and RTXAA if antialiasing_op_idx == 3: settings.update( {"/rtx/post/dlss/execMode": self.exec_mode,} ) settings.update( {"/rtx/post/aa/sharpness": self.sharpness, "/rtx/post/aa/autoExposureMode": self.auto_exposure_mode,} ) auto_exposure_idx = self._carb_settings.get("/rtx/post/aa/autoExposureMode") if auto_exposure_idx == 1: settings.update( {"/rtx/post/aa/exposureMultiplier": self.exposure_multiplier,} ) elif auto_exposure_idx == 2: settings.update( {"/rtx/post/aa/exposure": self.exposure,} ) return settings class DirectLightingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.shadows_enabled = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Shadows", "/rtx/shadows/enabled") self.sampled_lighting_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Sampled Direct Lighting", "/rtx/directLighting/sampledLighting/enabled" ) self.sampled_lighting_auto_enable = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Auto-enable Sampled Lighting Above Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnable", ) self.sampled_lighting_auto_enable_light_count_threshold = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Auto-enable Sampled Lighting: Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold", ) # if not self._settings.get("/rtx/directLighting/sampledLighting/enabled" self.shadows_sample_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Shadow Samples per Pixel", "/rtx/shadows/sampleCount", range_from=1, range_to=16 ) self.shadows_denoiser_quarter_res = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Lower Resolution Shadows Denoiser", "/rtx/shadows/denoiser/quarterRes" ) self.dome_light_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Dome Lighting", "/rtx/directLighting/domeLight/enabled" ) self.dome_light_sample_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Dome Light Samples per Pixel", "/rtx/directLighting/domeLight/sampleCount", range_from=0, range_to=32, ) self.dome_light_enabled_in_reflections = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Dome Lighting in Reflections", "/rtx/directLighting/domeLight/enabledInReflections" ) # if self._settings.get("/rtx/directLighting/sampledLighting/enabled") sampled_lighting_spp_items = {"1": 1, "2": 2, "4": 4, "8": 8} self.samples_per_pixel = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Samples per Pixel", "/rtx/directLighting/sampledLighting/samplesPerPixel", range_dict=sampled_lighting_spp_items, ) self.clamp_samples_per_pixel_to_number_of_lights = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Clamp Sample Count to Light Count", "/rtx/directLighting/sampledLighting/clampSamplesPerPixelToNumberOfLights", ) self.reflections_samples_per_pixel = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Reflections: Light Samples per Pixel", "/rtx/reflections/sampledLighting/samplesPerPixel", range_dict=sampled_lighting_spp_items, ) self.reflections_clamp_samples_per_pixel_to_number_of_lights = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Reflections: Clamp Sample Count to Light Count", "/rtx/reflections/sampledLighting/clampSamplesPerPixelToNumberOfLights", ) self.max_ray_intensity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max Ray Intensity", "/rtx/directLighting/sampledLighting/maxRayIntensity", range_from=0.0, range_to=1000000, ) self.reflections_max_ray_intensity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Reflections: Max Ray Intensity", "/rtx/reflections/sampledLighting/maxRayIntensity", range_from=0.0, range_to=1000000, ) self.enabled_in_reflections = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Dome Lighting in Reflections", "/rtx/directLighting/domeLight/enabledInReflections" ) firefly_filter_types = {"None": "None", "Median": "Cross-Bilateral Median", "RCRS": "Cross-Bilateral RCRS"} self.firefly_suppression_type = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Firefly Filter", "/rtx/lightspeed/ReLAX/fireflySuppressionType", range_dict=firefly_filter_types, ) self.history_clamping_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "History Clamping", "/rtx/lightspeed/ReLAX/historyClampingEnabled" ) self.denoiser_iterations = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Denoiser Iterations", "/rtx/lightspeed/ReLAX/aTrousIterations", range_from=1, range_to=10, ) self.diffuse_backscattering_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Extended Diffuse Backscattering", "/rtx/directLighting/diffuseBackscattering/enabled", ) self.shadow_offset = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Shadow Ray Offset", "/rtx/directLighting/diffuseBackscattering/shadowOffset", range_from=0.1, range_to=1000, ) self.extinction = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Extinction", "/rtx/directLighting/diffuseBackscattering/extinction", range_from=0.001, range_to=100, ) @property def settings(self): settings = { "/rtx/shadows/enabled": self.shadows_enabled, "/rtx/directLighting/sampledLighting/enabled": self.sampled_lighting_enabled, "/rtx/directLighting/sampledLighting/autoEnable": self.sampled_lighting_auto_enable, "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold": self.sampled_lighting_auto_enable_light_count_threshold, } if not self._carb_settings.get("/rtx/directLighting/sampledLighting/enabled"): settings.update( { "/rtx/shadows/sampleCount": self.shadows_sample_count, "/rtx/shadows/denoiser/quarterRes": self.shadows_denoiser_quarter_res, "/rtx/directLighting/domeLight/enabled": self.dome_light_enabled, "/rtx/directLighting/domeLight/sampleCount": self.dome_light_sample_count, "/rtx/directLighting/domeLight/enabledInReflections": self.dome_light_enabled_in_reflections, } ) else: settings.update( { "/rtx/directLighting/sampledLighting/samplesPerPixel": self.samples_per_pixel, "/rtx/directLighting/sampledLighting/clampSamplesPerPixelToNumberOfLights": self.clamp_samples_per_pixel_to_number_of_lights, "/rtx/reflections/sampledLighting/samplesPerPixel": self.reflections_samples_per_pixel, "/rtx/reflections/sampledLighting/clampSamplesPerPixelToNumberOfLights": self.reflections_clamp_samples_per_pixel_to_number_of_lights, "/rtx/directLighting/sampledLighting/maxRayIntensity": self.max_ray_intensity, "/rtx/reflections/sampledLighting/maxRayIntensity": self.reflections_max_ray_intensity, "/rtx/directLighting/domeLight/enabledInReflections": self.enabled_in_reflections, "/rtx/lightspeed/ReLAX/fireflySuppressionType": self.firefly_suppression_type, "/rtx/lightspeed/ReLAX/historyClampingEnabled": self.history_clamping_enabled, "/rtx/lightspeed/ReLAX/aTrousIterations": self.denoiser_iterations, "/rtx/directLighting/diffuseBackscattering/enabled": self.diffuse_backscattering_enabled, "/rtx/directLighting/diffuseBackscattering/shadowOffset": self.shadow_offset, "/rtx/directLighting/diffuseBackscattering/extinction": self.extinction, } ) return settings @property def enabled_setting_path(self): return "/rtx/directLighting/enabled" class ReflectionsSettings(SettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.max_roughness = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max Roughness", "/rtx/reflections/maxRoughness", range_from=0.0, range_to=1.0 ) self.max_reflection_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Reflection Bounces", "/rtx/reflections/maxReflectionBounces", range_from=0, range_to=100, ) @property def settings(self): return { "/rtx/reflections/maxRoughness": self.max_roughness, "/rtx/reflections/maxReflectionBounces": self.max_reflection_bounces, } @property def enabled_setting_path(self): return "/rtx/reflections/enabled" class TranslucencySettings(SettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.max_refraction_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Refraction Bounces", "/rtx/translucency/maxRefractionBounces", range_from=0, range_to=100, ) self.reflection_cutoff = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Secondary Bounce Roughness Cutoff", "/rtx/translucency/reflectionCutoff", range_from=0.0, range_to=1.0, ) self.fractional_cutou_opacity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Fractional Cutout Opacity", "/rtx/raytracing/fractionalCutoutOpacity" ) self.virtual_depth = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Depth Correction for DoF", "/rtx/translucency/virtualDepth" ) @property def settings(self): return { "/rtx/translucency/maxRefractionBounces": self.max_refraction_bounces, "/rtx/translucency/reflectionCutoff": self.reflection_cutoff, "/rtx/raytracing/fractionalCutoutOpacity": self.reflection_cutoff, "/rtx/translucency/virtualDepth": self.virtual_depth, } @property def enabled_setting_path(self): return "/rtx/translucency/enabled" class GlobalVolumetricEffectsSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.max_accumulation_frames = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Accumulation Frames", "/rtx/raytracing/inscattering/maxAccumulationFrames", range_from=1, range_to=255, ) self.depth_slices = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "# Depth Slices", "/rtx/raytracing/inscattering/depthSlices", range_from=16, range_to=1024, ) self.pixel_ratio = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Pixel Density", "/rtx/raytracing/inscattering/pixelRatio", range_from=4, range_to=64 ) self.max_distance = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max inscattering Distance", "/rtx/raytracing/inscattering/maxDistance", range_from=10, range_to=100000, ) self.atmosphere_height = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Atmosphere Height", "/rtx/raytracing/inscattering/atmosphereHeight", range_from=-100000, range_to=100000, ) self.transmittance_color = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Transmittance Color", "/rtx/raytracing/inscattering/transmittanceColor" ) self.transmittance_measurement_distance = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Transmittance Measurment Distance", "/rtx/raytracing/inscattering/transmittanceMeasurementDistance", range_from=0.0001, range_to=1000000, ) self.single_scattering_albedo = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Single Scattering Albedo", "/rtx/raytracing/inscattering/singleScatteringAlbedo", ) self.anisotropy_factor = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Anisotropy Factor", "/rtx/raytracing/inscattering/anisotropyFactor", range_from=-0.999, range_to=0.999, ) self.slice_distribution_exponent = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Slice Distribution Exponent", "/rtx/raytracing/inscattering/sliceDistributionExponent", range_from=1, range_to=16, ) self.blur_sigma = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Inscatter Blur Sigma", "/rtx/raytracing/inscattering/blurSigma", 0.0, range_to=10.0, ) self.dithering_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Inscatter Dithering Scale", "/rtx/raytracing/inscattering/ditheringScale", range_from=0, range_to=100, ) self.spatial_jitter_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Spatial Sample Jittering Scale", "/rtx/raytracing/inscattering/spatialJitterScale", range_from=0.0, range_to=1, ) self.temporal_jitter_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Temporal Reprojection Jittering Scale", "/rtx/raytracing/inscattering/temporalJitterScale", range_from=0.0, range_to=1, ) self.use_detail_noise = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Apply Density Noise", "/rtx/raytracing/inscattering/useDetailNoise" ) self.detail_noise_scale = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density Noise World Scale", "/rtx/raytracing/inscattering/detailNoiseScale", range_from=0.0, range_to=1, ) self.noise_animation_speed_x = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density Noise Animation Speed X", "/rtx/raytracing/inscattering/noiseAnimationSpeedX", range_from=-1.0, range_to=1.0, ) self.noise_animation_speed_y = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density Noise Animation Speed Y", "/rtx/raytracing/inscattering/noiseAnimationSpeedY", range_from=-1.0, range_to=1.0, ) self.noise_animation_speed_z = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density Noise Animation Speed Z", "/rtx/raytracing/inscattering/noiseAnimationSpeedZ", range_from=-1.0, range_to=1.0, ) self.noise_scale_range_min = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density Noise Scale Min", "/rtx/raytracing/inscattering/noiseScaleRangeMin", range_from=-1.0, range_to=5.0, ) self.noise_scale_range_max = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density Noise Scale Max", "/rtx/raytracing/inscattering/noiseScaleRangeMax", range_from=-1.0, range_to=5.0, ) self.noise_num_octaves = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Density Noise Octave Count", "/rtx/raytracing/inscattering/noiseNumOctaves", range_from=1, range_to=8, ) self.use_32bit_precision = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Use 32-bit Precision", "/rtx/raytracing/inscattering/use32bitPrecision" ) @property def settings(self): return { "/rtx/raytracing/inscattering/maxAccumulationFrames": self.max_accumulation_frames, "/rtx/raytracing/inscattering/depthSlices": self.depth_slices, "/rtx/raytracing/inscattering/pixelRatio": self.pixel_ratio, "/rtx/raytracing/inscattering/maxDistance": self.max_distance, "/rtx/raytracing/inscattering/atmosphereHeight": self.atmosphere_height, "/rtx/raytracing/inscattering/transmittanceColor": self.transmittance_color, "/rtx/raytracing/inscattering/transmittanceMeasurementDistance": self.transmittance_measurement_distance, "/rtx/raytracing/inscattering/singleScatteringAlbedo": self.single_scattering_albedo, "/rtx/raytracing/inscattering/anisotropyFactor": self.anisotropy_factor, "/rtx/raytracing/inscattering/sliceDistributionExponent": self.slice_distribution_exponent, "/rtx/raytracing/inscattering/blurSigma": self.blur_sigma, "/rtx/raytracing/inscattering/ditheringScale": self.dithering_scale, "/rtx/raytracing/inscattering/spatialJitterScale": self.spatial_jitter_scale, "/rtx/raytracing/inscattering/temporalJitterScale": self.temporal_jitter_scale, "/rtx/raytracing/inscattering/useDetailNoise": self.use_detail_noise, "/rtx/raytracing/inscattering/detailNoiseScale": self.detail_noise_scale, "/rtx/raytracing/inscattering/noiseAnimationSpeedX": self.noise_animation_speed_x, "/rtx/raytracing/inscattering/noiseAnimationSpeedY": self.noise_animation_speed_y, "/rtx/raytracing/inscattering/noiseAnimationSpeedZ": self.noise_animation_speed_z, "/rtx/raytracing/inscattering/noiseScaleRangeMin": self.noise_scale_range_min, "/rtx/raytracing/inscattering/noiseScaleRangeMax": self.noise_scale_range_max, "/rtx/raytracing/inscattering/noiseNumOctaves": self.noise_num_octaves, "/rtx/raytracing/inscattering/use32bitPrecision": self.use_32bit_precision, } @property def enabled_setting_path(self): return "/rtx/raytracing/globalVolumetricEffects/enabled" class CausticsSettings(SettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.photon_count_nultiplier = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Photon Count Multiplier", "/rtx/raytracing/caustics/photonCountMultiplier", range_from=1, range_to=5000, ) self.photon_max_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Photon Max Bounces", "/rtx/raytracing/caustics/photonMaxBounces", range_from=1, range_to=20, ) self.positio_phi = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Position Phi", "/rtx/raytracing/caustics/positionPhi", range_from=0.1, range_to=50 ) self.normal_phi = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Normal Phi", "/rtx/raytracing/caustics/normalPhi", range_from=0.3, range_to=1 ) self.filtering_iterations = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Filter Iterations", "/rtx/raytracing/caustics/eawFilteringSteps", range_from=0, range_to=10, ) @property def settings(self): return { "/rtx/raytracing/caustics/photonCountMultiplier": self.photon_count_nultiplier, "/rtx/raytracing/caustics/photonMaxBounces": self.photon_max_bounces, "/rtx/raytracing/caustics/positionPhi": self.positio_phi, "/rtx/raytracing/caustics/normalPhi": self.normal_phi, "/rtx/raytracing/caustics/eawFilteringSteps": self.filtering_iterations, } @property def enabled_setting_path(self): return "/rtx/caustics/enabled" class IndirectDiffuseLightingSettings(SettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.ambient_light_color = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Ambient Light Color", "/rtx/sceneDb/ambientLightColor" ) self.ambient_light_intensity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Ambient Light Intensity", "/rtx/sceneDb/ambientLightIntensity", range_from=0.0, range_to=10.0, ) self.ambient_occlusion_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Ambient Occlusion (AO)", "/rtx/ambientOcclusion/enabled" ) # if self._carb_settings.get("/rtx/ambientOcclusion/enabled") self.ray_length_in_cm = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "AO: Ray Length (cm)", "/rtx/ambientOcclusion/rayLengthInCm", range_from=0.0, range_to=2000.0, ) self.min_samples = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "AO: Minimum Samples per Pixel", "/rtx/ambientOcclusion/minSamples", range_from=1, range_to=16, ) self.max_samples = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "AO: Maximum Samples per Pixel", "/rtx/ambientOcclusion/maxSamples", range_from=1, range_to=16, ) self.aggressive_denoising = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "AO: Aggressive denoising", "/rtx/ambientOcclusion/aggressiveDenoising" ) self.indirect_diffuse_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Indirect Diffuse GI", "/rtx/indirectDiffuse/enabled" ) # if self._carb_settings.get("/rtx/indirectDiffuse/enabled") gi_denoising_techniques_ops = ["NVRTD", "NRD:Reblur"] self.fetch_sample_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Samples per Pixel", "/rtx/indirectDiffuse/fetchSampleCount", range_from=0, range_to=4, ) self.max_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Bounces", "/rtx/indirectDiffuse/maxBounces", range_from=0, range_to=16 ) self.scaling_factor = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Intensity", "/rtx/indirectDiffuse/scalingFactor", range_from=0.0, range_to=20.0 ) self.denoiser_method = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Denoising technique", "/rtx/indirectDiffuse/denoiser/method", range_list=gi_denoising_techniques_ops, ) # if enabled and self._carb_settings.get("/rtx/indirectDiffuse/denoiser/method") == 0: self.kernel_radius = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Kernel radius", "/rtx/indirectDiffuse/denoiser/kernelRadius", range_from=1, range_to=64, ) self.iterations = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Iteration count", "/rtx/indirectDiffuse/denoiser/iterations", range_from=1, range_to=10, ) self.max_history = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max History Length", "/rtx/indirectDiffuse/denoiser/temporal/maxHistory", range_from=1, range_to=100, ) # if enabled and self._carb_settings.get("/rtx/indirectDiffuse/denoiser/method") == 1: self.max_accumulated_frame_num = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Frames in History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxAccumulatedFrameNum", range_from=0, range_to=63, ) self.max_fast_accumulated_frame_num = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Frames in Fast History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxFastAccumulatedFrameNum", range_from=0, range_to=63, ) self.plane_distance_sensitivity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Plane Distance Sensitivity", "/rtx/lightspeed/NRD_ReblurDiffuse/planeDistanceSensitivity", range_from=0, range_to=1, ) self.blur_radius = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Blur Radius", "/rtx/lightspeed/NRD_ReblurDiffuse/blurRadius", range_from=0, range_to=100, ) @property def settings(self): settings = { "/rtx/sceneDb/ambientLightColor": self.ambient_light_color, "/rtx/sceneDb/ambientLightIntensity": self.ambient_light_intensity, "/rtx/ambientOcclusion/enabled": self.ambient_occlusion_enabled, "/rtx/indirectDiffuse/enabled": self.indirect_diffuse_enabled, } if self._carb_settings.get("/rtx/ambientOcclusion/enabled"): settings.update( { "/rtx/ambientOcclusion/rayLengthInCm": self.ray_length_in_cm, "/rtx/ambientOcclusion/minSamples": self.min_samples, "/rtx/ambientOcclusion/maxSamples": self.max_samples, "/rtx/ambientOcclusion/aggressiveDenoising": self.aggressive_denoising, } ) if self._carb_settings.get("/rtx/indirectDiffuse/enabled"): settings.update( { "/rtx/indirectDiffuse/fetchSampleCount": self.max_bounces, "/rtx/indirectDiffuse/maxBounces": self.ambient_light_color, "/rtx/indirectDiffuse/scalingFactor": self.scaling_factor, "/rtx/indirectDiffuse/denoiser/method": self.denoiser_method, } ) if self._carb_settings.get("/rtx/indirectDiffuse/denoiser/method") == 0: settings.update( { "/rtx/indirectDiffuse/denoiser/kernelRadius": self.kernel_radius, "/rtx/indirectDiffuse/denoiser/iterations": self.iterations, "/rtx/indirectDiffuse/denoiser/temporal/maxHistory": self.max_history, } ) elif self._carb_settings.get("/rtx/indirectDiffuse/denoiser/method") == 1: settings.update( { "/rtx/lightspeed/NRD_ReblurDiffuse/maxAccumulatedFrameNum": self.max_accumulated_frame_num, "/rtx/lightspeed/NRD_ReblurDiffuse/maxFastAccumulatedFrameNum": self.max_fast_accumulated_frame_num, "/rtx/lightspeed/NRD_ReblurDiffuse/planeDistanceSensitivity": self.plane_distance_sensitivity, "/rtx/lightspeed/NRD_ReblurDiffuse/blurRadius": self.blur_radius, } ) return settings class RTMultiGPUSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() currentGpuCount = self._carb_settings.get("/renderer/multiGpu/currentGpuCount") self.tile_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Tile Count", "/rtx/realtime/mgpu/tileCount", range_from=2, range_to=currentGpuCount ) self.master_post_processOnly = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "GPU 0 Post Process Only", "/rtx/realtime/mgpu/masterPostProcessOnly" ) self.tile_overlap = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Tile Overlap (Pixels)", "/rtx/realtime/mgpu/tileOverlap", range_from=0, range_to=256 ) self.tile_overlap_blend_fraction = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Fraction of Overlap Pixels to Blend", "/rtx/realtime/mgpu/tileOverlapBlendFraction", range_from=0.0, range_to=1.0, ) @property def settings(self): return { "/rtx/realtime/mgpu/tileCount": self.tile_count, "/rtx/realtime/mgpu/masterPostProcessOnly": self.master_post_processOnly, "/rtx/realtime/mgpu/tileOverlap": self.tile_overlap, "/rtx/realtime/mgpu/tileOverlapBlendFraction": self.tile_overlap_blend_fraction, } @property def enabled_setting_path(self): return "/rtx/realtime/mgpu/enabled"
39,074
Python
42.320399
154
0.609203
StanfordVL/OmniGibson/omnigibson/renderer_settings/__init__.py
from omnigibson.renderer_settings.renderer_settings import RendererSettings
76
Python
37.499981
75
0.894737
StanfordVL/OmniGibson/omnigibson/renderer_settings/path_tracing_settings.py
import omnigibson.lazy as lazy from omnigibson.renderer_settings.settings_base import SettingItem, SettingsBase, SubSettingsBase class PathTracingSettings(SettingsBase): """ Path-Tracing setting group that handles a variety of sub-settings, including: - Anti-Aliasing - Firefly Filter - Path-Tracing - Sampling & Caching - Denoising - Path-Traced Fog - Heterogeneous Volumes (Path Traced Volume) - Multi GPU (if multiple GPUs available) """ def __init__(self): self.anti_aliasing_settings = AntiAliasingSettings() self.firefly_filter_settings = FireflyFilterSettings() self.path_tracing_settings = PathTracingSettings() self.sampling_and_caching_settings = SamplingAndCachingSettings() self.denoising_settings = DenoisingSettings() self.path_traced_fog_settings = PathTracedFogSettings() self.path_traced_volume_settings = PathTracedVolumeSettings() if lazy.carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") > 1: self.multi_gpu_settings = MultiGPUSettings() @property def settings(self): settings = {} settings.update(self.anti_aliasing_settings.settings) settings.update(self.firefly_filter_settings.settings) settings.update(self.path_tracing_settings.settings) settings.update(self.sampling_and_caching_settings.settings) settings.update(self.denoising_settings.settings) settings.update(self.path_traced_fog_settings.settings) settings.update(self.path_traced_volume_settings.settings) if lazy.carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") > 1: settings.update(self.multi_gpu_settings.settings) return settings class AntiAliasingSettings(SubSettingsBase): def __init__(self): pt_aa_ops = ["Box", "Triangle", "Gaussian", "Uniform"] self.sample_pattern = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Anti-Aliasing Sample Pattern", "/rtx/pathtracing/aa/op", pt_aa_ops ) self.filter_radius = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Anti-Aliasing Radius", "/rtx/pathtracing/aa/filterRadius", range_from=0.0001, range_to=5.0, ) @property def settings(self): return { "/rtx/pathtracing/aa/op": self.sample_pattern, "/rtx/pathtracing/aa/filterRadius": self.filter_radius, } class FireflyFilterSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.max_intensity_per_sample = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max Ray Intensity Glossy", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSample", range_from=0, range_to=100000, ) self.max_intensityper_sample_diffuse = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max Ray Intensity Diffuse", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSampleDiffuse", range_from=0, range_to=100000, ) @property def settings(self): return { "/rtx/pathtracing/fireflyFilter/maxIntensityPerSample": self.max_intensity_per_sample, "/rtx/pathtracing/fireflyFilter/maxIntensityPerSampleDiffuse": self.max_intensityper_sample_diffuse, } @property def enabled_setting_path(self): return "/rtx/pathtracing/fireflyFilter/enabled" class PathTracingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.pathtracing_max_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Bounces", "/rtx/pathtracing/maxBounces", range_from=0, range_to=64 ) self.max_specular_and_transmission_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Specular and Transmission Bounces", "/rtx/pathtracing/maxSpecularAndTransmissionBounces", range_from=1, range_to=128, ) self.maxvolume_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max SSS Volume Scattering Bounces", "/rtx/pathtracing/maxVolumeBounces", range_from=0, range_to=1024, ) self.ptfog_max_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Fog Scattering Bounces", "/rtx/pathtracing/ptfog/maxBounces", range_from=1, range_to=10, ) self.ptvol_max_bounces = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Heterogeneous Volume Scattering Bounces", "/rtx/pathtracing/ptvol/maxBounces", range_from=0, range_to=1024, ) clamp_spp = self._carb_settings.get("/rtx/pathtracing/clampSpp") if clamp_spp > 1: # better 0, but setting range = (1,1) completely disables the UI control range self.spp = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Samples per Pixel per Frame (1 to {})".format(clamp_spp), "/rtx/pathtracing/spp", range_from=1, range_to=clamp_spp, ) else: self.spp = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Samples per Pixel per Frame", "/rtx/pathtracing/spp", range_from=1, range_to=1048576, ) self.total_spp = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Total Samples per Pixel (0 = inf)", "/rtx/pathtracing/totalSpp", range_from=0, range_to=1048576, ) self.fractional_cutout_opacity = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Fractional Cutout Opacity", "/rtx/pathtracing/fractionalCutoutOpacity" ) self.reset_pt_accum_on_anim_time_change = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Reset Accumulation on Time Change", "/rtx/resetPtAccumOnAnimTimeChange" ) @property def settings(self): return { "/rtx/pathtracing/maxBounces": self.pathtracing_max_bounces, "/rtx/pathtracing/maxSpecularAndTransmissionBounces": self.max_specular_and_transmission_bounces, "/rtx/pathtracing/maxVolumeBounces": self.maxvolume_bounces, "/rtx/pathtracing/ptfog/maxBounces": self.ptfog_max_bounces, "/rtx/pathtracing/ptvol/maxBounces": self.ptvol_max_bounces, "/rtx/pathtracing/spp": self.spp, "/rtx/pathtracing/totalSpp": self.total_spp, "/rtx/pathtracing/fractionalCutoutOpacity": self.fractional_cutout_opacity, "/rtx/resetPtAccumOnAnimTimeChange": self.reset_pt_accum_on_anim_time_change, } class SamplingAndCachingSettings(SubSettingsBase): def __init__(self): self.cached_enabled = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Caching", "/rtx/pathtracing/cached/enabled") self.lightcache_cached_enabled = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Enable Many-Light Sampling", "/rtx/pathtracing/lightcache/cached/enabled" ) @property def settings(self): return { "/rtx/pathtracing/cached/enabled": self.cached_enabled, "/rtx/pathtracing/lightcache/cached/enabled": self.lightcache_cached_enabled, } class DenoisingSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.blend_factor = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "OptiX Denoiser Blend Factor", "/rtx/pathtracing/optixDenoiser/blendFactor", range_from=0, range_to=1, ) @property def settings(self): return { "/rtx/pathtracing/optixDenoiser/blendFactor": self.blend_factor, } @property def enabled_setting_path(self): return "/rtx/pathtracing/optixDenoiser/enabled" class PathTracedFogSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.density = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Density", "/rtx/pathtracing/ptfog/density", range_from=0, range_to=1 ) self.height = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Height", "/rtx/pathtracing/ptfog/height", range_from=-10, range_to=1000 ) self.falloff = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Falloff", "/rtx/pathtracing/ptfog/falloff", range_from=0, range_to=100 ) self.color = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.COLOR3, "Color", "/rtx/pathtracing/ptfog/color", range_from=0, range_to=1 ) self.asymmetry = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Asymmetry (g)", "/rtx/pathtracing/ptfog/asymmetry", range_from=-0.99, range_to=0.99, ) self.z_up = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Use +Z Axis for Height", "/rtx/pathtracing/ptfog/ZUp") @property def settings(self): return { "/rtx/pathtracing/ptfog/density": self.density, "/rtx/pathtracing/ptfog/height": self.height, "/rtx/pathtracing/ptfog/falloff": self.falloff, "/rtx/pathtracing/ptfog/color": self.color, "/rtx/pathtracing/ptfog/asymmetry": self.asymmetry, "/rtx/pathtracing/ptfog/ZUp": self.z_up, } @property def enabled_setting_path(self): return "/rtx/pathtracing/ptfog/enabled" class PathTracedVolumeSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() pt_vol_tr_ops = ["Biased Ray Marching", "Ratio Tracking", "Brute-force Ray Marching"] self.transmittance_method = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.STRING, "Transmittance Method", "/rtx/pathtracing/ptvol/transmittanceMethod", range_list=pt_vol_tr_ops, ) self.max_collision_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Collision Count", "/rtx/pathtracing/ptvol/maxCollisionCount", range_from=0, range_to=1024, ) self.max_light_collision_count = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.INT, "Max Light Collision Count", "/rtx/pathtracing/ptvol/maxLightCollisionCount", range_from=0, range_to=1024, ) self.max_density = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "Max Density", "/rtx/pathtracing/ptvol/maxDensity", range_from=0, range_to=1000 ) self.fast_vdb = SettingItem(self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Fast VDB", "/rtx/pathtracing/ptvol/fastVdb") # if self._carb_settings.get("/rtx/pathtracing/ptvol/fastVdb") self.autoMajorant_vdb = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Fast VDB Auto majorant", "/rtx/pathtracing/ptvol/autoMajorantVdb" ) @property def settings(self): settings = { "/rtx/pathtracing/ptvol/transmittanceMethod": self.transmittance_method, "/rtx/pathtracing/ptvol/maxCollisionCount": self.max_collision_count, "/rtx/pathtracing/ptvol/maxLightCollisionCount": self.max_light_collision_count, "/rtx/pathtracing/ptvol/maxDensity": self.max_density, "/rtx/pathtracing/ptvol/fastVdb": self.fast_vdb, } if self._carb_settings.get("/rtx/pathtracing/ptvol/fastVdb"): settings.update( {"/rtx/pathtracing/ptvol/autoMajorantVdb": self.autoMajorant_vdb,} ) return settings @property def enabled_setting_path(self): return "/rtx/pathtracing/ptvol/enabled" class MultiGPUSettings(SubSettingsBase): def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.weight_gpu0 = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.FLOAT, "GPU 0 Weight", "/rtx/pathtracing/mgpu/weightGpu0", range_from=0, range_to=1 ) self.compress_radiance = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Compress Radiance", "/rtx/pathtracing/mgpu/compressRadiance" ) self.compress_albedo = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Compress Albedo", "/rtx/pathtracing/mgpu/compressAlbedo" ) self.compress_normals = SettingItem( self, lazy.omni.kit.widget.settings.SettingType.BOOL, "Compress Normals", "/rtx/pathtracing/mgpu/compressNormals" ) @property def settings(self): return { "/rtx/pathtracing/mgpu/weightGpu0": self.weight_gpu0, "/rtx/pathtracing/mgpu/compressRadiance": self.compress_radiance, "/rtx/pathtracing/mgpu/compressAlbedo": self.compress_albedo, "/rtx/pathtracing/mgpu/compressNormals": self.compress_normals, } @property def enabled_setting_path(self): return "/rtx/pathtracing/mgpu/enabled"
14,389
Python
39.083565
148
0.623601
StanfordVL/OmniGibson/omnigibson/renderer_settings/renderer_settings.py
import omnigibson.lazy as lazy from omnigibson.renderer_settings.common_settings import CommonSettings from omnigibson.renderer_settings.path_tracing_settings import PathTracingSettings from omnigibson.renderer_settings.post_processing_settings import PostProcessingSettings from omnigibson.renderer_settings.real_time_settings import RealTimeSettings def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class RendererSettings: """ Controller for all renderer settings. """ def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() self.common_settings = CommonSettings() self.path_tracing_settings = PathTracingSettings() self.post_processing_settings = PostProcessingSettings() self.real_time_settings = RealTimeSettings() def set_setting(self, path, value): """ Sets setting @path with value @value. Args: path (str): Path of the setting to set. value (any): Value to set for for setting @path. """ if path not in self.settings: raise NotImplementedError(f"Setting {path} is not supported.") self.settings[path].set(value) def reset_setting(self, path): """ Resets setting @path to default value. Args: path (str): Path of the setting to reset. """ if path not in self.settings: raise NotImplementedError(f"Setting {path} is not supported.") self.settings[path].reset() def get_setting_from_path(self, path): """ Get the value of setting @path. Args: path (str): Path of the setting to get. Returns: any: Value of the requested setting @path. """ return self._carb_settings.get(path) def get_current_renderer(self): """ Get the current renderer. Args: path (str): Path of the setting to get. Returns: str: the current renderer. """ return lazy.omni.rtx.window.settings.RendererSettingsFactory.get_current_renderer() def set_current_renderer(self, renderer): """ Set the current renderer to @renderer. Args: renderer (str): The renderer to set as current (e.g. Real-Time, Path-Traced). """ assert ( renderer in lazy.omni.rtx.window.settings.RendererSettingsFactory.get_registered_renderers() ), f"renderer must be one of {lazy.omni.rtx.window.settings.RendererSettingsFactory.get_registered_renderers()}" print(f"Set current renderer to {renderer}.") lazy.omni.rtx.window.settings.RendererSettingsFactory.set_current_renderer(renderer) @property def settings(self): """ Get all available settings. Returns: dict: A dictionary of all available settings. Keys are setting paths and values are setting item objects. """ settings = {} settings.update(self.common_settings.settings) settings.update(self.path_tracing_settings.settings) settings.update(self.post_processing_settings.settings) settings.update(self.real_time_settings.settings) return settings
3,431
Python
31.685714
120
0.632469
StanfordVL/OmniGibson/omnigibson/renderer_settings/settings_base.py
from abc import ABCMeta import numpy as np import omnigibson.lazy as lazy class SettingsBase(metaclass=ABCMeta): """ Base class for all renderer settings classes. Settings classes include Common, Real-Time (Ray-Tracing), Path-Tracing and Post Processing. """ class SubSettingsBase(metaclass=ABCMeta): """ Base class for all renderer sub-settings classes. """ def __init__(self): self._carb_settings = lazy.carb.settings.get_settings() @property def enabled_setting_path(self): """ The path of "enabled" setting for this sub-settings class. Subclass with "enabled" mode needs to overwrite this method. Returns: str or None: The path of "enabled" mode for this sub-setting class. Defaults to None, which means this sub-setting group cannot be enabled/disabled. """ return None def is_enabled(self): """ Get the enabled status for this sub-setting class. Returns: bool: Whether this sub-setting group is enabled. Returns true if this sub-setting group has no "enabled" mode. """ if not self.enabled_setting_path: return True return self._carb_settings.get(self.enabled_setting_path) def enable(self): """ Enable this sub-setting class. """ if not self.enabled_setting_path: print(f"{self.__class__.__name__} has no enabled mode.") return self._carb_settings.set_bool(self.enabled_setting_path, True) def disable(self): """ Disable this sub-setting class. """ if not self.enabled_setting_path: print(f"{self.__class__.__name__} has no enabled mode.") return self._carb_settings.set_bool(self.enabled_setting_path, False) class SettingItem: """ A wrapper of an individual setting item. Args: owner (:class:`SubSettingsBase`): The SubSettingsBase object owning this setting. setting_type (:class:`SettingType`): Setting type (e.g. float, int). name (str): Description of this setting. path (str): Path of this setting. range_from (float): The lower bound of the values for this setting. Defaults to -inf. range_to (float): The upper bound of the values for this settin. Defaults to inf. range_list (list): Possible values for this setting. Defaults to None. range_dict (dict): Possible values for this setting. Defaults to None. """ def __init__( self, owner, setting_type, name, path, range_from=-float("inf"), range_to=float("inf"), range_list=None, range_dict=None, ): self._carb_settings = lazy.carb.settings.get_settings() self.owner = owner self.setting_type = setting_type self.name = name self.path = path self.range_from = range_from self.range_to = range_to self.range_list = range_list self.range_dict = range_dict self.initial_value = self.value @property def value(self): """ Get the current setting value. Returns: any: The current setting value. """ return self._carb_settings.get(self.path) def get(self): """ Get the current setting value. Returns: any: The current setting value. """ return self.value def reset(self): """ Reset the current setting value to default. """ self.set(self.initial_value) def set(self, value): """ Set the current setting to @value. Args: value (any): Value to set for the current setting value. """ print(f"Set setting {self.path} ({self.name}) to {value}.") # carb.log_info if not self.owner.is_enabled(): print(f"Note: {self.owner.enabled_setting_path} is not enabled.") # Validate range list and range dict. if self.range_list: assert value in self.range_list, f"Setting {self.path} must be chosen from {self.range_list}." if self.range_dict: assert isinstance(self.range_dict, dict) assert ( value in self.range_dict.values() ), f"Setting {self.path} must be chosen from a value (not key) in {self.range_dict}." if self.setting_type == lazy.omni.kit.widget.settings.SettingType.FLOAT: assert isinstance(value, (int, float)), f"Setting {self.path} must be of type float." assert ( value >= self.range_from and value <= self.range_to ), f"Setting {self.path} must be within range ({self.range_from}, {self.range_to})." self._carb_settings.set_float(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.INT: assert isinstance(value, int), f"Setting {self.path} must be of type int." assert ( value >= self.range_from and value <= self.range_to ), f"Setting {self.path} must be within range ({self.range_from}, {self.range_to})." self._carb_settings.set_int(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.COLOR3: assert ( isinstance(value, (list, tuple, np.ndarray)) and len(value) == 3 ), f"Setting {self.path} must be a list of 3 numbers within range [0,1]." for v in value: assert ( isinstance(v, (int, float)) and v >= 0 and v <= 1 ), f"Setting {self.path} must be a list of 3 numbers within range [0,1]." self._carb_settings.set_float_array(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.BOOL: assert isinstance(value, bool), f"Setting {self.path} must be of type bool." self._carb_settings.set_bool(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.STRING: assert isinstance(value, str), f"Setting {self.path} must be of type str." self._carb_settings.set_string(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.DOUBLE3: assert ( isinstance(value, (list, tuple, np.ndarray)) and len(value) == 3 ), f"Setting {self.path} must be a list of 3 floats." for v in value: assert isinstance(v, (int, float)), f"Setting {self.path} must be a list of 3 floats." self._carb_settings.set_float_array(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.INT2: assert ( isinstance(value, (list, tuple, np.ndarray)) and len(value) == 2 ), f"Setting {self.path} must be a list of 2 ints." for v in value: assert isinstance(v, int), f"Setting {self.path} must be a list of 2 ints." self._carb_settings.set_int_array(self.path, value) elif self.setting_type == lazy.omni.kit.widget.settings.SettingType.DOUBLE2: assert ( isinstance(value, (list, tuple, np.ndarray)) and len(value) == 2 ), f"Setting {self.path} must be a list of 2 floats." for v in value: assert isinstance(v, (int, float)), f"Setting {self.path} must be a list of 2 floats." self._carb_settings.set_float_array(self.path, value) else: raise TypeError(f"Setting type {self.setting_type} is not supported.")
7,821
Python
36.787439
106
0.586626
StanfordVL/OmniGibson/omnigibson/scene_graphs/graph_builder.py
import itertools import os import networkx as nx import numpy as np from PIL import Image from matplotlib import pyplot as plt from omnigibson import object_states from omnigibson.macros import create_module_macros from omnigibson.sensors import VisionSensor from omnigibson.object_states.factory import get_state_name from omnigibson.object_states.object_state_base import AbsoluteObjectState, BooleanStateMixin, RelativeObjectState from omnigibson.utils import transform_utils as T def _formatted_aabb(obj): return T.pose2mat((obj.aabb_center, [0, 0, 0, 1])), obj.aabb_extent class SceneGraphBuilder(object): def __init__( self, robot_name=None, egocentric=False, full_obs=False, only_true=False, merge_parallel_edges=False, exclude_states=(object_states.Touching,) ): """ A utility that builds a scene graph with objects as nodes and relative states as edges, alongside additional metadata. Args: robot_name (str): Name of the robot whose POV the scene graph will be from. If None, we assert that there is exactly one robot in the scene and use that robot. egocentric (bool): Whether the objects should have poses in the world frame or robot frame. full_obs (bool): Whether all objects should be updated or only those in FOV of the robot. only_true (bool): Whether edges should be created only for relative states that have a value True, or for all relative states (with the appropriate value attached as an attribute). merge_parallel_edges (bool): Whether parallel edges (e.g. different states of the same pair of objects) should exist (making the graph a MultiDiGraph) or should be merged into a single edge instead. exclude_states (Iterable): Object state classes that should be ignored when building the graph. """ self._G = None self._robot = None self._robot_name = robot_name self._egocentric = egocentric self._full_obs = full_obs self._only_true = only_true self._merge_parallel_edges = merge_parallel_edges self._last_desired_frame_to_world = None self._exclude_states = set(exclude_states) def get_scene_graph(self): return self._G.copy() def _get_desired_frame(self): desired_frame_to_world = np.eye(4) world_to_desired_frame = np.eye(4) if self._egocentric: desired_frame_to_world = self._get_robot_to_world_transform() world_to_desired_frame = T.pose_inv(desired_frame_to_world) return desired_frame_to_world, world_to_desired_frame def _get_robot_to_world_transform(self): robot_to_world = self._robot.get_position_orientation() # Get rid of any rotation outside xy plane robot_to_world = T.pose2mat((robot_to_world[0], T.z_rotation_from_quat(robot_to_world[1]))) return robot_to_world def _get_boolean_unary_states(self, obj): states = {} for state_type, state_inst in obj.states.items(): if not issubclass(state_type, BooleanStateMixin) or not issubclass(state_type, AbsoluteObjectState): continue if state_type in self._exclude_states: continue value = state_inst.get_value() if self._only_true and not value: continue states[get_state_name(state_type)] = value return states def _get_boolean_binary_states(self, objs): states = [] for obj1 in objs: for obj2 in objs: if obj1 == obj2: continue for state_type, state_inst in obj1.states.items(): if not issubclass(state_type, BooleanStateMixin) or not issubclass(state_type, RelativeObjectState): continue if state_type in self._exclude_states: continue try: value = state_inst.get_value(obj2) if self._only_true and not value: continue states.append((obj1, obj2, get_state_name(state_type), {"value": value})) except: pass return states def start(self, scene): assert self._G is None, "Cannot start graph builder multiple times." if self._robot_name is None: assert len(scene.robots) == 1, "Cannot build scene graph without specifying robot name if there are multiple robots." self._robot = scene.robots[0] else: self._robot = scene.object_registry("name", self._robot_name) assert self._robot, f"Robot with name {self._robot_name} not found in scene." self._G = nx.DiGraph() if self._merge_parallel_edges else nx.MultiDiGraph() desired_frame_to_world, world_to_desired_frame = self._get_desired_frame() robot_pose = world_to_desired_frame @ self._get_robot_to_world_transform() robot_bbox_pose, robot_bbox_extent = _formatted_aabb(self._robot) robot_bbox_pose = world_to_desired_frame @ robot_bbox_pose self._G.add_node( self._robot, pose=robot_pose, bbox_pose=robot_bbox_pose, bbox_extent=robot_bbox_extent, states={} ) self._last_desired_frame_to_world = desired_frame_to_world # Let's also take the first step. self.step(scene) def step(self, scene): assert self._G is not None, "Cannot step graph builder before starting it." # Prepare the necessary transformations. desired_frame_to_world, world_to_desired_frame = self._get_desired_frame() # Update the position of everything that's already in the scene by using our relative position to last frame. old_desired_to_new_desired = world_to_desired_frame @ self._last_desired_frame_to_world nodes = list(self._G.nodes) poses = np.array([self._G.nodes[obj]["pose"] for obj in nodes]) bbox_poses = np.array([self._G.nodes[obj]["bbox_pose"] for obj in nodes]) updated_poses = old_desired_to_new_desired @ poses updated_bbox_poses = old_desired_to_new_desired @ bbox_poses for i, obj in enumerate(nodes): self._G.nodes[obj]["pose"] = updated_poses[i] self._G.nodes[obj]["bbox_pose"] = updated_bbox_poses[i] # Update the robot's pose. We don't want to accumulate errors because of the repeated transforms. self._G.nodes[self._robot]["pose"] = world_to_desired_frame @ self._get_robot_to_world_transform() robot_bbox_pose, robot_bbox_extent = _formatted_aabb(self._robot) robot_bbox_pose = world_to_desired_frame @ robot_bbox_pose self._G.nodes[self._robot]["bbox_pose"] = robot_bbox_pose self._G.nodes[self._robot]["bbox_extent"] = robot_bbox_extent # Go through the objects in FOV of the robot. objs_to_add = set(scene.objects) if not self._full_obs: # TODO: Reenable this once InFOV state is fixed. # If we're not in full observability mode, only pick the objects in FOV of robot. # bids_in_fov = self._robot.states[object_states.ObjectsInFOVOfRobot].get_value() # objs_in_fov = set( # scene.objects_by_id[bid] # for bid in bids_in_fov # if bid in scene.objects_by_id # ) # objs_to_add &= objs_in_fov raise NotImplementedError("Partial observability not supported in scene graph builder yet.") for obj in objs_to_add: # Add the object if not already in the graph if obj not in self._G.nodes: self._G.add_node(obj) # Get the relative position of the object & update it (reducing accumulated errors) self._G.nodes[obj]["pose"] = world_to_desired_frame @ T.pose2mat(obj.get_position_orientation()) # Get the bounding box. if hasattr(obj, "get_base_aligned_bbox"): bbox_center, bbox_orn, bbox_extent, _ = obj.get_base_aligned_bbox(visual=True) bbox_pose = T.pose2mat((bbox_center, bbox_orn)) else: bbox_pose, bbox_extent = _formatted_aabb(obj) self._G.nodes[obj]["bbox_pose"] = world_to_desired_frame @ bbox_pose self._G.nodes[obj]["bbox_extent"] = bbox_extent # Update the states of the object self._G.nodes[obj]["states"] = self._get_boolean_unary_states(obj) # Update the binary states for seen objects. self._G.remove_edges_from(list(itertools.product(objs_to_add, objs_to_add))) edges = self._get_boolean_binary_states(objs_to_add) if self._merge_parallel_edges: new_edges = {} for edge in edges: edge_pair = (edge[0], edge[1]) if edge_pair not in new_edges: new_edges[edge_pair] = [] new_edges[edge_pair].append((edge[2], edge[3]["value"])) edges = [(k[0], k[1], {"states": v}) for k, v in new_edges.items()] self._G.add_edges_from(edges) # Save the robot's transform in this frame. self._last_desired_frame_to_world = desired_frame_to_world def visualize_scene_graph(scene, G, show_window=True, realistic_positioning=False): """ Converts the graph into an image and shows it in a cv2 window if preferred. Args: show_window (bool): Whether a cv2 GUI window containing the visualization should be shown. realistic_positioning (bool): Whether nodes should be positioned based on their position in the scene (if True) or placed using a graphviz layout (neato) that makes it easier to read edges & find clusters. """ def _draw_graph(): nodes = list(G.nodes) node_labels = {obj: obj.category for obj in nodes} colors = [ "yellow" if obj.category == "agent" else ("green" if obj.states[object_states.InFOVOfRobot].get_value() else "red") for obj in nodes ] positions = ( {obj: (-pose[0][1], pose[0][0]) for obj, pose in G.nodes.data("pose")} if realistic_positioning else nx.nx_pydot.pydot_layout(G, prog="neato") ) nx.drawing.draw_networkx( G, pos=positions, labels=node_labels, nodelist=nodes, node_color=colors, font_size=4, arrowsize=5, node_size=150, ) edge_labels = { edge: ", ".join( state + "=" + str(value) for state, value in G.edges[edge]["states"] ) for edge in G.edges } nx.drawing.draw_networkx_edge_labels(G, pos=positions, edge_labels=edge_labels, font_size=4) # Prepare pyplot figure that's sized to match the robot video. robot = scene.robots[0] robot_camera_sensor, = [s for s in robot.sensors.values() if isinstance(s, VisionSensor) and "rgb" in s.modalities] robot_view = (robot_camera_sensor.get_obs()[0]["rgb"][..., :3]).astype(np.uint8) imgheight, imgwidth, _ = robot_view.shape figheight = 4.8 figdpi = imgheight / figheight figwidth = imgwidth / figdpi # Draw the graph onto the figure. fig = plt.figure(figsize=(figwidth, figheight), dpi=figdpi) _draw_graph() fig.canvas.draw() # Convert the canvas to image graph_view = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="") graph_view = graph_view.reshape(fig.canvas.get_width_height()[::-1] + (3,)) assert graph_view.shape == robot_view.shape plt.close(fig) # Combine the two images side-by-side img = np.hstack((robot_view, graph_view)) # # Convert to BGR for cv2-based viewing. if show_window: import cv2 cv_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) cv2.imshow("SceneGraph", cv_img) cv2.waitKey(1) return Image.fromarray(img).save(r"D:\test.png")
12,289
Python
40.52027
129
0.604768
StanfordVL/OmniGibson/omnigibson/robots/franka_allegro.py
import os import numpy as np import omnigibson.utils.transform_utils as T from omnigibson.macros import gm from omnigibson.robots.manipulation_robot import ManipulationRobot, GraspingPoint class FrankaAllegro(ManipulationRobot): """ Franka Robot with Allegro hand """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=True, load_config=None, fixed_base=True, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at teh render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. If "sticky", will magnetize any object touching the gripper's fingers. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Run super init super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, grasping_mode=grasping_mode, grasping_direction="upper", **kwargs, ) @property def model_name(self): return "FrankaAllegro" @property def discrete_action_list(self): # Not supported for this robot raise NotImplementedError() def _create_discrete_action_space(self): # Fetch does not support discrete actions raise ValueError("Franka does not support discrete actions!") @property def controller_order(self): return ["arm_{}".format(self.default_arm), "gripper_{}".format(self.default_arm)] @property def _default_controllers(self): controllers = super()._default_controllers controllers["arm_{}".format(self.default_arm)] = "InverseKinematicsController" controllers["gripper_{}".format(self.default_arm)] = "MultiFingerGripperController" return controllers @property def _default_gripper_multi_finger_controller_configs(self): conf = super()._default_gripper_multi_finger_controller_configs conf[self.default_arm]["mode"] = "independent" conf[self.default_arm]["command_input_limits"] = None return conf @property def _default_joint_pos(self): # position where the hand is parallel to the ground return np.r_[[0.86, -0.27, -0.68, -1.52, -0.18, 1.29, 1.72], np.zeros(16)] @property def finger_lengths(self): return {self.default_arm: 0.1} @property def arm_control_idx(self): return {self.default_arm: np.arange(7)} @property def gripper_control_idx(self): # thumb.proximal, ..., thumb.tip, ..., ring.tip return {self.default_arm: np.array([8, 12, 16, 20, 10, 14, 18, 22, 9, 13, 17, 21, 7, 11, 15, 19])} @property def arm_link_names(self): return {self.default_arm: [f"panda_link{i}" for i in range(8)]} @property def arm_joint_names(self): return {self.default_arm: [f"panda_joint_{i+1}" for i in range(7)]} @property def eef_link_names(self): return {self.default_arm: "base_link"} @property def finger_link_names(self): return {self.default_arm: [f"link_{i}_0" for i in range(16)]} @property def finger_joint_names(self): # thumb.proximal, ..., thumb.tip, ..., ring.tip return {self.default_arm: [f"joint_{i}_0" for i in [12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3]]} @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/franka/franka_allegro.usd") @property def robot_arm_descriptor_yamls(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/franka/franka_allegro_description.yaml")} @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/franka/franka_allegro.urdf") @property def disabled_collision_pairs(self): return [ ["link_12_0", "part_studio_link"], ] @property def assisted_grasp_start_points(self): return {self.default_arm: [ GraspingPoint(link_name=f"base_link", position=[0.015, 0, -0.03]), GraspingPoint(link_name=f"base_link", position=[0.015, 0, -0.08]), GraspingPoint(link_name=f"link_15_0_tip", position=[0, 0.015, 0.007]), ]} @property def assisted_grasp_end_points(self): return {self.default_arm: [ GraspingPoint(link_name=f"link_3_0_tip", position=[0.012, 0, 0.007]), GraspingPoint(link_name=f"link_7_0_tip", position=[0.012, 0, 0.007]), GraspingPoint(link_name=f"link_11_0_tip", position=[0.012, 0, 0.007]), ]} @property def teleop_rotation_offset(self): return {self.default_arm: T.euler2quat(np.array([0, np.pi / 2, 0]))}
9,906
Python
42.643172
126
0.628104
StanfordVL/OmniGibson/omnigibson/robots/two_wheel_robot.py
from abc import abstractmethod import gym import numpy as np from omnigibson.controllers import DifferentialDriveController from omnigibson.robots.locomotion_robot import LocomotionRobot from omnigibson.utils.python_utils import classproperty class TwoWheelRobot(LocomotionRobot): """ Robot that is is equipped with locomotive (navigational) capabilities, as defined by two wheels that can be used for differential drive (e.g.: Turtlebot). Provides common interface for a wide variety of robots. NOTE: controller_config should, at the minimum, contain: base: controller specifications for the controller to control this robot's base (locomotion). Should include: - name: Controller to create - <other kwargs> relevant to the controller being created. Note that all values will have default values specified, but setting these individual kwargs will override them """ def _validate_configuration(self): # Make sure base only has two indices (i.e.: two wheels for differential drive) assert len(self.base_control_idx) == 2, "Differential drive can only be used with robot with two base joints!" # run super super()._validate_configuration() def _create_discrete_action_space(self): # Set action list based on controller (joint or DD) used # We set straight velocity to be 50% of max velocity for the wheels max_wheel_joint_vels = self.control_limits["velocity"][1][self.base_control_idx] assert len(max_wheel_joint_vels) == 2, "TwoWheelRobot must only have two base (wheel) joints!" assert max_wheel_joint_vels[0] == max_wheel_joint_vels[1], "Both wheels must have the same max speed!" wheel_straight_vel = 0.5 * max_wheel_joint_vels[0] wheel_rotate_vel = 0.5 if self._controller_config["base"]["name"] == "JointController": action_list = [ [wheel_straight_vel, wheel_straight_vel], [-wheel_straight_vel, -wheel_straight_vel], [wheel_rotate_vel, -wheel_rotate_vel], [-wheel_rotate_vel, wheel_rotate_vel], [0, 0], ] else: # DifferentialDriveController lin_vel = wheel_straight_vel * self.wheel_radius ang_vel = wheel_rotate_vel * self.wheel_radius * 2.0 / self.wheel_axle_length action_list = [ [lin_vel, 0], [-lin_vel, 0], [0, ang_vel], [0, -ang_vel], [0, 0], ] self.action_list = action_list # Return this action space return gym.spaces.Discrete(n=len(self.action_list)) def _get_proprioception_dict(self): dic = super()._get_proprioception_dict() # Grab wheel joint velocity info joints = list(self._joints.values()) wheel_joints = [joints[idx] for idx in self.base_control_idx] l_vel, r_vel = [jnt.get_state()[1] for jnt in wheel_joints] # Compute linear and angular velocities lin_vel = (l_vel + r_vel) / 2.0 * self.wheel_radius ang_vel = (r_vel - l_vel) / self.wheel_axle_length # Add info dic["dd_base_lin_vel"] = lin_vel # lin_vel is already 1D np array of length 1 dic["dd_base_ang_vel"] = ang_vel # lin_vel is already 1D np array of length 1 return dic @property def default_proprio_obs(self): obs_keys = super().default_proprio_obs return obs_keys + ["dd_base_lin_vel", "dd_base_ang_vel"] @property def _default_controllers(self): # Always call super first controllers = super()._default_controllers # Use DifferentialDrive as default controllers["base"] = "DifferentialDriveController" return controllers @property def _default_base_differential_drive_controller_config(self): """ Returns: dict: Default differential drive controller config to control this robot's base. """ return { "name": "DifferentialDriveController", "control_freq": self._control_freq, "wheel_radius": self.wheel_radius, "wheel_axle_length": self.wheel_axle_length, "control_limits": self.control_limits, "dof_idx": self.base_control_idx, } @property def _default_controller_config(self): # Always run super method first cfg = super()._default_controller_config # Add differential drive option to base cfg["base"][ self._default_base_differential_drive_controller_config["name"] ] = self._default_base_differential_drive_controller_config return cfg @property @abstractmethod def wheel_radius(self): """ Returns: float: radius of each wheel at the base, in metric units """ raise NotImplementedError @property @abstractmethod def wheel_axle_length(self): """ Returns: float: perpendicular distance between the robot's two wheels, in metric units """ 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("TwoWheelRobot") return classes def teleop_data_to_action(self, teleop_action) -> np.ndarray: """ Generate action data from teleoperation action data NOTE: This implementation only supports DifferentialDriveController. Overwrite this function if the robot is using a different base controller. Args: teleop_action (TeleopAction): teleoperation action data Returns: np.ndarray: array of action data """ action = super().teleop_data_to_action(teleop_action) assert isinstance(self._controllers["base"], DifferentialDriveController), "Only DifferentialDriveController is supported!" action[self.base_action_idx] = np.array([teleop_action.base[0], teleop_action.base[2]]) * 0.3 return action
6,279
Python
36.60479
131
0.621118
StanfordVL/OmniGibson/omnigibson/robots/tiago.py
import os import numpy as np import omnigibson as og import omnigibson.lazy as lazy from omnigibson.macros import gm import omnigibson.utils.transform_utils as T from omnigibson.macros import create_module_macros from omnigibson.robots.active_camera_robot import ActiveCameraRobot from omnigibson.robots.manipulation_robot import GraspingPoint, ManipulationRobot from omnigibson.robots.locomotion_robot import LocomotionRobot from omnigibson.utils.python_utils import assert_valid_key from omnigibson.utils.usd_utils import JointType # Create settings for this module m = create_module_macros(module_path=__file__) DEFAULT_ARM_POSES = { "vertical", "diagonal15", "diagonal30", "diagonal45", "horizontal", } RESET_JOINT_OPTIONS = { "tuck", "untuck", } m.MAX_LINEAR_VELOCITY = 1.5 # linear velocity in meters/second m.MAX_ANGULAR_VELOCITY = np.pi # angular velocity in radians/second class Tiago(ManipulationRobot, LocomotionRobot, ActiveCameraRobot): """ Tiago Robot Reference: https://pal-robotics.com/robots/tiago/ NOTE: If using IK Control for both the right and left arms, note that the left arm dictates control of the trunk, and the right arm passively must follow. That is, sending desired delta position commands to the right end effector will be computed independently from any trunk motion occurring during that timestep. """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=False, load_config=None, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", disable_grasp_handling=False, # Unique to Tiago variant="default", rigid_trunk=False, default_trunk_offset=0.365, default_reset_mode="untuck", default_arm_pose="vertical", **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> category (str): Category for the object. Defaults to "object". uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object prim_type (PrimType): Which type of prim the object is, Valid options are: {PrimType.RIGID, PrimType.CLOTH} load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. If "sticky", will magnetize any object touching the gripper's fingers. disable_grasp_handling (bool): If True, will disable all grasp handling for this object. This means that sticky and assisted grasp modes will not work unless the connection/release methodsare manually called. variant (str): Which variant of the robot should be loaded. One of "default", "wrist_cam" rigid_trunk (bool) if True, will prevent the trunk from moving during execution. default_trunk_offset (float): sets the default height of the robot's trunk default_reset_mode (str): Default reset mode for the robot. Should be one of: {"tuck", "untuck"} If reset_joint_pos is not None, this will be ignored (since _default_joint_pos won't be used during initialization). default_arm_pose (str): Default pose for the robot arm. Should be one of: {"vertical", "diagonal15", "diagonal30", "diagonal45", "horizontal"} If either reset_joint_pos is not None or default_reset_mode is "tuck", this will be ignored. Otherwise the reset_joint_pos will be initialized to the precomputed joint positions that represents default_arm_pose. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Store args assert variant in ("default", "wrist_cam"), f"Invalid Tiago variant specified {variant}!" self._variant = variant self.rigid_trunk = rigid_trunk self.default_trunk_offset = default_trunk_offset assert_valid_key(key=default_reset_mode, valid_keys=RESET_JOINT_OPTIONS, name="default_reset_mode") self.default_reset_mode = default_reset_mode assert_valid_key(key=default_arm_pose, valid_keys=DEFAULT_ARM_POSES, name="default_arm_pose") self.default_arm_pose = default_arm_pose # Other args that will be created at runtime self._world_base_fixed_joint_prim = None # Run super init super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=True, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, grasping_mode=grasping_mode, disable_grasp_handling=disable_grasp_handling, **kwargs, ) @property def arm_joint_names(self): names = dict() for arm in self.arm_names: names[arm] = ["torso_lift_joint"] + [ f"arm_{arm}_{i}_joint" for i in range(1, 8) ] return names @property def model_name(self): return "Tiago" @property def n_arms(self): return 2 @property def arm_names(self): return ["left", "right"] @property def tucked_default_joint_pos(self): pos = np.zeros(self.n_dof) # Keep the current joint positions for the base joints pos[self.base_idx] = self.get_joint_positions()[self.base_idx] pos[self.trunk_control_idx] = 0 pos[self.camera_control_idx] = np.array([0.0, 0.0]) for arm in self.arm_names: pos[self.gripper_control_idx[arm]] = np.array([0.045, 0.045]) # open gripper pos[self.arm_control_idx[arm]] = np.array( [-1.10, 1.47, 2.71, 1.71, -1.57, 1.39, 0] ) return pos @property def untucked_default_joint_pos(self): pos = np.zeros(self.n_dof) # Keep the current joint positions for the base joints pos[self.base_idx] = self.get_joint_positions()[self.base_idx] pos[self.trunk_control_idx] = 0.02 + self.default_trunk_offset pos[self.camera_control_idx] = np.array([0.0, -0.45]) # Choose arm joint pos based on setting for arm in self.arm_names: pos[self.gripper_control_idx[arm]] = np.array([0.045, 0.045]) # open gripper if self.default_arm_pose == "vertical": pos[self.arm_control_idx[arm]] = np.array( [0.85846, -0.14852, 1.81008, 1.63368, 0.13764, -1.32488, -0.68415] ) elif self.default_arm_pose == "diagonal15": pos[self.arm_control_idx[arm]] = np.array( [0.90522, -0.42811, 2.23505, 1.64627, 0.76867, -0.79464, 2.05251] ) elif self.default_arm_pose == "diagonal30": pos[self.arm_control_idx[arm]] = np.array( [0.71883, -0.02787, 1.86002, 1.52897, 0.52204, -0.99741, 2.03113] ) elif self.default_arm_pose == "diagonal45" : pos[self.arm_control_idx[arm]] = np.array( [0.66058, -0.14251, 1.77547, 1.43345, 0.65988, -1.02741, 1.81302] ) elif self.default_arm_pose == "horizontal": pos[self.arm_control_idx[arm]] = np.array( [0.61511, 0.49229, 1.46306, 1.24919, 1.08282, -1.28865, 1.50910] ) else: raise ValueError("Unknown default arm pose: {}".format(self.default_arm_pose)) return pos def _create_discrete_action_space(self): # Tiago does not support discrete actions raise ValueError("Fetch does not support discrete actions!") @property def discrete_action_list(self): # Not supported for this robot raise NotImplementedError() def tuck(self): """ Immediately set this robot's configuration to be in tucked mode """ self.set_joint_positions(self.tucked_default_joint_pos) def untuck(self): """ Immediately set this robot's configuration to be in untucked mode """ self.set_joint_positions(self.untucked_default_joint_pos) def reset(self): """ Reset should not change the robot base pose. We need to cache and restore the base joints to the world. """ base_joint_positions = self.get_joint_positions()[self.base_idx] super().reset() self.set_joint_positions(base_joint_positions, indices=self.base_idx) def _post_load(self): super()._post_load() # The eef gripper links should be visual-only. They only contain a "ghost" box volume for detecting objects # inside the gripper, in order to activate attachments (AG for Cloths). for arm in self.arm_names: self.eef_links[arm].visual_only = True self.eef_links[arm].visible = False self._world_base_fixed_joint_prim = lazy.omni.isaac.core.utils.prims.get_prim_at_path(f"{self._prim_path}/rootJoint") position, orientation = self.get_position_orientation() # Set the world-to-base fixed joint to be at the robot's current pose self._world_base_fixed_joint_prim.GetAttribute("physics:localPos0").Set(tuple(position)) self._world_base_fixed_joint_prim.GetAttribute("physics:localRot0").Set(lazy.pxr.Gf.Quatf(*orientation[[3, 0, 1, 2]].tolist())) def _initialize(self): # Run super method first super()._initialize() # Set the joint friction for EEF to be higher for arm in self.arm_names: for joint in self.finger_joints[arm]: if joint.joint_type != JointType.JOINT_FIXED: joint.friction = 500 # Name of the actual root link that we are interested in. Note that this is different from self.root_link_name, # which is "base_footprint_x", corresponding to the first of the 6 1DoF joints to control the base. @property def base_footprint_link_name(self): return "base_footprint" @property def base_footprint_link(self): """ Returns: RigidPrim: base footprint link of this object prim """ return self._links[self.base_footprint_link_name] def _postprocess_control(self, control, control_type): # Run super method first u_vec, u_type_vec = super()._postprocess_control(control=control, control_type=control_type) # Change the control from base_footprint_link ("base_footprint") frame to root_link ("base_footprint_x") frame base_orn = self.base_footprint_link.get_orientation() root_link_orn = self.root_link.get_orientation() cur_orn = T.mat2quat(T.quat2mat(root_link_orn).T @ T.quat2mat(base_orn)) # Rotate the linear and angular velocity to the desired frame lin_vel_global, _ = T.pose_transform([0, 0, 0], cur_orn, u_vec[self.base_idx[:3]], [0, 0, 0, 1]) ang_vel_global, _ = T.pose_transform([0, 0, 0], cur_orn, u_vec[self.base_idx[3:]], [0, 0, 0, 1]) u_vec[self.base_control_idx] = np.array([lin_vel_global[0], lin_vel_global[1], ang_vel_global[2]]) return u_vec, u_type_vec def _get_proprioception_dict(self): dic = super()._get_proprioception_dict() # Add trunk info joint_positions = self.get_joint_positions(normalized=False) joint_velocities = self.get_joint_velocities(normalized=False) dic["trunk_qpos"] = joint_positions[self.trunk_control_idx] dic["trunk_qvel"] = joint_velocities[self.trunk_control_idx] return dic @property def control_limits(self): # Overwrite the control limits with the maximum linear and angular velocities for the purpose of clip_control # Note that when clip_control happens, the control is still in the base_footprint_link ("base_footprint") frame # Omniverse still thinks these joints have no limits because when the control is transformed to the root_link # ("base_footprint_x") frame, it can go above this limit. limits = super().control_limits limits["velocity"][0][self.base_idx[:3]] = -m.MAX_LINEAR_VELOCITY limits["velocity"][1][self.base_idx[:3]] = m.MAX_LINEAR_VELOCITY limits["velocity"][0][self.base_idx[3:]] = -m.MAX_ANGULAR_VELOCITY limits["velocity"][1][self.base_idx[3:]] = m.MAX_ANGULAR_VELOCITY return limits def get_control_dict(self): # Modify the right hand's pos_relative in the z-direction based on the trunk's value # We do this so we decouple the trunk's dynamic value from influencing the IK controller solution for the right # hand, which does not control the trunk fcns = super().get_control_dict() native_fcn = fcns.get_fcn("eef_right_pos_relative") fcns["eef_right_pos_relative"] = lambda: (native_fcn() + np.array([0, 0, -self.get_joint_positions()[self.trunk_control_idx[0]]])) return fcns @property def default_proprio_obs(self): obs_keys = super().default_proprio_obs return obs_keys + ["trunk_qpos"] @property def controller_order(self): controllers = ["base", "camera"] for arm in self.arm_names: controllers += ["arm_{}".format(arm), "gripper_{}".format(arm)] return controllers @property def _default_controllers(self): # Always call super first controllers = super()._default_controllers # We use joint controllers for base and camera as default controllers["base"] = "JointController" controllers["camera"] = "JointController" # We use multi finger gripper, and IK controllers for eefs as default for arm in self.arm_names: controllers["arm_{}".format(arm)] = "InverseKinematicsController" controllers["gripper_{}".format(arm)] = "MultiFingerGripperController" return controllers @property def _default_base_controller_configs(self): dic = { "name": "JointController", "control_freq": self._control_freq, "control_limits": self.control_limits, "use_delta_commands": False, "use_impedances": False, "motor_type": "velocity", "dof_idx": self.base_control_idx, } return dic @property def _default_controller_config(self): # Grab defaults from super method first cfg = super()._default_controller_config # Get default base controller for omnidirectional Tiago cfg["base"] = {"JointController": self._default_base_controller_configs} for arm in self.arm_names: for arm_cfg in cfg["arm_{}".format(arm)].values(): if arm == "left": # Need to override joint idx being controlled to include trunk in default arm controller configs arm_control_idx = np.concatenate([self.trunk_control_idx, self.arm_control_idx[arm]]) arm_cfg["dof_idx"] = arm_control_idx # Need to modify the default joint positions also if this is a null joint controller if arm_cfg["name"] == "NullJointController": arm_cfg["default_command"] = self.reset_joint_pos[arm_control_idx] # If using rigid trunk, we also clamp its limits # TODO: How to handle for right arm which has a fixed trunk internally even though the trunk is moving # via the left arm?? if self.rigid_trunk: arm_cfg["control_limits"]["position"][0][self.trunk_control_idx] = \ self.untucked_default_joint_pos[self.trunk_control_idx] arm_cfg["control_limits"]["position"][1][self.trunk_control_idx] = \ self.untucked_default_joint_pos[self.trunk_control_idx] return cfg @property def _default_joint_pos(self): return self.tucked_default_joint_pos if self.default_reset_mode == "tuck" else self.untucked_default_joint_pos @property def assisted_grasp_start_points(self): return { arm: [ GraspingPoint(link_name="gripper_{}_right_finger_link".format(arm), position=[0.002, 0.0, -0.2]), GraspingPoint(link_name="gripper_{}_right_finger_link".format(arm), position=[0.002, 0.0, -0.13]), ] for arm in self.arm_names } @property def assisted_grasp_end_points(self): return { arm: [ GraspingPoint(link_name="gripper_{}_left_finger_link".format(arm), position=[-0.002, 0.0, -0.2]), GraspingPoint(link_name="gripper_{}_left_finger_link".format(arm), position=[-0.002, 0.0, -0.13]), ] for arm in self.arm_names } @property def base_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to the three controllable 1DoF base joints """ joints = list(self.joints.keys()) return np.array( [ joints.index(f"base_footprint_{component}_joint") for component in ["x", "y", "rz"] ] ) @property def base_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to the six 1DoF base joints """ joints = list(self.joints.keys()) return np.array( [ joints.index(f"base_footprint_{component}_joint") for component in ["x", "y", "z", "rx", "ry", "rz"] ] ) @property def trunk_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to trunk joint. """ return np.array([6]) @property def camera_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to [tilt, pan] camera joints. """ return np.array([9, 12]) @property def arm_control_idx(self): return {"left": np.array([7, 10, 13, 15, 17, 19, 21]), "right": np.array([8, 11, 14, 16, 18, 20, 22]), "combined": np.array([7, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])} @property def gripper_control_idx(self): return {"left": np.array([23, 24]), "right": np.array([25, 26])} @property def finger_lengths(self): return {arm: 0.12 for arm in self.arm_names} @property def disabled_collision_link_names(self): # These should NEVER have collisions in the first place (i.e.: these are poorly modeled geoms from the source # asset) -- they are strictly engulfed within ANOTHER collision mesh from a DIFFERENT link return [name for arm in self.arm_names for name in [f"arm_{arm}_tool_link", f"wrist_{arm}_ft_link", f"wrist_{arm}_ft_tool_link"]] @property def disabled_collision_pairs(self): return [ ["arm_left_1_link", "arm_left_2_link"], ["arm_left_2_link", "arm_left_3_link"], ["arm_left_3_link", "arm_left_4_link"], ["arm_left_4_link", "arm_left_5_link"], ["arm_left_5_link", "arm_left_6_link"], ["arm_left_6_link", "arm_left_7_link"], ["arm_right_1_link", "arm_right_2_link"], ["arm_right_2_link", "arm_right_3_link"], ["arm_right_3_link", "arm_right_4_link"], ["arm_right_4_link", "arm_right_5_link"], ["arm_right_5_link", "arm_right_6_link"], ["arm_right_6_link", "arm_right_7_link"], ["gripper_right_right_finger_link", "gripper_right_left_finger_link"], ["gripper_right_link", "wrist_right_ft_link"], ["arm_right_6_link", "gripper_right_link"], ["arm_right_6_link", "wrist_right_ft_tool_link"], ["arm_right_6_link", "wrist_right_ft_link"], ["arm_right_6_link", "arm_right_tool_link"], ["arm_right_5_link", "wrist_right_ft_link"], ["arm_right_5_link", "arm_right_tool_link"], ["gripper_left_right_finger_link", "gripper_left_left_finger_link"], ["gripper_left_link", "wrist_left_ft_link"], ["arm_left_6_link", "gripper_left_link"], ["arm_left_6_link", "wrist_left_ft_tool_link"], ["arm_left_6_link", "wrist_left_ft_link"], ["arm_left_6_link", "arm_left_tool_link"], ["arm_left_5_link", "wrist_left_ft_link"], ["arm_left_5_link", "arm_left_tool_link"], ["torso_lift_link", "torso_fixed_column_link"], ["torso_fixed_link", "torso_fixed_column_link"], ["base_antenna_left_link", "torso_fixed_link"], ["base_antenna_right_link", "torso_fixed_link"], ["base_link", "wheel_rear_left_link"], ["base_link", "wheel_rear_right_link"], ["base_link", "wheel_front_left_link"], ["base_link", "wheel_front_right_link"], ["base_link", "base_dock_link"], ["base_link", "base_antenna_right_link"], ["base_link", "base_antenna_left_link"], ["base_link", "torso_fixed_column_link"], ["base_link", "suspension_front_left_link"], ["base_link", "suspension_front_right_link"], ["base_link", "torso_fixed_link"], ["suspension_front_left_link", "wheel_front_left_link"], ["torso_lift_link", "arm_right_1_link"], ["torso_lift_link", "arm_right_2_link"], ["torso_lift_link", "arm_left_1_link"], ["torso_lift_link", "arm_left_2_link"], ["arm_left_tool_link", "wrist_left_ft_link"], ["wrist_left_ft_link", "wrist_left_ft_tool_link"], ["wrist_left_ft_tool_link", "gripper_left_link"], ['gripper_left_grasping_frame', 'gripper_left_left_finger_link'], ['gripper_left_grasping_frame', 'gripper_left_right_finger_link'], ['wrist_right_ft_link', 'arm_right_tool_link'], ['wrist_right_ft_tool_link', 'wrist_right_ft_link'], ['gripper_right_link', 'wrist_right_ft_tool_link'], ['head_1_link', 'head_2_link'], ['torso_fixed_column_link', 'arm_right_1_link'], ['torso_fixed_column_link', 'arm_left_1_link'], ['arm_left_1_link', 'arm_left_3_link'], ['arm_right_1_link', 'arm_right_3_link'], ['base_link', 'arm_right_4_link'], ['base_link', 'arm_right_5_link'], ['base_link', 'arm_left_4_link'], ['base_link', 'arm_left_5_link'], ['wrist_left_ft_tool_link', 'arm_left_5_link'], ['wrist_right_ft_tool_link', 'arm_right_5_link'], ['arm_left_tool_link', 'wrist_left_ft_tool_link'], ['arm_right_tool_link', 'wrist_right_ft_tool_link'] ] @property def manipulation_link_names(self): return [ "torso_fixed_link", "torso_lift_link", "arm_left_1_link", "arm_left_2_link", "arm_left_3_link", "arm_left_4_link", "arm_left_5_link", "arm_left_6_link", "arm_left_7_link", "arm_left_tool_link", "wrist_left_ft_link", "wrist_left_ft_tool_link", "gripper_left_link", # "gripper_left_grasping_frame", "gripper_left_left_finger_link", "gripper_left_right_finger_link", "gripper_left_tool_link", "arm_right_1_link", "arm_right_2_link", "arm_right_3_link", "arm_right_4_link", "arm_right_5_link", "arm_right_6_link", "arm_right_7_link", "arm_right_tool_link", "wrist_right_ft_link", "wrist_right_ft_tool_link", "gripper_right_link", # "gripper_right_grasping_frame", "gripper_right_left_finger_link", "gripper_right_right_finger_link", "gripper_right_tool_link", "head_1_link", "head_2_link", "xtion_link", ] @property def arm_link_names(self): return {arm: [f"arm_{arm}_{i}_link" for i in range(1, 8)] for arm in self.arm_names} @property def eef_link_names(self): return {arm: "gripper_{}_grasping_frame".format(arm) for arm in self.arm_names} @property def finger_link_names(self): return {arm: ["gripper_{}_right_finger_link".format(arm), "gripper_{}_left_finger_link".format(arm)] for arm in self.arm_names} @property def finger_joint_names(self): return {arm: ["gripper_{}_right_finger_joint".format(arm), "gripper_{}_left_finger_joint".format(arm)] for arm in self.arm_names} @property def usd_path(self): if self._variant == "wrist_cam": return os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford/tiago_dual_omnidirectional_stanford_33_with_wrist_cam.usd") # Default variant return os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford/tiago_dual_omnidirectional_stanford_33.usd") @property def simplified_mesh_usd_path(self): # TODO: How can we make this more general - maybe some automatic way to generate these? return os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford/tiago_dual_omnidirectional_stanford_33_simplified_collision_mesh.usd") @property def robot_arm_descriptor_yamls(self): # TODO: Remove the need to do this by making the arm descriptor yaml files generated automatically return {"left": os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford_left_arm_descriptor.yaml"), "left_fixed": os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford_left_arm_fixed_trunk_descriptor.yaml"), "right": os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford_right_arm_fixed_trunk_descriptor.yaml"), "combined": os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford.yaml")} @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford.urdf") @property def arm_workspace_range(self): return { "left": [np.deg2rad(15), np.deg2rad(75)], "right": [np.deg2rad(-75), np.deg2rad(-15)], } def get_position_orientation(self): # TODO: Investigate the need for this custom behavior. return self.base_footprint_link.get_position_orientation() def set_position_orientation(self, position=None, orientation=None): current_position, current_orientation = self.get_position_orientation() if position is None: position = current_position if orientation is None: orientation = current_orientation position, orientation = np.array(position), np.array(orientation) assert np.isclose(np.linalg.norm(orientation), 1, atol=1e-3), \ f"{self.name} desired orientation {orientation} is not a unit quaternion." # TODO: Reconsider the need for this. Why can't these behaviors be unified? Does the joint really need to move? # If the simulator is playing, set the 6 base joints to achieve the desired pose of base_footprint link frame if og.sim.is_playing() and self.initialized: # Find the relative transformation from base_footprint_link ("base_footprint") frame to root_link # ("base_footprint_x") frame. Assign it to the 6 1DoF joints that control the base. # Note that the 6 1DoF joints are originated from the root_link ("base_footprint_x") frame. joint_pos, joint_orn = self.root_link.get_position_orientation() inv_joint_pos, inv_joint_orn = T.mat2pose(T.pose_inv(T.pose2mat((joint_pos, joint_orn)))) relative_pos, relative_orn = T.pose_transform(inv_joint_pos, inv_joint_orn, position, orientation) relative_rpy = T.quat2euler(relative_orn) self.joints["base_footprint_x_joint"].set_pos(relative_pos[0], drive=False) self.joints["base_footprint_y_joint"].set_pos(relative_pos[1], drive=False) self.joints["base_footprint_z_joint"].set_pos(relative_pos[2], drive=False) self.joints["base_footprint_rx_joint"].set_pos(relative_rpy[0], drive=False) self.joints["base_footprint_ry_joint"].set_pos(relative_rpy[1], drive=False) self.joints["base_footprint_rz_joint"].set_pos(relative_rpy[2], drive=False) # Else, set the pose of the robot frame, and then move the joint frame of the world_base_joint to match it else: # Call the super() method to move the robot frame first super().set_position_orientation(position, orientation) # Move the joint frame for the world_base_joint if self._world_base_fixed_joint_prim is not None: self._world_base_fixed_joint_prim.GetAttribute("physics:localPos0").Set(tuple(position)) self._world_base_fixed_joint_prim.GetAttribute("physics:localRot0").Set(lazy.pxr.Gf.Quatf(*orientation[[3, 0, 1, 2]].tolist())) def set_linear_velocity(self, velocity: np.ndarray): # Transform the desired linear velocity from the world frame to the root_link ("base_footprint_x") frame # Note that this will also set the target to be the desired linear velocity (i.e. the robot will try to maintain # such velocity), which is different from the default behavior of set_linear_velocity for all other objects. orn = self.root_link.get_orientation() velocity_in_root_link = T.quat2mat(orn).T @ velocity self.joints["base_footprint_x_joint"].set_vel(velocity_in_root_link[0], drive=False) self.joints["base_footprint_y_joint"].set_vel(velocity_in_root_link[1], drive=False) self.joints["base_footprint_z_joint"].set_vel(velocity_in_root_link[2], drive=False) def get_linear_velocity(self) -> np.ndarray: # Note that the link we are interested in is self.base_footprint_link, not self.root_link return self.base_footprint_link.get_linear_velocity() def set_angular_velocity(self, velocity: np.ndarray) -> None: # See comments of self.set_linear_velocity orn = self.root_link.get_orientation() velocity_in_root_link = T.quat2mat(orn).T @ velocity self.joints["base_footprint_rx_joint"].set_vel(velocity_in_root_link[0], drive=False) self.joints["base_footprint_ry_joint"].set_vel(velocity_in_root_link[1], drive=False) self.joints["base_footprint_rz_joint"].set_vel(velocity_in_root_link[2], drive=False) def get_angular_velocity(self) -> np.ndarray: # Note that the link we are interested in is self.base_footprint_link, not self.root_link return self.base_footprint_link.get_angular_velocity() @property def eef_usd_path(self): return {arm: os.path.join(gm.ASSET_PATH, "models/tiago/tiago_dual_omnidirectional_stanford/tiago_eef.usd") for arm in self.arm_names} def teleop_data_to_action(self, teleop_action) -> np.ndarray: action = ManipulationRobot.teleop_data_to_action(self, teleop_action) action[self.base_action_idx] = teleop_action.base * 0.1 return action
36,634
Python
46.701823
163
0.611345
StanfordVL/OmniGibson/omnigibson/robots/active_camera_robot.py
from abc import abstractmethod import numpy as np from omnigibson.robots.robot_base import BaseRobot from omnigibson.utils.python_utils import classproperty class ActiveCameraRobot(BaseRobot): """ Robot that is is equipped with an onboard camera that can be moved independently from the robot's other kinematic joints (e.g.: independent of base and arm for a mobile manipulator). NOTE: controller_config should, at the minimum, contain: camera: controller specifications for the controller to control this robot's camera. Should include: - name: Controller to create - <other kwargs> relevant to the controller being created. Note that all values will have default values specified, but setting these individual kwargs will override them """ def _validate_configuration(self): # Make sure a camera controller is specified assert ( "camera" in self._controllers ), "Controller 'camera' must exist in controllers! Current controllers: {}".format( list(self._controllers.keys()) ) # run super super()._validate_configuration() def _get_proprioception_dict(self): dic = super()._get_proprioception_dict() # Add camera pos info joint_positions = self.get_joint_positions(normalized=False) joint_velocities = self.get_joint_velocities(normalized=False) dic["camera_qpos"] = joint_positions[self.camera_control_idx] dic["camera_qpos_sin"] = np.sin(joint_positions[self.camera_control_idx]) dic["camera_qpos_cos"] = np.cos(joint_positions[self.camera_control_idx]) dic["camera_qvel"] = joint_velocities[self.camera_control_idx] return dic @property def default_proprio_obs(self): obs_keys = super().default_proprio_obs return obs_keys + ["camera_qpos_sin", "camera_qpos_cos"] @property def controller_order(self): # By default, only camera is supported return ["camera"] @property def _default_controllers(self): # Always call super first controllers = super()._default_controllers # For best generalizability use, joint controller as default controllers["camera"] = "JointController" return controllers @property def _default_camera_joint_controller_config(self): """ Returns: dict: Default camera joint controller config to control this robot's camera """ return { "name": "JointController", "control_freq": self._control_freq, "control_limits": self.control_limits, "dof_idx": self.camera_control_idx, "command_output_limits": None, "motor_type": "position", "use_delta_commands": True, "use_impedances": False, } @property def _default_camera_null_joint_controller_config(self): """ Returns: dict: Default null joint controller config to control this robot's camera i.e. dummy controller """ return { "name": "NullJointController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.camera_control_idx, "default_command": self.reset_joint_pos[self.camera_control_idx], "use_impedances": False, } @property def _default_controller_config(self): # Always run super method first cfg = super()._default_controller_config # We additionally add in camera default cfg["camera"] = { self._default_camera_joint_controller_config["name"]: self._default_camera_joint_controller_config, self._default_camera_null_joint_controller_config["name"]: self._default_camera_null_joint_controller_config, } return cfg @property @abstractmethod def camera_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to camera joints. """ 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("ActiveCameraRobot") return classes
4,464
Python
33.882812
121
0.62948
StanfordVL/OmniGibson/omnigibson/robots/vx300s.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.robots.manipulation_robot import ManipulationRobot, GraspingPoint from omnigibson.utils.transform_utils import euler2quat class VX300S(ManipulationRobot): """ The VX300-6DOF arm from Trossen Robotics (https://www.trossenrobotics.com/docs/interbotix_xsarms/specifications/vx300s.html) """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=True, load_config=None, fixed_base=True, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. If "sticky", will magnetize any object touching the gripper's fingers. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Run super init super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, grasping_mode=grasping_mode, **kwargs, ) @property def model_name(self): return "VX300S" @property def discrete_action_list(self): # Not supported for this robot raise NotImplementedError() def _create_discrete_action_space(self): # Fetch does not support discrete actions raise ValueError("VX300S does not support discrete actions!") @property def controller_order(self): return [f"arm_{self.default_arm}", f"gripper_{self.default_arm}"] @property def _default_controllers(self): controllers = super()._default_controllers controllers[f"arm_{self.default_arm}"] = "InverseKinematicsController" controllers[f"gripper_{self.default_arm}"] = "MultiFingerGripperController" return controllers @property def _default_joint_pos(self): return np.array([0.0, -0.849879, 0.258767, 0.0, 1.2831712, 0.0, 0.057, 0.057]) @property def finger_lengths(self): return {self.default_arm: 0.1} @property def arm_control_idx(self): # The first 7 joints return {self.default_arm: np.arange(6)} @property def gripper_control_idx(self): # The last two joints return {self.default_arm: np.arange(6, 8)} @property def disabled_collision_pairs(self): return [ ["gripper_bar_link", "left_finger_link"], ["gripper_bar_link", "right_finger_link"], ["gripper_bar_link", "gripper_link"], ] @property def arm_link_names(self): return {self.default_arm: [ "base_link", "shoulder_link", "upper_arm_link", "upper_forearm_link", "lower_forearm_link", "wrist_link", "gripper_link", "gripper_bar_link", ]} @property def arm_joint_names(self): return {self.default_arm: [ "waist", "shoulder", "elbow", "forearm_roll", "wrist_angle", "wrist_rotate", ]} @property def eef_link_names(self): return {self.default_arm: "ee_gripper_link"} @property def finger_link_names(self): return {self.default_arm: ["left_finger_link", "right_finger_link"]} @property def finger_joint_names(self): return {self.default_arm: ["left_finger", "right_finger"]} @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/vx300s/vx300s/vx300s.usd") @property def robot_arm_descriptor_yamls(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/vx300s/vx300s_description.yaml")} @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/vx300s/vx300s.urdf") @property def eef_usd_path(self): # return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/vx300s/vx300s_eef.usd")} raise NotImplementedError @property def teleop_rotation_offset(self): return {self.default_arm: euler2quat([-np.pi, 0, 0])} @property def assisted_grasp_start_points(self): return {self.default_arm: [ GraspingPoint(link_name="right_finger_link", position=[0.0, 0.001, 0.057]), ]} @property def assisted_grasp_end_points(self): return {self.default_arm: [ GraspingPoint(link_name="left_finger_link", position=[0.0, 0.001, 0.057]), ]}
9,721
Python
40.021097
126
0.622673
StanfordVL/OmniGibson/omnigibson/robots/fetch.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.controllers import ControlType from omnigibson.robots.active_camera_robot import ActiveCameraRobot from omnigibson.robots.manipulation_robot import GraspingPoint, ManipulationRobot from omnigibson.robots.two_wheel_robot import TwoWheelRobot from omnigibson.utils.python_utils import assert_valid_key from omnigibson.utils.ui_utils import create_module_logger from omnigibson.utils.transform_utils import euler2quat from omnigibson.utils.usd_utils import JointType log = create_module_logger(module_name=__name__) DEFAULT_ARM_POSES = { "vertical", "diagonal15", "diagonal30", "diagonal45", "horizontal", } RESET_JOINT_OPTIONS = { "tuck", "untuck", } class Fetch(ManipulationRobot, TwoWheelRobot, ActiveCameraRobot): """ Fetch Robot Reference: https://fetchrobotics.com/robotics-platforms/fetch-mobile-manipulator/ """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=False, load_config=None, fixed_base=False, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", disable_grasp_handling=False, # Unique to Fetch rigid_trunk=False, default_trunk_offset=0.365, default_reset_mode="untuck", default_arm_pose="vertical", **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. If "sticky", will magnetize any object touching the gripper's fingers. disable_grasp_handling (bool): If True, will disable all grasp handling for this object. This means that sticky and assisted grasp modes will not work unless the connection/release methodsare manually called. rigid_trunk (bool) if True, will prevent the trunk from moving during execution. default_trunk_offset (float): sets the default height of the robot's trunk default_reset_mode (str): Default reset mode for the robot. Should be one of: {"tuck", "untuck"} If reset_joint_pos is not None, this will be ignored (since _default_joint_pos won't be used during initialization). default_arm_pose (str): Default pose for the robot arm. Should be one of: {"vertical", "diagonal15", "diagonal30", "diagonal45", "horizontal"} If either reset_joint_pos is not None or default_reset_mode is "tuck", this will be ignored. Otherwise the reset_joint_pos will be initialized to the precomputed joint positions that represents default_arm_pose. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Store args self.rigid_trunk = rigid_trunk self.default_trunk_offset = default_trunk_offset assert_valid_key(key=default_reset_mode, valid_keys=RESET_JOINT_OPTIONS, name="default_reset_mode") self.default_reset_mode = default_reset_mode assert_valid_key(key=default_arm_pose, valid_keys=DEFAULT_ARM_POSES, name="default_arm_pose") self.default_arm_pose = default_arm_pose # Run super init super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, grasping_mode=grasping_mode, disable_grasp_handling=disable_grasp_handling, **kwargs, ) @property def model_name(self): return "Fetch" @property def tucked_default_joint_pos(self): return np.array( [ 0.0, 0.0, # wheels 0.02, # trunk 0.0, 1.1707963267948966, 0.0, # head 1.4707963267948965, -0.4, 1.6707963267948966, 0.0, 1.5707963267948966, 0.0, # arm 0.05, 0.05, # gripper ] ) @property def untucked_default_joint_pos(self): pos = np.zeros(self.n_joints) pos[self.base_control_idx] = 0.0 pos[self.trunk_control_idx] = 0.02 + self.default_trunk_offset pos[self.camera_control_idx] = np.array([0.0, 0.45]) pos[self.gripper_control_idx[self.default_arm]] = np.array([0.05, 0.05]) # open gripper # Choose arm based on setting if self.default_arm_pose == "vertical": pos[self.arm_control_idx[self.default_arm]] = np.array( [-0.94121, -0.64134, 1.55186, 1.65672, -0.93218, 1.53416, 2.14474] ) elif self.default_arm_pose == "diagonal15": pos[self.arm_control_idx[self.default_arm]] = np.array( [-0.95587, -0.34778, 1.46388, 1.47821, -0.93813, 1.4587, 1.9939] ) elif self.default_arm_pose == "diagonal30": pos[self.arm_control_idx[self.default_arm]] = np.array( [-1.06595, -0.22184, 1.53448, 1.46076, -0.84995, 1.36904, 1.90996] ) elif self.default_arm_pose == "diagonal45": pos[self.arm_control_idx[self.default_arm]] = np.array( [-1.11479, -0.0685, 1.5696, 1.37304, -0.74273, 1.3983, 1.79618] ) elif self.default_arm_pose == "horizontal": pos[self.arm_control_idx[self.default_arm]] = np.array( [-1.43016, 0.20965, 1.86816, 1.77576, -0.27289, 1.31715, 2.01226] ) else: raise ValueError("Unknown default arm pose: {}".format(self.default_arm_pose)) return pos def _post_load(self): super()._post_load() # Set the wheels back to using sphere approximations for wheel_name in ["l_wheel_link", "r_wheel_link"]: log.warning( "Fetch wheel links are post-processed to use sphere approximation collision meshes." "Please ignore any previous errors about these collision meshes.") wheel_link = self.links[wheel_name] assert set(wheel_link.collision_meshes) == {"collisions"}, "Wheel link should only have 1 collision!" wheel_link.collision_meshes["collisions"].set_collision_approximation("boundingSphere") # Also apply a convex decomposition to the torso lift link torso_lift_link = self.links["torso_lift_link"] assert set(torso_lift_link.collision_meshes) == {"collisions"}, "Wheel link should only have 1 collision!" torso_lift_link.collision_meshes["collisions"].set_collision_approximation("convexDecomposition") @property def discrete_action_list(self): # Not supported for this robot raise NotImplementedError() def _create_discrete_action_space(self): # Fetch does not support discrete actions raise ValueError("Fetch does not support discrete actions!") def tuck(self): """ Immediately set this robot's configuration to be in tucked mode """ self.set_joint_positions(self.tucked_default_joint_pos) def untuck(self): """ Immediately set this robot's configuration to be in untucked mode """ self.set_joint_positions(self.untucked_default_joint_pos) def _initialize(self): # Run super method first super()._initialize() # Set the joint friction for EEF to be higher for arm in self.arm_names: for joint in self.finger_joints[arm]: if joint.joint_type != JointType.JOINT_FIXED: joint.friction = 500 def _postprocess_control(self, control, control_type): # Run super method first u_vec, u_type_vec = super()._postprocess_control(control=control, control_type=control_type) # Override trunk value if we're keeping the trunk rigid if self.rigid_trunk: u_vec[self.trunk_control_idx] = self.untucked_default_joint_pos[self.trunk_control_idx] u_type_vec[self.trunk_control_idx] = ControlType.POSITION # Return control return u_vec, u_type_vec def _get_proprioception_dict(self): dic = super()._get_proprioception_dict() # Add trunk info joint_positions = self.get_joint_positions(normalized=False) joint_velocities = self.get_joint_velocities(normalized=False) dic["trunk_qpos"] = joint_positions[self.trunk_control_idx] dic["trunk_qvel"] = joint_velocities[self.trunk_control_idx] return dic @property def default_proprio_obs(self): obs_keys = super().default_proprio_obs return obs_keys + ["trunk_qpos"] @property def controller_order(self): # Ordered by general robot kinematics chain return ["base", "camera", "arm_{}".format(self.default_arm), "gripper_{}".format(self.default_arm)] @property def _default_controllers(self): # Always call super first controllers = super()._default_controllers # We use multi finger gripper, differential drive, and IK controllers as default controllers["base"] = "DifferentialDriveController" controllers["camera"] = "JointController" controllers["arm_{}".format(self.default_arm)] = "InverseKinematicsController" controllers["gripper_{}".format(self.default_arm)] = "MultiFingerGripperController" return controllers @property def _default_controller_config(self): # Grab defaults from super method first cfg = super()._default_controller_config # Need to override joint idx being controlled to include trunk in default arm controller configs for arm_cfg in cfg[f"arm_{self.default_arm}"].values(): arm_control_idx = np.concatenate([self.trunk_control_idx, self.arm_control_idx[self.default_arm]]) arm_cfg["dof_idx"] = arm_control_idx # Need to modify the default joint positions also if this is a null joint controller if arm_cfg["name"] == "NullJointController": arm_cfg["default_command"] = self.reset_joint_pos[arm_control_idx] # If using rigid trunk, we also clamp its limits if self.rigid_trunk: arm_cfg["control_limits"]["position"][0][self.trunk_control_idx] = \ self.untucked_default_joint_pos[self.trunk_control_idx] arm_cfg["control_limits"]["position"][1][self.trunk_control_idx] = \ self.untucked_default_joint_pos[self.trunk_control_idx] return cfg @property def _default_joint_pos(self): return self.tucked_default_joint_pos if self.default_reset_mode == "tuck" else self.untucked_default_joint_pos @property def wheel_radius(self): return 0.0613 @property def wheel_axle_length(self): return 0.372 @property def finger_lengths(self): return {self.default_arm: 0.1} @property def assisted_grasp_start_points(self): return { self.default_arm: [ GraspingPoint(link_name="r_gripper_finger_link", position=[0.025, -0.012, 0.0]), GraspingPoint(link_name="r_gripper_finger_link", position=[-0.025, -0.012, 0.0]), ] } @property def assisted_grasp_end_points(self): return { self.default_arm: [ GraspingPoint(link_name="l_gripper_finger_link", position=[0.025, 0.012, 0.0]), GraspingPoint(link_name="l_gripper_finger_link", position=[-0.025, 0.012, 0.0]), ] } @property def base_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to [Left, Right] wheel joints. """ return np.array([0, 1]) @property def trunk_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to trunk joint. """ return np.array([2]) @property def camera_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to [tilt, pan] camera joints. """ return np.array([3, 5]) @property def arm_control_idx(self): return {self.default_arm: np.array([4, 6, 7, 8, 9, 10, 11])} @property def gripper_control_idx(self): return {self.default_arm: np.array([12, 13])} @property def disabled_collision_pairs(self): return [ ["torso_lift_link", "shoulder_lift_link"], ["torso_lift_link", "torso_fixed_link"], ["torso_lift_link", "estop_link"], ["base_link", "laser_link"], ["base_link", "torso_fixed_link"], ["base_link", "l_wheel_link"], ["base_link", "r_wheel_link"], ["base_link", "estop_link"], ["torso_lift_link", "shoulder_pan_link"], ["torso_lift_link", "head_pan_link"], ["head_pan_link", "head_tilt_link"], ["shoulder_pan_link", "shoulder_lift_link"], ["shoulder_lift_link", "upperarm_roll_link"], ["upperarm_roll_link", "elbow_flex_link"], ["elbow_flex_link", "forearm_roll_link"], ["forearm_roll_link", "wrist_flex_link"], ["wrist_flex_link", "wrist_roll_link"], ["wrist_roll_link", "gripper_link"], ] @property def manipulation_link_names(self): return [ "torso_lift_link", "head_pan_link", "head_tilt_link", "shoulder_pan_link", "shoulder_lift_link", "upperarm_roll_link", "elbow_flex_link", "forearm_roll_link", "wrist_flex_link", "wrist_roll_link", "gripper_link", "l_gripper_finger_link", "r_gripper_finger_link", ] @property def arm_link_names(self): return {self.default_arm: [ "shoulder_pan_link", "shoulder_lift_link", "upperarm_roll_link", "elbow_flex_link", "forearm_roll_link", "wrist_flex_link", "wrist_roll_link", ]} @property def arm_joint_names(self): return {self.default_arm: [ "torso_lift_joint", "shoulder_pan_joint", "shoulder_lift_joint", "upperarm_roll_joint", "elbow_flex_joint", "forearm_roll_joint", "wrist_flex_joint", "wrist_roll_joint", ]} @property def eef_link_names(self): return {self.default_arm: "gripper_link"} @property def finger_link_names(self): return {self.default_arm: ["r_gripper_finger_link", "l_gripper_finger_link"]} @property def finger_joint_names(self): return {self.default_arm: ["r_gripper_finger_joint", "l_gripper_finger_joint"]} @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/fetch/fetch/fetch.usd") @property def robot_arm_descriptor_yamls(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/fetch/fetch_descriptor.yaml")} @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/fetch/fetch.urdf") @property def arm_workspace_range(self): return { self.default_arm : [np.deg2rad(-45), np.deg2rad(45)] } @property def eef_usd_path(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/fetch/fetch/fetch_eef.usd")} @property def teleop_rotation_offset(self): return {self.default_arm: euler2quat([0, np.pi / 2, np.pi])}
20,962
Python
40.184676
134
0.60686
StanfordVL/OmniGibson/omnigibson/robots/__init__.py
from omnigibson.robots.active_camera_robot import ActiveCameraRobot from omnigibson.robots.freight import Freight from omnigibson.robots.husky import Husky from omnigibson.robots.locobot import Locobot from omnigibson.robots.locomotion_robot import LocomotionRobot from omnigibson.robots.manipulation_robot import ManipulationRobot from omnigibson.robots.robot_base import REGISTERED_ROBOTS, BaseRobot from omnigibson.robots.turtlebot import Turtlebot from omnigibson.robots.fetch import Fetch from omnigibson.robots.tiago import Tiago from omnigibson.robots.two_wheel_robot import TwoWheelRobot from omnigibson.robots.franka import FrankaPanda from omnigibson.robots.franka_allegro import FrankaAllegro from omnigibson.robots.franka_leap import FrankaLeap from omnigibson.robots.vx300s import VX300S from omnigibson.robots.behavior_robot import BehaviorRobot
860
Python
49.647056
69
0.873256
StanfordVL/OmniGibson/omnigibson/robots/turtlebot.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.robots.two_wheel_robot import TwoWheelRobot class Turtlebot(TwoWheelRobot): """ Turtlebot robot Reference: http://wiki.ros.org/Robots/TurtleBot Uses joint velocity control """ @property def wheel_radius(self): return 0.038 @property def wheel_axle_length(self): return 0.23 @property def base_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to [Left, Right] wheel joints. """ return np.array([0, 1]) @property def _default_joint_pos(self): return np.zeros(self.n_joints) @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/turtlebot/turtlebot/turtlebot.usd") @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/turtlebot/turtlebot.urdf")
963
Python
21.95238
101
0.643821
StanfordVL/OmniGibson/omnigibson/robots/manipulation_robot.py
from abc import abstractmethod from collections import namedtuple import numpy as np import networkx as nx import omnigibson as og import omnigibson.lazy as lazy from omnigibson.controllers import InverseKinematicsController, MultiFingerGripperController, OperationalSpaceController from omnigibson.macros import gm, create_module_macros from omnigibson.object_states import ContactBodies import omnigibson.utils.transform_utils as T from omnigibson.controllers import ( IsGraspingState, ControlType, ManipulationController, GripperController, ) from omnigibson.robots.robot_base import BaseRobot from omnigibson.utils.python_utils import classproperty, assert_valid_key from omnigibson.utils.geometry_utils import generate_points_in_volume_checker_function from omnigibson.utils.constants import JointType, PrimType from omnigibson.utils.usd_utils import create_joint from omnigibson.utils.sampling_utils import raytest_batch # Create settings for this module m = create_module_macros(module_path=__file__) # Assisted grasping parameters m.ASSIST_FRACTION = 1.0 m.ASSIST_GRASP_MASS_THRESHOLD = 10.0 m.ARTICULATED_ASSIST_FRACTION = 0.7 m.MIN_ASSIST_FORCE = 0 m.MAX_ASSIST_FORCE = 100 m.ASSIST_FORCE = m.MIN_ASSIST_FORCE + (m.MAX_ASSIST_FORCE - m.MIN_ASSIST_FORCE) * m.ASSIST_FRACTION m.CONSTRAINT_VIOLATION_THRESHOLD = 0.1 m.RELEASE_WINDOW = 1 / 30.0 # release window in seconds AG_MODES = { "physical", "assisted", "sticky", } GraspingPoint = namedtuple("GraspingPoint", ["link_name", "position"]) # link_name (str), position (x,y,z tuple) class ManipulationRobot(BaseRobot): """ Robot that is is equipped with grasping (manipulation) capabilities. Provides common interface for a wide variety of robots. NOTE: controller_config should, at the minimum, contain: arm: controller specifications for the controller to control this robot's arm (manipulation). Should include: - name: Controller to create - <other kwargs> relevant to the controller being created. Note that all values will have default values specified, but setting these individual kwargs will override them """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, self_collisions=False, load_config=None, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", grasping_direction="lower", disable_grasp_handling=False, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. In this mode, at least two "fingers" need to touch the object. If "sticky", will magnetize any object touching the gripper's fingers. In this mode, only one finger needs to touch the object. grasping_direction (str): One of {"lower", "upper"}. If "lower", lower limit represents a closed grasp, otherwise upper limit represents a closed grasp. disable_grasp_handling (bool): If True, the robot will not automatically handle assisted or sticky grasps. Instead, you will need to call the grasp handling methods yourself. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Store relevant internal vars assert_valid_key(key=grasping_mode, valid_keys=AG_MODES, name="grasping_mode") assert_valid_key(key=grasping_direction, valid_keys=["lower", "upper"], name="grasping direction") self._grasping_mode = grasping_mode self._grasping_direction = grasping_direction self._disable_grasp_handling = disable_grasp_handling # Initialize other variables used for assistive grasping self._ag_freeze_joint_pos = { arm: {} for arm in self.arm_names } # Frozen positions for keeping fingers held still self._ag_obj_in_hand = {arm: None for arm in self.arm_names} self._ag_obj_constraints = {arm: None for arm in self.arm_names} self._ag_obj_constraint_params = {arm: {} for arm in self.arm_names} self._ag_freeze_gripper = {arm: None for arm in self.arm_names} self._ag_release_counter = {arm: None for arm in self.arm_names} self._ag_check_in_volume = {arm: None for arm in self.arm_names} self._ag_calculate_volume = {arm: None for arm in self.arm_names} # Call super() method super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, **kwargs, ) def _validate_configuration(self): # Iterate over all arms for arm in self.arm_names: # We make sure that our arm controller exists and is a manipulation controller assert ( "arm_{}".format(arm) in self._controllers ), "Controller 'arm_{}' must exist in controllers! Current controllers: {}".format( arm, list(self._controllers.keys()) ) assert isinstance( self._controllers["arm_{}".format(arm)], ManipulationController ), "Arm {} controller must be a ManipulationController!".format(arm) # We make sure that our gripper controller exists and is a gripper controller assert ( "gripper_{}".format(arm) in self._controllers ), "Controller 'gripper_{}' must exist in controllers! Current controllers: {}".format( arm, list(self._controllers.keys()) ) assert isinstance( self._controllers["gripper_{}".format(arm)], GripperController ), "Gripper {} controller must be a GripperController!".format(arm) # run super super()._validate_configuration() def _initialize(self): super()._initialize() if gm.AG_CLOTH: for arm in self.arm_names: self._ag_check_in_volume[arm], self._ag_calculate_volume[arm] = \ generate_points_in_volume_checker_function(obj=self, volume_link=self.eef_links[arm], mesh_name_prefixes="container") def is_grasping(self, arm="default", candidate_obj=None): """ Returns True if the robot is grasping the target option @candidate_obj or any object if @candidate_obj is None. Args: arm (str): specific arm to check for grasping. Default is "default" which corresponds to the first entry in self.arm_names candidate_obj (StatefulObject or None): object to check if this robot is currently grasping. If None, then will be a general (object-agnostic) check for grasping. Note: if self.grasping_mode is "physical", then @candidate_obj will be ignored completely Returns: IsGraspingState: For the specific manipulator appendage, returns IsGraspingState.TRUE if it is grasping (potentially @candidate_obj if specified), IsGraspingState.FALSE if it is not grasping, and IsGraspingState.UNKNOWN if unknown. """ arm = self.default_arm if arm == "default" else arm if self.grasping_mode != "physical": is_grasping_obj = ( self._ag_obj_in_hand[arm] is not None if candidate_obj is None else self._ag_obj_in_hand[arm] == candidate_obj ) is_grasping = ( IsGraspingState.TRUE if is_grasping_obj and self._ag_release_counter[arm] is None else IsGraspingState.FALSE ) else: # Infer from the gripper controller the state is_grasping = self._controllers["gripper_{}".format(arm)].is_grasping() # If candidate obj is not None, we also check to see if our fingers are in contact with the object if is_grasping == IsGraspingState.TRUE and candidate_obj is not None: finger_links = {link for link in self.finger_links[arm]} is_grasping = len(candidate_obj.states[ContactBodies].get_value().intersection(finger_links)) > 0 return is_grasping def _find_gripper_contacts(self, arm="default", return_contact_positions=False): """ For arm @arm, calculate any body IDs and corresponding link IDs that are not part of the robot itself that are in contact with any of this arm's gripper's fingers Args: arm (str): specific arm whose gripper will be checked for contact. Default is "default" which corresponds to the first entry in self.arm_names return_contact_positions (bool): if True, will additionally return the contact (x,y,z) position Returns: 2-tuple: - set: set of unique contact prim_paths that are not the robot self-collisions. If @return_contact_positions is True, then returns (prim_path, pos), where pos is the contact (x,y,z) position Note: if no objects that are not the robot itself are intersecting, the set will be empty. - dict: dictionary mapping unique contact objects defined by the contact prim_path to set of unique robot link prim_paths that it is in contact with """ arm = self.default_arm if arm == "default" else arm robot_contact_links = dict() contact_data = set() # Find all objects in contact with all finger joints for this arm con_results = [con for link in self.finger_links[arm] for con in link.contact_list()] # Get robot contact links link_paths = set(self.link_prim_paths) for con_res in con_results: # Only add this contact if it's not a robot self-collision other_contact_set = {con_res.body0, con_res.body1} - link_paths if len(other_contact_set) == 1: link_contact, other_contact = (con_res.body0, con_res.body1) if \ list(other_contact_set)[0] == con_res.body1 else (con_res.body1, con_res.body0) # Add to contact data contact_data.add((other_contact, tuple(con_res.position)) if return_contact_positions else other_contact) # Also add robot contact link info if other_contact not in robot_contact_links: robot_contact_links[other_contact] = set() robot_contact_links[other_contact].add(link_contact) return contact_data, robot_contact_links def set_position_orientation(self, position=None, orientation=None): # Store the original EEF poses. original_poses = {} for arm in self.arm_names: original_poses[arm] = (self.get_eef_position(arm), self.get_eef_orientation(arm)) # Run the super method super().set_position_orientation(position=position, orientation=orientation) # Now for each hand, if it was holding an AG object, teleport it. for arm in self.arm_names: if self._ag_obj_in_hand[arm] is not None: original_eef_pose = T.pose2mat(original_poses[arm]) inv_original_eef_pose = T.pose_inv(pose_mat=original_eef_pose) original_obj_pose = T.pose2mat(self._ag_obj_in_hand[arm].get_position_orientation()) new_eef_pose = T.pose2mat((self.get_eef_position(arm), self.get_eef_orientation(arm))) # New object pose is transform: # original --> "De"transform the original EEF pose --> "Re"transform the new EEF pose new_obj_pose = new_eef_pose @ inv_original_eef_pose @ original_obj_pose self._ag_obj_in_hand[arm].set_position_orientation(*T.mat2pose(hmat=new_obj_pose)) def deploy_control(self, control, control_type, indices=None, normalized=False): # We intercept the gripper control and replace it with the current joint position if we're freezing our gripper for arm in self.arm_names: if self._ag_freeze_gripper[arm]: control[self.gripper_control_idx[arm]] = self._ag_obj_constraint_params[arm]["gripper_pos"] if \ self.controllers[f"gripper_{arm}"].control_type == ControlType.POSITION else 0.0 super().deploy_control(control=control, control_type=control_type, indices=indices, normalized=normalized) # Then run assisted grasping if self.grasping_mode != "physical" and not self._disable_grasp_handling: self._handle_assisted_grasping() # Potentially freeze gripper joints for arm in self.arm_names: if self._ag_freeze_gripper[arm]: self._freeze_gripper(arm) def _release_grasp(self, arm="default"): """ Magic action to release this robot's grasp on an object Args: arm (str): specific arm whose grasp will be released. Default is "default" which corresponds to the first entry in self.arm_names """ arm = self.default_arm if arm == "default" else arm # Remove joint and filtered collision restraints og.sim.stage.RemovePrim(self._ag_obj_constraint_params[arm]["ag_joint_prim_path"]) self._ag_obj_constraints[arm] = None self._ag_obj_constraint_params[arm] = {} self._ag_freeze_gripper[arm] = False self._ag_release_counter[arm] = 0 def release_grasp_immediately(self): """ Magic action to release this robot's grasp for all arms at once. As opposed to @_release_grasp, this method would byupass the release window mechanism and immediately release. """ for arm in self.arm_names: if self._ag_obj_in_hand[arm] is not None: self._release_grasp(arm=arm) self._ag_release_counter[arm] = int(np.ceil(m.RELEASE_WINDOW / og.sim.get_rendering_dt())) self._handle_release_window(arm=arm) assert not self._ag_obj_in_hand[arm], "Object still in ag list after release!" # TODO: Verify not needed! # for finger_link in self.finger_links[arm]: # finger_link.remove_filtered_collision_pair(prim=self._ag_obj_in_hand[arm]) def get_control_dict(self): # In addition to super method, add in EEF states fcns = super().get_control_dict() for arm in self.arm_names: self._add_arm_control_dict(fcns=fcns, arm=arm) return fcns def _add_arm_control_dict(self, fcns, arm): """ Internally helper function to generate per-arm control dictionary entries. Needed because otherwise generated functions inadvertently point to the same arm, if directly iterated in a for loop! Args: fcns (CachedFunctions): Keyword-mapped control values for this object, mapping names to n-arrays. arm (str): specific arm to generate necessary control dict entries for """ fcns[f"_eef_{arm}_pos_quat_relative"] = lambda: self.get_relative_eef_pose(arm) fcns[f"eef_{arm}_pos_relative"] = lambda: fcns[f"_eef_{arm}_pos_quat_relative"][0] fcns[f"eef_{arm}_quat_relative"] = lambda: fcns[f"_eef_{arm}_pos_quat_relative"][1] fcns[f"eef_{arm}_lin_vel_relative"] = lambda: self.get_relative_eef_lin_vel(arm) fcns[f"eef_{arm}_ang_vel_relative"] = lambda: self.get_relative_eef_ang_vel(arm) # -n_joints because there may be an additional 6 entries at the beginning of the array, if this robot does # not have a fixed base (i.e.: the 6DOF --> "floating" joint) # see self.get_relative_jacobian() for more info eef_link_idx = self._articulation_view.get_body_index(self.eef_links[arm].body_name) fcns[f"eef_{arm}_jacobian_relative"] = lambda: self.get_relative_jacobian(clone=False)[eef_link_idx, :, -self.n_joints:] def _get_proprioception_dict(self): dic = super()._get_proprioception_dict() # Loop over all arms to grab proprio info joint_positions = self.get_joint_positions(normalized=False) joint_velocities = self.get_joint_velocities(normalized=False) for arm in self.arm_names: # Add arm info dic["arm_{}_qpos".format(arm)] = joint_positions[self.arm_control_idx[arm]] dic["arm_{}_qpos_sin".format(arm)] = np.sin(joint_positions[self.arm_control_idx[arm]]) dic["arm_{}_qpos_cos".format(arm)] = np.cos(joint_positions[self.arm_control_idx[arm]]) dic["arm_{}_qvel".format(arm)] = joint_velocities[self.arm_control_idx[arm]] # Add eef and grasping info dic["eef_{}_pos_global".format(arm)] = self.get_eef_position(arm) dic["eef_{}_quat_global".format(arm)] = self.get_eef_orientation(arm) dic["eef_{}_pos".format(arm)] = self.get_relative_eef_position(arm) dic["eef_{}_quat".format(arm)] = self.get_relative_eef_orientation(arm) dic["grasp_{}".format(arm)] = np.array([self.is_grasping(arm)]) dic["gripper_{}_qpos".format(arm)] = joint_positions[self.gripper_control_idx[arm]] dic["gripper_{}_qvel".format(arm)] = joint_velocities[self.gripper_control_idx[arm]] return dic @property def default_proprio_obs(self): obs_keys = super().default_proprio_obs for arm in self.arm_names: obs_keys += [ "arm_{}_qpos_sin".format(arm), "arm_{}_qpos_cos".format(arm), "eef_{}_pos".format(arm), "eef_{}_quat".format(arm), "gripper_{}_qpos".format(arm), "grasp_{}".format(arm), ] return obs_keys @property def grasping_mode(self): """ Grasping mode of this robot. Is one of AG_MODES Returns: str: Grasping mode for this robot """ return self._grasping_mode @property def controller_order(self): # Assumes we have arm(s) and corresponding gripper(s) controllers = [] for arm in self.arm_names: controllers += ["arm_{}".format(arm), "gripper_{}".format(arm)] return controllers @property def _default_controllers(self): # Always call super first controllers = super()._default_controllers # For best generalizability use, joint controller as default for arm in self.arm_names: controllers["arm_{}".format(arm)] = "JointController" controllers["gripper_{}".format(arm)] = "JointController" return controllers @property def n_arms(self): """ Returns: int: Number of arms this robot has. Returns 1 by default """ return 1 @property def arm_names(self): """ Returns: list of str: List of arm names for this robot. Should correspond to the keys used to index into arm- and gripper-related dictionaries, e.g.: eef_link_names, finger_link_names, etc. Default is string enumeration based on @self.n_arms. """ return [str(i) for i in range(self.n_arms)] @property def default_arm(self): """ Returns: str: Default arm name for this robot, corresponds to the first entry in @arm_names by default """ return self.arm_names[0] @property def arm_action_idx(self): arm_action_idx = {} for arm_name in self.arm_names: controller_idx = self.controller_order.index(f"arm_{arm_name}") action_start_idx = sum([self.controllers[self.controller_order[i]].command_dim for i in range(controller_idx)]) arm_action_idx[arm_name] = np.arange(action_start_idx, action_start_idx + self.controllers[f"arm_{arm_name}"].command_dim) return arm_action_idx @property def gripper_action_idx(self): gripper_action_idx = {} for arm_name in self.arm_names: controller_idx = self.controller_order.index(f"gripper_{arm_name}") action_start_idx = sum([self.controllers[self.controller_order[i]].command_dim for i in range(controller_idx)]) gripper_action_idx[arm_name] = np.arange(action_start_idx, action_start_idx + self.controllers[f"gripper_{arm_name}"].command_dim) return gripper_action_idx @property @abstractmethod def arm_link_names(self): """ Returns: dict: Dictionary mapping arm appendage name to corresponding arm link names, should correspond to specific link names in this robot's underlying model file """ raise NotImplementedError @property @abstractmethod def arm_joint_names(self): """ Returns: dict: Dictionary mapping arm appendage name to corresponding arm joint names, should correspond to specific joint names in this robot's underlying model file """ raise NotImplementedError @property @abstractmethod def eef_link_names(self): """ Returns: dict: Dictionary mapping arm appendage name to corresponding name of the EEF link, should correspond to specific link name in this robot's underlying model file """ raise NotImplementedError @property @abstractmethod def finger_link_names(self): """ Returns: dict: Dictionary mapping arm appendage name to array of link names corresponding to this robot's fingers """ raise NotImplementedError @property @abstractmethod def finger_joint_names(self): """ Returns: dict: Dictionary mapping arm appendage name to array of joint names corresponding to this robot's fingers """ raise NotImplementedError @property @abstractmethod def arm_control_idx(self): """ Returns: dict: Dictionary mapping arm appendage name to indices in low-level control vector corresponding to arm joints. """ raise NotImplementedError @property @abstractmethod def gripper_control_idx(self): """ Returns: dict: Dictionary mapping arm appendage name to indices in low-level control vector corresponding to gripper joints. """ raise NotImplementedError @property def arm_links(self): """ Returns: dict: Dictionary mapping arm appendage name to robot links corresponding to that arm's links """ return {arm: [self._links[link] for link in self.arm_link_names[arm]] for arm in self.arm_names} @property def eef_links(self): """ Returns: dict: Dictionary mapping arm appendage name to robot link corresponding to that arm's eef link """ return {arm: self._links[self.eef_link_names[arm]] for arm in self.arm_names} @property def finger_links(self): """ Returns: dict: Dictionary mapping arm appendage name to robot links corresponding to that arm's finger links """ return {arm: [self._links[link] for link in self.finger_link_names[arm]] for arm in self.arm_names} @property def finger_joints(self): """ Returns: dict: Dictionary mapping arm appendage name to robot joints corresponding to that arm's finger joints """ return {arm: [self._joints[joint] for joint in self.finger_joint_names[arm]] for arm in self.arm_names} @property def assisted_grasp_start_points(self): """ Returns: dict: Dictionary mapping individual arm appendage names to array of GraspingPoint tuples, composed of (link_name, position) values specifying valid grasping start points located at cartesian (x,y,z) coordinates specified in link_name's local coordinate frame. These values will be used in conjunction with @self.assisted_grasp_end_points to trigger assisted grasps, where objects that intersect with any ray starting at any point in @self.assisted_grasp_start_points and terminating at any point in @self.assisted_grasp_end_points will trigger an assisted grasp (calculated individually for each gripper appendage). By default, each entry returns None, and must be implemented by any robot subclass that wishes to use assisted grasping. """ return {arm: None for arm in self.arm_names} @property def assisted_grasp_end_points(self): """ Returns: dict: Dictionary mapping individual arm appendage names to array of GraspingPoint tuples, composed of (link_name, position) values specifying valid grasping end points located at cartesian (x,y,z) coordinates specified in link_name's local coordinate frame. These values will be used in conjunction with @self.assisted_grasp_start_points to trigger assisted grasps, where objects that intersect with any ray starting at any point in @self.assisted_grasp_start_points and terminating at any point in @self.assisted_grasp_end_points will trigger an assisted grasp (calculated individually for each gripper appendage). By default, each entry returns None, and must be implemented by any robot subclass that wishes to use assisted grasping. """ return {arm: None for arm in self.arm_names} @property def finger_lengths(self): """ Returns: dict: Dictionary mapping arm appendage name to corresponding length of the fingers in that hand defined from the palm (assuming all fingers in one hand are equally long) """ raise NotImplementedError @property def arm_workspace_range(self): """ Returns: dict: Dictionary mapping arm appendage name to a tuple indicating the start and end of the angular range of the arm workspace around the Z axis of the robot, where 0 is facing forward. """ raise NotImplementedError def get_eef_position(self, arm="default"): """ Args: arm (str): specific arm to grab eef position. Default is "default" which corresponds to the first entry in self.arm_names Returns: 3-array: (x,y,z) global end-effector Cartesian position for this robot's end-effector corresponding to arm @arm """ arm = self.default_arm if arm == "default" else arm return self._links[self.eef_link_names[arm]].get_position() def get_eef_orientation(self, arm="default"): """ Args: arm (str): specific arm to grab eef orientation. Default is "default" which corresponds to the first entry in self.arm_names Returns: 3-array: (x,y,z,w) global quaternion orientation for this robot's end-effector corresponding to arm @arm """ arm = self.default_arm if arm == "default" else arm return self._links[self.eef_link_names[arm]].get_orientation() def get_relative_eef_pose(self, arm="default", mat=False): """ Args: arm (str): specific arm to grab eef pose. Default is "default" which corresponds to the first entry in self.arm_names mat (bool): whether to return pose in matrix form (mat=True) or (pos, quat) tuple (mat=False) Returns: 2-tuple or (4, 4)-array: End-effector pose, either in 4x4 homogeneous matrix form (if @mat=True) or (pos, quat) tuple (if @mat=False), corresponding to arm @arm """ arm = self.default_arm if arm == "default" else arm eef_link_pose = self.eef_links[arm].get_position_orientation() base_link_pose = self.get_position_orientation() pose = T.relative_pose_transform(*eef_link_pose, *base_link_pose) return T.pose2mat(pose) if mat else pose def get_relative_eef_position(self, arm="default"): """ Args: arm (str): specific arm to grab relative eef pos. Default is "default" which corresponds to the first entry in self.arm_names Returns: 3-array: (x,y,z) Cartesian position of end-effector relative to robot base frame """ arm = self.default_arm if arm == "default" else arm return self.get_relative_eef_pose(arm=arm)[0] def get_relative_eef_orientation(self, arm="default"): """ Args: arm (str): specific arm to grab relative eef orientation. Default is "default" which corresponds to the first entry in self.arm_names Returns: 4-array: (x,y,z,w) quaternion orientation of end-effector relative to robot base frame """ arm = self.default_arm if arm == "default" else arm return self.get_relative_eef_pose(arm=arm)[1] def get_relative_eef_lin_vel(self, arm="default"): """ Args: arm (str): specific arm to grab relative eef linear velocity. Default is "default" which corresponds to the first entry in self.arm_names Returns: 3-array: (x,y,z) Linear velocity of end-effector relative to robot base frame """ arm = self.default_arm if arm == "default" else arm base_link_quat = self.get_orientation() return T.quat2mat(base_link_quat).T @ self.eef_links[arm].get_linear_velocity() def get_relative_eef_ang_vel(self, arm="default"): """ Args: arm (str): specific arm to grab relative eef angular velocity. Default is "default" which corresponds to the first entry in self.arm_names Returns: 3-array: (ax,ay,az) angular velocity of end-effector relative to robot base frame """ arm = self.default_arm if arm == "default" else arm base_link_quat = self.get_orientation() return T.quat2mat(base_link_quat).T @ self.eef_links[arm].get_angular_velocity() def _calculate_in_hand_object_rigid(self, arm="default"): """ Calculates which object to assisted-grasp for arm @arm. Returns an (object_id, link_id) tuple or None if no valid AG-enabled object can be found. Args: arm (str): specific arm to calculate in-hand object for. Default is "default" which corresponds to the first entry in self.arm_names Returns: None or 2-tuple: If a valid assisted-grasp object is found, returns the corresponding (object, object_link) (i.e.: (BaseObject, RigidPrim)) pair to the contacted in-hand object. Otherwise, returns None """ arm = self.default_arm if arm == "default" else arm # If we're not using physical grasping, we check for gripper contact if self.grasping_mode != "physical": candidates_set, robot_contact_links = self._find_gripper_contacts(arm=arm) # If we're using assisted grasping, we further filter candidates via ray-casting if self.grasping_mode == "assisted": candidates_set_raycast = self._find_gripper_raycast_collisions(arm=arm) candidates_set = candidates_set.intersection(candidates_set_raycast) else: raise ValueError("Invalid grasping mode for calculating in hand object: {}".format(self.grasping_mode)) # Immediately return if there are no valid candidates if len(candidates_set) == 0: return None # Find the closest object to the gripper center gripper_center_pos = self.eef_links[arm].get_position() candidate_data = [] for prim_path in candidates_set: # Calculate position of the object link. Only allow this for objects currently. obj_prim_path, link_name = prim_path.rsplit("/", 1) candidate_obj = og.sim.scene.object_registry("prim_path", obj_prim_path, None) if candidate_obj is None or link_name not in candidate_obj.links: continue candidate_link = candidate_obj.links[link_name] dist = np.linalg.norm(np.array(candidate_link.get_position()) - np.array(gripper_center_pos)) candidate_data.append((prim_path, dist)) if not candidate_data: return None candidate_data = sorted(candidate_data, key=lambda x: x[-1]) ag_prim_path, _ = candidate_data[0] # Make sure the ag_prim_path is not a self collision assert ag_prim_path not in self.link_prim_paths, "assisted grasp object cannot be the robot itself!" # Make sure at least two fingers are in contact with this object robot_contacts = robot_contact_links[ag_prim_path] touching_at_least_two_fingers = True if self.grasping_mode == "sticky" else len({link.prim_path for link in self.finger_links[arm]}.intersection(robot_contacts)) >= 2 # TODO: Better heuristic, hacky, we assume the parent object prim path is the prim_path minus the last "/" item ag_obj_prim_path = "/".join(ag_prim_path.split("/")[:-1]) ag_obj_link_name = ag_prim_path.split("/")[-1] ag_obj = og.sim.scene.object_registry("prim_path", ag_obj_prim_path) # Return None if object cannot be assisted grasped or not touching at least two fingers if ag_obj is None or not touching_at_least_two_fingers: return None # Get object and its contacted link return ag_obj, ag_obj.links[ag_obj_link_name] def _find_gripper_raycast_collisions(self, arm="default"): """ For arm @arm, calculate any prims that are not part of the robot itself that intersect with rays cast between any of the gripper's start and end points Args: arm (str): specific arm whose gripper will be checked for raycast collisions. Default is "default" which corresponds to the first entry in self.arm_names Returns: set[str]: set of prim path of detected raycast intersections that are not the robot itself. Note: if no objects that are not the robot itself are intersecting, the set will be empty. """ arm = self.default_arm if arm == "default" else arm # First, make sure start and end grasp points exist (i.e.: aren't None) assert ( self.assisted_grasp_start_points[arm] is not None ), "In order to use assisted grasping, assisted_grasp_start_points must not be None!" assert ( self.assisted_grasp_end_points[arm] is not None ), "In order to use assisted grasping, assisted_grasp_end_points must not be None!" # Iterate over all start and end grasp points and calculate their x,y,z positions in the world frame # (per arm appendage) # Since we'll be calculating the cartesian cross product between start and end points, we stack the start points # by the number of end points and repeat the individual elements of the end points by the number of start points startpoints = [] endpoints = [] for grasp_start_point in self.assisted_grasp_start_points[arm]: # Get world coordinates of link base frame link_pos, link_orn = self.links[grasp_start_point.link_name].get_position_orientation() # Calculate grasp start point in world frame and add to startpoints start_point, _ = T.pose_transform(link_pos, link_orn, grasp_start_point.position, [0, 0, 0, 1]) startpoints.append(start_point) # Repeat for end points for grasp_end_point in self.assisted_grasp_end_points[arm]: # Get world coordinates of link base frame link_pos, link_orn = self.links[grasp_end_point.link_name].get_position_orientation() # Calculate grasp start point in world frame and add to endpoints end_point, _ = T.pose_transform(link_pos, link_orn, grasp_end_point.position, [0, 0, 0, 1]) endpoints.append(end_point) # Stack the start points and repeat the end points, and add these values to the raycast dicts n_startpoints, n_endpoints = len(startpoints), len(endpoints) raycast_startpoints = startpoints * n_endpoints raycast_endpoints = [] for endpoint in endpoints: raycast_endpoints += [endpoint] * n_startpoints ray_data = set() # Calculate raycasts from each start point to end point -- this is n_startpoints * n_endpoints total rays for result in raytest_batch(raycast_startpoints, raycast_endpoints, only_closest=True): if result["hit"]: # filter out self body parts (we currently assume that the robot cannot grasp itself) if self.prim_path not in result["rigidBody"]: ray_data.add(result["rigidBody"]) return ray_data def _handle_release_window(self, arm="default"): """ Handles releasing an object from arm @arm Args: arm (str): specific arm to handle release window. Default is "default" which corresponds to the first entry in self.arm_names """ arm = self.default_arm if arm == "default" else arm self._ag_release_counter[arm] += 1 time_since_release = self._ag_release_counter[arm] * og.sim.get_rendering_dt() if time_since_release >= m.RELEASE_WINDOW: self._ag_obj_in_hand[arm] = None self._ag_release_counter[arm] = None def _freeze_gripper(self, arm="default"): """ Freezes gripper finger joints - used in assisted grasping. Args: arm (str): specific arm to freeze gripper. Default is "default" which corresponds to the first entry in self.arm_names """ arm = self.default_arm if arm == "default" else arm for joint_name, j_val in self._ag_freeze_joint_pos[arm].items(): joint = self._joints[joint_name] joint.set_pos(pos=j_val) joint.set_vel(vel=0.0) @property def robot_arm_descriptor_yamls(self): """ Returns: dict: Dictionary mapping arm appendage name to files path to the descriptor of the robot for IK Controller. """ raise NotImplementedError @property def _default_arm_joint_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default controller config to control that robot's arm. Uses velocity control by default. """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "JointController", "control_freq": self._control_freq, "control_limits": self.control_limits, "dof_idx": self.arm_control_idx[arm], "command_output_limits": None, "motor_type": "position", "use_delta_commands": True, "use_impedances": True, } return dic @property def _default_arm_ik_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default controller config for an Inverse kinematics controller to control this robot's arm """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "InverseKinematicsController", "task_name": f"eef_{arm}", "robot_description_path": self.robot_arm_descriptor_yamls[arm], "robot_urdf_path": self.urdf_path, "eef_name": self.eef_link_names[arm], "control_freq": self._control_freq, "reset_joint_pos": self.reset_joint_pos, "control_limits": self.control_limits, "dof_idx": self.arm_control_idx[arm], "command_output_limits": ( np.array([-0.2, -0.2, -0.2, -0.5, -0.5, -0.5]), np.array([0.2, 0.2, 0.2, 0.5, 0.5, 0.5]), ), "mode": "pose_delta_ori", "smoothing_filter_size": 2, "workspace_pose_limiter": None, } return dic @property def _default_arm_osc_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default controller config for an operational space controller to control this robot's arm """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "OperationalSpaceController", "task_name": f"eef_{arm}", "control_freq": self._control_freq, "reset_joint_pos": self.reset_joint_pos, "control_limits": self.control_limits, "dof_idx": self.arm_control_idx[arm], "command_output_limits": ( np.array([-0.2, -0.2, -0.2, -0.5, -0.5, -0.5]), np.array([0.2, 0.2, 0.2, 0.5, 0.5, 0.5]), ), "mode": "pose_delta_ori", "workspace_pose_limiter": None, } return dic @property def _default_arm_null_joint_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default arm null controller config to control this robot's arm i.e. dummy controller """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "NullJointController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.arm_control_idx[arm], "default_command": self.reset_joint_pos[self.arm_control_idx[arm]], "use_impedances": False, } return dic @property def _default_gripper_multi_finger_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default controller config to control this robot's multi finger gripper. Assumes robot gripper idx has exactly two elements """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "MultiFingerGripperController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.gripper_control_idx[arm], "command_output_limits": "default", "mode": "binary", "limit_tolerance": 0.001, } return dic @property def _default_gripper_joint_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default gripper joint controller config to control this robot's gripper """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "JointController", "control_freq": self._control_freq, "motor_type": "velocity", "control_limits": self.control_limits, "dof_idx": self.gripper_control_idx[arm], "command_output_limits": "default", "use_delta_commands": False, "use_impedances": False, } return dic @property def _default_gripper_null_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default gripper null controller config to control this robot's (non-prehensile) gripper i.e. dummy controller """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "NullJointController", "control_freq": self._control_freq, "motor_type": "velocity", "control_limits": self.control_limits, "dof_idx": self.gripper_control_idx[arm], "default_command": np.zeros(len(self.gripper_control_idx[arm])), "use_impedances": False, } return dic @property def _default_controller_config(self): # Always run super method first cfg = super()._default_controller_config arm_ik_configs = self._default_arm_ik_controller_configs arm_osc_configs = self._default_arm_osc_controller_configs arm_joint_configs = self._default_arm_joint_controller_configs arm_null_joint_configs = self._default_arm_null_joint_controller_configs gripper_pj_configs = self._default_gripper_multi_finger_controller_configs gripper_joint_configs = self._default_gripper_joint_controller_configs gripper_null_configs = self._default_gripper_null_controller_configs # Add arm and gripper defaults, per arm for arm in self.arm_names: cfg["arm_{}".format(arm)] = { arm_ik_configs[arm]["name"]: arm_ik_configs[arm], arm_osc_configs[arm]["name"]: arm_osc_configs[arm], arm_joint_configs[arm]["name"]: arm_joint_configs[arm], arm_null_joint_configs[arm]["name"]: arm_null_joint_configs[arm], } cfg["gripper_{}".format(arm)] = { gripper_pj_configs[arm]["name"]: gripper_pj_configs[arm], gripper_joint_configs[arm]["name"]: gripper_joint_configs[arm], gripper_null_configs[arm]["name"]: gripper_null_configs[arm], } return cfg def _get_assisted_grasp_joint_type(self, ag_obj, ag_link): """ Check whether an object @obj can be grasped. If so, return the joint type to use for assisted grasping. Otherwise, return None. Args: ag_obj (BaseObject): Object targeted for an assisted grasp ag_link (RigidPrim): Link of the object to be grasped Returns: (None or str): If obj can be grasped, returns the joint type to use for assisted grasping. """ # Deny objects that are too heavy and are not a non-base link of a fixed-base object) mass = ag_link.mass if mass > m.ASSIST_GRASP_MASS_THRESHOLD and not (ag_obj.fixed_base and ag_link != ag_obj.root_link): return None # Otherwise, compute the joint type. We use a fixed joint unless the link is a non-fixed link. # A link is non-fixed if it has any non-fixed parent joints. joint_type = "FixedJoint" for edge in nx.edge_dfs(ag_obj.articulation_tree, ag_link.body_name, orientation="reverse"): joint = ag_obj.articulation_tree.edges[edge]["joint"] if joint.joint_type != JointType.JOINT_FIXED: joint_type = "SphericalJoint" break return joint_type def _establish_grasp_rigid(self, arm="default", ag_data=None, contact_pos=None): """ Establishes an ag-assisted grasp, if enabled. Args: arm (str): specific arm to establish grasp. Default is "default" which corresponds to the first entry in self.arm_names ag_data (None or 2-tuple): if specified, assisted-grasp object, link tuple (i.e. :(BaseObject, RigidPrim)). Otherwise, does a no-op contact_pos (None or np.array): if specified, contact position to use for grasp. """ arm = self.default_arm if arm == "default" else arm # Return immediately if ag_data is None if ag_data is None: return ag_obj, ag_link = ag_data # Get the appropriate joint type joint_type = self._get_assisted_grasp_joint_type(ag_obj, ag_link) if joint_type is None: return if contact_pos is None: force_data, _ = self._find_gripper_contacts(arm=arm, return_contact_positions=True) for c_link_prim_path, c_contact_pos in force_data: if c_link_prim_path == ag_link.prim_path: contact_pos = np.array(c_contact_pos) break assert contact_pos is not None # Joint frame set at the contact point # Need to find distance between robot and contact point in robot link's local frame and # ag link and contact point in ag link's local frame joint_frame_pos = contact_pos joint_frame_orn = np.array([0, 0, 0, 1.0]) eef_link_pos, eef_link_orn = self.eef_links[arm].get_position_orientation() parent_frame_pos, parent_frame_orn = T.relative_pose_transform(joint_frame_pos, joint_frame_orn, eef_link_pos, eef_link_orn) obj_link_pos, obj_link_orn = ag_link.get_position_orientation() child_frame_pos, child_frame_orn = T.relative_pose_transform(joint_frame_pos, joint_frame_orn, obj_link_pos, obj_link_orn) # Create the joint joint_prim_path = f"{self.eef_links[arm].prim_path}/ag_constraint" joint_prim = create_joint( prim_path=joint_prim_path, joint_type=joint_type, body0=self.eef_links[arm].prim_path, body1=ag_link.prim_path, enabled=True, joint_frame_in_parent_frame_pos=parent_frame_pos / self.scale, joint_frame_in_parent_frame_quat=parent_frame_orn, joint_frame_in_child_frame_pos=child_frame_pos / ag_obj.scale, joint_frame_in_child_frame_quat=child_frame_orn, ) # Save a reference to this joint prim self._ag_obj_constraints[arm] = joint_prim # Modify max force based on user-determined assist parameters # TODO max_force = m.ASSIST_FORCE if joint_type == "FixedJoint" else m.ASSIST_FORCE * m.ARTICULATED_ASSIST_FRACTION # joint_prim.GetAttribute("physics:breakForce").Set(max_force) self._ag_obj_constraint_params[arm] = { "ag_obj_prim_path": ag_obj.prim_path, "ag_link_prim_path": ag_link.prim_path, "ag_joint_prim_path": joint_prim_path, "joint_type": joint_type, "gripper_pos": self.get_joint_positions()[self.gripper_control_idx[arm]], "max_force": max_force, "contact_pos": contact_pos, } self._ag_obj_in_hand[arm] = ag_obj self._ag_freeze_gripper[arm] = True for joint in self.finger_joints[arm]: j_val = joint.get_state()[0][0] self._ag_freeze_joint_pos[arm][joint.joint_name] = j_val def _handle_assisted_grasping(self): """ Handles assisted grasping by creating or removing constraints. """ # Loop over all arms for arm in self.arm_names: # We apply a threshold based on the control rather than the command here so that the behavior # stays the same across different controllers and control modes (absolute / delta). This way, # a zero action will actually keep the AG setting where it already is. controller = self._controllers[f"gripper_{arm}"] controlled_joints = controller.dof_idx threshold = np.mean([self.joint_lower_limits[controlled_joints], self.joint_upper_limits[controlled_joints]], axis=0) if controller.control is None: applying_grasp = False elif self._grasping_direction == "lower": applying_grasp = np.any(controller.control < threshold) else: applying_grasp = np.any(controller.control > threshold) # Execute gradual release of object if self._ag_obj_in_hand[arm]: if self._ag_release_counter[arm] is not None: self._handle_release_window(arm=arm) else: if gm.AG_CLOTH: self._update_constraint_cloth(arm=arm) if not applying_grasp: self._release_grasp(arm=arm) elif applying_grasp: self._establish_grasp(arm=arm, ag_data=self._calculate_in_hand_object(arm=arm)) def _update_constraint_cloth(self, arm="default"): """ Update the AG constraint for cloth: for the fixed joint between the attachment point and the world, we set the local pos to match the current eef link position plus the attachment_point_pos_local offset. As a result, the joint will drive the attachment point to the updated position, which will then drive the cloth. See _establish_grasp_cloth for more details. Args: arm (str): specific arm to establish grasp. Default is "default" which corresponds to the first entry in self.arm_names """ attachment_point_pos_local = self._ag_obj_constraint_params[arm]["attachment_point_pos_local"] eef_link_pos, eef_link_orn = self.eef_links[arm].get_position_orientation() attachment_point_pos, _ = T.pose_transform(eef_link_pos, eef_link_orn, attachment_point_pos_local, [0, 0, 0, 1]) joint_prim = self._ag_obj_constraints[arm] joint_prim.GetAttribute("physics:localPos1").Set(lazy.pxr.Gf.Vec3f(*attachment_point_pos.astype(float))) def _calculate_in_hand_object(self, arm="default"): if gm.AG_CLOTH: return self._calculate_in_hand_object_cloth(arm) else: return self._calculate_in_hand_object_rigid(arm) def _establish_grasp(self, arm="default", ag_data=None, contact_pos=None): if gm.AG_CLOTH: return self._establish_grasp_cloth(arm, ag_data) else: return self._establish_grasp_rigid(arm, ag_data, contact_pos) def _calculate_in_hand_object_cloth(self, arm="default"): """ Same as _calculate_in_hand_object_rigid, except for cloth. Only one should be used at any given time. Calculates which object to assisted-grasp for arm @arm. Returns an (BaseObject, RigidPrim, np.ndarray) tuple or None if no valid AG-enabled object can be found. 1) Check if the gripper is closed enough 2) Go through each of the cloth object, and check if its attachment point link position is within the "ghost" box volume of the gripper link. Only returns the first valid object and ignore the rest. Args: arm (str): specific arm to establish grasp. Default is "default" which corresponds to the first entry in self.arm_names Returns: None or 3-tuple: If a valid assisted-grasp object is found, returns the corresponding (object, object_link, attachment_point_position), i.e. ((BaseObject, RigidPrim, np.ndarray)) to the contacted in-hand object. Otherwise, returns None """ # TODO (eric): Assume joint_pos = 0 means fully closed GRIPPER_FINGER_CLOSE_THRESHOLD = 0.03 gripper_finger_pos = self.get_joint_positions()[self.gripper_control_idx[arm]] gripper_finger_close = np.sum(gripper_finger_pos) < GRIPPER_FINGER_CLOSE_THRESHOLD if not gripper_finger_close: return None cloth_objs = og.sim.scene.object_registry("prim_type", PrimType.CLOTH) if cloth_objs is None: return None # TODO (eric): Only AG one cloth at any given moment. # Returns the first cloth that overlaps with the "ghost" box volume for cloth_obj in cloth_objs: attachment_point_pos = cloth_obj.links["attachment_point"].get_position() particles_in_volume = self._ag_check_in_volume[arm]([attachment_point_pos]) if particles_in_volume.sum() > 0: return cloth_obj, cloth_obj.links["attachment_point"], attachment_point_pos return None def _establish_grasp_cloth(self, arm="default", ag_data=None): """ Same as _establish_grasp_cloth, except for cloth. Only one should be used at any given time. Establishes an ag-assisted grasp, if enabled. Create a fixed joint between the attachment point link of the cloth object and the world. In theory, we could have created a fixed joint to the eef link, but omni doesn't support this as the robot has an articulation root API attached to it, which is incompatible with the attachment API. We also store attachment_point_pos_local as the attachment point position in the eef link frame when the fixed joint is created. As the eef link frame changes its pose, we will use attachment_point_pos_local to figure out the new attachment_point_pos in the world frame and set the fixed joint to there. See _update_constraint_cloth for more details. Args: arm (str): specific arm to establish grasp. Default is "default" which corresponds to the first entry in self.arm_names ag_data (None or 3-tuple): If specified, should be the corresponding (object, object_link, attachment_point_position), i.e. ((BaseObject, RigidPrim, np.ndarray)) to the] contacted in-hand object """ arm = self.default_arm if arm == "default" else arm # Return immediately if ag_data is None if ag_data is None: return ag_obj, ag_link, attachment_point_pos = ag_data # Find the attachment point position in the eef frame eef_link_pos, eef_link_orn = self.eef_links[arm].get_position_orientation() attachment_point_pos_local, _ = \ T.relative_pose_transform(attachment_point_pos, [0, 0, 0, 1], eef_link_pos, eef_link_orn) # Create the joint joint_prim_path = f"{ag_link.prim_path}/ag_constraint" joint_type = "FixedJoint" joint_prim = create_joint( prim_path=joint_prim_path, joint_type=joint_type, body0=ag_link.prim_path, body1=None, enabled=False, joint_frame_in_child_frame_pos=attachment_point_pos, ) # Save a reference to this joint prim self._ag_obj_constraints[arm] = joint_prim # Modify max force based on user-determined assist parameters # TODO max_force = m.ASSIST_FORCE # joint_prim.GetAttribute("physics:breakForce").Set(max_force) self._ag_obj_constraint_params[arm] = { "ag_obj_prim_path": ag_obj.prim_path, "ag_link_prim_path": ag_link.prim_path, "ag_joint_prim_path": joint_prim_path, "joint_type": joint_type, "gripper_pos": self.get_joint_positions()[self.gripper_control_idx[arm]], "max_force": max_force, "attachment_point_pos_local": attachment_point_pos_local, "contact_pos": attachment_point_pos, } self._ag_obj_in_hand[arm] = ag_obj self._ag_freeze_gripper[arm] = True for joint in self.finger_joints[arm]: j_val = joint.get_state()[0][0] self._ag_freeze_joint_pos[arm][joint.joint_name] = j_val def _dump_state(self): # Call super first state = super()._dump_state() # If we're using actual physical grasping, no extra state needed to save if self.grasping_mode == "physical": return state # Include AG_state state["ag_obj_constraint_params"] = self._ag_obj_constraint_params.copy() return state def _load_state(self, state): # If there is an existing AG object, remove it self.release_grasp_immediately() super()._load_state(state=state) # No additional loading needed if we're using physical grasping if self.grasping_mode == "physical": return # Include AG_state # TODO: currently does not take care of cloth objects # TODO: add unit tests for arm in state["ag_obj_constraint_params"].keys(): if len(state["ag_obj_constraint_params"][arm]) > 0: data = state["ag_obj_constraint_params"][arm] obj = og.sim.scene.object_registry("prim_path", data["ag_obj_prim_path"]) link = obj.links[data["ag_link_prim_path"].split("/")[-1]] self._establish_grasp(arm=arm, ag_data=(obj, link), contact_pos=data["contact_pos"]) def _serialize(self, state): # Call super first state_flat = super()._serialize(state=state) # No additional serialization needed if we're using physical grasping if self.grasping_mode == "physical": return state_flat # TODO AG return state_flat def _deserialize(self, state): # Call super first state_dict, idx = super()._deserialize(state=state) # No additional deserialization needed if we're using physical grasping if self.grasping_mode == "physical": return state_dict, idx # TODO AG return state_dict, idx @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("ManipulationRobot") return classes @property def eef_usd_path(self): """ Returns: dict(str, str): dict mapping arm name to the path to the eef usd file """ raise NotImplementedError @property def teleop_rotation_offset(self): """ Rotational offset that will be applied for teleoperation such that [0, 0, 0, 1] as action will keep the robot eef pointing at +x axis """ return {arm: np.array([0, 0, 0, 1]) for arm in self.arm_names} def teleop_data_to_action(self, teleop_action) -> np.ndarray: """ Generate action data from teleoperation action data NOTE: This implementation only supports IK/OSC controller for arm and MultiFingerGripperController for gripper. Overwrite this function if the robot is using a different controller. Args: teleop_action (TeleopAction): teleoperation action data Returns: np.ndarray: array of action data for arm and gripper """ action = super().teleop_data_to_action(teleop_action) hands = ["left", "right"] if self.n_arms == 2 else ["right"] for i, hand in enumerate(hands): arm_name = self.arm_names[i] arm_action = teleop_action[hand] # arm action assert \ isinstance(self._controllers[f"arm_{arm_name}"], InverseKinematicsController) or \ isinstance(self._controllers[f"arm_{arm_name}"], OperationalSpaceController), \ f"Only IK and OSC controllers are supported for arm {arm_name}!" target_pos, target_orn = arm_action[:3], T.quat2axisangle(T.euler2quat(arm_action[3:6])) action[self.arm_action_idx[arm_name]] = np.r_[target_pos, target_orn] # gripper action assert isinstance(self._controllers[f"gripper_{arm_name}"], MultiFingerGripperController), \ f"Only MultiFingerGripperController is supported for gripper {arm_name}!" action[self.gripper_action_idx[arm_name]] = arm_action[6] return action
69,213
Python
45.050566
174
0.612515
StanfordVL/OmniGibson/omnigibson/robots/freight.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.robots.two_wheel_robot import TwoWheelRobot class Freight(TwoWheelRobot): """ Freight Robot Reference: https://fetchrobotics.com/robotics-platforms/freight-base/ Uses joint velocity control """ @property def model_name(self): return "Freight" @property def wheel_radius(self): return 0.0613 @property def wheel_axle_length(self): return 0.372 @property def base_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to [Left, Right] wheel joints. """ return np.array([0, 1]) @property def _default_joint_pos(self): return np.zeros(self.n_joints) @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/fetch/freight/freight.usd") @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/fetch/freight.urdf")
1,035
Python
21.521739
101
0.638647
StanfordVL/OmniGibson/omnigibson/robots/locobot.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.robots.two_wheel_robot import TwoWheelRobot class Locobot(TwoWheelRobot): """ Locobot robot Reference: https://www.trossenrobotics.com/locobot-pyrobot-ros-rover.aspx """ @property def model_name(self): return "Locobot" @property def wheel_radius(self): return 0.038 @property def wheel_axle_length(self): return 0.230 @property def base_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to [Left, Right] wheel joints. """ return np.array([1, 0]) @property def _default_joint_pos(self): return np.zeros(self.n_joints) @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/locobot/locobot/locobot.usd") @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/locobot/locobot.urdf")
1,010
Python
21.466666
101
0.636634
StanfordVL/OmniGibson/omnigibson/robots/franka.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.robots.manipulation_robot import ManipulationRobot, GraspingPoint from omnigibson.utils.transform_utils import euler2quat class FrankaPanda(ManipulationRobot): """ The Franka Emika Panda robot """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=True, load_config=None, fixed_base=True, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. If "sticky", will magnetize any object touching the gripper's fingers. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Run super init super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, grasping_mode=grasping_mode, **kwargs, ) @property def model_name(self): return "FrankaPanda" @property def discrete_action_list(self): # Not supported for this robot raise NotImplementedError() def _create_discrete_action_space(self): # Fetch does not support discrete actions raise ValueError("Franka does not support discrete actions!") def update_controller_mode(self): super().update_controller_mode() # overwrite joint params (e.g. damping, stiffess, max_effort) here @property def controller_order(self): return ["arm_{}".format(self.default_arm), "gripper_{}".format(self.default_arm)] @property def _default_controllers(self): controllers = super()._default_controllers controllers["arm_{}".format(self.default_arm)] = "InverseKinematicsController" controllers["gripper_{}".format(self.default_arm)] = "MultiFingerGripperController" return controllers @property def _default_joint_pos(self): return np.array([0.00, -1.3, 0.00, -2.87, 0.00, 2.00, 0.75, 0.00, 0.00]) @property def finger_lengths(self): return {self.default_arm: 0.1} @property def arm_control_idx(self): return {self.default_arm: np.arange(7)} @property def gripper_control_idx(self): return {self.default_arm: np.arange(7, 9)} @property def arm_link_names(self): return {self.default_arm: [f"panda_link{i}" for i in range(8)]} @property def arm_joint_names(self): return {self.default_arm: [f"panda_joint_{i+1}" for i in range(7)]} @property def eef_link_names(self): return {self.default_arm: "panda_hand"} @property def finger_link_names(self): return {self.default_arm: ["panda_leftfinger", "panda_rightfinger"]} @property def finger_joint_names(self): return {self.default_arm: ["panda_finger_joint1", "panda_finger_joint2"]} @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/franka/franka_panda.usd") @property def robot_arm_descriptor_yamls(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/franka/franka_panda_description.yaml")} @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/franka/franka_panda.urdf") @property def eef_usd_path(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/franka/franka_panda_eef.usd")} @property def teleop_rotation_offset(self): return {self.default_arm: euler2quat([-np.pi, 0, 0])} @property def assisted_grasp_start_points(self): return {self.default_arm: [ GraspingPoint(link_name="panda_rightfinger", position=[0.0, 0.001, 0.045]), ]} @property def assisted_grasp_end_points(self): return {self.default_arm: [ GraspingPoint(link_name="panda_leftfinger", position=[0.0, 0.001, 0.045]), ]}
9,169
Python
42.254717
126
0.637147
StanfordVL/OmniGibson/omnigibson/robots/robot_base.py
from abc import abstractmethod from copy import deepcopy import numpy as np import matplotlib.pyplot as plt from omnigibson.macros import create_module_macros from omnigibson.sensors import create_sensor, SENSOR_PRIMS_TO_SENSOR_CLS, ALL_SENSOR_MODALITIES, VisionSensor, ScanSensor from omnigibson.objects.usd_object import USDObject from omnigibson.objects.object_base import BaseObject from omnigibson.objects.controllable_object import ControllableObject from omnigibson.utils.gym_utils import GymObservable from omnigibson.utils.usd_utils import add_asset_to_stage from omnigibson.utils.python_utils import classproperty, merge_nested_dicts from omnigibson.utils.vision_utils import segmentation_to_rgb from omnigibson.utils.constants import PrimType # Global dicts that will contain mappings REGISTERED_ROBOTS = dict() # Add proprio sensor modality to ALL_SENSOR_MODALITIES ALL_SENSOR_MODALITIES.add("proprio") # Create settings for this module m = create_module_macros(module_path=__file__) # Name of the category to assign to all robots m.ROBOT_CATEGORY = "agent" class BaseRobot(USDObject, ControllableObject, GymObservable): """ Base class for USD-based robot agents. This class handles object loading, and provides method interfaces that should be implemented by subclassed robots. """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, fixed_base=False, visual_only=False, self_collisions=False, load_config=None, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to this class obs_modalities="all", proprio_obs="default", sensor_config=None, **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage fixed_base (bool): whether to fix the base of this object or not visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be at the render frequency by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ # Store inputs self._obs_modalities = obs_modalities if obs_modalities == "all" else \ {obs_modalities} if isinstance(obs_modalities, str) else set(obs_modalities) # this will get updated later when we fill in our sensors self._proprio_obs = self.default_proprio_obs if proprio_obs == "default" else list(proprio_obs) self._sensor_config = sensor_config # Process abilities robot_abilities = {"robot": {}} abilities = robot_abilities if abilities is None else robot_abilities.update(abilities) # Initialize internal attributes that will be loaded later self._sensors = None # e.g.: scan sensor, vision sensor self._dummy = None # Dummy version of the robot w/ fixed base for computing generalized gravity forces # If specified, make sure scale is uniform -- this is because non-uniform scale can result in non-matching # collision representations for parts of the robot that were optimized (e.g.: bounding sphere for wheels) assert scale is None or isinstance(scale, int) or isinstance(scale, float) or np.all(scale == scale[0]), \ f"Robot scale must be uniform! Got: {scale}" # Run super init super().__init__( prim_path=prim_path, usd_path=self.usd_path, name=name, category=m.ROBOT_CATEGORY, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, prim_type=PrimType.RIGID, include_default_states=True, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, **kwargs, ) def _load(self): # Run super first prim = super()._load() # Also import dummy object if this robot is not fixed base if self._use_dummy: dummy_path = f"{self._prim_path}_dummy" dummy_prim = add_asset_to_stage(asset_path=self._dummy_usd_path, prim_path=dummy_path) self._dummy = BaseObject( name=f"{self.name}_dummy", prim_path=dummy_path, scale=self._load_config.get("scale", None), visible=False, fixed_base=True, visual_only=True, ) return prim def _post_load(self): # Run super post load first super()._post_load() # Load the sensors self._load_sensors() def _initialize(self): # Initialize the dummy first if it exists if self._dummy is not None: self._dummy.initialize() # Run super super()._initialize() # Initialize all sensors for sensor in self._sensors.values(): sensor.initialize() # Load the observation space for this robot self.load_observation_space() # Validate this robot configuration self._validate_configuration() self._reset_joint_pos_aabb_extent = self.aabb_extent def _load_sensors(self): """ Loads sensor(s) to retrieve observations from this object. Stores created sensors as dictionary mapping sensor names to specific sensor instances used by this object. """ # Populate sensor config self._sensor_config = self._generate_sensor_config(custom_config=self._sensor_config) # Search for any sensors this robot might have attached to any of its links self._sensors = dict() obs_modalities = set() for link_name, link in self._links.items(): # Search through all children prims and see if we find any sensor sensor_counts = {p: 0 for p in SENSOR_PRIMS_TO_SENSOR_CLS.keys()} for prim in link.prim.GetChildren(): prim_type = prim.GetPrimTypeInfo().GetTypeName() if prim_type in SENSOR_PRIMS_TO_SENSOR_CLS: # Infer what obs modalities to use for this sensor sensor_cls = SENSOR_PRIMS_TO_SENSOR_CLS[prim_type] sensor_kwargs = self._sensor_config[sensor_cls.__name__] if "modalities" not in sensor_kwargs: sensor_kwargs["modalities"] = sensor_cls.all_modalities if self._obs_modalities == "all" else \ sensor_cls.all_modalities.intersection(self._obs_modalities) obs_modalities = obs_modalities.union(sensor_kwargs["modalities"]) # Create the sensor and store it internally sensor = create_sensor( sensor_type=prim_type, prim_path=str(prim.GetPrimPath()), name=f"{self.name}:{link_name}:{prim_type}:{sensor_counts[prim_type]}", **sensor_kwargs, ) self._sensors[sensor.name] = sensor sensor_counts[prim_type] += 1 # Since proprioception isn't an actual sensor, we need to possibly manually add it here as well if self._obs_modalities == "all" or "proprio" in self._obs_modalities: obs_modalities.add("proprio") # Update our overall obs modalities self._obs_modalities = obs_modalities def _generate_sensor_config(self, custom_config=None): """ Generates a fully-populated sensor config, overriding any default values with the corresponding values specified in @custom_config Args: custom_config (None or Dict[str, ...]): nested dictionary mapping sensor class name(s) to specific custom sensor configurations for this object. This will override any default values specified by this class Returns: dict: Fully-populated nested dictionary mapping sensor class name(s) to specific sensor configurations for this object """ sensor_config = {} if custom_config is None else deepcopy(custom_config) # Merge the sensor dictionaries sensor_config = merge_nested_dicts( base_dict=self._default_sensor_config, extra_dict=sensor_config, ) return sensor_config def _validate_configuration(self): """ Run any needed sanity checks to make sure this robot was created correctly. """ pass def step(self): # Skip this step if our articulation view is not valid if self._articulation_view_direct is None or not self._articulation_view_direct.initialized: return # Before calling super, update the dummy robot's kinematic state based on this robot's kinematic state # This is done prior to any state getter calls, since setting kinematic state results in physx backend # having to re-fetch tensorized state. # We do this so we have more optimal runtime performance if self._use_dummy: self._dummy.set_joint_positions(self.get_joint_positions()) self._dummy.set_joint_velocities(self.get_joint_velocities()) self._dummy.set_position_orientation(*self.get_position_orientation()) super().step() def get_obs(self): """ Grabs all observations from the robot. This is keyword-mapped based on each observation modality (e.g.: proprio, rgb, etc.) Returns: 2-tuple: dict: Keyword-mapped dictionary mapping observation modality names to observations (usually np arrays) dict: Keyword-mapped dictionary mapping observation modality names to additional info """ # Our sensors already know what observation modalities it has, so we simply iterate over all of them # and grab their observations, processing them into a flat dict obs_dict = dict() info_dict = dict() for sensor_name, sensor in self._sensors.items(): obs_dict[sensor_name], info_dict[sensor_name] = sensor.get_obs() # Have to handle proprio separately since it's not an actual sensor if "proprio" in self._obs_modalities: obs_dict["proprio"], info_dict["proprio"] = self.get_proprioception() return obs_dict, info_dict def get_proprioception(self): """ Returns: n-array: numpy array of all robot-specific proprioceptive observations. dict: empty dictionary, a placeholder for additional info """ proprio_dict = self._get_proprioception_dict() return np.concatenate([proprio_dict[obs] for obs in self._proprio_obs]), {} def _get_proprioception_dict(self): """ Returns: dict: keyword-mapped proprioception observations available for this robot. Can be extended by subclasses """ joint_positions = self.get_joint_positions(normalized=False) joint_velocities = self.get_joint_velocities(normalized=False) joint_efforts = self.get_joint_efforts(normalized=False) pos, ori = self.get_position(), self.get_rpy() ori_2d = self.get_2d_orientation() return dict( joint_qpos=joint_positions, joint_qpos_sin=np.sin(joint_positions), joint_qpos_cos=np.cos(joint_positions), joint_qvel=joint_velocities, joint_qeffort=joint_efforts, robot_pos=pos, robot_ori_cos=np.cos(ori), robot_ori_sin=np.sin(ori), robot_2d_ori=ori_2d, robot_2d_ori_cos=np.cos(ori_2d), robot_2d_ori_sin=np.sin(ori_2d), robot_lin_vel=self.get_linear_velocity(), robot_ang_vel=self.get_angular_velocity(), ) def _load_observation_space(self): # We compile observation spaces from our sensors obs_space = dict() for sensor_name, sensor in self._sensors.items(): # Load the sensor observation space obs_space[sensor_name] = sensor.load_observation_space() # Have to handle proprio separately since it's not an actual sensor if "proprio" in self._obs_modalities: obs_space["proprio"] = self._build_obs_box_space(shape=(self.proprioception_dim,), low=-np.inf, high=np.inf, dtype=np.float64) return obs_space def add_obs_modality(self, modality): """ Adds observation modality @modality to this robot. Note: Should be one of omnigibson.sensors.ALL_SENSOR_MODALITIES Args: modality (str): Observation modality to add to this robot """ # Iterate over all sensors we own, and if the requested modality is a part of its possible valid modalities, # then we add it for sensor in self._sensors.values(): if modality in sensor.all_modalities: sensor.add_modality(modality=modality) def remove_obs_modality(self, modality): """ Remove observation modality @modality from this robot. Note: Should be one of omnigibson.sensors.ALL_SENSOR_MODALITIES Args: modality (str): Observation modality to remove from this robot """ # Iterate over all sensors we own, and if the requested modality is a part of its possible valid modalities, # then we remove it for sensor in self._sensors.values(): if modality in sensor.all_modalities: sensor.remove_modality(modality=modality) def visualize_sensors(self): """ Renders this robot's key sensors, visualizing them via matplotlib plots """ frames = dict() remaining_obs_modalities = deepcopy(self.obs_modalities) for sensor in self.sensors.values(): obs, _ = sensor.get_obs() sensor_frames = [] if isinstance(sensor, VisionSensor): # We check for rgb, depth, normal, seg_instance for modality in ["rgb", "depth", "normal", "seg_instance"]: if modality in sensor.modalities: ob = obs[modality] if modality == "rgb": # Ignore alpha channel, map to floats ob = ob[:, :, :3] / 255.0 elif modality == "seg_instance": # Map IDs to rgb ob = segmentation_to_rgb(ob, N=256) / 255.0 elif modality == "normal": # Re-map to 0 - 1 range ob = (ob + 1.0) / 2.0 else: # Depth, nothing to do here pass # Add this observation to our frames and remove the modality sensor_frames.append((modality, ob)) remaining_obs_modalities -= {modality} else: # Warn user that we didn't find this modality print(f"Modality {modality} is not active in sensor {sensor.name}, skipping...") elif isinstance(sensor, ScanSensor): # We check for occupancy_grid occupancy_grid = obs.get("occupancy_grid", None) if occupancy_grid is not None: sensor_frames.append(("occupancy_grid", occupancy_grid)) remaining_obs_modalities -= {"occupancy_grid"} # Map the sensor name to the frames for that sensor frames[sensor.name] = sensor_frames # Warn user that any remaining modalities are not able to be visualized if len(remaining_obs_modalities) > 0: print(f"Modalities: {remaining_obs_modalities} cannot be visualized, skipping...") # Write all the frames to a plot for sensor_name, sensor_frames in frames.items(): n_sensor_frames = len(sensor_frames) if n_sensor_frames > 0: fig, axes = plt.subplots(nrows=1, ncols=n_sensor_frames) if n_sensor_frames == 1: axes = [axes] # Dump frames and set each subtitle for i, (modality, frame) in enumerate(sensor_frames): axes[i].imshow(frame) axes[i].set_title(modality) axes[i].set_axis_off() # Set title fig.suptitle(sensor_name) plt.show(block=False) # One final plot show so all the figures get rendered plt.show() def update_handles(self): # Call super first super().update_handles() # If we have a dummy robot, also update its handles too if self._dummy is not None: self._dummy.update_handles() def remove(self): """ Do NOT call this function directly to remove a prim - call og.sim.remove_prim(prim) for proper cleanup """ # Remove all sensors for sensor in self._sensors.values(): sensor.remove() # Run super super().remove() @property def reset_joint_pos_aabb_extent(self): """ This is the aabb extent of the robot in the robot frame after resetting the joints. Returns: 3-array: Axis-aligned bounding box extent of the robot base """ return self._reset_joint_pos_aabb_extent def teleop_data_to_action(self, teleop_action) -> np.ndarray: """ Generate action data from teleoperation action data Args: teleop_action (TeleopAction): teleoperation action data Returns: np.ndarray: array of action data filled with update value """ return np.zeros(self.action_dim) def get_generalized_gravity_forces(self, clone=True): # Override method based on whether we're using a dummy or not return self._dummy.get_generalized_gravity_forces(clone=clone) \ if self._use_dummy else super().get_generalized_gravity_forces(clone=clone) @property def sensors(self): """ Returns: dict: Keyword-mapped dictionary mapping sensor names to BaseSensor instances owned by this robot """ return self._sensors @property def obs_modalities(self): """ Returns: set of str: Observation modalities used for this robot (e.g.: proprio, rgb, etc.) """ assert self._loaded, "Cannot check observation modalities until we load this robot!" return self._obs_modalities @property def proprioception_dim(self): """ Returns: int: Size of self.get_proprioception() vector """ return len(self.get_proprioception()[0]) @property def _default_sensor_config(self): """ Returns: dict: default nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. See kwargs from omnigibson/sensors/__init__/create_sensor for more details Expected structure is as follows: SensorClassName1: modalities: ... enabled: ... noise_type: ... noise_kwargs: ... sensor_kwargs: ... SensorClassName2: modalities: ... enabled: ... noise_type: ... noise_kwargs: ... sensor_kwargs: ... ... """ return { "VisionSensor": { "enabled": True, "noise_type": None, "noise_kwargs": None, "sensor_kwargs": { "image_height": 128, "image_width": 128, }, }, "ScanSensor": { "enabled": True, "noise_type": None, "noise_kwargs": None, "sensor_kwargs": { # Basic LIDAR kwargs "min_range": 0.05, "max_range": 10.0, "horizontal_fov": 360.0, "vertical_fov": 1.0, "yaw_offset": 0.0, "horizontal_resolution": 1.0, "vertical_resolution": 1.0, "rotation_rate": 0.0, "draw_points": False, "draw_lines": False, # Occupancy Grid kwargs "occupancy_grid_resolution": 128, "occupancy_grid_range": 5.0, "occupancy_grid_inner_radius": 0.5, "occupancy_grid_local_link": None, }, }, } @property def default_proprio_obs(self): """ Returns: list of str: Default proprioception observations to use """ return [] @property def model_name(self): """ Returns: str: name of this robot model. usually corresponds to the class name of a given robot model """ return self.__class__.__name__ @property @abstractmethod def usd_path(self): # For all robots, this must be specified a priori, before we actually initialize the USDObject constructor! # So we override the parent implementation, and make this an abstract method raise NotImplementedError @property def _dummy_usd_path(self): """ Returns: str: Absolute path to the dummy USD to load for, e.g., computing gravity compensation """ # By default, this is just the normal usd path return self.usd_path @property def urdf_path(self): """ Returns: str: file path to the robot urdf file. """ raise NotImplementedError @property def _use_dummy(self): """ Returns: bool: Whether the robot dummy should be loaded and used for some computations, e.g., gravity compensation """ # By default, only load if robot is not fixed base return not self.fixed_base @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("BaseRobot") return classes @classproperty def _cls_registry(cls): # Global robot registry -- override super registry global REGISTERED_ROBOTS return REGISTERED_ROBOTS
27,335
Python
41.250386
159
0.588257
StanfordVL/OmniGibson/omnigibson/robots/behavior_robot.py
from abc import ABC from collections import OrderedDict import itertools import numpy as np import os from scipy.spatial.transform import Rotation as R from typing import List, Tuple, Iterable import omnigibson as og import omnigibson.lazy as lazy import omnigibson.utils.transform_utils as T from omnigibson.macros import gm, create_module_macros from omnigibson.robots.locomotion_robot import LocomotionRobot from omnigibson.robots.manipulation_robot import ManipulationRobot, GraspingPoint from omnigibson.robots.active_camera_robot import ActiveCameraRobot from omnigibson.objects.usd_object import USDObject m = create_module_macros(module_path=__file__) # component suffixes for the 6-DOF arm joint names m.COMPONENT_SUFFIXES = ['x', 'y', 'z', 'rx', 'ry', 'rz'] # Offset between the body and parts m.HEAD_TO_BODY_OFFSET = [0, 0, -0.4] m.HAND_TO_BODY_OFFSET = { "left": [0, -0.15, -0.4], "right": [0, 0.15, -0.4] } m.BODY_HEIGHT_OFFSET = 0.45 # Hand parameters m.HAND_GHOST_HAND_APPEAR_THRESHOLD = 0.15 m.THUMB_2_POS = [0, -0.02, -0.05] m.THUMB_1_POS = [0, -0.015, -0.02] m.PALM_CENTER_POS = [0, -0.04, 0.01] m.PALM_BASE_POS = [0, 0, 0.015] m.FINGER_TIP_POS = [0, -0.025, -0.055] # Hand link index constants m.PALM_LINK_NAME = "palm" m.FINGER_MID_LINK_NAMES = ("Tproximal", "Iproximal", "Mproximal", "Rproximal", "Pproximal") m.FINGER_TIP_LINK_NAMES = ("Tmiddle", "Imiddle", "Mmiddle", "Rmiddle", "Pmiddle") m.THUMB_LINK_NAME = "Tmiddle" # joint parameters m.BASE_JOINT_STIFFNESS = 1e8 m.BASE_JOINT_MAX_EFFORT = 7500 m.ARM_JOINT_STIFFNESS = 1e6 m.ARM_JOINT_MAX_EFFORT = 300 m.FINGER_JOINT_STIFFNESS = 1e3 m.FINGER_JOINT_MAX_EFFORT = 50 m.FINGER_JOINT_MAX_VELOCITY = np.pi * 4 class BehaviorRobot(ManipulationRobot, LocomotionRobot, ActiveCameraRobot): """ A humanoid robot that can be used in VR as an avatar. It has two hands, a body and a head with two cameras. """ def __init__( self, # Shared kwargs in hierarchy name, prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=True, load_config=None, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=False, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="rgb", proprio_obs="default", # Unique to ManipulationRobot grasping_mode="assisted", # unique to BehaviorRobot use_ghost_hands=True, **kwargs ): """ Initializes BehaviorRobot Args: use_ghost_hands (bool): whether to show ghost hand when the robot hand is too far away from the controller """ super(BehaviorRobot, self).__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=True, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, grasping_mode=grasping_mode, grasping_direction="upper", **kwargs, ) # setup eef parts self.parts = OrderedDict() for arm_name in self.arm_names: self.parts[arm_name] = BRPart( name=arm_name, parent=self, prim_path=f"{arm_name}_palm", eef_type="hand", offset_to_body=m.HAND_TO_BODY_OFFSET[arm_name], **kwargs ) self.parts["head"] = BRPart( name="head", parent=self, prim_path="eye", eef_type="head", offset_to_body=m.HEAD_TO_BODY_OFFSET, **kwargs ) # whether to use ghost hands (visual markers to help visualize current vr hand pose) self._use_ghost_hands = use_ghost_hands # prim for the world_base_fixed_joint, used to reset the robot pose self._world_base_fixed_joint_prim = None # whether hand or body is in contact with other objects (we need this since checking contact list is costly) self._part_is_in_contact = {hand_name: False for hand_name in self.arm_names + ["body"]} @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/behavior_robot/usd/BehaviorRobot.usd") @property def model_name(self): return "BehaviorRobot" @property def n_arms(self): return 2 @property def arm_names(self): return ["left", "right"] @property def eef_link_names(self): dic = {arm: f"{arm}_{m.PALM_LINK_NAME}" for arm in self.arm_names} dic["head"] = "head" return dic @property def arm_link_names(self): """The head counts as a arm since it has the same 33 joint configuration""" return {arm: [f"{arm}_{component}" for component in m.COMPONENT_SUFFIXES] for arm in self.arm_names + ['head']} @property def finger_link_names(self): return { arm: [f"{arm}_{link_name}" for link_name in itertools.chain(m.FINGER_MID_LINK_NAMES, m.FINGER_TIP_LINK_NAMES)] for arm in self.arm_names } @property def base_joint_names(self): return [f"base_{component}_joint" for component in m.COMPONENT_SUFFIXES] @property def arm_joint_names(self): """The head counts as a arm since it has the same 33 joint configuration""" return {eef: [f"{eef}_{component}_joint" for component in m.COMPONENT_SUFFIXES] for eef in self.arm_names + ["head"]} @property def finger_joint_names(self): return { arm: ( # palm-to-proximal joints. [f"{arm}_{to_link}__{arm}_{m.PALM_LINK_NAME}" for to_link in m.FINGER_MID_LINK_NAMES] + # proximal-to-tip joints. [f"{arm}_{to_link}__{arm}_{from_link}" for from_link, to_link in zip(m.FINGER_MID_LINK_NAMES, m.FINGER_TIP_LINK_NAMES)] ) for arm in self.arm_names } @property def base_control_idx(self): joints = list(self.joints.keys()) return [joints.index(joint) for joint in self.base_joint_names] @property def arm_control_idx(self): joints = list(self.joints.keys()) return { arm: [joints.index(f"{arm}_{component}_joint") for component in m.COMPONENT_SUFFIXES] for arm in self.arm_names } @property def gripper_control_idx(self): joints = list(self.joints.values()) return {arm: [joints.index(joint) for joint in arm_joints] for arm, arm_joints in self.finger_joints.items()} @property def camera_control_idx(self): joints = list(self.joints.keys()) return [joints.index(f"head_{component}_joint") for component in m.COMPONENT_SUFFIXES] @property def _default_joint_pos(self): return np.zeros(self.n_joints) @property def controller_order(self): controllers = ["base", "camera"] for arm_name in self.arm_names: controllers += [f"arm_{arm_name}", f"gripper_{arm_name}"] return controllers @property def _default_controllers(self): controllers = { "base": "JointController", "camera": "JointController" } controllers.update({f"arm_{arm_name}": "JointController" for arm_name in self.arm_names}) controllers.update({f"gripper_{arm_name}": "MultiFingerGripperController" for arm_name in self.arm_names}) return controllers @property def _default_base_joint_controller_config(self): return { "name": "JointController", "control_freq": self._control_freq, "control_limits": self.control_limits, "use_delta_commands": False, "motor_type": "position", "dof_idx": self.base_control_idx, "command_input_limits": None, } @property def _default_arm_joint_controller_configs(self): dic = {} for arm in self.arm_names: dic[arm] = { "name": "JointController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.arm_control_idx[arm], "command_input_limits": None, "use_delta_commands": False, } return dic @property def _default_gripper_multi_finger_controller_configs(self): dic = {} for arm in self.arm_names: dic[arm] = { "name": "MultiFingerGripperController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.gripper_control_idx[arm], "command_input_limits": None, "mode": "independent", } return dic @property def _default_camera_joint_controller_config(self): return { "name": "JointController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.camera_control_idx, "command_input_limits": None, "use_delta_commands": False, } @property def _default_gripper_joint_controller_configs(self): """ Returns: dict: Dictionary mapping arm appendage name to default gripper joint controller config to control this robot's gripper """ dic = {} for arm in self.arm_names: dic[arm] = { "name": "JointController", "control_freq": self._control_freq, "motor_type": "position", "control_limits": self.control_limits, "dof_idx": self.gripper_control_idx[arm], "command_input_limits": None, "use_delta_commands": False, } return dic @property def _default_controller_config(self): controllers = { "base": {"JointController": self._default_base_joint_controller_config}, "camera": {"JointController": self._default_camera_joint_controller_config}, } controllers.update( { f"arm_{arm_name}": {"JointController": self._default_arm_joint_controller_configs[arm_name]} for arm_name in self.arm_names } ) controllers.update( { f"gripper_{arm_name}": { "MultiFingerGripperController": self._default_gripper_multi_finger_controller_configs[arm_name], "JointController": self._default_gripper_joint_controller_configs[arm_name], } for arm_name in self.arm_names } ) return controllers def load(self): prim = super(BehaviorRobot, self).load() for part in self.parts.values(): part.load() return prim def _post_load(self): super()._post_load() def _create_discrete_action_space(self): raise ValueError("BehaviorRobot does not support discrete actions!") def update_controller_mode(self): super().update_controller_mode() # set base joint properties for joint_name in self.base_joint_names: self.joints[joint_name].stiffness = m.BASE_JOINT_STIFFNESS self.joints[joint_name].max_effort = m.BASE_JOINT_MAX_EFFORT # set arm joint properties for arm in self.arm_joint_names: for joint_name in self.arm_joint_names[arm]: self.joints[joint_name].stiffness = m.ARM_JOINT_STIFFNESS self.joints[joint_name].max_effort = m.ARM_JOINT_MAX_EFFORT # set finger joint properties for arm in self.finger_joint_names: for joint_name in self.finger_joint_names[arm]: self.joints[joint_name].stiffness = m.FINGER_JOINT_STIFFNESS self.joints[joint_name].max_effort = m.FINGER_JOINT_MAX_EFFORT self.joints[joint_name].max_velocity = m.FINGER_JOINT_MAX_VELOCITY @property def base_footprint_link_name(self): """ Name of the actual root link that we are interested in. """ return "base" @property def base_footprint_link(self): """ Returns: RigidPrim: base footprint link of this object prim """ return self._links[self.base_footprint_link_name] def get_position_orientation(self): return self.base_footprint_link.get_position_orientation() def set_position_orientation(self, position=None, orientation=None): super().set_position_orientation(position, orientation) # Move the joint frame for the world_base_joint if self._world_base_fixed_joint_prim is not None: if position is not None: self._world_base_fixed_joint_prim.GetAttribute("physics:localPos0").Set(tuple(position)) if orientation is not None: self._world_base_fixed_joint_prim.GetAttribute("physics:localRot0").Set(lazy.pxr.Gf.Quatf(*np.float_(orientation)[[3, 0, 1, 2]])) @property def assisted_grasp_start_points(self): side_coefficients = {"left": np.array([1, -1, 1]), "right": np.array([1, 1, 1])} return { arm: [ GraspingPoint(link_name=f"{arm}_{m.PALM_LINK_NAME}", position=m.PALM_BASE_POS), GraspingPoint(link_name=f"{arm}_{m.PALM_LINK_NAME}", position=m.PALM_CENTER_POS * side_coefficients[arm]), GraspingPoint( link_name=f"{arm}_{m.THUMB_LINK_NAME}", position=m.THUMB_1_POS * side_coefficients[arm] ), GraspingPoint( link_name=f"{arm}_{m.THUMB_LINK_NAME}", position=m.THUMB_2_POS * side_coefficients[arm] ), ] for arm in self.arm_names } @property def assisted_grasp_end_points(self): side_coefficients = {"left": np.array([1, -1, 1]), "right": np.array([1, 1, 1])} return { arm: [ GraspingPoint(link_name=f"{arm}_{finger}", position=m.FINGER_TIP_POS * side_coefficients[arm]) for finger in m.FINGER_TIP_LINK_NAMES ] for arm in self.arm_names } def update_hand_contact_info(self): """ Helper function that updates the contact info for the hands and body. Can be used in the future with device haptics to provide collision feedback. """ self._part_is_in_contact["body"] = len(self.links["body"].contact_list()) > 0 for hand_name in self.arm_names: self._part_is_in_contact[hand_name] = len(self.eef_links[hand_name].contact_list()) > 0 \ or np.any([len(finger.contact_list()) > 0 for finger in self.finger_links[hand_name]]) def teleop_data_to_action(self, teleop_action) -> np.ndarray: """ Generates an action for the BehaviorRobot to perform based on teleop action data dict. Action space (all non-normalized values that will be clipped if they are too large) Body: - 6DOF pose - relative to body frame from previous frame Eye: - 6DOF pose - relative to body frame (where the body will be after applying this frame's action) Left hand, right hand (in that order): - 6DOF pose - relative to body frame (same as above) - 10DOF gripper joint rotation Total size: 44 """ # Actions are stored as 1D numpy array action = np.zeros(self.action_dim) # Update body action space if teleop_action.is_valid["head"]: head_pos, head_orn = teleop_action.head[:3], T.euler2quat(teleop_action.head[3:6]) des_body_pos = head_pos - np.array([0, 0, m.BODY_HEIGHT_OFFSET]) des_body_rpy = np.array([0, 0, R.from_quat(head_orn).as_euler("XYZ")[2]]) des_body_orn = T.euler2quat(des_body_rpy) else: des_body_pos, des_body_orn = self.get_position_orientation() des_body_rpy = R.from_quat(des_body_orn).as_euler("XYZ") action[self.controller_action_idx["base"]] = np.r_[des_body_pos, des_body_rpy] # Update action space for other VR objects for part_name, eef_part in self.parts.items(): # Process local transform adjustments hand_data = 0 if teleop_action.is_valid[part_name]: des_world_part_pos, des_world_part_orn = teleop_action[part_name][:3], T.euler2quat(teleop_action[part_name][3:6]) if part_name in self.arm_names: # compute gripper action if hasattr(teleop_action, "hand_data"): # hand tracking mode, compute joint rotations for each independent hand joint hand_data = teleop_action.hand_data[part_name] hand_data = hand_data[:, :2].T.reshape(-1) else: # controller mode, map trigger fraction from [0, 1] to [-1, 1] range. hand_data = teleop_action[part_name][6] * 2 - 1 action[self.controller_action_idx[f"gripper_{part_name}"]] = hand_data # update ghost hand if necessary if self._use_ghost_hands: self.parts[part_name].update_ghost_hands(des_world_part_pos, des_world_part_orn) else: des_world_part_pos, des_world_part_orn = eef_part.local_position_orientation # Get local pose with respect to the new body frame des_local_part_pos, des_local_part_orn = T.relative_pose_transform( des_world_part_pos, des_world_part_orn, des_body_pos, des_body_orn ) # apply shoulder position offset to the part transform to get final destination pose des_local_part_pos, des_local_part_orn = T.pose_transform( eef_part.offset_to_body, [0, 0, 0, 1], des_local_part_pos, des_local_part_orn ) des_part_rpy = R.from_quat(des_local_part_orn).as_euler("XYZ") controller_name = "camera" if part_name == "head" else "arm_" + part_name action[self.controller_action_idx[controller_name]] = np.r_[des_local_part_pos, des_part_rpy] # If we reset, teleop the robot parts to the desired pose if part_name in self.arm_names and teleop_action.reset[part_name]: self.parts[part_name].set_position_orientation(des_local_part_pos, des_part_rpy) return action class BRPart(ABC): """This is the interface that all BehaviorRobot eef parts must implement.""" def __init__(self, name: str, parent: BehaviorRobot, prim_path: str, eef_type: str, offset_to_body: List[float]) -> None: """ Create an object instance with the minimum information of class ID and rendering parameters. Args: name (str): unique name of this BR part parent (BehaviorRobot): the parent BR object prim_path (str): prim path to the root link of the eef eef_type (str): type of eef. One of hand, head offset_to_body (List[float]): relative POSITION offset between the rz link and the eef link. """ self.name = name self.parent = parent self.prim_path = prim_path self.eef_type = eef_type self.offset_to_body = offset_to_body self.ghost_hand = None self._root_link = None def load(self) -> None: self._root_link = self.parent.links[self.prim_path] # setup ghost hand if self.eef_type == "hand" and self.parent._use_ghost_hands: gh_name = f"ghost_hand_{self.name}" self.ghost_hand = USDObject( prim_path=f"/World/{gh_name}", usd_path=os.path.join(gm.ASSET_PATH, f"models/behavior_robot/usd/{gh_name}.usd"), name=gh_name, scale=0.001, visible=False, visual_only=True, ) og.sim.import_object(self.ghost_hand) @property def local_position_orientation(self) -> Tuple[Iterable[float], Iterable[float]]: """ Get local position and orientation w.r.t. to the body Returns: Tuple[Array[x, y, z], Array[x, y, z, w]] """ return T.relative_pose_transform(*self.get_position_orientation(), *self.parent.get_position_orientation()) def get_position_orientation(self) -> Tuple[Iterable[float], Iterable[float]]: """ Get position and orientation in the world space Returns: Tuple[Array[x, y, z], Array[x, y, z, w]] """ return self._root_link.get_position_orientation() def set_position_orientation(self, pos: Iterable[float], orn: Iterable[float]) -> None: """ Call back function to set the base's position """ self.parent.joints[f"{self.name}_x_joint"].set_pos(pos[0], drive=False) self.parent.joints[f"{self.name}_y_joint"].set_pos(pos[1], drive=False) self.parent.joints[f"{self.name}_z_joint"].set_pos(pos[2], drive=False) self.parent.joints[f"{self.name}_rx_joint"].set_pos(orn[0], drive=False) self.parent.joints[f"{self.name}_ry_joint"].set_pos(orn[1], drive=False) self.parent.joints[f"{self.name}_rz_joint"].set_pos(orn[2], drive=False) def update_ghost_hands(self, pos: Iterable[float], orn: Iterable[float]) -> None: """ Updates ghost hand to track real hand and displays it if the real and virtual hands are too far apart. Args: pos (Iterable[float]): list of positions [x, y, z] orn (Iterable[float]): list of rotations [x, y, z, w] """ assert self.eef_type == "hand", "ghost hand is only valid for BR hand!" # Ghost hand tracks real hand whether it is hidden or not self.ghost_hand.set_position_orientation(pos, orn) # If distance between hand and controller is greater than threshold, # ghost hand appears dist_to_real_controller = np.linalg.norm(pos - self.get_position_orientation()[0]) should_visible = dist_to_real_controller > m.HAND_GHOST_HAND_APPEAR_THRESHOLD # Only toggle visibility if we are transition from hidden to unhidden, or the other way around if self.ghost_hand.visible is not should_visible: self.ghost_hand.visible = should_visible
23,460
Python
39.035836
145
0.587127
StanfordVL/OmniGibson/omnigibson/robots/franka_leap.py
import os import numpy as np from typing import Dict, Iterable import omnigibson.utils.transform_utils as T from omnigibson.macros import gm from omnigibson.robots.manipulation_robot import ManipulationRobot, GraspingPoint class FrankaLeap(ManipulationRobot): """ Franka Robot with Leap right hand """ def __init__( self, # Shared kwargs in hierarchy name, hand="right", prim_path=None, uuid=None, scale=None, visible=True, visual_only=False, self_collisions=True, load_config=None, fixed_base=True, # Unique to USDObject hierarchy abilities=None, # Unique to ControllableObject hierarchy control_freq=None, controller_config=None, action_type="continuous", action_normalize=True, reset_joint_pos=None, # Unique to BaseRobot obs_modalities="all", proprio_obs="default", sensor_config=None, # Unique to ManipulationRobot grasping_mode="physical", **kwargs, ): """ Args: name (str): Name for the object. Names need to be unique per scene hand (str): One of {"left", "right"} - which hand to use, default is right prim_path (None or str): global path in the stage to this object. If not specified, will automatically be created at /World/<name> uuid (None or int): Unique unsigned-integer identifier to assign to this object (max 8-numbers). If None is specified, then it will be auto-generated scale (None or float or 3-array): if specified, sets either the uniform (float) or x,y,z (3-array) scale for this object. A single number corresponds to uniform scaling along the x,y,z axes, whereas a 3-array specifies per-axis scaling. visible (bool): whether to render this object or not in the stage visual_only (bool): Whether this object should be visual only (and not collide with any other objects) self_collisions (bool): Whether to enable self collisions for this object load_config (None or dict): If specified, should contain keyword-mapped values that are relevant for loading this prim at runtime. abilities (None or dict): If specified, manually adds specific object states to this object. It should be a dict in the form of {ability: {param: value}} containing object abilities and parameters to pass to the object state instance constructor. control_freq (float): control frequency (in Hz) at which to control the object. If set to be None, simulator.import_object will automatically set the control frequency to be 1 / render_timestep by default. controller_config (None or dict): nested dictionary mapping controller name(s) to specific controller configurations for this object. This will override any default values specified by this class. action_type (str): one of {discrete, continuous} - what type of action space to use action_normalize (bool): whether to normalize inputted actions. This will override any default values specified by this class. reset_joint_pos (None or n-array): if specified, should be the joint positions that the object should be set to during a reset. If None (default), self._default_joint_pos will be used instead. Note that _default_joint_pos are hardcoded & precomputed, and thus should not be modified by the user. Set this value instead if you want to initialize the robot with a different rese joint position. obs_modalities (str or list of str): Observation modalities to use for this robot. Default is "all", which corresponds to all modalities being used. Otherwise, valid options should be part of omnigibson.sensors.ALL_SENSOR_MODALITIES. Note: If @sensor_config explicitly specifies `modalities` for a given sensor class, it will override any values specified from @obs_modalities! proprio_obs (str or list of str): proprioception observation key(s) to use for generating proprioceptive observations. If str, should be exactly "default" -- this results in the default proprioception observations being used, as defined by self.default_proprio_obs. See self._get_proprioception_dict for valid key choices sensor_config (None or dict): nested dictionary mapping sensor class name(s) to specific sensor configurations for this object. This will override any default values specified by this class. grasping_mode (str): One of {"physical", "assisted", "sticky"}. If "physical", no assistive grasping will be applied (relies on contact friction + finger force). If "assisted", will magnetize any object touching and within the gripper's fingers. If "sticky", will magnetize any object touching the gripper's fingers. kwargs (dict): Additional keyword arguments that are used for other super() calls from subclasses, allowing for flexible compositions of various object subclasses (e.g.: Robot is USDObject + ControllableObject). """ self.hand = hand # Run super init super().__init__( prim_path=prim_path, name=name, uuid=uuid, scale=scale, visible=visible, fixed_base=fixed_base, visual_only=visual_only, self_collisions=self_collisions, load_config=load_config, abilities=abilities, control_freq=control_freq, controller_config=controller_config, action_type=action_type, action_normalize=action_normalize, reset_joint_pos=reset_joint_pos, obs_modalities=obs_modalities, proprio_obs=proprio_obs, sensor_config=sensor_config, grasping_mode=grasping_mode, grasping_direction="upper", **kwargs, ) @property def model_name(self): return f"FrankaLeap{self.hand.capitalize()}" @property def discrete_action_list(self): # Not supported for this robot raise NotImplementedError() def _create_discrete_action_space(self): # Fetch does not support discrete actions raise ValueError("Franka does not support discrete actions!") @property def controller_order(self): return ["arm_{}".format(self.default_arm), "gripper_{}".format(self.default_arm)] @property def _default_controllers(self): controllers = super()._default_controllers controllers["arm_{}".format(self.default_arm)] = "InverseKinematicsController" controllers["gripper_{}".format(self.default_arm)] = "MultiFingerGripperController" return controllers @property def _default_gripper_multi_finger_controller_configs(self): conf = super()._default_gripper_multi_finger_controller_configs conf[self.default_arm]["mode"] = "independent" conf[self.default_arm]["command_input_limits"] = None return conf @property def _default_joint_pos(self): # position where the hand is parallel to the ground return np.r_[[0.86, -0.27, -0.68, -1.52, -0.18, 1.29, 1.72], np.zeros(16)] @property def assisted_grasp_start_points(self): return {self.default_arm: [ GraspingPoint(link_name=f"palm_center", position=[0, -0.025, 0.035]), GraspingPoint(link_name=f"palm_center", position=[0, 0.03, 0.035]), GraspingPoint(link_name=f"fingertip_4", position=[-0.0115, -0.07, -0.015]), ]} @property def assisted_grasp_end_points(self): return {self.default_arm: [ GraspingPoint(link_name=f"fingertip_1", position=[-0.0115, -0.06, 0.015]), GraspingPoint(link_name=f"fingertip_2", position=[-0.0115, -0.06, 0.015]), GraspingPoint(link_name=f"fingertip_3", position=[-0.0115, -0.06, 0.015]), ]} @property def finger_lengths(self): return {self.default_arm: 0.1} @property def arm_control_idx(self): return {self.default_arm: np.arange(7)} @property def gripper_control_idx(self): # thumb.proximal, ..., thumb.tip, ..., ring.tip return {self.default_arm: np.array([8, 12, 16, 20, 7, 11, 15, 19, 9, 13, 17, 21, 10, 14, 18, 22])} @property def arm_link_names(self): return {self.default_arm: [f"panda_link{i}" for i in range(8)]} @property def arm_joint_names(self): return {self.default_arm: [f"panda_joint_{i+1}" for i in range(7)]} @property def eef_link_names(self): return {self.default_arm: "palm_center"} @property def finger_link_names(self): links = ["mcp_joint", "pip", "dip", "fingertip", "realtip"] return {self.default_arm: [f"{link}_{i}" for i in range(1, 5) for link in links]} @property def finger_joint_names(self): # thumb.proximal, ..., thumb.tip, ..., ring.tip return {self.default_arm: [f"finger_joint_{i}" for i in [12, 13, 14, 15, 1, 0, 2, 3, 5, 4, 6, 7, 9, 8, 10, 11]]} @property def usd_path(self): return os.path.join(gm.ASSET_PATH, f"models/franka/franka_leap_{self.hand}.usd") @property def robot_arm_descriptor_yamls(self): return {self.default_arm: os.path.join(gm.ASSET_PATH, "models/franka/franka_leap_description.yaml")} @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, f"models/franka/franka_leap_{self.hand}.urdf") @property def teleop_rotation_offset(self): return {self.default_arm: T.euler2quat(np.array([0, np.pi, np.pi / 2]))}
10,090
Python
43.650442
122
0.629534
StanfordVL/OmniGibson/omnigibson/robots/locomotion_robot.py
from abc import abstractmethod import numpy as np from transforms3d.euler import euler2quat from transforms3d.quaternions import qmult, quat2mat from omnigibson.controllers import LocomotionController from omnigibson.robots.robot_base import BaseRobot from omnigibson.utils.python_utils import classproperty class LocomotionRobot(BaseRobot): """ Robot that is is equipped with locomotive (navigational) capabilities. Provides common interface for a wide variety of robots. NOTE: controller_config should, at the minimum, contain: base: controller specifications for the controller to control this robot's base (locomotion). Should include: - name: Controller to create - <other kwargs> relevant to the controller being created. Note that all values will have default values specified, but setting these individual kwargs will override them """ def _validate_configuration(self): # We make sure that our base controller exists and is a locomotion controller assert ( "base" in self._controllers ), "Controller 'base' must exist in controllers! Current controllers: {}".format(list(self._controllers.keys())) assert isinstance( self._controllers["base"], LocomotionController ), "Base controller must be a LocomotionController!" # run super super()._validate_configuration() def _get_proprioception_dict(self): dic = super()._get_proprioception_dict() joint_positions = self.get_joint_positions(normalized=False) joint_velocities = self.get_joint_velocities(normalized=False) # Add base info dic["base_qpos"] = joint_positions[self.base_control_idx] dic["base_qpos_sin"] = np.sin(joint_positions[self.base_control_idx]) dic["base_qpos_cos"] = np.cos(joint_positions[self.base_control_idx]) dic["base_qvel"] = joint_velocities[self.base_control_idx] return dic @property def default_proprio_obs(self): obs_keys = super().default_proprio_obs return obs_keys + ["base_qpos_sin", "base_qpos_cos", "robot_lin_vel", "robot_ang_vel"] @property def controller_order(self): # By default, only base is supported return ["base"] @property def _default_controllers(self): # Always call super first controllers = super()._default_controllers # For best generalizability use, joint controller as default controllers["base"] = "JointController" return controllers @property def _default_base_joint_controller_config(self): """ Returns: dict: Default base joint controller config to control this robot's base. Uses velocity control by default. """ return { "name": "JointController", "control_freq": self._control_freq, "motor_type": "velocity", "control_limits": self.control_limits, "dof_idx": self.base_control_idx, "command_output_limits": "default", "use_delta_commands": False, } @property def _default_base_null_joint_controller_config(self): """ Returns: dict: Default null joint controller config to control this robot's base i.e. dummy controller """ return { "name": "NullJointController", "control_freq": self._control_freq, "motor_type": "velocity", "control_limits": self.control_limits, "dof_idx": self.base_control_idx, "default_command": np.zeros(len(self.base_control_idx)), "use_impedances": False, } @property def _default_controller_config(self): # Always run super method first cfg = super()._default_controller_config # Add supported base controllers cfg["base"] = { self._default_base_joint_controller_config["name"]: self._default_base_joint_controller_config, self._default_base_null_joint_controller_config["name"]: self._default_base_null_joint_controller_config, } return cfg def move_by(self, delta): """ Move robot base without physics simulation Args: delta (float):float], (x,y,z) cartesian delta base position """ new_pos = np.array(delta) + self.get_position() self.set_position(position=new_pos) def move_forward(self, delta=0.05): """ Move robot base forward without physics simulation Args: delta (float): delta base position forward """ self.move_by(quat2mat(self.get_orientation()).dot(np.array([delta, 0, 0]))) def move_backward(self, delta=0.05): """ Move robot base backward without physics simulation Args: delta (float): delta base position backward """ self.move_by(quat2mat(self.get_orientation()).dot(np.array([-delta, 0, 0]))) def move_left(self, delta=0.05): """ Move robot base left without physics simulation Args: delta (float): delta base position left """ self.move_by(quat2mat(self.get_orientation()).dot(np.array([0, -delta, 0]))) def move_right(self, delta=0.05): """ Move robot base right without physics simulation Args: delta (float): delta base position right """ self.move_by(quat2mat(self.get_orientation()).dot(np.array([0, delta, 0]))) def turn_left(self, delta=0.03): """ Rotate robot base left without physics simulation Args: delta (float): delta angle to rotate the base left """ quat = self.get_orientation() quat = qmult((euler2quat(-delta, 0, 0)), quat) self.set_orientation(quat) def turn_right(self, delta=0.03): """ Rotate robot base right without physics simulation Args: delta (float): angle to rotate the base right """ quat = self.get_orientation() quat = qmult((euler2quat(delta, 0, 0)), quat) self.set_orientation(quat) @property def base_action_idx(self): controller_idx = self.controller_order.index("base") action_start_idx = sum([self.controllers[self.controller_order[i]].command_dim for i in range(controller_idx)]) return np.arange(action_start_idx, action_start_idx + self.controllers["base"].command_dim) @property @abstractmethod def base_control_idx(self): """ Returns: n-array: Indices in low-level control vector corresponding to base joints. """ 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("LocomotionRobot") return classes
7,069
Python
32.990384
120
0.618758
StanfordVL/OmniGibson/omnigibson/robots/husky.py
import os import numpy as np from omnigibson.macros import gm from omnigibson.robots.locomotion_robot import LocomotionRobot class Husky(LocomotionRobot): """ Husky robot Reference: https://clearpathrobotics.com/, http://wiki.ros.org/Robots/Husky """ def _create_discrete_action_space(self): raise ValueError("Husky does not support discrete actions!") @property def base_control_idx(self): return np.array([0, 1, 2, 3]) @property def _default_joint_pos(self): return np.zeros(self.n_joints) @property def usd_path(self): return os.path.join(gm.ASSET_PATH, "models/husky/husky/husky.usd") @property def urdf_path(self): return os.path.join(gm.ASSET_PATH, "models/husky/husky.urdf")
782
Python
23.468749
79
0.671355