Vinyeh commited on
Commit
fa6aaa6
·
verified ·
1 Parent(s): a471ee7

Add pinned source: behavior-1k-bddl (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/max_collision.py +49 -0
  3. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/point_goal.py +43 -0
  4. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/predicate_goal.py +53 -0
  5. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/reaching_goal.py +34 -0
  6. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/termination_condition_base.py +167 -0
  7. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/timeout.py +23 -0
  8. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/transition_rules.py +0 -0
  9. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/__init__.py +0 -0
  10. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_conversion_utils.py +0 -0
  11. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_utils.py +674 -0
  12. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/backend_utils.py +175 -0
  13. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/bddl_utils.py +1550 -0
  14. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/coacd_runner.py +24 -0
  15. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/config_utils.py +79 -0
  16. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/constants.py +210 -0
  17. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/control_utils.py +140 -0
  18. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/data_utils.py +193 -0
  19. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/deprecated_utils.py +1057 -0
  20. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/geometry_utils.py +179 -0
  21. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/git_utils.py +28 -0
  22. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/grasping_planning_utils.py +545 -0
  23. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/gym_utils.py +158 -0
  24. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/lazy_import_utils.py +46 -0
  25. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/motion_planning_utils.py +638 -0
  26. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/numpy_utils.py +37 -0
  27. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_state_utils.py +464 -0
  28. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_utils.py +131 -0
  29. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/physx_utils.py +284 -0
  30. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/processing_utils.py +386 -0
  31. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/profiling_utils.py +107 -0
  32. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/pynvml_utils.py +0 -0
  33. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/python_utils.py +884 -0
  34. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/registry_utils.py +502 -0
  35. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/render_utils.py +83 -0
  36. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sampling_utils.py +1227 -0
  37. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sim_utils.py +18 -0
  38. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/teleop_utils.py +693 -0
  39. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils.py +1612 -0
  40. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils_np.py +1442 -0
  41. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/ui_utils.py +1171 -0
  42. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdf_preprocessing.py +311 -0
  43. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdfpy_utils.py +0 -0
  44. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/usd_utils.py +0 -0
  45. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/vision_utils.py +372 -0
  46. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/pyproject.toml +38 -0
  47. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/build_docs.sh +13 -0
  48. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/aggregate_lerobot_task_shards.py +254 -0
  49. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/benchmark.py +279 -0
  50. source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.py +292 -0
.gitattributes CHANGED
@@ -205,3 +205,5 @@ source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-Semibold-webf
205
  source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-Semibold-webfont.ttf filter=lfs diff=lfs merge=lfs -text
206
  source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-SemiboldItalic-webfont.ttf filter=lfs diff=lfs merge=lfs -text
207
  source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/fontawesome-webfont.ttf filter=lfs diff=lfs merge=lfs -text
 
 
 
205
  source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-Semibold-webfont.ttf filter=lfs diff=lfs merge=lfs -text
206
  source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/OpenSans-SemiboldItalic-webfont.ttf filter=lfs diff=lfs merge=lfs -text
207
  source_data/pinned/dmn-tck/commit-1e349176e5ae/docs/fonts/fontawesome-webfont.ttf filter=lfs diff=lfs merge=lfs -text
208
+ source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7za.exe filter=lfs diff=lfs merge=lfs -text
209
+ source_data/pinned/behavior-1k-bddl/v3.9.3-post2/asset_pipeline/7zzs filter=lfs diff=lfs merge=lfs -text
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/max_collision.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as th
2
+
3
+ from omnigibson.utils.usd_utils import RigidContactAPI
4
+ from omnigibson.termination_conditions.termination_condition_base import FailureCondition
5
+
6
+
7
+ class MaxCollision(FailureCondition):
8
+ """
9
+ MaxCollision (failure condition) used for navigation tasks
10
+ Episode terminates if the robot has collided more than max_collisions_allowed times
11
+ Note that we ignore collisions with any floor objects.
12
+
13
+ Args:
14
+ robot_idn (int): robot identifier to evaluate collision checking with. Default is 0, corresponding to the first
15
+ robot added to the scene
16
+ ignore_self_collisions (bool): Whether to ignore robot self-collisions or not
17
+ max_collisions (int): Maximum number of collisions allowed for any robots in the scene before a termination
18
+ is triggered
19
+ """
20
+
21
+ def __init__(self, robot_idn=0, ignore_self_collisions=True, max_collisions=500):
22
+ self._robot_idn = robot_idn
23
+ self._ignore_self_collisions = ignore_self_collisions
24
+ self._max_collisions = max_collisions
25
+ self._n_collisions = None
26
+
27
+ # Run super init
28
+ super().__init__()
29
+
30
+ def reset(self, task, env, env_indices):
31
+ # Call super first
32
+ super().reset(task, env, env_indices)
33
+
34
+ # Also reset collision counter
35
+ if self._n_collisions is None:
36
+ self._n_collisions = th.zeros(env.num_envs, dtype=th.int64)
37
+ self._n_collisions[env_indices] = 0
38
+
39
+ def _step(self, task, env, action):
40
+ # Terminate if the robot has collided more than self._max_collisions times
41
+ for env_idx in range(env.num_envs):
42
+ robot = env.scenes[env_idx].robots[self._robot_idn]
43
+ floors = list(env.scenes[env_idx].object_registry("category", "floors", []))
44
+ ignore_objs = floors + [robot] if self._ignore_self_collisions else floors
45
+ in_contact = RigidContactAPI.is_in_contact(
46
+ scene_idx=robot.scene.idx, query_set=[robot], with_set=None, ignore_set=ignore_objs, current_only=False
47
+ )
48
+ self._n_collisions[env_idx] += int(in_contact)
49
+ return self._n_collisions > self._max_collisions
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/point_goal.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as th
2
+
3
+ import omnigibson.utils.transform_utils as T
4
+ from omnigibson.termination_conditions.termination_condition_base import SuccessCondition
5
+
6
+
7
+ class PointGoal(SuccessCondition):
8
+ """
9
+ PointGoal (success condition) used for PointNavFixed/RandomTask
10
+ Episode terminates if point goal is reached within @distance_tol by the @robot_idn robot's base
11
+
12
+ Args:
13
+ robot_idn (int): robot identifier to evaluate point goal with. Default is 0, corresponding to the first
14
+ robot added to the scene
15
+ distance_tol (float): Distance (m) tolerance between goal position and @robot_idn's robot base position
16
+ that is accepted as a success
17
+ distance_axes (str): Which axes to calculate distances when calculating the goal. Any combination of "x",
18
+ "y", and "z" is valid (e.g.: "xy" or "xyz" or "y")
19
+ """
20
+
21
+ def __init__(self, robot_idn=0, distance_tol=0.5, distance_axes="xyz"):
22
+ self._robot_idn = robot_idn
23
+ self._distance_tol = distance_tol
24
+ self._distance_axes = [i for i, axis in enumerate("xyz") if axis in distance_axes]
25
+
26
+ # Run super init
27
+ super().__init__()
28
+
29
+ def _step(self, task, env, action):
30
+ # Make sure task is of type PointNavigation -- we import at runtime to avoid circular imports
31
+ from omnigibson.tasks.point_navigation_task import PointNavigationTask
32
+
33
+ assert isinstance(
34
+ task, PointNavigationTask
35
+ ), f"Cannot use {self.__class__.__name__} with a non-PointNavigationTask task instance!"
36
+ # Terminate if point goal is reached (distance below threshold)
37
+ results = th.zeros(env.num_envs, dtype=th.bool)
38
+ for env_idx in range(env.num_envs):
39
+ current = task.get_current_pos(env, env_idx)
40
+ goal = task.get_goal_pos(env_idx)
41
+ dist = T.l2_distance(current[self._distance_axes], goal[self._distance_axes])
42
+ results[env_idx] = dist < self._distance_tol
43
+ return results
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/predicate_goal.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as th
2
+
3
+
4
+ from omnigibson.termination_conditions.termination_condition_base import SuccessCondition
5
+
6
+
7
+ class PredicateGoal(SuccessCondition):
8
+ """
9
+ PredicateGoal (success condition) used for BehaviorTask
10
+ Episode terminates if all the predicates are satisfied
11
+
12
+ Args:
13
+ check_goal_fn (method): function that checks goal satisfaction. Function signature should be:
14
+
15
+ (all_satisfied, results) = check_goal_fn()
16
+
17
+ where @all_satisfied is a bool and @results maps "satisfied"/"unsatisfied" to lists of indices.
18
+ """
19
+
20
+ def __init__(self, check_goal_fn):
21
+ # Store internal vars
22
+ self._check_goal_fn = check_goal_fn
23
+ self._goal_status = None
24
+
25
+ # Run super
26
+ super().__init__()
27
+
28
+ def reset(self, task, env, env_indices):
29
+ # Run super first
30
+ super().reset(task, env, env_indices)
31
+
32
+ # Reset status
33
+ if self._goal_status is None:
34
+ self._goal_status = [{"satisfied": [], "unsatisfied": []} for _ in range(env.num_envs)]
35
+ for idx in env_indices:
36
+ self._goal_status[idx] = {"satisfied": [], "unsatisfied": []}
37
+
38
+ def _step(self, task, env, action):
39
+ # Terminate if all goal conditions are met in the task
40
+ results = th.zeros(env.num_envs, dtype=th.bool)
41
+ for env_idx in range(env.num_envs):
42
+ done, self._goal_status[env_idx] = self._check_goal_fn(env_idx)
43
+ results[env_idx] = done
44
+ return results
45
+
46
+ @property
47
+ def goal_status(self):
48
+ """
49
+ Returns:
50
+ list[dict]: Current goal status for the active predicate(s), mapping "satisfied" and "unsatisfied" to a list
51
+ of the predicates matching either of those conditions for each env
52
+ """
53
+ return self._goal_status
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/reaching_goal.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as th
2
+
3
+ import omnigibson.utils.transform_utils as T
4
+ from omnigibson.termination_conditions.termination_condition_base import SuccessCondition
5
+
6
+
7
+ class ReachingGoal(SuccessCondition):
8
+ """
9
+ ReachingGoal (success condition) used for reaching-type tasks
10
+ Episode terminates if reaching goal is reached within @distance_tol by the @robot_idn robot's end effector
11
+
12
+ Args:
13
+ robot_idn (int): robot identifier to evaluate point goal with. Default is 0, corresponding to the first
14
+ robot added to the scene
15
+ distance_tol (float): Distance (m) tolerance between goal position and @robot_idn's robot eef position
16
+ that is accepted as a success
17
+ """
18
+
19
+ def __init__(self, robot_idn=0, distance_tol=0.5):
20
+ self._robot_idn = robot_idn
21
+ self._distance_tol = distance_tol
22
+
23
+ # Run super init
24
+ super().__init__()
25
+
26
+ def _step(self, task, env, action):
27
+ # Terminate if point goal is reached (distance below threshold)
28
+ results = th.zeros(env.num_envs, dtype=th.bool)
29
+ for env_idx in range(env.num_envs):
30
+ robot = env.scenes[env_idx].robots[self._robot_idn]
31
+ eef_pos = robot.get_eef_position()
32
+ dist = T.l2_distance(eef_pos, task.get_goal_pos(env_idx))
33
+ results[env_idx] = dist < self._distance_tol
34
+ return results
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/termination_condition_base.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABCMeta, abstractmethod
2
+
3
+ import torch as th
4
+
5
+ from omnigibson.utils.python_utils import Registerable, classproperty
6
+
7
+ REGISTERED_TERMINATION_CONDITIONS = dict()
8
+ REGISTERED_SUCCESS_CONDITIONS = dict()
9
+ REGISTERED_FAILURE_CONDITIONS = dict()
10
+
11
+
12
+ def register_success_condition(cls):
13
+ if cls.__name__ not in REGISTERED_SUCCESS_CONDITIONS:
14
+ REGISTERED_SUCCESS_CONDITIONS[cls.__name__] = cls
15
+
16
+
17
+ def register_failure_condition(cls):
18
+ if cls.__name__ not in REGISTERED_FAILURE_CONDITIONS:
19
+ REGISTERED_FAILURE_CONDITIONS[cls.__name__] = cls
20
+
21
+
22
+ class BaseTerminationCondition(Registerable, metaclass=ABCMeta):
23
+ """
24
+ Base TerminationCondition class
25
+ Condition-specific _step() method is implemented in subclasses
26
+ """
27
+
28
+ def __init__(self):
29
+ # Initialize internal vars that will be filled in at runtime
30
+ self._num_envs = None
31
+ self._done = None
32
+
33
+ @abstractmethod
34
+ def _step(self, task, env, action):
35
+ """
36
+ Step the termination condition and return whether the episode should terminate. Overwritten by subclasses.
37
+
38
+ Args:
39
+ task (BaseTask): Task instance
40
+ env (Environment): Environment instance
41
+ action (n-array): 1D flattened array of actions executed by all agents in the environment
42
+
43
+ Returns:
44
+ th.Tensor: (num_envs,) bool tensor indicating whether each env should terminate
45
+ """
46
+ raise NotImplementedError()
47
+
48
+ def step(self, task, env, action):
49
+ """
50
+ Step the termination condition and return whether the episode should terminate.
51
+
52
+ Args:
53
+ task (BaseTask): Task instance
54
+ env (Environment): Environment instance
55
+ action (n-array): 1D flattened array of actions executed by all agents in the environment
56
+
57
+ Returns:
58
+ 2-tuple:
59
+ - th.Tensor: (num_envs,) bool tensor indicating whether each env should terminate or not
60
+ - th.Tensor: (num_envs,) bool tensor indicating whether a success was reached under this termination condition
61
+ """
62
+ # Step internally and store the done state internally as well
63
+ self._done = self._step(task=task, env=env, action=action)
64
+
65
+ # We are successful if done is True AND this is a success condition
66
+ success = self._done & self._terminate_is_success
67
+
68
+ return self._done, success
69
+
70
+ def reset(self, task, env, env_indices):
71
+ """
72
+ Termination condition-specific reset
73
+
74
+ Args:
75
+ task (BaseTask): Task instance
76
+ env (Environment): Environment instance
77
+ env_indices (th.Tensor): Indices of environments to reset
78
+ """
79
+ if self._num_envs is None:
80
+ self._num_envs = env.num_envs
81
+ self._done = th.zeros(self._num_envs, dtype=th.bool)
82
+ self._done[env_indices] = False
83
+
84
+ @property
85
+ def done(self):
86
+ """
87
+ Returns:
88
+ th.Tensor: (num_envs,) bool tensor indicating whether this termination condition has triggered
89
+ """
90
+ assert self._done is not None, "At least one step() must occur before done can be calculated!"
91
+ return self._done
92
+
93
+ @property
94
+ def success(self):
95
+ """
96
+ Returns:
97
+ th.Tensor: (num_envs,) bool tensor indicating whether this termination condition is a success
98
+ """
99
+ assert self._done is not None, "At least one step() must occur before success can be calculated!"
100
+ return self._done & self._terminate_is_success
101
+
102
+ @classproperty
103
+ def _terminate_is_success(cls):
104
+ """
105
+ Returns:
106
+ bool: Whether this termination condition corresponds to a success
107
+ """
108
+ raise NotImplementedError()
109
+
110
+ @classproperty
111
+ def _do_not_register_classes(cls):
112
+ # Don't register this class since it's an abstract template
113
+ classes = super()._do_not_register_classes
114
+ classes.add("BaseTerminationCondition")
115
+ return classes
116
+
117
+ @classproperty
118
+ def _cls_registry(cls):
119
+ # Global registry
120
+ global REGISTERED_TERMINATION_CONDITIONS
121
+ return REGISTERED_TERMINATION_CONDITIONS
122
+
123
+
124
+ class SuccessCondition(BaseTerminationCondition):
125
+ """
126
+ Termination condition corresponding to a success
127
+ """
128
+
129
+ def __init_subclass__(cls, **kwargs):
130
+ # Register as part of locomotion controllers
131
+ super().__init_subclass__(**kwargs)
132
+ register_success_condition(cls)
133
+
134
+ @classproperty
135
+ def _terminate_is_success(cls):
136
+ # Done --> success
137
+ return True
138
+
139
+ @classproperty
140
+ def _do_not_register_classes(cls):
141
+ # Don't register this class since it's an abstract template
142
+ classes = super()._do_not_register_classes
143
+ classes.add("SuccessCondition")
144
+ return classes
145
+
146
+
147
+ class FailureCondition(BaseTerminationCondition):
148
+ """
149
+ Termination condition corresponding to a failure
150
+ """
151
+
152
+ def __init_subclass__(cls, **kwargs):
153
+ # Register as part of locomotion controllers
154
+ super().__init_subclass__(**kwargs)
155
+ register_failure_condition(cls)
156
+
157
+ @classproperty
158
+ def _terminate_is_success(cls):
159
+ # Done --> not success
160
+ return False
161
+
162
+ @classproperty
163
+ def _do_not_register_classes(cls):
164
+ # Don't register this class since it's an abstract template
165
+ classes = super()._do_not_register_classes
166
+ classes.add("FailureCondition")
167
+ return classes
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/termination_conditions/timeout.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from omnigibson.termination_conditions.termination_condition_base import FailureCondition
2
+
3
+
4
+ class Timeout(FailureCondition):
5
+ """
6
+ Timeout (failure condition)
7
+ Episode terminates if max_step steps have passed
8
+
9
+ Args:
10
+ max_steps (int): Maximum number of episode steps before timeout occurs
11
+ """
12
+
13
+ def __init__(self, max_steps=500):
14
+ # Store internal vars
15
+ self._max_steps = max_steps
16
+
17
+ # Run super
18
+ super().__init__()
19
+
20
+ def _step(self, task, env, action):
21
+ # Terminate if number of steps passed exceeds threshold
22
+ # env.episode_steps is (num_envs,) tensor
23
+ return env.episode_steps >= self._max_steps
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/transition_rules.py ADDED
The diff for this file is too large to render. See raw diff
 
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/__init__.py ADDED
File without changes
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_conversion_utils.py ADDED
The diff for this file is too large to render. See raw diff
 
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/asset_utils.py ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import contextlib
3
+ from importlib.metadata import version
4
+ import inspect
5
+ import json
6
+ import os
7
+ from packaging.version import Version
8
+ import pathlib
9
+ import shutil
10
+ import subprocess
11
+ import tempfile
12
+ from collections import defaultdict
13
+ from copy import deepcopy
14
+ from pathlib import Path
15
+ from urllib.request import urlretrieve
16
+ import zipfile
17
+
18
+ from huggingface_hub import hf_hub_download
19
+ from cryptography.fernet import Fernet
20
+
21
+ import omnigibson as og
22
+ from omnigibson.macros import gm
23
+ from omnigibson.utils.ui_utils import create_module_logger
24
+
25
+ if os.getenv("OMNIGIBSON_NO_OMNIVERSE", default=0) != "1":
26
+ import omnigibson.lazy as lazy
27
+
28
+ # Create module logger
29
+ log = create_module_logger(module_name=__name__)
30
+
31
+ # The latest version of the dataset that should be downloaded
32
+ BEHAVIOR_1K_ASSET_VERSION = "3.9.0"
33
+ OMNIGIBSON_ROBOT_ASSETS_VERSION = "3.8.2"
34
+ # The minimum compatible version of the dataset that should be used.
35
+ MINIMUM_ROBOT_ASSETS_VERSION = "3.8.2"
36
+
37
+
38
+ def is_dot_file(p):
39
+ """
40
+ Check if a filename starts with a dot.
41
+ Note that while this does not actually correspond to checking for hidden files on Windows, the
42
+ files we want to ignore will still start with a dot and thus this works.
43
+
44
+ Returns:
45
+ bool: true if a folder is hidden in the OS
46
+ """
47
+ return p.startswith(".")
48
+
49
+
50
+ def get_dataset_path(dataset_name):
51
+ return os.path.join(gm.DATA_PATH, dataset_name)
52
+
53
+
54
+ def get_key_path():
55
+ return os.path.join(gm.DATA_PATH, "omnigibson.key")
56
+
57
+
58
+ def get_avg_category_specs():
59
+ """
60
+ Load average object specs (dimension and mass) for objects
61
+
62
+ Returns:
63
+ dict: Average category specifications for all object categories
64
+ """
65
+ avg_obj_dim_file = os.path.join(og.example_config_path, "avg_category_specs.json")
66
+ if os.path.exists(avg_obj_dim_file):
67
+ with open(avg_obj_dim_file) as f:
68
+ return json.load(f)
69
+ else:
70
+ log.warning(
71
+ "Requested average specs of the object categories in the BEHAVIOR-1K Dataset of objects, but the "
72
+ "file cannot be found. Did you download the dataset? Returning an empty dictionary"
73
+ )
74
+ return dict()
75
+
76
+
77
+ def get_behavior_1k_category_ids():
78
+ """
79
+ Get OmniGibson object categories
80
+
81
+ Returns:
82
+ str: file path to the scene name
83
+ """
84
+ behavior_1k_assets_path = get_dataset_path("behavior-1k-assets")
85
+ categories_files = os.path.join(behavior_1k_assets_path, "metadata", "categories.txt")
86
+ name_to_id = {}
87
+ with open(categories_files, "r") as fp:
88
+ for i, l in enumerate(fp.readlines()):
89
+ name_to_id[l.rstrip()] = i
90
+ return defaultdict(lambda: 255, name_to_id)
91
+
92
+
93
+ def get_available_behavior_1k_scenes():
94
+ """
95
+ OmniGibson interactive scenes
96
+
97
+ Returns:
98
+ list: Available OmniGibson interactive scenes
99
+ """
100
+ behavior_1k_assets_path = get_dataset_path("behavior-1k-assets")
101
+ behavior_1k_scenes_path = os.path.join(behavior_1k_assets_path, "scenes")
102
+ available_behavior_1k_scenes = sorted(
103
+ [f for f in os.listdir(behavior_1k_scenes_path) if (not is_dot_file(f) and f != "background")]
104
+ )
105
+ return available_behavior_1k_scenes
106
+
107
+
108
+ def get_scene_path(scene_name, dataset_name="behavior-1k-assets"):
109
+ """
110
+ Get OmniGibson scene path
111
+
112
+ Args:
113
+ scene_name (str): scene name, e.g., "Rs_int"
114
+
115
+ Returns:
116
+ str: file path to the scene name
117
+ """
118
+ dataset_path = get_dataset_path(dataset_name)
119
+ scenes_path = os.path.join(dataset_path, "scenes")
120
+ log.info("Scene name: {}".format(scene_name))
121
+ assert scene_name in os.listdir(scenes_path), "Scene {} does not exist".format(scene_name)
122
+ return os.path.join(scenes_path, scene_name)
123
+
124
+
125
+ def get_task_instance_path(scene_name, instance_name, mode="train"):
126
+ """
127
+ Get task instance path
128
+
129
+ Args:
130
+ scene_name (str): scene name, e.g., "Rs_int"
131
+ instance_name (str): instance name, e.g., "house_double_floor_lower_task_turning_on_radio_0_0_template"
132
+ mode (str): Instance split to load. One of "train", "public_test", or "hidden_test".
133
+
134
+ Returns:
135
+ str: file path to the scene name
136
+ """
137
+ mode_to_dir = {
138
+ "train": "scenes",
139
+ "public_test": os.path.join("scene_test", "public"),
140
+ "hidden_test": os.path.join("scene_test", "private"),
141
+ }
142
+ assert mode in mode_to_dir, f"Invalid task instance mode: {mode}"
143
+ task_instances_path_2026 = os.path.join(
144
+ gm.DATA_PATH, "2026-challenge-task-instances", mode_to_dir[mode], scene_name, "json", f"{instance_name}.json"
145
+ )
146
+ return task_instances_path_2026 if os.path.exists(task_instances_path_2026) else None
147
+
148
+
149
+ def get_category_path(category_name, dataset_name="behavior-1k-assets"):
150
+ """
151
+ Get OmniGibson object category path
152
+
153
+ Args:
154
+ category_name (str): object category
155
+
156
+ Returns:
157
+ str: file path to the object category
158
+ """
159
+ dataset_path = get_dataset_path(dataset_name)
160
+ categories_path = os.path.join(dataset_path, "objects")
161
+ assert category_name in os.listdir(categories_path), "Category {} does not exist".format(category_name)
162
+ return os.path.join(categories_path, category_name)
163
+
164
+
165
+ def get_model_path(category_name, model_name, dataset_name="behavior-1k-assets"):
166
+ """
167
+ Get OmniGibson object model path
168
+
169
+ Args:
170
+ category_name (str): object category
171
+ model_name (str): object model
172
+
173
+ Returns:
174
+ str: file path to the object model
175
+ """
176
+ category_path = get_category_path(category_name, dataset_name=dataset_name)
177
+ assert model_name in os.listdir(category_path), "Model {} from category {} in dataset {} does not exist".format(
178
+ model_name, category_name, dataset_name
179
+ )
180
+ return os.path.join(category_path, model_name)
181
+
182
+
183
+ def get_all_system_categories(include_cloth=False):
184
+ """
185
+ Get OmniGibson all system categories
186
+
187
+ Args:
188
+ include_cloth (bool): whether to include cloth category; default to only include non-cloth particle systems
189
+
190
+ Returns:
191
+ list: all system categories
192
+ """
193
+ behavior_1k_assets_path = get_dataset_path("behavior-1k-assets")
194
+ categories_path = os.path.join(behavior_1k_assets_path, "systems")
195
+
196
+ categories = [f for f in os.listdir(categories_path) if not is_dot_file(f)]
197
+ if include_cloth:
198
+ categories.append("cloth")
199
+ return sorted(categories)
200
+
201
+
202
+ def get_all_object_categories():
203
+ """
204
+ Get OmniGibson all object categories
205
+
206
+ Returns:
207
+ list: all object categories
208
+ """
209
+ categories = {x.name for x in Path(gm.DATA_PATH).glob("*/objects/*") if x.is_dir() and not is_dot_file(x.name)}
210
+ return sorted(categories)
211
+
212
+
213
+ def get_all_object_models():
214
+ """
215
+ Get OmniGibson all object models
216
+
217
+ Returns:
218
+ list: all object model paths
219
+ """
220
+ return sorted({str(x) for x in Path(gm.DATA_PATH).glob("*/objects/*/*") if x.is_dir() and not is_dot_file(x.name)})
221
+
222
+
223
+ def get_all_object_category_models(category):
224
+ """
225
+ Get all object models from @category
226
+
227
+ Args:
228
+ category (str): Object category name
229
+
230
+ Returns:
231
+ list of str: all object models belonging to @category
232
+ """
233
+ behavior_1k_assets_path = get_dataset_path("behavior-1k-assets")
234
+ categories_path = os.path.join(behavior_1k_assets_path, "objects", category)
235
+ return sorted(os.listdir(categories_path)) if os.path.exists(categories_path) else []
236
+
237
+
238
+ def get_all_object_category_models_with_abilities(category, abilities):
239
+ """
240
+ Get all object models from @category whose assets are properly annotated with necessary requirements to support
241
+ abilities @abilities
242
+
243
+ Args:
244
+ category (str): Object category name
245
+ abilities (dict): Dictionary mapping requested abilities to keyword arguments to pass to the corresponding
246
+ object state constructors. The abilities' required annotations will be guaranteed for the returned
247
+ models
248
+
249
+ Returns:
250
+ list of str: all object models belonging to @category which are properly annotated with necessary requirements
251
+ to support the requested list of @abilities
252
+ """
253
+ # Avoid circular imports
254
+ from omnigibson.object_states.factory import get_requirements_for_ability, get_states_and_params_for_ability
255
+ from omnigibson.objects.dataset_object import DatasetObject
256
+
257
+ # Get all valid models
258
+ all_models = get_all_object_category_models(category=category)
259
+
260
+ # Generate all object states required per object given the requested set of abilities. We must
261
+ # apply the same per-(ability, state) param transform that object hydration uses (via the shared
262
+ # get_states_and_params_for_ability helper), otherwise a state's asset compatibility is checked
263
+ # with the wrong kwargs -- e.g. flammable's HeatSourceOrSink would be validated with
264
+ # requires_on_fire=False and wrongly demand a heatsource meta link.
265
+ abilities_info = {
266
+ ability: get_states_and_params_for_ability(ability, params) for ability, params in abilities.items()
267
+ }
268
+
269
+ # Get mapping for class init kwargs
270
+ state_init_default_kwargs = dict()
271
+
272
+ for ability, state_types_and_params in abilities_info.items():
273
+ for state_type, _ in state_types_and_params:
274
+ # Add each state's dependencies, too. Note that only required dependencies are added.
275
+ for dependency in state_type.get_dependencies():
276
+ if all(other_state != dependency for other_state, _ in state_types_and_params):
277
+ state_types_and_params.append((dependency, dict()))
278
+
279
+ for state_type, _ in state_types_and_params:
280
+ default_kwargs = inspect.signature(state_type.__init__).parameters
281
+ state_init_default_kwargs[state_type] = {
282
+ kwarg: val.default
283
+ for kwarg, val in default_kwargs.items()
284
+ if kwarg != "self" and val.default != inspect._empty
285
+ }
286
+
287
+ # Iterate over all models and sanity check each one, making sure they satisfy all the requested @abilities
288
+ valid_models = []
289
+
290
+ def supports_abilities(info, obj_prim):
291
+ for ability, states_and_params in info.items():
292
+ # Check ability requirements
293
+ for requirement in get_requirements_for_ability(ability):
294
+ if not requirement.is_compatible_asset(prim=obj_prim)[0]:
295
+ return False
296
+
297
+ # Check all link states
298
+ for state_type, params in states_and_params:
299
+ kwargs = deepcopy(state_init_default_kwargs[state_type])
300
+ kwargs.update(params)
301
+ if not state_type.is_compatible_asset(prim=obj_prim, **kwargs)[0]:
302
+ return False
303
+ return True
304
+
305
+ for model in all_models:
306
+ usd_path = DatasetObject.get_usd_path(category=category, model=model)
307
+ usd_path = usd_path.replace(".usd", ".encrypted.usd")
308
+ with decrypted(usd_path) as fpath:
309
+ stage = lazy.pxr.Usd.Stage.Open(fpath)
310
+ prim = stage.GetDefaultPrim()
311
+ if supports_abilities(abilities_info, prim):
312
+ valid_models.append(model)
313
+
314
+ return valid_models
315
+
316
+
317
+ def get_attachment_meta_links(category, model):
318
+ """
319
+ Get attachment meta links for an object model
320
+
321
+ Args:
322
+ category (str): Object category name
323
+ model (str): Object model name
324
+
325
+ Returns:
326
+ list of str: all attachment meta links for the object model
327
+ """
328
+ # Avoid circular imports
329
+ from omnigibson.object_states import AttachedTo
330
+ from omnigibson.objects.dataset_object import DatasetObject
331
+
332
+ usd_path = DatasetObject.get_usd_path(category=category, model=model)
333
+ usd_path = usd_path.replace(".usd", ".encrypted.usd")
334
+ with decrypted(usd_path) as fpath:
335
+ stage = lazy.pxr.Usd.Stage.Open(fpath)
336
+ prim = stage.GetDefaultPrim()
337
+ attachment_meta_links = []
338
+ for child in prim.GetChildren():
339
+ if child.GetTypeName() == "Xform":
340
+ if any(meta_link_type in child.GetName() for meta_link_type in AttachedTo.meta_link_types):
341
+ attachment_meta_links.append(child.GetName())
342
+ return attachment_meta_links
343
+
344
+
345
+ def get_omnigibson_robot_asset_version():
346
+ """
347
+ Returns:
348
+ str: OmniGibson assets version
349
+ """
350
+ try:
351
+ return (Path(get_dataset_path("omnigibson-robot-assets")) / "VERSION").read_text().strip()
352
+ except FileNotFoundError:
353
+ return None
354
+
355
+
356
+ def get_omnigibson_git_hash():
357
+ """
358
+ Returns:
359
+ str: OmniGibson commit hash
360
+ """
361
+ try:
362
+ git_hash = subprocess.check_output(
363
+ ["git", "-C", Path(og.__file__).parent, "rev-parse", "HEAD"], shell=False, stderr=subprocess.DEVNULL
364
+ )
365
+ return git_hash.decode("utf-8").strip()
366
+ except subprocess.CalledProcessError:
367
+ return None
368
+
369
+
370
+ def get_omnigibson_version():
371
+ return og.__version__
372
+
373
+
374
+ def get_bddl_version():
375
+ return version("bddl")
376
+
377
+
378
+ def get_behavior_1k_assets_version():
379
+ """
380
+ Returns:
381
+ str: BEHAVIOR-1K dataset version
382
+ """
383
+ try:
384
+ return (Path(get_dataset_path("behavior-1k-assets")) / "VERSION").read_text().strip()
385
+ except FileNotFoundError:
386
+ return None
387
+
388
+
389
+ def check_minimum_behavior_1k_assets_version(min_version_str):
390
+ current_version = get_behavior_1k_assets_version()
391
+ if current_version is None:
392
+ return False
393
+
394
+ return Version(current_version) >= Version(min_version_str)
395
+
396
+
397
+ def get_texture_file(mesh_file):
398
+ """
399
+ Get texture file
400
+
401
+ Args:
402
+ mesh_file (str): path to mesh obj file
403
+
404
+ Returns:
405
+ str: texture file path
406
+ """
407
+ model_dir = os.path.dirname(mesh_file)
408
+ with open(mesh_file, "r") as f:
409
+ lines = [line.strip() for line in f.readlines() if "mtllib" in line]
410
+ if len(lines) == 0:
411
+ return
412
+ mtl_file = lines[0].split()[1]
413
+ mtl_file = os.path.join(model_dir, mtl_file)
414
+
415
+ with open(mtl_file, "r") as f:
416
+ lines = [line.strip() for line in f.readlines() if "map_Kd" in line]
417
+ if len(lines) == 0:
418
+ return
419
+ texture_file = lines[0].split()[1]
420
+ texture_file = os.path.join(model_dir, texture_file)
421
+
422
+ return texture_file
423
+
424
+
425
+ def download_and_unpack_zipped_dataset(dataset_name):
426
+ tempdir = tempfile.mkdtemp()
427
+ real_target = get_dataset_path(dataset_name)
428
+ if dataset_name == "behavior-1k-assets":
429
+ online_filename = f"behavior-1k-assets-{BEHAVIOR_1K_ASSET_VERSION}.zip"
430
+ elif dataset_name == "omnigibson-robot-assets":
431
+ online_filename = f"omnigibson-robot-assets-{OMNIGIBSON_ROBOT_ASSETS_VERSION}.zip"
432
+ else:
433
+ online_filename = f"{dataset_name}.zip"
434
+ local_path = hf_hub_download(
435
+ repo_id="behavior-1k/zipped-datasets",
436
+ filename=online_filename,
437
+ repo_type="dataset",
438
+ local_dir=tempdir,
439
+ )
440
+ with zipfile.ZipFile(local_path, "r") as zip_ref:
441
+ zip_ref.extractall(real_target)
442
+ shutil.rmtree(tempdir)
443
+
444
+
445
+ def ensure_omnigibson_robot_assets_version():
446
+ current_version = get_omnigibson_robot_asset_version()
447
+ if current_version is None or Version(current_version) < Version(MINIMUM_ROBOT_ASSETS_VERSION):
448
+ raise RuntimeError(
449
+ f"OmniGibson robot assets version {current_version} is older than the minimum compatible version "
450
+ f"{MINIMUM_ROBOT_ASSETS_VERSION}. Please run `python -m omnigibson.utils.asset_utils --update_omnigibson_robot_assets` to remove the existing installation and redownload."
451
+ )
452
+
453
+
454
+ def download_omnigibson_robot_assets(upgrade: bool = False):
455
+ """
456
+ Download OmniGibson robot assets
457
+
458
+ Args:
459
+ upgrade (bool): If True, remove existing installation and redownload if no version or older version
460
+ """
461
+ dataset_path = get_dataset_path("omnigibson-robot-assets")
462
+ current_version = get_omnigibson_robot_asset_version()
463
+ needs_upgrade = current_version is None or Version(current_version) < Version(MINIMUM_ROBOT_ASSETS_VERSION)
464
+ upgraded = False
465
+ if os.path.exists(dataset_path):
466
+ if upgrade and needs_upgrade:
467
+ print(f"Removing existing omnigibson-robot-assets (version: {current_version}) to upgrade...")
468
+ shutil.rmtree(dataset_path)
469
+ download_and_unpack_zipped_dataset("omnigibson-robot-assets")
470
+ upgraded = True
471
+ else:
472
+ print(f"OmniGibson robot assets already downloaded (version: {current_version}).")
473
+ else:
474
+ download_and_unpack_zipped_dataset("omnigibson-robot-assets")
475
+ upgraded = True
476
+ if upgraded:
477
+ new_version = get_omnigibson_robot_asset_version()
478
+ print(f"Successfully downloaded OmniGibson robot assets version {new_version}.")
479
+
480
+
481
+ def print_user_agreement():
482
+ print(
483
+ "\n\nBEHAVIOR DATA BUNDLE END USER LICENSE AGREEMENT\n"
484
+ "Last revision: December 8, 2022\n"
485
+ "This License Agreement is for the BEHAVIOR Data Bundle (“Data”). It works with OmniGibson (“Software”) which is a software stack licensed under the MIT License, provided in this repository: https://github.com/StanfordVL/OmniGibson. The license agreements for OmniGibson and the Data are independent. This BEHAVIOR Data Bundle contains artwork and images (“Third Party Content”) from third parties with restrictions on redistribution. It requires measures to protect the Third Party Content which we have taken such as encryption and the inclusion of restrictions on any reverse engineering and use. Recipient is granted the right to use the Data under the following terms and conditions of this License Agreement (“Agreement”):\n\n"
486
+ '1. Use of the Data is permitted after responding "Yes" to this agreement. A decryption key will be installed automatically.\n'
487
+ "2. Data may only be used for non-commercial academic research. You may not use a Data for any other purpose.\n"
488
+ "3. The Data has been encrypted. You are strictly prohibited from extracting any Data from OmniGibson or reverse engineering.\n"
489
+ "4. You may only use the Data within OmniGibson.\n"
490
+ "5. You may not redistribute the key or any other Data or elements in whole or part.\n"
491
+ '6. THE DATA AND SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR SOFTWARE OR THE USE OR OTHER DEALINGS IN THE DATA OR SOFTWARE.\n\n'
492
+ )
493
+
494
+
495
+ def download_key():
496
+ if not os.path.exists(get_key_path()):
497
+ _ = (() == ()) + (() == ())
498
+ __ = ((_ << _) << _) * _
499
+ ___ = (
500
+ ("c%"[:: (([] != []) - (() == ()))])
501
+ * (((_ << _) << _) + (((_ << _) * _) + ((_ << _) + (_ + (() == ())))))
502
+ % (
503
+ (__ + (((_ << _) << _) + (_ << _))),
504
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ * _)))),
505
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ * _)))),
506
+ (__ + (((_ << _) << _) + ((_ << _) * _))),
507
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
508
+ (((_ << _) << _) + (((_ << _) * _) + ((_ << _) + _))),
509
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))),
510
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))),
511
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
512
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ * _)))),
513
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
514
+ (__ + (((_ << _) << _) + (((_ << _) * _) + _))),
515
+ (__ + (((_ << _) << _) + (() == ()))),
516
+ (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))),
517
+ (__ + (((_ << _) << _) + ((_ * _) + (() == ())))),
518
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + _))),
519
+ (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))),
520
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
521
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
522
+ (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))),
523
+ (__ + (((_ << _) << _) + ((_ << _) + (_ * _)))),
524
+ (__ + (((_ << _) << _) + ((_ * _) + (() == ())))),
525
+ (__ + (((_ << _) << _) + (() == ()))),
526
+ (__ + (((_ << _) << _) + ((_ << _) * _))),
527
+ (__ + (((_ << _) << _) + ((_ << _) + (() == ())))),
528
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
529
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + _))),
530
+ (__ + (((_ << _) << _) + (_ + (() == ())))),
531
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
532
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (() == ()))))),
533
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))),
534
+ (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))),
535
+ (__ + (((_ << _) << _) + ((_ << _) + (() == ())))),
536
+ (__ + (((_ << _) << _) + _)),
537
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
538
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
539
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))),
540
+ (__ + (((_ << _) * _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
541
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
542
+ (__ + (((_ << _) << _) + (_ + (() == ())))),
543
+ (__ + (((_ << _) << _) + ((_ * _) + (() == ())))),
544
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))),
545
+ (__ + (((_ << _) << _) + ((_ * _) + (() == ())))),
546
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
547
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ()))))),
548
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
549
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (() == ()))))),
550
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))),
551
+ (__ + (((_ << _) << _) + ((_ << _) + (() == ())))),
552
+ (__ + (((_ << _) << _) + ((_ * _) + (_ + (() == ()))))),
553
+ (__ + (((_ << _) << _) + ((_ << _) + (() == ())))),
554
+ (__ + (((_ << _) << _) + _)),
555
+ (__ + (((_ << _) << _) + (((_ << _) * _) + (_ + (() == ()))))),
556
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + (_ + (() == ())))))),
557
+ (__ + (((_ << _) << _) + ((_ << _) + ((_ * _) + _)))),
558
+ (((_ << _) << _) + ((_ << _) + ((_ * _) + _))),
559
+ (__ + (((_ << _) << _) + ((_ << _) + (_ + (() == ()))))),
560
+ (__ + (((_ << _) << _) + ((_ * _) + (() == ())))),
561
+ (__ + (((_ << _) << _) + (((_ << _) * _) + ((_ << _) + (() == ()))))),
562
+ )
563
+ )
564
+ path = ___
565
+ assert urlretrieve(path, get_key_path()), "Key download failed."
566
+
567
+
568
+ def download_behavior_1k_assets(accept_license=False):
569
+ """
570
+ Download BEHAVIOR-1K dataset
571
+ """
572
+ # Print user agreement
573
+ if os.path.exists(get_key_path()):
574
+ print("BEHAVIOR-1K dataset encryption key already installed.")
575
+ else:
576
+ if not accept_license:
577
+ print("\n")
578
+ print_user_agreement()
579
+ while input("Do you agree to the above terms for using BEHAVIOR-1K dataset? [y/n]") != "y":
580
+ print("You need to agree to the terms for using BEHAVIOR-1K dataset.")
581
+
582
+ download_key()
583
+
584
+ if os.path.exists(get_dataset_path("behavior-1k-assets")):
585
+ print("BEHAVIOR-1K dataset already installed.")
586
+ else:
587
+ download_and_unpack_zipped_dataset("behavior-1k-assets")
588
+
589
+
590
+ def download_2026_challenge_task_instances():
591
+ if not os.path.exists(get_dataset_path("2026-challenge-task-instances")):
592
+ download_and_unpack_zipped_dataset("2026-challenge-task-instances")
593
+ print("2026 BEHAVIOR Challenge Task Instances updated.")
594
+
595
+
596
+ def download_2025_challenge_task_instances():
597
+ if not os.path.exists(get_dataset_path("2025-challenge-task-instances")):
598
+ download_and_unpack_zipped_dataset("2025-challenge-task-instances")
599
+ print("2025 BEHAVIOR Challenge Tasks Instances updated.")
600
+
601
+
602
+ def decrypt_file(encrypted_filename, decrypted_filename):
603
+ with open(get_key_path(), "rb") as filekey:
604
+ key = filekey.read()
605
+ fernet = Fernet(key)
606
+
607
+ with open(encrypted_filename, "rb") as enc_f:
608
+ encrypted = enc_f.read()
609
+
610
+ decrypted = fernet.decrypt(encrypted)
611
+
612
+ with open(decrypted_filename, "wb") as decrypted_file:
613
+ decrypted_file.write(decrypted)
614
+
615
+
616
+ def encrypt_file(original_filename, encrypted_filename=None, encrypted_file=None):
617
+ with open(get_key_path(), "rb") as filekey:
618
+ key = filekey.read()
619
+ fernet = Fernet(key)
620
+
621
+ with open(original_filename, "rb") as org_f:
622
+ original = org_f.read()
623
+
624
+ encrypted = fernet.encrypt(original)
625
+
626
+ if encrypted_file is not None:
627
+ encrypted_file.write(encrypted)
628
+ else:
629
+ with open(encrypted_filename, "wb") as encrypted_file:
630
+ encrypted_file.write(encrypted)
631
+
632
+
633
+ @contextlib.contextmanager
634
+ def decrypted(encrypted_filename):
635
+ decrypted_filename_template = pathlib.Path(encrypted_filename.replace(".encrypted", ""))
636
+ decrypted_fd, decrypted_filename = tempfile.mkstemp(
637
+ suffix=decrypted_filename_template.suffix, prefix=decrypted_filename_template.stem, dir=og.tempdir
638
+ )
639
+ os.close(decrypted_fd)
640
+ decrypt_file(encrypted_filename=encrypted_filename, decrypted_filename=decrypted_filename)
641
+ yield decrypted_filename
642
+ os.remove(decrypted_filename)
643
+
644
+
645
+ if __name__ == "__main__":
646
+ parser = argparse.ArgumentParser()
647
+ parser.add_argument("--download_omnigibson_robot_assets", action="store_true", help="download assets file")
648
+ parser.add_argument("--update_omnigibson_robot_assets", action="store_true", help="update assets file")
649
+ parser.add_argument("--download_behavior_1k_assets", action="store_true", help="download BEHAVIOR-1K Dataset")
650
+ parser.add_argument(
651
+ "--download_2025_challenge_task_instances",
652
+ action="store_true",
653
+ help="download 2025 BEHAVIOR Challenge Tasks dataset",
654
+ )
655
+ parser.add_argument(
656
+ "--download_2026_challenge_task_instances",
657
+ action="store_true",
658
+ help="download 2026 BEHAVIOR Challenge Tasks dataset",
659
+ )
660
+ parser.add_argument("--accept_license", action="store_true", help="pre-accept the BEHAVIOR-1K dataset license")
661
+ args = parser.parse_args()
662
+
663
+ if args.download_omnigibson_robot_assets:
664
+ download_omnigibson_robot_assets()
665
+ if args.update_omnigibson_robot_assets:
666
+ download_omnigibson_robot_assets(upgrade=True)
667
+ if args.download_behavior_1k_assets:
668
+ download_behavior_1k_assets(accept_license=args.accept_license)
669
+ if args.download_2025_challenge_task_instances:
670
+ download_2025_challenge_task_instances()
671
+ if args.download_2026_challenge_task_instances:
672
+ download_2026_challenge_task_instances()
673
+
674
+ og.shutdown()
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/backend_utils.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch as th
3
+
4
+ import omnigibson.utils.transform_utils as TT
5
+ import omnigibson.utils.transform_utils_np as NT
6
+
7
+
8
+ # Global function for adding custom compute functions
9
+ def add_compute_function(name, np_function, th_function):
10
+ """
11
+ Adds a custom compute function defined by @name
12
+
13
+ Args:
14
+ name (str): name of the function to add
15
+ np_function (callable): numpy version of the function
16
+ th_function (callable): torch version of the function
17
+ """
18
+ _ComputeNumpyBackend.set_custom_method(name, np_function)
19
+ _ComputeTorchBackend.set_custom_method(name, th_function)
20
+
21
+
22
+ class _ComputeBackend:
23
+ # Dictionary mapping custom externally-defined function name to function
24
+ _custom_fcns = None
25
+
26
+ array = None
27
+ int_array = None
28
+ bool_array = None
29
+ bool_zeros = None
30
+ prod = None
31
+ cat = None
32
+ zeros = None
33
+ ones = None
34
+ to_numpy = None
35
+ from_numpy = None
36
+ to_torch = None
37
+ from_torch = None
38
+ allclose = None
39
+ arr_type = None
40
+ as_int = None
41
+ as_float32 = None
42
+ pinv = None
43
+ meshgrid = None
44
+ full = None
45
+ logical_or = None
46
+ all = None
47
+ abs = None
48
+ sqrt = None
49
+ norm = None
50
+ mean = None
51
+ sum = None
52
+ copy = None
53
+ eye = None
54
+ view = None
55
+ arange = None
56
+ where = None
57
+ squeeze = None
58
+ T = None
59
+ indices_where = None
60
+ item_bool = None
61
+
62
+ @classmethod
63
+ def get_custom_method(cls, method_name):
64
+ """
65
+ Gets a custom method from the internal backend
66
+
67
+ Args:
68
+ method_name (str): Name of the method to get
69
+ """
70
+ return cls._custom_fcns[method_name]
71
+
72
+ @classmethod
73
+ def set_custom_method(cls, method_name, method):
74
+ """
75
+ Sets a custom method to the internal backend
76
+
77
+ Args:
78
+ method_name (str): Name of the method
79
+ method (callable): Custom method to add
80
+ """
81
+ if cls._custom_fcns is None:
82
+ cls._custom_fcns = dict()
83
+ cls._custom_fcns[method_name] = method
84
+
85
+ @classmethod
86
+ def set_methods_from_backend(cls, backend):
87
+ for attr, fcn in backend.__dict__.items():
88
+ # Do not override reserved functions
89
+ if attr.startswith("__"):
90
+ continue
91
+ # Set function to this backend
92
+ setattr(cls, attr, fcn)
93
+
94
+
95
+ class _ComputeTorchBackend(_ComputeBackend):
96
+ array = lambda *args: th.tensor(*args, dtype=th.float32)
97
+ int_array = lambda *args: th.tensor(*args, dtype=th.int32)
98
+ bool_array = lambda *args: th.tensor(*args, dtype=th.bool)
99
+ bool_zeros = lambda *args: th.zeros(*args, dtype=th.bool)
100
+ prod = th.prod
101
+ cat = th.cat
102
+ zeros = lambda *args: th.zeros(*args, dtype=th.float32)
103
+ ones = lambda *args: th.ones(*args, dtype=th.float32)
104
+ to_numpy = lambda x: x.numpy()
105
+ from_numpy = lambda x: th.from_numpy(x) if isinstance(x, np.ndarray) else th.as_tensor(x)
106
+ to_torch = lambda x: x
107
+ from_torch = lambda x: x
108
+ allclose = th.allclose
109
+ arr_type = th.Tensor
110
+ as_int = lambda arr: arr.int()
111
+ as_float32 = lambda arr: arr.float()
112
+ pinv = th.linalg.pinv
113
+ meshgrid = lambda idx_a, idx_b: th.meshgrid(idx_a, idx_b, indexing="xy")
114
+ full = lambda shape, fill_value: th.full(shape, fill_value, dtype=th.float32)
115
+ logical_or = th.logical_or
116
+ all = th.all
117
+ abs = th.abs
118
+ sqrt = th.sqrt
119
+ norm = lambda val, dim=None, keepdim=False: th.norm(val, dim=dim, keepdim=keepdim)
120
+ mean = lambda val, dim=None, keepdim=False: th.mean(val, dim=dim, keepdim=keepdim)
121
+ sum = lambda val, dim=None, keepdim=False: th.sum(val, dim=dim, keepdim=keepdim)
122
+ copy = lambda arr: arr.clone()
123
+ eye = th.eye
124
+ view = lambda arr, shape: arr.view(shape)
125
+ arange = th.arange
126
+ where = th.where
127
+ squeeze = lambda arr, dim=None: arr.squeeze(dim=dim)
128
+ T = TT
129
+ indices_where = lambda mask: th.nonzero(mask, as_tuple=False).squeeze(-1)
130
+ item_bool = lambda x: bool(x.item())
131
+ item_int = lambda x: int(x.item())
132
+ item_float = lambda x: float(x.item())
133
+
134
+
135
+ class _ComputeNumpyBackend(_ComputeBackend):
136
+ array = lambda *args: np.array(*args, dtype=np.float32)
137
+ int_array = lambda *args: np.array(*args, dtype=np.int32)
138
+ bool_array = lambda *args: np.array(*args, dtype=bool)
139
+ bool_zeros = lambda *args: np.zeros(*args, dtype=bool)
140
+ prod = np.prod
141
+ cat = lambda tensors, dim=0: np.concatenate(tensors, axis=dim)
142
+ zeros = lambda *args: np.zeros(*args, dtype=np.float32)
143
+ ones = lambda *args: np.ones(*args, dtype=np.float32)
144
+ to_numpy = lambda x: x
145
+ from_numpy = lambda x: x
146
+ to_torch = lambda x: th.from_numpy(x) if isinstance(x, np.ndarray) else th.as_tensor(x)
147
+ from_torch = lambda x: x.numpy()
148
+ allclose = np.allclose
149
+ arr_type = np.ndarray
150
+ as_int = lambda arr: arr.astype(int)
151
+ as_float32 = lambda arr: arr.astype(np.float32)
152
+ pinv = np.linalg.pinv
153
+ meshgrid = lambda idx_a, idx_b: np.ix_(idx_a, idx_b)
154
+ full = lambda shape, fill_value: np.full(shape, fill_value, dtype=np.float32)
155
+ logical_or = np.logical_or
156
+ all = np.all
157
+ abs = np.abs
158
+ sqrt = np.sqrt
159
+ norm = lambda val, dim=None, keepdim=False: np.linalg.norm(val, axis=dim, keepdims=keepdim)
160
+ mean = lambda val, dim=None, keepdim=False: np.mean(val, axis=dim, keepdims=keepdim)
161
+ sum = lambda val, dim=None, keepdim=False: np.sum(val, axis=dim, keepdims=keepdim)
162
+ copy = lambda arr: arr.copy()
163
+ eye = np.eye
164
+ view = lambda arr, shape: arr.reshape(shape)
165
+ arange = np.arange
166
+ where = np.where
167
+ squeeze = lambda arr, dim=None: arr.squeeze(axis=dim)
168
+ T = NT
169
+ indices_where = lambda mask: np.nonzero(mask)[0]
170
+ item_bool = lambda x: bool(x)
171
+ item_int = lambda x: int(x)
172
+ item_float = lambda x: float(x)
173
+
174
+
175
+ _compute_backend = _ComputeBackend
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/bddl_utils.py ADDED
@@ -0,0 +1,1550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import re
3
+ from collections import defaultdict
4
+ from copy import deepcopy
5
+
6
+ import networkx as nx
7
+ import torch as th
8
+
9
+ from bddl.condition_evaluation import Negation
10
+ from bddl.knowledge_base import KnowledgeBase
11
+ from bddl import predicates as bddl_predicates
12
+ from bddl.predicates import Predicate
13
+
14
+ import omnigibson as og
15
+ from omnigibson import object_states
16
+ from omnigibson.macros import create_module_macros
17
+ from omnigibson.object_states.factory import _KINEMATIC_STATE_SET, get_system_states
18
+ from omnigibson.object_states.object_state_base import AbsoluteObjectState, RelativeObjectState
19
+ from omnigibson.utils.asset_utils import (
20
+ get_all_object_categories,
21
+ get_all_object_category_models_with_abilities,
22
+ get_attachment_meta_links,
23
+ )
24
+ from omnigibson.utils.constants import PrimType
25
+ from omnigibson.utils.ui_utils import create_module_logger
26
+
27
+ # Create module logger
28
+ log = create_module_logger(module_name=__name__)
29
+
30
+
31
+ # Create settings for this module
32
+ m = create_module_macros(module_path=__file__)
33
+
34
+ m.MIN_DYNAMIC_SCALE = 0.5
35
+ m.DYNAMIC_SCALE_INCREMENT = 0.1
36
+
37
+ GOOD_MODELS = {
38
+ # "jar": {"kijnrj"},
39
+ # "carton": {"causya", "msfzpz", "sxlklf"},
40
+ # "hamper": {"drgdfh", "hlgjme", "iofciz", "pdzaca", "ssfvij"},
41
+ # "hanging_plant": set(),
42
+ # "hardback": {"esxakn"},
43
+ # "notebook": {"hwhisw"},
44
+ # "paperback": {"okcflv"},
45
+ # "plant_pot": {"ihnfbi", "vhglly", "ygrtaz"},
46
+ # "pot_plant": {"cvthyv", "dbjcic", "cecdwu"},
47
+ # "recycling_bin": {"nuoypc"},
48
+ # "tray": {"gsxbym", "huwhjg", "txcjux", "uekqey", "yqtlhy"},
49
+ }
50
+
51
+ GOOD_BBOXES = {
52
+ # "basil": {
53
+ # "dkuhvb": [0.07286304, 0.0545199, 0.03108144],
54
+ # },
55
+ # "basil_jar": {
56
+ # "swytaw": [0.22969539, 0.19492961, 0.30791675],
57
+ # },
58
+ # "bicycle_chain": {
59
+ # "czrssf": [0.242, 0.012, 0.021],
60
+ # },
61
+ # "clam": {
62
+ # "ihhbfj": [0.078, 0.081, 0.034],
63
+ # },
64
+ # "envelope": {
65
+ # "urcigc": [0.004, 0.06535058, 0.10321216],
66
+ # },
67
+ # "mail": {
68
+ # "azunex": [0.19989018, 0.005, 0.12992871],
69
+ # "gvivdi": [0.28932137, 0.005, 0.17610794],
70
+ # "mbbwhn": [0.27069291, 0.005, 0.13114884],
71
+ # "ojkepk": [0.19092424, 0.005, 0.13252979],
72
+ # "qpwlor": [0.22472473, 0.005, 0.18983322],
73
+ # },
74
+ # "pill_bottle": {
75
+ # "csvdbe": [0.078, 0.078, 0.109],
76
+ # "wsasmm": [0.078, 0.078, 0.109],
77
+ # },
78
+ # "plant_pot": {
79
+ # "ihnfbi": [0.24578613, 0.2457865, 0.18862737],
80
+ # },
81
+ # "razor": {
82
+ # "jocsgp": [0.046, 0.063, 0.204],
83
+ # },
84
+ # "recycling_bin": {
85
+ # "nuoypc": [0.69529409, 0.80712041, 1.07168694],
86
+ # },
87
+ # "tupperware": {
88
+ # "mkstwr": [0.33, 0.33, 0.21],
89
+ # },
90
+ # "copper_wire": {
91
+ # "nzafel": [0.1762, 0.17655, 0.0631],
92
+ # },
93
+ # "backpack": {
94
+ # "gvbiwl": [0.7397, 0.6109, 0.6019],
95
+ # },
96
+ }
97
+
98
+ BAD_CLOTH_MODELS = {
99
+ # "bandana": {"wbhliu"},
100
+ # "curtain": {"ohvomi", "shbakk"},
101
+ # "cardigan": {"itrkhr"},
102
+ # "sweatshirt": {"nowqqh"},
103
+ # "jeans": {"nmvvil", "pvzxyp"},
104
+ # "pajamas": {"rcgdde"},
105
+ # "polo_shirt": {"vqbvph"},
106
+ # "vest": {"girtqm"}, # bddl NOT FIXED
107
+ # "onesie": {"pbytey"},
108
+ # "dishtowel": {"ltydgg"},
109
+ # "dress": {"gtghon"},
110
+ # "hammock": {"aiftuk", "fglfga", "klhkgd", "lqweda", "qewdqa"},
111
+ # "jacket": {"kiiium", "nogevo", "remcyk"},
112
+ # "quilt": {"mksdlu", "prhems"},
113
+ # "pennant": {"tfnwti"},
114
+ # "pillowcase": {"dtoahb", "yakvci"},
115
+ # "rubber_glove": {"leuiso"},
116
+ # "scarf": {"kclcrj"},
117
+ # "sock": {"vpafgj"},
118
+ # "tank_top": {"fzldgi"},
119
+ }
120
+
121
+
122
+ def synset_from_bddl_inst(bddl_inst):
123
+ """Derive synset from a BDDL instance name, e.g. 'almond.n.01_1' -> 'almond.n.01'."""
124
+ return "_".join(bddl_inst.split("_")[:-1])
125
+
126
+
127
+ def is_system_bddl_inst(bddl_inst):
128
+ """Check if a BDDL instance refers to a substance/system."""
129
+ return is_substance_synset(synset_from_bddl_inst(bddl_inst))
130
+
131
+
132
+ def og_categories_from_bddl_inst(bddl_inst):
133
+ """Get OG categories for a BDDL instance."""
134
+ synset_obj = get_knowledge_base().get_synset(synset_from_bddl_inst(bddl_inst))
135
+ synset_and_descendants = [synset_obj] + sorted(synset_obj.descendants, key=lambda s: s.name)
136
+ if synset_obj.is_substance:
137
+ return [ps.name for s in synset_and_descendants for ps in s.particle_systems]
138
+ return [c.name for s in synset_and_descendants if s.is_leaf for c in s.categories]
139
+
140
+
141
+ def is_substance_synset(synset):
142
+ synset_obj = get_knowledge_base().get_synset(synset)
143
+ return synset_obj is not None and synset_obj.is_substance
144
+
145
+
146
+ def get_system_name_by_synset(synset):
147
+ synset_obj = get_knowledge_base().get_synset(synset)
148
+ synset_and_descendants = [synset_obj] + sorted(synset_obj.descendants, key=lambda s: s.name)
149
+ systems = [ps.name for s in synset_and_descendants for ps in s.particle_systems]
150
+ assert len(systems) == 1, f"Got zero or multiple systems for {synset}: {systems}"
151
+ return systems[0]
152
+
153
+
154
+ def process_single_condition(condition):
155
+ """
156
+ Processes a single BDDL condition
157
+
158
+ Args:
159
+ condition (Condition): Condition to process
160
+
161
+ Returns:
162
+ 2-tuple:
163
+ - Expression: Condition's expression
164
+ - bool: Whether this evaluated condition is positive or negative
165
+ """
166
+ if not isinstance(condition.children[0], Negation) and not isinstance(condition.children[0], Predicate):
167
+ log.debug(("Skipping over sampling of predicate that is not a negation or a generic predicate"))
168
+ return None, None
169
+
170
+ if isinstance(condition.children[0], Negation):
171
+ condition = condition.children[0].children[0]
172
+ positive = False
173
+ else:
174
+ condition = condition.children[0]
175
+ positive = True
176
+
177
+ return condition, positive
178
+
179
+
180
+ PREDICATE_TO_STATE = {
181
+ bddl_predicates.Inside: object_states.Inside,
182
+ bddl_predicates.NextTo: object_states.NextTo,
183
+ bddl_predicates.OnTop: object_states.OnTop,
184
+ bddl_predicates.Under: object_states.Under,
185
+ bddl_predicates.Touching: object_states.Touching,
186
+ bddl_predicates.Covered: object_states.Covered,
187
+ bddl_predicates.Contains: object_states.Contains,
188
+ bddl_predicates.Saturated: object_states.Saturated,
189
+ bddl_predicates.Filled: object_states.Filled,
190
+ bddl_predicates.Cooked: object_states.Cooked,
191
+ bddl_predicates.Frozen: object_states.Frozen,
192
+ bddl_predicates.Hot: object_states.Heated,
193
+ bddl_predicates.Open: object_states.Open,
194
+ bddl_predicates.ToggledOn: object_states.ToggledOn,
195
+ bddl_predicates.OnFire: object_states.OnFire,
196
+ bddl_predicates.Attached: object_states.AttachedTo,
197
+ bddl_predicates.Overlaid: object_states.Overlaid,
198
+ bddl_predicates.Folded: object_states.Folded,
199
+ bddl_predicates.Unfolded: object_states.Unfolded,
200
+ bddl_predicates.Draped: object_states.Draped,
201
+ }
202
+
203
+ KINEMATIC_STATES_BDDL = frozenset([state.__name__.lower() for state in _KINEMATIC_STATE_SET] + ["attached"])
204
+ UNSAMPLEABLE_PREDICATES = frozenset([bddl_predicates.InSource, bddl_predicates.Future, bddl_predicates.Real])
205
+
206
+
207
+ def evaluate_bddl_predicate(predicate_cls, *entities):
208
+ """Evaluate a BDDL predicate against simulator objects.
209
+
210
+ Args:
211
+ predicate_cls: A :class:`~bddl.predicates.Predicate` subclass.
212
+ *entities: Raw simulator objects (or None for nonexistent objects).
213
+
214
+ Returns:
215
+ bool: Whether the predicate is satisfied.
216
+ """
217
+ if predicate_cls is bddl_predicates.InSource:
218
+ return True
219
+ if predicate_cls is bddl_predicates.Future:
220
+ return entities[0] is None
221
+ if predicate_cls is bddl_predicates.Real:
222
+ return entities[0] is not None
223
+
224
+ state_class = PREDICATE_TO_STATE[predicate_cls]
225
+ if predicate_cls.arity == 2:
226
+ obj1, obj2 = entities[0], entities[1]
227
+ if obj1 is None or not obj1.initialized:
228
+ return False
229
+ if obj2 is None or not obj2.initialized:
230
+ return False
231
+ return obj1.states[state_class].get_value(obj2)
232
+ else:
233
+ obj = entities[0]
234
+ if obj is None or not obj.initialized:
235
+ return False
236
+ return obj.states[state_class].get_value()
237
+
238
+
239
+ def sample_bddl_predicate(predicate_cls, *args, **kwargs):
240
+ """Request the simulator to set a BDDL predicate to a desired state.
241
+
242
+ Args:
243
+ predicate_cls: A :class:`~bddl.predicates.Predicate` subclass.
244
+ *args: For unary predicates: (obj, binary_state). For binary: (obj1, obj2, binary_state).
245
+ **kwargs: Extra arguments forwarded to set_value (e.g. reset_before_sampling).
246
+
247
+ Returns:
248
+ bool or None: Whether sampling succeeded.
249
+ """
250
+ if predicate_cls in UNSAMPLEABLE_PREDICATES:
251
+ raise NotImplementedError(f"Cannot sample unsampleable predicate: {predicate_cls.__name__}")
252
+
253
+ state_class = PREDICATE_TO_STATE[predicate_cls]
254
+ if predicate_cls.arity == 2:
255
+ obj1, obj2, binary_state = args[0], args[1], args[2]
256
+ if obj2 is None or not obj2.initialized:
257
+ return None
258
+ return obj1.states[state_class].set_value(obj2, binary_state, **kwargs)
259
+ else:
260
+ obj, binary_state = args[0], args[1]
261
+ return obj.states[state_class].set_value(binary_state, **kwargs)
262
+
263
+
264
+ # Shared KnowledgeBase instance for all of OmniGibson. Use the getter for lazy access.
265
+ _KB = None
266
+
267
+
268
+ def get_knowledge_base():
269
+ global _KB
270
+ if _KB is None:
271
+ _KB = KnowledgeBase(verbose=False)
272
+
273
+ return _KB
274
+
275
+
276
+ def get_behavior_activities():
277
+ return sorted(set(t.name.rsplit("-", 1)[0] for t in get_knowledge_base().all_tasks()))
278
+
279
+
280
+ def _populate_input_output_objects_systems(og_recipe, input_synsets, output_synsets):
281
+ # Map input/output synsets into input/output objects and systems.
282
+ for synsets, obj_key, system_key in zip(
283
+ (input_synsets, output_synsets), ("input_objects", "output_objects"), ("input_systems", "output_systems")
284
+ ):
285
+ for synset, count in synsets.items():
286
+ assert (
287
+ get_knowledge_base().get_synset(synset).is_leaf
288
+ ), f"Synset {synset} must be a leaf node in the taxonomy!"
289
+ if is_substance_synset(synset):
290
+ og_recipe[system_key].append(get_system_name_by_synset(synset))
291
+ else:
292
+ obj_categories = [c.name for c in get_knowledge_base().get_synset(synset).categories]
293
+ assert (
294
+ len(obj_categories) == 1
295
+ ), f"Object synset {synset} must map to exactly one object category! Now: {obj_categories}."
296
+ og_recipe[obj_key][obj_categories[0]] = count
297
+
298
+ # Assert only one of output_objects or output_systems is not None
299
+ assert (
300
+ len(og_recipe["output_objects"]) == 0 or len(og_recipe["output_systems"]) == 0
301
+ ), "Recipe can only generate output objects or output systems, but not both!"
302
+
303
+
304
+ def _populate_input_output_states(og_recipe, input_states, output_states):
305
+ # Apply post-processing for input/output states if specified.
306
+ # States are dicts mapping synset keys to lists of StateCondition instances.
307
+ for synsets_to_states, states_key in zip((input_states, output_states), ("input_states", "output_states")):
308
+ if synsets_to_states is None:
309
+ continue
310
+ for synsets, state_conditions in synsets_to_states.items():
311
+ # For unary/binary states, synsets is a single synset or a comma-separated pair of synsets, respectively
312
+ synset_split = synsets.split(",")
313
+ if len(synset_split) == 1:
314
+ first_synset = synset_split[0]
315
+ second_synset = None
316
+ else:
317
+ first_synset, second_synset = synset_split
318
+
319
+ # Assert the first synset is an object because the systems don't have any states.
320
+ assert (
321
+ get_knowledge_base().get_synset(first_synset).is_leaf
322
+ ), f"Input/output state synset {first_synset} must be a leaf node in the taxonomy!"
323
+ assert not is_substance_synset(
324
+ first_synset
325
+ ), f"Input/output state synset {first_synset} must be applied to an object, not a substance!"
326
+ obj_categories = [c.name for c in get_knowledge_base().get_synset(first_synset).categories]
327
+ assert (
328
+ len(obj_categories) == 1
329
+ ), f"Input/output state synset {first_synset} must map to exactly one object category! Now: {obj_categories}."
330
+ first_obj_category = obj_categories[0]
331
+
332
+ if second_synset is None:
333
+ for sc in state_conditions:
334
+ state_class = PREDICATE_TO_STATE[sc.predicate]
335
+ assert issubclass(
336
+ state_class, AbsoluteObjectState
337
+ ), f"Input/output state type {sc.predicate.__name__} must be a unary state!"
338
+ og_recipe[states_key][first_obj_category]["unary"].append((state_class, sc.value))
339
+ else:
340
+ assert (
341
+ get_knowledge_base().get_synset(second_synset).is_leaf
342
+ ), f"Input/output state synset {second_synset} must be a leaf node in the taxonomy!"
343
+ if is_substance_synset(second_synset):
344
+ second_obj_category = get_system_name_by_synset(second_synset)
345
+ is_substance = True
346
+ else:
347
+ obj_categories = [c.name for c in get_knowledge_base().get_synset(second_synset).categories]
348
+ assert (
349
+ len(obj_categories) == 1
350
+ ), f"Input/output state synset {second_synset} must map to exactly one object category! Now: {obj_categories}."
351
+ second_obj_category = obj_categories[0]
352
+ is_substance = False
353
+
354
+ for sc in state_conditions:
355
+ state_class = PREDICATE_TO_STATE[sc.predicate]
356
+ assert issubclass(
357
+ state_class, RelativeObjectState
358
+ ), f"Input/output state type {sc.predicate.__name__} must be a binary state!"
359
+ assert is_substance == (
360
+ state_class in get_system_states()
361
+ ), f"Input/output state type {sc.predicate.__name__} system state inconsistency found!"
362
+ if is_substance:
363
+ og_recipe[states_key][first_obj_category]["binary_system"].append(
364
+ (state_class, second_obj_category, sc.value)
365
+ )
366
+ else:
367
+ assert (
368
+ states_key != "output_states"
369
+ ), f"Output state type {sc.predicate.__name__} can only be used in input states!"
370
+ og_recipe[states_key][first_obj_category]["binary_object"].append(
371
+ (state_class, second_obj_category, sc.value)
372
+ )
373
+
374
+
375
+ def _populate_filter_categories(og_recipe, filter_name, synsets):
376
+ # Map synsets to categories.
377
+ if synsets is not None:
378
+ og_recipe[f"{filter_name}_categories"] = set()
379
+ for synset in synsets:
380
+ assert (
381
+ get_knowledge_base().get_synset(synset).is_leaf
382
+ ), f"Synset {synset} must be a leaf node in the taxonomy!"
383
+ assert not is_substance_synset(synset), f"Synset {synset} must be applied to an object, not a substance!"
384
+ for category in [c.name for c in get_knowledge_base().get_synset(synset).categories]:
385
+ og_recipe[f"{filter_name}_categories"].add(category)
386
+
387
+
388
+ def translate_bddl_recipe_to_og_recipe(recipe):
389
+ """Translate a BDDL Recipe dataclass to an OG recipe dict.
390
+
391
+ Args:
392
+ recipe (bddl.transition_rules.Recipe): A parsed BDDL recipe instance.
393
+
394
+ Returns:
395
+ dict: OG-format recipe dict ready for ``RecipeRule.add_recipe(**og_recipe)``.
396
+ """
397
+ from bddl.knowledge_base import CookingRecipe, MachineRecipe
398
+
399
+ # Determine fillable/heatsource synsets from recipe type
400
+ fillable_synsets = None
401
+ heatsource_synsets = None
402
+ timesteps = 1
403
+ if isinstance(recipe, CookingRecipe):
404
+ fillable_synsets = recipe.container_synsets or None
405
+ heatsource_synsets = recipe.heatsource_synsets or None
406
+ timesteps = recipe.timesteps if recipe.timesteps is not None else 1
407
+ elif isinstance(recipe, MachineRecipe):
408
+ fillable_synsets = recipe.machine_synsets or None
409
+
410
+ og_recipe = {
411
+ "name": recipe.name,
412
+ "input_objects": dict(),
413
+ "input_systems": list(),
414
+ "output_objects": dict(),
415
+ "output_systems": list(),
416
+ "input_states": defaultdict(lambda: defaultdict(list)),
417
+ "output_states": defaultdict(lambda: defaultdict(list)),
418
+ "fillable_categories": None,
419
+ "heatsource_categories": None,
420
+ "timesteps": timesteps,
421
+ }
422
+
423
+ _populate_input_output_objects_systems(
424
+ og_recipe=og_recipe, input_synsets=recipe.input_synsets, output_synsets=recipe.output_synsets
425
+ )
426
+ _populate_input_output_states(
427
+ og_recipe=og_recipe, input_states=recipe.input_states, output_states=recipe.output_states
428
+ )
429
+ _populate_filter_categories(og_recipe=og_recipe, filter_name="fillable", synsets=fillable_synsets)
430
+ _populate_filter_categories(og_recipe=og_recipe, filter_name="heatsource", synsets=heatsource_synsets)
431
+
432
+ return og_recipe
433
+
434
+
435
+ def translate_bddl_washer_rule_to_og_washer_rule(washer_rule):
436
+ """Translate a BDDL WasherRecipe to an OG washer rule dict.
437
+
438
+ Args:
439
+ washer_rule (bddl.knowledge_base.WasherRecipe): Parsed washer recipe.
440
+
441
+ Returns:
442
+ dict: Maps system name (str) to None (never remove), [] (always remove),
443
+ or list of system names (remove if any solvent present).
444
+ """
445
+ og_washer_rule = dict()
446
+ for solute, solvents in washer_rule.conditions.items():
447
+ assert get_knowledge_base().get_synset(solute).is_leaf, f"Synset {solute} must be a leaf node in the taxonomy!"
448
+ assert is_substance_synset(solute), f"Synset {solute} must be a substance synset!"
449
+ solute_name = get_system_name_by_synset(solute)
450
+ if solvents is None:
451
+ og_washer_rule[solute_name] = None
452
+ else:
453
+ solvent_names = []
454
+ for solvent in solvents:
455
+ assert (
456
+ get_knowledge_base().get_synset(solvent).is_leaf
457
+ ), f"Synset {solvent} must be a leaf node in the taxonomy!"
458
+ assert is_substance_synset(solvent), f"Synset {solvent} must be a substance synset!"
459
+ solvent_name = get_system_name_by_synset(solvent)
460
+ solvent_names.append(solvent_name)
461
+ og_washer_rule[solute_name] = solvent_names
462
+ return og_washer_rule
463
+
464
+
465
+ class BDDLSampler:
466
+ def __init__(self, env, env_idx, activity_conditions, object_scope):
467
+ # Avoid circular imports here
468
+ from omnigibson.scenes.traversable_scene import TraversableScene
469
+
470
+ # Store internal variables from inputs
471
+ self._env = env
472
+ self._scene = env.scenes[env_idx]
473
+ self._scene_model = self._scene.scene_model if isinstance(self._scene, TraversableScene) else None
474
+ self._agent = self._scene.robots[0]
475
+
476
+ self._compiled_task = None
477
+ self._activity_conditions = activity_conditions
478
+ self._object_scope = object_scope
479
+ self._object_instance_to_synset = {
480
+ obj_inst: obj_cat
481
+ for obj_cat in self._activity_conditions.parsed_objects
482
+ for obj_inst in self._activity_conditions.parsed_objects[obj_cat]
483
+ }
484
+ self._substance_instances = {
485
+ obj_inst
486
+ for obj_inst in self._object_scope.keys()
487
+ if is_substance_synset(self._object_instance_to_synset[obj_inst])
488
+ }
489
+
490
+ # Initialize other variables that will be filled in later
491
+ self._sampling_whitelist = None # Maps str to str to list
492
+ self._sampling_blacklist = None # Maps str to str to list
493
+ self._room_type_to_object_instance = None # dict
494
+ self._inroom_object_instances = None # set of str
495
+ self._object_sampling_orders = None # dict mapping str to list of str
496
+ self._sampled_objects = None # set of USDObject
497
+ self._future_obj_instances = None # set of str
498
+ self._inroom_object_conditions = None # list of (condition, positive) tuple
499
+ self._inroom_object_scope_filtered_initial = None # dict mapping str to sim object or None
500
+ self._attached_objects = defaultdict(set) # dict mapping str to set of str
501
+
502
+ def _sample_predicate(self, predicate_cls, *args, **kwargs):
503
+ """Wrapper around sample_bddl_predicate that resolves string instance names to sim objects."""
504
+ resolved = [self._object_scope.get(a, a) if isinstance(a, str) else a for a in args]
505
+ return sample_bddl_predicate(predicate_cls, *resolved, **kwargs)
506
+
507
+ def assign_objects(self, sampling_whitelist=None, sampling_blacklist=None):
508
+ """Assign inroom objects and import sampleable objects into the scene.
509
+
510
+ This is phase 1 of sampling: it finds/imports all objects needed by the
511
+ task without requiring compiled conditions. After this call, the object
512
+ scope is populated and room instances can be determined for compilation.
513
+
514
+ Args:
515
+ sampling_whitelist (None or dict): Maps synset name to dict of
516
+ category -> list of valid models.
517
+ sampling_blacklist (None or dict): Maps synset name to dict of
518
+ category -> list of invalid models.
519
+
520
+ Returns:
521
+ 2-tuple:
522
+ - bool: Whether object assignment was successful
523
+ - None or str: None if successful, otherwise the error message
524
+ """
525
+ log.info("Assigning objects for task...")
526
+ self._sampling_whitelist = sampling_whitelist
527
+ self._sampling_blacklist = sampling_blacklist
528
+
529
+ # Derive future object instances from parsed initial conditions
530
+ self._future_obj_instances = {
531
+ cond[1] for cond in self._activity_conditions.parsed_initial_conditions if cond[0] == "future"
532
+ }
533
+
534
+ error_msg = self._parse_inroom_object_room_assignment()
535
+ if error_msg:
536
+ log.error(error_msg)
537
+ return False, error_msg
538
+
539
+ error_msg = self._parse_attached_states()
540
+ if error_msg:
541
+ log.error(error_msg)
542
+ return False, error_msg
543
+
544
+ error_msg = self._build_inroom_object_scope()
545
+ if error_msg:
546
+ log.error(error_msg)
547
+ return False, error_msg
548
+
549
+ error_msg = self._import_sampleable_objects()
550
+ if error_msg:
551
+ log.error(error_msg)
552
+ return False, error_msg
553
+
554
+ self._object_scope["agent.n.01_1"] = self._agent
555
+
556
+ return True, None
557
+
558
+ def sample_states(self, compiled_task, validate_goal=False):
559
+ """Sample object states to satisfy initial (and optionally goal) conditions.
560
+
561
+ This is phase 2 of sampling: it requires a compiled task with condition
562
+ trees. Must be called after :meth:`assign_objects` and after the task
563
+ has been compiled with the correct scene layout.
564
+
565
+ Args:
566
+ compiled_task: A :class:`CompiledTask` with compiled condition trees.
567
+ validate_goal (bool): Whether the goal should also be validated.
568
+
569
+ Returns:
570
+ 2-tuple:
571
+ - bool: Whether sampling was successful
572
+ - None or str: None if successful, otherwise the error message
573
+ """
574
+ log.info("Sampling states...")
575
+ self._compiled_task = compiled_task
576
+
577
+ error_msg = self._build_sampling_order()
578
+ if error_msg:
579
+ log.error(error_msg)
580
+ return False, error_msg
581
+
582
+ accept_scene, feedback = self._sample_all_conditions(validate_goal=validate_goal)
583
+ if not accept_scene:
584
+ return accept_scene, feedback
585
+
586
+ log.info("Sampling succeeded!")
587
+ return True, None
588
+
589
+ def _sample_all_conditions(self, validate_goal=False):
590
+ """
591
+ Run sampling for this BEHAVIOR task
592
+
593
+ Args:
594
+ validate_goal (bool): Whether the goal should be validated or not
595
+
596
+ Returns:
597
+ 2-tuple:
598
+ - bool: Whether sampling was successful or not
599
+ - None or str: None if successful, otherwise the associated error message
600
+ """
601
+ # Auto-initialize all sampleable objects
602
+ og.sim.play()
603
+ try:
604
+ # Update the scene to include the latest robots / objects
605
+ self._scene.update_initial_file()
606
+ self._scene.reset()
607
+
608
+ error_msg = self._sample_initial_conditions()
609
+ if error_msg:
610
+ log.error(error_msg)
611
+ return False, error_msg
612
+
613
+ if validate_goal:
614
+ error_msg = self._sample_goal_conditions()
615
+ if error_msg:
616
+ log.error(error_msg)
617
+ return False, error_msg
618
+
619
+ error_msg = self._sample_initial_conditions_final()
620
+ if error_msg:
621
+ log.error(error_msg)
622
+ return False, error_msg
623
+
624
+ self._scene.update_initial_file()
625
+
626
+ return True, None
627
+ finally:
628
+ og.sim.stop()
629
+
630
+ def _parse_inroom_object_room_assignment(self):
631
+ """
632
+ Infers which rooms each object is assigned to
633
+ """
634
+ self._room_type_to_object_instance = dict()
635
+ self._inroom_object_instances = set()
636
+ for cond in self._activity_conditions.parsed_initial_conditions:
637
+ if cond[0] == "inroom":
638
+ obj_inst, room_type = cond[1], cond[2]
639
+ obj_synset = self._object_instance_to_synset[obj_inst]
640
+ abilities = get_knowledge_base().get_synset(obj_synset).abilities
641
+ if "sceneObject" not in abilities:
642
+ # Invalid room assignment
643
+ return (
644
+ f"You have assigned room type for [{obj_synset}], but [{obj_synset}] is sampleable. "
645
+ f"Only non-sampleable (scene) objects can have room assignment."
646
+ )
647
+ if self._scene_model is not None and room_type not in self._scene.seg_map.room_sem_name_to_ins_name:
648
+ # Missing room type
649
+ return f"Room type [{room_type}] missing in scene [{self._scene_model}]."
650
+ if room_type not in self._room_type_to_object_instance:
651
+ self._room_type_to_object_instance[room_type] = []
652
+ self._room_type_to_object_instance[room_type].append(obj_inst)
653
+
654
+ if obj_inst in self._inroom_object_instances:
655
+ # Duplicate room assignment
656
+ return f"Object [{obj_inst}] has more than one room assignment"
657
+
658
+ self._inroom_object_instances.add(obj_inst)
659
+
660
+ def _parse_attached_states(self):
661
+ """
662
+ Infers which objects are attached to which other objects.
663
+ If a category-level attachment is specified, it will be expanded to all instances of that category.
664
+ E.g. if the goal condition requires corks to be attached to bottles, every cork needs to be able to
665
+ attach to every bottle.
666
+ """
667
+ for cond in self._activity_conditions.parsed_initial_conditions:
668
+ if cond[0] == "attached":
669
+ obj_inst, parent_inst = cond[1], cond[2]
670
+ if obj_inst not in self._object_scope or parent_inst not in self._object_scope:
671
+ return f"Object [{obj_inst}] or parent [{parent_inst}] in attached initial condition not found in object scope"
672
+ self._attached_objects[obj_inst].add(parent_inst)
673
+
674
+ ground_attached_conditions = []
675
+ conditions_to_check = self._activity_conditions.parsed_goal_conditions.copy()
676
+ while conditions_to_check:
677
+ new_conditions_to_check = []
678
+ for cond in conditions_to_check:
679
+ if cond[0] == "attached":
680
+ ground_attached_conditions.append(cond)
681
+ else:
682
+ new_conditions_to_check.extend([ele for ele in cond if isinstance(ele, list)])
683
+ conditions_to_check = new_conditions_to_check
684
+
685
+ for cond in ground_attached_conditions:
686
+ obj_inst, parent_inst = cond[1].lstrip("?"), cond[2].lstrip("?")
687
+ if obj_inst in self._object_scope:
688
+ obj_insts = [obj_inst]
689
+ elif obj_inst in self._activity_conditions.parsed_objects:
690
+ obj_insts = self._activity_conditions.parsed_objects[obj_inst]
691
+ else:
692
+ return f"Object [{obj_inst}] in attached goal condition not found in object scope or parsed objects"
693
+
694
+ if parent_inst in self._object_scope:
695
+ parent_insts = [parent_inst]
696
+ elif parent_inst in self._activity_conditions.parsed_objects:
697
+ parent_insts = self._activity_conditions.parsed_objects[parent_inst]
698
+ else:
699
+ return f"Parent [{parent_inst}] in attached goal condition not found in object scope or parsed objects"
700
+
701
+ for obj_inst in obj_insts:
702
+ for parent_inst in parent_insts:
703
+ self._attached_objects[obj_inst].add(parent_inst)
704
+
705
+ def _build_sampling_order(self):
706
+ """
707
+ Sampling orders is a list of lists: [[batch_1_inst_1, ... batch_1_inst_N], [batch_2_inst_1, batch_2_inst_M], ...]
708
+ Sampling should happen for batch 1 first, then batch 2, so on and so forth
709
+ Example: OnTop(plate, table) should belong to batch 1, and OnTop(apple, plate) should belong to batch 2
710
+ """
711
+ unsampleable_conditions = []
712
+ sampling_groups = {group: [] for group in ("kinematic", "particle", "unary")}
713
+ self._object_sampling_conditions = {group: [] for group in ("kinematic", "particle", "unary")}
714
+ self._object_sampling_orders = {group: [] for group in ("kinematic", "particle", "unary")}
715
+ self._inroom_object_conditions = []
716
+
717
+ # First, sort initial conditions into kinematic, particle and unary groups
718
+ # bddl.condition_evaluation.HEAD, each with one child.
719
+ # This child is either a ObjectStateUnaryPredicate/ObjectStateBinaryPredicate or
720
+ # a Negation of a ObjectStateUnaryPredicate/ObjectStateBinaryPredicate
721
+ for condition in self._compiled_task.initial_conditions:
722
+ condition, positive = process_single_condition(condition)
723
+ if condition is None:
724
+ continue
725
+
726
+ # Sampled conditions must always be positive
727
+ # Non-positive (e.g.: NOT onTop) is not restrictive enough for sampling
728
+ if condition.STATE_NAME in KINEMATIC_STATES_BDDL and not positive:
729
+ return "Initial condition has negative kinematic conditions: {}".format(condition.body)
730
+
731
+ # Store any unsampleable conditions separately
732
+ if type(condition) in UNSAMPLEABLE_PREDICATES:
733
+ unsampleable_conditions.append(condition)
734
+ continue
735
+
736
+ # Infer the group the condition and its object instances belong to
737
+ # (a) Kinematic (binary) conditions, where (ent0, ent1) are both objects
738
+ # (b) Particle (binary) conditions, where (ent0, ent1) are (object, substance)
739
+ # (d) Unary conditions, where (ent0,) is an object
740
+ # Binary conditions have length 2: (ent0, ent1)
741
+ if len(condition.body) == 2:
742
+ group = "particle" if condition.body[1] in self._substance_instances else "kinematic"
743
+ else:
744
+ assert len(condition.body) == 1, (
745
+ f"Got invalid parsed initial condition; body length should either be 2 or 1. "
746
+ f"Got body: {condition.body} for condition: {condition}"
747
+ )
748
+ group = "unary"
749
+ sampling_groups[group].append(condition.body)
750
+ self._object_sampling_conditions[group].append((condition, positive))
751
+
752
+ # If the condition involves any non-sampleable object (e.g.: furniture), it's a non-sampleable condition
753
+ # This means that there's no ordering constraint in terms of sampling, because we know the, e.g., furniture
754
+ # object already exists in the scene and is placed, so these specific conditions can be sampled without
755
+ # any dependencies
756
+ if len(self._inroom_object_instances.intersection(set(condition.body))) > 0:
757
+ self._inroom_object_conditions.append((condition, positive))
758
+
759
+ # Now, sort each group, ignoring the futures (since they don't get sampled)
760
+ # First handle kinematics, then particles, then unary
761
+
762
+ # Start with the non-sampleable objects as the first sampled set, then infer recursively
763
+ cur_batch = self._inroom_object_instances
764
+ while len(cur_batch) > 0:
765
+ next_batch = set()
766
+ for cur_batch_inst in cur_batch:
767
+ inst_batch = set()
768
+ for condition, _ in self._object_sampling_conditions["kinematic"]:
769
+ if condition.body[1] == cur_batch_inst:
770
+ inst_batch.add(condition.body[0])
771
+ next_batch.add(condition.body[0])
772
+ if len(inst_batch) > 0:
773
+ self._object_sampling_orders["kinematic"].append(inst_batch)
774
+ cur_batch = next_batch
775
+
776
+ # Now parse particles -- simply unordered, since particle systems shouldn't impact each other
777
+ self._object_sampling_orders["particle"].append({cond[0] for cond in sampling_groups["particle"]})
778
+ sampled_particle_entities = {cond[1] for cond in sampling_groups["particle"]}
779
+
780
+ # Finally, parse unaries -- this is simply unordered, since it is assumed that unary predicates do not
781
+ # affect each other
782
+ self._object_sampling_orders["unary"].append({cond[0] for cond in sampling_groups["unary"]})
783
+
784
+ # Aggregate future objects and any unsampleable obj instances
785
+ # Unsampleable obj instances are strictly a superset of future obj instances
786
+ unsampleable_obj_instances = {cond.body[-1] for cond in unsampleable_conditions}
787
+ self._future_obj_instances = {
788
+ cond.body[0] for cond in unsampleable_conditions if isinstance(cond, bddl_predicates.Future)
789
+ }
790
+
791
+ nonparticle_entities = set(self._object_scope.keys()) - self._substance_instances
792
+
793
+ # Sanity check kinematic objects -- any non-system must be kinematically sampled
794
+ remaining_kinematic_entities = (
795
+ nonparticle_entities
796
+ - unsampleable_obj_instances
797
+ - self._inroom_object_instances
798
+ - set.union(*(self._object_sampling_orders["kinematic"] + [set()]))
799
+ )
800
+
801
+ # Possibly remove the agent entity if we're in an empty scene -- i.e.: no kinematic sampling needed for the
802
+ # agent
803
+ if self._scene_model is None:
804
+ remaining_kinematic_entities -= {"agent.n.01_1"}
805
+
806
+ if len(remaining_kinematic_entities) != 0:
807
+ return (
808
+ f"Some objects do not have any kinematic condition defined for them in the initial conditions: "
809
+ f"{', '.join(remaining_kinematic_entities)}"
810
+ )
811
+
812
+ # Sanity check particle systems -- any non-future system must be sampled as part of particle groups
813
+ remaining_particle_entities = self._substance_instances - unsampleable_obj_instances - sampled_particle_entities
814
+ if len(remaining_particle_entities) != 0:
815
+ return (
816
+ f"Some systems do not have any particle condition defined for them in the initial conditions: "
817
+ f"{', '.join(remaining_particle_entities)}"
818
+ )
819
+
820
+ def _build_inroom_object_scope(self):
821
+ """
822
+ Store simulator object options for non-sampleable objects in self.inroom_object_scope
823
+ {
824
+ "living_room": {
825
+ "table1": {
826
+ "living_room_0": [URDFObject, URDFObject, URDFObject],
827
+ "living_room_1": [URDFObject]
828
+ },
829
+ "table2": {
830
+ "living_room_0": [URDFObject, URDFObject],
831
+ "living_room_1": [URDFObject, URDFObject]
832
+ },
833
+ "chair1": {
834
+ "living_room_0": [URDFObject],
835
+ "living_room_1": [URDFObject]
836
+ },
837
+ }
838
+ }
839
+ """
840
+ room_type_to_scene_objs = {}
841
+ for room_type in self._room_type_to_object_instance:
842
+ room_type_to_scene_objs[room_type] = {}
843
+ for obj_inst in self._room_type_to_object_instance[room_type]:
844
+ room_type_to_scene_objs[room_type][obj_inst] = {}
845
+ obj_synset = self._object_instance_to_synset[obj_inst]
846
+ synset_whitelist = (
847
+ None if self._sampling_whitelist is None else self._sampling_whitelist.get(obj_synset, None)
848
+ )
849
+ synset_blacklist = (
850
+ None if self._sampling_blacklist is None else self._sampling_blacklist.get(obj_synset, None)
851
+ )
852
+
853
+ # We allow burners to be used as if they are stoves
854
+ # No need to safeguard check for subtree_substances because inroom objects will never be substances
855
+ _so = get_knowledge_base().get_synset(obj_synset)
856
+ categories = [
857
+ c.name
858
+ for s in [_so] + sorted(_so.descendants, key=lambda x: x.name)
859
+ if s.is_leaf
860
+ for c in s.categories
861
+ ]
862
+
863
+ # Grab all models that fully support all abilities for the corresponding category
864
+ valid_models = {
865
+ cat: set(
866
+ get_all_object_category_models_with_abilities(
867
+ cat, get_knowledge_base().get_category(cat).synset.abilities
868
+ )
869
+ )
870
+ for cat in categories
871
+ }
872
+ valid_models = {
873
+ cat: (models if cat not in GOOD_MODELS else models.intersection(GOOD_MODELS[cat]))
874
+ - BAD_CLOTH_MODELS.get(cat, set())
875
+ for cat, models in valid_models.items()
876
+ }
877
+ valid_models = {
878
+ cat: self._filter_model_choices_by_attached_states(models, cat, obj_inst)
879
+ for cat, models in valid_models.items()
880
+ }
881
+
882
+ # Filter based on white / blacklist
883
+ if synset_whitelist is not None:
884
+ valid_models = {
885
+ cat: models.intersection(set(synset_whitelist[cat].keys()))
886
+ if cat in synset_whitelist
887
+ else set()
888
+ for cat, models in valid_models.items()
889
+ }
890
+
891
+ if synset_blacklist is not None:
892
+ valid_models = {
893
+ cat: models - set(synset_blacklist[cat].keys()) if cat in synset_blacklist else models
894
+ for cat, models in valid_models.items()
895
+ }
896
+
897
+ room_insts = (
898
+ [None] if self._scene_model is None else self._scene.seg_map.room_sem_name_to_ins_name[room_type]
899
+ )
900
+ for room_inst in room_insts:
901
+ # A list of scene objects that satisfy the requested categories
902
+ room_objs = self._scene.object_registry("in_rooms", room_inst, default_val=[])
903
+ scene_objs = [
904
+ obj
905
+ for obj in room_objs
906
+ if obj.category in categories and obj.model in valid_models[obj.category]
907
+ ]
908
+
909
+ if len(scene_objs) != 0:
910
+ room_type_to_scene_objs[room_type][obj_inst][room_inst] = scene_objs
911
+
912
+ error_msg = self._consolidate_room_instance(room_type_to_scene_objs, "initial_pre-sampling")
913
+ if error_msg:
914
+ return error_msg
915
+ self._inroom_object_scope = room_type_to_scene_objs
916
+
917
+ def _filter_object_scope(self, input_object_scope, conditions, condition_type):
918
+ """
919
+ Filters the object scope based on given @input_object_scope, @conditions, and @condition_type
920
+
921
+ Args:
922
+ input_object_scope (dict):
923
+ conditions (list): List of conditions to filter scope with, where each list entry is
924
+ a tuple of (condition, positive), where @positive is True if the condition has a positive
925
+ evaluation.
926
+ condition_type (str): What type of condition to sample, e.g., "initial"
927
+
928
+ Returns:
929
+ 2-tuple:
930
+
931
+ - dict: Filtered object scope
932
+ - list of str: The name of children object(s) that have the highest proportion of kinematic sampling
933
+ failures
934
+ """
935
+ filtered_object_scope = {}
936
+ # Maps child obj name (SCOPE name) to parent obj name (OBJECT name) to T / F,
937
+ # ie: if the kinematic relationship was sampled successfully
938
+ problematic_objs = defaultdict(dict)
939
+ for room_type in input_object_scope:
940
+ filtered_object_scope[room_type] = {}
941
+ for scene_obj in input_object_scope[room_type]:
942
+ filtered_object_scope[room_type][scene_obj] = {}
943
+ for room_inst in input_object_scope[room_type][scene_obj]:
944
+ # These are a list of candidate simulator objects that need sampling test
945
+ for obj in input_object_scope[room_type][scene_obj][room_inst]:
946
+ # Temporarily set object_scope to point to this candidate object
947
+ self._object_scope[scene_obj] = obj
948
+
949
+ success = True
950
+ # If this candidate object is not involved in any conditions,
951
+ # success will be True by default and this object will qualify
952
+ parent_obj_name = obj.name
953
+ conditions_to_sample = []
954
+ for condition, positive in conditions:
955
+ # Sample positive kinematic conditions that involve this candidate object
956
+ if (
957
+ condition.STATE_NAME in KINEMATIC_STATES_BDDL
958
+ and positive
959
+ and scene_obj in condition.body
960
+ ):
961
+ child_scope_name = condition.body[0]
962
+ entity = self._object_scope[child_scope_name]
963
+ conditions_to_sample.append((condition, positive, entity, child_scope_name))
964
+
965
+ # If we're sampling kinematics, sort children based on (a) whether they are cloth or not, and
966
+ # then (b) their AABB, so that first all rigid objects are sampled before all cloth objects,
967
+ # and within each group the larger objects are sampled first. This is needed because rigid
968
+ # objects currently don't detect collisions with cloth objects (rigid-object contact checks
969
+ # is empty even when a cloth object is in contact with it).
970
+ rigid_conditions = [c for c in conditions_to_sample if c[2].prim_type != PrimType.CLOTH]
971
+ cloth_conditions = [c for c in conditions_to_sample if c[2].prim_type == PrimType.CLOTH]
972
+ conditions_to_sample = list(
973
+ reversed(sorted(rigid_conditions, key=lambda x: th.prod(x[2].aabb_extent)))
974
+ ) + list(reversed(sorted(cloth_conditions, key=lambda x: th.prod(x[2].aabb_extent))))
975
+
976
+ # Sample!
977
+ for condition, positive, entity, child_scope_name in conditions_to_sample:
978
+ kwargs = dict()
979
+ # Reset if we're sampling a kinematic state
980
+ if condition.STATE_NAME in {"inside", "ontop", "under"}:
981
+ kwargs["reset_before_sampling"] = True
982
+ kwargs["use_trav_map"] = True
983
+ elif condition.STATE_NAME in {"attached"}:
984
+ kwargs["bypass_alignment_checking"] = True
985
+ kwargs["check_physics_stability"] = True
986
+ kwargs["can_joint_break"] = False
987
+ success = condition.sample(self._sample_predicate, binary_state=positive, **kwargs)
988
+ log_msg = " ".join(
989
+ [
990
+ f"{condition_type} kinematic condition sampling",
991
+ room_type,
992
+ scene_obj,
993
+ str(room_inst),
994
+ parent_obj_name,
995
+ condition.STATE_NAME,
996
+ str(condition.body),
997
+ str(success),
998
+ ]
999
+ )
1000
+ log.warning(log_msg)
1001
+
1002
+ # Record the result for the child object
1003
+ assert (
1004
+ parent_obj_name not in problematic_objs[child_scope_name]
1005
+ ), f"Multiple kinematic relationships attempted for pair {condition.body}"
1006
+ problematic_objs[child_scope_name][parent_obj_name] = success
1007
+ # If any condition fails for this candidate object, skip
1008
+ if not success:
1009
+ break
1010
+
1011
+ # If this candidate object fails, move on to the next candidate object
1012
+ if not success:
1013
+ continue
1014
+
1015
+ if room_inst not in filtered_object_scope[room_type][scene_obj]:
1016
+ filtered_object_scope[room_type][scene_obj][room_inst] = []
1017
+ filtered_object_scope[room_type][scene_obj][room_inst].append(obj)
1018
+
1019
+ # Compute most problematic objects
1020
+ if len(problematic_objs) == 0:
1021
+ max_problematic_objs = []
1022
+ else:
1023
+ problematic_objs_by_proportion = defaultdict(list)
1024
+ for child_scope_name, parent_obj_names in problematic_objs.items():
1025
+ problematic_objs_by_proportion[
1026
+ th.mean(th.tensor(list(parent_obj_names.values()), dtype=th.float32)).item()
1027
+ ].append(child_scope_name)
1028
+ max_problematic_objs = problematic_objs_by_proportion[min(problematic_objs_by_proportion.keys())]
1029
+
1030
+ return filtered_object_scope, max_problematic_objs
1031
+
1032
+ def _consolidate_room_instance(self, filtered_object_scope, condition_type):
1033
+ """
1034
+ Consolidates room instances
1035
+
1036
+ Args:
1037
+ filtered_object_scope (dict): Filtered object scope
1038
+ condition_type (str): What type of condition to sample, e.g., "initial"
1039
+
1040
+ Returns:
1041
+ None or str: Error message, if any
1042
+ """
1043
+ for room_type in filtered_object_scope:
1044
+ # For each room_type, filter in room_inst that has successful
1045
+ # sampling options for all obj_inst in this room_type
1046
+ room_inst_satisfied = set.intersection(
1047
+ *[
1048
+ set(filtered_object_scope[room_type][obj_inst].keys())
1049
+ for obj_inst in filtered_object_scope[room_type]
1050
+ ]
1051
+ )
1052
+
1053
+ if len(room_inst_satisfied) == 0:
1054
+ 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(
1055
+ condition_type, room_type, self._scene_model
1056
+ )
1057
+ for obj_inst in filtered_object_scope[room_type]:
1058
+ error_msg += (
1059
+ "{}: ".format(obj_inst) + ", ".join(filtered_object_scope[room_type][obj_inst].keys()) + "\n"
1060
+ )
1061
+
1062
+ return error_msg
1063
+
1064
+ for obj_inst in filtered_object_scope[room_type]:
1065
+ filtered_object_scope[room_type][obj_inst] = {
1066
+ key: val
1067
+ for key, val in filtered_object_scope[room_type][obj_inst].items()
1068
+ if key in room_inst_satisfied
1069
+ }
1070
+
1071
+ def _filter_model_choices_by_attached_states(self, model_choices, category, obj_inst):
1072
+ # If obj_inst is a child object that depends on a parent object that has been imported or exists in the scene,
1073
+ # we filter in only models that match the parent object's attachment meta links.
1074
+ if obj_inst in self._attached_objects:
1075
+ parent_insts = self._attached_objects[obj_inst]
1076
+ parent_objects = []
1077
+ for parent_inst in parent_insts:
1078
+ # If parent_inst is not an inroom object, it must be a non-sampleable object that has already been imported.
1079
+ # Grab it from the object_scope
1080
+ if parent_inst not in self._inroom_object_instances:
1081
+ assert self._object_scope[parent_inst] is not None
1082
+ parent_objects.append([self._object_scope[parent_inst]])
1083
+ # If parent_inst is an inroom object, it can refer to multiple objects in the scene in different rooms.
1084
+ # We gather all of them and require that the model choice supports attachment to at least one of them.
1085
+ else:
1086
+ for _, parent_inst_to_parent_objs in self._inroom_object_scope.items():
1087
+ if parent_inst in parent_inst_to_parent_objs:
1088
+ parent_objects.append(sum(parent_inst_to_parent_objs[parent_inst].values(), []))
1089
+
1090
+ # Help function to check if a child object can attach to a parent object
1091
+ def can_attach(child_attachment_links, parent_attachment_links):
1092
+ for child_link_name in child_attachment_links:
1093
+ child_category = re.search(r"attachment_(.+?)_\d+_link$", child_link_name).group(1)
1094
+ if child_category.endswith("F"):
1095
+ continue
1096
+ assert child_category.endswith("M")
1097
+ target_parent_category = child_category[:-1] + "F"
1098
+ for parent_link_name in parent_attachment_links:
1099
+ parent_category = re.search(r"attachment_(.+?)_\d+_link$", parent_link_name).group(1)
1100
+ if parent_category == target_parent_category:
1101
+ return True
1102
+ return False
1103
+
1104
+ # Filter out models that don't support the attached states
1105
+ new_model_choices = set()
1106
+ for model_choice in model_choices:
1107
+ child_attachment_links = get_attachment_meta_links(category, model_choice)
1108
+ # The child model choice needs to be able to attach to all parent instances.
1109
+ # For in-room parent instances, there might be multiple parent objects (e.g. different wall nails),
1110
+ # and the child object needs to be able to attach to at least one of them.
1111
+ if all(
1112
+ any(
1113
+ can_attach(
1114
+ child_attachment_links, get_attachment_meta_links(parent_obj.category, parent_obj.model)
1115
+ )
1116
+ for parent_obj in parent_objs_per_inst
1117
+ )
1118
+ for parent_objs_per_inst in parent_objects
1119
+ ):
1120
+ new_model_choices.add(model_choice)
1121
+
1122
+ return new_model_choices
1123
+
1124
+ # If obj_inst is a prent object that other objects depend on, we filter in only models that have at least some
1125
+ # attachment links.
1126
+ elif any(obj_inst in parents for parents in self._attached_objects.values()):
1127
+ # Filter out models that don't support the attached states
1128
+ new_model_choices = set()
1129
+ for model_choice in model_choices:
1130
+ if len(get_attachment_meta_links(category, model_choice)) > 0:
1131
+ new_model_choices.add(model_choice)
1132
+ return new_model_choices
1133
+
1134
+ # If neither of the above cases apply, we don't need to filter the model choices
1135
+ else:
1136
+ return model_choices
1137
+
1138
+ def _import_sampleable_objects(self):
1139
+ """
1140
+ Import all objects that can be sampled
1141
+
1142
+ Args:
1143
+ env (Environment): Current active environment instance
1144
+ """
1145
+ assert og.sim.is_stopped(), "Simulator should be stopped when importing sampleable objects"
1146
+
1147
+ # Move the robot object frame to a far away location, similar to other newly imported objects below
1148
+ self._agent.set_position_orientation(
1149
+ position=th.tensor([300, 300, 300], dtype=th.float32), orientation=th.tensor([0, 0, 0, 1], dtype=th.float32)
1150
+ )
1151
+
1152
+ self._sampled_objects = set()
1153
+ num_new_obj = 0
1154
+ # Only populate self.object_scope for sampleable objects
1155
+ available_categories = set(get_all_object_categories())
1156
+
1157
+ # Attached states introduce dependencies among objects during import time.
1158
+ # For example, when importing a child object instance, we need to make sure the imported model can be attached
1159
+ # to the parent object instance. We sort the object instances such that parent object instances are imported
1160
+ # before child object instances.
1161
+ dependencies = {key: self._attached_objects.get(key, {}) for key in self._object_instance_to_synset.keys()}
1162
+ for obj_inst in list(reversed(list(nx.algorithms.topological_sort(nx.DiGraph(dependencies))))):
1163
+ obj_synset = self._object_instance_to_synset[obj_inst]
1164
+ synset_whitelist = (
1165
+ None if self._sampling_whitelist is None else self._sampling_whitelist.get(obj_synset, None)
1166
+ )
1167
+ synset_blacklist = (
1168
+ None if self._sampling_blacklist is None else self._sampling_blacklist.get(obj_synset, None)
1169
+ )
1170
+
1171
+ # Don't populate agent
1172
+ if obj_synset == "agent.n.01":
1173
+ continue
1174
+
1175
+ # Populate based on whether it's a substance or not
1176
+ if is_substance_synset(obj_synset):
1177
+ assert len(self._activity_conditions.parsed_objects[obj_synset]) == 1, "Systems are singletons"
1178
+ obj_inst = self._activity_conditions.parsed_objects[obj_synset][0]
1179
+ _so = get_knowledge_base().get_synset(obj_synset)
1180
+ system_name = [
1181
+ ps.name for s in [_so] + sorted(_so.descendants, key=lambda x: x.name) for ps in s.particle_systems
1182
+ ][0]
1183
+ self._object_scope[obj_inst] = (
1184
+ None if obj_inst in self._future_obj_instances else self._scene.get_system(system_name)
1185
+ )
1186
+ else:
1187
+ _so = get_knowledge_base().get_synset(obj_synset)
1188
+ valid_categories = set(
1189
+ [
1190
+ c.name
1191
+ for s in [_so] + sorted(_so.descendants, key=lambda x: x.name)
1192
+ if s.is_leaf
1193
+ for c in s.categories
1194
+ ]
1195
+ )
1196
+ categories = list(valid_categories.intersection(available_categories))
1197
+ if len(categories) == 0:
1198
+ return (
1199
+ f"None of the following categories could be found in the dataset for synset {obj_synset}: "
1200
+ f"{valid_categories}"
1201
+ )
1202
+
1203
+ # Don't explicitly sample if future
1204
+ if obj_inst in self._future_obj_instances:
1205
+ self._object_scope[obj_inst] = None
1206
+ continue
1207
+ # Don't sample if already in room
1208
+ if obj_inst in self._inroom_object_instances:
1209
+ continue
1210
+
1211
+ # Shuffle categories and sample to find a valid model
1212
+ random.shuffle(categories)
1213
+ model_choices = set()
1214
+ for category in categories:
1215
+ # Get all available models that support all of its synset abilities
1216
+ model_choices = set(
1217
+ get_all_object_category_models_with_abilities(
1218
+ category=category,
1219
+ abilities=get_knowledge_base().get_category(category).synset.abilities,
1220
+ )
1221
+ )
1222
+ model_choices = (
1223
+ model_choices
1224
+ if category not in GOOD_MODELS
1225
+ else model_choices.intersection(GOOD_MODELS[category])
1226
+ )
1227
+ model_choices -= BAD_CLOTH_MODELS.get(category, set())
1228
+ model_choices = self._filter_model_choices_by_attached_states(model_choices, category, obj_inst)
1229
+
1230
+ # Filter based on white / blacklist
1231
+ if synset_whitelist is not None:
1232
+ model_choices = (
1233
+ model_choices.intersection(set(synset_whitelist[category].keys()))
1234
+ if category in synset_whitelist
1235
+ else set()
1236
+ )
1237
+
1238
+ if synset_blacklist is not None:
1239
+ model_choices = (
1240
+ model_choices - set(synset_blacklist[category].keys())
1241
+ if category in synset_blacklist
1242
+ else model_choices
1243
+ )
1244
+
1245
+ # Filter by category
1246
+ if len(model_choices) > 0:
1247
+ break
1248
+
1249
+ if len(model_choices) == 0:
1250
+ # We failed to find ANY valid model across ALL valid categories
1251
+ return f"Missing valid object models for all categories: {categories}"
1252
+
1253
+ # Randomly select an object model
1254
+ model = random.choice(list(model_choices))
1255
+
1256
+ # Potentially add additional kwargs
1257
+ obj_kwargs = dict()
1258
+
1259
+ size = synset_whitelist.get(category, dict()).get(model, None) if synset_whitelist else None
1260
+
1261
+ # if size is one dimension, this is a scale; if it's three dimensions, this is a bounding box
1262
+ if size is not None:
1263
+ if isinstance(size, (int, float)):
1264
+ obj_kwargs["scale"] = th.tensor(size, dtype=th.float32)
1265
+ elif isinstance(size, list) and len(size) == 3:
1266
+ obj_kwargs["bounding_box"] = th.tensor(size, dtype=th.float32)
1267
+ else:
1268
+ return f"Invalid size for object {obj_inst} with model {model} in category {category}: {size}"
1269
+
1270
+ # Create the object. This is imported here to avoid a circular import.
1271
+ from omnigibson.objects.dataset_object import DatasetObject
1272
+
1273
+ simulator_obj = DatasetObject(
1274
+ name=f"{category}_{len(self._scene.objects)}",
1275
+ category=category,
1276
+ model=model,
1277
+ prim_type=(
1278
+ PrimType.CLOTH
1279
+ if "cloth" in get_knowledge_base().get_synset(obj_synset).abilities
1280
+ else PrimType.RIGID
1281
+ ),
1282
+ **obj_kwargs,
1283
+ )
1284
+ num_new_obj += 1
1285
+
1286
+ # Load the object into the simulator
1287
+ self._scene.add_object(simulator_obj)
1288
+
1289
+ # Set these objects to be far-away locations
1290
+ simulator_obj.set_position_orientation(
1291
+ position=th.tensor([100.0, 100.0, -100.0]) + th.ones(3) * num_new_obj * 5.0
1292
+ )
1293
+
1294
+ self._sampled_objects.add(simulator_obj)
1295
+ self._object_scope[obj_inst] = simulator_obj
1296
+
1297
+ og.sim.play()
1298
+ og.sim.stop()
1299
+
1300
+ def _sample_initial_conditions(self):
1301
+ """
1302
+ Sample initial conditions
1303
+
1304
+ Returns:
1305
+ None or str: If successful, returns None. Otherwise, returns an error message
1306
+ """
1307
+ error_msg, self._inroom_object_scope_filtered_initial = self._sample_conditions(
1308
+ self._inroom_object_scope, self._inroom_object_conditions, "initial"
1309
+ )
1310
+ return error_msg
1311
+
1312
+ def _sample_goal_conditions(self):
1313
+ """
1314
+ Sample goal conditions
1315
+
1316
+ Returns:
1317
+ None or str: If successful, returns None. Otherwise, returns an error message
1318
+ """
1319
+ # ground_goal_state_options is list[list[HEAD]] post-#2040; shuffle a copy of the outer list
1320
+ ground_goal_state_options = list(self._compiled_task.ground_goal_state_options)
1321
+ random.shuffle(ground_goal_state_options)
1322
+ log.debug(("number of ground_goal_state_options", len(ground_goal_state_options)))
1323
+ num_goal_condition_set_to_test = 10
1324
+
1325
+ goal_condition_success = False
1326
+ # Try to fulfill different set of ground goal conditions (maximum num_goal_condition_set_to_test)
1327
+ for goal_condition_set in ground_goal_state_options[:num_goal_condition_set_to_test]:
1328
+ goal_condition_processed = []
1329
+ for condition in goal_condition_set:
1330
+ condition, positive = process_single_condition(condition)
1331
+ if condition is None:
1332
+ continue
1333
+ goal_condition_processed.append((condition, positive))
1334
+
1335
+ error_msg, _ = self._sample_conditions(
1336
+ self._inroom_object_scope_filtered_initial, goal_condition_processed, "goal"
1337
+ )
1338
+ if not error_msg:
1339
+ # if one set of goal conditions (and initial conditions) are satisfied, sampling is successful
1340
+ goal_condition_success = True
1341
+ break
1342
+
1343
+ if not goal_condition_success:
1344
+ return error_msg
1345
+
1346
+ def _sample_initial_conditions_final(self, dynamic_scale=False):
1347
+ """
1348
+ Sample final initial conditions
1349
+
1350
+ Returns:
1351
+ None or str: If successful, returns None. Otherwise, returns an error message
1352
+ """
1353
+ # Sample kinematics first, then particle states, then unary states
1354
+ state = og.sim.dump_state(serialized=False)
1355
+ for group in ("kinematic", "particle", "unary"):
1356
+ log.info(f"Sampling {group} states...")
1357
+ if len(self._object_sampling_orders[group]) > 0:
1358
+ for cur_batch in self._object_sampling_orders[group]:
1359
+ conditions_to_sample = []
1360
+ for condition, positive in self._object_sampling_conditions[group]:
1361
+ # Sample conditions that involve the current batch of objects
1362
+ child_scope_name = condition.body[0]
1363
+ if child_scope_name in cur_batch:
1364
+ entity = self._object_scope[child_scope_name]
1365
+ conditions_to_sample.append((condition, positive, entity, child_scope_name))
1366
+
1367
+ # If we're sampling kinematics, sort children based on (a) whether they are cloth or not, and then
1368
+ # (b) their AABB, so that first all rigid objects are sampled before cloth objects, and within each
1369
+ # group the larger objects are sampled first
1370
+ if group == "kinematic":
1371
+ rigid_conditions = [c for c in conditions_to_sample if c[2].prim_type != PrimType.CLOTH]
1372
+ cloth_conditions = [c for c in conditions_to_sample if c[2].prim_type == PrimType.CLOTH]
1373
+ conditions_to_sample = list(
1374
+ reversed(sorted(rigid_conditions, key=lambda x: th.prod(x[2].aabb_extent)))
1375
+ ) + list(reversed(sorted(cloth_conditions, key=lambda x: th.prod(x[2].aabb_extent))))
1376
+
1377
+ # Sample!
1378
+ for condition, positive, entity, child_scope_name in conditions_to_sample:
1379
+ success = False
1380
+
1381
+ kwargs = dict()
1382
+ # Reset if we're sampling a kinematic state
1383
+ if condition.STATE_NAME in {"inside", "ontop", "under"}:
1384
+ kwargs["reset_before_sampling"] = True
1385
+ kwargs["use_trav_map"] = True
1386
+ elif condition.STATE_NAME in {"attached"}:
1387
+ kwargs["bypass_alignment_checking"] = True
1388
+ kwargs["check_physics_stability"] = True
1389
+ kwargs["can_joint_break"] = False
1390
+
1391
+ while True:
1392
+ num_trials = 3
1393
+ for _ in range(num_trials):
1394
+ success = condition.sample(self._sample_predicate, binary_state=positive, **kwargs)
1395
+ log_msg = " ".join(
1396
+ [
1397
+ "initial final kinematic condition sampling",
1398
+ condition.STATE_NAME,
1399
+ str(condition.body),
1400
+ str(success),
1401
+ ]
1402
+ )
1403
+ log.warning(log_msg)
1404
+ if success:
1405
+ # Update state
1406
+ state = og.sim.dump_state(serialized=False)
1407
+ break
1408
+ if success:
1409
+ # After the final round of kinematic sampling, we assign in_rooms to newly imported objects
1410
+ if group == "kinematic":
1411
+ parent = self._object_scope[condition.body[1]]
1412
+ entity.in_rooms = deepcopy(parent.in_rooms)
1413
+
1414
+ # Can terminate immediately
1415
+ break
1416
+
1417
+ # Can't re-sample non-kinematics or rescale cloth or agent, so in
1418
+ # those cases terminate immediately
1419
+ if (
1420
+ group != "kinematic"
1421
+ or condition.STATE_NAME == "attached"
1422
+ or "agent" in child_scope_name
1423
+ or entity.prim_type == PrimType.CLOTH
1424
+ ):
1425
+ break
1426
+
1427
+ if dynamic_scale:
1428
+ # If any scales are equal or less than the lower threshold, terminate immediately
1429
+ new_scale = entity.scale - m.DYNAMIC_SCALE_INCREMENT
1430
+ if th.any(new_scale < m.MIN_DYNAMIC_SCALE):
1431
+ break
1432
+
1433
+ # Re-scale and re-attempt
1434
+ # Re-scaling is not respected unless sim cycle occurs
1435
+ og.sim.stop()
1436
+ entity.scale = new_scale
1437
+ log.info(
1438
+ f"Kinematic sampling {condition.STATE_NAME} {condition.body} failed, rescaling obj: {child_scope_name} to {entity.scale}"
1439
+ )
1440
+ og.sim.play()
1441
+ og.sim.load_state(state, serialized=False)
1442
+ og.sim.step_physics()
1443
+ else:
1444
+ break
1445
+ if not success:
1446
+ # Update object registry because we just assigned in_rooms to newly imported objects
1447
+ self._scene.object_registry.update(keys=["in_rooms"])
1448
+ return f"Sampleable object conditions failed: {condition.STATE_NAME} {condition.body}"
1449
+
1450
+ # Update object registry because we just assigned in_rooms to newly imported objects
1451
+ self._scene.object_registry.update(keys=["in_rooms"])
1452
+
1453
+ # One more sim step to make sure the object states are propagated correctly
1454
+ # E.g. after sampling Filled.set_value(True), Filled.get_value() will become True only after one step
1455
+ og.sim.step()
1456
+
1457
+ def _sample_conditions(self, input_object_scope, conditions, condition_type):
1458
+ """
1459
+ Sample conditions
1460
+
1461
+ Args:
1462
+ input_object_scope (dict):
1463
+ conditions (list): List of conditions to filter scope with, where each list entry is
1464
+ a tuple of (condition, positive), where @positive is True if the condition has a positive
1465
+ evaluation.
1466
+ condition_type (str): What type of condition to sample, e.g., "initial"
1467
+
1468
+ Returns:
1469
+ None or str: If successful, returns None. Otherwise, returns an error message
1470
+ """
1471
+ error_msg, problematic_objs = "", []
1472
+ while not any(
1473
+ th.any(self._object_scope[obj_inst].scale < m.MIN_DYNAMIC_SCALE).item() for obj_inst in problematic_objs
1474
+ ):
1475
+ filtered_object_scope, problematic_objs = self._filter_object_scope(
1476
+ input_object_scope, conditions, condition_type
1477
+ )
1478
+ error_msg = self._consolidate_room_instance(filtered_object_scope, condition_type)
1479
+ if error_msg is None:
1480
+ break
1481
+ # Re-scaling is not respected unless sim cycle occurs
1482
+ og.sim.stop()
1483
+ for obj_inst in problematic_objs:
1484
+ obj = self._object_scope[obj_inst]
1485
+ # If the object's initial condition is attachment, or it's agent or cloth, we can't / shouldn't scale
1486
+ # down, so play again and then terminate immediately
1487
+ if obj_inst in self._attached_objects or "agent" in obj_inst or obj.prim_type == PrimType.CLOTH:
1488
+ og.sim.play()
1489
+ return error_msg, None
1490
+ assert th.all(obj.scale > m.DYNAMIC_SCALE_INCREMENT)
1491
+ obj.scale -= m.DYNAMIC_SCALE_INCREMENT
1492
+ og.sim.play()
1493
+
1494
+ if error_msg:
1495
+ return error_msg, None
1496
+ return self._maximum_bipartite_matching(filtered_object_scope, condition_type), filtered_object_scope
1497
+
1498
+ def _maximum_bipartite_matching(self, filtered_object_scope, condition_type):
1499
+ """
1500
+ Matches objects from @filtered_object_scope to specific room instances it can be
1501
+ sampled from
1502
+
1503
+ Args:
1504
+ filtered_object_scope (dict): Filtered object scope
1505
+ condition_type (str): What type of condition to sample, e.g., "initial"
1506
+
1507
+ Returns:
1508
+ None or str: If successful, returns None. Otherwise, returns an error message
1509
+ """
1510
+ # For each room instance, perform maximum bipartite matching between object instance in scope to simulator objects
1511
+ # Left nodes: a list of object instance in scope
1512
+ # Right nodes: a list of simulator objects
1513
+ # Edges: if the simulator object can support the sampling requirement of ths object instance
1514
+ for room_type in filtered_object_scope:
1515
+ # The same room instances will be shared across all scene obj in a given room type
1516
+ some_obj = list(filtered_object_scope[room_type].keys())[0]
1517
+ room_insts = list(filtered_object_scope[room_type][some_obj].keys())
1518
+ success = False
1519
+ # Loop through each room instance
1520
+ for room_inst in room_insts:
1521
+ graph = nx.Graph()
1522
+ # For this given room instance, gether mapping from obj instance to a list of simulator obj
1523
+ obj_inst_to_obj_per_room_inst = {}
1524
+ for obj_inst in filtered_object_scope[room_type]:
1525
+ obj_inst_to_obj_per_room_inst[obj_inst] = filtered_object_scope[room_type][obj_inst][room_inst]
1526
+ top_nodes = []
1527
+ log_msg = "MBM for room instance [{}]".format(room_inst)
1528
+ log.debug((log_msg))
1529
+ for obj_inst in obj_inst_to_obj_per_room_inst:
1530
+ for obj in obj_inst_to_obj_per_room_inst[obj_inst]:
1531
+ # Create an edge between obj instance and each of the simulator obj that supports sampling
1532
+ graph.add_edge(obj_inst, obj)
1533
+ log_msg = "Adding edge: {} <-> {}".format(obj_inst, obj.name)
1534
+ log.debug((log_msg))
1535
+ top_nodes.append(obj_inst)
1536
+ # Need to provide top_nodes that contain all nodes in one bipartite node set
1537
+ # The matches will have two items for each match (e.g. A -> B, B -> A)
1538
+ matches = nx.bipartite.maximum_matching(graph, top_nodes=top_nodes)
1539
+ if len(matches) == 2 * len(obj_inst_to_obj_per_room_inst):
1540
+ log.debug(("Object scope finalized:"))
1541
+ for obj_inst, obj in matches.items():
1542
+ if obj_inst in obj_inst_to_obj_per_room_inst:
1543
+ self._object_scope[obj_inst] = obj
1544
+ log.debug((obj_inst, obj.name))
1545
+ success = True
1546
+ break
1547
+ if not success:
1548
+ 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(
1549
+ condition_type, room_type, self._scene_model
1550
+ )
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/coacd_runner.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Subprocess to run coacd to prevent the generate_collision_meshes() in asset_conversion_utils.py from crashing
3
+ """
4
+
5
+ import pickle
6
+ import coacd
7
+ import sys
8
+
9
+ try:
10
+ with open(sys.argv[1], "rb") as f:
11
+ vertices, faces, hull_count = pickle.load(f)
12
+ mesh = coacd.Mesh(vertices, faces)
13
+ result = coacd.run_coacd(
14
+ mesh,
15
+ max_convex_hull=hull_count,
16
+ decimate=True,
17
+ max_ch_vertex=60,
18
+ )
19
+ with open(sys.argv[2], "wb") as f:
20
+ pickle.dump(result, f)
21
+ sys.exit(0)
22
+ except Exception as e:
23
+ print("Error in CoACD:", e)
24
+ sys.exit(1)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/config_utils.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ import json
3
+ import os
4
+
5
+ import torch as th
6
+ import yaml
7
+
8
+ # File I/O related
9
+
10
+
11
+ def parse_config(config):
12
+ """
13
+ Parse OmniGibson config file / object
14
+
15
+ Args:
16
+ config (dict or str): Either config dictionary or path to yaml config to load
17
+
18
+ Returns:
19
+ dict: Parsed config
20
+ """
21
+ if isinstance(config, collections.abc.Mapping):
22
+ return config
23
+ else:
24
+ assert isinstance(config, str)
25
+
26
+ if not os.path.exists(config):
27
+ raise IOError(
28
+ "config path {} does not exist. Please either pass in a dict or a string that represents the file path to the config yaml.".format(
29
+ config
30
+ )
31
+ )
32
+ with open(config, "r") as f:
33
+ config_data = yaml.load(f, Loader=yaml.FullLoader)
34
+ return config_data
35
+
36
+
37
+ def parse_str_config(config):
38
+ """
39
+ Parse string config
40
+
41
+ Args:
42
+ config (str): Yaml cfg as a string to load
43
+
44
+ Returns:
45
+ dict: Parsed config
46
+ """
47
+ return yaml.safe_load(config)
48
+
49
+
50
+ def dump_config(config):
51
+ """
52
+ Converts YML config into a string
53
+
54
+ Args:
55
+ config (dict): Config to dump
56
+
57
+ Returns:
58
+ str: Config as a string
59
+ """
60
+ return yaml.dump(config)
61
+
62
+
63
+ def load_default_config():
64
+ """
65
+ Loads a default configuration to use for OmniGibson
66
+
67
+ Returns:
68
+ dict: Loaded default configuration file
69
+ """
70
+ from omnigibson import example_config_path
71
+
72
+ return parse_config(f"{example_config_path}/default_cfg.yaml")
73
+
74
+
75
+ class TorchEncoder(json.JSONEncoder):
76
+ def default(self, obj):
77
+ if isinstance(obj, th.Tensor):
78
+ return obj.tolist()
79
+ return json.JSONEncoder.default(self, obj)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/constants.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Constant Definitions
3
+ """
4
+
5
+ import hashlib
6
+ from enum import Enum, IntEnum
7
+ from functools import cache
8
+
9
+ import torch as th
10
+
11
+ from omnigibson.utils.asset_utils import get_all_object_categories, get_all_system_categories
12
+
13
+ MAX_INSTANCE_COUNT = th.iinfo(th.int32).max
14
+ MAX_CLASS_COUNT = th.iinfo(th.int32).max
15
+ MAX_VIEWER_SIZE = 2048
16
+
17
+ # Category name assigned to all robots
18
+ ROBOT_CATEGORY = "agent"
19
+
20
+
21
+ class ViewerMode(IntEnum):
22
+ NAVIGATION = 0
23
+ MANIPULATION = 1
24
+ PLANNING = 2
25
+
26
+
27
+ class LightingMode(str, Enum):
28
+ # See https://stackoverflow.com/a/58608362 for info on string enums
29
+ STAGE = "stage"
30
+ CAMERA = "camera"
31
+ RIG_DEFAULT = "Default"
32
+ RIG_GREY = "Grey Studio"
33
+ RIG_COLORED = "Colored Lights"
34
+
35
+
36
+ class SimulatorMode(IntEnum):
37
+ GUI = 1
38
+ HEADLESS = 2
39
+ VR = 3
40
+
41
+
42
+ # Specific methods for applying / removing particles
43
+ class ParticleModifyMethod(str, Enum):
44
+ ADJACENCY = "adjacency"
45
+ PROJECTION = "projection"
46
+
47
+
48
+ # Specific condition types for applying / removing particles
49
+ class ParticleModifyCondition(str, Enum):
50
+ FUNCTION = "function"
51
+ SATURATED = "saturated"
52
+ TOGGLEDON = "toggled_on"
53
+ GRAVITY = "gravity"
54
+
55
+
56
+ # Object categories -- grabbed directly from the dataset to begin with
57
+ # This will be automatically added to when objects are added with custom categories
58
+ OBJECT_CATEGORIES = set(get_all_object_categories())
59
+
60
+ # Structure categories that need to always be loaded for stability purposes
61
+ STRUCTURE_CATEGORIES = frozenset({"floors", "walls", "ceilings", "lawn", "driveway", "fence", "roof", "background"})
62
+
63
+ # Ground categories / prim names used for filtering collisions, e.g.: during motion planning
64
+ GROUND_CATEGORIES = frozenset({"floors", "lawn", "driveway", "carpet"})
65
+
66
+ # Structural door categories used for filtering collisions with structure categories
67
+ STRUCTURAL_DOOR_CATEGORIES = frozenset({"sliding_door", "garage_door"})
68
+
69
+ # Joint friction magic values
70
+ DEFAULT_PRISMATIC_JOINT_FRICTION = 0.3
71
+ DEFAULT_REVOLUTE_JOINT_FRICTION = 0.2
72
+
73
+ # Joint damping value
74
+ DEFAULT_PRISMATIC_JOINT_DAMPING = 5.0
75
+ DEFAULT_REVOLUTE_JOINT_DAMPING = 0.05
76
+
77
+
78
+ class PrimType(IntEnum):
79
+ RIGID = 0
80
+ CLOTH = 1
81
+
82
+
83
+ class EmitterType(IntEnum):
84
+ FIRE = 0
85
+ STEAM = 1
86
+
87
+
88
+ # Valid primitive mesh types
89
+ PRIMITIVE_MESH_TYPES = {
90
+ "Cone",
91
+ "Cube",
92
+ "Cylinder",
93
+ "Disk",
94
+ "Plane",
95
+ "Sphere",
96
+ "Torus",
97
+ }
98
+
99
+ # Valid geom types
100
+ GEOM_TYPES = {"Sphere", "Cube", "Cone", "Cylinder", "Mesh"}
101
+
102
+ # Valid joint axis
103
+ JointAxis = ["X", "Y", "Z"]
104
+
105
+
106
+ # TODO: Clean up this class to be better enum with sanity checks
107
+ # Joint types
108
+ class JointType:
109
+ JOINT = "Joint"
110
+ JOINT_FIXED = "FixedJoint"
111
+ JOINT_PRISMATIC = "PrismaticJoint"
112
+ JOINT_REVOLUTE = "RevoluteJoint"
113
+ JOINT_SPHERICAL = "SphericalJoint"
114
+
115
+ _STR_TO_TYPE = {
116
+ "Joint": JOINT,
117
+ "FixedJoint": JOINT_FIXED,
118
+ "PrismaticJoint": JOINT_PRISMATIC,
119
+ "RevoluteJoint": JOINT_REVOLUTE,
120
+ "SphericalJoint": JOINT_SPHERICAL,
121
+ }
122
+
123
+ _TYPE_TO_STR = {
124
+ JOINT: "Joint",
125
+ JOINT_FIXED: "FixedJoint",
126
+ JOINT_PRISMATIC: "PrismaticJoint",
127
+ JOINT_REVOLUTE: "RevoluteJoint",
128
+ JOINT_SPHERICAL: "SphericalJoint",
129
+ }
130
+
131
+ @classmethod
132
+ def get_type(cls, str_type):
133
+ assert str_type in cls._STR_TO_TYPE, f"Invalid string joint type name received: {str_type}"
134
+ return cls._STR_TO_TYPE[str_type]
135
+
136
+ @classmethod
137
+ def get_str(cls, joint_type):
138
+ assert joint_type in cls._TYPE_TO_STR, f"Invalid joint type name received: {joint_type}"
139
+ return cls._TYPE_TO_STR[joint_type]
140
+
141
+ @classmethod
142
+ def is_valid(cls, joint_type):
143
+ return joint_type in cls._TYPE_TO_STR if isinstance(joint_type, cls) else joint_type in cls._STR_TO_TYPE
144
+
145
+
146
+ # Object category specs
147
+ AVERAGE_OBJ_DENSITY = 67.0
148
+
149
+
150
+ class OccupancyGridState:
151
+ OBSTACLES = 0.0
152
+ UNKNOWN = 0.5
153
+ FREESPACE = 1.0
154
+
155
+
156
+ MAX_TASK_RELEVANT_OBJS = 50
157
+ TASK_RELEVANT_OBJS_OBS_DIM = 9
158
+ AGENT_POSE_DIM = 6
159
+
160
+ # TODO: What the hell is this magic list?? It's not used anywhere
161
+ UNDER_OBJECTS = [
162
+ "breakfast_table",
163
+ "coffee_table",
164
+ "console_table",
165
+ "desk",
166
+ "gaming_table",
167
+ "pedestal_table",
168
+ "pool_table",
169
+ "stand",
170
+ "armchair",
171
+ "chaise_longue",
172
+ "folding_chair",
173
+ "highchair",
174
+ "rocking_chair",
175
+ "straight_chair",
176
+ "swivel_chair",
177
+ "bench",
178
+ ]
179
+
180
+
181
+ @cache
182
+ def semantic_class_name_to_id():
183
+ """
184
+ Get mapping from semantic class name to class id
185
+
186
+ Returns:
187
+ dict: class name to class id
188
+ """
189
+ systems = get_all_system_categories(include_cloth=True)
190
+
191
+ all_semantics = sorted(
192
+ set(list(OBJECT_CATEGORIES) + systems + ["background", "unlabelled", "object", "light", "agent"])
193
+ )
194
+
195
+ # Assign a unique class id to each class name with hashing, the upper limit here is the max of int32
196
+ max_int32 = th.iinfo(th.int32).max + 1
197
+ class_name_to_class_id = {s: int(hashlib.md5(s.encode()).hexdigest(), 16) % max_int32 for s in all_semantics}
198
+
199
+ return class_name_to_class_id
200
+
201
+
202
+ @cache
203
+ def semantic_class_id_to_name():
204
+ """
205
+ Get mapping from semantic class id to class name
206
+
207
+ Returns:
208
+ dict: class id to class name
209
+ """
210
+ return {v: k for k, v in semantic_class_name_to_id().items()}
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/control_utils.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Set of utilities for helping to execute robot control
3
+ """
4
+
5
+ import torch as th
6
+
7
+ import omnigibson.lazy as lazy
8
+ import omnigibson.utils.transform_utils as T
9
+
10
+
11
+ class FKSolver:
12
+ """
13
+ Class for thinly wrapping Lula Forward Kinematics solver
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ robot_description_path,
19
+ robot_urdf_path,
20
+ ):
21
+ # Create robot description and kinematics
22
+ self.robot_description = lazy.lula.load_robot(robot_description_path, robot_urdf_path)
23
+ self.kinematics = self.robot_description.kinematics()
24
+
25
+ def get_link_poses(
26
+ self,
27
+ joint_positions,
28
+ link_names,
29
+ ):
30
+ """
31
+ Given @joint_positions, get poses of the desired links (specified by @link_names)
32
+
33
+ Args:
34
+ joint_positions (n-array): Joint positions in configuration space
35
+ link_names (list): List of robot link names we want to specify (e.g. "gripper_link")
36
+
37
+ Returns:
38
+ link_poses (dict): Dictionary mapping each robot link name to its pose
39
+ """
40
+ # TODO: Refactor this to go over all links at once
41
+ link_poses = {}
42
+ for link_name in link_names:
43
+ pose3_lula = self.kinematics.pose(joint_positions, link_name)
44
+
45
+ # get position
46
+ link_position = th.tensor(pose3_lula.translation, dtype=th.float32)
47
+
48
+ # get orientation
49
+ rotation_lula = pose3_lula.rotation
50
+ link_orientation = th.tensor(
51
+ [rotation_lula.x(), rotation_lula.y(), rotation_lula.z(), rotation_lula.w()], dtype=th.float32
52
+ )
53
+ link_poses[link_name] = (link_position, link_orientation)
54
+ return link_poses
55
+
56
+
57
+ class IKSolver:
58
+ """
59
+ Class for thinly wrapping Lula IK solver
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ robot_description_path,
65
+ robot_urdf_path,
66
+ eef_name,
67
+ reset_joint_pos,
68
+ ):
69
+ # Create robot description, kinematics, and config
70
+ self.robot_description = lazy.lula.load_robot(robot_description_path, robot_urdf_path)
71
+ self.kinematics = self.robot_description.kinematics()
72
+ self.config = lazy.lula.CyclicCoordDescentIkConfig()
73
+ self.eef_name = eef_name
74
+ self.reset_joint_pos = reset_joint_pos
75
+
76
+ def solve(
77
+ self,
78
+ target_pos,
79
+ target_quat=None,
80
+ tolerance_pos=0.002,
81
+ tolerance_quat=0.01,
82
+ weight_pos=1.0,
83
+ weight_quat=0.05,
84
+ bfgs_orientation_weight=100.0,
85
+ max_iterations=10,
86
+ initial_joint_pos=None,
87
+ ):
88
+ """
89
+ Backs out joint positions to achieve desired @target_pos and @target_quat
90
+
91
+ Args:
92
+ target_pos (3-array): desired (x,y,z) local target cartesian position in robot's base coordinate frame
93
+ target_quat (4-array or None): If specified, desired (x,y,z,w) local target quaternion orientation in
94
+ robot's base coordinate frame. If None, IK will be position-only (will override settings such that
95
+ orientation's tolerance is very high and weight is 0)
96
+ tolerance_pos (float): Maximum position error (L2-norm) for a successful IK solution
97
+ tolerance_quat (float): Maximum orientation error (per-axis L2-norm) for a successful IK solution
98
+ weight_pos (float): Weight for the relative importance of position error during CCD
99
+ weight_quat (float): Weight for the relative importance of position error during CCD
100
+ bfgs_orientation_weight (float): Weight when applying BFGS algorithm during optimization. Only used if
101
+ target_quat is specified
102
+ max_iterations (int): Number of iterations used for each cyclic coordinate descent.
103
+ initial_joint_pos (None or n-array): If specified, will set the initial cspace seed when solving for joint
104
+ positions. Otherwise, will use self.reset_joint_pos
105
+
106
+ Returns:
107
+ None or n-array: Joint positions for reaching desired target_pos and target_quat, otherwise None if no
108
+ solution was found
109
+ """
110
+ pos = (
111
+ target_pos.to(th.float64) if isinstance(target_pos, th.Tensor) else th.tensor(target_pos, dtype=th.float64)
112
+ ).reshape(3, 1)
113
+
114
+ if target_quat is None:
115
+ rot = T.quat2mat(th.tensor([0, 0, 0, 1.0], dtype=th.float64))
116
+ else:
117
+ rot = T.quat2mat(
118
+ target_quat.to(th.float64)
119
+ if isinstance(target_quat, th.Tensor)
120
+ else th.tensor(target_quat, dtype=th.float64)
121
+ )
122
+ ik_target_pose = lazy.lula.Pose3(lazy.lula.Rotation3(rot), pos)
123
+
124
+ # Set the cspace seed and tolerance
125
+ initial_joint_pos = self.reset_joint_pos if initial_joint_pos is None else initial_joint_pos
126
+ self.config.cspace_seeds = [initial_joint_pos]
127
+ self.config.position_tolerance = tolerance_pos
128
+ self.config.orientation_tolerance = 100.0 if target_quat is None else tolerance_quat
129
+
130
+ self.config.ccd_position_weight = weight_pos
131
+ self.config.ccd_orientation_weight = 0.0 if target_quat is None else weight_quat
132
+ self.config.bfgs_orientation_weight = 0.0 if target_quat is None else bfgs_orientation_weight
133
+ self.config.max_num_descents = max_iterations
134
+
135
+ # Compute target joint positions
136
+ ik_results = lazy.lula.compute_ik_ccd(self.kinematics, ik_target_pose, self.eef_name, self.config)
137
+ if ik_results.success:
138
+ return th.tensor(ik_results.cspace_position, dtype=th.float32)
139
+ else:
140
+ return None
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/data_utils.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from omnigibson.robots import REGISTERED_ROBOTS
2
+ import numpy as np
3
+
4
+
5
+ def merge_scene_files(scene_a, scene_b, keep_robot_from="b"):
6
+ """
7
+ Merge two scene files, keeping the robot from the specified scene
8
+ and merging all other objects.
9
+
10
+ Design decisions:
11
+ - Scene B is considered the most up-to-date version and its data is preferred
12
+ when there are conflicts
13
+ - For objects that exist in both scenes, we perform sanity checks on objects_info
14
+ but always use Scene B's version
15
+ - For states of objects that exist in both scenes, we always use Scene B's version
16
+ without sanity checking
17
+ - For system registry, we always use Scene B's version (no merging)
18
+
19
+ Args:
20
+ scene_a (dict): First scene file
21
+ scene_b (dict): Second scene file (considered the most up-to-date version for conflicts)
22
+ keep_robot_from (str or None): Which scene to keep the robot from ('a', 'b', or None)
23
+ If None, no robot will be included
24
+
25
+ Returns:
26
+ dict: Merged scene file
27
+ """
28
+ assert isinstance(scene_a, dict), "Scene A must be a dictionary"
29
+ assert isinstance(scene_b, dict), "Scene B must be a dictionary"
30
+ assert keep_robot_from in ["a", "b", None], "keep_robot_from must be 'a', 'b', or None"
31
+
32
+ # Sanity check to make sure the two scene files are compatible
33
+ if "init_info" in scene_a and "init_info" in scene_b:
34
+ assert (
35
+ scene_a["init_info"]["args"]["scene_model"] == scene_b["init_info"]["args"]["scene_model"]
36
+ ), "Scene models must match for merging"
37
+
38
+ # Initialize merged scene file
39
+ result = {
40
+ "metadata": scene_b["metadata"], # Just use metadata from scene_b
41
+ "init_info": scene_b["init_info"], # Start with init_info from scene_b
42
+ "objects_info": {"init_info": {}},
43
+ "state": {
44
+ "pos": [0.0, 0.0, 0.0],
45
+ "ori": [0.0, 0.0, 0.0, 1.0],
46
+ "registry": {
47
+ "system_registry": {},
48
+ "object_registry": {},
49
+ },
50
+ },
51
+ }
52
+
53
+ # Update init_info settings
54
+ result["init_info"]["args"]["load_room_types"] = None
55
+ result["init_info"]["args"]["load_room_instances"] = None
56
+ result["init_info"]["args"]["include_robots"] = keep_robot_from is not None
57
+
58
+ # Find robots in both scenes
59
+ robots_a = {}
60
+ robots_b = {}
61
+
62
+ for obj_name, obj in scene_a["objects_info"]["init_info"].items():
63
+ if obj["class_name"].lower() in REGISTERED_ROBOTS or obj["class_name"] == "Robot":
64
+ # change class_name to "Robot" for compatibility
65
+ obj["class_name"] = "Robot"
66
+ robots_a[obj_name] = obj
67
+
68
+ for obj_name, obj in scene_b["objects_info"]["init_info"].items():
69
+ if obj["class_name"].lower() in REGISTERED_ROBOTS or obj["class_name"] == "Robot":
70
+ # change class_name to "Robot" for compatibility
71
+ obj["class_name"] = "Robot"
72
+ robots_b[obj_name] = obj
73
+
74
+ # Merge non-robot objects from both scenes
75
+ # Start with all objects from scene_a (excluding robots)
76
+ for obj_name, obj in scene_a["objects_info"]["init_info"].items():
77
+ if obj_name not in robots_a:
78
+ result["objects_info"]["init_info"][obj_name] = obj
79
+
80
+ # Add all objects from scene_b (excluding robots) and check for conflicts
81
+ for obj_name, obj in scene_b["objects_info"]["init_info"].items():
82
+ if obj_name not in robots_b:
83
+ if obj_name in result["objects_info"]["init_info"]:
84
+ # Object exists in both scenes, perform sanity check
85
+ sanity_check_object_compatibility(obj_name, result["objects_info"]["init_info"][obj_name], obj)
86
+ # Always use scene_b's version as the most up-to-date
87
+ result["objects_info"]["init_info"][obj_name] = obj
88
+
89
+ # Add robot based on keep_robot_from
90
+ if keep_robot_from == "a" and robots_a:
91
+ for robot_name, robot in robots_a.items():
92
+ result["objects_info"]["init_info"][robot_name] = robot
93
+ elif keep_robot_from == "b" and robots_b:
94
+ for robot_name, robot in robots_b.items():
95
+ result["objects_info"]["init_info"][robot_name] = robot
96
+
97
+ # Handle state information
98
+ # First add states for all non-robot objects from scene_a
99
+ for obj_name in scene_a["objects_info"]["init_info"]:
100
+ if obj_name not in robots_a and obj_name in scene_a["state"]["registry"]["object_registry"]:
101
+ result["state"]["registry"]["object_registry"][obj_name] = scene_a["state"]["registry"]["object_registry"][
102
+ obj_name
103
+ ]
104
+
105
+ # Then add states for all non-robot objects from scene_b
106
+ # Always use scene_b's version without sanity checking
107
+ for obj_name in scene_b["objects_info"]["init_info"]:
108
+ if obj_name not in robots_b and obj_name in scene_b["state"]["registry"]["object_registry"]:
109
+ result["state"]["registry"]["object_registry"][obj_name] = scene_b["state"]["registry"]["object_registry"][
110
+ obj_name
111
+ ]
112
+
113
+ # Add robot state based on keep_robot_from
114
+ if keep_robot_from == "a":
115
+ for robot_name in robots_a:
116
+ if robot_name in scene_a["state"]["registry"]["object_registry"]:
117
+ result["state"]["registry"]["object_registry"][robot_name] = scene_a["state"]["registry"][
118
+ "object_registry"
119
+ ][robot_name]
120
+ elif keep_robot_from == "b":
121
+ for robot_name in robots_b:
122
+ if robot_name in scene_b["state"]["registry"]["object_registry"]:
123
+ result["state"]["registry"]["object_registry"][robot_name] = scene_b["state"]["registry"][
124
+ "object_registry"
125
+ ][robot_name]
126
+
127
+ # Use system_registry from scene_b (considered more up-to-date)
128
+ result["state"]["registry"]["system_registry"] = scene_b["state"]["registry"]["system_registry"]
129
+
130
+ # Validate merged scene
131
+ validate_merged_scene(result, require_robot=(keep_robot_from is not None))
132
+
133
+ return result
134
+
135
+
136
+ def sanity_check_object_compatibility(obj_name, obj_a, obj_b):
137
+ """
138
+ Sanity check if two object definitions are compatible.
139
+ This is only applied to objects_info, not to states.
140
+
141
+ Args:
142
+ obj_name (str): Name of the object
143
+ obj_a (dict): Object definition from scene_a
144
+ obj_b (dict): Object definition from scene_b
145
+
146
+ Raises:
147
+ AssertionError: If objects are incompatible
148
+ """
149
+ # Check basic properties must match exactly
150
+ assert obj_a["class_module"] == obj_b["class_module"], f"Object {obj_name} has different class_module in two scenes"
151
+ assert obj_a["class_name"] == obj_b["class_name"], f"Object {obj_name} has different class_name in two scenes"
152
+
153
+ # For args, we'll check critical properties exactly and allow small differences in numeric values
154
+ args_a = obj_a["args"]
155
+ args_b = obj_b["args"]
156
+
157
+ # Critical properties must match exactly
158
+ assert args_a["name"] == args_b["name"], f"Object {obj_name} has different name in args"
159
+ assert args_a["category"] == args_b["category"], f"Object {obj_name} has different category in args"
160
+ assert args_a["model"] == args_b["model"], f"Object {obj_name} has different model in args"
161
+ if "fixed_base" in args_a or "fixed_base" in args_b:
162
+ assert args_a["fixed_base"] == args_b["fixed_base"], f"Object {obj_name} has different fixed_base in args"
163
+ if "visual_only" in args_a or "visual_only" in args_b:
164
+ assert args_a["visual_only"] == args_b["visual_only"], f"Object {obj_name} has different visual_only in args"
165
+ assert args_a["in_rooms"] == args_b["in_rooms"], f"Object {obj_name} has different in_rooms in args"
166
+
167
+ # For scale, they should be identical
168
+ if "scale" in args_a and "scale" in args_b:
169
+ scale_a = np.array(args_a["scale"])
170
+ scale_b = np.array(args_b["scale"])
171
+ assert np.allclose(scale_a, scale_b), f"Object {obj_name} has different scale in args"
172
+
173
+
174
+ def validate_merged_scene(scene, require_robot=True):
175
+ """
176
+ Validate that the merged scene is coherent and complete.
177
+
178
+ Args:
179
+ scene (dict): Scene to validate
180
+ require_robot (bool): Whether to require exactly one robot
181
+ """
182
+ # Check that all objects in objects_info have corresponding state
183
+ for obj_name in scene["objects_info"]["init_info"]:
184
+ assert obj_name in scene["state"]["registry"]["object_registry"], f"Missing state for object: {obj_name}"
185
+
186
+ # Robot check (if required)
187
+ if require_robot:
188
+ robot_count = 0
189
+ for obj in scene["objects_info"]["init_info"].values():
190
+ if obj["class_name"] == "Robot":
191
+ robot_count += 1
192
+
193
+ assert robot_count == 1, f"Scene must have exactly one robot, found {robot_count}"
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/deprecated_utils.py ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of utility functions slated to be deprecated once Omniverse bugs are fixed
3
+ """
4
+
5
+ import math
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import carb
9
+ import numpy as np
10
+ import omni
11
+ import omni.timeline
12
+ import torch
13
+ import warp as wp
14
+ from isaacsim.core.prims import Articulation as _ArticulationView
15
+ from isaacsim.core.prims import RigidPrim as _RigidPrimView
16
+ from isaacsim.core.prims import XFormPrim as _XFormPrimView
17
+ from isaacsim.core.utils.prims import get_prim_at_path
18
+ from omni.kit.primitive.mesh.command import CreateMeshPrimWithDefaultXformCommand as CMPWDXC
19
+ from omni.kit.primitive.mesh.command import _get_all_evaluators
20
+ from omni.replicator.core import random_colours
21
+ from PIL import Image, ImageDraw
22
+ from pxr import Gf, PhysxSchema, UsdPhysics
23
+
24
+ DEG2RAD = math.pi / 180.0
25
+
26
+
27
+ class CreateMeshPrimWithDefaultXformCommand(CMPWDXC):
28
+ def __init__(self, prim_type: str, **kwargs):
29
+ """
30
+ Creates primitive.
31
+
32
+ Args:
33
+ prim_type (str): It supports Plane/Sphere/Cone/Cylinder/Disk/Torus/Cube.
34
+
35
+ kwargs:
36
+ object_origin (Gf.Vec3f): Position of mesh center in stage units.
37
+
38
+ u_patches (int): The number of patches to tessellate U direction.
39
+
40
+ v_patches (int): The number of patches to tessellate V direction.
41
+
42
+ w_patches (int): The number of patches to tessellate W direction.
43
+ It only works for Cone/Cylinder/Cube.
44
+
45
+ half_scale (float): Half size of mesh in centimeters. Default is None, which means it's controlled by settings.
46
+
47
+ u_verts_scale (int): Tessellation Level of U. It's a multiplier of u_patches.
48
+
49
+ v_verts_scale (int): Tessellation Level of V. It's a multiplier of v_patches.
50
+
51
+ w_verts_scale (int): Tessellation Level of W. It's a multiplier of w_patches.
52
+ It only works for Cone/Cylinder/Cube.
53
+ For Cone/Cylinder, it's to tessellate the caps.
54
+ For Cube, it's to tessellate along z-axis.
55
+
56
+ above_ground (bool): It will offset the center of mesh above the ground plane if it's True,
57
+ False otherwise. It's False by default. This param only works when param object_origin is not given.
58
+ Otherwise, it will be ignored.
59
+
60
+ stage (Usd.Stage): If specified, stage to create prim on
61
+ """
62
+
63
+ self._prim_type = prim_type[0:1].upper() + prim_type[1:].lower()
64
+ self._usd_context = omni.usd.get_context()
65
+ self._selection = self._usd_context.get_selection()
66
+ self._stage = kwargs.get("stage", self._usd_context.get_stage())
67
+ self._settings = carb.settings.get_settings()
68
+ self._default_path = kwargs.get("prim_path", None)
69
+ self._select_new_prim = kwargs.get("select_new_prim", True)
70
+ self._prepend_default_prim = kwargs.get("prepend_default_prim", True)
71
+ self._above_round = kwargs.get("above_ground", False)
72
+
73
+ self._attributes = {**kwargs}
74
+ # Supported mesh types should have an associated evaluator class
75
+ self._evaluator_class = _get_all_evaluators()[prim_type]
76
+ assert isinstance(self._evaluator_class, type)
77
+
78
+
79
+ class ArticulationView(_ArticulationView):
80
+ """ArticulationView with some additional functionality implemented."""
81
+
82
+ def set_joint_limits(
83
+ self,
84
+ values: Union[np.ndarray, torch.Tensor],
85
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
86
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
87
+ ) -> None:
88
+ """Sets joint limits for articulation joints in the view.
89
+
90
+ Args:
91
+ values (Union[np.ndarray, torch.Tensor, wp.array]): joint limits for articulations in the view. shape (M, K, 2).
92
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims
93
+ to manipulate. Shape (M,).
94
+ Where M <= size of the encapsulated prims in the view.
95
+ Defaults to None (i.e: all prims in the view).
96
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints
97
+ to manipulate. Shape (K,).
98
+ Where K <= num of dofs.
99
+ Defaults to None (i.e: all dofs).
100
+ """
101
+ if not self._is_initialized:
102
+ carb.log_warn("ArticulationView needs to be initialized.")
103
+ return
104
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
105
+ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu")
106
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, "cpu")
107
+ new_values = self._physics_view.get_dof_limits()
108
+ values = self._backend_utils.move_data(values, device="cpu")
109
+ new_values = self._backend_utils.assign(
110
+ values,
111
+ new_values,
112
+ [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices],
113
+ )
114
+ self._physics_view.set_dof_limits(new_values, indices)
115
+ else:
116
+ indices = self._backend_utils.to_list(
117
+ self._backend_utils.resolve_indices(indices, self.count, self._device)
118
+ )
119
+ dof_types = self._backend_utils.to_list(self.get_dof_types())
120
+ joint_indices = self._backend_utils.to_list(
121
+ self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
122
+ )
123
+ values = self._backend_utils.to_list(values)
124
+ articulation_read_idx = 0
125
+ for i in indices:
126
+ dof_read_idx = 0
127
+ for dof_index in joint_indices:
128
+ dof_val = values[articulation_read_idx][dof_read_idx]
129
+ if dof_types[dof_index] == omni.physics.tensors.DofType.Rotation:
130
+ dof_val /= DEG2RAD
131
+ prim = get_prim_at_path(self._dof_paths[i][dof_index])
132
+ prim.GetAttribute("physics:lowerLimit").Set(dof_val[0])
133
+ prim.GetAttribute("physics:upperLimit").Set(dof_val[1])
134
+ dof_read_idx += 1
135
+ articulation_read_idx += 1
136
+ return
137
+
138
+ def get_joint_limits(
139
+ self,
140
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
141
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
142
+ clone: bool = True,
143
+ ) -> Union[np.ndarray, torch.Tensor, wp.array]:
144
+ """Gets joint limits for articulation in the view.
145
+
146
+ Args:
147
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims
148
+ to query. Shape (M,).
149
+ Where M <= size of the encapsulated prims in the view.
150
+ Defaults to None (i.e: all prims in the view).
151
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints
152
+ to query. Shape (K,).
153
+ Where K <= num of dofs.
154
+ Defaults to None (i.e: all dofs).
155
+ clone (Optional[bool]): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
156
+
157
+ Returns:
158
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: joint limits for articulations in the view. shape (M, K).
159
+ """
160
+ if not self._is_initialized:
161
+ carb.log_warn("ArticulationView needs to be initialized.")
162
+ return None
163
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
164
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
165
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
166
+ values = self._backend_utils.move_data(self._physics_view.get_dof_limits(), self._device)
167
+ if clone:
168
+ values = self._backend_utils.clone_tensor(values, device=self._device)
169
+ result = values[
170
+ self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices
171
+ ]
172
+ return result
173
+ else:
174
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
175
+ dof_types = self._backend_utils.to_list(self.get_dof_types())
176
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
177
+ values = np.zeros(shape=(indices.shape[0], joint_indices.shape[0], 2), dtype="float32")
178
+ articulation_write_idx = 0
179
+ indices = self._backend_utils.to_list(indices)
180
+ joint_indices = self._backend_utils.to_list(joint_indices)
181
+ for i in indices:
182
+ dof_write_idx = 0
183
+ for dof_index in joint_indices:
184
+ prim = get_prim_at_path(self._dof_paths[i][dof_index])
185
+ values[articulation_write_idx][dof_write_idx][0] = prim.GetAttribute("physics:lowerLimit").Get()
186
+ values[articulation_write_idx][dof_write_idx][1] = prim.GetAttribute("physics:upperLimit").Get()
187
+ if dof_types[dof_index] == omni.physics.tensors.DofType.Rotation:
188
+ values[articulation_write_idx][dof_write_idx] = (
189
+ values[articulation_write_idx][dof_write_idx] * DEG2RAD
190
+ )
191
+ dof_write_idx += 1
192
+ articulation_write_idx += 1
193
+ values = self._backend_utils.convert(values, dtype="float32", device=self._device, indexed=True)
194
+ return values
195
+
196
+ def get_joint_position_targets(
197
+ self,
198
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
199
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
200
+ clone: bool = True,
201
+ ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]:
202
+ """Get the joint position targets of articulations in the view
203
+
204
+ Args:
205
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
206
+ to query. Shape (M,).
207
+ Where M <= size of the encapsulated prims in the view.
208
+ Defaults to None (i.e: all prims in the view).
209
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints
210
+ to query. Shape (K,).
211
+ Where K <= num of dofs.
212
+ Defaults to None (i.e: all dofs).
213
+ clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
214
+
215
+ Returns:
216
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: joint positions of articulations in the view.
217
+ Shape is (M, K).
218
+ """
219
+ if not self._is_initialized:
220
+ carb.log_warn("ArticulationView needs to be initialized.")
221
+ return None
222
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
223
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
224
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
225
+ current_joint_positions = self._physics_view.get_dof_position_targets()
226
+ if clone:
227
+ current_joint_positions = self._backend_utils.clone_tensor(current_joint_positions, device=self._device)
228
+ result = current_joint_positions[
229
+ self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices
230
+ ]
231
+ return result
232
+ else:
233
+ carb.log_warn("Physics Simulation View is not created yet in order to use get_joint_position_targets")
234
+ return None
235
+
236
+ def get_joint_velocity_targets(
237
+ self,
238
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
239
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
240
+ clone: bool = True,
241
+ ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]:
242
+ """Get the joint velocity targets of articulations in the view
243
+
244
+ Args:
245
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
246
+ to query. Shape (M,).
247
+ Where M <= size of the encapsulated prims in the view.
248
+ Defaults to None (i.e: all prims in the view).
249
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints
250
+ to query. Shape (K,).
251
+ Where K <= num of dofs.
252
+ Defaults to None (i.e: all dofs).
253
+ clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
254
+
255
+ Returns:
256
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: joint velocities of articulations in the view.
257
+ Shape is (M, K).
258
+ """
259
+ if not self._is_initialized:
260
+ carb.log_warn("ArticulationView needs to be initialized.")
261
+ return None
262
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
263
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
264
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
265
+ current_joint_velocities = self._physics_view.get_dof_velocity_targets()
266
+ if clone:
267
+ current_joint_velocities = self._backend_utils.clone_tensor(
268
+ current_joint_velocities, device=self._device
269
+ )
270
+ result = current_joint_velocities[
271
+ self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices
272
+ ]
273
+ return result
274
+ else:
275
+ carb.log_warn("Physics Simulation View is not created yet in order to use get_joint_velocity_targets")
276
+ return None
277
+
278
+ def set_max_velocities(
279
+ self,
280
+ values: Union[np.ndarray, torch.Tensor, wp.array],
281
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
282
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
283
+ ) -> None:
284
+ """Sets maximum velocities for articulation in the view.
285
+
286
+ Args:
287
+ values (Union[np.ndarray, torch.Tensor, wp.array]): maximum velocities for articulations in the view. shape (M, K).
288
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims
289
+ to manipulate. Shape (M,).
290
+ Where M <= size of the encapsulated prims in the view.
291
+ Defaults to None (i.e: all prims in the view).
292
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints
293
+ to manipulate. Shape (K,).
294
+ Where K <= num of dofs.
295
+ Defaults to None (i.e: all dofs).
296
+ """
297
+ if not self._is_initialized:
298
+ carb.log_warn("ArticulationView needs to be initialized.")
299
+ return
300
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
301
+ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu")
302
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, "cpu")
303
+ new_values = self._physics_view.get_dof_max_velocities()
304
+ new_values = self._backend_utils.assign(
305
+ self._backend_utils.move_data(values, device="cpu"),
306
+ new_values,
307
+ [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices],
308
+ )
309
+ self._physics_view.set_dof_max_velocities(new_values, indices)
310
+ else:
311
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
312
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
313
+ articulation_read_idx = 0
314
+ indices = self._backend_utils.to_list(indices)
315
+ joint_indices = self._backend_utils.to_list(joint_indices)
316
+ values = self._backend_utils.to_list(values)
317
+ for i in indices:
318
+ dof_read_idx = 0
319
+ for dof_index in joint_indices:
320
+ prim = PhysxSchema.PhysxJointAPI(get_prim_at_path(self._dof_paths[i][dof_index]))
321
+ if not prim.GetMaxJointVelocityAttr():
322
+ prim.CreateMaxJointVelocityAttr().Set(values[articulation_read_idx][dof_read_idx])
323
+ else:
324
+ prim.GetMaxJointVelocityAttr().Set(values[articulation_read_idx][dof_read_idx])
325
+ dof_read_idx += 1
326
+ articulation_read_idx += 1
327
+ return
328
+
329
+ def get_max_velocities(
330
+ self,
331
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
332
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
333
+ clone: bool = True,
334
+ ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]:
335
+ """Gets maximum velocities for articulation in the view.
336
+
337
+ Args:
338
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indicies to specify which prims
339
+ to query. Shape (M,).
340
+ Where M <= size of the encapsulated prims in the view.
341
+ Defaults to None (i.e: all prims in the view).
342
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indicies to specify which joints
343
+ to query. Shape (K,).
344
+ Where K <= num of dofs.
345
+ Defaults to None (i.e: all dofs).
346
+ clone (Optional[bool]): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
347
+
348
+ Returns:
349
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: maximum velocities for articulations in the view. shape (M, K).
350
+ """
351
+ if not self._is_initialized:
352
+ carb.log_warn("ArticulationView needs to be initialized.")
353
+ return None
354
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
355
+ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu")
356
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, "cpu")
357
+ max_velocities = self._physics_view.get_dof_max_velocities()
358
+ if clone:
359
+ max_velocities = self._backend_utils.clone_tensor(max_velocities, device="cpu")
360
+ result = self._backend_utils.move_data(
361
+ max_velocities[
362
+ self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices
363
+ ],
364
+ device=self._device,
365
+ )
366
+ return result
367
+ else:
368
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
369
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
370
+ max_velocities = np.zeros(shape=(indices.shape[0], joint_indices.shape[0]), dtype="float32")
371
+ indices = self._backend_utils.to_list(indices)
372
+ joint_indices = self._backend_utils.to_list(joint_indices)
373
+ articulation_write_idx = 0
374
+ for i in indices:
375
+ dof_write_idx = 0
376
+ for dof_index in joint_indices:
377
+ prim = PhysxSchema.PhysxJointAPI(get_prim_at_path(self._dof_paths[i][dof_index]))
378
+ max_velocities[articulation_write_idx][dof_write_idx] = prim.GetMaxJointVelocityAttr().Get()
379
+ dof_write_idx += 1
380
+ articulation_write_idx += 1
381
+ max_velocities = self._backend_utils.convert(
382
+ max_velocities, dtype="float32", device=self._device, indexed=True
383
+ )
384
+ return max_velocities
385
+
386
+ def set_joint_positions(
387
+ self,
388
+ positions: Optional[Union[np.ndarray, torch.Tensor, wp.array]],
389
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
390
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
391
+ ) -> None:
392
+ """Set the joint positions of articulations in the view
393
+
394
+ .. warning::
395
+
396
+ This method will immediately set (teleport) the affected joints to the indicated value.
397
+ Use the ``set_joint_position_targets`` or the ``apply_action`` methods to control the articulation joints.
398
+
399
+ Args:
400
+ positions (Optional[Union[np.ndarray, torch.Tensor, wp.array]]): joint positions of articulations in the view to be set to in the next frame.
401
+ shape is (M, K).
402
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
403
+ to manipulate. Shape (M,).
404
+ Where M <= size of the encapsulated prims in the view.
405
+ Defaults to None (i.e: all prims in the view).
406
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints
407
+ to manipulate. Shape (K,).
408
+ Where K <= num of dofs.
409
+ Defaults to None (i.e: all dofs).
410
+
411
+ .. hint::
412
+
413
+ This method belongs to the methods used to set the articulation kinematic states:
414
+
415
+ ``set_velocities`` (``set_linear_velocities``, ``set_angular_velocities``),
416
+ ``set_joint_positions``, ``set_joint_velocities``, ``set_joint_efforts``
417
+
418
+ Example:
419
+
420
+ .. code-block:: python
421
+
422
+ >>> # set all the articulation joints.
423
+ >>> # Since there are 5 envs, the joint positions are repeated 5 times
424
+ >>> 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))
425
+ >>> prims.set_joint_positions(positions)
426
+ >>>
427
+ >>> # set only the fingers in closed position: panda_finger_joint1 (7) and panda_finger_joint2 (8) to 0.0
428
+ >>> # for the first, middle and last of the 5 envs
429
+ >>> positions = np.tile(np.array([0.0, 0.0]), (3, 1))
430
+ >>> prims.set_joint_positions(positions, indices=np.array([0, 2, 4]), joint_indices=np.array([7, 8]))
431
+ """
432
+ if not self._is_initialized:
433
+ carb.log_warn("ArticulationView needs to be initialized.")
434
+ return
435
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
436
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
437
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
438
+ new_dof_pos = self._physics_view.get_dof_positions()
439
+ new_dof_pos = self._backend_utils.assign(
440
+ self._backend_utils.move_data(positions, device=self._device),
441
+ new_dof_pos,
442
+ [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices],
443
+ )
444
+ self._physics_view.set_dof_positions(new_dof_pos, indices)
445
+
446
+ # THIS IS THE FIX:
447
+ # FIX V1: COMMENT OUT THE BELOW LINE AND SET TARGETS INSTEAD
448
+ # FIX V2: DECOUPLE INSTANTANEOUS POSITION FROM TARGETS
449
+ # self._physics_view.set_dof_position_targets(new_dof_pos, indices)
450
+ # self.set_joint_position_targets(positions, indices, joint_indices)
451
+ else:
452
+ carb.log_warn("Physics Simulation View is not created yet in order to use set_joint_positions")
453
+
454
+ def set_joint_velocities(
455
+ self,
456
+ velocities: Optional[Union[np.ndarray, torch.Tensor, wp.array]],
457
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
458
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
459
+ ) -> None:
460
+ """Set the joint velocities of articulations in the view
461
+
462
+ .. warning::
463
+
464
+ This method will immediately set the affected joints to the indicated value.
465
+ Use the ``set_joint_velocity_targets`` or the ``apply_action`` methods to control the articulation joints.
466
+
467
+ Args:
468
+ velocities (Optional[Union[np.ndarray, torch.Tensor, wp.array]]): joint velocities of articulations in the view to be set to in the next frame.
469
+ shape is (M, K).
470
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
471
+ to manipulate. Shape (M,).
472
+ Where M <= size of the encapsulated prims in the view.
473
+ Defaults to None (i.e: all prims in the view).
474
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints
475
+ to manipulate. Shape (K,).
476
+ Where K <= num of dofs.
477
+ Defaults to None (i.e: all dofs).
478
+
479
+ .. hint::
480
+
481
+ This method belongs to the methods used to set the articulation kinematic states:
482
+
483
+ ``set_velocities`` (``set_linear_velocities``, ``set_angular_velocities``),
484
+ ``set_joint_positions``, ``set_joint_velocities``, ``set_joint_efforts``
485
+
486
+ Example:
487
+
488
+ .. code-block:: python
489
+
490
+ >>> # set the velocities for all the articulation joints to the indicated values.
491
+ >>> # Since there are 5 envs, the joint velocities are repeated 5 times
492
+ >>> 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))
493
+ >>> prims.set_joint_velocities(velocities)
494
+ >>>
495
+ >>> # set the fingers velocities: panda_finger_joint1 (7) and panda_finger_joint2 (8) to -0.1
496
+ >>> # for the first, middle and last of the 5 envs
497
+ >>> velocities = np.tile(np.array([-0.1, -0.1]), (3, 1))
498
+ >>> prims.set_joint_velocities(velocities, indices=np.array([0, 2, 4]), joint_indices=np.array([7, 8]))
499
+ """
500
+ if not self._is_initialized:
501
+ carb.log_warn("ArticulationView needs to be initialized.")
502
+ return
503
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
504
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
505
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
506
+ new_dof_vel = self._physics_view.get_dof_velocities()
507
+ new_dof_vel = self._backend_utils.assign(
508
+ self._backend_utils.move_data(velocities, device=self._device),
509
+ new_dof_vel,
510
+ [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices],
511
+ )
512
+ self._physics_view.set_dof_velocities(new_dof_vel, indices)
513
+
514
+ # THIS IS THE FIX:
515
+ # FIX V1: COMMENT OUT THE BELOW LINE AND SET TARGETS INSTEAD
516
+ # FIX V2: DECOUPLE INSTANTANEOUS VELOCITY FROM TARGETS
517
+ # self._physics_view.set_dof_velocity_targets(new_dof_vel, indices)
518
+ # self.set_joint_velocity_targets(velocities, indices, joint_indices)
519
+ else:
520
+ carb.log_warn("Physics Simulation View is not created yet in order to use set_joint_velocities")
521
+ return
522
+
523
+ def set_joint_efforts(
524
+ self,
525
+ efforts: Optional[Union[np.ndarray, torch.Tensor, wp.array]],
526
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
527
+ joint_indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
528
+ ) -> None:
529
+ """Set the joint efforts of articulations in the view
530
+
531
+ .. note::
532
+
533
+ This method can be used for effort control. For this purpose, there must be no joint drive
534
+ or the stiffness and damping must be set to zero.
535
+
536
+ Args:
537
+ efforts (Optional[Union[np.ndarray, torch.Tensor, wp.array]]): efforts of articulations in the view to be set to in the next frame.
538
+ shape is (M, K).
539
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
540
+ to manipulate. Shape (M,).
541
+ Where M <= size of the encapsulated prims in the view.
542
+ Defaults to None (i.e: all prims in the view).
543
+ joint_indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): joint indices to specify which joints
544
+ to manipulate. Shape (K,).
545
+ Where K <= num of dofs.
546
+ Defaults to None (i.e: all dofs).
547
+
548
+ .. hint::
549
+
550
+ This method belongs to the methods used to set the articulation kinematic states:
551
+
552
+ ``set_velocities`` (``set_linear_velocities``, ``set_angular_velocities``),
553
+ ``set_joint_positions``, ``set_joint_velocities``, ``set_joint_efforts``
554
+
555
+ Example:
556
+
557
+ .. code-block:: python
558
+
559
+ >>> # set the efforts for all the articulation joints to the indicated values.
560
+ >>> # Since there are 5 envs, the joint efforts are repeated 5 times
561
+ >>> efforts = np.tile(np.array([10, 20, 30, 40, 50, 60, 70, 80, 90]), (num_envs, 1))
562
+ >>> prims.set_joint_efforts(efforts)
563
+ >>>
564
+ >>> # set the fingers efforts: panda_finger_joint1 (7) and panda_finger_joint2 (8) to 10
565
+ >>> # for the first, middle and last of the 5 envs
566
+ >>> efforts = np.tile(np.array([10, 10]), (3, 1))
567
+ >>> prims.set_joint_efforts(efforts, indices=np.array([0, 2, 4]), joint_indices=np.array([7, 8]))
568
+ """
569
+ if not self._is_initialized:
570
+ carb.log_warn("ArticulationView needs to be initialized.")
571
+ return
572
+
573
+ if not omni.timeline.get_timeline_interface().is_stopped() and self._physics_view is not None:
574
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
575
+ joint_indices = self._backend_utils.resolve_indices(joint_indices, self.num_dof, self._device)
576
+
577
+ # THIS IS THE FIX: COMMENT OUT THE BELOW LINE AND USE ACTUATION FORCES INSTEAD
578
+ # new_dof_efforts = self._backend_utils.create_zeros_tensor(
579
+ # shape=[self.count, self.num_dof], dtype="float32", device=self._device
580
+ # )
581
+ new_dof_efforts = self._physics_view.get_dof_actuation_forces()
582
+ new_dof_efforts = self._backend_utils.assign(
583
+ self._backend_utils.move_data(efforts, device=self._device),
584
+ new_dof_efforts,
585
+ [self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, joint_indices],
586
+ )
587
+ self._physics_view.set_dof_actuation_forces(new_dof_efforts, indices)
588
+ else:
589
+ carb.log_warn("Physics Simulation View is not created yet in order to use set_joint_efforts")
590
+ return
591
+
592
+ def _invalidate_physics_handle_callback(self, event):
593
+ # Overwrite super method, add additional de-initialization
594
+ if event.type == int(omni.timeline.TimelineEventType.STOP):
595
+ self._physics_view = None
596
+ self._invalidate_physics_handle_event = None
597
+ self._is_initialized = False
598
+
599
+ @property
600
+ def initialized(self):
601
+ # THIS IS THE FIX: another crazy bug from isaac, specifically isaac 4.5
602
+ return self._is_initialized
603
+
604
+ def _on_prim_deletion(self, prim_path):
605
+ _XFormPrimView._on_prim_deletion(self, prim_path)
606
+ self._physics_view = None
607
+
608
+
609
+ class RigidPrimView(_RigidPrimView):
610
+ def get_linear_velocities(
611
+ self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None, clone: bool = True
612
+ ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]:
613
+ """Get the linear velocities of prims in the view.
614
+
615
+ Args:
616
+ indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indices to specify which prims
617
+ to query. Shape (M,).
618
+ Where M <= size of the encapsulated prims in the view.
619
+ Defaults to None (i.e: all prims in the view)
620
+ clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
621
+
622
+ Returns:
623
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: linear velocities of the prims in the view. shape is (M, 3).
624
+
625
+ Example:
626
+
627
+ .. code-block:: python
628
+
629
+ >>> # get all rigid prim linear velocities. Returned shape is (5, 3) for the example: 5 envs, linear (3)
630
+ >>> prims.get_linear_velocities()
631
+ [[0. 0. 0.]
632
+ [0. 0. 0.]
633
+ [0. 0. 0.]
634
+ [0. 0. 0.]
635
+ [0. 0. 0.]]
636
+ >>>
637
+ >>> # get only the rigid prim linear velocities for the first, middle and last of the 5 envs.
638
+ >>> # Returned shape is (3, 3) for the example: 3 envs selected, linear (3)
639
+ >>> prims.get_linear_velocities(indices=np.array([0, 2, 4]))
640
+ [[0. 0. 0.]
641
+ [0. 0. 0.]
642
+ [0. 0. 0.]]
643
+ """
644
+ if not self._is_valid:
645
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
646
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
647
+
648
+ if self.is_physics_handle_valid():
649
+ linear_velocities = self._physics_view.get_velocities()
650
+ if clone:
651
+ # THIS LINE WAS NAMED INCORRECTLY!!!
652
+ linear_velocities = self._backend_utils.clone_tensor(linear_velocities, device=self._device)
653
+ return linear_velocities[indices, 0:3]
654
+ else:
655
+ linear_velocities = np.zeros(shape=(indices.shape[0], 3), dtype=np.float32)
656
+ write_idx = 0
657
+ indices = self._backend_utils.to_list(indices)
658
+ for i in indices:
659
+ if self._rigid_body_apis[i] is None:
660
+ if self._prims[i].HasAPI(UsdPhysics.RigidBodyAPI):
661
+ rigid_api = UsdPhysics.RigidBodyAPI(self._prims[i])
662
+ else:
663
+ rigid_api = UsdPhysics.RigidBodyAPI.Apply(self._prims[i])
664
+ self._rigid_body_apis[i] = rigid_api
665
+ linear_velocities[write_idx] = np.array(
666
+ self._rigid_body_apis[i].GetVelocityAttr().Get(), dtype=np.float32
667
+ )
668
+ write_idx += 1
669
+ linear_velocities = self._backend_utils.convert(
670
+ linear_velocities, dtype="float32", device=self._device, indexed=True
671
+ )
672
+ return linear_velocities
673
+
674
+ def get_angular_velocities(
675
+ self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None, clone: bool = True
676
+ ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]:
677
+ """Get the angular velocities of prims in the view.
678
+
679
+ Args:
680
+ indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indices to specify which prims
681
+ to query. Shape (M,).
682
+ Where M <= size of the encapsulated prims in the view.
683
+ Defaults to None (i.e: all prims in the view)
684
+ clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
685
+
686
+ Returns:
687
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: angular velocities of the prims in the view. shape is (M, 3).
688
+
689
+ Example:
690
+
691
+ .. code-block:: python
692
+
693
+ >>> # get all rigid prim angular velocities. Returned shape is (5, 3) for the example: 5 envs, angular (3)
694
+ >>> prims.get_angular_velocities()
695
+ [[0. 0. 0.]
696
+ [0. 0. 0.]
697
+ [0. 0. 0.]
698
+ [0. 0. 0.]
699
+ [0. 0. 0.]]
700
+ >>>
701
+ >>> # get only the rigid prim angular velocities for the first, middle and last of the 5 envs
702
+ >>> # Returned shape is (5, 3) for the example: 3 envs selected, angular (3)
703
+ >>> prims.get_angular_velocities(indices=np.array([0, 2, 4]))
704
+ [[0. 0. 0.]
705
+ [0. 0. 0.]
706
+ [0. 0. 0.]]
707
+ """
708
+ if not self._is_valid:
709
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
710
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
711
+ if self.is_physics_handle_valid():
712
+ angular_velocities = self._physics_view.get_velocities()
713
+ if clone:
714
+ # THIS LINE WAS NAMED INCORRECTLY!!
715
+ angular_velocities = self._backend_utils.clone_tensor(angular_velocities, device=self._device)
716
+ return angular_velocities[indices, 3:6]
717
+ else:
718
+ angular_velocities = np.zeros(shape=(indices.shape[0], 3), dtype=np.float32)
719
+ write_idx = 0
720
+ indices = self._backend_utils.to_list(indices)
721
+ for i in indices:
722
+ if self._rigid_body_apis[i] is None:
723
+ if self._prims[i].HasAPI(UsdPhysics.RigidBodyAPI):
724
+ rigid_api = UsdPhysics.RigidBodyAPI(self._prims[i])
725
+ else:
726
+ rigid_api = UsdPhysics.RigidBodyAPI.Apply(self._prims[i])
727
+ self._rigid_body_apis[i] = rigid_api
728
+ angular_velocities[write_idx] = np.array(
729
+ self._rigid_body_apis[i].GetAngularVelocityAttr().Get(), dtype="float32"
730
+ )
731
+ write_idx += 1
732
+ angular_velocities = self._backend_utils.convert(
733
+ angular_velocities, dtype="float32", device=self._device, indexed=True
734
+ )
735
+ return angular_velocities
736
+
737
+ def get_world_poses(
738
+ self,
739
+ indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None,
740
+ clone: bool = True,
741
+ usd: bool = True,
742
+ ) -> Union[
743
+ Tuple[np.ndarray, np.ndarray], Tuple[torch.Tensor, torch.Tensor], Tuple[wp.indexedarray, wp.indexedarray]
744
+ ]:
745
+ """Get the poses of the prims in the view with respect to the world's frame.
746
+
747
+ Args:
748
+ indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indices to specify which prims
749
+ to query. Shape (M,).
750
+ Where M <= size of the encapsulated prims in the view.
751
+ Defaults to None (i.e: all prims in the view).
752
+ clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
753
+ usd (bool, optional): True to query from usd. Otherwise False to query from Fabric data. Defaults to True.
754
+
755
+ Returns:
756
+ Union[Tuple[np.ndarray, np.ndarray], Tuple[torch.Tensor, torch.Tensor], Tuple[wp.indexedarray, wp.indexedarray]]:
757
+ first index is positions in the world frame of the prims. shape is (M, 3).
758
+ second index is quaternion orientations in the world frame of the prims.
759
+ quaternion is scalar-first (w, x, y, z). shape is (M, 4).
760
+
761
+ Example:
762
+
763
+ .. code-block:: python
764
+
765
+ >>> # get all rigid prim poses with respect to the world's frame.
766
+ >>> # Returned shape is position (5, 3) and orientation (5, 4) for the example: 5 envs
767
+ >>> positions, orientations = prims.get_world_poses()
768
+ >>> positions
769
+ [[ 1.4999989e+00 -7.4999851e-01 -1.5118626e-07]
770
+ [ 1.4999989e+00 7.5000149e-01 -2.5988294e-07]
771
+ [-1.0017333e-06 -7.4999845e-01 7.6070329e-08]
772
+ [-9.5906785e-07 7.5000149e-01 1.0593490e-07]
773
+ [-1.5000011e+00 -7.4999851e-01 1.9655154e-07]]
774
+ >>> orientations
775
+ [[ 9.9999994e-01 -8.8168377e-07 -4.1946004e-07 -1.5067183e-08]
776
+ [ 9.9999994e-01 -8.8691013e-07 -4.2665880e-07 -2.7188951e-09]
777
+ [ 1.0000000e+00 -9.5171310e-07 -2.2615541e-07 5.5922797e-08]
778
+ [ 1.0000000e+00 -8.9923367e-07 -1.4408238e-07 1.3476099e-08]
779
+ [ 1.0000000e+00 -7.9806580e-07 -1.3064776e-07 5.3154917e-08]]
780
+ >>>
781
+ >>> # get only the rigid prim poses with respect to the world's frame for the first, middle and last of the 5 envs.
782
+ >>> # Returned shape is position (3, 3) and orientation (3, 4) for the example: 3 envs selected
783
+ >>> positions, orientations = prims.get_world_poses(indices=np.array([0, 2, 4]))
784
+ >>> positions
785
+ [[ 1.4999989e+00 -7.4999851e-01 -1.5118626e-07]
786
+ [-1.0017333e-06 -7.4999845e-01 7.6070329e-08]
787
+ [-1.5000011e+00 -7.4999851e-01 1.9655154e-07]]
788
+ >>> orientations
789
+ [[ 9.9999994e-01 -8.8168377e-07 -4.1946004e-07 -1.5067183e-08]
790
+ [ 1.0000000e+00 -9.5171310e-07 -2.2615541e-07 5.5922797e-08]
791
+ [ 1.0000000e+00 -7.9806580e-07 -1.3064776e-07 5.3154917e-08]]
792
+ """
793
+ if not self._is_valid:
794
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
795
+ if self.is_physics_handle_valid():
796
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
797
+ pose = self._physics_view.get_transforms()
798
+ if clone:
799
+ pose = self._backend_utils.clone_tensor(pose, device=self._device)
800
+ pos = pose[indices, 0:3]
801
+
802
+ # We AVOID native self._backend_utils.xyzw2wxyz(pose[indices, 3:7]) because it's slow!!
803
+ rot = pose[:, [6, 3, 4, 5]][indices]
804
+ return pos, rot
805
+ else:
806
+ return _XFormPrimView.get_world_poses(self, indices=indices, usd=usd)
807
+
808
+ def enable_gravities(self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None) -> None:
809
+ """Enable gravity on rigid bodies (enabled by default).
810
+
811
+ Args:
812
+ indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indicies to specify which prims
813
+ to manipulate. Shape (M,).
814
+ Where M <= size of the encapsulated prims in the view.
815
+ Defaults to None (i.e: all prims in the view).
816
+ """
817
+ if not self._is_valid:
818
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
819
+ if self.is_physics_handle_valid():
820
+ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu")
821
+ data = self._physics_view.get_disable_gravities().reshape(self._count)
822
+ data = self._backend_utils.assign(
823
+ self._backend_utils.create_tensor_from_list([False] * len(indices), dtype="uint8"), data, indices
824
+ )
825
+ self._physics_view.set_disable_gravities(data, indices)
826
+ else:
827
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
828
+ indices = self._backend_utils.to_list(indices)
829
+ for i in indices:
830
+ if self._physx_rigid_body_apis[i] is None:
831
+ if self._prims[i].HasAPI(PhysxSchema.PhysxRigidBodyAPI):
832
+ rigid_api = PhysxSchema.PhysxRigidBodyAPI(self._prims[i])
833
+ else:
834
+ rigid_api = PhysxSchema.PhysxRigidBodyAPI.Apply(self._prims[i])
835
+ self._physx_rigid_body_apis[i] = rigid_api
836
+ self._physx_rigid_body_apis[i].GetDisableGravityAttr().Set(False)
837
+
838
+ def disable_gravities(self, indices: Optional[Union[np.ndarray, list, torch.Tensor, wp.array]] = None) -> None:
839
+ """Disable gravity on rigid bodies (enabled by default).
840
+
841
+ Args:
842
+ indices (Optional[Union[np.ndarray, list, torch.Tensor, wp.array]], optional): indicies to specify which prims
843
+ to manipulate. Shape (M,).
844
+ Where M <= size of the encapsulated prims in the view.
845
+ Defaults to None (i.e: all prims in the view).
846
+ """
847
+ if not self._is_valid:
848
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
849
+ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu")
850
+ if self.is_physics_handle_valid():
851
+ data = self._physics_view.get_disable_gravities().reshape(self._count)
852
+ data = self._backend_utils.assign(
853
+ self._backend_utils.create_tensor_from_list([True] * len(indices), dtype="uint8"), data, indices
854
+ )
855
+ self._physics_view.set_disable_gravities(data, indices)
856
+ else:
857
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
858
+ indices = self._backend_utils.to_list(indices)
859
+ for i in indices:
860
+ if self._physx_rigid_body_apis[i] is None:
861
+ if self._prims[i].HasAPI(PhysxSchema.PhysxRigidBodyAPI):
862
+ rigid_api = PhysxSchema.PhysxRigidBodyAPI(self._prims[i])
863
+ else:
864
+ rigid_api = PhysxSchema.PhysxRigidBodyAPI.Apply(self._prims[i])
865
+ self._physx_rigid_body_apis[i] = rigid_api
866
+ self._physx_rigid_body_apis[i].GetDisableGravityAttr().Set(True)
867
+ return
868
+
869
+ def get_coms(
870
+ self, indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None, clone: bool = True
871
+ ) -> Union[np.ndarray, torch.Tensor, wp.indexedarray]:
872
+ """Get rigid body center of mass (COM) of bodies in the view.
873
+
874
+ Args:
875
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
876
+ to query. Shape (M,).
877
+ Where M <= size of the encapsulated prims in the view.
878
+ Defaults to None (i.e: all prims in the view).
879
+ clone (bool, optional): True to return a clone of the internal buffer. Otherwise False. Defaults to True.
880
+
881
+ Returns:
882
+ Union[np.ndarray, torch.Tensor, wp.indexedarray]: rigid body center of mass positions and orientations of prims in the view.
883
+ position shape is (M, 1, 3), orientation shape is (M, 1, 4).
884
+
885
+ Example:
886
+
887
+ .. code-block:: python
888
+
889
+ >>> # get all rigid body center of mass.
890
+ >>> # Returned shape is (5, 1, 3) for positions and (5, 1, 4) for orientations for the example: 5 envs
891
+ >>> positions, orientations = prims.get_coms()
892
+ >>> positions
893
+ [[[0. 0. 0.]]
894
+ [[0. 0. 0.]]
895
+ [[0. 0. 0.]]
896
+ [[0. 0. 0.]]
897
+ [[0. 0. 0.]]]
898
+ >>> orientations
899
+ [[[1. 0. 0. 0.]]
900
+ [[1. 0. 0. 0.]]
901
+ [[1. 0. 0. 0.]]
902
+ [[1. 0. 0. 0.]]
903
+ [[1. 0. 0. 0.]]]
904
+ >>>
905
+ >>> # get rigid body center of mass for the first, middle and last of the 5 envs.
906
+ >>> # Returned shape is (3, 1, 3) for positions and (3, 1, 4) for orientations
907
+ >>> positions, orientations = prims.get_coms(indices=np.array([0, 2, 4]))
908
+ >>> positions
909
+ [[[0. 0. 0.]]
910
+ [[0. 0. 0.]]
911
+ [[0. 0. 0.]]]
912
+ >>> orientations
913
+ [[[1. 0. 0. 0.]]
914
+ [[1. 0. 0. 0.]]
915
+ [[1. 0. 0. 0.]]]
916
+ """
917
+ if not self._is_valid:
918
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
919
+ if self.is_physics_handle_valid():
920
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
921
+ current_values = self._backend_utils.move_data(
922
+ self._physics_view.get_coms().reshape((self.count, 7)), self._device
923
+ )
924
+ if clone:
925
+ current_values = self._backend_utils.clone_tensor(current_values, device=self._device)
926
+ positions = current_values[
927
+ self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, 0:3
928
+ ]
929
+ orientations = self._backend_utils.xyzw2wxyz(
930
+ current_values[self._backend_utils.expand_dims(indices, 1) if self._backend != "warp" else indices, 3:7]
931
+ )
932
+ return positions, orientations
933
+ else:
934
+ indices = self._backend_utils.resolve_indices(indices, self.count, self._device)
935
+ positions = np.zeros((indices.shape[0], 1, 3), dtype=np.float32)
936
+ orientations = np.zeros((indices.shape[0], 1, 4), dtype=np.float32)
937
+ indices = self._backend_utils.to_list(indices)
938
+ write_idx = 0
939
+ for i in indices:
940
+ positions[write_idx][0] = np.array(self._prims[i].GetAttribute("physics:centerOfMass").Get())
941
+ orientations[write_idx][0] = np.array([1, 0, 0, 0])
942
+ write_idx += 1
943
+ positions = self._backend_utils.convert(positions, device=self._device, dtype="float32", indexed=True)
944
+ orientations = self._backend_utils.convert(orientations, device=self._device, dtype="float32", indexed=True)
945
+ return positions, orientations
946
+
947
+ def set_coms(
948
+ self,
949
+ positions: Union[np.ndarray, torch.Tensor, wp.array] = None,
950
+ orientations: Union[np.ndarray, torch.Tensor, wp.array] = None,
951
+ indices: Optional[Union[np.ndarray, List, torch.Tensor, wp.array]] = None,
952
+ ) -> None:
953
+ """Set body center of mass (COM) positions and orientations for bodies in the view.
954
+
955
+ Args:
956
+ positions (Union[np.ndarray, torch.Tensor, wp.array]): body center of mass positions for bodies in the view. shape (M, 1, 3).
957
+ orientations (Union[np.ndarray, torch.Tensor, wp.array]): body center of mass orientations for bodies in the view. shape (M, 1, 4).
958
+ indices (Optional[Union[np.ndarray, List, torch.Tensor, wp.array]], optional): indices to specify which prims
959
+ to manipulate. Shape (M,).
960
+ Where M <= size of the encapsulated prims in the view.
961
+ Defaults to None (i.e: all prims in the view).
962
+
963
+ Example:
964
+
965
+ .. code-block:: python
966
+
967
+ >>> # set the center of mass for all the rigid bodies to the specified values.
968
+ >>> # Since there are 5 envs, the inertias are repeated 5 times
969
+ >>> positions = np.tile(np.array([0.01, 0.02, 0.03]), (num_envs, 1, 1))
970
+ >>> orientations = np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (num_envs, 1, 1))
971
+ >>> prims.set_coms(positions, orientations)
972
+ >>>
973
+ >>> # set the rigid bodies center of mass for the first, middle and last of the 5 envs
974
+ >>> positions = np.tile(np.array([0.01, 0.02, 0.03]), (3, 1, 1))
975
+ >>> orientations = np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (3, 1, 1))
976
+ >>> prims.set_coms(positions, orientations, indices=np.array([0, 2, 4]))
977
+ """
978
+ if not self._is_valid:
979
+ raise Exception("prim view {} is not a valid view".format(self._regex_prim_paths))
980
+ indices = self._backend_utils.resolve_indices(indices, self.count, "cpu")
981
+ if self.is_physics_handle_valid():
982
+ coms = self._physics_view.get_coms().reshape((self.count, 7))
983
+ if positions is not None:
984
+ if self._backend == "warp":
985
+ coms = self._backend_utils.assign(
986
+ self._backend_utils.move_data(positions, device="cpu"),
987
+ coms,
988
+ [indices, wp.array([0, 1, 2], dtype=wp.int32, device="cpu")],
989
+ )
990
+ else:
991
+ coms[self._backend_utils.expand_dims(indices, 1), 0:3] = self._backend_utils.move_data(
992
+ positions, device="cpu"
993
+ )
994
+ if orientations is not None:
995
+ if self._backend == "warp":
996
+ coms = self._backend_utils.assign(
997
+ self._backend_utils.move_data(self._backend_utils.wxyz2xyzw(orientations), device="cpu"),
998
+ coms,
999
+ [indices, wp.array([3, 4, 5, 6], dtype=wp.int32, device="cpu")],
1000
+ )
1001
+ else:
1002
+ coms[self._backend_utils.expand_dims(indices, 1), 3:7] = self._backend_utils.move_data(
1003
+ orientations[:, :, [1, 2, 3, 0]], device="cpu"
1004
+ )
1005
+ self._physics_view.set_coms(coms, indices)
1006
+ else:
1007
+ # Note: this does NOT set orientation, as it is not supported in USD
1008
+ positions = self._backend_utils.to_list(positions)
1009
+ write_idx = 0
1010
+ for i in indices:
1011
+ properties = self._prims[i].GetPropertyNames()
1012
+ position = Gf.Vec3f(*positions[write_idx][0])
1013
+ if "physics:centerOfMass" not in properties:
1014
+ carb.log_error(
1015
+ "physics:centerOfMass property needs to be set for {} before setting its position".format(
1016
+ self.name
1017
+ )
1018
+ )
1019
+ xform_op = self._prims[i].GetAttribute("physics:centerOfMass")
1020
+ xform_op.Set(position)
1021
+ write_idx += 1
1022
+
1023
+
1024
+ def colorize_bboxes(bboxes_2d_data, bboxes_2d_rgb, num_channels=3):
1025
+ """Colorizes 2D bounding box data for visualization.
1026
+
1027
+ We are overriding the replicator native version of this function to fix a bug.
1028
+ In their version of this function, the ordering of the rectangle corners is incorrect and we fix it here.
1029
+
1030
+ Args:
1031
+ bboxes_2d_data (numpy.ndarray): 2D bounding box data from the sensor.
1032
+ bboxes_2d_rgb (numpy.ndarray): RGB data from the sensor to embed bounding box.
1033
+ num_channels (int): Specify number of channels i.e. 3 or 4.
1034
+ """
1035
+ semantic_id_list = []
1036
+ bbox_2d_list = []
1037
+ rgb_img = Image.fromarray(bboxes_2d_rgb)
1038
+ rgb_img_draw = ImageDraw.Draw(rgb_img)
1039
+ for bbox_2d in bboxes_2d_data:
1040
+ semantic_id_list.append(bbox_2d[0])
1041
+ bbox_2d_list.append(bbox_2d)
1042
+ semantic_id_list_np = np.unique(np.array(semantic_id_list))
1043
+ color_list = random_colours(len(semantic_id_list_np.tolist()), False, num_channels)
1044
+ for bbox_2d in bbox_2d_list:
1045
+ index = np.where(semantic_id_list_np == bbox_2d[0])[0][0]
1046
+ bbox_color = color_list[index]
1047
+ outline = (bbox_color[0], bbox_color[1], bbox_color[2])
1048
+ if num_channels == 4:
1049
+ outline = (
1050
+ bbox_color[0],
1051
+ bbox_color[1],
1052
+ bbox_color[2],
1053
+ bbox_color[3],
1054
+ )
1055
+ rgb_img_draw.rectangle([(bbox_2d[1], bbox_2d[2]), (bbox_2d[3], bbox_2d[4])], outline=outline, width=2)
1056
+ bboxes_2d_rgb = np.array(rgb_img)
1057
+ return bboxes_2d_rgb
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/geometry_utils.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of helper utility functions for dealing with 3D geometry
3
+ """
4
+
5
+ import math
6
+
7
+ import torch as th
8
+
9
+ import omnigibson.utils.transform_utils as T
10
+
11
+
12
+ def wrap_angle(theta):
13
+ """ "
14
+ Converts an angle to the range [-pi, pi).
15
+
16
+ Args:
17
+ theta (float): angle in radians
18
+
19
+ Returns:
20
+ float: angle in radians in range [-pi, pi)
21
+ """
22
+ return (theta + math.pi) % (2 * math.pi) - math.pi
23
+
24
+
25
+ def get_particle_positions_in_frame(pos, quat, scale, particle_positions):
26
+ """
27
+ Transforms particle positions @positions into the frame specified by @pos and @quat with new scale @scale,
28
+ where @pos and @quat are assumed to be specified in the same coordinate frame that @particle_positions is specified
29
+
30
+ Args:
31
+ pos (3-array): (x,y,z) pos of the new frame
32
+ quat (4-array): (x,y,z,w) quaternion orientation of the new frame
33
+ scale (3-array): (x,y,z) local scale of the new frame
34
+ particle_positions ((N, 3) array): positions
35
+
36
+ Returns:
37
+ (N,) array: updated particle positions in the new coordinate frame
38
+ """
39
+
40
+ # Get pose of origin (global frame) in new_frame
41
+ origin_in_new_frame = T.pose_inv(T.pose2mat((pos, quat)))
42
+ # Batch the transforms to get all particle points in the local link frame
43
+ positions_tensor = th.tile(th.eye(4).reshape(1, 4, 4), (len(particle_positions), 1, 1)) # (N, 4, 4)
44
+ # Scale by the new scale#
45
+ positions_tensor[:, :3, 3] = particle_positions
46
+ particle_positions = (origin_in_new_frame @ positions_tensor)[:, :3, 3] # (N, 3)
47
+ # Scale by the new scale
48
+ return particle_positions / scale.reshape(1, 3)
49
+
50
+
51
+ def get_particle_positions_from_frame(pos, quat, scale, particle_positions):
52
+ """
53
+ Transforms particle positions @positions from the frame specified by @pos and @quat with new scale @scale.
54
+
55
+ This is similar to @get_particle_positions_in_frame, but does the reverse operation, inverting @pos and @quat
56
+
57
+ Args:
58
+ pos (3-array): (x,y,z) pos of the local frame
59
+ quat (4-array): (x,y,z,w) quaternion orientation of the local frame
60
+ scale (3-array): (x,y,z) local scale of the local frame
61
+ particle_positions ((N, 3) array): positions
62
+
63
+ Returns:
64
+ (N,) array: updated particle positions in the parent coordinate frame
65
+ """
66
+ # Scale by the new scale
67
+ particle_positions = particle_positions * scale.reshape(1, 3)
68
+
69
+ # Get pose of origin (global frame) in new_frame
70
+ origin_in_new_frame = T.pose2mat((pos, quat))
71
+ # Batch the transforms to get all particle points in the local link frame
72
+ positions_tensor = th.tile(th.eye(4).reshape(1, 4, 4), (len(particle_positions), 1, 1)) # (N, 4, 4)
73
+ # Scale by the new scale#
74
+ positions_tensor[:, :3, 3] = particle_positions
75
+ return (origin_in_new_frame @ positions_tensor)[:, :3, 3] # (N, 3)
76
+
77
+
78
+ def check_points_in_cube(size, particle_positions):
79
+ """
80
+ Checks which points are within a cube with specified size @size.
81
+
82
+ NOTE: Assumes the cube and positions are expressed
83
+ in the same coordinate frame such that the cube's dimensions are axis-aligned with (x,y,z)
84
+
85
+ Args:
86
+ size float: length of each side of the cube, specified in its local frame
87
+ particle_positions ((N, 3) array): positions to check for whether it is in the cube
88
+
89
+ Returns:
90
+ (N,) array: boolean numpy array specifying whether each point lies in the cube.
91
+ """
92
+ return ((-size / 2.0 < particle_positions) & (particle_positions < size / 2.0)).sum(dim=-1) == 3
93
+
94
+
95
+ def check_points_in_cone(size, particle_positions):
96
+ """
97
+ Checks which points are within a cone with specified size @size.
98
+
99
+ NOTE: Assumes the cone and positions are
100
+ expressed in the same coordinate frame such that the cone's height is aligned with the z-axis
101
+
102
+ Args:
103
+ size (2-array): (radius, height) dimensions of the cone, specified in its local frame
104
+ particle_positions ((N, 3) array): positions to check for whether it is in the cone
105
+
106
+ Returns:
107
+ (N,) array: boolean numpy array specifying whether each point lies in the cone.
108
+ """
109
+ radius, height = size
110
+ in_height = (-height / 2.0 < particle_positions[:, -1]) & (particle_positions[:, -1] < height / 2.0)
111
+ in_radius = th.norm(particle_positions[:, :-1], dim=-1) < (
112
+ radius * (1 - (particle_positions[:, -1] + height / 2.0) / height)
113
+ )
114
+ return in_height & in_radius
115
+
116
+
117
+ def check_points_in_cylinder(size, particle_positions):
118
+ """
119
+ Checks which points are within a cylinder with specified size @size.
120
+
121
+ NOTE: Assumes the cylinder and positions are
122
+ expressed in the same coordinate frame such that the cylinder's height is aligned with the z-axis
123
+
124
+ Args:
125
+ size (2-array): (radius, height) dimensions of the cylinder, specified in its local frame
126
+ particle_positions ((N, 3) array): positions to check for whether it is in the cylinder
127
+
128
+ Returns:
129
+ (N,) array: boolean numpy array specifying whether each point lies in the cylinder.
130
+ """
131
+ radius, height = size
132
+ in_height = (-height / 2.0 < particle_positions[:, -1]) & (particle_positions[:, -1] < height / 2.0)
133
+ in_radius = th.norm(particle_positions[:, :-1], dim=-1) < radius
134
+ return in_height & in_radius
135
+
136
+
137
+ def check_points_in_sphere(size, particle_positions):
138
+ """
139
+ Checks which points are within a sphere with specified size @size.
140
+
141
+ NOTE: Assumes the sphere and positions are expressed in the same coordinate frame
142
+
143
+ Args:
144
+ size (float): radius dimensions of the sphere
145
+ particle_positions ((N, 3) array): positions to check for whether it is in the sphere
146
+
147
+ Returns:
148
+ (N,) array: boolean numpy array specifying whether each point lies in the sphere
149
+ """
150
+ return th.norm(particle_positions, dim=-1) < size
151
+
152
+
153
+ def check_points_in_convex_hull_mesh(mesh_face_centroids, mesh_face_normals, particle_positions):
154
+ """
155
+ Checks which points are within a sphere with specified size @size.
156
+
157
+ NOTE: Assumes the mesh and positions are expressed in the same coordinate frame
158
+
159
+ Args:
160
+ mesh_face_centroids (D, 3): (x,y,z) location of the centroid of each mesh face, expressed in its local frame
161
+ mesh_face_normals (D, 3): (x,y,z) normalized direction vector of each mesh face, expressed in its local frame
162
+ particle_positions ((N, 3) array): positions to check for whether it is in the mesh
163
+
164
+ Returns:
165
+ (N,) array: boolean numpy array specifying whether each point lies in the mesh
166
+ """
167
+ # For every mesh point / normal and particle position pair, we check whether it is "inside" (i.e.: the point lies
168
+ # BEHIND the normal plane -- this is easily done by taking the dot product with the vector from the point to the
169
+ # particle position with the normal, and validating that the value is < 0)
170
+ D, _ = mesh_face_centroids.shape
171
+ N, _ = particle_positions.shape
172
+ mesh_points = th.tile(mesh_face_centroids.reshape(1, D, 3), (N, 1, 1))
173
+ mesh_normals = th.tile(mesh_face_normals.reshape(1, D, 3), (N, 1, 1))
174
+ particle_positions = th.tile(particle_positions.reshape(N, 1, 3), (1, D, 1))
175
+ # All arrays are now (N, D, 3) shape -- efficient for batching
176
+ in_range = ((particle_positions - mesh_points) * mesh_normals).sum(dim=-1) < 0 # shape (N, D)
177
+ # All D normals must be satisfied for a single point to be considered inside the hull
178
+ in_range = in_range.sum(dim=-1) == D
179
+ return in_range
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/git_utils.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import bddl
4
+ import git
5
+
6
+ import omnigibson as og
7
+
8
+
9
+ def git_info(directory):
10
+ repo = git.Repo(directory)
11
+ try:
12
+ branch_name = repo.active_branch.name
13
+ except TypeError:
14
+ branch_name = "[DETACHED]"
15
+ return {
16
+ "directory": str(directory),
17
+ "code_diff": repo.git.diff(None),
18
+ "code_diff_staged": repo.git.diff("--staged"),
19
+ "commit_hash": repo.head.commit.hexsha,
20
+ "branch_name": branch_name,
21
+ }
22
+
23
+
24
+ def project_git_info():
25
+ return {
26
+ "OmniGibson": git_info(Path(og.root_path).parent),
27
+ "bddl": git_info(Path(bddl.__file__).parent.parent),
28
+ }
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/grasping_planning_utils.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ import torch as th
5
+
6
+ import omnigibson.lazy as lazy
7
+ import omnigibson.utils.transform_utils as T
8
+ from omnigibson.macros import create_module_macros
9
+ from omnigibson.object_states.open_state import _get_relevant_joints
10
+ from omnigibson.utils.constants import JointType
11
+
12
+ m = create_module_macros(module_path=__file__)
13
+
14
+ m.REVOLUTE_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS = (0.4, 0.6)
15
+ m.PRISMATIC_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS = (0.2, 0.8)
16
+ m.ROTATION_ARC_SEGMENT_LENGTHS = 0.05
17
+ m.OPENNESS_THRESHOLD_TO_OPEN = 0.8
18
+ m.OPENNESS_THRESHOLD_TO_CLOSE = 0.05
19
+
20
+
21
+ def get_grasp_poses_for_object_sticky(target_obj):
22
+ """
23
+ Obtain a grasp pose for an object from top down, to be used with sticky grasping.
24
+ The grasp pose should be in the world frame.
25
+
26
+ Args:
27
+ target_obj (StatefulObject): Object to get a grasp pose for
28
+
29
+ Returns:
30
+ list: List of grasp poses.
31
+ """
32
+
33
+ aabb_min_world, aabb_max_world = target_obj.aabb
34
+
35
+ bbox_center_world = (aabb_min_world + aabb_max_world) / 2
36
+ bbox_extent_world = aabb_max_world - aabb_min_world
37
+
38
+ grasp_center_pos = bbox_center_world + th.tensor([0, 0, bbox_extent_world[2] / 2])
39
+ towards_object_in_world_frame = bbox_center_world - grasp_center_pos
40
+ towards_object_in_world_frame /= th.norm(towards_object_in_world_frame)
41
+
42
+ # Identity quaternion for top-down grasping (x-forward, y-right, z-down)
43
+ grasp_quat = T.euler2quat(th.tensor([0, 0, 0], dtype=th.float32))
44
+
45
+ grasp_pose = (grasp_center_pos, grasp_quat)
46
+ grasp_poses = [grasp_pose]
47
+
48
+ return grasp_poses
49
+
50
+
51
+ def get_grasp_poses_for_object_sticky_from_arbitrary_direction(target_obj):
52
+ """
53
+ Obtain a grasp pose for an object from an arbitrary direction to be used with sticky grasping.
54
+
55
+ Args:
56
+ target_obj (StatefulObject): Object to get a grasp pose for
57
+
58
+ Returns:
59
+ list: List of grasp candidates, where each grasp candidate is a tuple containing the grasp pose and the approach direction.
60
+ """
61
+ bbox_center_in_world, bbox_quat_in_world, bbox_extent_in_base_frame, _ = target_obj.get_base_aligned_bbox(
62
+ visual=False
63
+ )
64
+
65
+ # Pick an axis and a direction.
66
+ approach_axis = random.choice([0, 1, 2])
67
+ approach_direction = random.choice([-1, 1]) if approach_axis != 2 else 1
68
+ constant_dimension_in_base_frame = approach_direction * bbox_extent_in_base_frame * th.eye(3)[approach_axis]
69
+ randomizable_dimensions_in_base_frame = bbox_extent_in_base_frame - th.abs(constant_dimension_in_base_frame)
70
+ dim_lo, dim_hi = th.tensor([-1, -1, 0]), th.tensor([1, 1, 1])
71
+ random_dimensions_in_base_frame = (dim_hi - dim_lo) * th.rand(
72
+ dim_lo.size()
73
+ ) + dim_lo # note that we don't allow going below center
74
+ grasp_center_in_base_frame = (
75
+ random_dimensions_in_base_frame * randomizable_dimensions_in_base_frame + constant_dimension_in_base_frame
76
+ )
77
+
78
+ grasp_center_pos = T.mat2pose(
79
+ T.pose2mat((bbox_center_in_world, bbox_quat_in_world)) # base frame to world frame
80
+ @ T.pose2mat((grasp_center_in_base_frame, [0, 0, 0, 1])) # grasp pose in base frame
81
+ )[0] + th.tensor([0, 0, 0.02])
82
+ towards_object_in_world_frame = bbox_center_in_world - grasp_center_pos
83
+ towards_object_in_world_frame /= th.norm(towards_object_in_world_frame)
84
+
85
+ # For the grasp, we want the X+ direction to be the direction of the object's surface.
86
+ # The other two directions can be randomized.
87
+ rand_vec = th.rand(3)
88
+ rand_vec /= th.norm(rand_vec)
89
+ grasp_x = towards_object_in_world_frame
90
+ grasp_y = th.linalg.cross(rand_vec, grasp_x)
91
+ grasp_y /= th.norm(grasp_y)
92
+ grasp_z = th.linalg.cross(grasp_x, grasp_y)
93
+ grasp_z /= th.norm(grasp_z)
94
+ grasp_mat = th.tensor([grasp_x, grasp_y, grasp_z]).T
95
+ grasp_quat = T.mat2quat(grasp_mat)
96
+
97
+ grasp_pose = (grasp_center_pos, grasp_quat)
98
+ grasp_candidate = [(grasp_pose, towards_object_in_world_frame)]
99
+
100
+ return grasp_candidate
101
+
102
+
103
+ def get_grasp_position_for_open(robot, target_obj, should_open, relevant_joint=None, num_waypoints="default"):
104
+ """
105
+ Computes the grasp position for opening or closing a joint.
106
+
107
+ Args:
108
+ robot (BaseRobot): the robot object
109
+ target_obj (USDObject): the object to open/close a joint of
110
+ should_open (bool): a boolean indicating whether we are opening or closing
111
+ relevant_joint (Joint or None): the joint to open/close if we want to do a particular one in advance
112
+ num_waypoints (int or str): the number of waypoints to interpolate between the start and end poses (default is "default")
113
+
114
+ Returns:
115
+ None (if no grasp was found), or Tuple, containing:
116
+ relevant_joint: the joint that is being targeted for open/close by the returned grasp
117
+ offset_grasp_pose_in_world_frame: the grasp pose in the world frame
118
+ waypoints: the interpolated waypoints between the start and end poses
119
+ approach_direction_in_world_frame: the approach direction in the world frame
120
+ grasp_required: a boolean indicating whether a grasp is required for the opening/closing based on which side of the joint we are
121
+ required_pos_change: the required change in position of the joint to open/close
122
+ """
123
+ # Pick a moving link of the object.
124
+ relevant_joints = [relevant_joint] if relevant_joint is not None else _get_relevant_joints(target_obj)[1]
125
+ if len(relevant_joints) == 0:
126
+ raise ValueError("Cannot open/close object without relevant joints.")
127
+
128
+ # Make sure what we got is an appropriately open/close joint.
129
+ relevant_joints = relevant_joints[th.randperm(relevant_joints.size(0))]
130
+ selected_joint = None
131
+ for joint in relevant_joints:
132
+ current_position = joint.get_state()[0][0]
133
+ joint_range = joint.upper_limit - joint.lower_limit
134
+ openness_fraction = (current_position - joint.lower_limit) / joint_range
135
+ if (should_open and openness_fraction < m.OPENNESS_FRACTION_TO_OPEN) or (
136
+ not should_open and openness_fraction > m.OPENNESS_THRESHOLD_TO_CLOSE
137
+ ):
138
+ selected_joint = joint
139
+ break
140
+
141
+ if selected_joint is None:
142
+ return None
143
+
144
+ if selected_joint.joint_type == JointType.JOINT_REVOLUTE:
145
+ return (selected_joint,) + grasp_position_for_open_on_revolute_joint(
146
+ robot, target_obj, selected_joint, should_open, num_waypoints=num_waypoints
147
+ )
148
+ elif selected_joint.joint_type == JointType.JOINT_PRISMATIC:
149
+ return (selected_joint,) + grasp_position_for_open_on_prismatic_joint(
150
+ robot, target_obj, selected_joint, should_open, num_waypoints=num_waypoints
151
+ )
152
+ else:
153
+ raise ValueError("Unknown joint type encountered while generating joint position.")
154
+
155
+
156
+ def grasp_position_for_open_on_prismatic_joint(robot, target_obj, relevant_joint, should_open, num_waypoints="default"):
157
+ """
158
+ Computes the grasp position for opening or closing a prismatic joint.
159
+
160
+ Args:
161
+ robot (BaseRobot): the robot object
162
+ target_obj (USDObject): the object to open
163
+ relevant_joint (Joint): the prismatic joint to open
164
+ should_open (bool): a boolean indicating whether we are opening or closing
165
+ num_waypoints (int or str): the number of waypoints to interpolate between the start and end poses (default is "default")
166
+
167
+ Returns:
168
+ Tuple, containing:
169
+ offset_grasp_pose_in_world_frame: the grasp pose in the world frame
170
+ waypoints: the interpolated waypoints between the start and end poses
171
+ approach_direction_in_world_frame: the approach direction in the world frame
172
+ grasp_required: a boolean indicating whether a grasp is required for the opening/closing based on which side of the joint we are
173
+ required_pos_change: the required change in position of the joint to open/close
174
+ """
175
+ link_name = relevant_joint.body1.split("/")[-1]
176
+
177
+ # Get the bounding box of the child link.
178
+ (
179
+ bbox_center_in_world,
180
+ bbox_quat_in_world,
181
+ bbox_extent_in_link_frame,
182
+ _,
183
+ ) = target_obj.get_base_aligned_bbox(link_name=link_name, visual=False)
184
+
185
+ # Match the push axis to one of the bb axes.
186
+ joint_orientation = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array(
187
+ relevant_joint.get_attribute("physics:localRot0")
188
+ )[[1, 2, 3, 0]]
189
+ push_axis = T.quat_apply(joint_orientation, th.tensor([1, 0, 0], dtype=th.float32))
190
+ assert math.isclose(th.max(th.abs(push_axis)).item(), 1.0) # Make sure we're aligned with a bb axis.
191
+ push_axis_idx = th.argmax(th.abs(push_axis))
192
+ canonical_push_axis = th.eye(3)[push_axis_idx]
193
+
194
+ # TODO: Need to figure out how to get the correct push direction.
195
+ push_direction = th.sign(push_axis[push_axis_idx]) if should_open else -1 * th.sign(push_axis[push_axis_idx])
196
+ canonical_push_direction = canonical_push_axis * push_direction
197
+
198
+ # Pick the closer of the two faces along the push axis as our favorite.
199
+ points_along_push_axis = (
200
+ th.tensor([canonical_push_axis, -canonical_push_axis]) * bbox_extent_in_link_frame[push_axis_idx] / 2
201
+ )
202
+ (
203
+ push_axis_closer_side_idx,
204
+ center_of_selected_surface_along_push_axis,
205
+ _,
206
+ ) = _get_closest_point_to_point_in_world_frame(
207
+ points_along_push_axis, (bbox_center_in_world, bbox_quat_in_world), robot.get_position_orientation()[0]
208
+ )
209
+ push_axis_closer_side_sign = 1 if push_axis_closer_side_idx == 0 else -1
210
+
211
+ # Pick the other axes.
212
+ all_axes = list(set(range(3)) - {push_axis_idx})
213
+ x_axis_idx, y_axis_idx = tuple(sorted(all_axes))
214
+ canonical_x_axis = th.eye(3)[x_axis_idx]
215
+ canonical_y_axis = th.eye(3)[y_axis_idx]
216
+
217
+ # Find the correct side of the lateral axis & go some distance along that direction.
218
+ min_lateral_pos_wrt_surface_center = (canonical_x_axis + canonical_y_axis) * -bbox_extent_in_link_frame / 2
219
+ max_lateral_pos_wrt_surface_center = (canonical_x_axis + canonical_y_axis) * bbox_extent_in_link_frame / 2
220
+ diff_lateral_pos_wrt_surface_center = max_lateral_pos_wrt_surface_center - min_lateral_pos_wrt_surface_center
221
+ bound_lo, bound_hi = (
222
+ m.PRISMATIC_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[0] * diff_lateral_pos_wrt_surface_center,
223
+ m.PRISMATIC_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[1] * diff_lateral_pos_wrt_surface_center,
224
+ )
225
+ sampled_lateral_pos_wrt_min = th.rand(bound_lo.size()) * (bound_hi - bound_lo) + bound_lo
226
+ lateral_pos_wrt_surface_center = min_lateral_pos_wrt_surface_center + sampled_lateral_pos_wrt_min
227
+ grasp_position_in_bbox_frame = center_of_selected_surface_along_push_axis + lateral_pos_wrt_surface_center
228
+ grasp_quat_in_bbox_frame = T.quat_inverse(joint_orientation)
229
+ grasp_pose_in_world_frame = T.pose_transform(
230
+ bbox_center_in_world, bbox_quat_in_world, grasp_position_in_bbox_frame, grasp_quat_in_bbox_frame
231
+ )
232
+
233
+ # Now apply the grasp offset.
234
+ avg_finger_offset = th.mean(
235
+ th.tensor([length for length in robot.eef_to_fingertip_lengths[robot.default_arm].values()])
236
+ )
237
+ dist_from_grasp_pos = avg_finger_offset + 0.05
238
+ offset_grasp_pose_in_bbox_frame = (
239
+ grasp_position_in_bbox_frame + canonical_push_axis * push_axis_closer_side_sign * dist_from_grasp_pos,
240
+ grasp_quat_in_bbox_frame,
241
+ )
242
+ offset_grasp_pose_in_world_frame = T.pose_transform(
243
+ bbox_center_in_world, bbox_quat_in_world, *offset_grasp_pose_in_bbox_frame
244
+ )
245
+
246
+ # To compute the rotation position, we want to decide how far along the rotation axis we'll go.
247
+ target_joint_pos = relevant_joint.upper_limit if should_open else relevant_joint.lower_limit
248
+ current_joint_pos = relevant_joint.get_state()[0][0]
249
+
250
+ required_pos_change = target_joint_pos - current_joint_pos
251
+ push_vector_in_bbox_frame = canonical_push_direction * abs(required_pos_change)
252
+ target_hand_pos_in_bbox_frame = grasp_position_in_bbox_frame + push_vector_in_bbox_frame
253
+ target_hand_pose_in_world_frame = T.pose_transform(
254
+ bbox_center_in_world, bbox_quat_in_world, target_hand_pos_in_bbox_frame, grasp_quat_in_bbox_frame
255
+ )
256
+
257
+ # Compute the approach direction.
258
+ approach_direction_in_world_frame = T.quat_apply(
259
+ bbox_quat_in_world, canonical_push_axis * -push_axis_closer_side_sign
260
+ )
261
+
262
+ # Decide whether a grasp is required. If approach direction and displacement are similar, no need to grasp.
263
+ grasp_required = th.dot(push_vector_in_bbox_frame, canonical_push_axis * -push_axis_closer_side_sign) < 0
264
+ # TODO: Need to find a better of getting the predicted position of eef for start point of interpolating waypoints. Maybe
265
+ # break this into another function that called after the grasp is executed, so we know the eef position?
266
+ waypoint_start_offset = (
267
+ -0.05 * approach_direction_in_world_frame if should_open else 0.05 * approach_direction_in_world_frame
268
+ )
269
+ avg_finger_offset = th.mean(
270
+ th.tensor([length for length in robot.eef_to_fingertip_lengths[robot.default_arm].values()])
271
+ )
272
+ waypoint_start_pose = (
273
+ grasp_pose_in_world_frame[0]
274
+ + -1 * approach_direction_in_world_frame * (avg_finger_offset + waypoint_start_offset),
275
+ grasp_pose_in_world_frame[1],
276
+ )
277
+ waypoint_end_pose = (
278
+ target_hand_pose_in_world_frame[0] + -1 * approach_direction_in_world_frame * avg_finger_offset,
279
+ target_hand_pose_in_world_frame[1],
280
+ )
281
+ waypoints = interpolate_waypoints(waypoint_start_pose, waypoint_end_pose, num_waypoints=num_waypoints)
282
+
283
+ return (
284
+ offset_grasp_pose_in_world_frame,
285
+ waypoints,
286
+ approach_direction_in_world_frame,
287
+ relevant_joint,
288
+ grasp_required,
289
+ required_pos_change,
290
+ )
291
+
292
+
293
+ def interpolate_waypoints(start_pose, end_pose, num_waypoints="default"):
294
+ """
295
+ Interpolates a series of waypoints between a start and end pose.
296
+
297
+ Args:
298
+ start_pose (tuple): A tuple containing the starting position and orientation as a quaternion.
299
+ end_pose (tuple): A tuple containing the ending position and orientation as a quaternion.
300
+ 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.
301
+
302
+ Returns:
303
+ list: A list of tuples representing the interpolated waypoints, where each tuple contains a position and orientation as a quaternion.
304
+ """
305
+ start_pos, start_orn = start_pose
306
+ travel_distance = th.norm(end_pose[0] - start_pos)
307
+
308
+ if num_waypoints == "default":
309
+ num_waypoints = th.max([2, int(travel_distance / 0.01) + 1]).item()
310
+ pos_waypoints = th.linspace(start_pos, end_pose[0], num_waypoints)
311
+
312
+ # Also interpolate the rotations
313
+ fracs = th.linspace(0, 1, num_waypoints)
314
+ orn_waypoints = T.quat_slerp(start_orn.unsqueeze(0), end_pose[1].unsqueeze(0), fracs.unsqueeze(1))
315
+ quat_waypoints = [x.as_quat() for x in orn_waypoints]
316
+ return [waypoint for waypoint in zip(pos_waypoints, quat_waypoints)]
317
+
318
+
319
+ def grasp_position_for_open_on_revolute_joint(robot, target_obj, relevant_joint, should_open):
320
+ """
321
+ Computes the grasp position for opening or closing a revolute joint.
322
+
323
+ Args:
324
+ robot (BaseRobot): the robot object
325
+ target_obj (USDObject): the object to open
326
+ relevant_joint (Joint): the revolute joint to open
327
+ should_open (bool): a boolean indicating whether we are opening or closing
328
+
329
+ Returns:
330
+ Tuple, containing:
331
+ offset_grasp_pose_in_world_frame: the grasp pose in the world frame
332
+ waypoints: the interpolated waypoints between the start and end poses
333
+ approach_direction_in_world_frame: the approach direction in the world frame
334
+ grasp_required: a boolean indicating whether a grasp is required for the opening/closing based on which side of the joint we are
335
+ required_pos_change: the required change in position of the joint to open/close
336
+ """
337
+ link_name = relevant_joint.body1.split("/")[-1]
338
+ link = target_obj.links[link_name]
339
+
340
+ # Get the bounding box of the child link.
341
+ (bbox_center_in_world, bbox_quat_in_world, _, bbox_center_in_obj_frame) = target_obj.get_base_aligned_bbox(
342
+ link_name=link_name, visual=False
343
+ )
344
+
345
+ bbox_quat_in_world = link.get_position_orientation()[1]
346
+ bbox_extent_in_link_frame = th.tensor(
347
+ target_obj.native_link_bboxes[link_name]["collision"]["axis_aligned"]["extent"]
348
+ )
349
+ bbox_wrt_origin = T.relative_pose_transform(
350
+ bbox_center_in_world, bbox_quat_in_world, *link.get_position_orientation()
351
+ )
352
+ origin_wrt_bbox = T.invert_pose_transform(*bbox_wrt_origin)
353
+
354
+ joint_orientation = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array(
355
+ relevant_joint.get_attribute("physics:localRot0")
356
+ )[[1, 2, 3, 0]]
357
+ joint_axis = T.quat_apply(joint_orientation, th.tensor([1, 0, 0], dtype=th.float32))
358
+ joint_axis /= th.norm(joint_axis)
359
+ origin_towards_bbox = th.tensor(bbox_wrt_origin[0])
360
+ open_direction = th.linalg.cross(joint_axis, origin_towards_bbox)
361
+ open_direction /= th.norm(open_direction)
362
+ lateral_axis = th.linalg.cross(open_direction, joint_axis)
363
+
364
+ # Match the axes to the canonical axes of the link bb.
365
+ lateral_axis_idx = th.argmax(th.abs(lateral_axis))
366
+ open_axis_idx = th.argmax(th.abs(open_direction))
367
+ joint_axis_idx = th.argmax(th.abs(joint_axis))
368
+ assert lateral_axis_idx != open_axis_idx
369
+ assert lateral_axis_idx != joint_axis_idx
370
+ assert open_axis_idx != joint_axis_idx
371
+
372
+ canonical_open_direction = th.eye(3)[open_axis_idx]
373
+ points_along_open_axis = (
374
+ th.tensor([canonical_open_direction, -canonical_open_direction]) * bbox_extent_in_link_frame[open_axis_idx] / 2
375
+ )
376
+ current_yaw = relevant_joint.get_state()[0][0]
377
+ closed_yaw = relevant_joint.lower_limit
378
+ points_along_open_axis_after_rotation = [
379
+ _rotate_point_around_axis((point, [0, 0, 0, 1]), bbox_wrt_origin, joint_axis, closed_yaw - current_yaw)[0]
380
+ for point in points_along_open_axis
381
+ ]
382
+ open_axis_closer_side_idx, _, _ = _get_closest_point_to_point_in_world_frame(
383
+ points_along_open_axis_after_rotation,
384
+ (bbox_center_in_world, bbox_quat_in_world),
385
+ robot.get_position_orientation()[0],
386
+ )
387
+ open_axis_closer_side_sign = 1 if open_axis_closer_side_idx == 0 else -1
388
+ center_of_selected_surface_along_push_axis = points_along_open_axis[open_axis_closer_side_idx]
389
+
390
+ # Find the correct side of the lateral axis & go some distance along that direction.
391
+ canonical_joint_axis = th.eye(3)[joint_axis_idx]
392
+ lateral_away_from_origin = th.eye(3)[lateral_axis_idx] * th.sign(origin_towards_bbox[lateral_axis_idx])
393
+ min_lateral_pos_wrt_surface_center = (
394
+ lateral_away_from_origin * -th.tensor(origin_wrt_bbox[0])
395
+ - canonical_joint_axis * bbox_extent_in_link_frame[lateral_axis_idx] / 2
396
+ )
397
+ max_lateral_pos_wrt_surface_center = (
398
+ lateral_away_from_origin * bbox_extent_in_link_frame[lateral_axis_idx] / 2
399
+ + canonical_joint_axis * bbox_extent_in_link_frame[lateral_axis_idx] / 2
400
+ )
401
+ diff_lateral_pos_wrt_surface_center = max_lateral_pos_wrt_surface_center - min_lateral_pos_wrt_surface_center
402
+ bound_lo, bound_hi = (
403
+ m.REVOLUTE_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[0] * diff_lateral_pos_wrt_surface_center,
404
+ m.REVOLUTE_JOINT_FRACTION_ACROSS_SURFACE_AXIS_BOUNDS[1] * diff_lateral_pos_wrt_surface_center,
405
+ )
406
+ sampled_lateral_pos_wrt_min = th.rand(bound_lo.size()) * (bound_hi - bound_lo) + bound_lo
407
+ lateral_pos_wrt_surface_center = min_lateral_pos_wrt_surface_center + sampled_lateral_pos_wrt_min
408
+ grasp_position = center_of_selected_surface_along_push_axis + lateral_pos_wrt_surface_center
409
+ # Get the appropriate rotation
410
+
411
+ # grasp_quat_in_bbox_frame = get_quaternion_between_vectors([1, 0, 0], canonical_open_direction * open_axis_closer_side_sign * -1)
412
+ grasp_quat_in_bbox_frame = _get_orientation_facing_vector_with_random_yaw(
413
+ canonical_open_direction * open_axis_closer_side_sign * -1
414
+ )
415
+
416
+ # Now apply the grasp offset.
417
+ avg_finger_offset = th.mean(
418
+ th.tensor([length for length in robot.eef_to_fingertip_lengths[robot.default_arm].values()])
419
+ )
420
+ dist_from_grasp_pos = avg_finger_offset + 0.05
421
+ offset_in_bbox_frame = canonical_open_direction * open_axis_closer_side_sign * dist_from_grasp_pos
422
+ offset_grasp_pose_in_bbox_frame = (grasp_position + offset_in_bbox_frame, grasp_quat_in_bbox_frame)
423
+ offset_grasp_pose_in_world_frame = T.pose_transform(
424
+ bbox_center_in_world, bbox_quat_in_world, *offset_grasp_pose_in_bbox_frame
425
+ )
426
+
427
+ # To compute the rotation position, we want to decide how far along the rotation axis we'll go.
428
+ desired_yaw = relevant_joint.upper_limit if should_open else relevant_joint.lower_limit
429
+ required_yaw_change = desired_yaw - current_yaw
430
+
431
+ # Now we'll rotate the grasp position around the origin by the desired rotation.
432
+ # Note that we use the non-offset position here since the joint can't be pulled all the way to the offset.
433
+ grasp_pose_in_bbox_frame = grasp_position, grasp_quat_in_bbox_frame
434
+ grasp_pose_in_origin_frame = T.pose_transform(*bbox_wrt_origin, *grasp_pose_in_bbox_frame)
435
+
436
+ # Get the arc length and divide it up to 10cm segments
437
+ arc_length = abs(required_yaw_change) * th.norm(grasp_pose_in_origin_frame[0])
438
+ turn_steps = int(math.ceil(arc_length / m.ROTATION_ARC_SEGMENT_LENGTHS))
439
+ targets = []
440
+
441
+ for i in range(turn_steps):
442
+ partial_yaw_change = (i + 1) / turn_steps * required_yaw_change
443
+ rotated_grasp_pose_in_bbox_frame = _rotate_point_around_axis(
444
+ (offset_grasp_pose_in_bbox_frame[0], offset_grasp_pose_in_bbox_frame[1]),
445
+ bbox_wrt_origin,
446
+ joint_axis,
447
+ partial_yaw_change,
448
+ )
449
+ rotated_grasp_pose_in_world_frame = T.pose_transform(
450
+ bbox_center_in_world, bbox_quat_in_world, *rotated_grasp_pose_in_bbox_frame
451
+ )
452
+ targets.append(rotated_grasp_pose_in_world_frame)
453
+
454
+ # Compute the approach direction.
455
+ approach_direction_in_world_frame = T.quat_apply(
456
+ bbox_quat_in_world, canonical_open_direction * -open_axis_closer_side_sign
457
+ )
458
+
459
+ # Decide whether a grasp is required. If approach direction and displacement are similar, no need to grasp.
460
+ movement_in_world_frame = th.tensor(targets[-1][0]) - th.tensor(offset_grasp_pose_in_world_frame[0])
461
+ grasp_required = th.dot(movement_in_world_frame, approach_direction_in_world_frame) < 0
462
+
463
+ return (
464
+ offset_grasp_pose_in_world_frame,
465
+ targets,
466
+ approach_direction_in_world_frame,
467
+ grasp_required,
468
+ required_yaw_change,
469
+ )
470
+
471
+
472
+ def _get_orientation_facing_vector_with_random_yaw(vector):
473
+ """
474
+ Get a quaternion that orients the x-axis of the object to face the given vector and the y and z
475
+ axes to be random.
476
+
477
+ Args:
478
+ vector (th.tensor): The vector to face.
479
+
480
+ Returns:
481
+ th.tensor: A quaternion representing the orientation.
482
+ """
483
+ forward = vector / th.norm(vector)
484
+ rand_vec = th.rand(3)
485
+ rand_vec /= th.norm(3)
486
+ side = th.linalg.cross(rand_vec, forward)
487
+ side /= th.norm(3)
488
+ up = th.linalg.cross(forward, side)
489
+ # assert math.isclose(th.norm(up).item(), 1, abs_tol=1e-3)
490
+ rotmat = th.tensor([forward, side, up]).T
491
+ return T.mat2quat(rotmat)
492
+
493
+
494
+ def _rotate_point_around_axis(point_wrt_arbitrary_frame, arbitrary_frame_wrt_origin, joint_axis, yaw_change):
495
+ """
496
+ Rotate a point around an axis, given the point in an arbitrary frame, the arbitrary frame's pose in the origin frame,
497
+ the axis to rotate around, and the amount to rotate by. This is a utility for rotating the grasp position around the
498
+ joint axis.
499
+
500
+ Args:
501
+ point_wrt_arbitrary_frame (tuple): The point in the arbitrary frame.
502
+ arbitrary_frame_wrt_origin (tuple): The pose of the arbitrary frame in the origin frame.
503
+ joint_axis (th.tensor): The axis to rotate around.
504
+ yaw_change (float): The amount to rotate by.
505
+
506
+ Returns:
507
+ tuple: The rotated point in the arbitrary frame.
508
+ """
509
+ rotation = T.euler2quat(joint_axis * yaw_change)
510
+ origin_wrt_arbitrary_frame = T.invert_pose_transform(*arbitrary_frame_wrt_origin)
511
+
512
+ pose_in_origin_frame = T.pose_transform(*arbitrary_frame_wrt_origin, *point_wrt_arbitrary_frame)
513
+ rotated_pose_in_origin_frame = T.pose_transform([0, 0, 0], rotation, *pose_in_origin_frame)
514
+ rotated_pose_in_arbitrary_frame = T.pose_transform(*origin_wrt_arbitrary_frame, *rotated_pose_in_origin_frame)
515
+ return rotated_pose_in_arbitrary_frame
516
+
517
+
518
+ def _get_closest_point_to_point_in_world_frame(
519
+ vectors_in_arbitrary_frame, arbitrary_frame_to_world_frame, point_in_world
520
+ ):
521
+ """
522
+ Given a set of vectors in an arbitrary frame, find the closest vector to a point in world frame.
523
+ Useful for picking between two sides of a joint for grasping.
524
+
525
+ Args:
526
+ vectors_in_arbitrary_frame (list): A list of vectors in the arbitrary frame.
527
+ arbitrary_frame_to_world_frame (tuple): The pose of the arbitrary frame in the world frame.
528
+ point_in_world (tuple): The point in the world frame.
529
+
530
+ Returns:
531
+ tuple: The index of the closest vector, the closest vector in the arbitrary frame, and the closest vector in the world frame.
532
+ """
533
+ vectors_in_world = th.tensor(
534
+ [
535
+ T.pose_transform(*arbitrary_frame_to_world_frame, vector, [0, 0, 0, 1])[0]
536
+ for vector in vectors_in_arbitrary_frame
537
+ ]
538
+ )
539
+
540
+ vector_distances_to_point = th.norm(vectors_in_world - th.tensor(point_in_world)[None, :], dim=1)
541
+ closer_option_idx = th.argmin(vector_distances_to_point)
542
+ vector_in_arbitrary_frame = vectors_in_arbitrary_frame[closer_option_idx]
543
+ vector_in_world_frame = vectors_in_world[closer_option_idx]
544
+
545
+ return closer_option_idx, vector_in_arbitrary_frame, vector_in_world_frame
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/gym_utils.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABCMeta, abstractmethod
2
+ from collections.abc import Iterable
3
+
4
+ import gymnasium as gym
5
+ import torch as th
6
+
7
+ from omnigibson.utils.ui_utils import create_module_logger
8
+
9
+ # Create module logger
10
+ log = create_module_logger(module_name=__name__)
11
+
12
+
13
+ def recursively_generate_flat_dict(dic, prefix=None):
14
+ """
15
+ Helper function to recursively iterate through dictionary / gym.spaces.Dict @dic and flatten any nested elements,
16
+ such that the result is a flat dictionary mapping keys to values
17
+
18
+ Args:
19
+ dic (dict or gym.spaces.Dict): (Potentially nested) dictionary to convert into a flattened dictionary
20
+ prefix (None or str): Prefix to append to the beginning of all strings in the flattened dictionary. None results
21
+ in no prefix being applied
22
+
23
+ Returns:
24
+ dict: Flattened version of @dic
25
+ """
26
+ out = dict()
27
+ prefix = "" if prefix is None else f"{prefix}::"
28
+ for k, v in dic.items():
29
+ if isinstance(v, gym.spaces.Dict) or isinstance(v, dict):
30
+ out.update(recursively_generate_flat_dict(dic=v, prefix=f"{prefix}{k}"))
31
+ elif isinstance(v, gym.spaces.Tuple) or isinstance(v, tuple):
32
+ for i, vv in enumerate(v):
33
+ # Assume no dicts are nested within tuples
34
+ out[f"{prefix}{k}::{i}"] = vv
35
+ else:
36
+ # Add to out dict
37
+ out[f"{prefix}{k}"] = v
38
+
39
+ return out
40
+
41
+
42
+ def recursively_generate_compatible_dict(dic):
43
+ """
44
+ Helper function to recursively iterate through dictionary and cast values to necessary types to be compatible with
45
+ Gym spaces -- in particular, the Sequence and Tuple types for th.tensor values in @dic
46
+
47
+ Args:
48
+ dic (dict or gym.spaces.Dict): (Potentially nested) dictionary to convert into a flattened dictionary
49
+
50
+ Returns:
51
+ dict: Gym-compatible version of @dic
52
+ """
53
+ out = dict()
54
+ for k, v in dic.items():
55
+ if isinstance(v, dict):
56
+ out[k] = recursively_generate_compatible_dict(dic=v)
57
+ elif isinstance(v, th.Tensor) and v.dim() > 1:
58
+ # Map to list of tuples
59
+ out[k] = tuple(tuple(row.tolist()) for row in v)
60
+ elif isinstance(v, Iterable):
61
+ # bounding box modalities give a list of tuples
62
+ out[k] = tuple(v)
63
+ else:
64
+ # Preserve the key-value pair
65
+ out[k] = v
66
+
67
+ return out
68
+
69
+
70
+ class GymObservable(metaclass=ABCMeta):
71
+ """
72
+ Simple class interface for observable objects. These objects should implement a way to grab observations,
73
+ (get_obs()), and should define an observation space that is created when load_observation_space() is called
74
+
75
+ Args:
76
+ **kwargs (dict): does nothing, used to sink any extraneous arguments during initialization
77
+ """
78
+
79
+ def __init__(self, *args, **kwargs):
80
+ # Initialize variables that we will fill in later
81
+ self.observation_space = None
82
+
83
+ # Call any super methods
84
+ super().__init__(*args, **kwargs)
85
+
86
+ @abstractmethod
87
+ def get_obs(self, **kwargs):
88
+ """
89
+ Get observations for the object. Note that the shape / nested structure should match that
90
+ of @self.observation_space!
91
+
92
+ Args:
93
+ kwargs (dict): Any keyword args necessary for grabbing observations
94
+
95
+ Returns:
96
+ 2-tuple:
97
+ dict: Keyword-mapped observations mapping observation names to nested observations
98
+ dict: Additional information about the observations
99
+ """
100
+ raise NotImplementedError()
101
+
102
+ @staticmethod
103
+ def _build_obs_box_space(shape, low, high, dtype=th.float32):
104
+ """
105
+ Helper function that builds individual observation box spaces.
106
+
107
+ Args:
108
+ shape (n-array): Shape of the space
109
+ low (float): Lower bound of the space
110
+ high (float): Upper bound of the space
111
+
112
+ Returns:
113
+ gym.spaces.Box: Generated gym box observation space
114
+ """
115
+ return gym.spaces.Box(low=low, high=high, shape=shape, dtype=dtype)
116
+
117
+ @abstractmethod
118
+ def _load_observation_space(self):
119
+ """
120
+ Create the observation space for this object. Should be implemented by subclass
121
+
122
+ Returns:
123
+ dict: Keyword-mapped observation space for this object mapping observation name to observation space
124
+ """
125
+ raise NotImplementedError()
126
+
127
+ def load_observation_space(self):
128
+ """
129
+ Load the observation space internally, and also return this value
130
+
131
+ Returns:
132
+ gym.spaces.Dict: Loaded observation space for this object
133
+ """
134
+ # Load the observation space and convert it into a gym-compatible dictionary
135
+ self.observation_space = gym.spaces.Dict(self._load_observation_space())
136
+ log.debug(f"Loaded obs space dictionary for: {self.__class__.__name__}")
137
+
138
+ return self.observation_space
139
+
140
+
141
+ def maxdim(space):
142
+ """
143
+ Helper function to get the maximum dimension of a gym space
144
+
145
+ Args:
146
+ space (gym.spaces.Space): Gym space to get the maximum dimension of
147
+
148
+ Returns:
149
+ int: Maximum dimension of the gym space
150
+ """
151
+ if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple)):
152
+ return sum([maxdim(s) for s in space.spaces.values()])
153
+ elif isinstance(space, (gym.spaces.Box, gym.spaces.Discrete, gym.spaces.MultiDiscrete, gym.spaces.MultiBinary)):
154
+ return gym.spaces.utils.flatdim(space)
155
+ elif isinstance(space, (gym.spaces.Sequence, gym.spaces.Graph)):
156
+ return float("inf")
157
+ else:
158
+ raise ValueError(f"Unsupported gym space type: {type(space)}")
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/lazy_import_utils.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ from types import ModuleType
3
+
4
+
5
+ class LazyImporter(ModuleType):
6
+ """Replace a module's global namespace with me to support lazy imports of submodules and members."""
7
+
8
+ def __init__(self, module_name, module):
9
+ super().__init__("lazy_" + module_name)
10
+ self._module_path = module_name
11
+ self._module = module
12
+ self._not_module = set()
13
+ self._submodules = {}
14
+
15
+ def __getattr__(self, name: str):
16
+ # First, try the argument as a module name.
17
+ if name not in self._not_module:
18
+ submodule = self._get_module(name)
19
+ if submodule:
20
+ return submodule
21
+ else:
22
+ # Record module not found so that we don't keep looking.
23
+ self._not_module.add(name)
24
+
25
+ # If it's not a module name, try it as a member of this module.
26
+ try:
27
+ return getattr(self._module, name)
28
+ except:
29
+ raise AttributeError(f"module {self.__name__} has no attribute {name}") from None
30
+
31
+ def _get_module(self, module_name: str):
32
+ """Recursively create and return a LazyImporter for the given module name."""
33
+
34
+ # Get the fully qualified module name by prepending self._module_path
35
+ if self._module_path:
36
+ module_name = f"{self._module_path}.{module_name}"
37
+
38
+ if module_name in self._submodules:
39
+ return self._submodules[module_name]
40
+
41
+ try:
42
+ wrapper = LazyImporter(module_name, importlib.import_module(module_name))
43
+ self._submodules[module_name] = wrapper
44
+ return wrapper
45
+ except ModuleNotFoundError:
46
+ return None
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/motion_planning_utils.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import heapq
2
+ import math
3
+
4
+ import torch as th
5
+
6
+ import omnigibson as og
7
+ import omnigibson.lazy as lazy
8
+ import omnigibson.utils.transform_utils as T
9
+ from omnigibson.macros import create_module_macros
10
+ from omnigibson.utils.control_utils import IKSolver
11
+ from omnigibson.utils.geometry_utils import wrap_angle
12
+ from omnigibson.utils.ui_utils import create_module_logger
13
+ from omnigibson.utils.constants import GROUND_CATEGORIES
14
+ from omnigibson.utils.usd_utils import RigidContactAPI
15
+
16
+ # Create module logger
17
+ logger = create_module_logger(module_name=__name__)
18
+ m = create_module_macros(module_path=__file__)
19
+ m.ANGLE_DIFF = 0.3
20
+ m.DIST_DIFF = 0.1
21
+
22
+
23
+ def plan_base_motion(
24
+ robot,
25
+ end_conf,
26
+ context,
27
+ planning_time=15.0,
28
+ ):
29
+ """
30
+ Plans a base motion to a 2d pose
31
+
32
+ Args:
33
+ robot (omnigibson.object_states.Robot): Robot object to plan for
34
+ end_conf (Iterable): [x, y, yaw] 2d pose to plan to
35
+ context (PlanningContext): Context to plan in that includes the robot copy
36
+ planning_time (float): Time to plan for
37
+
38
+ Returns:
39
+ Array of arrays: Array of 2d poses that the robot should navigate to
40
+ """
41
+ from ompl import base as ob
42
+ from ompl import geometric as ompl_geo
43
+
44
+ class CustomMotionValidator(ob.MotionValidator):
45
+ def __init__(self, si, space):
46
+ super(CustomMotionValidator, self).__init__(si)
47
+ self.si = si
48
+ self.space = space
49
+
50
+ def checkMotion(self, s1, s2):
51
+ if not self.si.isValid(s2):
52
+ return False
53
+
54
+ start = th.tensor([s1.getX(), s1.getY(), s1.getYaw()])
55
+ goal = th.tensor([s2.getX(), s2.getY(), s2.getYaw()])
56
+ segment_theta = self.get_angle_between_poses(start, goal)
57
+
58
+ # Start rotation
59
+ if not self.is_valid_rotation(self.si, start, segment_theta):
60
+ return False
61
+
62
+ # Navigation
63
+ dist = th.norm(goal[:2] - start[:2])
64
+ num_points = math.ceil(dist / m.DIST_DIFF) + 1
65
+ nav_x = th.linspace(start[0], goal[0], num_points).tolist()
66
+ nav_y = th.linspace(start[1], goal[1], num_points).tolist()
67
+ for i in range(num_points):
68
+ state = create_state(self.si, nav_x[i], nav_y[i], segment_theta)
69
+ if not self.si.isValid(state()):
70
+ return False
71
+
72
+ # Goal rotation
73
+ if not self.is_valid_rotation(self.si, [goal[0], goal[1], segment_theta], goal[2]):
74
+ return False
75
+
76
+ return True
77
+
78
+ @staticmethod
79
+ def is_valid_rotation(si, start_conf, final_orientation):
80
+ diff = wrap_angle(final_orientation - start_conf[2])
81
+ direction = th.sign(diff)
82
+ diff = abs(diff)
83
+ num_points = math.ceil(diff / m.ANGLE_DIFF) + 1
84
+ nav_angle = th.linspace(0.0, diff, num_points) * direction
85
+ angles = nav_angle + start_conf[2]
86
+ for i in range(num_points):
87
+ state = create_state(si.getStateSpace(), start_conf[0], start_conf[1], angles[i])
88
+ if not si.isValid(state()):
89
+ return False
90
+ return True
91
+
92
+ @staticmethod
93
+ # Get angle between 2d robot poses
94
+ def get_angle_between_poses(p1, p2):
95
+ segment = []
96
+ segment.append(p2[0] - p1[0])
97
+ segment.append(p2[1] - p1[1])
98
+ segment = th.tensor(segment, dtype=th.float32)
99
+ return th.arctan2(segment[1], segment[0])
100
+
101
+ def create_state(space, x, y, yaw):
102
+ x = float(x)
103
+ y = float(y)
104
+ yaw = float(yaw)
105
+ state = ob.State(space)
106
+ state().setX(x)
107
+ state().setY(y)
108
+ state().setYaw(wrap_angle(yaw))
109
+ return state
110
+
111
+ def state_valid_fn(q, verbose=False):
112
+ """
113
+ returns if the input pose is in collision with any objects within the context
114
+ verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False
115
+ """
116
+
117
+ x = q.getX()
118
+ y = q.getY()
119
+ yaw = q.getYaw()
120
+ pose = (th.tensor([x, y, 0.0], dtype=th.float32), T.euler2quat(th.tensor([0, 0, yaw], dtype=th.float32)))
121
+ return not set_base_and_detect_collision(context, pose, verbose=verbose)
122
+
123
+ def remove_unnecessary_rotations(path):
124
+ """
125
+ 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
126
+ the position of the next pose in the path
127
+
128
+ Args:
129
+ path (Array of arrays): Array of 2d poses
130
+
131
+ Returns:
132
+ Array of numpy arrays: Array of 2d poses with unnecessary rotations removed
133
+ """
134
+ # Start at the same starting pose
135
+ new_path = [path[0]]
136
+
137
+ # Process every intermediate waypoint
138
+ for i in range(1, len(path) - 1):
139
+ # compute the yaw you'd be at when arriving into path[i] and departing from it
140
+ arriving_yaw = CustomMotionValidator.get_angle_between_poses(path[i - 1], path[i])
141
+ departing_yaw = CustomMotionValidator.get_angle_between_poses(path[i], path[i + 1])
142
+
143
+ # check if you are able to make that rotation directly.
144
+ arriving_state = (path[i][0], path[i][1], arriving_yaw)
145
+ if CustomMotionValidator.is_valid_rotation(si, arriving_state, departing_yaw):
146
+ # Then use the arriving yaw directly
147
+ new_path.append(arriving_state)
148
+ else:
149
+ # Otherwise, keep the waypoint
150
+ new_path.append(path[i])
151
+
152
+ # Don't forget to add back the same ending pose
153
+ new_path.append(path[-1])
154
+
155
+ return new_path
156
+
157
+ pos, orn = robot.get_position_orientation()
158
+ yaw = T.quat2euler(orn)[2]
159
+ start_conf = (pos[0], pos[1], yaw)
160
+
161
+ # create an SE(2) state space
162
+ space = ob.SE2StateSpace()
163
+
164
+ # set lower and upper bounds
165
+ bbox_vals = []
166
+ for floor in filter(lambda o: o.category == "floors", robot.scene.objects):
167
+ bbox_vals += floor.aabb[0][:2].tolist()
168
+ bbox_vals += floor.aabb[1][:2].tolist()
169
+ bounds = ob.RealVectorBounds(2)
170
+ bounds.setLow(min(bbox_vals))
171
+ bounds.setHigh(max(bbox_vals))
172
+ space.setBounds(bounds)
173
+
174
+ # create a simple setup object
175
+ ss = ompl_geo.SimpleSetup(space)
176
+ ss.setStateValidityChecker(ob.StateValidityCheckerFn(state_valid_fn))
177
+
178
+ si = ss.getSpaceInformation()
179
+ si.setMotionValidator(CustomMotionValidator(si, space))
180
+ # TODO: Try changing to RRTConnect in the future. Currently using RRT because movement is not direction invariant. Can change to RRTConnect
181
+ # possibly if hasSymmetricInterpolate is set to False for the state space. Doc here https://ompl.kavrakilab.org/classompl_1_1base_1_1StateSpace.html
182
+ planner = ompl_geo.RRT(si)
183
+ ss.setPlanner(planner)
184
+
185
+ start = create_state(space, start_conf[0], start_conf[1], start_conf[2])
186
+ goal = create_state(space, end_conf[0], end_conf[1], end_conf[2])
187
+
188
+ ss.setStartAndGoalStates(start, goal)
189
+ if not state_valid_fn(start(), verbose=True) or not state_valid_fn(goal(), verbose=True):
190
+ return
191
+
192
+ solved = ss.solve(planning_time)
193
+
194
+ if solved:
195
+ # try to shorten the path
196
+ ss.simplifySolution()
197
+ sol_path = ss.getSolutionPath()
198
+ return_path = []
199
+ for i in range(sol_path.getStateCount()):
200
+ x = sol_path.getState(i).getX()
201
+ y = sol_path.getState(i).getY()
202
+ yaw = sol_path.getState(i).getYaw()
203
+ return_path.append([x, y, yaw])
204
+ return remove_unnecessary_rotations(return_path)
205
+ return None
206
+
207
+
208
+ def plan_arm_motion(robot, end_conf, context, planning_time=15.0, torso_fixed=True):
209
+ """
210
+ Plans an arm motion to a final joint position
211
+
212
+ Args:
213
+ robot (BaseRobot): Robot object to plan for
214
+ end_conf (Iterable): Final joint position to plan to
215
+ context (PlanningContext): Context to plan in that includes the robot copy
216
+ planning_time (float): Time to plan for
217
+
218
+ Returns:
219
+ Array of arrays: Array of joint positions that the robot should navigate to
220
+ """
221
+ from ompl import base as ob
222
+ from ompl import geometric as ompl_geo
223
+
224
+ if torso_fixed:
225
+ joint_control_idx = robot.arm_control_idx[robot.default_arm]
226
+ dim = len(joint_control_idx)
227
+ initial_joint_pos = robot.get_joint_positions()[joint_control_idx]
228
+ control_idx_in_joint_pos = th.arange(dim)
229
+ else:
230
+ joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]])
231
+ dim = len(joint_control_idx)
232
+ if "combined" in robot.robot_arm_descriptor_yamls:
233
+ joint_combined_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx["combined"]])
234
+ initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_combined_idx])
235
+ control_idx_in_joint_pos = th.where(th.isin(joint_combined_idx, joint_control_idx))[0]
236
+ else:
237
+ initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_control_idx])
238
+ control_idx_in_joint_pos = th.arange(dim)
239
+
240
+ def state_valid_fn(q, verbose=False):
241
+ joint_pos = initial_joint_pos
242
+ joint_pos[control_idx_in_joint_pos] = th.tensor([q[i] for i in range(dim)])
243
+ return not set_arm_and_detect_collision(context, joint_pos, verbose=verbose)
244
+
245
+ # create an SE2 state space
246
+ space = ob.RealVectorStateSpace(dim)
247
+
248
+ # set lower and upper bounds
249
+ bounds = ob.RealVectorBounds(dim)
250
+ all_joints = list(robot.joints.values())
251
+ arm_joints = [all_joints[i] for i in joint_control_idx.tolist()]
252
+ for i, joint in enumerate(arm_joints):
253
+ if end_conf[i] > joint.upper_limit:
254
+ end_conf[i] = joint.upper_limit
255
+ if end_conf[i] < joint.lower_limit:
256
+ end_conf[i] = joint.lower_limit
257
+ bounds.setLow(i, float(joint.lower_limit))
258
+ bounds.setHigh(i, float(joint.upper_limit))
259
+ space.setBounds(bounds)
260
+
261
+ # create a simple setup object
262
+ ss = ompl_geo.SimpleSetup(space)
263
+ ss.setStateValidityChecker(ob.StateValidityCheckerFn(state_valid_fn))
264
+
265
+ si = ss.getSpaceInformation()
266
+ planner = ompl_geo.BITstar(si)
267
+ ss.setPlanner(planner)
268
+
269
+ start_conf = robot.get_joint_positions()[joint_control_idx]
270
+ start = ob.State(space)
271
+ for i in range(dim):
272
+ start[i] = float(start_conf[i])
273
+
274
+ goal = ob.State(space)
275
+ for i in range(dim):
276
+ goal[i] = float(end_conf[i])
277
+ ss.setStartAndGoalStates(start, goal)
278
+
279
+ # if the start pose or the goal pose collides, abort
280
+ if not state_valid_fn(start, verbose=True) or not state_valid_fn(goal, verbose=True):
281
+ return
282
+
283
+ # this will automatically choose a default planner with
284
+ # default parameters
285
+ solved = ss.solve(planning_time)
286
+
287
+ if solved:
288
+ # try to shorten the path
289
+ ss.simplifySolution()
290
+
291
+ sol_path = ss.getSolutionPath()
292
+ return_path = []
293
+ for i in range(sol_path.getStateCount()):
294
+ joint_pos = th.tensor([sol_path.getState(i)[j] for j in range(dim)], dtype=th.float32)
295
+ return_path.append(joint_pos)
296
+ return return_path
297
+ return None
298
+
299
+
300
+ def plan_arm_motion_ik(robot, end_conf, context, planning_time=15.0, torso_fixed=True):
301
+ """
302
+ Plans an arm motion to a final end effector pose
303
+
304
+ Args:
305
+ robot (BaseRobot): Robot object to plan for
306
+ end_conf (Iterable): Final end effector pose to plan to
307
+ context (PlanningContext): Context to plan in that includes the robot copy
308
+ planning_time (float): Time to plan for
309
+
310
+ Returns:
311
+ th.tensor or None: Tensors of end effector pose that the robot should navigate to, if available
312
+ """
313
+ from ompl import base as ob
314
+ from ompl import geometric as ompl_geo
315
+
316
+ DOF = 6
317
+
318
+ if torso_fixed:
319
+ joint_control_idx = robot.arm_control_idx[robot.default_arm]
320
+ dim = len(joint_control_idx)
321
+ initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_control_idx])
322
+ control_idx_in_joint_pos = th.arange(dim)
323
+ robot_description_path = robot.robot_arm_descriptor_yamls["left_fixed"]
324
+ else:
325
+ joint_control_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx[robot.default_arm]])
326
+ dim = len(joint_control_idx)
327
+ if "combined" in robot.robot_arm_descriptor_yamls:
328
+ joint_combined_idx = th.cat([robot.trunk_control_idx, robot.arm_control_idx["combined"]])
329
+ initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_combined_idx])
330
+ control_idx_in_joint_pos = th.where(th.isin(joint_combined_idx, joint_control_idx))[0]
331
+ else:
332
+ initial_joint_pos = th.tensor(robot.get_joint_positions()[joint_control_idx])
333
+ control_idx_in_joint_pos = th.arange(dim)
334
+ robot_description_path = robot.robot_arm_descriptor_yamls[robot.default_arm]
335
+
336
+ ik_solver = IKSolver(
337
+ robot_description_path=robot_description_path,
338
+ robot_urdf_path=robot.urdf_path,
339
+ reset_joint_pos=robot.reset_joint_pos[joint_control_idx],
340
+ eef_name=robot.eef_link_names[robot.default_arm],
341
+ )
342
+
343
+ def state_valid_fn(q, verbose=False):
344
+ joint_pos = initial_joint_pos
345
+ eef_pose = th.tensor([q[i] for i in range(6)], dtype=th.float32)
346
+ control_joint_pos = ik_solver.solve(
347
+ target_pos=eef_pose[:3],
348
+ target_quat=T.axisangle2quat(eef_pose[3:]),
349
+ max_iterations=1000,
350
+ )
351
+
352
+ if control_joint_pos is None:
353
+ return False
354
+ joint_pos[control_idx_in_joint_pos] = control_joint_pos
355
+ return not set_arm_and_detect_collision(context, joint_pos, verbose=verbose)
356
+
357
+ # create an SE2 state space
358
+ space = ob.RealVectorStateSpace(DOF)
359
+
360
+ # set lower and upper bounds for eef position
361
+ bounds = ob.RealVectorBounds(DOF)
362
+
363
+ EEF_X_LIM = [-0.8, 0.8]
364
+ EEF_Y_LIM = [-0.8, 0.8]
365
+ EEF_Z_LIM = [-2.0, 2.0]
366
+ bounds.setLow(0, EEF_X_LIM[0])
367
+ bounds.setHigh(0, EEF_X_LIM[1])
368
+ bounds.setLow(1, EEF_Y_LIM[0])
369
+ bounds.setHigh(1, EEF_Y_LIM[1])
370
+ bounds.setLow(2, EEF_Z_LIM[0])
371
+ bounds.setHigh(2, EEF_Z_LIM[1])
372
+
373
+ # # set lower and upper bounds for eef orientation (axis angle bounds)
374
+ for i in range(3, 6):
375
+ bounds.setLow(i, -math.pi)
376
+ bounds.setHigh(i, math.pi)
377
+ space.setBounds(bounds)
378
+
379
+ # create a simple setup object
380
+ ss = ompl_geo.SimpleSetup(space)
381
+ ss.setStateValidityChecker(ob.StateValidityCheckerFn(state_valid_fn))
382
+
383
+ si = ss.getSpaceInformation()
384
+ planner = ompl_geo.BITstar(si)
385
+ ss.setPlanner(planner)
386
+
387
+ start_conf = th.cat((robot.get_relative_eef_position(), T.quat2axisangle(robot.get_relative_eef_orientation())))
388
+ # do fk
389
+ start = ob.State(space)
390
+ for i in range(DOF):
391
+ start[i] = float(start_conf[i])
392
+
393
+ goal = ob.State(space)
394
+ for i in range(DOF):
395
+ goal[i] = float(end_conf[i])
396
+ ss.setStartAndGoalStates(start, goal)
397
+
398
+ if not state_valid_fn(start, verbose=True) or not state_valid_fn(goal, verbose=True):
399
+ return
400
+
401
+ # this will automatically choose a default planner with
402
+ # default parameters
403
+ solved = ss.solve(planning_time)
404
+
405
+ if solved:
406
+ # try to shorten the path
407
+ ss.simplifySolution()
408
+
409
+ sol_path = ss.getSolutionPath()
410
+ return_path = []
411
+ for i in range(sol_path.getStateCount()):
412
+ eef_pose = th.tensor([sol_path.getState(i)[j] for j in range(DOF)], dtype=th.float32)
413
+ return_path.append(eef_pose)
414
+ return return_path
415
+ return None
416
+
417
+
418
+ def set_base_and_detect_collision(context, pose, verbose=False):
419
+ """
420
+ Moves the robot and detects robot collisions with the environment and itself
421
+
422
+ Args:
423
+ context (PlanningContext): Context to plan in that includes the robot copy
424
+ pose (Array): Pose in the world frame to check for collisions at
425
+ verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False
426
+
427
+ Returns:
428
+ bool: Whether the robot is in collision
429
+ """
430
+ # make a copy of the robot, set it to the goal pose, and check for possible collision
431
+ robot_copy = context.robot_copy
432
+ robot_copy_type = context.robot_copy_type
433
+
434
+ translation = lazy.pxr.Gf.Vec3d(pose[0].tolist())
435
+ robot_copy.prims[robot_copy_type].GetAttribute("xformOp:translate").Set(translation)
436
+
437
+ orientation = pose[1][[3, 0, 1, 2]]
438
+ robot_copy.prims[robot_copy_type].GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*orientation.tolist()))
439
+ return detect_robot_collision(context, verbose=verbose)
440
+
441
+
442
+ def set_arm_and_detect_collision(context, joint_pos, verbose=False):
443
+ """
444
+ Sets joint positions of the robot and detects robot collisions with the environment and itself
445
+
446
+ Args:
447
+ context (PlanningContext): Context to plan in that includes the robot copy
448
+ joint_pos (Array): Joint positions to set the robot to
449
+ verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False
450
+
451
+ Returns:
452
+ bool: Whether the robot is in a valid state i.e. not in collision
453
+ """
454
+ robot_copy = context.robot_copy
455
+ robot_copy_type = context.robot_copy_type
456
+
457
+ arm_links = context.robot.manipulation_link_names
458
+ link_poses = context.fk_solver.get_link_poses(joint_pos, arm_links)
459
+
460
+ for link in arm_links:
461
+ pose = link_poses[link]
462
+ if link in robot_copy.meshes[robot_copy_type].keys():
463
+ for mesh_name, mesh in robot_copy.meshes[robot_copy_type][link].items():
464
+ relative_pose = robot_copy.relative_poses[robot_copy_type][link][mesh_name]
465
+ mesh_pose = T.pose_transform(*pose, *relative_pose)
466
+ translation = lazy.pxr.Gf.Vec3d(*mesh_pose[0].tolist())
467
+ mesh.GetAttribute("xformOp:translate").Set(translation)
468
+ orientation = mesh_pose[1][[3, 0, 1, 2]]
469
+ mesh.GetAttribute("xformOp:orient").Set(lazy.pxr.Gf.Quatd(*orientation.tolist()))
470
+
471
+ return detect_robot_collision(context, verbose=verbose)
472
+
473
+
474
+ def detect_robot_collision(context, verbose=False):
475
+ """
476
+ Detects robot collisions
477
+
478
+ Args:
479
+ context (PlanningContext): Context to plan in that includes the robot copy
480
+ verbose (bool): Whether the collision detector should output information about collisions or not. The verbose mode is too noisy in sampling so it is default to False
481
+
482
+ Returns:
483
+ valid_hit(bool): Whether the robot is in collision
484
+ """
485
+ robot_copy = context.robot_copy
486
+ robot_copy_type = context.robot_copy_type
487
+
488
+ # Define function for checking overlap
489
+ valid_hit = False
490
+ mesh_path = None
491
+
492
+ def overlap_callback(hit):
493
+ nonlocal valid_hit
494
+
495
+ valid_hit = hit.rigid_body not in context.disabled_collision_pairs_dict[mesh_path]
496
+
497
+ # if verbose mode is on and overlap is detected, output a warning on the colliding object and robot mesh_path
498
+ if valid_hit and verbose:
499
+ logger.warning(
500
+ f"Could not make a plan to get to the target position, colliding objects: {hit.rigid_body} and {mesh_path}",
501
+ )
502
+
503
+ return not valid_hit
504
+
505
+ for meshes in robot_copy.meshes[robot_copy_type].values():
506
+ for mesh in meshes.values():
507
+ if valid_hit:
508
+ return valid_hit
509
+ mesh_path = mesh.GetPrimPath().pathString
510
+ mesh_id = lazy.pxr.PhysicsSchemaTools.encodeSdfPath(mesh_path)
511
+ if mesh.GetTypeName() == "Mesh":
512
+ og.sim.psqi.overlap_mesh(*mesh_id, reportFn=overlap_callback)
513
+ else:
514
+ og.sim.psqi.overlap_shape(*mesh_id, reportFn=overlap_callback)
515
+
516
+ return valid_hit
517
+
518
+
519
+ def detect_robot_collision_in_sim(robot, filter_objs=None, ignore_obj_in_hand=True):
520
+ """
521
+ Detects robot collisions with the environment, but not with itself using the RigidContactAPI cache.
522
+
523
+ Args:
524
+ robot (BaseRobot): Robot object to detect collisions for
525
+ filter_objs (list of DatasetObject or None): Objects to ignore collisions with
526
+ ignore_obj_in_hand (bool): Whether to ignore collisions with the object in the robot's hand
527
+
528
+ Returns:
529
+ bool: Whether the robot is in collision
530
+ """
531
+ if filter_objs is None:
532
+ filter_objs = []
533
+
534
+ if ignore_obj_in_hand:
535
+ for arm in robot.arm_names:
536
+ if robot.grasping_mode in ["sticky", "assisted"]:
537
+ if robot._ag_obj_in_hand[arm] is not None:
538
+ filter_objs.append(robot._ag_obj_in_hand[arm])
539
+ elif robot.grasping_mode == "physical":
540
+ filter_objs.extend(robot._find_gripper_raycast_collisions(arm=arm))
541
+ else:
542
+ raise ValueError(f"Unknown grasping mode: {robot.grasping_mode}")
543
+
544
+ for category in GROUND_CATEGORIES:
545
+ filter_objs.extend(robot.scene.object_registry("category", category, []))
546
+
547
+ # Always exclude robot self-collisions (internal link-to-link contacts)
548
+ if robot not in filter_objs:
549
+ filter_objs.append(robot)
550
+
551
+ return RigidContactAPI.is_in_contact(
552
+ scene_idx=robot.scene.idx, query_set=[robot], with_set=None, ignore_set=filter_objs, current_only=False
553
+ )
554
+
555
+
556
+ def astar(search_map, start, goal, eight_connected=True):
557
+ """
558
+ A* search algorithm for finding a path from start to goal on a grid map
559
+
560
+ Args:
561
+ search_map (Array): 2D Grid map to search on
562
+ start (Array): Start position on the map
563
+ goal (Array): Goal position on the map
564
+ eight_connected (bool): Whether we consider the sides and diagonals of a cell as neighbors or just the sides
565
+
566
+ Returns:
567
+ 2D numpy array or None: Array of shape (N, 2) where N is the number of steps in the path.
568
+ Each row represents the (x, y) coordinates of a step on the path.
569
+ If no path is found, returns None.
570
+ """
571
+
572
+ def heuristic(node):
573
+ # Calculate the Euclidean distance from node to goal
574
+ return math.sqrt((node[0] - goal[0]) ** 2 + (node[1] - goal[1]) ** 2)
575
+
576
+ def get_neighbors(cell):
577
+ if eight_connected:
578
+ # 8-connected grid
579
+ return [
580
+ (cell[0] + 1, cell[1]),
581
+ (cell[0] - 1, cell[1]),
582
+ (cell[0], cell[1] + 1),
583
+ (cell[0], cell[1] - 1),
584
+ (cell[0] + 1, cell[1] + 1),
585
+ (cell[0] - 1, cell[1] - 1),
586
+ (cell[0] + 1, cell[1] - 1),
587
+ (cell[0] - 1, cell[1] + 1),
588
+ ]
589
+ else:
590
+ # 4-connected grid
591
+ return [(cell[0] + 1, cell[1]), (cell[0] - 1, cell[1]), (cell[0], cell[1] + 1), (cell[0], cell[1] - 1)]
592
+
593
+ def is_valid(cell):
594
+ # Check if cell is within the map and traversable
595
+ return 0 <= cell[0] < search_map.shape[0] and 0 <= cell[1] < search_map.shape[1] and search_map[cell] != 0
596
+
597
+ def cost(cell1, cell2):
598
+ # Define the cost of moving from cell1 to cell2
599
+ # Return 1 for adjacent cells and square root of 2 for diagonal cells in an 8-connected grid.
600
+ if cell1[0] == cell2[0] or cell1[1] == cell2[1]:
601
+ return 1
602
+ else:
603
+ return math.sqrt(2)
604
+
605
+ open_set = [(0, start)]
606
+ came_from = {}
607
+ visited = set()
608
+ rows, cols = search_map.shape
609
+ g_score = {(i.item(), j.item()): float("inf") for i, j in th.cartesian_prod(th.arange(rows), th.arange(cols))}
610
+ g_score[start] = 0
611
+
612
+ while open_set:
613
+ _, current = heapq.heappop(open_set)
614
+
615
+ visited.add(current)
616
+
617
+ if current == goal:
618
+ # Reconstruct path
619
+ path = []
620
+ while current in came_from:
621
+ path.insert(0, current)
622
+ current = came_from[current]
623
+ path.insert(0, start)
624
+ return th.tensor(path)
625
+
626
+ for neighbor in get_neighbors(current):
627
+ # Skip neighbors that are not valid or have already been visited
628
+ if not is_valid(neighbor) or neighbor in visited:
629
+ continue
630
+ tentative_g_score = g_score[current] + cost(current, neighbor)
631
+ if tentative_g_score < g_score[neighbor]:
632
+ came_from[neighbor] = current
633
+ g_score[neighbor] = tentative_g_score
634
+ f_score = tentative_g_score + heuristic(neighbor)
635
+ heapq.heappush(open_set, (f_score, neighbor))
636
+
637
+ # Return None if no path is found
638
+ return None
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/numpy_utils.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch as th
3
+ import omnigibson.lazy as lazy
4
+
5
+
6
+ class NumpyTypes:
7
+ FLOAT32 = np.float32
8
+ INT32 = np.int32
9
+ INT64 = np.int64
10
+ UINT8 = np.uint8
11
+ UINT32 = np.uint32
12
+
13
+
14
+ def numpy_to_torch(np_array, dtype=th.float32, device="cpu"):
15
+ if device == "cpu":
16
+ return th.from_numpy(np_array).to(dtype)
17
+ else:
18
+ assert device.startswith("cuda")
19
+ return th.tensor(np_array, dtype=dtype, device=device)
20
+
21
+
22
+ def vtarray_to_torch(vtarray, dtype=th.float32, device="cpu"):
23
+ np_array = np.array(vtarray)
24
+ return numpy_to_torch(np_array, dtype=dtype, device=device)
25
+
26
+
27
+ def gf_quat_to_torch(gf_quat, dtype=th.float32, device="cpu"):
28
+ np_array = lazy.isaacsim.core.utils.rotations.gf_quat_to_np_array(gf_quat)[[1, 2, 3, 0]]
29
+ return numpy_to_torch(np_array, dtype=dtype, device=device)
30
+
31
+
32
+ def pil_to_tensor(pil_image):
33
+ return th.tensor(np.array(pil_image), dtype=th.uint8)
34
+
35
+
36
+ def list_to_np_array(list):
37
+ return np.array(list)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_state_utils.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import math
3
+ import numpy as np
4
+ import torch as th
5
+
6
+ import omnigibson as og
7
+ import omnigibson.utils.transform_utils as T
8
+ from omnigibson.macros import Dict, create_module_macros, macros
9
+ from omnigibson.utils import sampling_utils
10
+ from omnigibson.utils.constants import GROUND_CATEGORIES, PrimType
11
+ from omnigibson.utils.ui_utils import debug_breakpoint, create_module_logger
12
+ from omnigibson.utils.constants import JointType
13
+ from omnigibson.utils.usd_utils import RigidContactAPI
14
+
15
+ # Create settings for this module
16
+ m = create_module_macros(module_path=__file__)
17
+
18
+ log = create_module_logger(module_name=__name__)
19
+
20
+ m.DEFAULT_HIGH_LEVEL_SAMPLING_ATTEMPTS = 10
21
+ m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS = 10
22
+ m.ARM_LENGTH_XY = 0.8
23
+ m.EEF_Z_MAX = 1.7
24
+ m.EEF_Z_MIN = 0.3
25
+ m.ON_TOP_RAY_CASTING_SAMPLING_PARAMS = Dict(
26
+ {
27
+ "bimodal_stdev_fraction": 1e-6,
28
+ "bimodal_mean_fraction": 1.0,
29
+ "aabb_offset_fraction": 0.02,
30
+ "max_sampling_attempts": 50,
31
+ }
32
+ )
33
+
34
+ m.INSIDE_RAY_CASTING_SAMPLING_PARAMS = Dict(
35
+ {
36
+ "bimodal_stdev_fraction": 0.4,
37
+ "bimodal_mean_fraction": 0.5,
38
+ "aabb_offset_fraction": -0.02,
39
+ "max_sampling_attempts": 100,
40
+ }
41
+ )
42
+
43
+ m.UNDER_RAY_CASTING_SAMPLING_PARAMS = Dict(
44
+ {
45
+ "bimodal_stdev_fraction": 1e-6,
46
+ "bimodal_mean_fraction": 0.5,
47
+ "aabb_offset_fraction": 0.02,
48
+ "max_sampling_attempts": 50,
49
+ }
50
+ )
51
+
52
+
53
+ def sample_cuboid_for_predicate(predicate, on_obj, bbox_extent):
54
+ if predicate == "onTop":
55
+ params = m.ON_TOP_RAY_CASTING_SAMPLING_PARAMS
56
+ elif predicate == "inside":
57
+ params = m.INSIDE_RAY_CASTING_SAMPLING_PARAMS
58
+ elif predicate == "under":
59
+ params = m.UNDER_RAY_CASTING_SAMPLING_PARAMS
60
+ else:
61
+ raise ValueError(
62
+ f"predicate must be onTop, under or inside in order to use ray casting-based "
63
+ f"kinematic sampling, but instead got: {predicate}"
64
+ )
65
+
66
+ if predicate == "under":
67
+ start_points, end_points = sampling_utils.sample_raytest_start_end_symmetric_bimodal_distribution(
68
+ obj=on_obj,
69
+ num_samples=1,
70
+ axis_probabilities=[0, 0, 1],
71
+ **params,
72
+ )
73
+ return sampling_utils.sample_cuboid_on_object(
74
+ obj=None,
75
+ start_points=start_points,
76
+ end_points=end_points,
77
+ ignore_objs=[on_obj],
78
+ cuboid_dimensions=bbox_extent,
79
+ refuse_downwards=True,
80
+ undo_cuboid_bottom_padding=True,
81
+ max_angle_with_z_axis=0.17,
82
+ hit_proportion=0.0, # rays will NOT hit the object itself, but the surface below it.
83
+ )
84
+ else:
85
+ return sampling_utils.sample_cuboid_on_object_symmetric_bimodal_distribution(
86
+ on_obj,
87
+ num_samples=1,
88
+ axis_probabilities=[0, 0, 1],
89
+ cuboid_dimensions=bbox_extent,
90
+ refuse_downwards=True,
91
+ undo_cuboid_bottom_padding=True,
92
+ max_angle_with_z_axis=0.17,
93
+ **params,
94
+ )
95
+
96
+
97
+ def get_reachability_sampling_context(objB, predicate, use_trav_map=True, warn_on_scene_mismatch=False):
98
+ """
99
+ Builds cached traversability / reachability data used for kinematic sampling checks.
100
+
101
+ Args:
102
+ objB (StatefulObject): Reference object used for sampling.
103
+ predicate (str): Predicate being sampled, e.g. "inside", "onTop", "under".
104
+ use_trav_map (bool): Whether to enable traversability-based reachability checks.
105
+ warn_on_scene_mismatch (bool): Whether to log a warning if objB.scene is not traversable.
106
+
107
+ Returns:
108
+ dict or None: Context dict if traversability checks are enabled, else None.
109
+ """
110
+ if not use_trav_map:
111
+ return None
112
+
113
+ from omnigibson.scenes.traversable_scene import TraversableScene
114
+
115
+ if not isinstance(objB.scene, TraversableScene):
116
+ if warn_on_scene_mismatch:
117
+ log.warning(
118
+ f"Using trav_map=True requires objB.scene to be a TraversableScene, but got {type(objB.scene)} instead."
119
+ )
120
+ return None
121
+
122
+ trav_map = objB.scene.trav_map
123
+ trav_map_floor_map = trav_map.floor_map[0]
124
+ arm_length_pixel = int(math.ceil(m.ARM_LENGTH_XY / trav_map.map_resolution))
125
+
126
+ robot = objB.scene.robots[0] if len(objB.scene.robots) > 0 else None
127
+ eroded_trav_map = trav_map._erode_trav_map(trav_map_floor_map, robot=robot)
128
+
129
+ # The eroded map pulls robot standing positions back by erosion_radius from obstacles.
130
+ # Dilating by arm_length alone would give net reach of (arm_length - erosion_radius) from
131
+ # obstacles, which is too small. Adding erosion_radius back restores the correct effective reach.
132
+ if robot is not None:
133
+ erosion_radius = th.norm(robot.reset_joint_pos_aabb_extent[:2]).item() / 2.0 + 0.2
134
+ else:
135
+ erosion_radius = trav_map.default_erosion_radius
136
+ erosion_radius_pixel = int(math.ceil(erosion_radius / trav_map.map_resolution))
137
+ reach_pixel = arm_length_pixel + erosion_radius_pixel
138
+
139
+ reachability_map = th.tensor(cv2.dilate(eroded_trav_map.cpu().numpy(), np.ones((reach_pixel, reach_pixel))))
140
+ has_prismatic_joint = any(j.joint_type == JointType.JOINT_PRISMATIC for j in objB.joints.values())
141
+
142
+ return {
143
+ "trav_map": trav_map,
144
+ "reachability_map": reachability_map,
145
+ "has_prismatic_joint": has_prismatic_joint,
146
+ "eroded_trav_map": eroded_trav_map,
147
+ }
148
+
149
+
150
+ def is_pose_reachable_for_predicate(pos, objB, predicate, reachability_context):
151
+ """
152
+ Checks whether sampled pose @pos satisfies robot-reachability constraints.
153
+
154
+ Args:
155
+ pos (Array[float]): Candidate world-frame position (x, y, z).
156
+ objB (StatefulObject): Reference object used for sampling.
157
+ predicate (str): Predicate being sampled, e.g. "inside", "onTop", "under".
158
+ reachability_context (dict or None): Context returned by get_reachability_sampling_context.
159
+
160
+ Returns:
161
+ bool: True if sampled pose passes reachability checks.
162
+ """
163
+ if reachability_context is None:
164
+ return True
165
+
166
+ trav_map = reachability_context["trav_map"]
167
+ reachability_map = reachability_context["reachability_map"]
168
+ has_prismatic_joint = reachability_context["has_prismatic_joint"]
169
+ eroded_trav_map = reachability_context["eroded_trav_map"]
170
+
171
+ xy_map = trav_map.world_to_map(pos[:2])
172
+ map_x, map_y = int(xy_map[0]), int(xy_map[1])
173
+ if pos[2] > m.EEF_Z_MAX:
174
+ # Sampled position is above the maximum z of the arm
175
+ return False
176
+ if pos[2] < m.EEF_Z_MIN and predicate == "inside" and objB.fixed_base:
177
+ # Sampling inside fixed-base object, position is below the minimum z of the arm
178
+ return False
179
+ if predicate == "onTop" and objB.category in GROUND_CATEGORIES:
180
+ # Sampling onTop of ground category, sampled position should be traversable
181
+ map_h, map_w = eroded_trav_map.shape
182
+ if map_x < 0 or map_x >= map_h or map_y < 0 or map_y >= map_w:
183
+ return False
184
+ return eroded_trav_map[map_x, map_y] == 255
185
+ if not has_prismatic_joint:
186
+ # Sampling around object with no prismatic joints, sampled position should be reachable
187
+ map_h, map_w = reachability_map.shape
188
+ if map_x < 0 or map_x >= map_h or map_y < 0 or map_y >= map_w:
189
+ return False
190
+ return reachability_map[map_x, map_y] == 255
191
+
192
+ return True
193
+
194
+
195
+ def sample_kinematics(
196
+ predicate,
197
+ objA,
198
+ objB,
199
+ max_trials=None,
200
+ z_offset=0.05,
201
+ skip_falling=False,
202
+ use_last_ditch_effort=False,
203
+ use_trav_map=True,
204
+ reachability_context=None,
205
+ ):
206
+ """
207
+ Samples the given @predicate kinematic state for @objA with respect to @objB
208
+
209
+ Args:
210
+ predicate (str): Name of the predicate to sample, e.g.: "onTop"
211
+ objA (StatefulObject): Object whose state should be sampled. e.g.: for sampling a microwave
212
+ on a cabinet, @objA is the microwave
213
+ objB (StatefulObject): Object who is the reference point for @objA's state. e.g.: for sampling
214
+ a microwave on a cabinet, @objB is the cabinet
215
+ max_trials (int): Number of attempts for sampling
216
+ z_offset (float): Z-offset to apply to the sampled pose
217
+ skip_falling (bool): Whether to let @objA fall after its position is sampled or not
218
+ use_last_ditch_effort (bool): Whether to use last-ditch effort to sample the kinematics if the first
219
+ sampling attempt fails. This will place @objA at the center of @objB's AABB, offset in z direction such
220
+ use_trav_map (bool): Whether to use the traversability map of the scene to check if the sampled position is traversable.
221
+ reachability_context (dict or None): Pre-computed context from get_reachability_sampling_context. If provided,
222
+ skips recomputing it (avoids repeated cv2.erode calls when sample_kinematics is called in a loop).
223
+
224
+ Returns:
225
+ bool: True if successfully sampled, else False
226
+ """
227
+ if reachability_context is None:
228
+ reachability_context = get_reachability_sampling_context(
229
+ objB=objB,
230
+ predicate=predicate,
231
+ use_trav_map=use_trav_map,
232
+ warn_on_scene_mismatch=True,
233
+ )
234
+ use_trav_map = reachability_context is not None
235
+ if max_trials is None:
236
+ max_trials = m.DEFAULT_LOW_LEVEL_SAMPLING_ATTEMPTS
237
+ assert (
238
+ z_offset > 0.5 * 9.81 * (og.sim.get_physics_dt() ** 2) + 0.02
239
+ ), f"z_offset {z_offset} is too small for the current physics_dt {og.sim.get_physics_dt()}"
240
+
241
+ # Wake objects accordingly and make sure both are kept still
242
+ objA.wake()
243
+ objB.wake()
244
+
245
+ objA.keep_still()
246
+ objB.keep_still()
247
+
248
+ # Save the state of the simulator
249
+ state = og.sim.dump_state()
250
+
251
+ # Attempt sampling
252
+ def _is_in_contact():
253
+ if objA.prim_type == PrimType.RIGID:
254
+ return RigidContactAPI.is_in_contact(
255
+ scene_idx=objA.scene.idx, query_set=[objA], with_set=None, ignore_set=None, current_only=False
256
+ )
257
+ else:
258
+ return len(objA.root_link.get_contacts()) > 0
259
+
260
+ for i in range(max_trials):
261
+ pos = None
262
+ if hasattr(objA, "orientations") and objA.orientations is not None:
263
+ orientation = objA.sample_orientation()
264
+ else:
265
+ orientation = th.tensor([0, 0, 0, 1.0])
266
+
267
+ # Orientation needs to be set for stable_z_on_aabb to work correctly
268
+ # Position needs to be set to be very far away because the object's
269
+ # original position might be blocking rays (use_ray_casting_method=True)
270
+ old_pos = th.tensor([100, 100, 10])
271
+ objA.set_position_orientation(position=old_pos, orientation=orientation)
272
+ objA.keep_still()
273
+ # We also need to step physics to make sure the pose propagates downstream (e.g.: to Bounding Box computations)
274
+ og.sim.step_physics()
275
+
276
+ # This would slightly change because of the step_physics call.
277
+ old_pos, orientation = objA.get_position_orientation()
278
+
279
+ # Run import here to avoid circular imports
280
+ from omnigibson.objects.dataset_object import DatasetObject
281
+
282
+ if isinstance(objA, DatasetObject) and objA.prim_type == PrimType.RIGID:
283
+ # Retrieve base CoM frame-aligned bounding box parallel to the XY plane
284
+ parallel_bbox_center, parallel_bbox_orn, parallel_bbox_extents, _ = objA.get_base_aligned_bbox(
285
+ xy_aligned=True
286
+ )
287
+ else:
288
+ aabb_lower, aabb_upper = objA.aabb
289
+ parallel_bbox_center = (aabb_lower + aabb_upper) / 2.0
290
+ parallel_bbox_orn = th.tensor([0.0, 0.0, 0.0, 1.0])
291
+ parallel_bbox_extents = aabb_upper - aabb_lower
292
+
293
+ sampling_results = sample_cuboid_for_predicate(predicate, objB, parallel_bbox_extents)
294
+ sampled_vector = sampling_results[0][0]
295
+ sampled_quaternion = sampling_results[0][2]
296
+
297
+ sampling_success = sampled_vector is not None
298
+
299
+ if sampling_success:
300
+ # Move the object from the original parallel bbox to the sampled bbox
301
+ # The additional orientation to be applied should be the delta orientation
302
+ # between the parallel bbox orientation and the sample orientation
303
+ additional_quat = T.quat_multiply(sampled_quaternion, T.quat_inverse(parallel_bbox_orn))
304
+ combined_quat = T.quat_multiply(additional_quat, orientation)
305
+ orientation = combined_quat
306
+
307
+ # The delta vector between the base CoM frame and the parallel bbox center needs to be rotated
308
+ # by the same additional orientation
309
+ diff = old_pos - parallel_bbox_center
310
+ rotated_diff = T.quat_apply(additional_quat, diff)
311
+ pos = sampled_vector + rotated_diff
312
+
313
+ from omnigibson.robots.robot import Robot
314
+
315
+ if use_trav_map and not isinstance(objA, Robot):
316
+ if not is_pose_reachable_for_predicate(
317
+ pos=pos,
318
+ objB=objB,
319
+ predicate=predicate,
320
+ reachability_context=reachability_context,
321
+ ):
322
+ pos = None
323
+ success = False
324
+ if pos is None:
325
+ success = False
326
+ else:
327
+ pos[2] += z_offset
328
+ objA.set_position_orientation(position=pos, orientation=orientation)
329
+ objA.keep_still()
330
+
331
+ og.sim.step_physics()
332
+ objA.keep_still()
333
+ success = not _is_in_contact()
334
+
335
+ if macros.utils.sampling_utils.DEBUG_SAMPLING:
336
+ debug_breakpoint(f"sample_kinematics: {success}")
337
+
338
+ if success:
339
+ break
340
+ else:
341
+ og.sim.load_state(state)
342
+
343
+ # If we didn't succeed, optionally try last-ditch effort
344
+ if not success and use_last_ditch_effort and predicate in {"onTop", "inside"}:
345
+ # Do not use last-ditch effort for onTop ground categories because it will
346
+ # break the traversability constraint (see above)
347
+ if predicate == "onTop" and objB.category in GROUND_CATEGORIES:
348
+ pass
349
+ else:
350
+ og.sim.step_physics()
351
+ # Place objA at center of objB's AABB, offset in z direction such that their AABBs are "stacked", and let fall
352
+ # until it settles
353
+ aabb_lower_a, aabb_upper_a = objA.aabb
354
+ aabb_lower_b, aabb_upper_b = objB.aabb
355
+ bbox_to_obj = objA.get_position_orientation()[0] - (aabb_lower_a + aabb_upper_a) / 2.0
356
+ desired_bbox_pos = (aabb_lower_b + aabb_upper_b) / 2.0
357
+ desired_bbox_pos[2] = aabb_upper_b[2] + (aabb_upper_a[2] - aabb_lower_a[2]) / 2.0
358
+ pos = desired_bbox_pos + bbox_to_obj
359
+ success = True
360
+
361
+ if success and not skip_falling:
362
+ objA.set_position_orientation(position=pos, orientation=orientation)
363
+ objA.keep_still()
364
+
365
+ # Step until either (a) max steps is reached (total of 0.5 second in sim time) or (b) contact is made, then
366
+ # step until (a) max steps is reached (restarted from 0) or (b) velocity is below some threshold
367
+ n_steps_max = int(0.5 / og.sim.get_physics_dt())
368
+ i = 0
369
+
370
+ while not _is_in_contact() and i < n_steps_max:
371
+ og.sim.step_physics()
372
+ i += 1
373
+ objA.keep_still()
374
+ objB.keep_still()
375
+ # Step a few times so velocity can become non-zero if the objects are moving
376
+ for i in range(5):
377
+ og.sim.step_physics()
378
+ i = 0
379
+ while th.norm(objA.get_linear_velocity()) > 1e-3 and i < n_steps_max:
380
+ og.sim.step_physics()
381
+ i += 1
382
+
383
+ return success
384
+
385
+
386
+ def sample_cloth_on_rigid(obj, other, max_trials=40, z_offset=0.05, randomize_xy=True):
387
+ """
388
+ Samples the cloth object @obj on the rigid object @other
389
+
390
+ Args:
391
+ obj (StatefulObject): Object whose state should be sampled. e.g.: for sampling a bed sheet on a rack,
392
+ @obj is the bed sheet
393
+ other (StatefulObject): Object who is the reference point for @obj's state. e.g.: for sampling a bed sheet
394
+ on a rack, @other is the rack
395
+ max_trials (int): Number of attempts for sampling
396
+ z_offset (float): Z-offset to apply to the sampled pose
397
+ randomize_xy (bool): Whether to randomize the XY position of the sampled pose. If False, the center of @other
398
+ will always be used.
399
+
400
+ Returns:
401
+ bool: True if successfully sampled, else False
402
+ """
403
+ assert (
404
+ z_offset > 0.5 * 9.81 * (og.sim.get_physics_dt() ** 2) + 0.02
405
+ ), f"z_offset {z_offset} is too small for the current physics_dt {og.sim.get_physics_dt()}"
406
+
407
+ if not (obj.prim_type == PrimType.CLOTH and other.prim_type == PrimType.RIGID):
408
+ raise ValueError("sample_cloth_on_rigid requires obj1 is cloth and obj2 is rigid.")
409
+
410
+ state = og.sim.dump_state(serialized=False)
411
+
412
+ # Reset the cloth to the settled configuration if available
413
+ if "settled" in obj.root_link.get_available_configurations():
414
+ obj.root_link.reset_points_to_configuration("settled")
415
+ else:
416
+ obj.root_link.reset()
417
+
418
+ obj_aabb_low, obj_aabb_high = obj.aabb
419
+ other_aabb_low, other_aabb_high = other.aabb
420
+
421
+ # z value is always the same: the top-z of the other object + half the height of the object to be placed + offset
422
+ z_value = other_aabb_high[2] + (obj_aabb_high[2] - obj_aabb_low[2]) / 2.0 + z_offset
423
+
424
+ if randomize_xy:
425
+ # Sample a random position in the x-y plane within the other object's AABB
426
+ low = th.tensor([other_aabb_low[0], other_aabb_low[1], z_value])
427
+ high = th.tensor([other_aabb_high[0], other_aabb_high[1], z_value])
428
+ else:
429
+ # Always sample the center of the other object's AABB
430
+ low = th.tensor(
431
+ [(other_aabb_low[0] + other_aabb_high[0]) / 2.0, (other_aabb_low[1] + other_aabb_high[1]) / 2.0, z_value]
432
+ )
433
+ high = low
434
+
435
+ for _ in range(max_trials):
436
+ # Sample a random position
437
+ pos = th.rand(low.size()) * (high - low) + low
438
+ # Sample a random orientation in the z-axis
439
+ z_lo, z_hi = 0, math.pi * 2
440
+ orn = T.euler2quat(th.tensor([0.0, 0.0, (th.rand(1) * (z_hi - z_lo) + z_lo).item()]))
441
+
442
+ obj.set_position_orientation(position=pos, orientation=orn)
443
+ obj.root_link.reset()
444
+ obj.keep_still()
445
+
446
+ og.sim.step_physics()
447
+ success = len(obj.root_link.get_contacts()) == 0
448
+
449
+ if success:
450
+ break
451
+ else:
452
+ og.sim.load_state(state)
453
+
454
+ if success:
455
+ # Let it fall for 0.2 second always to let the cloth settle
456
+ for _ in range(int(0.2 / og.sim.get_physics_dt())):
457
+ og.sim.step_physics()
458
+
459
+ obj.keep_still()
460
+
461
+ # Render at the end
462
+ og.sim.render()
463
+
464
+ return success
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/object_utils.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper utility functions for computing relevant object information
3
+ """
4
+
5
+ import torch as th
6
+
7
+ import omnigibson as og
8
+ import omnigibson.utils.transform_utils as T
9
+ from omnigibson.scenes import Scene
10
+ from omnigibson.utils.geometry_utils import get_particle_positions_from_frame
11
+
12
+
13
+ def sample_stable_orientations(obj, n_samples=10, drop_aabb_offset=0.1):
14
+ """
15
+ Samples random stable orientations for obj @obj by stochastically dropping the object and recording its
16
+ resulting orientations
17
+
18
+ Args:
19
+ obj (USDObject): Object whose orientations will be sampled
20
+ n_samples (int): How many sampled orientations will be recorded
21
+ drop_aabb_offset (float): Offset to apply in the z-direction when dropping the object
22
+
23
+ Returns:
24
+ n-array: (N, 4) array, where each of the N rows are sampled (x,y,z,w) stable orientations
25
+ """
26
+ og.sim.play()
27
+ assert th.all(obj.scale == 1.0)
28
+ aabb_extent = obj.aabb_extent
29
+ radius = th.norm(aabb_extent) / 2.0
30
+ drop_pos = th.tensor([0, 0, radius + drop_aabb_offset])
31
+ center_offset = obj.get_position_orientation()[0] - obj.aabb_center
32
+ drop_orientations = T.random_quaternion(n_samples)
33
+ stable_orientations = th.zeros_like(drop_orientations)
34
+ for i, drop_orientation in enumerate(drop_orientations):
35
+ # Sample orientation, drop, wait to stabilize, then record
36
+ pos = drop_pos + T.quat2mat(drop_orientation) @ center_offset
37
+ obj.set_position_orientation(position=pos, orientation=drop_orientation)
38
+ obj.keep_still()
39
+ for j in range(25):
40
+ og.sim.step()
41
+ stable_orientations[i] = obj.get_position_orientation()[1]
42
+
43
+ return stable_orientations
44
+
45
+
46
+ def compute_bbox_offset(obj):
47
+ """
48
+ Computes the base link offset of @obj, specifying the relative position of the object's bounding box center wrt to
49
+ its root link frame, expressed in the world frame
50
+
51
+ Args:
52
+ obj (USDObject): Object whose bbox offset will be computed
53
+
54
+ Returns:
55
+ n-array: (x,y,z) offset specifying the relative position from the root link to @obj's bounding box center
56
+ """
57
+ og.sim.stop()
58
+ assert th.all(obj.scale == 1.0)
59
+ obj.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0]))
60
+ return obj.aabb_center - obj.get_position_orientation()[0]
61
+
62
+
63
+ def compute_native_bbox_extent(obj):
64
+ """
65
+ Computes the native bounding box extent for @obj, which is the extent with the obj placed at (0, 0, 0) with
66
+ orientation (0, 0, 0, 1) and scale (1, 1, 1)
67
+
68
+ Args:
69
+ obj (USDObject): Object whose native bbox extent will be computed
70
+
71
+ Returns:
72
+ n-array: (x,y,z) native bounding box extent
73
+ """
74
+ og.sim.stop()
75
+ assert th.all(obj.scale == 1.0)
76
+ obj.set_position_orientation(position=th.zeros(3), orientation=th.tensor([0, 0, 0, 1.0]))
77
+ return obj.aabb_extent
78
+
79
+
80
+ def compute_base_aligned_bboxes(obj):
81
+ link_bounding_boxes = {}
82
+ for link_name, link in obj.links.items():
83
+ link_bounding_boxes[link_name] = {}
84
+ for mesh_type, mesh_list in zip(("collision", "visual"), (link.collision_meshes, link.visual_meshes)):
85
+ pts_in_link_frame = []
86
+ for mesh_name, mesh in mesh_list.items():
87
+ pts = mesh.get_attribute("points")
88
+ local_pos, local_orn = mesh.get_position_orientation(frame="parent")
89
+ pts_in_link_frame.append(get_particle_positions_from_frame(local_pos, local_orn, mesh.scale, pts))
90
+ pts_in_link_frame = th.cat(pts_in_link_frame, dim=0)
91
+ max_pt = th.max(pts_in_link_frame, dim=0).values
92
+ min_pt = th.min(pts_in_link_frame, dim=0).values
93
+ extent = max_pt - min_pt
94
+ center = (max_pt + min_pt) / 2.0
95
+ transform = T.pose2mat((center, th.tensor([0, 0, 0, 1.0])))
96
+ print(pts_in_link_frame.shape)
97
+ link_bounding_boxes[link_name][mesh_type] = {
98
+ "extent": extent,
99
+ "transform": transform,
100
+ }
101
+ return link_bounding_boxes
102
+
103
+
104
+ def compute_obj_kinematic_metadata(obj):
105
+ """
106
+ Computes relevant kinematic metadata for @obj, such as stable_orientations, bounding box offsets,
107
+ bounding box extents, and base_aligned_bboxes
108
+
109
+ Args:
110
+ obj (USDObject): Object whose metadata will be computed
111
+
112
+ Returns:
113
+ dict: Relevant metadata, with the following keys:
114
+
115
+ - "stable_orientations": 2D (N, 4)-array of sampled stable (x,y,z,w) quaternion orientations
116
+ - "bbox_offset": (x,y,z) relative position from the root link to @obj's bounding box center
117
+ - "native_bbox_extent": (x,y,z) native bounding box extent
118
+ - "base_aligned_bboxes": TODO
119
+ """
120
+ assert obj.scene is not None
121
+ assert og.sim.floor_plane is not None
122
+ assert type(obj.scene) is Scene, "An empty scene must be used in order to compute kinematic metadata!"
123
+ assert th.all(obj.scale == 1.0), "Object must have scale [1, 1, 1] in order to compute kinematic metadata!"
124
+ og.sim.stop()
125
+
126
+ return {
127
+ "stable_orientations": sample_stable_orientations(obj=obj),
128
+ "bbox_offset": compute_bbox_offset(obj=obj),
129
+ "native_bbox_extent": compute_native_bbox_extent(obj=obj),
130
+ "base_aligned_bboxes": compute_base_aligned_bboxes(obj=obj),
131
+ }
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/physx_utils.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as th
2
+
3
+ import omnigibson as og
4
+ import omnigibson.lazy as lazy
5
+ from omnigibson.macros import create_module_macros
6
+ from omnigibson.utils.ui_utils import suppress_omni_log
7
+ from omnigibson.utils.usd_utils import ensure_usd_api
8
+
9
+ # Create settings for this module
10
+ m = create_module_macros(module_path=__file__)
11
+
12
+ m.PROTOTYPE_GRAVEYARD_POS = (100.0, 100.0, 100.0)
13
+
14
+
15
+ def create_physx_particle_system(
16
+ prim_path,
17
+ physics_scene_path,
18
+ particle_contact_offset,
19
+ visual_only=False,
20
+ smoothing=True,
21
+ anisotropy=True,
22
+ isosurface=True,
23
+ ):
24
+ """
25
+ Creates an Omniverse physx particle system at @prim_path. For post-processing visualization effects (anisotropy,
26
+ smoothing, isosurface), see the Omniverse documentation
27
+ (https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_physics.html?highlight=isosurface#post-processing-for-fluid-rendering)
28
+ for more info
29
+
30
+ Args:
31
+ prim_path (str): Stage path to where particle system should be created
32
+ physics_scene_path (str): Stage path to where active physicsScene prim is defined
33
+ particle_contact_offset (float): Distance between particles which triggers a collision (m)
34
+ visual_only (bool): If True, will disable collisions between particles and non-particles,
35
+ as well as self-collisions
36
+ smoothing (bool): Whether to smooth particle positions or not
37
+ anisotropy (bool): Whether to apply anisotropy post-processing when visualizing particles. Stretches generated
38
+ particles in order to make the particle cluster surface appear smoother. Useful for fluids
39
+ isosurface (bool): Whether to apply isosurface mesh to visualize particles. Uses a monolithic surface that
40
+ can have materials attached to it, useful for visualizing fluids
41
+
42
+ Returns:
43
+ UsdGeom.PhysxParticleSystem: Generated particle system prim
44
+ """
45
+ with og.sim.editing_usd():
46
+ # TODO: Add sanity check to make sure GPU dynamics are enabled
47
+ # Create particle system
48
+ stage = lazy.isaacsim.core.utils.stage.get_current_stage()
49
+ particle_system = lazy.pxr.PhysxSchema.PhysxParticleSystem.Define(stage, prim_path)
50
+ particle_system.CreateSimulationOwnerRel().SetTargets([physics_scene_path])
51
+
52
+ # Use a smaller particle size for nicer fluid, and let the sim figure out the other offsets
53
+ particle_system.CreateParticleContactOffsetAttr().Set(particle_contact_offset)
54
+
55
+ # Possibly disable collisions if we're only visual
56
+ if visual_only:
57
+ particle_system.GetGlobalSelfCollisionEnabledAttr().Set(False)
58
+ particle_system.GetNonParticleCollisionEnabledAttr().Set(False)
59
+
60
+ if anisotropy:
61
+ # apply api and use all defaults
62
+ ani_api = ensure_usd_api(particle_system.GetPrim(), lazy.pxr.PhysxSchema.PhysxParticleAnisotropyAPI)
63
+
64
+ if smoothing:
65
+ # apply api and use all defaults
66
+ ensure_usd_api(particle_system.GetPrim(), lazy.pxr.PhysxSchema.PhysxParticleSmoothingAPI)
67
+
68
+ if isosurface:
69
+ # apply api and use all defaults
70
+ ensure_usd_api(particle_system.GetPrim(), lazy.pxr.PhysxSchema.PhysxParticleIsosurfaceAPI)
71
+
72
+ with og.sim.editing_usd():
73
+ # Make sure we're not casting shadows
74
+ primVarsApi = lazy.pxr.UsdGeom.PrimvarsAPI(particle_system.GetPrim())
75
+ primVarsApi.CreatePrimvar("doNotCastShadows", lazy.pxr.Sdf.ValueTypeNames.Bool).Set(True)
76
+ # tweak anisotropy min, max, and scale to work better with isosurface:
77
+ if anisotropy:
78
+ ani_api.CreateScaleAttr().Set(5.0)
79
+ ani_api.CreateMinAttr().Set(1.0) # avoids gaps in surface
80
+ ani_api.CreateMaxAttr().Set(2.0)
81
+
82
+ return particle_system
83
+
84
+
85
+ def bind_material(prim_path, material_path):
86
+ """
87
+ Binds material located at @material_path to the prim located at @prim_path.
88
+
89
+ Args:
90
+ prim_path (str): Stage path to prim to bind material to
91
+ material_path (str): Stage path to material to be bound
92
+ """
93
+ with og.sim.editing_usd():
94
+ lazy.omni.kit.commands.execute(
95
+ "BindMaterialCommand",
96
+ prim_path=prim_path,
97
+ material_path=material_path,
98
+ strength=None,
99
+ )
100
+
101
+
102
+ def create_physx_particleset_pointinstancer(
103
+ name,
104
+ particle_system_path,
105
+ physx_particle_system_path,
106
+ prototype_prim_paths,
107
+ particle_group,
108
+ positions,
109
+ self_collision=True,
110
+ fluid=False,
111
+ particle_mass=None,
112
+ particle_density=None,
113
+ orientations=None,
114
+ velocities=None,
115
+ angular_velocities=None,
116
+ scales=None,
117
+ prototype_indices=None,
118
+ enabled=True,
119
+ ):
120
+ """
121
+ Creates a particle set instancer based on a UsdGeom.PointInstancer at @prim_path on the current stage, with
122
+ the specified parameters.
123
+
124
+ Args:
125
+ name (str): Name for this point instancer
126
+ particle_system_path (str): Stage path to particle system (Scope)
127
+ physx_particle_system_path (str): Stage path to physx particle system (PhysxParticleSystem)
128
+ prototype_prim_paths (list of str): Stage path(s) to the prototypes to reference for this particle set.
129
+ particle_group (int): ID for this particle set. Particles from different groups will automatically collide
130
+ with each other. Particles in the same group will have collision behavior dictated by @self_collision
131
+ positions (list of 3-tuple or th.tensor): Particle (x,y,z) positions either as a list or a (N, 3) numpy array
132
+ self_collision (bool): Whether to enable particle-particle collision within the set
133
+ (as defined by @particle_group) or not
134
+ fluid (bool): Whether to simulated the particle set as fluid or not
135
+ particle_mass (None or float): If specified, should be per-particle mass. Otherwise, will be
136
+ inferred from @density. Note: Either @particle_mass or @particle_density must be specified!
137
+ particle_density (None or float): If specified, should be per-particle density and is used to compute total
138
+ point set mass. Otherwise, will be inferred from @density. Note: Either @particle_mass or
139
+ @particle_density must be specified!
140
+ orientations (None or list of 4-array or th.tensor): Particle (x,y,z,w) quaternion orientations, either as a
141
+ list or a (N, 4) numpy array. If not specified, all will be set to canonical orientation (0, 0, 0, 1)
142
+ velocities (None or list of 3-array or th.tensor): Particle (x,y,z) velocities either as a list or a (N, 3)
143
+ numpy array. If not specified, all will be set to 0
144
+ angular_velocities (None or list of 3-array or th.tensor): Particle (x,y,z) angular velocities either as a
145
+ list or a (N, 3) numpy array. If not specified, all will be set to 0
146
+ scales (None or list of 3-array or th.tensor): Particle (x,y,z) scales either as a list or a (N, 3)
147
+ numpy array. If not specified, all will be set to 1.0
148
+ prototype_indices (None or list of int): If specified, should specify which prototype should be used for
149
+ each particle. If None, will use all 0s (i.e.: the first prototype created)
150
+ enabled (bool): Whether to enable this particle instancer. If not enabled, then no physics will be used
151
+
152
+ Returns:
153
+ UsdGeom.PointInstancer: Created point instancer prim
154
+ """
155
+ with og.sim.editing_usd():
156
+ stage = og.sim.stage
157
+ n_particles = len(positions)
158
+ particle_system = lazy.isaacsim.core.utils.prims.get_prim_at_path(physx_particle_system_path)
159
+
160
+ # Create point instancer scope
161
+ prim_path = f"{particle_system_path}/{name}"
162
+ assert not stage.GetPrimAtPath(
163
+ prim_path
164
+ ), f"Cannot create an instancer scope, scope already exists at {prim_path}!"
165
+ stage.DefinePrim(prim_path, "Scope")
166
+
167
+ # Create point instancer
168
+ instancer_prim_path = f"{prim_path}/instancer"
169
+ assert not stage.GetPrimAtPath(
170
+ instancer_prim_path
171
+ ), f"Cannot create a PointInstancer prim, prim already exists at {instancer_prim_path}!"
172
+ instancer = lazy.pxr.UsdGeom.PointInstancer.Define(stage, instancer_prim_path)
173
+
174
+ is_isosurface = (
175
+ particle_system.HasAPI(lazy.pxr.PhysxSchema.PhysxParticleIsosurfaceAPI)
176
+ and particle_system.GetAttribute("physxParticleIsosurface:isosurfaceEnabled").Get()
177
+ )
178
+
179
+ # Add prototype mesh prim paths to the prototypes relationship attribute for this point set
180
+ # We need to make copies of prototypes for each instancer currently because particles won't render properly
181
+ # if multiple instancers share the same prototypes for some reason
182
+ mesh_list = instancer.GetPrototypesRel()
183
+ prototype_prims = []
184
+ for i, original_path in enumerate(prototype_prim_paths):
185
+ prototype_prim_path = f"{prim_path}/prototype{i}"
186
+ lazy.omni.kit.commands.execute("CopyPrim", path_from=original_path, path_to=prototype_prim_path)
187
+ prototype_prim = lazy.isaacsim.core.utils.prims.get_prim_at_path(prototype_prim_path)
188
+ # Make sure this prim is invisible if we're using isosurface, and vice versa.
189
+ imageable = lazy.pxr.UsdGeom.Imageable(prototype_prim)
190
+ if is_isosurface:
191
+ imageable.MakeInvisible()
192
+ else:
193
+ imageable.MakeVisible()
194
+
195
+ # Move the prototype to the graveyard position so that it won't be visible to the agent
196
+ # We can't directly hide the prototype because it will also hide all the generated particles (if not isosurface)
197
+ prototype_prim.GetAttribute("xformOp:translate").Set(m.PROTOTYPE_GRAVEYARD_POS)
198
+
199
+ mesh_list.AddTarget(lazy.pxr.Sdf.Path(prototype_prim_path))
200
+ prototype_prims.append(prototype_prim)
201
+
202
+ # Set particle instance default data
203
+ prototype_indices = [0] * n_particles if prototype_indices is None else prototype_indices
204
+ if orientations is None:
205
+ orientations = th.zeros((n_particles, 4))
206
+ orientations[:, -1] = 1.0
207
+ orientations = th.tensor(orientations) if not isinstance(orientations, th.Tensor) else orientations
208
+ orientations = orientations[:, [3, 0, 1, 2]] # x,y,z,w --> w,x,y,z
209
+ velocities = th.zeros((n_particles, 3)) if velocities is None else velocities
210
+ angular_velocities = th.zeros((n_particles, 3)) if angular_velocities is None else angular_velocities
211
+ scales = th.ones((n_particles, 3)) if scales is None else scales
212
+ assert (
213
+ particle_mass is not None or particle_density is not None
214
+ ), "Either particle mass or particle density must be specified when creating particle instancer!"
215
+ particle_mass = 0.0 if particle_mass is None else particle_mass
216
+ particle_density = 0.0 if particle_density is None else particle_density
217
+
218
+ # Set particle states
219
+ instancer.GetProtoIndicesAttr().Set(prototype_indices)
220
+ instancer.GetPositionsAttr().Set(lazy.pxr.Vt.Vec3fArray(positions.tolist()))
221
+ instancer.GetOrientationsAttr().Set(lazy.pxr.Vt.QuathArray.FromNumpy(orientations.cpu().numpy()))
222
+ instancer.GetVelocitiesAttr().Set(lazy.pxr.Vt.Vec3fArray(velocities.tolist()))
223
+ instancer.GetAngularVelocitiesAttr().Set(lazy.pxr.Vt.Vec3fArray(angular_velocities.tolist()))
224
+ instancer.GetScalesAttr().Set(lazy.pxr.Vt.Vec3fArray(scales.tolist()))
225
+
226
+ # Take a render step to "lock" the visuals of the prototypes at the graveyard position
227
+ # This needs to happen AFTER setting particle states
228
+ # We suppress a known warning that we have no control over where omni complains about a prototype
229
+ # not being populated yet
230
+ with suppress_omni_log(channels=["omni.hydra.scene_delegate.plugin"]):
231
+ og.sim.render()
232
+
233
+ # Then we move the prototypes back to zero offset because otherwise all the generated particles will be offset by
234
+ # the graveyard position. At this point, the prototypes themselves no longer appear at the zero offset (locked at
235
+ # the graveyard position), which is desirable because we don't want the agent to see the prototypes themselves.
236
+ for prototype_prim in prototype_prims:
237
+ prototype_prim.GetAttribute("xformOp:translate").Set((0.0, 0.0, 0.0))
238
+
239
+ instancer_prim = instancer.GetPrim()
240
+
241
+ lazy.omni.physx.scripts.particleUtils.configure_particle_set(
242
+ instancer_prim,
243
+ physx_particle_system_path,
244
+ self_collision,
245
+ fluid,
246
+ particle_group,
247
+ particle_mass * n_particles,
248
+ particle_density,
249
+ )
250
+
251
+ # Set whether the instancer is enabled or not
252
+ instancer_prim.GetAttribute("physxParticle:particleEnabled").Set(enabled)
253
+
254
+ # Render three more times to fully propagate changes
255
+ # Omni always complains about a low-level USD thing we have no control over
256
+ # so we suppress the warnings
257
+ with suppress_omni_log(channels=["omni.usd"]):
258
+ for i in range(3):
259
+ og.sim.render()
260
+
261
+ # Isosurfaces require an additional physics timestep before they're actually rendered
262
+ if is_isosurface:
263
+ og.log.warning(
264
+ f"Creating an instancer that uses isosurface {instancer_prim_path}. "
265
+ f"The rendering of these particles will have a delay of one timestep."
266
+ )
267
+
268
+ return instancer_prim
269
+
270
+
271
+ def apply_force_at_pos(prim, force, pos):
272
+ if isinstance(force, th.Tensor):
273
+ force = force.cpu().numpy()
274
+ if isinstance(pos, th.Tensor):
275
+ pos = pos.cpu().numpy()
276
+ prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(prim.prim_path)
277
+ og.sim.psi.apply_force_at_pos(og.sim.stage_id, prim_id, force, pos)
278
+
279
+
280
+ def apply_torque(prim, foward_vect, roll_torque_scalar):
281
+ if isinstance(foward_vect, th.Tensor):
282
+ foward_vect = foward_vect.cpu().numpy()
283
+ prim_id = lazy.pxr.PhysicsSchemaTools.sdfPathToInt(prim.prim_path)
284
+ og.sim.psi.apply_torque(og.sim.stage_id, prim_id, foward_vect * roll_torque_scalar)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/processing_utils.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as th
2
+
3
+ from omnigibson.utils.backend_utils import _compute_backend as cb
4
+ from omnigibson.utils.python_utils import Serializable
5
+
6
+
7
+ class Filter(Serializable):
8
+ """
9
+ A base class for filtering a noisy data stream in an online fashion.
10
+
11
+ Implementations store state as compute-backend arrays (``cb.arr_type``) and accept observations
12
+ as ``cb`` arrays, torch tensors, or Python sequences (converted at the call boundary).
13
+ """
14
+
15
+ def estimate(self, observation):
16
+ """
17
+ Takes an observation and returns a de-noised estimate.
18
+
19
+ Args:
20
+ observation: Current observation, cb.arr_type.
21
+
22
+ Returns:
23
+ cb.arr_type: De-noised estimate.
24
+ """
25
+ raise NotImplementedError
26
+
27
+ def reset(self):
28
+ """
29
+ Resets this filter. Default is no-op.
30
+ """
31
+ pass
32
+
33
+ def _dump_state(self):
34
+ # Default is no state (empty dict)
35
+ return dict()
36
+
37
+ def _load_state(self, state):
38
+ # Default is no state (empty dict), so this is a no-op
39
+ pass
40
+
41
+ def serialize(self, state):
42
+ # Default is no state, so do nothing
43
+ return th.empty(0, dtype=th.float32)
44
+
45
+ def deserialize(self, state):
46
+ # Default is no state, so do nothing
47
+ return dict(), 0
48
+
49
+ @property
50
+ def state_size(self):
51
+ """
52
+ Size of the serialized state of this filter
53
+ """
54
+ raise NotImplementedError
55
+
56
+
57
+ class MovingAverageFilter(Filter):
58
+ """
59
+ This class uses a moving average to de-noise a noisy data stream in an online fashion.
60
+ This is a FIR filter.
61
+
62
+ Supports a batch of n_members independent filter rows. Each member has its own circular
63
+ buffer row; estimate() targets one member, estimate_batch() processes all rows at once
64
+ using matrix operations and broadcasting with no intermediate large allocations.
65
+
66
+ Internal buffers are compute-backend arrays (``cb``). The per-member ``fully_filled`` row uses
67
+ ``cb.bool_zeros`` / ``cb.logical_or``. Serialized / dumped state uses torch tensors (``cb.to_torch``);
68
+ loads convert incoming torch tensors back to ``cb``.
69
+ """
70
+
71
+ def __init__(self, obs_dim, filter_width, n_members=1):
72
+ """
73
+ Args:
74
+ obs_dim (int): The dimension of the points to filter.
75
+ filter_width (int): The number of past samples to take the moving average over.
76
+ n_members (int): Number of independent filter rows (one per controller member). Defaults to 1.
77
+ """
78
+ self.obs_dim = obs_dim
79
+ assert filter_width > 0, f"MovingAverageFilter must have a non-zero size! Got: {filter_width}"
80
+ self.filter_width = filter_width
81
+ self.n_members = n_members
82
+ # (n_members, filter_width, obs_dim) — unfilled slots stay zero so sum/count gives correct mean
83
+ self.past_samples = cb.zeros((n_members, filter_width, obs_dim))
84
+ self.current_idx = cb.int_array([0] * n_members)
85
+ # True once the circular buffer has wrapped at least once for that member
86
+ self.fully_filled = cb.bool_zeros(n_members)
87
+ # cached row indices to avoid re-allocating in estimate_batch
88
+ self._member_arange = cb.arange(n_members)
89
+
90
+ super().__init__()
91
+
92
+ def add_member(self, slot):
93
+ """Register a member at the given slot index.
94
+
95
+ If slot < n_members the slot is being reused (tombstone reuse): its buffer is cleared
96
+ in-place and n_members is unchanged. If slot == n_members a new row is appended.
97
+
98
+ Args:
99
+ slot (int): Slot index as determined by the controller's add_member (either a
100
+ previously tombstoned index or the next new index == current n_members).
101
+ """
102
+ if slot < self.n_members:
103
+ # Reuse: clear the slot so it starts fresh
104
+ self.past_samples[slot] *= 0.0
105
+ self.current_idx[slot] = 0
106
+ self.fully_filled[slot] = False
107
+ # n_members and _member_arange stay the same — slot count is unchanged
108
+ return
109
+ # New slot: append a fresh row
110
+ self.past_samples = cb.cat([self.past_samples, cb.zeros((1, self.filter_width, self.obs_dim))], dim=0)
111
+ self.current_idx = cb.cat([self.current_idx, cb.int_array([0])], dim=0)
112
+ self.fully_filled = cb.cat([self.fully_filled, cb.bool_zeros(1)], dim=0)
113
+ # rebuild arange to include the new member
114
+ self._member_arange = cb.arange(self.n_members + 1)
115
+ self.n_members += 1
116
+
117
+ def unregister_member(self, member_idx):
118
+ """Zero a member's buffer when it is unregistered (tombstoned at the controller level).
119
+
120
+ Args:
121
+ member_idx (int): Index of the member to unregister.
122
+ """
123
+ self.past_samples[member_idx] *= 0.0
124
+ self.current_idx[member_idx] = 0
125
+ self.fully_filled[member_idx] = False
126
+
127
+ def estimate(self, member_idx, observation):
128
+ """
129
+ Do an online hold for state estimation given a recent observation for one member.
130
+
131
+ Args:
132
+ member_idx (int): Index of the controller member whose row to update.
133
+ observation: New observation of shape (obs_dim,) as ``cb``, torch, or sequence.
134
+
135
+ Returns:
136
+ cb.arr_type: New estimate of state.
137
+ """
138
+ idx = int(cb.to_torch(self.current_idx[member_idx]).item())
139
+ self.past_samples[member_idx, idx, :] = observation
140
+
141
+ # Compute value based on whether we're fully filled or not
142
+ if not cb.item_bool(self.fully_filled[member_idx]):
143
+ val = cb.mean(self.past_samples[member_idx, : idx + 1, :], dim=0)
144
+ # Denote that we're fully filled if we're at the end of the buffer
145
+ if idx == self.filter_width - 1:
146
+ self.fully_filled[member_idx] = True
147
+ else:
148
+ val = cb.mean(self.past_samples[member_idx], dim=0)
149
+
150
+ # Increment the index to write the next sample to
151
+ self.current_idx[member_idx] = (idx + 1) % self.filter_width
152
+ return val
153
+
154
+ def estimate_batch(self, observations):
155
+ """
156
+ Process all N member rows at once using batched matrix operations.
157
+
158
+ Unfilled slots in past_samples are zero, so sum(dim=1) / fill_count gives the correct
159
+ per-member mean without any masking matrix. Broadcasting is used throughout to avoid
160
+ allocating intermediate large tensors.
161
+
162
+ Args:
163
+ observations: (N, obs_dim) new observations for all members, cb.arr_type.
164
+
165
+ Returns:
166
+ cb.arr_type: (N, obs_dim) smoothed estimates.
167
+ """
168
+ # Write new observations in-place via advanced indexing — no new large tensor
169
+ self.past_samples[self._member_arange, self.current_idx] = observations
170
+
171
+ fill_count = cb.where(self.fully_filled, float(self.filter_width), self.current_idx + 1.0)
172
+
173
+ sample_sums = cb.sum(self.past_samples, dim=1)
174
+ fill_bc = cb.view(fill_count, (-1, 1))
175
+ vals = sample_sums / fill_bc
176
+
177
+ hit_end = self.current_idx == (self.filter_width - 1)
178
+ self.fully_filled = cb.logical_or(self.fully_filled, hit_end)
179
+
180
+ # Advance circular buffer pointer in-place
181
+ self.current_idx = cb.as_int(self.current_idx + 1)
182
+ self.current_idx = cb.as_int(self.current_idx % self.filter_width)
183
+
184
+ return vals
185
+
186
+ def reset(self, member_idx=None):
187
+ """
188
+ Reset one member's filter row, or all rows if member_idx is None.
189
+
190
+ Args:
191
+ member_idx (int or None): Member to reset. Resets all members if None.
192
+ """
193
+ if member_idx is None:
194
+ self.past_samples *= 0.0
195
+ self.current_idx *= 0
196
+ self.fully_filled = cb.bool_zeros(self.n_members)
197
+ else:
198
+ self.past_samples[member_idx] *= 0.0
199
+ self.current_idx[member_idx] = 0
200
+ self.fully_filled[member_idx] = False
201
+
202
+ @property
203
+ def state_size(self):
204
+ return self.filter_width * self.obs_dim + 2
205
+
206
+ def dump_state(self, controller_idx, serialized=False):
207
+ state = self._dump_state(controller_idx)
208
+ return self.serialize(state, controller_idx) if serialized else state
209
+
210
+ def _dump_state(self, controller_idx):
211
+ return {
212
+ "past_samples": cb.to_torch(self.past_samples[controller_idx]),
213
+ "current_idx": cb.item_int(self.current_idx[controller_idx]),
214
+ "fully_filled": cb.item_bool(self.fully_filled[controller_idx]),
215
+ }
216
+
217
+ def load_state(self, controller_idx, state, serialized=False):
218
+ if serialized:
219
+ orig_state_len = len(state)
220
+ state, deserialized_items = self.deserialize(state, controller_idx)
221
+ assert deserialized_items == orig_state_len, (
222
+ f"Invalid state deserialization occurred! Expected {orig_state_len} total "
223
+ f"values to be deserialized, only {deserialized_items} were."
224
+ )
225
+ self._load_state(controller_idx, state)
226
+
227
+ def _load_state(self, controller_idx, state):
228
+ self.past_samples[controller_idx] = cb.from_torch(state["past_samples"])
229
+ self.current_idx[controller_idx] = state["current_idx"]
230
+ self.fully_filled[controller_idx] = state["fully_filled"]
231
+
232
+ def serialize(self, state, controller_idx):
233
+ return th.cat(
234
+ [
235
+ state["past_samples"].flatten(),
236
+ th.tensor([state["current_idx"]], dtype=th.float32),
237
+ th.tensor([state["fully_filled"]], dtype=th.float32),
238
+ ]
239
+ )
240
+
241
+ def deserialize(self, state, controller_idx):
242
+ samples_len = self.filter_width * self.obs_dim
243
+ state_dict = {
244
+ "past_samples": state[:samples_len].reshape(self.filter_width, self.obs_dim),
245
+ "current_idx": int(state[samples_len].item()),
246
+ "fully_filled": bool(state[samples_len + 1].item()),
247
+ }
248
+ return state_dict, samples_len + 2
249
+
250
+
251
+ class ExponentialAverageFilter(Filter):
252
+ """
253
+ This class uses an exponential average of the form y_n = alpha * x_n + (1 - alpha) * y_{n - 1}.
254
+ This is an IIR filter.
255
+ """
256
+
257
+ def __init__(self, obs_dim, alpha=0.9):
258
+ """
259
+
260
+ Args:
261
+ obs_dim (int): The dimension of the points to filter.
262
+ alpha (float): The relative weighting of new samples relative to older samples
263
+ """
264
+ self.obs_dim = obs_dim
265
+ self.avg = cb.zeros(obs_dim)
266
+ self.num_samples = 0
267
+ self.alpha = alpha
268
+
269
+ super().__init__()
270
+
271
+ def estimate(self, observation):
272
+ """
273
+ Do an online hold for state estimation given a recent observation.
274
+
275
+ Args:
276
+ observation: New observation, cb.arr_type.
277
+
278
+ Returns:
279
+ cb.arr_type: New estimate of state.
280
+ """
281
+ self.avg = self.alpha * observation + (1.0 - self.alpha) * self.avg
282
+ self.num_samples += 1
283
+
284
+ return cb.copy(self.avg)
285
+
286
+ def reset(self):
287
+ # Clear internal state
288
+ self.avg *= 0.0
289
+ self.num_samples = 0
290
+
291
+ @property
292
+ def state_size(self):
293
+ # This is the size of the internal value as well as a num samples
294
+ return len(self.avg) + 1
295
+
296
+ def _dump_state(self):
297
+ # Run super init first
298
+ state = super()._dump_state()
299
+
300
+ # Add info from this filter
301
+ state["avg"] = cb.to_torch(self.avg)
302
+ state["num_samples"] = self.num_samples
303
+
304
+ return state
305
+
306
+ def _load_state(self, state):
307
+ # Run super first
308
+ super()._load_state(state=state)
309
+
310
+ # Load relevant info for this filter
311
+ self.avg = cb.from_torch(state["avg"])
312
+ self.num_samples = state["num_samples"]
313
+
314
+ def serialize(self, state):
315
+ # Run super first
316
+ state_flat = super().serialize(state=state)
317
+
318
+ # Serialize state for this filter
319
+ return th.cat(
320
+ [
321
+ state_flat,
322
+ state["avg"],
323
+ [state["num_samples"]],
324
+ ]
325
+ )
326
+
327
+ def deserialize(self, state):
328
+ # Run super first
329
+ state_dict, idx = super().deserialize(state=state)
330
+
331
+ # Deserialize state for this filter
332
+ state_dict["avg"] = state[idx : idx + self.obs_dim]
333
+ state_dict["num_samples"] = int(state[idx + self.obs_dim])
334
+
335
+ return state_dict, idx + self.obs_dim + 1
336
+
337
+
338
+ class Subsampler:
339
+ """
340
+ A base class for subsampling a data stream in an online fashion.
341
+ """
342
+
343
+ def subsample(self, observation):
344
+ """
345
+ Takes an observation and returns the observation, or None, which
346
+ corresponds to deleting the observation.
347
+
348
+ Args:
349
+ observation (n-array): A current observation.
350
+
351
+ Returns:
352
+ None or n-array: No observation if subsampled, otherwise the observation
353
+ """
354
+ raise NotImplementedError
355
+
356
+
357
+ class UniformSubsampler(Subsampler):
358
+ """
359
+ A class for subsampling a data stream uniformly in time in an online fashion.
360
+ """
361
+
362
+ def __init__(self, T):
363
+ """
364
+ Args:
365
+ T (int): Pick one every T observations.
366
+ """
367
+ self.T = T
368
+ self.counter = 0
369
+
370
+ super(UniformSubsampler, self).__init__()
371
+
372
+ def subsample(self, observation):
373
+ """
374
+ Returns an observation once every T observations, None otherwise.
375
+
376
+ Args:
377
+ observation (n-array): A current observation.
378
+
379
+ Returns:
380
+ None or n-array: The observation, or None.
381
+ """
382
+ self.counter += 1
383
+ if self.counter == self.T:
384
+ self.counter = 0
385
+ return observation
386
+ return None
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/profiling_utils.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from cProfile import Profile as CProfile
3
+ from time import perf_counter
4
+
5
+ import psutil
6
+
7
+ import omnigibson.utils.pynvml_utils as pynvml
8
+
9
+
10
+ class Profiler:
11
+ """
12
+ Lightweight profiler that tracks wall-clock timing across enable/disable cycles.
13
+
14
+ Used by the Simulator's `with_profiler` decorator. Each enable/disable pair records
15
+ one timing sample. Callers can read cumulative or per-call averages at any time.
16
+
17
+ Optionally wraps a cProfile.Profile for deep (function-level) profiling when
18
+ gm.ENABLE_DEEP_PROFILING is set.
19
+ """
20
+
21
+ def __init__(self, deep=False):
22
+ self._total_time = 0.0
23
+ self._call_count = 0
24
+ self._start = None
25
+ self._last_dt = 0.0
26
+ self._cprofiler = CProfile() if deep else None
27
+
28
+ def enable(self):
29
+ if self._cprofiler is not None:
30
+ self._cprofiler.enable()
31
+ self._start = perf_counter()
32
+
33
+ def disable(self):
34
+ dt = perf_counter() - self._start
35
+ if self._cprofiler is not None:
36
+ self._cprofiler.disable()
37
+ self._last_dt = dt
38
+ self._total_time += dt
39
+ self._call_count += 1
40
+
41
+ @property
42
+ def last_dt(self):
43
+ """Wall-clock seconds for the most recent enable/disable pair."""
44
+ return self._last_dt
45
+
46
+ @property
47
+ def total_time(self):
48
+ """Cumulative wall-clock seconds across all recorded calls."""
49
+ return self._total_time
50
+
51
+ @property
52
+ def call_count(self):
53
+ """Number of completed enable/disable cycles."""
54
+ return self._call_count
55
+
56
+ @property
57
+ def average_time(self):
58
+ """Average wall-clock seconds per call, or 0 if no calls recorded."""
59
+ return self._total_time / self._call_count if self._call_count > 0 else 0.0
60
+
61
+ def reset(self):
62
+ """Clear all accumulated timing data (does not affect the cProfile profiler)."""
63
+ self._total_time = 0.0
64
+ self._call_count = 0
65
+ self._last_dt = 0.0
66
+
67
+ def dump_stats(self, filename):
68
+ """Dump cProfile stats to a file (no-op if deep profiling is disabled)."""
69
+ if self._cprofiler is not None:
70
+ self._cprofiler.dump_stats(filename)
71
+
72
+
73
+ # Method copied from: https://github.com/wandb/wandb/blob/main/wandb/sdk/internal/system/assets/gpu.py
74
+ def gpu_in_use_by_this_process(gpu_handle, pid: int) -> bool:
75
+ if psutil is None:
76
+ return False
77
+
78
+ try:
79
+ base_process = psutil.Process(pid=pid)
80
+ except psutil.NoSuchProcess:
81
+ return False
82
+
83
+ our_processes = base_process.children(recursive=True)
84
+ our_processes.append(base_process)
85
+
86
+ our_pids = {process.pid for process in our_processes}
87
+
88
+ compute_pids = {process.pid for process in pynvml.nvmlDeviceGetComputeRunningProcesses(gpu_handle)}
89
+ graphics_pids = {process.pid for process in pynvml.nvmlDeviceGetGraphicsRunningProcesses(gpu_handle)}
90
+
91
+ pids_using_device = compute_pids | graphics_pids
92
+
93
+ return len(pids_using_device & our_pids) > 0
94
+
95
+
96
+ def get_vram_usage():
97
+ """Get VRAM usage in GB for the GPU used by this process."""
98
+ pynvml.nvmlInit()
99
+ device_count = pynvml.nvmlDeviceGetCount()
100
+ vram_usage = 0.0
101
+ for i in range(device_count):
102
+ handle = pynvml.nvmlDeviceGetHandleByIndex(i)
103
+ if gpu_in_use_by_this_process(handle, os.getpid()):
104
+ vram_usage = pynvml.nvmlDeviceGetMemoryInfo(handle).used / 1024**3
105
+ break
106
+ pynvml.nvmlShutdown()
107
+ return vram_usage
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/pynvml_utils.py ADDED
The diff for this file is too large to render. See raw diff
 
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/python_utils.py ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of utility functions for general python usage
3
+ """
4
+
5
+ import inspect
6
+ from abc import ABCMeta
7
+ from collections.abc import Iterable
8
+ from copy import deepcopy
9
+ from functools import wraps
10
+ from hashlib import md5
11
+ from importlib import import_module
12
+ import sys
13
+
14
+ import h5py
15
+ import torch as th
16
+
17
+ # Global dictionary storing all unique names
18
+ NAMES = set()
19
+ CLASS_NAMES = set()
20
+
21
+
22
+ class classproperty:
23
+ def __init__(self, fget):
24
+ self.fget = fget
25
+
26
+ def __get__(self, owner_self, owner_cls):
27
+ return self.fget(owner_cls)
28
+
29
+
30
+ def subclass_factory(name, base_classes, __init__=None, **kwargs):
31
+ """
32
+ Programmatically generates a new class type with name @name, subclassing from base classes @base_classes, with
33
+ corresponding __init__ call @__init__.
34
+
35
+ NOTE: If __init__ is None (default), the __init__ call from @base_classes will be used instead.
36
+
37
+ cf. https://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class
38
+
39
+ Args:
40
+ name (str): Generated class name
41
+ base_classes (type, or list of type): Base class(es) to use for generating the subclass
42
+ __init__ (None or function): Init call to use for the base class when it is instantiated. If None if specified,
43
+ the newly generated class will automatically inherit the __init__ call from @base_classes
44
+ **kwargs (any): keyword-mapped parameters to override / set in the child class, where the keys represent
45
+ the class / instance attribute to modify and the values represent the functions / value to set
46
+ """
47
+ # Standardize base_classes
48
+ base_classes = tuple(base_classes if isinstance(base_classes, Iterable) else [base_classes])
49
+
50
+ # Generate the new class
51
+ if __init__ is not None:
52
+ kwargs["__init__"] = __init__
53
+ return type(name, base_classes, kwargs)
54
+
55
+
56
+ def save_init_info(func):
57
+ """
58
+ Decorator to save the init info of an object to object._init_info.
59
+
60
+ _init_info contains class name and class constructor's input args.
61
+ """
62
+ sig = inspect.signature(func)
63
+
64
+ @wraps(func) # preserve func name, docstring, arguments list, etc.
65
+ def wrapper(self, *args, **kwargs):
66
+ values = sig.bind(self, *args, **kwargs)
67
+
68
+ # Prevent args of super init from being saved.
69
+ if hasattr(self, "_init_info"):
70
+ func(*values.args, **values.kwargs)
71
+ return
72
+
73
+ # Initialize class's self._init_info.
74
+ self._init_info = {}
75
+ self._init_info["class_module"] = self.__class__.__module__
76
+ self._init_info["class_name"] = self.__class__.__name__
77
+ self._init_info["args"] = {}
78
+
79
+ # Populate class's self._init_info.
80
+ for k, p in sig.parameters.items():
81
+ if k == "self":
82
+ continue
83
+ if k in values.arguments:
84
+ val = values.arguments[k]
85
+ if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY):
86
+ self._init_info["args"][k] = val
87
+ elif p.kind == inspect.Parameter.VAR_KEYWORD:
88
+ for kwarg_k, kwarg_val in values.arguments[k].items():
89
+ self._init_info["args"][kwarg_k] = kwarg_val
90
+
91
+ # Call the original function.
92
+ func(*values.args, **values.kwargs)
93
+
94
+ return wrapper
95
+
96
+
97
+ class RecreatableMeta(type):
98
+ """
99
+ Simple metaclass that automatically saves __init__ args of the instances it creates.
100
+ """
101
+
102
+ def __new__(cls, clsname, bases, clsdict):
103
+ if "__init__" in clsdict:
104
+ clsdict["__init__"] = save_init_info(clsdict["__init__"])
105
+ return super().__new__(cls, clsname, bases, clsdict)
106
+
107
+
108
+ class RecreatableAbcMeta(RecreatableMeta, ABCMeta):
109
+ """
110
+ A composite metaclass of both RecreatableMeta and ABCMeta.
111
+
112
+ Adding in ABCMeta to resolve metadata conflicts.
113
+ """
114
+
115
+ pass
116
+
117
+
118
+ class Recreatable(metaclass=RecreatableAbcMeta):
119
+ """
120
+ Simple class that provides an abstract interface automatically saving __init__ args of
121
+ the classes inheriting it.
122
+ """
123
+
124
+ def get_init_info(self):
125
+ """
126
+ Grabs relevant initialization information for this class instance. Useful for directly
127
+ reloading an object from this information, using @create_object_from_init_info.
128
+
129
+ Returns:
130
+ dict: Nested dictionary that contains this object's initialization information
131
+ """
132
+ # Note: self._init_info is procedurally generated via @save_init_info called in metaclass
133
+ return self._init_info
134
+
135
+
136
+ def create_object_from_init_info(init_info):
137
+ """
138
+ Create a new object based on given init info.
139
+
140
+ Args:
141
+ init_info (dict): Nested dictionary that contains an object's init information.
142
+
143
+ Returns:
144
+ any: Newly created object.
145
+ """
146
+ module = import_module(init_info["class_module"])
147
+ cls = getattr(module, init_info["class_name"])
148
+ return cls(**init_info["args"], **init_info.get("kwargs", {}))
149
+
150
+
151
+ def safe_equal(a, b):
152
+ if isinstance(a, th.Tensor) and isinstance(b, th.Tensor):
153
+ return a.shape == b.shape and (a == b).all().item()
154
+ elif isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
155
+ return len(a) == len(b) and all(safe_equal(a_item, b_item) for a_item, b_item in zip(a, b))
156
+ else:
157
+ return a == b
158
+
159
+
160
+ def merge_nested_dicts(base_dict, extra_dict, inplace=False, verbose=False):
161
+ """
162
+ Iteratively updates @base_dict with values from @extra_dict. Note: This generates a new dictionary!
163
+
164
+ Args:
165
+ base_dict (dict): Nested base dictionary, which should be updated with all values from @extra_dict
166
+ extra_dict (dict): Nested extra dictionary, whose values will overwrite corresponding ones in @base_dict
167
+ inplace (bool): Whether to modify @base_dict in place or not
168
+ verbose (bool): If True, will print when keys are mismatched
169
+
170
+ Returns:
171
+ dict: Updated dictionary
172
+ """
173
+ # Loop through all keys in @extra_dict and update the corresponding values in @base_dict
174
+ base_dict = base_dict if inplace else deepcopy(base_dict)
175
+ for k, v in extra_dict.items():
176
+ if k not in base_dict:
177
+ base_dict[k] = v
178
+ else:
179
+ if isinstance(v, dict) and isinstance(base_dict[k], dict):
180
+ base_dict[k] = merge_nested_dicts(base_dict[k], v)
181
+ else:
182
+ equal = safe_equal(base_dict[k], v)
183
+ if not equal and verbose:
184
+ print(f"Different values for key {k}: {base_dict[k]}, {v}\n")
185
+ base_dict[k] = v
186
+
187
+ # Return new dict
188
+ return base_dict
189
+
190
+
191
+ def get_class_init_kwargs(cls):
192
+ """
193
+ Helper function to return a list of all valid keyword arguments (excluding "self") for the given @cls class.
194
+
195
+ Args:
196
+ cls (object): Class from which to grab __init__ kwargs
197
+
198
+ Returns:
199
+ list: All keyword arguments (excluding "self") specified by @cls __init__ constructor method
200
+ """
201
+ # Fall back to signature inspection for regular classes
202
+ return list(inspect.signature(cls.__init__).parameters.keys())[1:]
203
+
204
+
205
+ def extract_subset_dict(dic, keys, copy=False):
206
+ """
207
+ Helper function to extract a subset of dictionary key-values from a current dictionary. Optionally (deep)copies
208
+ the values extracted from the original @dic if @copy is True.
209
+
210
+ Args:
211
+ dic (dict): Dictionary containing multiple key-values
212
+ keys (Iterable): Specific keys to extract from @dic. If the key doesn't exist in @dic, then the key is skipped
213
+ copy (bool): If True, will deepcopy all values corresponding to the specified @keys
214
+
215
+ Returns:
216
+ dict: Extracted subset dictionary containing only the specified @keys and their corresponding values
217
+ """
218
+ subset = {k: dic[k] for k in keys if k in dic}
219
+ return deepcopy(subset) if copy else subset
220
+
221
+
222
+ def extract_class_init_kwargs_from_dict(cls, dic, copy=False):
223
+ """
224
+ Helper function to return a dictionary of key-values that specifically correspond to @cls class's __init__
225
+ constructor method, from @dic which may or may not contain additional, irrelevant kwargs.
226
+ Note that @dic may possibly be missing certain kwargs as specified by cls.__init__. No error will be raised.
227
+
228
+ Args:
229
+ cls (object): Class from which to grab __init__ kwargs that will be be used as filtering keys for @dic
230
+ dic (dict): Dictionary containing multiple key-values
231
+ copy (bool): If True, will deepcopy all values corresponding to the specified @keys
232
+
233
+ Returns:
234
+ dict: Extracted subset dictionary possibly containing only the specified keys from cls.__init__ and their
235
+ corresponding values
236
+ """
237
+ # extract only relevant kwargs for this specific backbone
238
+ return extract_subset_dict(
239
+ dic=dic,
240
+ keys=get_class_init_kwargs(cls),
241
+ copy=copy,
242
+ )
243
+
244
+
245
+ def assert_valid_key(key, valid_keys, name=None):
246
+ """
247
+ Helper function that asserts that @key is in dictionary @valid_keys keys. If not, it will raise an error.
248
+
249
+ Args:
250
+ key (any): key to check for in dictionary @dic's keys
251
+ valid_keys (Iterable): contains keys should be checked with @key
252
+ name (str or None): if specified, is the name associated with the key that will be printed out if the
253
+ key is not found. If None, default is "value"
254
+ """
255
+ if name is None:
256
+ name = "value"
257
+ assert key in valid_keys, "Invalid {} received! Valid options are: {}, got: {}".format(
258
+ name, valid_keys.keys() if isinstance(valid_keys, dict) else valid_keys, key
259
+ )
260
+
261
+
262
+ def create_class_from_registry_and_config(cls_name, cls_registry, cfg, cls_type_descriptor):
263
+ """
264
+ Helper function to create a class with str type @cls_name, which should be a valid entry in @cls_registry, using
265
+ kwargs in dictionary form @cfg to pass to the constructor, with @cls_type_name specified for debugging
266
+
267
+ Args:
268
+ cls_name (str): Name of the class to create. This should correspond to the actual class type, in string form
269
+ cls_registry (dict): Class registry. This should map string names of valid classes to create to the
270
+ actual class type itself
271
+ cfg (dict): Any keyword arguments to pass to the class constructor
272
+ cls_type_descriptor (str): Description of the class type being created. This can be any string and is used
273
+ solely for debugging purposes
274
+
275
+ Returns:
276
+ any: Created class instance
277
+ """
278
+ # Make sure the requested class type is valid
279
+ assert_valid_key(key=cls_name, valid_keys=cls_registry, name=f"{cls_type_descriptor} type")
280
+
281
+ # Grab the kwargs relevant for the specific class
282
+ cls = cls_registry[cls_name]
283
+ cls_kwargs = extract_class_init_kwargs_from_dict(cls=cls, dic=cfg, copy=False)
284
+
285
+ # Create the class
286
+ return cls(**cls_kwargs)
287
+
288
+
289
+ def get_uuid(name, n_digits=8, deterministic=True):
290
+ """
291
+ Helper function to create a unique @n_digits uuid given a unique @name
292
+
293
+ Args:
294
+ name (str): Name of the object or class
295
+ n_digits (int): Number of digits of the uuid, default is 8
296
+ deterministic (bool): Whether the outputted UUID should be deterministic or not
297
+
298
+ Returns:
299
+ int: uuid
300
+ """
301
+ # Make sure the number is float32 compatible
302
+ val = int(md5(name.encode()).hexdigest(), 16) if deterministic else abs(hash(name))
303
+ return int(th.tensor(val % (10**n_digits), dtype=th.float32).item())
304
+
305
+
306
+ def meets_minimum_version(test_version, minimum_version):
307
+ """
308
+ Verify that @test_version meets the @minimum_version
309
+
310
+ Args:
311
+ test_version (str): Python package version. Should be, e.g., 0.26.1
312
+ minimum_version (str): Python package version to test against. Should be, e.g., 0.27.2
313
+
314
+ Returns:
315
+ bool: Whether @test_version meets @minimum_version
316
+ """
317
+ test_nums = [int(num) for num in test_version.split(".")]
318
+ minimum_nums = [int(num) for num in minimum_version.split(".")]
319
+ assert len(test_nums) == 3
320
+ assert len(minimum_nums) == 3
321
+
322
+ for test_num, minimum_num in zip(test_nums, minimum_nums):
323
+ if test_num > minimum_num:
324
+ return True
325
+ elif test_num < minimum_num:
326
+ return False
327
+ # Otherwise, we continue through all sub-versions
328
+
329
+ # If we get here, that means test_version == threshold_version, so this is a success
330
+ return True
331
+
332
+
333
+ class Registerable:
334
+ """
335
+ Simple class template that provides an abstract interface for registering classes.
336
+ """
337
+
338
+ def __init_subclass__(cls, **kwargs):
339
+ """
340
+ Registers all subclasses as part of this registry. This is useful to decouple internal codebase from external
341
+ user additions. This way, users can add their custom subclasses by simply extending this class,
342
+ and it will automatically be registered internally. This allows users to then specify their classes
343
+ directly in string-form in e.g., their config files, without having to manually set the str-to-class mapping
344
+ in our code.
345
+ """
346
+ cls._register_cls()
347
+
348
+ @classmethod
349
+ def _register_cls(cls):
350
+ """
351
+ Register this class. Can be extended by subclass.
352
+ """
353
+ # print(f"registering: {cls.__name__}")
354
+ # print(f"registry: {cls._cls_registry}", cls.__name__ not in cls._cls_registry)
355
+ # print(f"do not register: {cls._do_not_register_classes}", cls.__name__ not in cls._do_not_register_classes)
356
+ # input()
357
+ if cls.__name__ not in cls._cls_registry and cls.__name__ not in cls._do_not_register_classes:
358
+ cls._cls_registry[cls.__name__] = cls
359
+
360
+ @classproperty
361
+ def _do_not_register_classes(cls):
362
+ """
363
+ Returns:
364
+ set of str: Name(s) of classes that should not be registered. Default is empty set.
365
+ Subclasses that shouldn't be added should call super() and then add their own class name to the set
366
+ """
367
+ return set()
368
+
369
+ @classproperty
370
+ def _cls_registry(cls):
371
+ """
372
+ Returns:
373
+ dict: Mapping from all registered class names to their classes. This should be a REFERENCE
374
+ to some external, global dictionary that will be filled-in at runtime.
375
+ """
376
+ raise NotImplementedError()
377
+
378
+
379
+ class Serializable:
380
+ """
381
+ Simple class that provides an abstract interface to dump / load states, optionally with serialized functionality
382
+ as well.
383
+ """
384
+
385
+ def _dump_state(self):
386
+ """
387
+ Dumps the state of this object in dictionary form (can be empty). Should be implemented by subclass.
388
+
389
+ Returns:
390
+ dict: Keyword-mapped states of this object
391
+ """
392
+ raise NotImplementedError()
393
+
394
+ def dump_state(self, serialized=False):
395
+ """
396
+ Dumps the state of this object in either dictionary of flattened numerical form.
397
+
398
+ Args:
399
+ serialized (bool): If True, will return the state of this object as a 1D numpy array. Otherewise, will return
400
+ a (potentially nested) dictionary of states for this object
401
+
402
+ Returns:
403
+ dict or n-array: Either:
404
+ - Keyword-mapped states of this object, or
405
+ - encoded + serialized, 1D numerical th.tensor capturing this object's state
406
+ """
407
+ state = self._dump_state()
408
+ return self.serialize(state=state) if serialized else state
409
+
410
+ def _load_state(self, state):
411
+ """
412
+ Load the internal state to this object as specified by @state. Should be implemented by subclass.
413
+
414
+ Args:
415
+ state (dict): Keyword-mapped states of this object to set
416
+ """
417
+ raise NotImplementedError()
418
+
419
+ def load_state(self, state, serialized=False):
420
+ """
421
+ Deserializes and loads this object's state based on @state
422
+
423
+ Args:
424
+ state (dict or n-array): Either:
425
+ - Keyword-mapped states of this object, or
426
+ - encoded + serialized, 1D numerical th.tensor capturing this object's state.
427
+ serialized (bool): If True, will interpret @state as a 1D numpy array. Otherewise, will assume the input is
428
+ a (potentially nested) dictionary of states for this object
429
+ """
430
+ if serialized:
431
+ orig_state_len = len(state)
432
+ state, deserialized_items = self.deserialize(state=state)
433
+ assert deserialized_items == orig_state_len, (
434
+ f"Invalid state deserialization occurred! Expected {orig_state_len} total "
435
+ f"values to be deserialized, only {deserialized_items} were."
436
+ )
437
+ self._load_state(state=state)
438
+
439
+ def serialize(self, state):
440
+ """
441
+ Serializes nested dictionary state @state into a flattened 1D numpy array for encoding efficiency.
442
+ Should be implemented by subclass.
443
+
444
+ Args:
445
+ state (dict): Keyword-mapped states of this object to encode. Should match structure of output from
446
+ self._dump_state()
447
+
448
+ Returns:
449
+ n-array: encoded + serialized, 1D numerical th.tensor capturing this object's state
450
+ """
451
+ raise NotImplementedError()
452
+
453
+ def deserialize(self, state):
454
+ """
455
+ De-serializes flattened 1D numpy array @state into nested dictionary state.
456
+ Should be implemented by subclass.
457
+
458
+ Args:
459
+ state (n-array): encoded + serialized, 1D numerical th.tensor capturing this object's state
460
+
461
+ Returns:
462
+ 2-tuple:
463
+ - dict: Keyword-mapped states of this object. Should match structure of output from
464
+ self._dump_state()
465
+ - int: current index of the flattened state vector that is left off. This is helpful for subclasses
466
+ that inherit partial deserializations from parent classes, and need to know where the
467
+ deserialization left off before continuing.
468
+ """
469
+ raise NotImplementedError
470
+
471
+
472
+ class SerializableNonInstance:
473
+ """
474
+ Identical to Serializable, but intended for non-instanceable classes
475
+ """
476
+
477
+ @classmethod
478
+ def _dump_state(cls):
479
+ """
480
+ Dumps the state of this object in dictionary form (can be empty). Should be implemented by subclass.
481
+
482
+ Returns:
483
+ dict: Keyword-mapped states of this object
484
+ """
485
+ raise NotImplementedError()
486
+
487
+ @classmethod
488
+ def dump_state(cls, serialized=False):
489
+ """
490
+ Dumps the state of this object in either dictionary of flattened numerical form.
491
+
492
+ Args:
493
+ serialized (bool): If True, will return the state of this object as a 1D numpy array. Otherewise, will return
494
+ a (potentially nested) dictionary of states for this object
495
+
496
+ Returns:
497
+ dict or n-array: Either:
498
+ - Keyword-mapped states of this object, or
499
+ - encoded + serialized, 1D numerical th.tensor capturing this object's state.
500
+ """
501
+ state = cls._dump_state()
502
+ return cls.serialize(state=state) if serialized else state
503
+
504
+ @classmethod
505
+ def _load_state(cls, state):
506
+ """
507
+ Load the internal state to this object as specified by @state. Should be implemented by subclass.
508
+
509
+ Args:
510
+ state (dict): Keyword-mapped states of this object to set
511
+ """
512
+ raise NotImplementedError()
513
+
514
+ @classmethod
515
+ def load_state(cls, state, serialized=False):
516
+ """
517
+ Deserializes and loads this object's state based on @state
518
+
519
+ Args:
520
+ state (dict or n-array): Either:
521
+ - Keyword-mapped states of this object, or
522
+ - encoded + serialized, 1D numerical th.tensor capturing this object's state.
523
+ serialized (bool): If True, will interpret @state as a 1D numpy array. Otherewise, will assume the input is
524
+ a (potentially nested) dictionary of states for this object
525
+ """
526
+ if serialized:
527
+ orig_state_len = len(state)
528
+ state, deserialized_items = cls.deserialize(state=state)
529
+ assert deserialized_items == orig_state_len, (
530
+ f"Invalid state deserialization occurred! Expected {orig_state_len} total "
531
+ f"values to be deserialized, only {deserialized_items} were."
532
+ )
533
+ cls._load_state(state=state)
534
+
535
+ @classmethod
536
+ def serialize(cls, state):
537
+ """
538
+ Serializes nested dictionary state @state into a flattened 1D numpy array for encoding efficiency.
539
+ Should be implemented by subclass.
540
+
541
+ Args:
542
+ state (dict): Keyword-mapped states of this object to encode. Should match structure of output from
543
+ self._dump_state()
544
+
545
+ Returns:
546
+ n-array: encoded + serialized, 1D numerical th.tensor capturing this object's state
547
+ """
548
+ # Simply returns self.serialize() for now. this is for future proofing
549
+ return NotImplementedError()
550
+
551
+ @classmethod
552
+ def deserialize(cls, state):
553
+ """
554
+ De-serializes flattened 1D numpy array @state into nested dictionary state.
555
+ Should be implemented by subclass.
556
+
557
+ Args:
558
+ state (n-array): encoded + serialized, 1D numerical th.tensor capturing this object's state
559
+
560
+ Returns:
561
+ 2-tuple:
562
+ - dict: Keyword-mapped states of this object. Should match structure of output from
563
+ self._dump_state()
564
+ - int: current index of the flattened state vector that is left off. This is helpful for subclasses
565
+ that inherit partial deserializations from parent classes, and need to know where the
566
+ deserialization left off before continuing.
567
+ """
568
+ raise NotImplementedError
569
+
570
+
571
+ class CachedFunctions:
572
+ """
573
+ Thin object which owns a dictionary in which each entry should be a function -- when a key is queried via get()
574
+ and it exists, it will call the function exactly once, and cache the value so that subsequent calls will refer
575
+ to the cached value.
576
+
577
+ This allows the dictionary to be created with potentially expensive operations, but only queried up to exaclty once
578
+ as needed.
579
+ """
580
+
581
+ def __init__(self, **kwargs):
582
+ # Create internal dict to store functions
583
+ self._fcns = dict()
584
+ self._cache = dict()
585
+ for kwarg in kwargs:
586
+ self._fcns[kwarg] = kwargs[kwarg]
587
+
588
+ def __getitem__(self, item):
589
+ return self.get(name=item)
590
+
591
+ def __setitem__(self, key, value):
592
+ self.add_fcn(name=key, fcn=value)
593
+
594
+ def get(self, name):
595
+ """
596
+ Computes the function referenced by @name with the corresponding @args and @kwargs. Note that for a unique
597
+ set of arguments, this value will be internally cached
598
+
599
+ Args:
600
+ name (str): The name of the function to call
601
+
602
+ Returns:
603
+ any: Output of the function referenced by @name
604
+ """
605
+ if name not in self._cache:
606
+ self._cache[name] = self._fcns[name]()
607
+ return self._cache[name]
608
+
609
+ def get_fcn(self, name):
610
+ """
611
+ Gets the raw stored function referenced by @name
612
+
613
+ Args:
614
+ name (str): The name of the function to grab
615
+
616
+ Returns:
617
+ function: The stored function
618
+ """
619
+ return self._fcns[name]
620
+
621
+ def get_fcn_names(self):
622
+ """
623
+ Get all stored function names
624
+
625
+ Returns:
626
+ tuple of str: Names of stored functions
627
+ """
628
+ return tuple(self._fcns.keys())
629
+
630
+ def add_fcn(self, name, fcn):
631
+ """
632
+ Adds a function to the internal registry.
633
+
634
+ Args:
635
+ name (str): Name of the function. This is the name that should be queried with self.get()
636
+ fcn (function): Function to add. Can be an arbitrary signature
637
+ """
638
+ assert callable(fcn), "Only functions can be added via add_fcn!"
639
+ self._fcns[name] = fcn
640
+
641
+
642
+ class Wrapper:
643
+ """
644
+ Base class for all wrappers in OmniGibson
645
+
646
+ Args:
647
+ obj (any): Arbitrary python object instance to wrap
648
+ """
649
+
650
+ def __init__(self, obj):
651
+ # Set the internal attributes -- store wrapped obj
652
+ self.wrapped_obj = obj
653
+
654
+ @classmethod
655
+ def class_name(cls):
656
+ return cls.__name__
657
+
658
+ def _warn_double_wrap(self):
659
+ """
660
+ Utility function that checks if we're accidentally trying to double wrap an env
661
+ Raises:
662
+ Exception: [Double wrapping env]
663
+ """
664
+ obj = self.wrapped_obj
665
+ while True:
666
+ if isinstance(obj, Wrapper):
667
+ if obj.class_name() == self.class_name():
668
+ raise Exception("Attempted to double wrap with Wrapper: {}".format(self.__class__.__name__))
669
+ obj = obj.wrapped_obj
670
+ else:
671
+ break
672
+
673
+ @property
674
+ def unwrapped(self):
675
+ """
676
+ Grabs unwrapped object
677
+
678
+ Returns:
679
+ any: The unwrapped object instance
680
+ """
681
+ return self.wrapped_obj.unwrapped if hasattr(self.wrapped_obj, "unwrapped") else self.wrapped_obj
682
+
683
+ # this method is a fallback option on any methods the original env might support
684
+ def __getattr__(self, attr):
685
+ # If we're querying wrapped_obj, raise an error
686
+ if attr == "wrapped_obj":
687
+ raise AttributeError("wrapped_obj attribute not initialized yet!")
688
+
689
+ # Sanity check to make sure wrapped obj is not None -- if so, raise error
690
+ assert self.wrapped_obj is not None, f"Cannot access attribute {attr} since wrapped_obj is None!"
691
+
692
+ # using getattr ensures that both __getattribute__ and __getattr__ (fallback) get called
693
+ # (see https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute)
694
+ orig_attr = getattr(self.wrapped_obj, attr)
695
+ if callable(orig_attr):
696
+
697
+ def hooked(*args, **kwargs):
698
+ result = orig_attr(*args, **kwargs)
699
+ # prevent wrapped_class from becoming unwrapped
700
+ if id(result) == id(self.wrapped_obj):
701
+ return self
702
+ return result
703
+
704
+ return hooked
705
+ else:
706
+ return orig_attr
707
+
708
+ def __setattr__(self, key, value):
709
+ # Call setattr on wrapped obj if it has the attribute, otherwise, operate on this object
710
+ if hasattr(self, "wrapped_obj") and self.wrapped_obj is not None and hasattr(self.wrapped_obj, key):
711
+ setattr(self.wrapped_obj, key, value)
712
+ else:
713
+ super().__setattr__(key, value)
714
+
715
+
716
+ def torch_compile(func):
717
+ """
718
+ Decorator to compile a function with torch.compile on Linux and torch.jit.script on Windows. This is because of poor support for torch.compile on Windows.
719
+
720
+ Args:
721
+ func (function): Function to compile
722
+
723
+ Returns:
724
+ function: Compiled function
725
+ """
726
+ # If we're on Windows, return a jitscript option
727
+ if sys.platform == "win32":
728
+ return th.jit.script(func)
729
+ # Otherwise, return a torch.compile option
730
+ else:
731
+ return th.compile(func)
732
+
733
+
734
+ def nums2array(nums, dim, dtype=th.float32):
735
+ """
736
+ Converts input @nums into numpy array of length @dim. If @nums is a single number, broadcasts input to
737
+ corresponding dimension size @dim before converting into numpy array
738
+
739
+ Args:
740
+ nums (float or array): Numbers to map to numpy array
741
+ dim (int): Size of array to broadcast input to
742
+
743
+ Returns:
744
+ torch.Tensor: Mapped input numbers
745
+ """
746
+ # Make sure the inputted nums isn't a string
747
+ assert not isinstance(nums, str), "Only numeric types are supported for this operation!"
748
+
749
+ out = th.tensor(nums, dtype=dtype) if isinstance(nums, Iterable) else th.ones(dim, dtype=dtype) * nums
750
+
751
+ return out
752
+
753
+
754
+ def clear():
755
+ """
756
+ Clear state tied to singleton classes
757
+ """
758
+ NAMES.clear()
759
+ CLASS_NAMES.clear()
760
+
761
+
762
+ def torch_delete(tensor: th.Tensor, indices: th.Tensor | int, dim: int | None = None) -> th.Tensor:
763
+ """
764
+ Delete elements from a tensor along a specified dimension.
765
+
766
+ Parameters:
767
+ tensor (torch.Tensor): Input tensor.
768
+ indices (int or torch.Tensor): Indices of elements to remove.
769
+ dim (int, optional): The dimension along which to delete the elements.
770
+ If None, the tensor is flattened before deletion.
771
+
772
+ Returns:
773
+ torch.Tensor: Tensor with specified elements removed.
774
+ """
775
+ assert tensor.dim() > 0, "Input tensor must have at least one dimension"
776
+
777
+ if dim is None:
778
+ # Flatten the tensor if no dim is specified
779
+ tensor = tensor.flatten()
780
+ dim = 0
781
+
782
+ if not isinstance(indices, th.Tensor):
783
+ indices = th.tensor(indices, dtype=th.long, device=tensor.device)
784
+
785
+ assert th.all(indices >= 0) and th.all(indices < tensor.size(dim)), "Indices out of bounds"
786
+
787
+ # Create a mask for the indices to keep
788
+ keep_indices = th.ones(tensor.size(dim), dtype=th.bool, device=tensor.device)
789
+ keep_indices[indices] = False
790
+
791
+ return th.index_select(tensor, dim, th.nonzero(keep_indices).squeeze(1))
792
+
793
+
794
+ def recursively_convert_to_torch(state):
795
+ # For all the lists in state dict, convert to torch tensor
796
+ for key, value in state.items():
797
+ if isinstance(value, dict):
798
+ state[key] = recursively_convert_to_torch(value)
799
+ elif isinstance(value, list):
800
+ # Convert to torch tensor if all elements are numeric and have consistent shapes
801
+ try:
802
+ state[key] = th.tensor(value, dtype=th.float32)
803
+ except:
804
+ pass
805
+
806
+ return state
807
+
808
+
809
+ def recursively_convert_from_torch(state):
810
+ # For all the lists in state dict, convert from torch tensor -> numpy array
811
+ import numpy as np
812
+
813
+ for key, value in state.items():
814
+ if isinstance(value, dict):
815
+ state[key] = recursively_convert_from_torch(value)
816
+ elif isinstance(value, th.Tensor):
817
+ state[key] = value.cpu().numpy()
818
+ elif (isinstance(value, list) or isinstance(value, tuple)) and len(value) > 0:
819
+ if isinstance(value[0], dict):
820
+ state[key] = [recursively_convert_from_torch(val) for val in value]
821
+ elif isinstance(value[0], th.Tensor):
822
+ state[key] = [tensor.numpy() for tensor in value]
823
+ elif isinstance(value[0], int) or isinstance(value[0], float):
824
+ state[key] = np.array(value)
825
+ return state
826
+
827
+
828
+ def h5py_group_to_torch(group):
829
+ state = {}
830
+ for key, value in group.items():
831
+ if isinstance(value, h5py.Group):
832
+ state[key] = h5py_group_to_torch(value)
833
+ else:
834
+ state[key] = th.from_numpy(value[()])
835
+ return state
836
+
837
+
838
+ @th.jit.script
839
+ def multi_dim_linspace(start: th.Tensor, stop: th.Tensor, num: int, endpoint: bool = True) -> th.Tensor:
840
+ """
841
+ Generate a tensor with evenly spaced values along multiple dimensions.
842
+ This function creates a tensor where each slice along the first dimension
843
+ contains values linearly interpolated between the corresponding elements
844
+ of 'start' and 'stop'. It's similar to numpy.linspace but works with
845
+ multi-dimensional inputs in PyTorch.
846
+ Args:
847
+ start (th.Tensor): Starting values for each dimension.
848
+ stop (th.Tensor): Ending values for each dimension.
849
+ num (int): Number of samples to generate along the interpolated dimension.
850
+ endpoint (bool, optional): If True, stop is the last sample. Otherwise, it is not included.
851
+ Returns:
852
+ th.Tensor: A tensor of shape (num, *start.shape) containing the interpolated values.
853
+ Example:
854
+ >>> start = th.tensor([0.0, 10.0, 100.0])
855
+ >>> stop = th.tensor([1.0, 20.0, 200.0])
856
+ >>> result = multi_dim_linspace(start, stop, num=5, endpoint=True)
857
+ >>> print(result.shape)
858
+ torch.Size([5, 3])
859
+ >>> print(result)
860
+ tensor([[ 0.0000, 10.0000, 100.0000],
861
+ [ 0.2500, 12.5000, 125.0000],
862
+ [ 0.5000, 15.0000, 150.0000],
863
+ [ 0.7500, 17.5000, 175.0000],
864
+ [ 1.0000, 20.0000, 200.0000]])
865
+ >>> result = multi_dim_linspace(start, stop, num=5, endpoint=False)
866
+ >>> print(result.shape)
867
+ torch.Size([5, 3])
868
+ >>> print(result)
869
+ tensor([[ 0.0000, 10.0000, 100.0000],
870
+ [ 0.2000, 12.0000, 120.0000],
871
+ [ 0.4000, 14.0000, 140.0000],
872
+ [ 0.6000, 16.0000, 160.0000],
873
+ [ 0.8000, 18.0000, 180.0000]])
874
+ """
875
+ if endpoint:
876
+ steps = th.linspace(0, 1, num, dtype=start.dtype, device=start.device)
877
+ else:
878
+ steps = th.linspace(0, 1, num + 1, dtype=start.dtype, device=start.device)[:-1]
879
+
880
+ # Create a new shape for broadcasting
881
+ new_shape = [num] + [1] * start.dim()
882
+ steps = steps.reshape(new_shape)
883
+
884
+ return start + steps * (stop - start)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/registry_utils.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of utility functions for registering and tracking objects
3
+ """
4
+
5
+ from collections.abc import Iterable
6
+ from inspect import isclass
7
+
8
+ import torch as th
9
+
10
+ from omnigibson.macros import create_module_macros
11
+ from omnigibson.utils.python_utils import Serializable, SerializableNonInstance, get_uuid
12
+ from omnigibson.utils.ui_utils import create_module_logger
13
+ from omnigibson.objects.usd_object import USDObject
14
+
15
+ # Create module logger
16
+ log = create_module_logger(module_name=__name__)
17
+
18
+ # Create settings for this module
19
+ m = create_module_macros(module_path=__file__)
20
+
21
+ # Token identifier for default values if a key doesn't exist in a given object
22
+ m.DOES_NOT_EXIST = "DOES_NOT_EXIST"
23
+
24
+ m.STABILIZE_SKIPPED_OBJECTS = False
25
+
26
+
27
+ class Registry:
28
+ """
29
+ Simple class for easily registering and tracking arbitrary objects of the same (or very similar) class types.
30
+
31
+ Elements added are automatically organized by attributes specified by @unique_keys and @group_keys, and
32
+ can be accessed at runtime by specifying the desired key and indexing value to grab the object(s).
33
+
34
+ Default_key is a 1-to-1 mapping: i.e.: a single indexing value will return a single object.
35
+ default: "name" -- indexing by object.name (i.e.: every object's name should be unique)
36
+ Unique_keys are other 1-to-1 mappings: i.e.: a single indexing value will return a single object.
37
+ example: indexing by object.name (every object's name should be unique)
38
+ Group_keys are 1-to-many mappings: i.e.: a single indexing value will return a set of objects.
39
+ example: indexing by object.in_rooms (many objects can be in a single room)
40
+
41
+ Note that if a object's attribute is an array of values, then it will be stored under ALL of its values.
42
+ example: object.in_rooms = ["kitchen", "living_room"], indexing by in_rooms with a value of either kitchen OR
43
+ living room will return this object as part of its set!
44
+
45
+ You can also easily check for membership in this registry, via either the object's name OR the object itself,
46
+ e.g.:
47
+
48
+ > object.name in registry
49
+ > object in registry
50
+
51
+ If the latter, note that default_key attribute will automatically be used to search for the object
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ name,
57
+ class_types=object,
58
+ default_key="name",
59
+ unique_keys=None,
60
+ group_keys=None,
61
+ default_value=None,
62
+ ):
63
+ """
64
+ Args:
65
+ name (str): name of this registry
66
+ class_types (class or list of class): class expected for all entries in this registry. Default is `object`,
67
+ meaning any object entered will be accepted. This is used to sanity check added entries using add()
68
+ to make sure their type is correct (either that the entry itself is a valid class, or that they are an
69
+ object of the valid class). Note that if a list of classes are passed, any one of the classes are
70
+ considered a valid type for added objects
71
+ default_key (str): default key by which to reference a given object. This key should be a
72
+ publically accessible attribute in a given object (e.g.: object.name) and uniquely identify
73
+ any entries
74
+ unique_keys (None or list of str or set of str): keys by which to reference a given object. Any key should be a
75
+ publically accessible attribute in a given object (e.g.: object.name)
76
+ i.e.: these keys should map to a single object
77
+
78
+ group_keys (None or list of str): keys by which to reference a group of objects, based on the key
79
+ (e.g.: object.room)
80
+ i.e.: these keys can map to multiple objects
81
+
82
+ e.g.: default is "name" key only, so we will store objects by their object.name attribute
83
+
84
+ default_value (any): Default value to use if the attribute @key does not exist in the object
85
+ """
86
+ self._name = name
87
+ self.class_types = class_types if isinstance(class_types, Iterable) else [class_types]
88
+ self.default_key = default_key
89
+ self.unique_keys = set([] if unique_keys is None else unique_keys)
90
+ self.group_keys = set([] if group_keys is None else group_keys)
91
+ self.default_value = default_value
92
+
93
+ # We always add in the "name" attribute as well
94
+ self.unique_keys.add(self.default_key)
95
+
96
+ # Make sure there's no overlap between the unique and group keys
97
+ assert len(self.unique_keys.intersection(self.group_keys)) == 0, (
98
+ f"Cannot create registry with unique and group object keys that are the same! "
99
+ f"Unique keys: {self.unique_keys}, group keys: {self.group_keys}"
100
+ )
101
+
102
+ # Create the dicts programmatically
103
+ for k in self.unique_keys.union(self.group_keys):
104
+ self.__setattr__(f"_objects_by_{k}", dict())
105
+
106
+ # Run super init
107
+ super().__init__()
108
+
109
+ @property
110
+ def name(self):
111
+ return self._name
112
+
113
+ def add(self, obj):
114
+ """
115
+ Adds Instance @obj to this registry
116
+
117
+ Args:
118
+ obj (any): Instance to add to this registry
119
+ """
120
+ # Make sure that obj is of the correct class type
121
+ assert any(
122
+ [isinstance(obj, class_type) or issubclass(obj, class_type) for class_type in self.class_types]
123
+ ), f"Added object must be either an instance or subclass of one of the following classes: {self.class_types}!"
124
+ self._add(obj=obj, keys=self.all_keys)
125
+
126
+ def _add(self, obj, keys=None):
127
+ """
128
+ Same as self.add, but allows for selective @keys for adding this object to. Useful for internal things,
129
+ such as internal updating of mappings
130
+
131
+ Args:
132
+ obj (any): Instance to add to this registry
133
+ keys (None or set or list of str): Which object keys to use for adding the object to mappings.
134
+ None is default, which corresponds to all keys
135
+ """
136
+ keys = self.all_keys if keys is None else keys
137
+
138
+ for k in keys:
139
+ obj_attr = self._get_obj_attr(obj=obj, attr=k)
140
+ # Standardize input as a list
141
+ obj_attr = obj_attr if isinstance(obj_attr, Iterable) and not isinstance(obj_attr, str) else [obj_attr]
142
+
143
+ # Loop over all values in this attribute and add to all mappings
144
+ for attr in obj_attr:
145
+ mapping = self.get_dict(k)
146
+ if k in self.unique_keys:
147
+ # Handle unique case
148
+ if attr in mapping:
149
+ log.warning(
150
+ f"Instance identifier '{k}' should be unique for adding to this registry mapping! Existing {k}: {attr}"
151
+ )
152
+ # Special case for "name" attribute, which should ALWAYS be unique
153
+ assert k != "name", "For name attribute, objects MUST be unique."
154
+ mapping[attr] = obj
155
+ else:
156
+ # Not unique case
157
+ # Possibly initialize list
158
+ if attr not in mapping:
159
+ mapping[attr] = set()
160
+ mapping[attr].add(obj)
161
+
162
+ def remove(self, obj):
163
+ """
164
+ Removes object @object from this registry
165
+
166
+ Args:
167
+ obj (any): Instance to remove from this registry
168
+ """
169
+ # Iterate over all keys
170
+ for k in self.all_keys:
171
+ # Grab the attribute from the object
172
+ obj_attr = self._get_obj_attr(obj=obj, attr=k)
173
+ # Standardize input as a list
174
+ obj_attr = obj_attr if isinstance(obj_attr, Iterable) and not isinstance(obj_attr, str) else [obj_attr]
175
+
176
+ # Loop over all values in this attribute and remove them from all mappings
177
+ for attr in obj_attr:
178
+ mapping = self.get_dict(k)
179
+ if k in self.unique_keys:
180
+ # Handle unique case -- in this case, we just directly pop the value from the dictionary
181
+ mapping.pop(attr)
182
+ else:
183
+ # Not unique case
184
+ # We remove a value from the resulting set
185
+ mapping[attr].remove(obj)
186
+
187
+ def clear(self):
188
+ """
189
+ Removes all owned objects from this registry
190
+ """
191
+ # Re-create the owned dicts programmatically
192
+ for k in self.unique_keys.union(self.group_keys):
193
+ self.__setattr__(f"_objects_by_{k}", dict())
194
+
195
+ def update(self, keys=None):
196
+ """
197
+ Updates this registry, refreshing all internal mappings in case an object's value was updated
198
+
199
+ Args:
200
+ keys (None or str or set or list of str): Which object keys to update. None is default, which corresponds
201
+ to all keys
202
+ """
203
+ objects = self.objects
204
+ keys = self.all_keys if keys is None else (keys if type(keys) in {tuple, list} else [keys])
205
+
206
+ # Delete and re-create all keys mappings
207
+ for k in keys:
208
+ self.__delattr__(f"_objects_by_{k}")
209
+ self.__setattr__(f"_objects_by_{k}", dict())
210
+
211
+ # Iterate over all objects and re-populate the mappings
212
+ for obj in objects:
213
+ self._add(obj=obj, keys=[k])
214
+
215
+ def object_is_registered(self, obj):
216
+ """
217
+ Check if a given object @object is registered
218
+
219
+ Args:
220
+ obj (any): Instance to check if it is internally registered
221
+ """
222
+ return obj in self.objects
223
+
224
+ def get_dict(self, key):
225
+ """
226
+ Specific mapping dictionary within this registry corresponding to the mappings of @key.
227
+ e.g.: if key = "name", this will return the dictionary mapping object.name to objects
228
+
229
+ Args:
230
+ key (str): Key with which to grab mapping dict from
231
+
232
+ Returns:
233
+ dict: Mapping from identifiers to object(s) based on @key
234
+ """
235
+ return getattr(self, f"_objects_by_{key}")
236
+
237
+ def get_ids(self, key):
238
+ """
239
+ All identifiers within this registry corresponding to the mappings of @key.
240
+ e.g.: if key = "name", this will return all "names" stored internally that index into a object
241
+ Args:
242
+ key (str): Key with which to grab all identifiers from
243
+
244
+ Returns:
245
+ set: All identifiers within this registry corresponding to the mappings of @key.
246
+ """
247
+ return set(self.get_dict(key=key).keys())
248
+
249
+ def _get_obj_attr(self, obj, attr):
250
+ """
251
+ Grabs object's @obj's attribute @attr. Additionally checks to see if @obj is a class or a class instance, and
252
+ uses the correct logic
253
+
254
+ Args:
255
+ obj (any): Object to grab attribute from
256
+ attr (str): String name of the attribute to grab
257
+
258
+ Return:
259
+ any: Attribute @k of @obj
260
+ """
261
+ # We try to grab the object's attribute, and if it fails we fallback to the default value
262
+ try:
263
+ val = getattr(obj, attr)
264
+
265
+ except:
266
+ val = self.default_value if self.default_value is not None else m.DOES_NOT_EXIST
267
+
268
+ return val
269
+
270
+ @property
271
+ def objects(self):
272
+ """
273
+ Get the objects in this registry
274
+
275
+ Returns:
276
+ list of any: Instances owned by this registry
277
+ """
278
+ return list(self.get_dict(self.default_key).values())
279
+
280
+ @property
281
+ def object_names(self):
282
+ """
283
+ Get the names of the objects in this registry
284
+
285
+ Returns:
286
+ set of str: Names of the instances owned by this registry
287
+ """
288
+ return {obj.name for obj in self.objects}
289
+
290
+ @property
291
+ def all_keys(self):
292
+ """
293
+ Returns:
294
+ set of str: All object keys that are valid identification methods to index object(s)
295
+ """
296
+ return self.unique_keys.union(self.group_keys)
297
+
298
+ def __call__(self, key, value, default_val=None):
299
+ """
300
+ Grab the object in this registry based on @key and @value
301
+
302
+ Args:
303
+ key (str): What identification type to use to grab the requested object(s).
304
+ Should be one of @self.all_keys.
305
+ value (any): Value to grab. Should be the value of your requested object.<key> attribute
306
+ default_val (any): Default value to return if @value is not found
307
+
308
+ Returns:
309
+ any or set of any: requested unique object if @key is one of unique_keys, else a set if
310
+ @key is one of group_keys
311
+ """
312
+ assert key in self.all_keys, f"Invalid key requested! Valid options are: {self.all_keys}, got: {key}"
313
+
314
+ return self.get_dict(key).get(value, default_val)
315
+
316
+ def __contains__(self, obj):
317
+ # Instance can be either a string (default key) OR the object itself
318
+ if isinstance(obj, str):
319
+ obj = self(self.default_key, obj)
320
+ return self.object_is_registered(obj=obj)
321
+
322
+
323
+ class SerializableRegistry(Registry, Serializable):
324
+ """
325
+ Registry that is serializable, i.e.: entries contain states that can themselves be serialized /deserialized.
326
+
327
+ Note that this assumes that any objects added to this registry are themselves of @Serializable type!
328
+ """
329
+
330
+ def __init__(
331
+ self,
332
+ name,
333
+ class_types=object,
334
+ default_key="name",
335
+ hash_key="uuid",
336
+ unique_keys=None,
337
+ group_keys=None,
338
+ default_value=None,
339
+ ):
340
+ """
341
+ Args:
342
+ name (str): name of this registry
343
+ class_types (class or list of class): class expected for all entries in this registry. Default is `object`,
344
+ meaning any object entered will be accepted. This is used to sanity check added entries using add()
345
+ to make sure their type is correct (either that the entry itself is a valid class, or that they are an
346
+ object of the valid class). Note that if a list of classes are passed, any one of the classes are
347
+ considered a valid type for added objects
348
+ default_key (str): default key by which to reference a given object. This key should be a
349
+ publically accessible attribute in a given object (e.g.: object.name) and uniquely identify
350
+ any entries
351
+ hash_key (str): key by which to reference a given object when serializing / deserializing its state.
352
+ This key should be a publically accessible attribute in a given object (e.g.: object.name) and
353
+ uniquely identify any entries via a hash value (i.e.: integer)
354
+ unique_keys (None or list of str or set of str): keys by which to reference a given object. Any key should be a
355
+ publically accessible attribute in a given object (e.g.: object.name)
356
+ i.e.: these keys should map to a single object
357
+
358
+ group_keys (None or list of str): keys by which to reference a group of objects, based on the key
359
+ (e.g.: object.room)
360
+ i.e.: these keys can map to multiple objects
361
+
362
+ e.g.: default is "name" key only, so we will store objects by their object.name attribute
363
+
364
+ default_value (any): Default value to use if the attribute @key does not exist in the object
365
+ """
366
+ # Store hash key
367
+ self.hash_key = hash_key
368
+
369
+ # We always add in the hash_key attribute as well
370
+ unique_keys = set() if unique_keys is None else set(unique_keys)
371
+ unique_keys.add(self.hash_key)
372
+
373
+ # Set the default dump and load filters, which is a pass-through
374
+ self._dump_filter = lambda obj: True
375
+ self._load_filter = lambda obj: True
376
+
377
+ # Run super
378
+ super().__init__(
379
+ name=name,
380
+ class_types=class_types,
381
+ default_key=default_key,
382
+ unique_keys=unique_keys,
383
+ group_keys=group_keys,
384
+ default_value=default_value,
385
+ )
386
+
387
+ def add(self, obj):
388
+ # In addition to any other class types, we make sure that the object is a serializable instance / class
389
+ validate_class = issubclass if isclass(obj) else isinstance
390
+ assert any(
391
+ [validate_class(obj, class_type) for class_type in (Serializable, SerializableNonInstance)]
392
+ ), "Added object must be either an instance or subclass of Serializable or SerializableNonInstance!"
393
+ # Run super like normal
394
+ super().add(obj=obj)
395
+
396
+ def set_dump_filter(self, dump_filter):
397
+ """
398
+ Sets the internal filter that determines whether an object should be dumped or not.
399
+
400
+ Args:
401
+ dump_filter (function): Function that determines whether an object should be dumped or not.
402
+ Expected signature is:
403
+
404
+ def dump_filter(obj) -> bool
405
+
406
+ where it takes in a given registered object @obj and returns True if the object should have its state
407
+ dumped
408
+ """
409
+ self._dump_filter = dump_filter
410
+
411
+ def set_load_filter(self, load_filter):
412
+ """
413
+ Sets the internal filter that determines whether an object's state should be loaded or not.
414
+
415
+ Args:
416
+ load_filter (function): Function that determines whether an object should have its state loaded or not
417
+ Expected signature is:
418
+
419
+ def load_filter(obj) -> bool
420
+
421
+ where it takes in a given registered object @obj and returns True if the object should have its
422
+ state loaded or not
423
+ """
424
+ self._load_filter = load_filter
425
+
426
+ def _dump_state(self):
427
+ # Iterate over all objects and grab their states
428
+ state = dict()
429
+ for obj in self.objects:
430
+ if self._dump_filter(obj):
431
+ state[obj.name] = obj.dump_state(serialized=False)
432
+ return state
433
+
434
+ def _load_state(self, state):
435
+ # Iterate over all objects and load their states. Currently the objects and the state don't have to match, i.e.
436
+ # there might be objects in the scene that do not appear in the state dict (a warning will be printed), or
437
+ # the state might contain additional information about objects that are NOT in the scene. For both cases, state
438
+ # loading will be skipped.
439
+ for obj in self.objects:
440
+ if self._load_filter(obj):
441
+ if obj.name not in state:
442
+ log.debug(f"Object '{obj.name}' is not in the state dict to load from. Skip loading its state.")
443
+ if m.STABILIZE_SKIPPED_OBJECTS and isinstance(obj, USDObject) and not obj.kinematic_only:
444
+ obj.keep_still()
445
+ continue
446
+ obj.load_state(state[obj.name], serialized=False)
447
+
448
+ def serialize(self, state):
449
+ # Iterate over the entire dict and flatten
450
+ # We keep track of how many objects are being saved, as well as the unique identifier for each object so that
451
+ # the saved flattened array is agnostic to object ordering
452
+ # self("name", name) grabs the corresponding object from this registry so that we can serialize its state
453
+ # Each object's state in the flattened array is composed of [hash_key, serialized_state]
454
+ n_objs = len(state)
455
+
456
+ if len(state) > 0:
457
+ state_flat = []
458
+ for name in state:
459
+ obj = self("name", name)
460
+ serialized = obj.serialize(state[name])
461
+
462
+ # Handle the case where serialize returns an empty tensor
463
+ if serialized.numel() == 0:
464
+ hash_key_tensor = th.tensor([getattr(obj, self.hash_key)], dtype=th.float32)
465
+ state_flat.append(hash_key_tensor)
466
+ else:
467
+ hash_key_tensor = th.tensor([getattr(obj, self.hash_key)], dtype=serialized.dtype)
468
+ state_flat.append(th.cat([hash_key_tensor, serialized.flatten()]))
469
+
470
+ state_flat = th.cat(state_flat)
471
+ else:
472
+ state_flat = th.tensor([])
473
+
474
+ return th.cat([th.tensor([n_objs], dtype=th.float32), state_flat])
475
+
476
+ def deserialize(self, state):
477
+ state_dict = dict()
478
+ # Iterate over all the objects and deserialize their individual states, incrementing the index counter
479
+ # along the way
480
+ n_objects = int(state[0])
481
+ idx = 1
482
+ for _ in range(n_objects):
483
+ # Infer obj based on UUID
484
+ obj = self(self.hash_key, int(state[idx]))
485
+ assert (
486
+ obj is not None
487
+ ), f"Could not find object while deserializing with hash_key {self.hash_key}: {int(state[idx])}"
488
+ idx += 1
489
+ log.debug(f"obj: {obj.name}, idx: {idx}, passing in state length: {len(state[idx:])}")
490
+ # We pass in the entire remaining state vector, assuming the object only parses the relevant states
491
+ # at the beginning
492
+ state_dict[obj.name], deserialized_items = obj.deserialize(state[idx:])
493
+ idx += deserialized_items
494
+ return state_dict, idx
495
+
496
+ @property
497
+ def uuid(self):
498
+ """
499
+ Returns:
500
+ int: Unique hashed ID for this registry
501
+ """
502
+ return get_uuid(self.name)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/render_utils.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Set of rendering utility functions when working with Omni
3
+ """
4
+
5
+ import omnigibson as og
6
+ import omnigibson.lazy as lazy
7
+ from omnigibson.utils.physx_utils import bind_material
8
+ from omnigibson.utils.ui_utils import create_module_logger
9
+
10
+
11
+ # Create module logger
12
+ log = create_module_logger(module_name=__name__)
13
+
14
+
15
+ def make_glass(prim):
16
+ """
17
+ Links the OmniGlass material with EntityPrim, RigidPrim, or GeomPrim @obj, and procedurally generates
18
+ the necessary OmniGlass material prim if necessary.
19
+
20
+ Args:
21
+ prim (EntityPrim or RigidPrim or GeomPrim): Desired prim to convert into glass
22
+ """
23
+ # Do this here to avoid circular imports
24
+ from omnigibson.prims import EntityPrim, RigidPrim, GeomPrim
25
+
26
+ # Generate the set of visual meshes we'll convert into glass
27
+ if isinstance(prim, EntityPrim):
28
+ # Grab all visual meshes from all links
29
+ visual_meshes = [vm for link in prim.links.values() for vm in link.visual_meshes.values()]
30
+ elif isinstance(prim, RigidPrim):
31
+ # Grab all visual meshes from the link
32
+ visual_meshes = [vm for vm in prim.visual_meshes.values()]
33
+ elif isinstance(prim, GeomPrim):
34
+ # Just use this visual mesh
35
+ visual_meshes = [prim]
36
+ else:
37
+ raise ValueError(
38
+ "Inputted prim must an instance of EntityPrim, RigidPrim, or GeomPrim "
39
+ "in order to be converted into glass!"
40
+ )
41
+
42
+ # Grab the glass material prim; if it doesn't exist, we create it on the fly
43
+ glass_prim_path = "/Looks/OmniGlass"
44
+ if not lazy.isaacsim.core.utils.prims.get_prim_at_path(glass_prim_path):
45
+ mtl_created = []
46
+ lazy.omni.kit.commands.execute(
47
+ "CreateAndBindMdlMaterialFromLibrary",
48
+ mdl_name="OmniGlass.mdl",
49
+ mtl_name="OmniGlass",
50
+ mtl_created_list=mtl_created,
51
+ )
52
+
53
+ # Iterate over all meshes and bind the glass material to the mesh
54
+ for vm in visual_meshes:
55
+ bind_material(vm.prim_path, material_path=glass_prim_path)
56
+
57
+
58
+ def create_pbr_material(prim_path):
59
+ """
60
+ Creates an omni pbr material prim at the specified @prim_path
61
+
62
+ Args:
63
+ prim_path (str): Prim path where the PBR material should be generated
64
+
65
+ Returns:
66
+ Usd.Prim: Generated PBR material prim
67
+ """
68
+ # Use DeepWater omni present for rendering water
69
+ mtl_created = []
70
+ with og.sim.editing_usd():
71
+ lazy.omni.kit.commands.execute(
72
+ "CreateAndBindMdlMaterialFromLibrary",
73
+ mdl_name="OmniPBR.mdl",
74
+ mtl_name="OmniPBR",
75
+ mtl_created_list=mtl_created,
76
+ )
77
+ material_path = mtl_created[0]
78
+
79
+ # Move prim to desired location
80
+ lazy.omni.kit.commands.execute("MovePrim", path_from=material_path, path_to=prim_path)
81
+
82
+ # Return generated material
83
+ return lazy.isaacsim.core.utils.prims.get_prim_at_path(material_path)
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sampling_utils.py ADDED
@@ -0,0 +1,1227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import math
3
+ import random
4
+ from collections import Counter, defaultdict
5
+
6
+ import torch as th
7
+ from scipy.stats import truncnorm
8
+
9
+ import omnigibson as og
10
+ import omnigibson.utils.transform_utils as T
11
+ from omnigibson.macros import create_module_macros
12
+ from omnigibson.utils.ui_utils import create_module_logger, draw_line
13
+
14
+ # Create module logger
15
+ log = create_module_logger(module_name=__name__)
16
+
17
+
18
+ # Create settings for this module
19
+ m = create_module_macros(module_path=__file__)
20
+
21
+ m.DEBUG_SAMPLING = False
22
+ m.DEFAULT_AABB_OFFSET_FRACTION = 0.02
23
+ m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE = 1.0 # Around 60 degrees
24
+ m.DEFAULT_HIT_TO_PLANE_THRESHOLD = 0.05
25
+ m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS = 3 * math.pi / 4
26
+ m.DEFAULT_MAX_SAMPLING_ATTEMPTS = 10
27
+ m.DEFAULT_CUBOID_BOTTOM_PADDING = 0.005
28
+ # We will cast an additional parallel ray for each additional this much distance.
29
+ m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE = 0.1
30
+ m.DEFAULT_HIT_PROPORTION = 0.8
31
+
32
+
33
+ def fit_plane(points, refusal_log):
34
+ """
35
+ Fits a plane to the given 3D points.
36
+ Copied from https://stackoverflow.com/a/18968498
37
+
38
+ Args:
39
+ points ((k, 3)-array): th.tensor of shape (k, 3)
40
+ refusal_log (dict): Debugging dictionary to add error messages to
41
+
42
+ Returns:
43
+ 2-tuple:
44
+ - 3-array: (x,y,z) points' centroid
45
+ - 3-array: (x,y,z) normal of the fitted plane
46
+ """
47
+ if points.shape[0] < points.shape[1]:
48
+ if m.DEBUG_SAMPLING:
49
+ refusal_log.append(f"insufficient points to fit a 3D plane: needs 3, has {points.shape[0]}.")
50
+ return None, None
51
+
52
+ ctr = points.mean(dim=0)
53
+ x = points - ctr
54
+ normal = th.linalg.svd(x.T @ x).U[:, -1]
55
+ normal /= th.norm(normal)
56
+ return ctr, normal
57
+
58
+
59
+ def check_distance_to_plane(points, plane_centroid, plane_normal, hit_to_plane_threshold, refusal_log):
60
+ """
61
+ Calculates whether points are within @hit_to_plane_threshold distance to plane defined by @plane_centroid
62
+ and @plane_normal
63
+
64
+ Args:
65
+ points ((k, 3)-array): th.tensor of shape (k, 3)
66
+ plane_centroid (3-array): (x,y,z) points' centroid
67
+ plane_normal (3-array): (x,y,z) normal of the fitted plane
68
+ hit_to_plane_threshold (float): Threshold distance to check between @points and plane
69
+ refusal_log (dict): Debugging dictionary to add error messages to
70
+
71
+ Returns:
72
+ bool: True if all points are within @hit_to_plane_threshold distance to plane, otherwise False
73
+ """
74
+ distances = get_distance_to_plane(points, plane_centroid, plane_normal)
75
+ if th.any(distances > hit_to_plane_threshold):
76
+ if m.DEBUG_SAMPLING:
77
+ refusal_log.append("distances to plane: %r" % distances)
78
+ return False
79
+ return True
80
+
81
+
82
+ def get_distance_to_plane(points, plane_centroid, plane_normal):
83
+ """
84
+ Computes distance from @points to plane defined by @plane_centroid and @plane_normal
85
+
86
+ Args:
87
+ points ((k, 3)-array): th.tensor of shape (k, 3)
88
+ plane_centroid (3-array): (x,y,z) points' centroid
89
+ plane_normal (3-array): (x,y,z) normal of the fitted plane
90
+
91
+ Returns:
92
+ k-array: Absolute distances from each point to the plane
93
+ """
94
+ return th.abs((points - plane_centroid) @ plane_normal)
95
+
96
+
97
+ def get_projection_onto_plane(points, plane_centroid, plane_normal):
98
+ """
99
+ Computes @points' projection onto the plane defined by @plane_centroid and @plane_normal
100
+
101
+ Args:
102
+ points ((k, 3)-array): th.tensor of shape (k, 3)
103
+ plane_centroid (3-array): (x,y,z) points' centroid
104
+ plane_normal (3-array): (x,y,z) normal of the fitted plane
105
+
106
+ Returns:
107
+ (k,3)-array: Points' positions projected onto the plane
108
+ """
109
+ distances_to_plane = get_distance_to_plane(points, plane_centroid, plane_normal)
110
+ return points - th.outer(distances_to_plane, plane_normal)
111
+
112
+
113
+ def draw_debug_markers(hit_positions, radius=0.01):
114
+ """
115
+ Helper method to generate and place debug markers at @hit_positions
116
+
117
+ Args:
118
+ hit_positions ((n, 3)-array): Desired positions to place markers at
119
+ radius (float): Radius of the generated virtual marker
120
+ """
121
+ color = th.cat([th.rand(3), [1]])
122
+ for vec in hit_positions:
123
+ for dim in range(3):
124
+ start_point = vec + th.eye(3)[dim] * radius
125
+ end_point = vec - th.eye(3)[dim] * radius
126
+ draw_line(start_point, end_point, color)
127
+
128
+
129
+ def get_parallel_rays(source, destination, offset, new_ray_per_horizontal_distance):
130
+ """
131
+ Given an input ray described by a source and a destination, sample parallel rays around it as the center.
132
+
133
+ The parallel rays start at the corners of a square of edge length `offset` centered on `source`, with the square
134
+ orthogonal to the ray direction. That is, the cast rays are the height edges of a square-base cuboid with bases
135
+ centered on `source` and `destination`.
136
+
137
+ Args:
138
+ source (3-array): (x,y,z) source of the ray to sample parallel rays of.
139
+ destination (3-array): Source of the ray to sample parallel rays of.
140
+ offset (float): Orthogonal distance of parallel rays from input ray.
141
+ new_ray_per_horizontal_distance (float): Step in offset beyond which an additional split will be applied in the
142
+ parallel ray grid (which at minimum is 3x3 at the AABB corners & center).
143
+
144
+ Returns:
145
+ 3-tuple:
146
+ - list: generated sources from the original ray
147
+ - list: generated destinations from the original ray
148
+ - (W, H, 3)-array: unflattened, untransformed grid of parallel rays in object coordinates
149
+ """
150
+ ray_direction = destination - source
151
+
152
+ # Get an orthogonal vector using a random vector.
153
+ random_vector = th.randn(3)
154
+ random_vector /= th.norm(random_vector)
155
+ orthogonal_vector_1 = th.linalg.cross(ray_direction, random_vector)
156
+ orthogonal_vector_1 /= th.norm(orthogonal_vector_1)
157
+
158
+ # Get a second vector orthogonal to both the ray and the first vector.
159
+ orthogonal_vector_2 = -th.linalg.cross(ray_direction, orthogonal_vector_1)
160
+ orthogonal_vector_2 /= th.norm(orthogonal_vector_2)
161
+
162
+ orthogonal_vectors = th.stack([orthogonal_vector_1, orthogonal_vector_2])
163
+ assert th.all(th.isfinite(orthogonal_vectors))
164
+
165
+ # Convert the offset into a 2-vector if it already isn't one.
166
+ offset = th.tensor([1, 1]) * offset
167
+
168
+ # Compute the grid of rays
169
+ steps = (offset / new_ray_per_horizontal_distance).int() * 2 + 1
170
+ steps = th.maximum(steps, th.tensor(3))
171
+ x_range = th.linspace(-offset[0], offset[0], steps[0])
172
+ y_range = th.linspace(-offset[1], offset[1], steps[1])
173
+ ray_grid = th.stack(th.meshgrid(x_range, y_range, indexing="ij"), dim=-1)
174
+ ray_grid_flattened = ray_grid.reshape(-1, 2)
175
+
176
+ # Apply the grid onto the orthogonal vectors to obtain the rays in the world frame.
177
+ sources = [source + offsets @ orthogonal_vectors for offsets in ray_grid_flattened]
178
+ destinations = [destination + offsets @ orthogonal_vectors for offsets in ray_grid_flattened]
179
+
180
+ return sources, destinations, ray_grid
181
+
182
+
183
+ def sample_origin_positions(mins, maxes, count, bimodal_mean_fraction, bimodal_stdev_fraction, axis_probabilities):
184
+ """
185
+ Sample ray casting origin positions with a given distribution.
186
+
187
+ The way the sampling works is that for each particle, it will sample two coordinates uniformly and one
188
+ using a symmetric, bimodal truncated normal distribution. This way, the particles will mostly be close to the faces
189
+ of the AABB (given a correctly parameterized bimodal truncated normal) and will be spread across each face,
190
+ but there will still be a small number of particles spawned inside the object if it has an interior.
191
+
192
+ Args:
193
+ mins (3-array): the minimum coordinate along each axis.
194
+ maxes (3-array): the maximum coordinate along each axis.
195
+ count (int): Number of origins to sample.
196
+ bimodal_mean_fraction (float): the mean of one side of the symmetric bimodal distribution as a fraction of the
197
+ min-max range.
198
+ bimodal_stdev_fraction (float): the standard deviation of one side of the symmetric bimodal distribution as a
199
+ fraction of the min-max range.
200
+ axis_probabilities (3-array): the probability of ray casting along each axis.
201
+
202
+ Returns:
203
+ list: List where each element is (ray cast axis index, bool whether the axis was sampled from the top side,
204
+ [x, y, z]) tuples.
205
+ """
206
+ assert len(mins.shape) == 1
207
+ assert mins.shape == maxes.shape
208
+
209
+ results = []
210
+ for i in range(count):
211
+ # Get the uniform sample first.
212
+ position = th.rand(3)
213
+
214
+ # Sample the bimodal normal.
215
+ bottom = (0 - bimodal_mean_fraction) / bimodal_stdev_fraction
216
+ top = (1 - bimodal_mean_fraction) / bimodal_stdev_fraction
217
+ bimodal_sample = truncnorm.rvs(bottom, top, loc=bimodal_mean_fraction, scale=bimodal_stdev_fraction)
218
+
219
+ # Pick which axis the bimodal normal sample should go to.
220
+ bimodal_axis = th.multinomial(th.tensor(axis_probabilities, dtype=th.float32), 1).item()
221
+
222
+ # Choose which side of the axis to sample from. We only sample from the top for the Z axis.
223
+ if bimodal_axis == 2:
224
+ bimodal_axis_top_side = True
225
+ else:
226
+ bimodal_axis_top_side = random.choice([True, False])
227
+
228
+ # Move sample based on chosen side.
229
+ position[bimodal_axis] = bimodal_sample if bimodal_axis_top_side else 1 - bimodal_sample
230
+
231
+ # Scale the position from the standard normal range to the min-max range.
232
+ scaled_position = mins + (maxes - mins) * position
233
+
234
+ # Save the result.
235
+ results.append((bimodal_axis, bimodal_axis_top_side, scaled_position))
236
+
237
+ return results
238
+
239
+
240
+ def raytest_batch(
241
+ start_points, end_points, only_closest=True, ignore_bodies=None, ignore_collisions=None, callback=None
242
+ ):
243
+ """
244
+ Computes raytest collisions for a set of rays cast from @start_points to @end_points.
245
+
246
+ Args:
247
+ start_points (list of 3-array): Array of start locations to cast rays, where each is (x,y,z) global
248
+ start location of the ray
249
+ end_points (list of 3-array): Array of end locations to cast rays, where each is (x,y,z) global
250
+ end location of the ray
251
+ only_closest (bool): Whether we report the first (closest) hit from the ray or grab all hits
252
+ ignore_bodies (None or list of str): If specified, specifies absolute USD paths to rigid bodies
253
+ whose collisions should be ignored
254
+ ignore_collisions (None or list of str): If specified, specifies absolute USD paths to collision geoms
255
+ whose collisions should be ignored
256
+ callback (None or function): If specified and @only_closest is False, the custom callback to use per-hit.
257
+ This can be efficient if raytests are meant to terminate early. If None, no custom callback will be used.
258
+ Expected signature is callback(hit) -> bool, which returns True if the raycast should continue or not
259
+
260
+ Returns:
261
+ list of dict or list of list of dict: Results for all rays, where each entry corresponds to the result for the
262
+ ith ray cast. If @only_closest=True, each entry in the list is the closest hit. Otherwise, each entry is
263
+ its own (unordered) list of hits for that ray. Each dict is composed of:
264
+
265
+ "hit" (bool): Whether an object was hit or not
266
+ "position" (3-array): Location of the hit position
267
+ "normal" (3-array): normal vector of the face hit
268
+ "distance" (float): distance from @start_point the hit occurred
269
+ "collision" (str): absolute USD path to the collision body hit
270
+ "rigidBody" (str): absolute USD path to the associated rigid body hit
271
+
272
+ Note that only "hit" = False exists in the dict if no hit was found
273
+ """
274
+ # For now, we do a naive for loop over individual raytests until a better API comes out
275
+ results = []
276
+ for start_point, end_point in zip(start_points, end_points):
277
+ results.append(
278
+ raytest(
279
+ start_point=start_point,
280
+ end_point=end_point,
281
+ only_closest=only_closest,
282
+ ignore_bodies=ignore_bodies,
283
+ ignore_collisions=ignore_collisions,
284
+ callback=callback,
285
+ )
286
+ )
287
+
288
+ return results
289
+
290
+
291
+ def raytest(
292
+ start_point,
293
+ end_point,
294
+ only_closest=True,
295
+ ignore_bodies=None,
296
+ ignore_collisions=None,
297
+ callback=None,
298
+ ):
299
+ """
300
+ Computes raytest collision for ray cast from @start_point to @end_point
301
+
302
+ Args:
303
+ start_point (3-array): (x,y,z) global start location of the ray
304
+ end_point (3-array): (x,y,z) global end location of the ray
305
+ only_closest (bool): Whether we report the first (closest) hit from the ray or grab all hits
306
+ ignore_bodies (None or list of str): If specified, specifies absolute USD paths to rigid bodies
307
+ whose collisions should be ignored
308
+ ignore_collisions (None or list of str): If specified, specifies absolute USD paths to collision geoms
309
+ whose collisions should be ignored
310
+ callback (None or function): If specified and @only_closest is False, the custom callback to use per-hit.
311
+ This can be efficient if raytests are meant to terminate early. If None, no custom callback will be used.
312
+ Expected signature is callback(hit) -> bool, which returns True if the raycast should continue or not
313
+
314
+ Returns:
315
+ dict or list of dict: Results for this raytest. If @only_closest=True, then we only return the information from
316
+ the closest hit. Otherwise, we return an (unordered) list of information for all hits encountered.
317
+ Each dict is composed of:
318
+
319
+ "hit" (bool): Whether an object was hit or not
320
+ "position" (3-array): Location of the hit position
321
+ "normal" (3-array): normal vector of the face hit
322
+ "distance" (float): distance from @start_point the hit occurred
323
+ "collision" (str): absolute USD path to the collision body hit
324
+ "rigidBody" (str): absolute USD path to the associated rigid body hit
325
+
326
+ Note that only "hit" = False exists in the dict if no hit was found
327
+ """
328
+ # Make sure start point, end point are torch tensors
329
+ start_point = th.tensor(start_point) if not isinstance(start_point, th.Tensor) else start_point
330
+ end_point = th.tensor(end_point) if not isinstance(end_point, th.Tensor) else end_point
331
+ point_diff = end_point - start_point
332
+ distance = th.norm(point_diff)
333
+ direction = point_diff / distance
334
+
335
+ # For efficiency's sake, we handle special case of no ignore_bodies, ignore_collisions, and closest_hit
336
+ if only_closest and ignore_bodies is None and ignore_collisions is None:
337
+ result = og.sim.psqi.raycast_closest(
338
+ origin=start_point.tolist(),
339
+ dir=direction.tolist(),
340
+ distance=distance.tolist(),
341
+ )
342
+ if result["hit"]:
343
+ result["position"] = th.tensor(result["position"])
344
+ result["normal"] = th.tensor(result["normal"])
345
+ return result
346
+ else:
347
+ # Compose callback function for finding raycasts
348
+ hits = []
349
+ ignore_bodies = set() if ignore_bodies is None else set(ignore_bodies)
350
+ ignore_collisions = set() if ignore_collisions is None else set(ignore_collisions)
351
+
352
+ def hit_callback(hit):
353
+ # Only add to hits if we're not ignoring this body or collision
354
+ if hit.rigid_body not in ignore_bodies and hit.collision not in ignore_collisions:
355
+ hits.append(
356
+ {
357
+ "hit": True,
358
+ "position": th.tensor(hit.position),
359
+ "normal": th.tensor(hit.normal),
360
+ "distance": hit.distance,
361
+ "collision": hit.collision,
362
+ "rigidBody": hit.rigid_body,
363
+ }
364
+ )
365
+ # We always want to continue traversing to collect all hits
366
+ return True if callback is None else callback(hit)
367
+
368
+ # Grab all collisions
369
+ og.sim.psqi.raycast_all(
370
+ origin=start_point.tolist(),
371
+ dir=direction.tolist(),
372
+ distance=distance.tolist(),
373
+ reportFn=hit_callback,
374
+ )
375
+
376
+ # If we only want the closest, we need to sort these hits, otherwise we return them all
377
+ if only_closest:
378
+ # Return the empty hit dictionary if our ray did not hit anything, otherwise we return the closest
379
+ return {"hit": False} if len(hits) == 0 else sorted(hits, key=lambda hit: hit["distance"])[0]
380
+ else:
381
+ # Return all hits (list)
382
+ return hits
383
+
384
+
385
+ def sample_raytest_start_end_symmetric_bimodal_distribution(
386
+ obj,
387
+ num_samples,
388
+ bimodal_mean_fraction,
389
+ bimodal_stdev_fraction,
390
+ axis_probabilities,
391
+ aabb_offset=None,
392
+ aabb_offset_fraction=None,
393
+ max_sampling_attempts=None,
394
+ ):
395
+ """
396
+ Sample the start points and end points around a given object by a symmetric bimodal distribution
397
+
398
+ obj (DatasetObject): The object to sample points on.
399
+ num_samples (int): the number of points to try to sample.
400
+ bimodal_mean_fraction (float): the mean of one side of the symmetric bimodal distribution as a fraction of the
401
+ min-max range.
402
+ bimodal_stdev_fraction (float): the standard deviation of one side of the symmetric bimodal distribution as a
403
+ fraction of the min-max range.
404
+ axis_probabilities (3-array): probability of ray casting along each axis.
405
+ aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified,
406
+ will override @aabb_offset_fraction
407
+ aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB.
408
+ max_sampling_attempts (int): how many times sampling will be attempted for each requested point.
409
+
410
+ Returns:
411
+ 2-tuple:
412
+ - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the start points for
413
+ raycasting defined in the world frame
414
+ - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the end points for
415
+ raycasting defined in the world frame
416
+ """
417
+ aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION
418
+ max_sampling_attempts = (
419
+ max_sampling_attempts if max_sampling_attempts is not None else m.DEFAULT_MAX_SAMPLING_ATTEMPTS
420
+ )
421
+ bbox_center, bbox_orn, bbox_bf_extent, _ = obj.get_base_aligned_bbox(xy_aligned=True)
422
+ aabb_offset = aabb_offset_fraction * bbox_bf_extent if aabb_offset is None else aabb_offset
423
+ half_extent = bbox_bf_extent / 2
424
+ half_extent_with_offset = half_extent + aabb_offset
425
+
426
+ start_points = th.zeros((num_samples, max_sampling_attempts, 3))
427
+ end_points = th.zeros((num_samples, max_sampling_attempts, 3))
428
+ for i in range(num_samples):
429
+ # Sample the starting positions in advance.
430
+ # TODO: Narrow down the sampling domain so that we don't sample scenarios where the center is in-domain but the
431
+ # full extent isn't. Currently a lot of samples are being wasted because of this.
432
+ samples = sample_origin_positions(
433
+ -half_extent_with_offset,
434
+ half_extent_with_offset,
435
+ max_sampling_attempts,
436
+ bimodal_mean_fraction,
437
+ bimodal_stdev_fraction,
438
+ axis_probabilities,
439
+ )
440
+
441
+ # Try each sampled position in the AABB.
442
+ for j, (axis, is_top, start_point) in enumerate(samples):
443
+ # Compute the ray's destination using the sampling & AABB information.
444
+ end_point = compute_ray_destination(
445
+ axis, is_top, start_point, -half_extent_with_offset, half_extent_with_offset
446
+ )
447
+ start_points[i][j] = start_point
448
+ end_points[i][j] = end_point
449
+
450
+ # Convert the points into the world frame
451
+ orig_shape = start_points.shape
452
+ to_wf_transform = T.pose2mat((bbox_center, bbox_orn))
453
+ start_points = T.transform_points(start_points.reshape(-1, 3), to_wf_transform).reshape(orig_shape)
454
+ end_points = T.transform_points(end_points.reshape(-1, 3), to_wf_transform).reshape(orig_shape)
455
+
456
+ return start_points, end_points
457
+
458
+
459
+ def sample_raytest_start_end_full_grid_topdown(
460
+ obj,
461
+ ray_spacing,
462
+ aabb_offset=None,
463
+ aabb_offset_fraction=None,
464
+ ):
465
+ """
466
+ Sample the start points and end points around a given object by a dense grid from top down.
467
+
468
+ Args:
469
+ obj (DatasetObject): The object to sample points on.
470
+ ray_spacing (float): spacing between the rays, or equivalently, size of the grid cell
471
+ aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified,
472
+ will override @aabb_offset_fraction
473
+ aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB.
474
+
475
+ Returns:
476
+ 2-tuple:
477
+ - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the start points for
478
+ raycasting defined in the world frame
479
+ - (n, s, 3)-array: (num_samples, max_sampling_attempts, 3) shaped array representing the end points for
480
+ raycasting defined in the world frame
481
+ """
482
+ aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION
483
+ bbox_center, bbox_orn, bbox_bf_extent, _ = obj.get_base_aligned_bbox(xy_aligned=True)
484
+ aabb_offset = aabb_offset_fraction * bbox_bf_extent if aabb_offset is None else aabb_offset
485
+
486
+ half_extent_with_offset = (bbox_bf_extent / 2) + aabb_offset
487
+ x = th.linspace(
488
+ -half_extent_with_offset[0], half_extent_with_offset[0], int(half_extent_with_offset[0] * 2 / ray_spacing) + 1
489
+ )
490
+ y = th.linspace(
491
+ -half_extent_with_offset[1], half_extent_with_offset[1], int(half_extent_with_offset[1] * 2 / ray_spacing) + 1
492
+ )
493
+ n_rays = len(x) * len(y)
494
+
495
+ start_points = th.stack(
496
+ [
497
+ th.tile(x, (len(y),)),
498
+ th.repeat_interleave(y, len(x)),
499
+ th.ones(n_rays) * half_extent_with_offset[2],
500
+ ]
501
+ ).T
502
+
503
+ end_points = th.clone(start_points)
504
+ end_points[:, 2] = -half_extent_with_offset[2]
505
+
506
+ # Convert the points into the world frame
507
+ to_wf_transform = T.pose2mat((bbox_center, bbox_orn))
508
+ start_points = T.transform_points(start_points, to_wf_transform)
509
+ end_points = T.transform_points(end_points, to_wf_transform)
510
+
511
+ start_points = th.unsqueeze(start_points, dim=1)
512
+ end_points = th.unsqueeze(end_points, dim=1)
513
+
514
+ return start_points, end_points
515
+
516
+
517
+ def sample_cuboid_on_object_symmetric_bimodal_distribution(
518
+ obj,
519
+ num_samples,
520
+ cuboid_dimensions,
521
+ bimodal_mean_fraction,
522
+ bimodal_stdev_fraction,
523
+ axis_probabilities,
524
+ new_ray_per_horizontal_distance=None,
525
+ hit_proportion=None,
526
+ aabb_offset=None,
527
+ aabb_offset_fraction=None,
528
+ max_sampling_attempts=None,
529
+ max_angle_with_z_axis=None,
530
+ parallel_ray_normal_angle_tolerance=None,
531
+ hit_to_plane_threshold=None,
532
+ cuboid_bottom_padding=None,
533
+ undo_cuboid_bottom_padding=True,
534
+ verify_cuboid_empty=True,
535
+ refuse_downwards=False,
536
+ ):
537
+ """
538
+ Samples points on an object's surface using ray casting.
539
+ Rays are sampled with a symmetric bimodal distribution.
540
+
541
+ Args:
542
+ obj (DatasetObject): The object to sample points on.
543
+ num_samples (int): the number of points to try to sample.
544
+ cuboid_dimensions ((n, 3)-array): Float sequence of len 3, the size of the empty cuboid we are trying to sample.
545
+ Can also provide list of cuboid dimension triplets in which case each i'th sample will be sampled using
546
+ the i'th triplet. Alternatively, cuboid_dimensions can be set to be all zeros if the user just want to
547
+ sample points (instead of cuboids) for significantly better performance. This applies when the user wants
548
+ to sample very small particles.
549
+ bimodal_mean_fraction (float): the mean of one side of the symmetric bimodal distribution as a fraction of the
550
+ min-max range.
551
+ bimodal_stdev_fraction (float): the standard deviation of one side of the symmetric bimodal distribution as a
552
+ fraction of the min-max range.
553
+ axis_probabilities (3-array): the probability of ray casting along each axis.
554
+ new_ray_per_horizontal_distance (float): per this distance of the cuboid dimension, increase the grid size of
555
+ the parallel ray-testing by 1. This controls how fine-grained the grid ray-casting should be with respect to
556
+ the size of the sampled cuboid.
557
+ hit_proportion (float): the minimum percentage of the hits required across the grid.
558
+ aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified,
559
+ will override @aabb_offset_fraction
560
+ aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB.
561
+ max_sampling_attempts (int): how many times sampling will be attempted for each requested point.
562
+ max_angle_with_z_axis (float): maximum angle between hit normal and positive Z axis allowed. Can be used to
563
+ disallow downward-facing hits when refuse_downwards=True.
564
+ parallel_ray_normal_angle_tolerance (float): maximum angle difference between the normal of the center hit
565
+ and the normal of other hits allowed.
566
+ hit_to_plane_threshold (float): how far any given hit position can be from the least-squares fit plane to
567
+ all of the hit positions before the sample is rejected.
568
+ cuboid_bottom_padding (float): additional padding applied to the bottom of the cuboid. This is needed for the
569
+ emptiness check (@check_cuboid_empty) within the cuboid. un_padding=True can be set if the user wants to remove
570
+ the padding after the emptiness check.
571
+ undo_cuboid_bottom_padding (bool): Whether the bottom padding that's applied to the cuboid should be removed before return.
572
+ Useful when the cuboid needs to be flush with the surface for whatever reason. Note that the padding will still
573
+ be applied initially (since it's not possible to do the cuboid emptiness check without doing this - otherwise
574
+ the rays will hit the sampled-on object), so the emptiness check still checks a padded cuboid. This flag will
575
+ simply make the sampler undo the padding prior to returning.
576
+ verify_cuboid_empty (bool): Whether to filter out sampled cuboid locations that are not collision-free. Note
577
+ that this check will only potentially occur if nonzero cuboid dimensions are specified.
578
+ refuse_downwards (bool): whether downward-facing hits (as defined by max_angle_with_z_axis) are allowed.
579
+
580
+ Returns:
581
+ list of tuple: list of length num_samples elements where each element is a tuple in the form of
582
+ (cuboid_centroid, cuboid_up_vector, cuboid_rotation, {refusal_reason: [refusal_details...]}). Cuboid positions
583
+ are set to None when no successful sampling happens within the max number of attempts. Refusal details are only
584
+ filled if the m.DEBUG_SAMPLING flag is globally set to True.
585
+ """
586
+ new_ray_per_horizontal_distance = (
587
+ new_ray_per_horizontal_distance
588
+ if new_ray_per_horizontal_distance is not None
589
+ else m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE
590
+ )
591
+ hit_proportion = hit_proportion if hit_proportion is not None else m.DEFAULT_HIT_PROPORTION
592
+ aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION
593
+ max_sampling_attempts = (
594
+ max_sampling_attempts if max_sampling_attempts is not None else m.DEFAULT_MAX_SAMPLING_ATTEMPTS
595
+ )
596
+ max_angle_with_z_axis = (
597
+ max_angle_with_z_axis if max_angle_with_z_axis is not None else m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS
598
+ )
599
+ parallel_ray_normal_angle_tolerance = (
600
+ parallel_ray_normal_angle_tolerance
601
+ if parallel_ray_normal_angle_tolerance is not None
602
+ else m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE
603
+ )
604
+ hit_to_plane_threshold = (
605
+ hit_to_plane_threshold if hit_to_plane_threshold is not None else m.DEFAULT_HIT_TO_PLANE_THRESHOLD
606
+ )
607
+ cuboid_bottom_padding = (
608
+ cuboid_bottom_padding if cuboid_bottom_padding is not None else m.DEFAULT_CUBOID_BOTTOM_PADDING
609
+ )
610
+ start_points, end_points = sample_raytest_start_end_symmetric_bimodal_distribution(
611
+ obj,
612
+ num_samples,
613
+ bimodal_mean_fraction,
614
+ bimodal_stdev_fraction,
615
+ axis_probabilities,
616
+ aabb_offset=aabb_offset,
617
+ aabb_offset_fraction=aabb_offset_fraction,
618
+ max_sampling_attempts=max_sampling_attempts,
619
+ )
620
+
621
+ return sample_cuboid_on_object(
622
+ obj,
623
+ start_points,
624
+ end_points,
625
+ cuboid_dimensions,
626
+ new_ray_per_horizontal_distance=new_ray_per_horizontal_distance,
627
+ hit_proportion=hit_proportion,
628
+ max_angle_with_z_axis=max_angle_with_z_axis,
629
+ parallel_ray_normal_angle_tolerance=parallel_ray_normal_angle_tolerance,
630
+ hit_to_plane_threshold=hit_to_plane_threshold,
631
+ cuboid_bottom_padding=cuboid_bottom_padding,
632
+ undo_cuboid_bottom_padding=undo_cuboid_bottom_padding,
633
+ verify_cuboid_empty=verify_cuboid_empty,
634
+ refuse_downwards=refuse_downwards,
635
+ )
636
+
637
+
638
+ def sample_cuboid_on_object_full_grid_topdown(
639
+ obj,
640
+ ray_spacing,
641
+ cuboid_dimensions,
642
+ new_ray_per_horizontal_distance=None,
643
+ hit_proportion=None,
644
+ aabb_offset=None,
645
+ aabb_offset_fraction=None,
646
+ max_angle_with_z_axis=None,
647
+ parallel_ray_normal_angle_tolerance=None,
648
+ hit_to_plane_threshold=None,
649
+ cuboid_bottom_padding=None,
650
+ undo_cuboid_bottom_padding=True,
651
+ verify_cuboid_empty=True,
652
+ refuse_downwards=False,
653
+ ):
654
+ """
655
+ Samples points on an object's surface using ray casting.
656
+ Rays are sampled with a dense grid from top down.
657
+
658
+ Args:
659
+ obj (DatasetObject): The object to sample points on.
660
+ ray_spacing (float): spacing between the rays, or equivalently, size of the grid cell, when sampling the
661
+ start and end points. This implicitly determines the number of cuboids that will be sampled.
662
+ cuboid_dimensions ((n, 3)-array): Float sequence of len 3, the size of the empty cuboid we are trying to sample.
663
+ Can also provide list of cuboid dimension triplets in which case each i'th sample will be sampled using
664
+ the i'th triplet. Alternatively, cuboid_dimensions can be set to be all zeros if the user just want to
665
+ sample points (instead of cuboids) for significantly better performance. This applies when the user wants
666
+ to sample very small particles.
667
+ new_ray_per_horizontal_distance (float): per this distance of the cuboid dimension, increase the grid size of
668
+ the parallel ray-testing by 1. This controls how fine-grained the grid ray-casting should be with respect to
669
+ the size of the sampled cuboid.
670
+ hit_proportion (float): the minimum percentage of the hits required across the grid.
671
+ aabb_offset (None or float or 3-array): padding for AABB to initiate ray-testing, in absolute units. If specified,
672
+ will override @aabb_offset_fraction
673
+ aabb_offset_fraction (float or 3-array): padding for AABB to initiate ray-testing, as a fraction of overall AABB.
674
+ max_angle_with_z_axis (float): maximum angle between hit normal and positive Z axis allowed. Can be used to
675
+ disallow downward-facing hits when refuse_downwards=True.
676
+ parallel_ray_normal_angle_tolerance (float): maximum angle difference between the normal of the center hit
677
+ and the normal of other hits allowed.
678
+ hit_to_plane_threshold (float): how far any given hit position can be from the least-squares fit plane to
679
+ all of the hit positions before the sample is rejected.
680
+ cuboid_bottom_padding (float): additional padding applied to the bottom of the cuboid. This is needed for the
681
+ emptiness check (@check_cuboid_empty) within the cuboid. un_padding=True can be set if the user wants to remove
682
+ the padding after the emptiness check.
683
+ undo_cuboid_bottom_padding (bool): Whether the bottom padding that's applied to the cuboid should be removed before return.
684
+ Useful when the cuboid needs to be flush with the surface for whatever reason. Note that the padding will still
685
+ be applied initially (since it's not possible to do the cuboid emptiness check without doing this - otherwise
686
+ the rays will hit the sampled-on object), so the emptiness check still checks a padded cuboid. This flag will
687
+ simply make the sampler undo the padding prior to returning.
688
+ verify_cuboid_empty (bool): Whether to filter out sampled cuboid locations that are not collision-free. Note
689
+ that this check will only potentially occur if nonzero cuboid dimensions are specified.
690
+ refuse_downwards (bool): whether downward-facing hits (as defined by max_angle_with_z_axis) are allowed.
691
+
692
+ Returns:
693
+ list of tuple: list of length num_samples elements where each element is a tuple in the form of
694
+ (cuboid_centroid, cuboid_up_vector, cuboid_rotation, {refusal_reason: [refusal_details...]}). Cuboid positions
695
+ are set to None when no successful sampling happens within the max number of attempts. Refusal details are only
696
+ filled if the m.DEBUG_SAMPLING flag is globally set to True.
697
+ """
698
+ new_ray_per_horizontal_distance = (
699
+ new_ray_per_horizontal_distance
700
+ if new_ray_per_horizontal_distance is not None
701
+ else m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE
702
+ )
703
+ hit_proportion = hit_proportion if hit_proportion is not None else m.DEFAULT_HIT_PROPORTION
704
+ aabb_offset_fraction = aabb_offset_fraction if aabb_offset_fraction is not None else m.DEFAULT_AABB_OFFSET_FRACTION
705
+ max_angle_with_z_axis = (
706
+ max_angle_with_z_axis if max_angle_with_z_axis is not None else m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS
707
+ )
708
+ parallel_ray_normal_angle_tolerance = (
709
+ parallel_ray_normal_angle_tolerance
710
+ if parallel_ray_normal_angle_tolerance is not None
711
+ else m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE
712
+ )
713
+ hit_to_plane_threshold = (
714
+ hit_to_plane_threshold if hit_to_plane_threshold is not None else m.DEFAULT_HIT_TO_PLANE_THRESHOLD
715
+ )
716
+ cuboid_bottom_padding = (
717
+ cuboid_bottom_padding if cuboid_bottom_padding is not None else m.DEFAULT_CUBOID_BOTTOM_PADDING
718
+ )
719
+ start_points, end_points = sample_raytest_start_end_full_grid_topdown(
720
+ obj,
721
+ ray_spacing,
722
+ aabb_offset=aabb_offset,
723
+ aabb_offset_fraction=aabb_offset_fraction,
724
+ )
725
+ return sample_cuboid_on_object(
726
+ obj,
727
+ start_points,
728
+ end_points,
729
+ cuboid_dimensions,
730
+ new_ray_per_horizontal_distance=new_ray_per_horizontal_distance,
731
+ hit_proportion=hit_proportion,
732
+ max_angle_with_z_axis=max_angle_with_z_axis,
733
+ parallel_ray_normal_angle_tolerance=parallel_ray_normal_angle_tolerance,
734
+ hit_to_plane_threshold=hit_to_plane_threshold,
735
+ cuboid_bottom_padding=cuboid_bottom_padding,
736
+ undo_cuboid_bottom_padding=undo_cuboid_bottom_padding,
737
+ verify_cuboid_empty=verify_cuboid_empty,
738
+ refuse_downwards=refuse_downwards,
739
+ )
740
+
741
+
742
+ def sample_cuboid_on_object(
743
+ obj,
744
+ start_points,
745
+ end_points,
746
+ cuboid_dimensions,
747
+ ignore_objs=None,
748
+ new_ray_per_horizontal_distance=None,
749
+ hit_proportion=None,
750
+ max_angle_with_z_axis=None,
751
+ parallel_ray_normal_angle_tolerance=None,
752
+ hit_to_plane_threshold=None,
753
+ cuboid_bottom_padding=None,
754
+ undo_cuboid_bottom_padding=True,
755
+ verify_cuboid_empty=True,
756
+ refuse_downwards=False,
757
+ ):
758
+ """
759
+ Samples points on an object's surface using ray casting.
760
+
761
+ Args:
762
+ obj (DatasetObject): The object to sample points on.
763
+ start_points ((n, s, 3)-array): (num_samples, max_sampling_attempts, 3) shaped array representing the start points for
764
+ raycasting defined in the world frame
765
+ end_points ((n, s, 3)-array): (num_samples, max_sampling_attempts, 3) shaped array representing the end points for
766
+ raycasting defined in the world frame
767
+ cuboid_dimensions ((n, 3)-array): Float sequence of len 3, the size of the empty cuboid we are trying to sample.
768
+ Can also provide list of cuboid dimension triplets in which case each i'th sample will be sampled using
769
+ the i'th triplet. Alternatively, cuboid_dimensions can be set to be all zeros if the user just want to
770
+ sample points (instead of cuboids) for significantly better performance. This applies when the user wants
771
+ to sample very small particles.
772
+ ignore_objs (None or list of EntityPrim): If @obj is None, this can be used to filter objects when checking
773
+ for valid cuboid locations. Any sampled rays that hit an object in @ignore_objs will be ignored. If None,
774
+ no filtering will be used
775
+ new_ray_per_horizontal_distance (float): per this distance of the cuboid dimension, increase the grid size of
776
+ the parallel ray-testing by 1. This controls how fine-grained the grid ray-casting should be with respect to
777
+ the size of the sampled cuboid.
778
+ hit_proportion (float): the minimum percentage of the hits required across the grid.
779
+ max_angle_with_z_axis (float): maximum angle between hit normal and positive Z axis allowed. Can be used to
780
+ disallow downward-facing hits when refuse_downwards=True.
781
+ parallel_ray_normal_angle_tolerance (float): maximum angle difference between the normal of the center hit
782
+ and the normal of other hits allowed.
783
+ hit_to_plane_threshold (float): how far any given hit position can be from the least-squares fit plane to
784
+ all of the hit positions before the sample is rejected.
785
+ cuboid_bottom_padding (float): additional padding applied to the bottom of the cuboid. This is needed for the
786
+ emptiness check (@check_cuboid_empty) within the cuboid. un_padding=True can be set if the user wants to remove
787
+ the padding after the emptiness check.
788
+ undo_cuboid_bottom_padding (bool): Whether the bottom padding that's applied to the cuboid should be removed before return.
789
+ Useful when the cuboid needs to be flush with the surface for whatever reason. Note that the padding will still
790
+ be applied initially (since it's not possible to do the cuboid emptiness check without doing this - otherwise
791
+ the rays will hit the sampled-on object), so the emptiness check still checks a padded cuboid. This flag will
792
+ simply make the sampler undo the padding prior to returning.
793
+ verify_cuboid_empty (bool): Whether to filter out sampled cuboid locations that are not collision-free. Note
794
+ that this check will only potentially occur if nonzero cuboid dimensions are specified.
795
+ refuse_downwards (bool): whether downward-facing hits (as defined by max_angle_with_z_axis) are allowed.
796
+
797
+ Returns:
798
+ list of tuple: list of length num_samples elements where each element is a tuple in the form of
799
+ (cuboid_centroid, cuboid_up_vector, cuboid_rotation, {refusal_reason: [refusal_details...]}). Cuboid positions
800
+ are set to None when no successful sampling happens within the max number of attempts. Refusal details are only
801
+ filled if the m.DEBUG_SAMPLING flag is globally set to True.
802
+ """
803
+ new_ray_per_horizontal_distance = (
804
+ new_ray_per_horizontal_distance
805
+ if new_ray_per_horizontal_distance is not None
806
+ else m.DEFAULT_NEW_RAY_PER_HORIZONTAL_DISTANCE
807
+ )
808
+ hit_proportion = hit_proportion if hit_proportion is not None else m.DEFAULT_HIT_PROPORTION
809
+ max_angle_with_z_axis = (
810
+ max_angle_with_z_axis if max_angle_with_z_axis is not None else m.DEFAULT_MAX_ANGLE_WITH_Z_AXIS
811
+ )
812
+ parallel_ray_normal_angle_tolerance = (
813
+ parallel_ray_normal_angle_tolerance
814
+ if parallel_ray_normal_angle_tolerance is not None
815
+ else m.DEFAULT_PARALLEL_RAY_NORMAL_ANGLE_TOLERANCE
816
+ )
817
+ hit_to_plane_threshold = (
818
+ hit_to_plane_threshold if hit_to_plane_threshold is not None else m.DEFAULT_HIT_TO_PLANE_THRESHOLD
819
+ )
820
+ cuboid_bottom_padding = (
821
+ cuboid_bottom_padding if cuboid_bottom_padding is not None else m.DEFAULT_CUBOID_BOTTOM_PADDING
822
+ )
823
+
824
+ assert (
825
+ start_points.shape == end_points.shape
826
+ ), "the start and end points of raycasting are expected to have the same shape."
827
+ num_samples = start_points.shape[0]
828
+
829
+ if th.any(cuboid_dimensions > 50.0):
830
+ log.warning(
831
+ "WARNING: Trying to sample for a very large cuboid (at least one dimensions > 50). "
832
+ "Terminating immediately, no hits will be registered."
833
+ )
834
+ return [(None, None, None, None, defaultdict(list)) for _ in range(num_samples)]
835
+
836
+ assert cuboid_dimensions.ndim <= 2
837
+ assert cuboid_dimensions.shape[-1] == 3, "Cuboid dimensions need to contain all three dimensions."
838
+ if cuboid_dimensions.ndim == 2:
839
+ assert cuboid_dimensions.shape[0] == num_samples, "Need as many offsets as samples requested."
840
+
841
+ results = [(None, None, None, None, defaultdict(list)) for _ in range(num_samples)]
842
+ rigid_bodies = None if obj is None else {link.prim_path for link in obj.links.values()}
843
+ ignore_rigid_bodies = (
844
+ None
845
+ if ignore_objs is None
846
+ else {link.prim_path for ignore_obj in ignore_objs for link in ignore_obj.links.values()}
847
+ )
848
+
849
+ for i in range(num_samples):
850
+ refusal_reasons = results[i][4]
851
+ # Try each sampled position in the AABB.
852
+ for start_pos, end_pos in zip(start_points[i], end_points[i]):
853
+ # If we have a list of cuboid dimensions, pick the one that corresponds to this particular sample.
854
+ this_cuboid_dimensions = cuboid_dimensions if cuboid_dimensions.ndim == 1 else cuboid_dimensions[i]
855
+
856
+ zero_cuboid_dimension = (this_cuboid_dimensions == 0.0).all()
857
+
858
+ if not zero_cuboid_dimension:
859
+ # Make sure we have valid (nonzero) x and y values
860
+ assert (
861
+ this_cuboid_dimensions[:-1] > 0
862
+ ).all(), f"Cuboid x and y dimensions must not be zero if z dimension is nonzero! Got: {this_cuboid_dimensions}"
863
+ # Obtain the parallel rays using the direction sampling method.
864
+ sources, destinations, grid = get_parallel_rays(
865
+ start_pos,
866
+ end_pos,
867
+ this_cuboid_dimensions[:2] / 2.0,
868
+ new_ray_per_horizontal_distance,
869
+ )
870
+ else:
871
+ sources = [start_pos]
872
+ destinations = [end_pos]
873
+
874
+ # Time to cast the rays.
875
+ cast_results = raytest_batch(
876
+ start_points=sources, end_points=destinations, ignore_bodies=ignore_rigid_bodies
877
+ )
878
+
879
+ # Check whether sufficient number of rays hit the object
880
+ hits = check_rays_hit_object(cast_results, hit_proportion, refusal_reasons["missed_object"], rigid_bodies)
881
+ if hits is None:
882
+ continue
883
+
884
+ center_idx = int(len(hits) / 2)
885
+ # Only consider objects whose center idx has a ray hit
886
+ if not hits[center_idx]:
887
+ continue
888
+
889
+ filtered_cast_results = []
890
+ filtered_center_idx = None
891
+ for idx, hit in enumerate(hits):
892
+ if hit:
893
+ filtered_cast_results.append(cast_results[idx])
894
+ if idx == center_idx:
895
+ filtered_center_idx = len(filtered_cast_results) - 1
896
+
897
+ # Process the hit positions and normals.
898
+ hit_positions = th.stack([ray_res["position"] for ray_res in filtered_cast_results])
899
+ hit_normals = th.stack([ray_res["normal"] for ray_res in filtered_cast_results])
900
+ hit_normals /= th.norm(hit_normals, dim=1, keepdim=True)
901
+
902
+ assert filtered_center_idx is not None
903
+ hit_link = filtered_cast_results[filtered_center_idx]["rigidBody"]
904
+ center_hit_pos = hit_positions[filtered_center_idx]
905
+ center_hit_normal = hit_normals[filtered_center_idx]
906
+
907
+ # Reject anything facing more than 45deg downwards if requested.
908
+ if refuse_downwards:
909
+ if not check_hit_max_angle_from_z_axis(
910
+ center_hit_normal, max_angle_with_z_axis, refusal_reasons["downward_normal"]
911
+ ):
912
+ continue
913
+
914
+ # Check that none of the parallel rays' hit normal differs from center ray by more than threshold.
915
+ if not zero_cuboid_dimension:
916
+ if not check_normal_similarity(
917
+ center_hit_normal,
918
+ hit_normals,
919
+ parallel_ray_normal_angle_tolerance,
920
+ refusal_reasons["hit_normal_similarity"],
921
+ ):
922
+ continue
923
+
924
+ # Fit a plane to the points.
925
+ plane_centroid, plane_normal = fit_plane(hit_positions, refusal_reasons["fit_plane"])
926
+ if plane_centroid is None:
927
+ continue
928
+
929
+ # The fit_plane normal can be facing either direction on the normal axis, but we want it to face away from
930
+ # the object for purposes of normal checking and padding. To do this:
931
+ # We get a vector from the centroid towards the center ray source, and flip the plane normal to match it.
932
+ # The cosine has positive sign if the two vectors are similar and a negative one if not.
933
+ plane_to_source = sources[center_idx] - plane_centroid
934
+ plane_normal *= th.sign(th.dot(plane_to_source, plane_normal))
935
+
936
+ # Check that the plane normal is similar to the hit normal
937
+ if not check_normal_similarity(
938
+ center_hit_normal,
939
+ plane_normal[None, :],
940
+ parallel_ray_normal_angle_tolerance,
941
+ refusal_reasons["plane_normal_similarity"],
942
+ ):
943
+ continue
944
+
945
+ # Check that the points are all within some acceptable distance of the plane.
946
+ if not check_distance_to_plane(
947
+ hit_positions,
948
+ plane_centroid,
949
+ plane_normal,
950
+ hit_to_plane_threshold,
951
+ refusal_reasons["dist_to_plane"],
952
+ ):
953
+ continue
954
+
955
+ # Get projection of the base onto the plane, fit a rotation, and compute the new center hit / corners.
956
+ hit_positions = th.stack([ray_res.get("position", th.tensor([0.0] * 3)) for ray_res in cast_results])
957
+ projected_hits = get_projection_onto_plane(hit_positions, plane_centroid, plane_normal)
958
+ padding = cuboid_bottom_padding * plane_normal
959
+ projected_hits += padding
960
+ center_projected_hit = projected_hits[center_idx]
961
+ cuboid_centroid = center_projected_hit + plane_normal * this_cuboid_dimensions[2] / 2.0
962
+
963
+ rotation = compute_rotation_from_grid_sample(
964
+ grid,
965
+ projected_hits,
966
+ cuboid_centroid,
967
+ this_cuboid_dimensions,
968
+ hits,
969
+ refusal_reasons["rotation_not_computable"],
970
+ )
971
+
972
+ # Make sure there are enough hit points that can be used for alignment to find the rotation
973
+ if rotation is None:
974
+ continue
975
+
976
+ corner_vectors = (
977
+ 0.5
978
+ * this_cuboid_dimensions
979
+ * th.tensor([[1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]], dtype=th.float32)
980
+ )
981
+ corner_positions = cuboid_centroid.unsqueeze(0) + T.quat_apply(rotation, corner_vectors)
982
+
983
+ # Now we use the cuboid's diagonals to check that the cuboid is actually empty
984
+ if verify_cuboid_empty and not check_cuboid_empty(
985
+ plane_normal,
986
+ corner_positions,
987
+ this_cuboid_dimensions,
988
+ refusal_reasons["cuboid_not_empty"],
989
+ ):
990
+ continue
991
+
992
+ if undo_cuboid_bottom_padding:
993
+ cuboid_centroid -= padding
994
+
995
+ else:
996
+ cuboid_centroid = center_hit_pos
997
+ if not undo_cuboid_bottom_padding:
998
+ padding = cuboid_bottom_padding * center_hit_normal
999
+ cuboid_centroid += padding
1000
+ plane_normal = th.zeros(3)
1001
+ rotation = th.tensor([0, 0, 0, 1], dtype=th.float32)
1002
+
1003
+ # We've found a nice attachment point. Continue onto next point to sample.
1004
+ results[i] = (cuboid_centroid, plane_normal, rotation, hit_link, refusal_reasons)
1005
+ break
1006
+
1007
+ if m.DEBUG_SAMPLING:
1008
+ og.log.debug("Sampling rejection reasons:")
1009
+ counter = Counter()
1010
+
1011
+ for instance in results:
1012
+ for reason, refusals in instance[-1].items():
1013
+ counter[reason] += len(refusals)
1014
+
1015
+ og.log.debug("\n".join("%s: %d" % pair for pair in counter.items()))
1016
+
1017
+ return results
1018
+
1019
+
1020
+ def compute_rotation_from_grid_sample(
1021
+ two_d_grid, projected_hits, cuboid_centroid, this_cuboid_dimensions, hits, refusal_log
1022
+ ):
1023
+ """
1024
+ Computes
1025
+
1026
+ Args:
1027
+ two_d_grid (n, 2): (x,y) raycast origin points in the local plane frame
1028
+ projected_hits ((k,3)-array): Points' positions projected onto the plane generated
1029
+ cuboid_centroid (3-array): (x,y,z) sampled position of the hit cuboid centroid in the global frame
1030
+ this_cuboid_dimensions (3-array): (x,y,z) size of cuboid being sampled from the grid
1031
+ hits (list of bool): whether each point from @two_d_grid is a valid hit or not
1032
+ refusal_log (dict): Dictionary to write debugging and log information to
1033
+
1034
+ Returns:
1035
+ None or scipy.Rotation: If successfully hit, returns relative rotation from two_d_grid to
1036
+ generated hit plane. Otherwise, returns None
1037
+ """
1038
+ if sum(hits) < 3:
1039
+ if m.DEBUG_SAMPLING:
1040
+ refusal_log.append(f"insufficient hits to compute the rotation of the grid: needs 3, has {th.sum(hits)}")
1041
+ return None
1042
+
1043
+ grid_in_planar_coordinates = two_d_grid.reshape(-1, 2)
1044
+ grid_in_planar_coordinates = grid_in_planar_coordinates[hits]
1045
+ grid_in_object_coordinates = th.zeros((len(grid_in_planar_coordinates), 3))
1046
+ grid_in_object_coordinates[:, :2] = grid_in_planar_coordinates
1047
+ grid_in_object_coordinates[:, 2] = -this_cuboid_dimensions[2] / 2.0
1048
+
1049
+ projected_hits = projected_hits[hits]
1050
+ sampled_grid_relative_vectors = projected_hits - cuboid_centroid
1051
+
1052
+ rotation = T.align_vector_sets(sampled_grid_relative_vectors, grid_in_object_coordinates)
1053
+
1054
+ return rotation
1055
+
1056
+
1057
+ def check_normal_similarity(center_hit_normal, hit_normals, tolerance, refusal_log):
1058
+ """
1059
+ Check whether the normals from @hit_normals are within some @tolerance of @center_hit_normal.
1060
+
1061
+ Args:
1062
+ center_hit_normal (3-array): normal of the center hit point
1063
+ hit_normals ((n, 3)-array): normals of all the hit points
1064
+ tolerance (float): Acceptable deviation between the center hit normal and all normals
1065
+ refusal_log (dict): Dictionary to write debugging and log information to
1066
+
1067
+ Returns:
1068
+ bool: Whether the normal similarity is acceptable or not
1069
+ """
1070
+ parallel_hit_main_hit_dot_products = th.clip(
1071
+ hit_normals @ center_hit_normal / (th.norm(hit_normals, dim=1) * th.norm(center_hit_normal)),
1072
+ -1.0,
1073
+ 1.0,
1074
+ )
1075
+ parallel_hit_normal_angles_to_hit_normal = th.arccos(parallel_hit_main_hit_dot_products)
1076
+ all_rays_hit_with_similar_normal = th.all(parallel_hit_normal_angles_to_hit_normal < tolerance)
1077
+ if not all_rays_hit_with_similar_normal:
1078
+ if m.DEBUG_SAMPLING:
1079
+ refusal_log.append("angles %r" % (th.rad2deg(parallel_hit_normal_angles_to_hit_normal),))
1080
+
1081
+ return False
1082
+
1083
+ return True
1084
+
1085
+
1086
+ def check_rays_hit_object(cast_results, threshold, refusal_log, body_names=None):
1087
+ """
1088
+ Checks whether rays hit a specific object, as specified by a list of @body_names
1089
+
1090
+ Args:
1091
+ cast_results (list of dict): Output from raycast_batch.
1092
+ threshold (float): Relative ratio in [0, 1] specifying proportion of rays from @cast_results are
1093
+ required to hit @body_names to count as the object being hit
1094
+ refusal_log (list of str): Logging array for adding debug logs
1095
+ body_names (None or list or set of str): absolute USD paths to rigid bodies to check for hit. If not
1096
+ specified, then any valid hit will be accepted
1097
+
1098
+ Returns:
1099
+ None or list of bool: Individual T/F for each ray -- whether it hit the object or not
1100
+ """
1101
+ body_names = None if body_names is None else set(body_names)
1102
+ ray_hits = [
1103
+ ray_res["hit"] and (body_names is None or ray_res["rigidBody"] in body_names) for ray_res in cast_results
1104
+ ]
1105
+ if sum(ray_hits) / len(cast_results) < threshold:
1106
+ if m.DEBUG_SAMPLING:
1107
+ refusal_log.append(
1108
+ f"{sum(ray_hits)} / {len(cast_results)} < {threshold} hits: {[ray_res['rigidBody'] for ray_res in cast_results if ray_res['hit']]}"
1109
+ )
1110
+
1111
+ return None
1112
+
1113
+ return ray_hits
1114
+
1115
+
1116
+ def check_hit_max_angle_from_z_axis(hit_normal, max_angle_with_z_axis, refusal_log):
1117
+ """
1118
+ Check whether the normal @hit_normal deviates from the global z axis by more than @max_angle_with_z_axis
1119
+
1120
+ Args:
1121
+ hit_normal (3-array): Normal vector to check with respect to global z-axis
1122
+ max_angle_with_z_axis (float): Maximum acceptable angle between the global z-axis and @hit_normal
1123
+ refusal_log (list of str): Logging array for adding debug logs
1124
+
1125
+ Returns:
1126
+ bool: True if the angle between @hit_normal and the global z-axis is less than @max_angle_with_z_axis,
1127
+ otherwise False
1128
+ """
1129
+ hit_angle_with_z = th.arccos(th.clip(th.dot(hit_normal, th.tensor([0.0, 0.0, 1.0])), -1.0, 1.0))
1130
+ if hit_angle_with_z > max_angle_with_z_axis:
1131
+ if m.DEBUG_SAMPLING:
1132
+ refusal_log.append("normal %r" % hit_normal)
1133
+
1134
+ return False
1135
+
1136
+ return True
1137
+
1138
+
1139
+ def compute_ray_destination(axis, is_top, start_pos, aabb_min, aabb_max):
1140
+ """
1141
+ Compute the point on the AABB defined by @aabb_min and @aabb_max from shooting a ray at @start_pos
1142
+ in the direction defined by global axis @axis and @is_top
1143
+
1144
+ Args:
1145
+ axis (int): Which direction to compute the ray destination. Valid options are {0, 1, 2} -- the
1146
+ x, y, or z axes
1147
+ is_top (bool): Whether to shoot in the positive or negative @axis direction
1148
+ aabb_min (3-array): (x,y,z) position defining the lower corner of the AABB
1149
+ aabb_max (3-array): (x,y,z) position defining the upper corner of the AABB
1150
+
1151
+ Returns:
1152
+ 3-array: computed (x,y,z) point on the AABB surface
1153
+ """
1154
+ # Get the ray casting direction - we want to do it parallel to the sample axis.
1155
+ ray_direction = th.tensor([0, 0, 0])
1156
+ ray_direction[axis] = 1
1157
+ ray_direction *= -1 if is_top else 1
1158
+
1159
+ # We want to extend our ray until it intersects one of the AABB's faces.
1160
+ # Start by getting the distances towards the min and max boundaries of the AABB on each axis.
1161
+ point_to_min = aabb_min - start_pos
1162
+ point_to_max = aabb_max - start_pos
1163
+
1164
+ # Then choose the distance to the point in the correct direction on each axis.
1165
+ closer_point_on_each_axis = th.where(ray_direction < 0, point_to_min, point_to_max)
1166
+
1167
+ # For each axis, find how many times the ray direction should be multiplied to reach the AABB's boundary.
1168
+ multiple_to_face_on_each_axis = closer_point_on_each_axis / ray_direction
1169
+
1170
+ # Choose the minimum of these multiples, e.g. how many times the ray direction should be multiplied
1171
+ # to reach the nearest boundary.
1172
+ multiple_to_face = th.min(multiple_to_face_on_each_axis[th.isfinite(multiple_to_face_on_each_axis)]).item()
1173
+
1174
+ # Finally, use the multiple we found to calculate the point on the AABB boundary that we want to cast our
1175
+ # ray until.
1176
+ point_on_face = start_pos + ray_direction * multiple_to_face
1177
+
1178
+ # Make sure that we did not end up with all NaNs or infinities due to division issues.
1179
+ assert not th.any(th.isnan(point_on_face)) and not th.any(th.isinf(point_on_face))
1180
+
1181
+ return point_on_face
1182
+
1183
+
1184
+ def check_cuboid_empty(hit_normal, bottom_corner_positions, this_cuboid_dimensions, refusal_log):
1185
+ """
1186
+ Check whether the cuboid defined by @this_cuboid_dimensions and @bottom_corner_positions contains
1187
+ empty space or not
1188
+
1189
+ Args:
1190
+ hit_normal (3-array): (x,y,z) normal
1191
+ bottom_corner_positions ((4, 3)-array): the positions defining the bottom corners of the cuboid
1192
+ being sampled
1193
+ this_cuboid_dimensions (3-array): (x,y,z) size of the sampled cuboid
1194
+ refusal_log (list of str): Logging array for adding debug logs
1195
+
1196
+ Returns:
1197
+ bool: True if the cuboid is empty, else False
1198
+ """
1199
+ if m.DEBUG_SAMPLING:
1200
+ draw_debug_markers(bottom_corner_positions)
1201
+
1202
+ # Compute top corners.
1203
+ top_corner_positions = bottom_corner_positions + hit_normal * this_cuboid_dimensions[2]
1204
+
1205
+ # We only generate valid rays that have nonzero distances. If the inputted cuboid is flat (i.e.: one dimension
1206
+ # is zero, i.e.: it is in fact a rectangle), raise an error
1207
+ assert this_cuboid_dimensions[2] != 0, "Cannot check empty cuboid for cuboid with zero height!"
1208
+
1209
+ # Get all the top-to-bottom corner pairs.
1210
+ # When we cast these rays, we check that the faces & volume of the cuboid are unoccupied.
1211
+ top_to_bottom_pairs = list(itertools.product(top_corner_positions, bottom_corner_positions))
1212
+
1213
+ # Get all the same-height pairs. These also check that the surfaces areas are empty.
1214
+ bottom_pairs = list(itertools.combinations(bottom_corner_positions, 2))
1215
+ top_pairs = list(itertools.combinations(top_corner_positions, 2))
1216
+
1217
+ # Combine all these pairs, cast the rays, and make sure the rays don't hit anything.
1218
+ pairs_list = top_to_bottom_pairs + bottom_pairs + top_pairs
1219
+ all_pairs = th.stack([th.cat([pair[0], pair[1]]) for pair in pairs_list])
1220
+ check_cast_results = raytest_batch(start_points=all_pairs[:, :3], end_points=all_pairs[:, 3:])
1221
+ if any(ray["hit"] for ray in check_cast_results):
1222
+ if m.DEBUG_SAMPLING:
1223
+ refusal_log.append("check ray info: %r" % (check_cast_results))
1224
+
1225
+ return False
1226
+
1227
+ return True
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/sim_utils.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import omnigibson.lazy as lazy
2
+ from omnigibson.utils import python_utils
3
+
4
+
5
+ def meets_minimum_isaac_version(minimum_version, current_version=None):
6
+ def _transform_isaac_version(str):
7
+ # In order to avoid issues with the version scheme change from 202X.X.X to X.X.X,
8
+ # transform Isaac Sim versions to all not be 202x-based e.g. 2021.2.3 -> 1.2.3
9
+ return str[3:] if str.startswith("202") else str
10
+
11
+ # If the user has not provided the current Isaac version, get it from the system.
12
+ if current_version is None:
13
+ current_version = lazy.isaacsim.core.version.get_version()[0]
14
+
15
+ # Transform and compare.
16
+ return python_utils.meets_minimum_version(
17
+ _transform_isaac_version(current_version), _transform_isaac_version(minimum_version)
18
+ )
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/teleop_utils.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from dataclasses import dataclass, field
3
+ from typing import Iterable, Literal, Optional, Tuple
4
+
5
+ import torch as th
6
+
7
+ import omnigibson as og
8
+ import omnigibson.lazy as lazy
9
+ import omnigibson.utils.transform_utils as T
10
+ from omnigibson.macros import create_module_macros
11
+ from omnigibson.prims.geom_prim import GeomPrim
12
+ from omnigibson.prims.xform_prim import XFormPrim
13
+ from omnigibson.controllers import ControllerView
14
+ from omnigibson.robots.robot import Robot
15
+ from omnigibson.sensors import VisionSensor
16
+ from omnigibson.utils.ui_utils import KeyboardEventHandler, create_module_logger
17
+ from omnigibson.utils.usd_utils import scene_relative_prim_path_to_absolute
18
+
19
+ try:
20
+ from telemoma.configs.base_config import teleop_config
21
+
22
+ # TODO: the imported telemoma interfaces does not work for our purposes because
23
+ # 1) dimensionality mismatch - telemoma torso action is 1 dim 2) telemoma strictly uses numpy
24
+ # from telemoma.human_interface.teleop_core import TeleopAction, TeleopObservation
25
+ from telemoma.human_interface.teleop_policy import TeleopPolicy
26
+ from telemoma.utils.general_utils import AttrDict
27
+ except ImportError as e:
28
+ raise e from ValueError("For teleoperation, install telemoma by running 'pip install telemoma'")
29
+
30
+ # Create module logger
31
+ log = create_module_logger(module_name=__name__)
32
+
33
+ m = create_module_macros(module_path=__file__)
34
+ m.movement_speed = 0.5 # the speed of the robot base movement
35
+ m.rotation_speed = 0.1
36
+
37
+
38
+ @dataclass
39
+ class TeleopAction(AttrDict):
40
+ left: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(1))))
41
+ right: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(1))))
42
+ base: th.Tensor = field(default_factory=lambda: th.zeros(3))
43
+ torso: float = field(default_factory=lambda: 0.0)
44
+ extra: dict = field(default_factory=dict)
45
+
46
+
47
+ @dataclass
48
+ class TeleopObservation(AttrDict):
49
+ left: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(2))))
50
+ right: th.Tensor = field(default_factory=lambda: th.cat((th.zeros(6), th.ones(2))))
51
+ base: th.Tensor = field(default_factory=lambda: th.zeros(3))
52
+ torso: float = field(default_factory=lambda: 0.0)
53
+ extra: dict = field(default_factory=dict)
54
+
55
+
56
+ class TeleopSystem(TeleopPolicy):
57
+ """
58
+ Base class for teleop policy
59
+ """
60
+
61
+ def __init__(self, config: AttrDict, robot: Optional[Robot] = None, show_control_marker: bool = False) -> None:
62
+ """
63
+ Initializes the Teleoperation System
64
+ Args:
65
+ config (AttrDict): configuration dictionary
66
+ robot (Optional[Robot]): the robot that will be controlled. Can be None.
67
+ show_control_marker (bool): whether to show a visual marker that indicates the target pose of the control.
68
+ """
69
+ super().__init__(config)
70
+ self.teleop_action = TeleopAction()
71
+ self.robot_obs = TeleopObservation()
72
+ self.robot = robot
73
+ self.robot_arms = None if not self.robot else ["left", "right"] if self.robot.n_arms == 2 else ["right"]
74
+ # robot parameters
75
+ self.movement_speed = m.movement_speed
76
+ self.rotation_speed = m.rotation_speed
77
+ self.show_control_marker = show_control_marker
78
+
79
+ def get_obs(self) -> TeleopObservation:
80
+ """
81
+ Retrieve observation data from robot
82
+ Returns:
83
+ TeleopObservation: dataclass containing robot observations
84
+ """
85
+ robot_obs = TeleopObservation()
86
+
87
+ if self.robot is None:
88
+ return robot_obs
89
+
90
+ base_pos, base_orn = self.robot.get_position_orientation()
91
+ robot_obs.base = th.cat((base_pos[:2], th.tensor([T.quat2euler(base_orn)[2]])))
92
+
93
+ if self.robot_arms:
94
+ for i, arm in enumerate(self.robot_arms):
95
+ abs_cur_pos, abs_cur_orn = self.robot.eef_links[
96
+ self.robot.arm_names[self.robot_arms.index(arm)]
97
+ ].get_position_orientation()
98
+ rel_cur_pos, rel_cur_orn = T.relative_pose_transform(abs_cur_pos, abs_cur_orn, base_pos, base_orn)
99
+ gripper_pos = th.mean(
100
+ self.robot.get_joint_positions(normalized=True)[
101
+ self.robot.gripper_control_idx[self.robot.arm_names[i]]
102
+ ]
103
+ ).unsqueeze(0)
104
+ # if we are grasping, we manually set the gripper position to be at most 0.5
105
+ gripper_group_key, gripper_ci = self.robot.controllers[f"gripper_{self.robot.arm_names[i]}"]
106
+ if ControllerView.is_grasping(gripper_group_key, gripper_ci):
107
+ gripper_pos = th.min(gripper_pos, th.tensor([0.5]))
108
+ robot_obs[arm] = th.cat((rel_cur_pos, rel_cur_orn, gripper_pos))
109
+
110
+ return robot_obs
111
+
112
+ def get_action(self, obs: TeleopObservation) -> th.Tensor:
113
+ """
114
+ Generate action data from VR input for robot teleoperation
115
+ Args:
116
+ robot_obs (TeleopObservation): dataclass containing robot observations
117
+ Returns:
118
+ th.Tensor: array of action data or None if robot is None
119
+ """
120
+ if self.robot is None:
121
+ return None
122
+
123
+ # get teleop action
124
+ self.teleop_action = super().get_action(obs)
125
+ return self.robot.teleop_data_to_action(self.teleop_action)
126
+
127
+ def reset(self) -> None:
128
+ """
129
+ Reset the teleop policy
130
+ """
131
+ self.teleop_action = TeleopAction()
132
+ self.robot_obs = TeleopObservation()
133
+ for interface in self.interfaces.values():
134
+ interface.reset_state()
135
+
136
+
137
+ class OVXRSystem(TeleopSystem):
138
+ """
139
+ VR Teleoperation System build on top of Omniverse XR extension and TeleMoMa's TeleopSystem
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ robot: Robot,
145
+ show_control_marker: bool = True,
146
+ system: str = "SteamVR",
147
+ disable_display_output: bool = False,
148
+ eef_tracking_mode: Literal["controller", "hand", "disabled"] = "controller",
149
+ # TODO: fix this to only take something like a prim path
150
+ align_anchor_to: Literal["camera", "base", "touchpad"] = "camera",
151
+ view_angle_limits: Optional[Iterable[float]] = None,
152
+ ) -> None:
153
+ """
154
+ Initializes the VR system
155
+ Args:
156
+ robot (Robot): the robot that VR will control.
157
+ show_control_marker (bool): whether to show a control marker
158
+ system (str): the VR system to use, one of ["OpenXR", "SteamVR"], default is "SteamVR".
159
+ disable_display_output (bool): whether we will not display output to the VR headset (only use controller tracking), default is False.
160
+ eef_tracking_mode (Literal): whether to use controller tracking or hand tracking, one of ["controller", "hand", "disabled"], default is controller.
161
+ align_anchor_to (Literal): specify where the VR view aligns to, one of ["camera", "base", "touchpad"], defaults to robot camera.
162
+ The "touchpad" option enables free movement of the VR view (i.e. the user), while the other two constrain the VR view to the either the robot base or camera pose.
163
+ view_angle_limits (Iterable): the view angle limits for the VR system (roll, pitch, and yaw) in degrees, default is None.
164
+ """
165
+ align_to_prim = isinstance(align_anchor_to, XFormPrim)
166
+ assert (
167
+ align_anchor_to
168
+ in [
169
+ "camera",
170
+ "base",
171
+ "touchpad",
172
+ ]
173
+ or align_to_prim
174
+ ), "align_anchor_to must be one of ['camera', 'base', 'touchpad'] or a XFormPrim"
175
+ self.align_anchor_to = align_anchor_to
176
+ self.anchor_prim = None
177
+ if align_to_prim:
178
+ self.set_anchor_with_prim(self.align_anchor_to)
179
+ self.raw_data = {}
180
+ self.old_raw_data = {}
181
+ # run super method
182
+ super().__init__(teleop_config, robot, show_control_marker)
183
+ # get xr core and profile
184
+ self.xr_core = lazy.omni.kit.xr.core.XRCore.get_singleton()
185
+ self.vr_profile = self.xr_core.get_profile("vr")
186
+ self.disable_display_output = disable_display_output
187
+ # visualize control markers
188
+ lazy.carb.settings.get_settings().set(
189
+ "/defaults/xr/profile/" + self.xr_core.get_current_profile_name() + "/controllers/visible",
190
+ self.show_control_marker,
191
+ )
192
+ # set override leveled basis to be true (if this is false, headset would not track anchor pitch orientation)
193
+ allow_roll = False if align_anchor_to == "touchpad" else True
194
+ lazy.carb.settings.get_settings().set(
195
+ self.vr_profile.get_persistent_path() + "overrideLeveledBasis", allow_roll
196
+ )
197
+ # set anchor mode to be custom anchor
198
+ lazy.carb.settings.get_settings().set(
199
+ self.vr_profile.get_scene_persistent_path() + "anchorMode", "custom_anchor"
200
+ )
201
+ if align_anchor_to != "touchpad":
202
+ # set override leveled basis to be true (if this is false, headset would not track anchor pitch orientation)
203
+ lazy.carb.settings.get_settings().set(self.vr_profile.get_persistent_path() + "overrideLeveledBasis", True)
204
+ # set vr system
205
+ lazy.carb.settings.get_settings().set(self.vr_profile.get_persistent_path() + "system/display", system)
206
+ # set display mode
207
+ lazy.carb.settings.get_settings().set(
208
+ self.vr_profile.get_persistent_path() + "disableDisplayOutput", disable_display_output
209
+ )
210
+ lazy.carb.settings.get_settings().set("/rtx/rendermode", "RaytracedLighting")
211
+ # devices info
212
+ self.hmd = None
213
+ self.controllers = {}
214
+ self.trackers = {}
215
+ # setup event subscriptions
216
+ self.reset()
217
+ self.eef_tracking_mode = eef_tracking_mode
218
+ if eef_tracking_mode == "hand":
219
+ self.raw_data["hand_data"] = {}
220
+ self.teleop_action.hand_data = {}
221
+ self._hand_tracking_subscription = self.xr_core.get_message_bus().create_subscription_to_pop_by_type(
222
+ lazy.omni.kit.xr.core.XRCoreEventType.hand_joints, self._update_hand_tracking_data, name="hand tracking"
223
+ )
224
+ self.robot_cameras = (
225
+ [s for s in self.robot.sensors.values() if isinstance(s, VisionSensor)] if self.robot else []
226
+ )
227
+ # TODO: this camera id is specific to R1, because it has 3 cameras, we need to make this more general
228
+ self.active_camera_id = 2
229
+ if self.align_anchor_to == "camera" and len(self.robot_cameras) == 0:
230
+ raise ValueError("No camera found on robot, cannot align anchor to camera")
231
+ # we want to further slow down the movement speed if we are using touchpad movement
232
+ if self.align_anchor_to == "touchpad":
233
+ self.movement_speed *= 0.1
234
+ self.rotation_speed *= 0.3
235
+
236
+ self.head_canonical_transformation = None
237
+ KeyboardEventHandler.add_keyboard_callback(
238
+ key=lazy.carb.input.KeyboardInput.R,
239
+ callback_fn=self.register_head_canonical_transformation,
240
+ )
241
+ KeyboardEventHandler.add_keyboard_callback(
242
+ key=lazy.carb.input.KeyboardInput.Q,
243
+ callback_fn=self.stop,
244
+ )
245
+ self._update_camera_callback = self.xr_core.get_message_bus().create_subscription_to_pop_by_type(
246
+ lazy.omni.kit.xr.core.XRCoreEventType.pre_sync_update, self._update_camera_pose, name="update camera"
247
+ )
248
+
249
+ self._view_blackout_prim = None
250
+ self._view_angle_limits = (
251
+ [T.deg2rad(limit) for limit in view_angle_limits] if view_angle_limits is not None else None
252
+ )
253
+ if self._view_angle_limits is not None:
254
+ scene = self.robot.scene
255
+ blackout_relative_path = "/view_blackout"
256
+ blackout_prim_path = scene_relative_prim_path_to_absolute(scene, blackout_relative_path)
257
+ blackout_sphere = lazy.pxr.UsdGeom.Sphere.Define(og.sim.stage, blackout_prim_path)
258
+ blackout_sphere.CreateRadiusAttr().Set(0.1)
259
+ blackout_sphere.CreateDisplayColorAttr().Set(lazy.pxr.Vt.Vec3fArray([255, 255, 255]))
260
+ self._view_blackout_prim = GeomPrim(
261
+ relative_prim_path=blackout_relative_path,
262
+ name="view_blackout",
263
+ )
264
+ self._view_blackout_prim.load(scene)
265
+ self._view_blackout_prim.initialize()
266
+ self._view_blackout_prim.visible = False
267
+
268
+ def _update_camera_pose(self, e) -> None:
269
+ if self.align_anchor_to == "touchpad":
270
+ # we use x, y from right controller for 2d movement and y from left controller for z movement
271
+ self._move_anchor(
272
+ pos_offset=th.cat((th.tensor([self.teleop_action.torso]), self.teleop_action.base[[0, 2]]))
273
+ )
274
+ else:
275
+ if self.anchor_prim is not None:
276
+ reference_frame = self.anchor_prim
277
+ elif self.align_anchor_to == "camera":
278
+ reference_frame = self.robot_cameras[self.active_camera_id]
279
+ elif self.align_anchor_to == "base":
280
+ reference_frame = self.robot
281
+ else:
282
+ raise ValueError(f"Invalid anchor: {self.align_anchor_to}")
283
+
284
+ anchor_pos, anchor_orn = reference_frame.get_position_orientation()
285
+
286
+ if self.head_canonical_transformation is not None:
287
+ current_head_physical_world_pose = self.xr2og(self.hmd.get_pose())
288
+ # Find the orientation change from canonical to current physical orientation
289
+ _, relative_orientation = T.relative_pose_transform(
290
+ *current_head_physical_world_pose, *self.head_canonical_transformation
291
+ )
292
+ anchor_orn = T.quat_multiply(anchor_orn, relative_orientation)
293
+
294
+ if self._view_blackout_prim is not None:
295
+ relative_ori_in_euler = T.quat2euler(relative_orientation)
296
+ roll_limit, pitch_limit, yaw_limit = self._view_angle_limits
297
+ # OVXR has a different coordinate system than OmniGibson
298
+ if (
299
+ abs(relative_ori_in_euler[0]) > pitch_limit
300
+ or abs(relative_ori_in_euler[1]) > yaw_limit
301
+ or abs(relative_ori_in_euler[2]) > roll_limit
302
+ ):
303
+ self._view_blackout_prim.set_position_orientation(anchor_pos, anchor_orn)
304
+ self._view_blackout_prim.visible = True
305
+ else:
306
+ self._view_blackout_prim.visible = False
307
+ anchor_pose = self.og2xr(anchor_pos, anchor_orn)
308
+ self.xr_core.schedule_set_camera(anchor_pose.numpy())
309
+
310
+ def register_head_canonical_transformation(self):
311
+ """
312
+ Here's what we need to do:
313
+ 1) Let the user press a button to record head canonical orientation (GELLO and head facing forward)
314
+ 2) when the user turn their head, get orientation change from canonical to current physical orientation as R
315
+ 3) set the head in virtual world to robot head orientation + R, same position
316
+ """
317
+ if self.hmd is None:
318
+ log.warning("No HMD found, cannot register head canonical orientation")
319
+ return
320
+ self.head_canonical_transformation = self.xr2og(self.hmd.get_pose())
321
+
322
+ def set_anchor_with_prim(self, prim) -> None:
323
+ """
324
+ Set the anchor to a prim
325
+ Args:
326
+ prim (BasePrim): the prim to set the anchor to
327
+ """
328
+ self.anchor_prim = prim
329
+
330
+ def xr2og(self, transform: th.tensor) -> Tuple[th.tensor, th.tensor]:
331
+ """
332
+ Apply the orientation offset from the Omniverse XR coordinate system to the OmniGibson coordinate system
333
+ Note that we have to transpose the transform matrix because Omniverse uses row-major matrices
334
+ while OmniGibson uses column-major matrices
335
+ Args:
336
+ transform (th.tensor): the transform matrix in the Omniverse XR coordinate system
337
+ Returns:
338
+ tuple(th.tensor, th.Tensor): the position and orientation in the OmniGibson coordinate system
339
+ """
340
+ pos, orn = T.mat2pose(th.tensor(transform).T)
341
+ return pos, orn
342
+
343
+ def og2xr(self, pos: th.tensor, orn: th.tensor) -> th.Tensor:
344
+ """
345
+ Apply the orientation offset from the OmniGibson coordinate system to the Omniverse XR coordinate system
346
+ Args:
347
+ pos (th.tensor): the position in the OmniGibson coordinate system
348
+ orn (th.tensor): the orientation in the OmniGibson coordinate system
349
+ Returns:
350
+ th.tensor: the transform matrix in the Omniverse XR coordinate system
351
+ """
352
+ return T.pose2mat((pos, orn)).T.double()
353
+
354
+ def reset(self) -> None:
355
+ """
356
+ Reset the teleop policy
357
+ """
358
+ super().reset()
359
+ self.raw_data = {}
360
+ self.old_raw_data = {}
361
+ self.teleop_action.is_valid = {"left": False, "right": False, "head": False}
362
+ self.teleop_action.reset = {"left": False, "right": False}
363
+ self.teleop_action.head = th.zeros(6)
364
+
365
+ @property
366
+ def is_enabled(self) -> bool:
367
+ """
368
+ Checks whether the VR system is enabled
369
+ Returns:
370
+ bool: whether the VR system is enabled
371
+ """
372
+ return self.vr_profile.is_enabled()
373
+
374
+ def start(self) -> None:
375
+ """
376
+ Enabling the VR profile
377
+ """
378
+ self.vr_profile.request_enable_profile()
379
+ og.sim.app.update()
380
+ assert self.vr_profile.is_enabled(), "[VRSys] VR profile not enabled!"
381
+ # We want to make sure the hmd is tracking so that the whole system is ready to go
382
+ while True:
383
+ print("[VRSys] Waiting for VR headset and controllers to become active...")
384
+ og.sim.app.update()
385
+ self._update_devices()
386
+ if self.hmd is not None and "left" in self.controllers and "right" in self.controllers:
387
+ print("[VRSys] VR headset connected, put on the headset to start")
388
+ # When taking the first step, xr internally calls clear_controller_model(hand) which removes a prim from stage
389
+ # note that this does not invalidate the physics sim view but instead removes the physics view from articulation views
390
+ # og.sim.step()
391
+ # at this point we need to reinitialize the invalidated views
392
+ # og.sim.update_handles()
393
+ # for idx in range(50):
394
+ # self.update()
395
+ # # somehow, internally xr calls clear_controller_model(hand) which removes a prim from stage;
396
+ # # note that this does not invalidate the physics sim view but instead removes the physics view from articulation views
397
+ # breakpoint()
398
+ # og.sim.step()
399
+ # breakpoint()
400
+ print("[VRSys] VR system is ready")
401
+ self.register_head_canonical_transformation()
402
+ og.sim.step()
403
+ self.reset_head_transform()
404
+ og.sim.step()
405
+ break
406
+ time.sleep(1)
407
+
408
+ def stop(self) -> None:
409
+ """
410
+ disable VR profile
411
+ """
412
+ self.xr_core.request_disable_profile()
413
+ og.sim.step()
414
+ assert not self.vr_profile.is_enabled(), "[VRSys] VR profile not disabled!"
415
+
416
+ def update(self, optimized_for_tour=False) -> None:
417
+ """
418
+ Steps the VR system and update self.teleop_action
419
+ """
420
+ # update raw data
421
+ self.old_raw_data = self.raw_data
422
+ self.raw_data = {}
423
+ if not optimized_for_tour:
424
+ self._update_devices()
425
+ self._update_device_transforms()
426
+ self._update_button_data()
427
+
428
+ # Fire the button callbacks
429
+ for controller_name, controller_button_datas in self.raw_data["button_data"].items():
430
+ for button_name, button_data in controller_button_datas.items():
431
+ print(button_data)
432
+ button_pressed = button_data["click"]
433
+ if button_pressed and not self.old_raw_data["button_data"][controller_name][button_name]["click"]:
434
+ print(f"Button {button_name} pressed on controller {controller_name}")
435
+ KeyboardEventHandler.xr_callback(controller_name, button_name)
436
+
437
+ # Update teleop data based on controller input
438
+ if self.eef_tracking_mode == "controller":
439
+ # update eef related info
440
+ for arm_name, arm in zip(["left", "right"], self.robot_arms):
441
+ if arm in self.controllers:
442
+ controller_pose_in_robot_frame = self._pose_in_robot_frame(
443
+ self.raw_data["transforms"]["controllers"][arm][0],
444
+ self.raw_data["transforms"]["controllers"][arm][1],
445
+ )
446
+ # When trigger is pressed, this value would be 1.0, otherwise 0.0
447
+ # Our multi-finger gripper controller closes the gripper when the value is -1.0 and opens when > 0.0
448
+ # So we need to negate the value here
449
+ trigger_press = (
450
+ -self.raw_data["button_data"][arm]["trigger"]["value"]
451
+ if (
452
+ "button_data" in self.raw_data
453
+ and arm in self.raw_data["button_data"]
454
+ and "trigger" in self.raw_data["button_data"][arm]
455
+ )
456
+ else 0.0
457
+ )
458
+ self.teleop_action[arm_name] = th.cat(
459
+ (
460
+ controller_pose_in_robot_frame[0],
461
+ T.quat2axisangle(
462
+ T.quat_multiply(
463
+ controller_pose_in_robot_frame[1],
464
+ self.robot.teleop_rotation_offset[arm_name],
465
+ )
466
+ ),
467
+ th.tensor([trigger_press], dtype=th.float32),
468
+ )
469
+ )
470
+ self.teleop_action.is_valid[arm_name] = self._is_valid_transform(
471
+ self.raw_data["transforms"]["controllers"][arm]
472
+ )
473
+ else:
474
+ self.teleop_action.is_valid[arm_name] = False
475
+
476
+ # update base, torso, and reset info
477
+ self.teleop_action.base = th.zeros(3)
478
+ self.teleop_action.torso = 0.0
479
+ for controller_name in self.controllers.keys():
480
+ if "button_data" not in self.raw_data:
481
+ continue
482
+ if controller_name == "right" and "right" in self.raw_data["button_data"]:
483
+ thumbstick = self.raw_data["button_data"][controller_name]["thumbstick"]
484
+ self.teleop_action.base[2] = -thumbstick["x"] * self.rotation_speed
485
+ self.teleop_action.torso = -thumbstick["y"] * self.movement_speed
486
+ elif controller_name == "left" and "left" in self.raw_data["button_data"]:
487
+ thumbstick = self.raw_data["button_data"][controller_name]["thumbstick"]
488
+ self.teleop_action.base[0] = thumbstick["y"] * self.movement_speed
489
+ self.teleop_action.base[1] = -thumbstick["x"] * self.movement_speed
490
+ if not optimized_for_tour:
491
+ # update head related info
492
+ self.teleop_action.head = th.cat(
493
+ (self.raw_data["transforms"]["head"][0], T.quat2euler(self.raw_data["transforms"]["head"][1]))
494
+ )
495
+ self.teleop_action.is_valid["head"] = self._is_valid_transform(self.raw_data["transforms"]["head"])
496
+
497
+ def get_robot_teleop_action(self) -> th.Tensor:
498
+ """
499
+ Get the robot teleop action
500
+ Returns:
501
+ th.tensor: the robot teleop action
502
+ """
503
+ return self.robot.teleop_data_to_action(self.teleop_action)
504
+
505
+ def snap_controller_to_eef(self, arm: str = "right") -> None:
506
+ """
507
+ Snap device to the robot end effector (ManipulationRobot only)
508
+ Args:
509
+ arm(str): name of the arm, one of "left" or "right". Default is "right".
510
+ """
511
+ # TODO: fix this
512
+ pass
513
+ # robot_base_orn = self.robot.get_position_orientation()[1]
514
+ # robot_eef_pos = self.robot.eef_links[
515
+ # self.robot.arm_names[self.robot_arms.index(arm)]
516
+ # ].get_position_orientation()[0]
517
+ # target_transform = self.og2xr(pos=robot_eef_pos, orn=robot_base_orn)
518
+ # self.vr_profile.set_physical_world_to_world_anchor_transform_to_match_xr_device(
519
+ # target_transform.numpy(), self.controllers[arm]
520
+ # )
521
+
522
+ def reset_head_transform(self) -> None:
523
+ """
524
+ Function that resets the transform of the VR system (w.r.t.) head
525
+ """
526
+ if self.align_anchor_to == "touchpad":
527
+ pos = th.tensor([0.0, 0.0, 1.0])
528
+ orn = th.tensor([0.0, 0.0, 0.0, 1.0])
529
+ else:
530
+ if self.anchor_prim is not None:
531
+ reference_frame = self.anchor_prim
532
+ elif self.align_anchor_to == "camera":
533
+ reference_frame = self.robot_cameras[self.active_camera_id]
534
+ elif self.align_anchor_to == "base":
535
+ reference_frame = self.robot
536
+ else:
537
+ raise ValueError(f"Invalid anchor: {self.align_anchor_to}")
538
+ pos, orn = reference_frame.get_position_orientation()
539
+ if self.robot:
540
+ self.robot.keep_still()
541
+ try:
542
+ self.xr_core.schedule_set_camera(self.og2xr(pos, orn).numpy())
543
+ except Exception as _:
544
+ pass
545
+
546
+ def _pose_in_robot_frame(self, pos: th.tensor, orn: th.tensor) -> Tuple[th.tensor, th.tensor]:
547
+ """
548
+ Get the pose in the robot frame
549
+ Args:
550
+ pos (th.tensor): the position in the world frame
551
+ orn (th.tensor): the orientation in the world frame
552
+ Returns:
553
+ tuple(th.tensor, th.tensor): the position and orientation in the robot frame
554
+ """
555
+ robot_base_pos, robot_base_orn = self.robot.get_position_orientation()
556
+ return T.relative_pose_transform(pos, orn, robot_base_pos, robot_base_orn)
557
+
558
+ def _move_anchor(
559
+ self, pos_offset: Optional[Iterable[float]] = None, rot_offset: Optional[Iterable[float]] = None
560
+ ) -> None:
561
+ """
562
+ Updates the anchor of the xr system in the virtual world
563
+ Args:
564
+ pos_offset (Iterable[float]): the position offset to apply to the anchor *in hmd frame*.
565
+ rot_offset (Iterable[float]): the rotation offset to apply to the anchor *in hmd frame*.
566
+ """
567
+ if pos_offset is not None:
568
+ # 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
569
+ pos_offset = th.tensor([-pos_offset[0], pos_offset[2], -pos_offset[1]]).double().tolist()
570
+ # self.vr_profile.add_move_physical_world_relative_to_device(pos_offset)
571
+ self.xr_core.schedule_move_space_origin_relative_to_camera(*pos_offset)
572
+ if rot_offset is not None:
573
+ return
574
+ # TODO: Fix this later
575
+ rot_offset = th.tensor(rot_offset).double().tolist()
576
+ # self.vr_profile.add_rotate_physical_world_around_device(rot_offset)
577
+ self.xr_core.schedule_rotate_space_origin_relative_to_camera(*rot_offset) # this takes yaw and pitch
578
+
579
+ # TODO: check if this is necessary
580
+ def _is_valid_transform(self, transform: Tuple[th.tensor, th.tensor]) -> bool:
581
+ """
582
+ Determine whether the transform is valid (ovxr plugin will return a zero position and rotation if not valid)
583
+ """
584
+ return th.any(transform[0] != th.zeros(3))
585
+
586
+ def _update_devices(self) -> None:
587
+ """
588
+ Update the VR device list
589
+ """
590
+ # We are looking for '/user/head', '/user/hand/left', '/user/hand/right'
591
+ for device in self.xr_core.get_all_input_devices():
592
+ device_name = str(device.get_name())
593
+ if device_name == "/user/head" and self.hmd is None:
594
+ self.hmd = device
595
+ elif device_name == "/user/hand/left" and "left" not in self.controllers:
596
+ self.controllers["left"] = device
597
+ elif device_name == "/user/hand/right" and "right" not in self.controllers:
598
+ self.controllers["right"] = device
599
+
600
+ def _update_device_transforms(self) -> None:
601
+ """
602
+ Get the transform matrix of each VR device *in world frame* and store in self.raw_data
603
+ """
604
+ assert self.hmd is not None, "VR headset device not found"
605
+ self.raw_data["transforms"] = {
606
+ "head": self.xr2og(self.hmd.get_virtual_world_pose()),
607
+ "controllers": {
608
+ name: self.xr2og(controller.get_virtual_world_pose()) for name, controller in self.controllers.items()
609
+ },
610
+ "trackers": {
611
+ index: self.xr2og(tracker.get_virtual_world_pose()) for index, tracker in self.trackers.items()
612
+ },
613
+ }
614
+
615
+ def _update_button_data(self):
616
+ """
617
+ Get the button data for each controller and store in self.raw_data
618
+ """
619
+ if "button_data" not in self.raw_data:
620
+ self.raw_data["button_data"] = {}
621
+
622
+ for name, controller in self.controllers.items():
623
+ if len(controller.get_output_names()) == 0 and len(controller.get_input_names()) == 0:
624
+ continue
625
+
626
+ # Initialize controller entry if it doesn't exist
627
+ if name not in self.raw_data["button_data"]:
628
+ self.raw_data["button_data"][name] = {}
629
+
630
+ # Add input data
631
+ for input_name in controller.get_input_names():
632
+ input_name = str(input_name)
633
+ # Initialize input entry if it doesn't exist
634
+ if input_name not in self.raw_data["button_data"][name]:
635
+ self.raw_data["button_data"][name][input_name] = {}
636
+
637
+ # Add gesture data
638
+ for gesture_name in controller.get_input_gesture_names(input_name):
639
+ gesture_name = str(gesture_name)
640
+ gesture_value = controller.get_input_gesture_value(input_name, gesture_name)
641
+ self.raw_data["button_data"][name][input_name][gesture_name] = gesture_value
642
+
643
+ def _update_hand_tracking_data(self, e) -> None:
644
+ """
645
+ Get hand tracking data, see https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html#convention-of-hand-joints for joint indices
646
+ Args:
647
+ e (carb.events.IEvent): event that contains hand tracking data as payload
648
+ """
649
+ e.consume()
650
+ data_dict = e.payload
651
+ for i, hand in enumerate(self.robot_arms):
652
+ robot_arm_name = self.robot.arm_names[i]
653
+ if data_dict[f"joint_count_{hand}"] != 0:
654
+ self.teleop_action.is_valid[hand] = True
655
+ self.raw_data["hand_data"][hand] = {"pos": [], "orn": []}
656
+ # hand_joint_matrices is an array of flattened 4x4 transform matrices for the 26 hand markers
657
+ hand_joint_matrices = data_dict[f"joint_matrices_{hand}"]
658
+ for j in range(26):
659
+ # extract the pose from the flattened transform matrix
660
+ pos, orn = self.xr2og(hand_joint_matrices[16 * j : 16 * (j + 1)].reshape(4, 4))
661
+ self.raw_data["hand_data"][hand]["pos"].append(pos)
662
+ self.raw_data["hand_data"][hand]["orn"].append(orn)
663
+ self.teleop_action[hand] = th.cat(
664
+ (
665
+ self.raw_data["hand_data"][hand]["pos"][0],
666
+ T.quat2euler(
667
+ T.quat_multiply(
668
+ self.raw_data["hand_data"][hand]["orn"][0],
669
+ self.robot.teleop_rotation_offset[robot_arm_name],
670
+ )
671
+ ),
672
+ th.tensor([0]),
673
+ )
674
+ )
675
+ # Get each finger joint's rotation angle from hand tracking data
676
+ # joint_angles is a 5 x 3 array of joint rotations (from thumb to pinky, from base to tip)
677
+ joint_angles = th.zeros((5, 3))
678
+ raw_hand_data = self.raw_data["hand_data"][hand]["pos"]
679
+ for i in range(5):
680
+ for j in range(3):
681
+ # get the 3 related joints indices
682
+ prev_joint_idx, cur_joint_idx, next_joint_idx = i * 5 + j + 1, i * 5 + j + 2, i * 5 + j + 3
683
+ # get the 3 related joints' positions
684
+ prev_joint_pos = raw_hand_data[prev_joint_idx]
685
+ cur_joint_pos = raw_hand_data[cur_joint_idx]
686
+ next_joint_pos = raw_hand_data[next_joint_idx]
687
+ # calculate the angle formed by 3 points
688
+ v1 = cur_joint_pos - prev_joint_pos
689
+ v2 = next_joint_pos - cur_joint_pos
690
+ v1 /= th.norm(v1)
691
+ v2 /= th.norm(v2)
692
+ joint_angles[i, j] = th.arccos(v1 @ v2)
693
+ self.teleop_action.hand_data[hand] = joint_angles
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils.py ADDED
@@ -0,0 +1,1612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions of matrix and vector transformations.
3
+
4
+ NOTE: This file has a 1-to-1 correspondence to transform_utils_np.py
5
+
6
+ NOTE: convention for quaternions is (x, y, z, w)
7
+ """
8
+
9
+ import math
10
+ from typing import Optional, Tuple
11
+
12
+ from omnigibson.utils.python_utils import torch_compile
13
+ import torch
14
+
15
+ PI = math.pi
16
+
17
+ # map axes strings to/from tuples of inner axis, parity, repetition, frame
18
+ _AXES2TUPLE = {
19
+ "sxyz": (0, 0, 0, 0),
20
+ "sxyx": (0, 0, 1, 0),
21
+ "sxzy": (0, 1, 0, 0),
22
+ "sxzx": (0, 1, 1, 0),
23
+ "syzx": (1, 0, 0, 0),
24
+ "syzy": (1, 0, 1, 0),
25
+ "syxz": (1, 1, 0, 0),
26
+ "syxy": (1, 1, 1, 0),
27
+ "szxy": (2, 0, 0, 0),
28
+ "szxz": (2, 0, 1, 0),
29
+ "szyx": (2, 1, 0, 0),
30
+ "szyz": (2, 1, 1, 0),
31
+ "rzyx": (0, 0, 0, 1),
32
+ "rxyx": (0, 0, 1, 1),
33
+ "ryzx": (0, 1, 0, 1),
34
+ "rxzx": (0, 1, 1, 1),
35
+ "rxzy": (1, 0, 0, 1),
36
+ "ryzy": (1, 0, 1, 1),
37
+ "rzxy": (1, 1, 0, 1),
38
+ "ryxy": (1, 1, 1, 1),
39
+ "ryxz": (2, 0, 0, 1),
40
+ "rzxz": (2, 0, 1, 1),
41
+ "rxyz": (2, 1, 0, 1),
42
+ "rzyz": (2, 1, 1, 1),
43
+ }
44
+
45
+
46
+ @torch_compile
47
+ def copysign(a, b):
48
+ # type: (float, torch.Tensor) -> torch.Tensor
49
+ a = torch.tensor(a, device=b.device, dtype=torch.float).repeat(b.shape[0])
50
+ return torch.abs(a) * torch.sign(b)
51
+
52
+
53
+ @torch_compile
54
+ def anorm(x: torch.Tensor, dim: Optional[int] = None, keepdim: bool = False) -> torch.Tensor:
55
+ """Compute L2 norms along specified axes."""
56
+ return torch.norm(x, dim=dim, keepdim=keepdim)
57
+
58
+
59
+ @torch_compile
60
+ def normalize(v: torch.Tensor, dim: Optional[int] = None, eps: float = 1e-10) -> torch.Tensor:
61
+ """L2 Normalize along specified axes."""
62
+ norm = anorm(v, dim=dim, keepdim=True)
63
+ return v / torch.where(norm < eps, torch.full_like(norm, eps), norm)
64
+
65
+
66
+ @torch_compile
67
+ def dot(v1, v2, dim=-1, keepdim=False):
68
+ """
69
+ Computes dot product between two vectors along the provided dim, optionally keeping the dimension
70
+
71
+ Args:
72
+ v1 (tensor): (..., N, ...) arbitrary vector
73
+ v2 (tensor): (..., N, ...) arbitrary vector
74
+ dim (int): Dimension to sum over for dot product
75
+ keepdim (bool): Whether to keep dimension over which dot product is calculated
76
+
77
+ Returns:
78
+ tensor: (..., [1,] ...) dot product of vectors, with optional dimension kept if @keepdim is True
79
+ """
80
+ # type: (Tensor, Tensor, int, bool) -> Tensor
81
+ return torch.sum(v1 * v2, dim=dim, keepdim=keepdim)
82
+
83
+
84
+ @torch_compile
85
+ def unit_vector(data: torch.Tensor, dim: Optional[int] = None, out: Optional[torch.Tensor] = None) -> torch.Tensor:
86
+ """
87
+ Returns tensor normalized by length, i.e. Euclidean norm, along axis.
88
+
89
+ Args:
90
+ data (torch.Tensor): data to normalize
91
+ dim (Optional[int]): If specified, determines specific dimension along data to normalize
92
+ out (Optional[torch.Tensor]): If specified, will store computation in this variable
93
+
94
+ Returns:
95
+ torch.Tensor: Normalized vector
96
+ """
97
+ if out is None:
98
+ if not isinstance(data, torch.Tensor):
99
+ data = torch.tensor(data, dtype=torch.float32)
100
+ else:
101
+ data = data.clone().to(torch.float32)
102
+
103
+ if data.ndim == 1:
104
+ return data / torch.sqrt(torch.dot(data, data))
105
+ else:
106
+ if out is not data:
107
+ out.copy_(data)
108
+ data = out
109
+
110
+ if dim is None:
111
+ dim = -1
112
+
113
+ length = torch.sum(data * data, dim=dim, keepdim=True).sqrt()
114
+ data = data / (length + 1e-8) # Add small epsilon to avoid division by zero
115
+
116
+ return data
117
+
118
+
119
+ @torch_compile
120
+ def quat_apply(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
121
+ """
122
+ Apply a quaternion rotation to a vector (equivalent to R.from_quat(x).apply(y))
123
+ Args:
124
+ quat (torch.Tensor): (4,) or (N, 4) or (N, 1, 4) quaternion in (x, y, z, w) format
125
+ vec (torch.Tensor): (3,) or (M, 3) or (1, M, 3) vector to rotate
126
+ Returns:
127
+ torch.Tensor: (M, 3) or (N, M, 3) rotated vector
128
+ """
129
+ assert quat.shape[-1] == 4, "Quaternion must have 4 components in last dimension"
130
+ assert vec.shape[-1] == 3, "Vector must have 3 components in last dimension"
131
+
132
+ # Ensure quat is at least 2D and vec is at least 2D
133
+ if quat.dim() == 1:
134
+ quat = quat.unsqueeze(0)
135
+ if vec.dim() == 1:
136
+ vec = vec.unsqueeze(0)
137
+
138
+ # Ensure quat is (N, 1, 4) and vec is (1, M, 3)
139
+ if quat.dim() == 2:
140
+ quat = quat.unsqueeze(1)
141
+ if vec.dim() == 2:
142
+ vec = vec.unsqueeze(0)
143
+
144
+ # Extract quaternion components
145
+ qx, qy, qz, qw = quat.unbind(-1)
146
+
147
+ # Compute the quaternion multiplication
148
+ t = torch.stack(
149
+ [
150
+ 2 * (qy * vec[..., 2] - qz * vec[..., 1]),
151
+ 2 * (qz * vec[..., 0] - qx * vec[..., 2]),
152
+ 2 * (qx * vec[..., 1] - qy * vec[..., 0]),
153
+ ],
154
+ dim=-1,
155
+ )
156
+
157
+ # Compute the final rotated vector
158
+ result = vec + qw.unsqueeze(-1) * t + torch.cross(quat[..., :3], t, dim=-1)
159
+
160
+ # Remove any extra dimensions
161
+ return result.squeeze()
162
+
163
+
164
+ @torch_compile
165
+ def convert_quat(q: torch.Tensor, to: str = "xyzw") -> torch.Tensor:
166
+ """
167
+ Converts quaternion from one convention to another.
168
+ The convention to convert TO is specified as an optional argument.
169
+ If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa.
170
+
171
+ Args:
172
+ q (torch.Tensor): a 4-dim array corresponding to a quaternion
173
+ to (str): either 'xyzw' or 'wxyz', determining which convention to convert to.
174
+
175
+ Returns:
176
+ torch.Tensor: The converted quaternion
177
+ """
178
+ if to == "xyzw":
179
+ return torch.stack([q[1], q[2], q[3], q[0]], dim=0)
180
+ elif to == "wxyz":
181
+ return torch.stack([q[3], q[0], q[1], q[2]], dim=0)
182
+ else:
183
+ raise ValueError("convert_quat: choose a valid `to` argument (xyzw or wxyz)")
184
+
185
+
186
+ @torch_compile
187
+ def quat_multiply(quaternion1: torch.Tensor, quaternion0: torch.Tensor) -> torch.Tensor:
188
+ """
189
+ Return multiplication of two quaternions (q1 * q0).
190
+
191
+ Args:
192
+ quaternion1 (torch.Tensor): (x,y,z,w) quaternion
193
+ quaternion0 (torch.Tensor): (x,y,z,w) quaternion
194
+
195
+ Returns:
196
+ torch.Tensor: (x,y,z,w) multiplied quaternion
197
+ """
198
+ x0, y0, z0, w0 = quaternion0[0], quaternion0[1], quaternion0[2], quaternion0[3]
199
+ x1, y1, z1, w1 = quaternion1[0], quaternion1[1], quaternion1[2], quaternion1[3]
200
+
201
+ return torch.stack(
202
+ [
203
+ x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
204
+ -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
205
+ x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0,
206
+ -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
207
+ ],
208
+ dim=0,
209
+ )
210
+
211
+
212
+ @torch_compile
213
+ def quat_conjugate(quaternion: torch.Tensor) -> torch.Tensor:
214
+ """
215
+ Return conjugate of quaternion.
216
+
217
+ Args:
218
+ quaternion (torch.Tensor): (x,y,z,w) quaternion
219
+
220
+ Returns:
221
+ torch.Tensor: (x,y,z,w) quaternion conjugate
222
+ """
223
+ return torch.cat([-quaternion[:3], quaternion[3:]])
224
+
225
+
226
+ @torch_compile
227
+ def quat_inverse(quaternion: torch.Tensor) -> torch.Tensor:
228
+ """
229
+ Return inverse of quaternion.
230
+
231
+ E.g.:
232
+ >>> q0 = random_quaternion()
233
+ >>> q1 = quat_inverse(q0)
234
+ >>> torch.allclose(quat_multiply(q0, q1), [0, 0, 0, 1])
235
+ True
236
+
237
+ Args:
238
+ quaternion (torch.tensor): (x,y,z,w) quaternion
239
+
240
+ Returns:
241
+ torch.tensor: (x,y,z,w) quaternion inverse
242
+ """
243
+ return quat_conjugate(quaternion) / torch.dot(quaternion, quaternion)
244
+
245
+
246
+ @torch_compile
247
+ def quat_distance(quaternion1, quaternion0):
248
+ """
249
+ Returns distance between two quaternions, such that distance * quaternion0 = quaternion1
250
+ Always returns the shorter rotation path.
251
+
252
+ Args:
253
+ quaternion1 (torch.tensor): (x,y,z,w) quaternion or (..., 4) batched quaternions
254
+ quaternion0 (torch.tensor): (x,y,z,w) quaternion or (..., 4) batched quaternions
255
+
256
+ Returns:
257
+ torch.tensor: (x,y,z,w) quaternion distance or (..., 4) batched quaternion distances
258
+ """
259
+ # Compute dot product along the last axis (quaternion components)
260
+ d = torch.sum(quaternion0 * quaternion1, dim=-1, keepdim=True)
261
+ # If dot product is negative, negate one quaternion to get shorter path
262
+ quaternion1 = torch.where(d < 0.0, -quaternion1, quaternion1)
263
+
264
+ return quat_multiply(quaternion1, quat_inverse(quaternion0))
265
+
266
+
267
+ @torch_compile
268
+ def quat_slerp(quat0, quat1, frac, shortestpath=True, eps=1.0e-15):
269
+ """
270
+ Return spherical linear interpolation between two quaternions.
271
+
272
+ Args:
273
+ quat0 (tensor): (..., 4) tensor where the final dim is (x,y,z,w) initial quaternion
274
+ quat1 (tensor): (..., 4) tensor where the final dim is (x,y,z,w) final quaternion
275
+ frac (tensor): Values in [0.0, 1.0] representing fraction of interpolation
276
+ shortestpath (bool): If True, will calculate shortest path
277
+ eps (float): Value to check for singularities
278
+ Returns:
279
+ tensor: (..., 4) Interpolated
280
+ """
281
+ # type: (Tensor, Tensor, Tensor, bool, float) -> Tensor
282
+ # reshape quaternion
283
+ quat_shape = quat0.shape
284
+ quat0 = unit_vector(quat0.reshape(-1, 4), dim=-1, out=None)
285
+ quat1 = unit_vector(quat1.reshape(-1, 4), dim=-1, out=None)
286
+
287
+ # Check for endpoint cases
288
+ where_start = frac <= 0.0
289
+ where_end = frac >= 1.0
290
+
291
+ d = dot(quat0, quat1, dim=-1, keepdim=True)
292
+ if shortestpath:
293
+ quat1 = torch.where(d < 0.0, -quat1, quat1)
294
+ d = torch.abs(d)
295
+ angle = torch.acos(torch.clip(d, -1.0, 1.0))
296
+
297
+ # Check for small quantities (i.e.: q0 = q1)
298
+ where_small_diff = torch.abs(torch.abs(d) - 1.0) < eps
299
+ where_small_angle = abs(angle) < eps
300
+
301
+ isin = 1.0 / torch.sin(angle)
302
+ val = quat0 * torch.sin((1.0 - frac) * angle) * isin + quat1 * torch.sin(frac * angle) * isin
303
+
304
+ # Filter edge cases
305
+ val = torch.where(
306
+ where_small_diff | where_small_angle | where_start,
307
+ quat0,
308
+ torch.where(
309
+ where_end,
310
+ quat1,
311
+ val,
312
+ ),
313
+ )
314
+
315
+ # Reshape and return values
316
+ return val.reshape(list(quat_shape))
317
+
318
+
319
+ @torch_compile
320
+ def random_quaternion(num_quaternions: int = 1) -> torch.Tensor:
321
+ """
322
+ Generate random rotation quaternions, uniformly distributed over SO(3).
323
+
324
+ Arguments:
325
+ num_quaternions (int): number of quaternions to generate (default: 1)
326
+
327
+ Returns:
328
+ torch.Tensor: A tensor of shape (num_quaternions, 4) containing random unit quaternions.
329
+ """
330
+ # Generate four random numbers between 0 and 1
331
+ rand = torch.rand(num_quaternions, 4)
332
+
333
+ # Use the formula from Ken Shoemake's "Uniform Random Rotations"
334
+ r1 = torch.sqrt(1.0 - rand[:, 0])
335
+ r2 = torch.sqrt(rand[:, 0])
336
+ t1 = 2 * torch.pi * rand[:, 1]
337
+ t2 = 2 * torch.pi * rand[:, 2]
338
+
339
+ quaternions = torch.stack([r1 * torch.sin(t1), r1 * torch.cos(t1), r2 * torch.sin(t2), r2 * torch.cos(t2)], dim=1)
340
+
341
+ return quaternions
342
+
343
+
344
+ @torch_compile
345
+ def random_axis_angle(angle_limit: float = 2.0 * math.pi):
346
+ """
347
+ Samples an axis-angle rotation by first sampling a random axis
348
+ and then sampling an angle. If @angle_limit is provided, the size
349
+ of the rotation angle is constrained.
350
+
351
+ Args:
352
+ angle_limit (float): Determines magnitude limit of angles to generate
353
+
354
+ Raises:
355
+ AssertionError: [Invalid RNG]
356
+ """
357
+ # sample random axis using a normalized sample from spherical Gaussian.
358
+ # see (http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/)
359
+ # for why it works.
360
+ random_axis = torch.randn(3)
361
+ random_axis /= torch.norm(random_axis)
362
+ random_angle = torch.rand(1) * angle_limit
363
+ return random_axis, random_angle.item()
364
+
365
+
366
+ @torch_compile
367
+ def quat2mat(quaternion):
368
+ """
369
+ Convert quaternions into rotation matrices.
370
+
371
+ Args:
372
+ quaternion (torch.Tensor): A tensor of shape (..., 4) representing batches of quaternions (x, y, z, w).
373
+
374
+ Returns:
375
+ torch.Tensor: A tensor of shape (..., 3, 3) representing batches of rotation matrices.
376
+ """
377
+ quaternion = quaternion / torch.norm(quaternion, dim=-1, keepdim=True)
378
+
379
+ outer = quaternion.unsqueeze(-1) * quaternion.unsqueeze(-2)
380
+
381
+ # Extract the necessary components
382
+ xx = outer[..., 0, 0]
383
+ yy = outer[..., 1, 1]
384
+ zz = outer[..., 2, 2]
385
+ xy = outer[..., 0, 1]
386
+ xz = outer[..., 0, 2]
387
+ yz = outer[..., 1, 2]
388
+ xw = outer[..., 0, 3]
389
+ yw = outer[..., 1, 3]
390
+ zw = outer[..., 2, 3]
391
+
392
+ rmat = torch.empty(quaternion.shape[:-1] + (3, 3), dtype=quaternion.dtype, device=quaternion.device)
393
+
394
+ rmat[..., 0, 0] = 1 - 2 * (yy + zz)
395
+ rmat[..., 0, 1] = 2 * (xy - zw)
396
+ rmat[..., 0, 2] = 2 * (xz + yw)
397
+
398
+ rmat[..., 1, 0] = 2 * (xy + zw)
399
+ rmat[..., 1, 1] = 1 - 2 * (xx + zz)
400
+ rmat[..., 1, 2] = 2 * (yz - xw)
401
+
402
+ rmat[..., 2, 0] = 2 * (xz - yw)
403
+ rmat[..., 2, 1] = 2 * (yz + xw)
404
+ rmat[..., 2, 2] = 1 - 2 * (xx + yy)
405
+
406
+ return rmat
407
+
408
+
409
+ @torch_compile
410
+ def mat2quat(rmat: torch.Tensor) -> torch.Tensor:
411
+ """
412
+ Converts given rotation matrix to quaternion.
413
+ Args:
414
+ rmat (torch.Tensor): (3, 3) or (..., 3, 3) rotation matrix
415
+ Returns:
416
+ torch.Tensor: (4,) or (..., 4) (x,y,z,w) float quaternion angles
417
+ """
418
+ assert torch.allclose(torch.linalg.det(rmat), torch.tensor(1.0)), "Rotation matrix must not be scaled"
419
+
420
+ # Check if input is a single matrix or a batch
421
+ is_single = rmat.dim() == 2
422
+ if is_single:
423
+ rmat = rmat.unsqueeze(0)
424
+
425
+ batch_shape = rmat.shape[:-2]
426
+ mat_flat = rmat.reshape(-1, 3, 3)
427
+
428
+ m00, m01, m02 = mat_flat[:, 0, 0], mat_flat[:, 0, 1], mat_flat[:, 0, 2]
429
+ m10, m11, m12 = mat_flat[:, 1, 0], mat_flat[:, 1, 1], mat_flat[:, 1, 2]
430
+ m20, m21, m22 = mat_flat[:, 2, 0], mat_flat[:, 2, 1], mat_flat[:, 2, 2]
431
+
432
+ trace = m00 + m11 + m22
433
+
434
+ trace_positive = trace > 0
435
+ cond1 = (m00 > m11) & (m00 > m22) & ~trace_positive
436
+ cond2 = (m11 > m22) & ~(trace_positive | cond1)
437
+ cond3 = ~(trace_positive | cond1 | cond2)
438
+
439
+ # Trace positive condition
440
+ sq = torch.where(trace_positive, torch.sqrt(trace + 1.0) * 2.0, torch.zeros_like(trace))
441
+ qw = torch.where(trace_positive, 0.25 * sq, torch.zeros_like(trace))
442
+ qx = torch.where(trace_positive, (m21 - m12) / sq, torch.zeros_like(trace))
443
+ qy = torch.where(trace_positive, (m02 - m20) / sq, torch.zeros_like(trace))
444
+ qz = torch.where(trace_positive, (m10 - m01) / sq, torch.zeros_like(trace))
445
+
446
+ # Condition 1
447
+ sq = torch.where(cond1, torch.sqrt(1.0 + m00 - m11 - m22) * 2.0, sq)
448
+ qw = torch.where(cond1, (m21 - m12) / sq, qw)
449
+ qx = torch.where(cond1, 0.25 * sq, qx)
450
+ qy = torch.where(cond1, (m01 + m10) / sq, qy)
451
+ qz = torch.where(cond1, (m02 + m20) / sq, qz)
452
+
453
+ # Condition 2
454
+ sq = torch.where(cond2, torch.sqrt(1.0 + m11 - m00 - m22) * 2.0, sq)
455
+ qw = torch.where(cond2, (m02 - m20) / sq, qw)
456
+ qx = torch.where(cond2, (m01 + m10) / sq, qx)
457
+ qy = torch.where(cond2, 0.25 * sq, qy)
458
+ qz = torch.where(cond2, (m12 + m21) / sq, qz)
459
+
460
+ # Condition 3
461
+ sq = torch.where(cond3, torch.sqrt(1.0 + m22 - m00 - m11) * 2.0, sq)
462
+ qw = torch.where(cond3, (m10 - m01) / sq, qw)
463
+ qx = torch.where(cond3, (m02 + m20) / sq, qx)
464
+ qy = torch.where(cond3, (m12 + m21) / sq, qy)
465
+ qz = torch.where(cond3, 0.25 * sq, qz)
466
+
467
+ quat = torch.stack([qx, qy, qz, qw], dim=-1)
468
+
469
+ # Normalize the quaternion
470
+ quat = quat / torch.norm(quat, dim=-1, keepdim=True)
471
+
472
+ # Reshape to match input batch shape
473
+ quat = quat.reshape(batch_shape + (4,))
474
+
475
+ # If input was a single matrix, remove the batch dimension
476
+ if is_single:
477
+ quat = quat.squeeze(0)
478
+
479
+ return quat
480
+
481
+
482
+ def mat2quat_batch(rmat: torch.Tensor) -> torch.Tensor:
483
+ """
484
+ Converts given rotation matrix to quaternion. Version optimized for batch operations
485
+
486
+ Args:
487
+ rmat (torch.Tensor): (3, 3) or (..., 3, 3) rotation matrix
488
+
489
+ Returns:
490
+ torch.Tensor: (4,) or (..., 4) (x,y,z,w) float quaternion angles
491
+ """
492
+ # For torch, no different than basic version
493
+ return mat2quat(rmat)
494
+
495
+
496
+ @torch_compile
497
+ def decompose_mat(hmat):
498
+ """Batched decompose_mat function - assumes input is already batched
499
+
500
+ Args:
501
+ hmat (torch.Tensor): (B, 4, 4) batch of homogeneous matrices
502
+
503
+ Returns:
504
+ scale: (B, 3) scale factors
505
+ shear: (B, 3) shear factors
506
+ quat: (B, 4) quaternions
507
+ translate: (B, 3) translations
508
+ """
509
+ batch_size = hmat.shape[0]
510
+ M = torch.as_tensor(hmat, dtype=torch.float32).transpose(-2, -1) # (B, 4, 4) transposed
511
+
512
+ # Check M[3, 3] for all batch items
513
+ diag_vals = M[:, 3, 3] # (B,)
514
+
515
+ # TODO: this line might be a VRAM killer, investigate this
516
+ # if torch.any(torch.abs(diag_vals) < 1e-6):
517
+ # raise ValueError("Some M[3, 3] values are zero")
518
+
519
+ M = M / diag_vals.unsqueeze(-1).unsqueeze(-1) # (B, 4, 4)
520
+ P = M.clone()
521
+ P[:, :, 3] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=hmat.device, dtype=hmat.dtype).expand(batch_size, 4)
522
+
523
+ det_P = torch.linalg.det(P[:, :3, :3]) # (B,)
524
+ torch._assert(torch.all(torch.abs(det_P) >= 1e-6), "Some matrices are singular and cannot be decomposed")
525
+
526
+ if not torch.allclose(M[:, :3, 3], torch.tensor(0.0, device=hmat.device, dtype=hmat.dtype)):
527
+ raise ValueError("Some matrices have perspective components")
528
+
529
+ scale = torch.zeros((batch_size, 3), device=hmat.device, dtype=hmat.dtype)
530
+ shear = torch.zeros((batch_size, 3), device=hmat.device, dtype=hmat.dtype)
531
+
532
+ translate = M[:, 3, :3].clone() # (B, 3)
533
+ M[:, 3, :3] = 0.0
534
+
535
+ row = M[:, :3, :3].clone() # (B, 3, 3)
536
+
537
+ # Scale and orthogonalize rows
538
+ scale[:, 0] = torch.linalg.norm(row[:, 0], dim=-1) # (B,)
539
+ row[:, 0] = row[:, 0] / scale[:, 0].unsqueeze(-1) # (B, 3)
540
+
541
+ shear[:, 0] = torch.sum(row[:, 0] * row[:, 1], dim=-1) # (B,)
542
+ row[:, 1] = row[:, 1] - row[:, 0] * shear[:, 0].unsqueeze(-1) # (B, 3)
543
+
544
+ scale[:, 1] = torch.linalg.norm(row[:, 1], dim=-1) # (B,)
545
+ row[:, 1] = row[:, 1] / scale[:, 1].unsqueeze(-1) # (B, 3)
546
+ shear[:, 0] = shear[:, 0] / scale[:, 1]
547
+
548
+ shear[:, 1] = torch.sum(row[:, 0] * row[:, 2], dim=-1) # (B,)
549
+ row[:, 2] = row[:, 2] - row[:, 0] * shear[:, 1].unsqueeze(-1) # (B, 3)
550
+
551
+ shear[:, 2] = torch.sum(row[:, 1] * row[:, 2], dim=-1) # (B,)
552
+ row[:, 2] = row[:, 2] - row[:, 1] * shear[:, 2].unsqueeze(-1) # (B, 3)
553
+
554
+ scale[:, 2] = torch.linalg.norm(row[:, 2], dim=-1) # (B,)
555
+ row[:, 2] = row[:, 2] / scale[:, 2].unsqueeze(-1) # (B, 3)
556
+ shear[:, 1:] = shear[:, 1:] / scale[:, 2].unsqueeze(-1)
557
+
558
+ # Check orientation
559
+ cross_product = torch.cross(row[:, 1], row[:, 2], dim=-1) # (B, 3)
560
+ dot_product = torch.sum(row[:, 0] * cross_product, dim=-1) # (B,)
561
+ neg_mask = dot_product < 0 # (B,)
562
+
563
+ scale = torch.where(neg_mask.unsqueeze(-1), -scale, scale) # (B, 3)
564
+ row = torch.where(neg_mask.unsqueeze(-1).unsqueeze(-1), -row, row) # (B, 3, 3)
565
+
566
+ # Convert to quaternions - assuming mat2quat can handle batched input
567
+ quat = mat2quat(row.transpose(-2, -1)) # (B, 4)
568
+
569
+ return scale, shear, quat, translate
570
+
571
+
572
+ @torch_compile
573
+ def mat2pose(hmat):
574
+ """
575
+ Converts a homogeneous 4x4 matrix into pose.
576
+
577
+ Args:
578
+ hmat (torch.tensor): a 4x4 homogeneous matrix
579
+
580
+ Returns:
581
+ 2-tuple:
582
+ - (torch.tensor) (3,) position array in cartesian coordinates
583
+ - (torch.tensor) (4,) orientation array in quaternion form
584
+ """
585
+ # Add batch dimension, process, then squeeze
586
+ hmat_batched = hmat.unsqueeze(0) # (1, 4, 4)
587
+ _, _, quat, translate = decompose_mat(hmat_batched)
588
+ return translate.squeeze(0), quat.squeeze(0)
589
+
590
+
591
+ @torch_compile
592
+ def mat2pose_batched(hmat):
593
+ """
594
+ Converts batched homogeneous 4x4 matrices into poses.
595
+
596
+ Args:
597
+ hmat (torch.tensor): (B, 4, 4) batch of homogeneous matrices
598
+
599
+ Returns:
600
+ 2-tuple:
601
+ - (torch.tensor) (B, 3) position arrays in cartesian coordinates
602
+ - (torch.tensor) (B, 4) orientation arrays in quaternion form
603
+ """
604
+ _, _, quat, translate = decompose_mat(hmat)
605
+ return translate, quat
606
+
607
+
608
+ @torch_compile
609
+ def vec2quat(vec: torch.Tensor, up: torch.Tensor = torch.tensor([0.0, 0.0, 1.0])) -> torch.Tensor:
610
+ """
611
+ Converts given 3d-direction vector @vec to quaternion orientation with respect to another direction vector @up
612
+
613
+ Args:
614
+ vec (torch.Tensor): (x,y,z) direction vector (possibly non-normalized)
615
+ up (torch.Tensor): (x,y,z) direction vector representing the canonical up direction (possibly non-normalized)
616
+
617
+ Returns:
618
+ torch.Tensor: (x,y,z,w) quaternion
619
+ """
620
+ # Ensure inputs are 2D
621
+ if vec.dim() == 1:
622
+ vec = vec.unsqueeze(0)
623
+ if up.dim() == 1:
624
+ up = up.unsqueeze(0)
625
+
626
+ vec_n = normalize(vec, dim=-1, eps=1e-10)
627
+ up_n = normalize(up, dim=-1, eps=1e-10)
628
+
629
+ s_n = torch.cross(up_n, vec_n, dim=-1)
630
+ u_n = torch.cross(vec_n, s_n, dim=-1)
631
+
632
+ rmat = torch.stack([vec_n, s_n, u_n], dim=-1)
633
+
634
+ return mat2quat(rmat)
635
+
636
+
637
+ @torch_compile
638
+ def euler2quat(euler: torch.Tensor) -> torch.Tensor:
639
+ """
640
+ Converts euler angles into quaternion form
641
+
642
+ Args:
643
+ euler (torch.Tensor): (..., 3) (r,p,y) angles
644
+
645
+ Returns:
646
+ torch.Tensor: (..., 4) (x,y,z,w) float quaternion angles
647
+
648
+ Raises:
649
+ AssertionError: [Invalid input shape]
650
+ """
651
+ assert euler.shape[-1] == 3, "Invalid input shape"
652
+
653
+ # Unpack roll, pitch, yaw
654
+ unbound_euler = euler.unbind(-1)
655
+ roll, pitch, yaw = unbound_euler[0], unbound_euler[1], unbound_euler[2]
656
+
657
+ # Compute sines and cosines of half angles
658
+ cy = torch.cos(yaw * 0.5)
659
+ sy = torch.sin(yaw * 0.5)
660
+ cr = torch.cos(roll * 0.5)
661
+ sr = torch.sin(roll * 0.5)
662
+ cp = torch.cos(pitch * 0.5)
663
+ sp = torch.sin(pitch * 0.5)
664
+
665
+ # Compute quaternion components
666
+ qw = cy * cr * cp + sy * sr * sp
667
+ qx = cy * sr * cp - sy * cr * sp
668
+ qy = cy * cr * sp + sy * sr * cp
669
+ qz = sy * cr * cp - cy * sr * sp
670
+
671
+ # Stack and return
672
+ return torch.stack([qx, qy, qz, qw], dim=-1)
673
+
674
+
675
+ @torch_compile
676
+ def quat2euler(q):
677
+ single_dim = q.dim() == 1
678
+
679
+ if single_dim:
680
+ q = q.unsqueeze(0)
681
+
682
+ qx, qy, qz, qw = 0, 1, 2, 3
683
+ # roll (x-axis rotation)
684
+ sinr_cosp = 2.0 * (q[:, qw] * q[:, qx] + q[:, qy] * q[:, qz])
685
+ cosr_cosp = q[:, qw] * q[:, qw] - q[:, qx] * q[:, qx] - q[:, qy] * q[:, qy] + q[:, qz] * q[:, qz]
686
+ roll = torch.atan2(sinr_cosp, cosr_cosp)
687
+ # pitch (y-axis rotation)
688
+ sinp = 2.0 * (q[:, qw] * q[:, qy] - q[:, qz] * q[:, qx])
689
+ pitch = torch.where(torch.abs(sinp) >= 1, copysign(math.pi / 2.0, sinp), torch.asin(sinp))
690
+ # yaw (z-axis rotation)
691
+ siny_cosp = 2.0 * (q[:, qw] * q[:, qz] + q[:, qx] * q[:, qy])
692
+ cosy_cosp = q[:, qw] * q[:, qw] + q[:, qx] * q[:, qx] - q[:, qy] * q[:, qy] - q[:, qz] * q[:, qz]
693
+ yaw = torch.atan2(siny_cosp, cosy_cosp)
694
+
695
+ euler = torch.stack([roll, pitch, yaw], dim=-1) % (2 * math.pi)
696
+ euler[euler > math.pi] -= 2 * math.pi
697
+
698
+ if single_dim:
699
+ euler = euler.squeeze(0)
700
+
701
+ return euler
702
+
703
+
704
+ @torch_compile
705
+ def euler2mat(euler):
706
+ """
707
+ Converts euler angles into rotation matrix form
708
+
709
+ Args:
710
+ euler (torch.tensor): (r,p,y) angles
711
+
712
+ Returns:
713
+ torch.tensor: 3x3 rotation matrix
714
+
715
+ Raises:
716
+ AssertionError: [Invalid input shape]
717
+ """
718
+ euler = torch.as_tensor(euler, dtype=torch.float32)
719
+ assert euler.shape[-1] == 3, f"Invalid shaped euler {euler}"
720
+
721
+ # Convert Euler angles to quaternion
722
+ quat = euler2quat(euler)
723
+
724
+ # Convert quaternion to rotation matrix
725
+ return quat2mat(quat)
726
+
727
+
728
+ @torch_compile
729
+ def mat2euler(rmat):
730
+ """
731
+ Converts given rotation matrix to euler angles in radian.
732
+
733
+ Args:
734
+ rmat (torch.tensor): 3x3 rotation matrix
735
+
736
+ Returns:
737
+ torch.tensor: (r,p,y) converted euler angles in radian vec3 float
738
+ """
739
+ M = torch.as_tensor(rmat, dtype=torch.float32)[:3, :3]
740
+ assert torch.allclose(rmat.det(), torch.tensor(1.0)), "Rotation matrix must not be scaled"
741
+
742
+ # Convert rotation matrix to quaternion
743
+ # Note: You'll need to implement mat2quat function
744
+ quat = mat2quat(M)
745
+
746
+ # Convert quaternion to Euler angles
747
+ euler = quat2euler(quat)
748
+ roll = euler[..., 0]
749
+ pitch = euler[..., 1]
750
+ yaw = euler[..., 2]
751
+
752
+ return torch.stack([roll, pitch, yaw], dim=-1)
753
+
754
+
755
+ @torch_compile
756
+ def pose2mat(pose: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
757
+ pos, orn = pose
758
+
759
+ # Ensure pos and orn are the expected shape and dtype
760
+ pos = pos.to(dtype=torch.float32).reshape(-1, 3)
761
+ orn = orn.to(dtype=torch.float32).reshape(-1, 4)
762
+
763
+ batch_size = pos.shape[0]
764
+ homo_pose_mat = torch.eye(4, dtype=torch.float32).unsqueeze(0).repeat(batch_size, 1, 1)
765
+
766
+ homo_pose_mat[:, :3, :3] = quat2mat(orn)
767
+ homo_pose_mat[:, :3, 3] = pos
768
+
769
+ homo_pose_mat = homo_pose_mat.squeeze(0)
770
+
771
+ return homo_pose_mat
772
+
773
+
774
+ @torch_compile
775
+ def quat2axisangle(quat):
776
+ """
777
+ Converts quaternion to axis-angle format.
778
+ Returns a unit vector direction scaled by its angle in radians.
779
+ Args:
780
+ quat (tensor): (..., 4) tensor where the final dim is (x,y,z,w) quaternion
781
+ Returns:
782
+ tensor: (..., 3) axis-angle exponential coordinates
783
+ """
784
+ # reshape quaternion
785
+ quat_shape = quat.shape[:-1] # ignore last dim
786
+ quat = quat.reshape(-1, 4)
787
+ # clip quaternion
788
+ quat[:, 3] = torch.clip(quat[:, 3], -1.0, 1.0)
789
+ # Calculate denominator
790
+ den = torch.sqrt(1.0 - quat[:, 3] * quat[:, 3])
791
+ # Map this into a mask
792
+
793
+ # Create return array
794
+ ret = torch.zeros_like(quat)[:, :3]
795
+ idx = torch.nonzero(den).reshape(-1)
796
+ ret[idx, :] = (quat[idx, :3] * 2.0 * torch.acos(quat[idx, 3]).unsqueeze(-1)) / den[idx].unsqueeze(-1)
797
+
798
+ # Reshape and return output
799
+ ret = ret.reshape(
800
+ list(quat_shape)
801
+ + [
802
+ 3,
803
+ ]
804
+ )
805
+ return ret
806
+
807
+
808
+ @torch_compile
809
+ def axisangle2quat(vec, eps=1e-6):
810
+ """
811
+ Converts scaled axis-angle to quat.
812
+ Args:
813
+ vec (tensor): (..., 3) tensor where final dim is (ax,ay,az) axis-angle exponential coordinates
814
+ eps (float): Stability value below which small values will be mapped to 0
815
+
816
+ Returns:
817
+ tensor: (..., 4) tensor where final dim is (x,y,z,w) vec4 float quaternion
818
+ """
819
+ # type: (Tensor, float) -> Tensor
820
+ # store input shape and reshape
821
+ input_shape = vec.shape[:-1]
822
+ vec = vec.reshape(-1, 3)
823
+
824
+ # Grab angle
825
+ angle = torch.norm(vec, dim=-1, keepdim=True)
826
+
827
+ # Create return array
828
+ quat = torch.zeros(torch.prod(torch.tensor(input_shape, dtype=torch.int)), 4, device=vec.device)
829
+ quat[:, 3] = 1.0
830
+
831
+ # Grab indexes where angle is not zero an convert the input to its quaternion form
832
+ idx = angle.reshape(-1) > eps # torch.nonzero(angle).reshape(-1)
833
+ quat[idx, :] = torch.cat(
834
+ [vec[idx, :] * torch.sin(angle[idx, :] / 2.0) / angle[idx, :], torch.cos(angle[idx, :] / 2.0)], dim=-1
835
+ )
836
+
837
+ # Reshape and return output
838
+ quat = quat.reshape(
839
+ list(input_shape)
840
+ + [
841
+ 4,
842
+ ]
843
+ )
844
+ return quat
845
+
846
+
847
+ @torch_compile
848
+ def pose_in_A_to_pose_in_B(pose_A, pose_A_in_B):
849
+ """
850
+ Converts a homogenous matrix corresponding to a point C in frame A
851
+ to a homogenous matrix corresponding to the same point C in frame B.
852
+
853
+ Args:
854
+ pose_A (torch.tensor): 4x4 matrix corresponding to the pose of C in frame A
855
+ pose_A_in_B (torch.tensor): 4x4 matrix corresponding to the pose of A in frame B
856
+
857
+ Returns:
858
+ torch.tensor: 4x4 matrix corresponding to the pose of C in frame B
859
+ """
860
+
861
+ # pose of A in B takes a point in A and transforms it to a point in C.
862
+
863
+ # pose of C in B = pose of A in B * pose of C in A
864
+ # take a point in C, transform it to A, then to B
865
+ # T_B^C = T_A^C * T_B^A
866
+ return torch.matmul(pose_A_in_B, pose_A)
867
+
868
+
869
+ @torch_compile
870
+ def pose_inv(pose_mat: torch.Tensor) -> torch.Tensor:
871
+ """
872
+ Computes the inverse of a homogeneous matrix corresponding to the pose of some
873
+ frame B in frame A. The inverse is the pose of frame A in frame B.
874
+
875
+ Args:
876
+ pose_mat (torch.tensor): 4x4 matrix for the pose to inverse
877
+
878
+ Returns:
879
+ torch.tensor: 4x4 matrix for the inverse pose
880
+ """
881
+
882
+ # Note, the inverse of a pose matrix is the following
883
+ # [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]
884
+
885
+ # Intuitively, this makes sense.
886
+ # The original pose matrix translates by t, then rotates by R.
887
+ # We just invert the rotation by applying R-1 = R.T, and also translate back.
888
+ # Since we apply translation first before rotation, we need to translate by
889
+ # -t in the original frame, which is -R-1*t in the new frame, and then rotate back by
890
+ # R-1 to align the axis again.
891
+
892
+ pose_mat = pose_mat.reshape(-1, 4, 4)
893
+ batch_size = pose_mat.shape[0]
894
+ pose_inv = torch.zeros((batch_size, 4, 4), device=pose_mat.device)
895
+ pose_inv[:, :3, :3] = pose_mat[:, :3, :3].transpose(1, 2)
896
+ pose_inv[:, :3, 3] = (-pose_inv[:, :3, :3] @ pose_mat[:, :3, 3].unsqueeze(-1)).squeeze(-1)
897
+ pose_inv[:, 3, 3] = 1.0
898
+ pose_inv = pose_inv.squeeze(0)
899
+ return pose_inv
900
+
901
+
902
+ @torch_compile
903
+ def pose_transform(pos1, quat1, pos0, quat0):
904
+ """
905
+ Conducts forward transform from pose (pos0, quat0) to pose (pos1, quat1):
906
+
907
+ pose1 @ pose0, NOT pose0 @ pose1
908
+
909
+ Args:
910
+ pos1 (torch.Tensor): (x,y,z) position to transform
911
+ quat1 (torch.Tensor): (x,y,z,w) orientation to transform
912
+ pos0 (torch.Tensor): (x,y,z) initial position
913
+ quat0 (torch.Tensor): (x,y,z,w) initial orientation
914
+
915
+ Returns:
916
+ 2-tuple:
917
+ - (torch.tensor) (x,y,z) position array in cartesian coordinates
918
+ - (torch.tensor) (x,y,z,w) orientation array in quaternion form
919
+ """
920
+ # Get poses
921
+ mat0 = pose2mat((pos0, quat0))
922
+ mat1 = pose2mat((pos1, quat1))
923
+
924
+ # Multiply and convert back to pos, quat
925
+ return mat2pose(mat1 @ mat0)
926
+
927
+
928
+ @torch_compile
929
+ def invert_pose_transform(pos, quat):
930
+ """
931
+ Inverts a pose transform
932
+
933
+ Args:
934
+ pos (torch.Tensor): (x,y,z) position to transform
935
+ quat (torch.Tensor): (x,y,z,w) orientation to transform
936
+
937
+ Returns:
938
+ 2-tuple:
939
+ - (torch.tensor) (x,y,z) position array in cartesian coordinates
940
+ - (torch.tensor) (x,y,z,w) orientation array in quaternion form
941
+ """
942
+ # Get pose
943
+ mat = pose2mat((pos, quat))
944
+
945
+ # Invert pose and convert back to pos, quat
946
+ return mat2pose(pose_inv(mat))
947
+
948
+
949
+ @torch_compile
950
+ def relative_pose_transform(pos1, quat1, pos0, quat0):
951
+ """
952
+ Computes relative forward transform from pose (pos0, quat0) to pose (pos1, quat1), i.e.: solves:
953
+
954
+ pose1 = pose0 @ transform
955
+
956
+ Args:
957
+ pos1 (torch.Tensor): (x,y,z) position to transform
958
+ quat1 (torch.Tensor): (x,y,z,w) orientation to transform
959
+ pos0 (torch.Tensor): (x,y,z) initial position
960
+ quat0 (torch.Tensor): (x,y,z,w) initial orientation
961
+
962
+ Returns:
963
+ 2-tuple:
964
+ - (torch.tensor) (x,y,z) position array in cartesian coordinates
965
+ - (torch.tensor) (x,y,z,w) orientation array in quaternion form
966
+ """
967
+ # Get poses
968
+ mat0 = pose2mat((pos0, quat0))
969
+ mat1 = pose2mat((pos1, quat1))
970
+
971
+ # Invert pose0 and calculate transform
972
+ return mat2pose(pose_inv(mat0) @ mat1)
973
+
974
+
975
+ @torch_compile
976
+ def _skew_symmetric_translation(pos_A_in_B):
977
+ """
978
+ Helper function to get a skew symmetric translation matrix for converting quantities
979
+ between frames.
980
+
981
+ Args:
982
+ pos_A_in_B (torch.tensor): (x,y,z) position of A in frame B
983
+
984
+ Returns:
985
+ torch.tensor: 3x3 skew symmetric translation matrix
986
+ """
987
+ return torch.tensor(
988
+ [
989
+ [0.0, -pos_A_in_B[2].item(), pos_A_in_B[1].item()],
990
+ [pos_A_in_B[2].item(), 0.0, -pos_A_in_B[0].item()],
991
+ [-pos_A_in_B[1].item(), pos_A_in_B[0].item(), 0.0],
992
+ ],
993
+ dtype=torch.float32,
994
+ device=pos_A_in_B.device,
995
+ )
996
+
997
+
998
+ @torch_compile
999
+ def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B):
1000
+ """
1001
+ Converts linear and angular velocity of a point in frame A to the equivalent in frame B.
1002
+
1003
+ Args:
1004
+ vel_A (torch.tensor): (vx,vy,vz) linear velocity in A
1005
+ ang_vel_A (torch.tensor): (wx,wy,wz) angular velocity in A
1006
+ pose_A_in_B (torch.tensor): 4x4 matrix corresponding to the pose of A in frame B
1007
+
1008
+ Returns:
1009
+ 2-tuple:
1010
+
1011
+ - (torch.tensor) (vx,vy,vz) linear velocities in frame B
1012
+ - (torch.tensor) (wx,wy,wz) angular velocities in frame B
1013
+ """
1014
+ pos_A_in_B = pose_A_in_B[:3, 3]
1015
+ rot_A_in_B = pose_A_in_B[:3, :3]
1016
+ skew_symm = _skew_symmetric_translation(pos_A_in_B)
1017
+ vel_B = rot_A_in_B @ vel_A + skew_symm @ (rot_A_in_B @ ang_vel_A)
1018
+ ang_vel_B = rot_A_in_B @ ang_vel_A
1019
+ return vel_B, ang_vel_B
1020
+
1021
+
1022
+ @torch_compile
1023
+ def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B):
1024
+ """
1025
+ Converts linear and rotational force at a point in frame A to the equivalent in frame B.
1026
+
1027
+ Args:
1028
+ force_A (torch.tensor): (fx,fy,fz) linear force in A
1029
+ torque_A (torch.tensor): (tx,ty,tz) rotational force (moment) in A
1030
+ pose_A_in_B (torch.tensor): 4x4 matrix corresponding to the pose of A in frame B
1031
+
1032
+ Returns:
1033
+ 2-tuple:
1034
+
1035
+ - (torch.tensor) (fx,fy,fz) linear forces in frame B
1036
+ - (torch.tensor) (tx,ty,tz) moments in frame B
1037
+ """
1038
+ pos_A_in_B = pose_A_in_B[:3, 3]
1039
+ rot_A_in_B = pose_A_in_B[:3, :3]
1040
+ skew_symm = _skew_symmetric_translation(pos_A_in_B)
1041
+ force_B = rot_A_in_B.T @ force_A
1042
+ torque_B = -(rot_A_in_B.T @ (skew_symm @ force_A)) + rot_A_in_B.T @ torque_A
1043
+ return force_B, torque_B
1044
+
1045
+
1046
+ @torch_compile
1047
+ def rotation_matrix(angle: float, direction: torch.Tensor) -> torch.Tensor:
1048
+ """
1049
+ Returns a 3x3 rotation matrix to rotate about the given axis.
1050
+
1051
+ Args:
1052
+ angle (float): Magnitude of rotation in radians
1053
+ direction (torch.Tensor): (ax,ay,az) axis about which to rotate
1054
+
1055
+ Returns:
1056
+ torch.Tensor: 3x3 rotation matrix
1057
+ """
1058
+ sina = torch.sin(torch.tensor(angle, dtype=torch.float32))
1059
+ cosa = torch.cos(torch.tensor(angle, dtype=torch.float32))
1060
+
1061
+ direction = direction / torch.norm(direction) # Normalize direction vector
1062
+
1063
+ # Create rotation matrix
1064
+ R = torch.eye(3, dtype=torch.float32, device=direction.device)
1065
+ R *= cosa
1066
+ R += torch.outer(direction, direction) * (1.0 - cosa)
1067
+ direction *= sina
1068
+
1069
+ # Create the skew-symmetric matrix
1070
+ skew_matrix = torch.zeros(3, 3, dtype=torch.float32, device=direction.device)
1071
+ skew_matrix[0, 1] = -direction[2]
1072
+ skew_matrix[0, 2] = direction[1]
1073
+ skew_matrix[1, 0] = direction[2]
1074
+ skew_matrix[1, 2] = -direction[0]
1075
+ skew_matrix[2, 0] = -direction[1]
1076
+ skew_matrix[2, 1] = direction[0]
1077
+
1078
+ R += skew_matrix
1079
+
1080
+ return R
1081
+
1082
+
1083
+ @torch_compile
1084
+ def transformation_matrix(angle: float, direction: torch.Tensor, point: Optional[torch.Tensor] = None) -> torch.Tensor:
1085
+ """
1086
+ Returns a 4x4 homogeneous transformation matrix to rotate about axis defined by point and direction.
1087
+ Args:
1088
+ angle (float): Magnitude of rotation in radians
1089
+ direction (torch.Tensor): (ax,ay,az) axis about which to rotate
1090
+ point (Optional[torch.Tensor]): If specified, is the (x,y,z) point about which the rotation will occur
1091
+ Returns:
1092
+ torch.Tensor: 4x4 homogeneous transformation matrix
1093
+ """
1094
+ R = rotation_matrix(angle, direction)
1095
+
1096
+ M = torch.eye(4, dtype=torch.float32, device=direction.device)
1097
+ M[:3, :3] = R
1098
+
1099
+ if point is not None:
1100
+ # Rotation not about origin
1101
+ point = point.to(dtype=torch.float32)
1102
+ M[:3, 3] = point - R @ point
1103
+ return M
1104
+
1105
+
1106
+ @torch_compile
1107
+ def clip_translation(dpos, limit):
1108
+ """
1109
+ Limits a translation (delta position) to a specified limit
1110
+
1111
+ Scales down the norm of the dpos to 'limit' if norm(dpos) > limit, else returns immediately
1112
+
1113
+ Args:
1114
+ dpos (n-array): n-dim Translation being clipped (e,g.: (x, y, z)) -- numpy array
1115
+ limit (float): Value to limit translation by -- magnitude (scalar, in same units as input)
1116
+
1117
+ Returns:
1118
+ 2-tuple:
1119
+
1120
+ - (torch.tensor) Clipped translation (same dimension as inputs)
1121
+ - (bool) whether the value was clipped or not
1122
+ """
1123
+ input_norm = torch.norm(dpos)
1124
+ return (dpos * limit / input_norm, True) if input_norm > limit else (dpos, False)
1125
+
1126
+
1127
+ @torch_compile
1128
+ def clip_rotation(quat, limit):
1129
+ """
1130
+ Limits a (delta) rotation to a specified limit
1131
+
1132
+ Converts rotation to axis-angle, clips, then re-converts back into quaternion
1133
+
1134
+ Args:
1135
+ quat (torch.tensor): (x,y,z,w) rotation being clipped
1136
+ limit (float): Value to limit rotation by -- magnitude (scalar, in radians)
1137
+
1138
+ Returns:
1139
+ 2-tuple:
1140
+
1141
+ - (torch.tensor) Clipped rotation quaternion (x, y, z, w)
1142
+ - (bool) whether the value was clipped or not
1143
+ """
1144
+ clipped = False
1145
+
1146
+ # First, normalize the quaternion
1147
+ quat = quat / torch.norm(quat)
1148
+
1149
+ den = math.sqrt(max(1 - quat[3] * quat[3], 0))
1150
+ if den == 0:
1151
+ # This is a zero degree rotation, immediately return
1152
+ return quat, clipped
1153
+ else:
1154
+ # This is all other cases
1155
+ x = quat[0] / den
1156
+ y = quat[1] / den
1157
+ z = quat[2] / den
1158
+ a = 2 * math.acos(quat[3])
1159
+
1160
+ # Clip rotation if necessary and return clipped quat
1161
+ if abs(a) > limit:
1162
+ a = limit * torch.sign(a) / 2
1163
+ sa = math.sin(a)
1164
+ ca = math.cos(a)
1165
+ quat = torch.tensor([x * sa, y * sa, z * sa, ca])
1166
+ clipped = True
1167
+
1168
+ return quat, clipped
1169
+
1170
+
1171
+ @torch_compile
1172
+ def make_pose(translation, rotation):
1173
+ """
1174
+ Makes a homogeneous pose matrix from a translation vector and a rotation matrix.
1175
+
1176
+ Args:
1177
+ translation (torch.tensor): (x,y,z) translation value
1178
+ rotation (torch.tensor): a 3x3 matrix representing rotation
1179
+
1180
+ Returns:
1181
+ pose (torch.tensor): a 4x4 homogeneous matrix
1182
+ """
1183
+ pose = torch.zeros((4, 4))
1184
+ pose[:3, :3] = rotation
1185
+ pose[:3, 3] = translation
1186
+ pose[3, 3] = 1.0
1187
+ return pose
1188
+
1189
+
1190
+ @torch_compile
1191
+ def get_orientation_error(desired, current):
1192
+ """
1193
+ This function calculates a 3-dimensional orientation error vector, where inputs are quaternions
1194
+
1195
+ Args:
1196
+ desired (tensor): (..., 4) where final dim is (x,y,z,w) quaternion
1197
+ current (tensor): (..., 4) where final dim is (x,y,z,w) quaternion
1198
+ Returns:
1199
+ tensor: (..., 3) where final dim is (ax, ay, az) axis-angle representing orientation error
1200
+ """
1201
+ # convert input shapes
1202
+ input_shape = desired.shape[:-1]
1203
+ desired = desired.reshape(-1, 4)
1204
+ current = current.reshape(-1, 4)
1205
+
1206
+ cc = quat_conjugate(current)
1207
+ q_r = quat_multiply(desired, cc)
1208
+ return (q_r[:, 0:3] * torch.sign(q_r[:, 3]).unsqueeze(-1)).reshape(list(input_shape) + [3])
1209
+
1210
+
1211
+ @torch_compile
1212
+ def get_orientation_diff_in_radian(orn0: torch.Tensor, orn1: torch.Tensor) -> torch.Tensor:
1213
+ """
1214
+ Returns the difference between two quaternion orientations in radians.
1215
+
1216
+ Args:
1217
+ orn0 (torch.Tensor): (x, y, z, w) quaternion
1218
+ orn1 (torch.Tensor): (x, y, z, w) quaternion
1219
+
1220
+ Returns:
1221
+ orn_diff (torch.Tensor): orientation difference in radians
1222
+ """
1223
+ # Compute the difference quaternion
1224
+ diff_quat = quat_distance(orn0, orn1)
1225
+
1226
+ # Convert to axis-angle representation
1227
+ axis_angle = quat2axisangle(diff_quat)
1228
+
1229
+ # The magnitude of the axis-angle vector is the rotation angle
1230
+ return torch.norm(axis_angle)
1231
+
1232
+
1233
+ @torch_compile
1234
+ def get_pose_error(target_pose, current_pose):
1235
+ """
1236
+ Computes the error corresponding to target pose - current pose as a 6-dim vector.
1237
+ The first 3 components correspond to translational error while the last 3 components
1238
+ correspond to the rotational error.
1239
+
1240
+ Args:
1241
+ target_pose (torch.tensor): a 4x4 homogenous matrix for the target pose
1242
+ current_pose (torch.tensor): a 4x4 homogenous matrix for the current pose
1243
+
1244
+ Returns:
1245
+ torch.tensor: 6-dim pose error.
1246
+ """
1247
+ error = torch.zeros(6)
1248
+
1249
+ # compute translational error
1250
+ target_pos = target_pose[:3, 3]
1251
+ current_pos = current_pose[:3, 3]
1252
+ pos_err = target_pos - current_pos
1253
+
1254
+ # compute rotational error
1255
+ r1 = current_pose[:3, 0]
1256
+ r2 = current_pose[:3, 1]
1257
+ r3 = current_pose[:3, 2]
1258
+ r1d = target_pose[:3, 0]
1259
+ r2d = target_pose[:3, 1]
1260
+ r3d = target_pose[:3, 2]
1261
+ rot_err = 0.5 * (torch.linalg.cross(r1, r1d) + torch.linalg.cross(r2, r2d) + torch.linalg.cross(r3, r3d))
1262
+
1263
+ error[:3] = pos_err
1264
+ error[3:] = rot_err
1265
+ return error
1266
+
1267
+
1268
+ @torch_compile
1269
+ def matrix_inverse(matrix):
1270
+ """
1271
+ Helper function to have an efficient matrix inversion function.
1272
+
1273
+ Args:
1274
+ matrix (torch.tensor): 2d-array representing a matrix
1275
+
1276
+ Returns:
1277
+ torch.tensor: 2d-array representing the matrix inverse
1278
+ """
1279
+ return torch.linalg.inv_ex(matrix).inverse
1280
+
1281
+
1282
+ @torch_compile
1283
+ def vecs2axisangle(vec0, vec1):
1284
+ """
1285
+ Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into an axis-angle representation of the angle
1286
+
1287
+ Args:
1288
+ vec0 (torch.tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1289
+ vec1 (torch.tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1290
+ """
1291
+ # Normalize vectors
1292
+ vec0 = normalize(vec0, dim=-1, eps=1e-10)
1293
+ vec1 = normalize(vec1, dim=-1, eps=1e-10)
1294
+
1295
+ # Get cross product for direction of angle, and multiply by arcos of the dot product which is the angle
1296
+ return torch.linalg.cross(vec0, vec1) * torch.arccos((vec0 * vec1).sum(-1, keepdim=True))
1297
+
1298
+
1299
+ @torch_compile
1300
+ def vecs2quat(vec0: torch.Tensor, vec1: torch.Tensor, normalized: bool = False) -> torch.Tensor:
1301
+ """
1302
+ Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into a quaternion representation of the angle
1303
+ Args:
1304
+ vec0 (torch.Tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1305
+ vec1 (torch.Tensor): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1306
+ normalized (bool): If True, @vec0 and @vec1 are assumed to already be normalized and we will skip the
1307
+ normalization step (more efficient)
1308
+ Returns:
1309
+ torch.Tensor: (..., 4) Normalized quaternion representing the rotation from vec0 to vec1
1310
+ """
1311
+ # Normalize vectors if requested
1312
+ if not normalized:
1313
+ vec0 = normalize(vec0, dim=-1, eps=1e-10)
1314
+ vec1 = normalize(vec1, dim=-1, eps=1e-10)
1315
+
1316
+ # Half-way Quaternion Solution -- see https://stackoverflow.com/a/11741520
1317
+ cos_theta = torch.sum(vec0 * vec1, dim=-1, keepdim=True)
1318
+
1319
+ # Create a tensor for the case where cos_theta == -1
1320
+ batch_shape = vec0.shape[:-1]
1321
+ fallback = torch.zeros(batch_shape + (4,), device=vec0.device, dtype=vec0.dtype)
1322
+ fallback[..., 0] = 1.0
1323
+
1324
+ # Compute the quaternion
1325
+ quat_unnormalized = torch.where(
1326
+ cos_theta == -1,
1327
+ fallback,
1328
+ torch.cat([torch.linalg.cross(vec0, vec1), 1 + cos_theta], dim=-1),
1329
+ )
1330
+
1331
+ return quat_unnormalized / torch.norm(quat_unnormalized, dim=-1, keepdim=True)
1332
+
1333
+
1334
+ # Ref: https://github.com/scipy/scipy/blob/9974222eb58ec3eafe5d12f25ee960f3170c277a/scipy/spatial/transform/_rotation.pyx#L3249
1335
+ @torch_compile
1336
+ def align_vector_sets(vec_set1: torch.Tensor, vec_set2: torch.Tensor) -> torch.Tensor:
1337
+ """
1338
+ Computes a single quaternion representing the rotation that best aligns vec_set1 to vec_set2.
1339
+
1340
+ Args:
1341
+ vec_set1 (torch.Tensor): (N, 3) tensor of N 3D vectors
1342
+ vec_set2 (torch.Tensor): (N, 3) tensor of N 3D vectors
1343
+
1344
+ Returns:
1345
+ torch.Tensor: (4,) Normalized quaternion representing the overall rotation
1346
+ """
1347
+ B = torch.einsum("ji,jk->ik", vec_set1, vec_set2)
1348
+ u, s, vh = torch.linalg.svd(B)
1349
+
1350
+ # Correct improper rotation if necessary (as in Kabsch algorithm)
1351
+ if torch.linalg.det(u @ vh) < 0:
1352
+ s[-1] = -s[-1]
1353
+ u[:, -1] = -u[:, -1]
1354
+
1355
+ C = u @ vh
1356
+
1357
+ # if s[1] + s[2] < 1e-16 * s[0]:
1358
+ # warnings.warn("Optimal rotation is not uniquely or poorly defined "
1359
+ # "for the given sets of vectors.")
1360
+
1361
+ return mat2quat(C)
1362
+
1363
+
1364
+ @torch_compile
1365
+ def l2_distance(v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
1366
+ """Returns the L2 distance between vector v1 and v2."""
1367
+ return torch.norm(v1 - v2)
1368
+
1369
+
1370
+ @torch_compile
1371
+ def cartesian_to_polar(x, y):
1372
+ """Convert cartesian coordinate to polar coordinate"""
1373
+ rho = torch.sqrt(x**2 + y**2)
1374
+ phi = torch.arctan2(y, x)
1375
+ return rho, phi
1376
+
1377
+
1378
+ def deg2rad(deg):
1379
+ return deg * math.pi / 180.0
1380
+
1381
+
1382
+ def rad2deg(rad):
1383
+ return rad * 180.0 / math.pi
1384
+
1385
+
1386
+ @torch_compile
1387
+ def check_quat_right_angle(quat: torch.Tensor, atol: float = 5e-2) -> torch.Tensor:
1388
+ """
1389
+ Check by making sure the quaternion is some permutation of +/- (1, 0, 0, 0),
1390
+ +/- (0.707, 0.707, 0, 0), or +/- (0.5, 0.5, 0.5, 0.5)
1391
+ Because orientations are all normalized (same L2-norm), every orientation should have a unique L1-norm
1392
+ So we check the L1-norm of the absolute value of the orientation as a proxy for verifying these values
1393
+
1394
+ Args:
1395
+ quat (torch.Tensor): (x,y,z,w) quaternion orientation to check
1396
+ atol (float): Absolute tolerance permitted
1397
+
1398
+ Returns:
1399
+ torch.Tensor: Boolean tensor indicating whether the quaternion is a right angle or not
1400
+ """
1401
+ l1_norm = torch.abs(quat).sum(dim=-1)
1402
+ reference_norms = torch.tensor([1.0, 1.414, 2.0], device=quat.device, dtype=quat.dtype)
1403
+ return torch.any(torch.abs(l1_norm.unsqueeze(-1) - reference_norms) < atol, dim=-1)
1404
+
1405
+
1406
+ @torch_compile
1407
+ def z_angle_from_quat(quat):
1408
+ """Get the angle around the Z axis produced by the quaternion."""
1409
+ rotated_X_axis = quat_apply(quat, torch.tensor([1, 0, 0], dtype=torch.float32))
1410
+ return torch.arctan2(rotated_X_axis[1], rotated_X_axis[0])
1411
+
1412
+
1413
+ @torch_compile
1414
+ def integer_spiral_coordinates(n: int) -> Tuple[int, int]:
1415
+ """A function to map integers to 2D coordinates in a spiral pattern around the origin."""
1416
+ # Map integers from Z to Z^2 in a spiral pattern around the origin.
1417
+ # Sources:
1418
+ # https://www.reddit.com/r/askmath/comments/18vqorf/find_the_nth_coordinate_of_a_square_spiral/
1419
+ # https://oeis.org/A174344
1420
+ m = math.floor(math.sqrt(n))
1421
+ x = ((-1) ** m) * ((n - m * (m + 1)) * (math.floor(2 * math.sqrt(n)) % 2) - math.ceil(m / 2))
1422
+ y = ((-1) ** (m + 1)) * ((n - m * (m + 1)) * (math.floor(2 * math.sqrt(n) + 1) % 2) + math.ceil(m / 2))
1423
+ return int(x), int(y)
1424
+
1425
+
1426
+ @torch_compile
1427
+ def transform_points(points: torch.Tensor, matrix: torch.Tensor, translate: bool = True) -> torch.Tensor:
1428
+ """
1429
+ Returns points rotated by a homogeneous
1430
+ transformation matrix.
1431
+ If points are (n, 2) matrix must be (3, 3)
1432
+ If points are (n, 3) matrix must be (4, 4)
1433
+
1434
+ Arguments:
1435
+ points : (n, dim) torch.Tensor
1436
+ Points where `dim` is 2 or 3.
1437
+ matrix : (3, 3) or (4, 4) torch.Tensor
1438
+ Homogeneous rotation matrix.
1439
+ translate : bool
1440
+ Apply translation from matrix or not.
1441
+
1442
+ Returns:
1443
+ transformed : (n, dim) torch.Tensor
1444
+ Transformed points.
1445
+ """
1446
+ if len(points) == 0 or matrix is None:
1447
+ return points.clone()
1448
+
1449
+ count, dim = points.shape
1450
+ # Check if the matrix is close to an identity matrix
1451
+ identity = torch.eye(dim + 1, device=points.device)
1452
+ if torch.abs(matrix - identity[: dim + 1, : dim + 1]).max() < 1e-8:
1453
+ return points.clone().contiguous()
1454
+
1455
+ if translate:
1456
+ stack = torch.cat((points, torch.ones(count, 1, device=points.device)), dim=1)
1457
+ return torch.mm(matrix, stack.t()).t()[:, :dim]
1458
+ else:
1459
+ return torch.mm(matrix[:dim, :dim], points.t()).t()
1460
+
1461
+
1462
+ @torch_compile
1463
+ def quaternions_close(q1: torch.Tensor, q2: torch.Tensor, atol: float = 1e-3) -> bool:
1464
+ """
1465
+ Whether two quaternions represent the same rotation,
1466
+ allowing for the possibility that one is the negative of the other.
1467
+
1468
+ Arguments:
1469
+ q1: torch.Tensor
1470
+ First quaternion
1471
+ q2: torch.Tensor
1472
+ Second quaternion
1473
+ atol: float
1474
+ Absolute tolerance for comparison
1475
+
1476
+ Returns:
1477
+ bool
1478
+ Whether the quaternions are close
1479
+ """
1480
+ return torch.allclose(q1, q2, atol=atol) or torch.allclose(q1, -q2, atol=atol)
1481
+
1482
+
1483
+ @torch_compile
1484
+ def orientation_error(desired, current):
1485
+ """
1486
+ This function calculates a 3-dimensional orientation error vector for use in the
1487
+ impedance controller. It does this by computing the delta rotation between the
1488
+ inputs and converting that rotation to exponential coordinates (axis-angle
1489
+ representation, where the 3d vector is axis * angle).
1490
+ See https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation for more information.
1491
+ Optimized function to determine orientation error from matrices
1492
+
1493
+ Args:
1494
+ desired (tensor): (..., 3, 3) where final two dims are 2d array representing target orientation matrix
1495
+ current (tensor): (..., 3, 3) where final two dims are 2d array representing current orientation matrix
1496
+ Returns:
1497
+ tensor: (..., 3) where final dim is (ax, ay, az) axis-angle representing orientation error
1498
+ """
1499
+ # Compute batch size
1500
+ batch_size = desired.numel() // 9 # Each 3x3 matrix has 9 elements
1501
+
1502
+ desired_flat = desired.reshape(batch_size, 3, 3)
1503
+ current_flat = current.reshape(batch_size, 3, 3)
1504
+
1505
+ rc1, rc2, rc3 = current_flat[:, :, 0], current_flat[:, :, 1], current_flat[:, :, 2]
1506
+ rd1, rd2, rd3 = desired_flat[:, :, 0], desired_flat[:, :, 1], desired_flat[:, :, 2]
1507
+
1508
+ error = 0.5 * (torch.linalg.cross(rc1, rd1) + torch.linalg.cross(rc2, rd2) + torch.linalg.cross(rc3, rd3))
1509
+
1510
+ return error.reshape(desired.shape[:-2] + (3,))
1511
+
1512
+
1513
+ @torch_compile
1514
+ def delta_rotation_matrix(omega, delta_t):
1515
+ """
1516
+ Compute the delta rotation matrix given angular velocity and time elapsed.
1517
+
1518
+ Arguments:
1519
+ omega (torch.tensor): Angular velocity vector [omega_x, omega_y, omega_z].
1520
+ delta_t (float): Time elapsed.
1521
+
1522
+ Returns:
1523
+ torch.tensor: 3x3 Delta rotation matrix.
1524
+ """
1525
+ # Magnitude of angular velocity (angular speed)
1526
+ omega_magnitude = torch.linalg.norm(omega)
1527
+
1528
+ # If angular speed is zero, return identity matrix
1529
+ if omega_magnitude == 0:
1530
+ return torch.eye(3)
1531
+
1532
+ # Rotation angle
1533
+ theta = omega_magnitude * delta_t
1534
+
1535
+ # Normalized axis of rotation
1536
+ axis = omega / omega_magnitude
1537
+
1538
+ # Skew-symmetric matrix K
1539
+ u_x, u_y, u_z = axis[0], axis[1], axis[2]
1540
+ K = torch.zeros((3, 3))
1541
+ K[0, 1] = -u_z
1542
+ K[0, 2] = u_y
1543
+ K[1, 0] = u_z
1544
+ K[1, 2] = -u_x
1545
+ K[2, 0] = -u_y
1546
+ K[2, 1] = u_x
1547
+
1548
+ # Rodrigues' rotation formula
1549
+ R = torch.eye(3) + torch.sin(theta) * K + (1 - torch.cos(theta)) * (K @ K)
1550
+
1551
+ return R
1552
+
1553
+
1554
+ @torch_compile
1555
+ def mat2euler_intrinsic(rmat):
1556
+ """
1557
+ Converts given rotation matrix to intrinsic euler angles in radian.
1558
+
1559
+ Parameters:
1560
+ rmat (torch.tensor): 3x3 rotation matrix
1561
+
1562
+ Returns:
1563
+ torch.array: (r,p,y) converted intrinsic euler angles in radian vec3 float
1564
+ """
1565
+ # Check for gimbal lock (pitch = +-90 degrees)
1566
+ assert torch.allclose(rmat.det(), torch.tensor(1.0)), "Rotation matrix must not be scaled"
1567
+ if abs(rmat[0, 2]) != 1:
1568
+ # General case
1569
+ pitch = torch.arcsin(rmat[0, 2])
1570
+ roll = torch.arctan2(-rmat[1, 2], rmat[2, 2])
1571
+ yaw = torch.arctan2(-rmat[0, 1], rmat[0, 0])
1572
+ else:
1573
+ # Gimbal lock case
1574
+ pitch = torch.tensor(math.pi / 2 if rmat[0, 2] == 1 else -math.pi / 2)
1575
+ roll = torch.arctan2(rmat[1, 0], rmat[1, 1])
1576
+ yaw = torch.tensor(0.0) # Can set yaw to 0 in gimbal lock
1577
+
1578
+ return torch.stack([roll, pitch, yaw])
1579
+
1580
+
1581
+ @torch_compile
1582
+ def euler_intrinsic2mat(euler):
1583
+ """
1584
+ Converts intrinsic euler angles into rotation matrix form
1585
+
1586
+ Parameters:
1587
+ euler (torch.tensor): (r,p,y) intrinsic euler angles in radian vec3 float
1588
+
1589
+ Returns:
1590
+ torch.tensor: 3x3 rotation matrix
1591
+ """
1592
+ roll, pitch, yaw = euler[0], euler[1], euler[2]
1593
+
1594
+ # Rotation matrix around X-axis
1595
+ euler_x = torch.zeros(3)
1596
+ euler_x[0] = roll
1597
+ Rx = euler2mat(euler_x)
1598
+
1599
+ # Rotation matrix around Y-axis
1600
+ euler_y = torch.zeros(3)
1601
+ euler_y[1] = pitch
1602
+ Ry = euler2mat(euler_y)
1603
+
1604
+ # Rotation matrix around Z-axis
1605
+ euler_z = torch.zeros(3)
1606
+ euler_z[2] = yaw
1607
+ Rz = euler2mat(euler_z)
1608
+
1609
+ # Combine the rotation matrices
1610
+ # Intrinsic x-y-z is the same as extrinsic z-y-x
1611
+ # Multiply Rz first, then Ry, then Rx
1612
+ return Rx @ Ry @ Rz
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/transform_utils_np.py ADDED
@@ -0,0 +1,1442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions of matrix and vector transformations.
3
+
4
+ NOTE: This file has a 1-to-1 correspondence to transform_utils.py. By default, we use scipy for most transform-related
5
+ operations, but we optionally implement numba versions for functions that are often called in "batch" mode
6
+
7
+ NOTE: convention for quaternions is (x, y, z, w)
8
+ """
9
+
10
+ import math
11
+
12
+ import numpy as np
13
+ from numba import jit, prange
14
+ from scipy.spatial.transform import Rotation as R
15
+
16
+ PI = np.pi
17
+ EPS = np.finfo(float).eps * 4.0
18
+
19
+ # axis sequences for Euler angles
20
+ _NEXT_AXIS = [1, 2, 0, 1]
21
+
22
+ # map axes strings to/from tuples of inner axis, parity, repetition, frame
23
+ _AXES2TUPLE = {
24
+ "sxyz": (0, 0, 0, 0),
25
+ "sxyx": (0, 0, 1, 0),
26
+ "sxzy": (0, 1, 0, 0),
27
+ "sxzx": (0, 1, 1, 0),
28
+ "syzx": (1, 0, 0, 0),
29
+ "syzy": (1, 0, 1, 0),
30
+ "syxz": (1, 1, 0, 0),
31
+ "syxy": (1, 1, 1, 0),
32
+ "szxy": (2, 0, 0, 0),
33
+ "szxz": (2, 0, 1, 0),
34
+ "szyx": (2, 1, 0, 0),
35
+ "szyz": (2, 1, 1, 0),
36
+ "rzyx": (0, 0, 0, 1),
37
+ "rxyx": (0, 0, 1, 1),
38
+ "ryzx": (0, 1, 0, 1),
39
+ "rxzx": (0, 1, 1, 1),
40
+ "rxzy": (1, 0, 0, 1),
41
+ "ryzy": (1, 0, 1, 1),
42
+ "rzxy": (1, 1, 0, 1),
43
+ "ryxy": (1, 1, 1, 1),
44
+ "ryxz": (2, 0, 0, 1),
45
+ "rzxz": (2, 0, 1, 1),
46
+ "rxyz": (2, 1, 0, 1),
47
+ "rzyz": (2, 1, 1, 1),
48
+ }
49
+
50
+ _TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())
51
+
52
+
53
+ def copysign(a, b):
54
+ a = np.array(a).repeat(b.shape[0])
55
+ return np.abs(a) * np.sign(b)
56
+
57
+
58
+ def anorm(x, axis=None, keepdims=False):
59
+ """Compute L2 norms alogn specified axes."""
60
+ return np.linalg.norm(x, axis=axis, keepdims=keepdims)
61
+
62
+
63
+ def normalize(v, axis=None, eps=1e-10):
64
+ """L2 Normalize along specified axes."""
65
+ norm = anorm(v, axis=axis, keepdims=True)
66
+ return v / np.where(norm < eps, eps, norm)
67
+
68
+
69
+ def dot(v1, v2, dim=-1, keepdim=False):
70
+ return np.sum(v1 * v2, axis=dim, keepdims=keepdim)
71
+
72
+
73
+ def unit_vector(data, axis=None, out=None):
74
+ """
75
+ Returns ndarray normalized by length, i.e. eucledian norm, along axis.
76
+
77
+ E.g.:
78
+ >>> v0 = numpy.random.random(3)
79
+ >>> v1 = unit_vector(v0)
80
+ >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0))
81
+ True
82
+
83
+ >>> v0 = numpy.random.rand(5, 4, 3)
84
+ >>> v1 = unit_vector(v0, axis=-1)
85
+ >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0 * v0, axis=2)), 2)
86
+ >>> numpy.allclose(v1, v2)
87
+ True
88
+
89
+ >>> v1 = unit_vector(v0, axis=1)
90
+ >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0 * v0, axis=1)), 1)
91
+ >>> numpy.allclose(v1, v2)
92
+ True
93
+
94
+ >>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float32)
95
+ >>> unit_vector(v0, axis=1, out=v1)
96
+ >>> numpy.allclose(v1, v2)
97
+ True
98
+
99
+ >>> list(unit_vector([]))
100
+ []
101
+
102
+ >>> list(unit_vector([1.0]))
103
+ [1.0]
104
+
105
+ Args:
106
+ data (np.array): data to normalize
107
+ axis (None or int): If specified, determines specific axis along data to normalize
108
+ out (None or np.array): If specified, will store computation in this variable
109
+
110
+ Returns:
111
+ None or np.array: If @out is not specified, will return normalized vector. Otherwise, stores the output in @out
112
+ """
113
+ if out is None:
114
+ data = np.array(data, dtype=np.float32, copy=True)
115
+ if data.ndim == 1:
116
+ data /= math.sqrt(np.dot(data, data))
117
+ return data
118
+ else:
119
+ if out is not data:
120
+ out[:] = np.array(data, copy=False)
121
+ data = out
122
+ length = np.atleast_1d(np.sum(data * data, axis))
123
+ np.sqrt(length, length)
124
+ if axis is not None:
125
+ length = np.expand_dims(length, axis)
126
+ data /= length
127
+ if out is None:
128
+ return data
129
+
130
+
131
+ def quat_apply(quat, vec):
132
+ """
133
+ Apply a quaternion rotation to a vector (equivalent to R.from_quat(x).apply(y))
134
+ Args:
135
+ quat (np.array): (4,) or (N, 4) or (N, 1, 4) quaternion in (x, y, z, w) format
136
+ vec (np.array): (3,) or (M, 3) or (1, M, 3) vector to rotate
137
+
138
+ Returns:
139
+ np.array: (M, 3) or (N, M, 3) rotated vector
140
+ """
141
+ return R.from_quat(quat).apply(vec)
142
+
143
+
144
+ def convert_quat(q, to="xyzw"):
145
+ """
146
+ Converts quaternion from one convention to another.
147
+ The convention to convert TO is specified as an optional argument.
148
+ If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa.
149
+
150
+ Args:
151
+ q (np.array): a 4-dim array corresponding to a quaternion
152
+ to (str): either 'xyzw' or 'wxyz', determining which convention to convert to.
153
+ """
154
+ if to == "xyzw":
155
+ return q[[1, 2, 3, 0]]
156
+ if to == "wxyz":
157
+ return q[[3, 0, 1, 2]]
158
+ raise Exception("convert_quat: choose a valid `to` argument (xyzw or wxyz)")
159
+
160
+
161
+ def quat_multiply(quaternion1, quaternion0):
162
+ if quaternion1.dtype != np.float32:
163
+ quaternion1 = quaternion1.astype(np.float32)
164
+ if quaternion0.dtype != np.float32:
165
+ quaternion0 = quaternion0.astype(np.float32)
166
+ return _quat_multiply(quaternion1, quaternion0)
167
+
168
+
169
+ @jit(nopython=True, cache=True)
170
+ def _quat_multiply(quaternion1, quaternion0):
171
+ """
172
+ Return multiplication of two quaternions (q1 * q0).
173
+
174
+ E.g.:
175
+ >>> q = quat_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
176
+ >>> np.allclose(q, [-44, -14, 48, 28])
177
+ True
178
+
179
+ Args:
180
+ quaternion1 (np.array): (x,y,z,w) quaternion
181
+ quaternion0 (np.array): (x,y,z,w) quaternion
182
+
183
+ Returns:
184
+ np.array: (x,y,z,w) multiplied quaternion
185
+ """
186
+ x0, y0, z0, w0 = np.split(quaternion0, 4, axis=-1)
187
+ x1, y1, z1, w1 = np.split(quaternion1, 4, axis=-1)
188
+ return np.concatenate(
189
+ (
190
+ x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
191
+ -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
192
+ x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0,
193
+ -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
194
+ ),
195
+ axis=-1,
196
+ )
197
+
198
+
199
+ def quat_conjugate(quaternion):
200
+ """
201
+ Return conjugate of quaternion.
202
+
203
+ E.g.:
204
+ >>> q0 = random_quaternion()
205
+ >>> q1 = quat_conjugate(q0)
206
+ >>> q1[3] == q0[3] and all(q1[:3] == -q0[:3])
207
+ True
208
+
209
+ Args:
210
+ quaternion (np.array): (x,y,z,w) quaternion
211
+
212
+ Returns:
213
+ np.array: (x,y,z,w) quaternion conjugate
214
+ """
215
+ n_dims = len(quaternion.shape)
216
+ # Reshape to explicitly handle batched calls
217
+ return quaternion * np.array([-1.0, -1.0, -1.0, 1.0], dtype=np.float32).reshape([1] * (n_dims - 1) + [4])
218
+
219
+
220
+ def quat_inverse(quaternion):
221
+ """
222
+ Return inverse of quaternion.
223
+
224
+ E.g.:
225
+ >>> q0 = random_quaternion()
226
+ >>> q1 = quat_inverse(q0)
227
+ >>> np.allclose(quat_multiply(q0, q1), [0, 0, 0, 1])
228
+ True
229
+
230
+ Args:
231
+ quaternion (np.array): (x,y,z,w) quaternion
232
+
233
+ Returns:
234
+ np.array: (x,y,z,w) quaternion inverse
235
+ """
236
+ return quat_conjugate(quaternion) / np.sum(quaternion * quaternion, axis=-1, keepdims=True)
237
+
238
+
239
+ def quat_distance(quaternion1, quaternion0):
240
+ """
241
+ Returns distance between two quaternions, such that distance * quaternion0 = quaternion1
242
+ Always returns the shorter rotation path.
243
+
244
+ Args:
245
+ quaternion1 (np.array): (x,y,z,w) quaternion or (..., 4) batched quaternions
246
+ quaternion0 (np.array): (x,y,z,w) quaternion or (..., 4) batched quaternions
247
+
248
+ Returns:
249
+ np.array: (x,y,z,w) quaternion distance or (..., 4) batched quaternion distances
250
+ """
251
+ # Compute dot product along the last axis (quaternion components)
252
+ d = np.sum(quaternion0 * quaternion1, axis=-1, keepdims=True)
253
+ # If dot product is negative, negate one quaternion to get shorter path
254
+ quaternion1 = np.where(d < 0.0, -quaternion1, quaternion1)
255
+
256
+ return quat_multiply(quaternion1, quat_inverse(quaternion0))
257
+
258
+
259
+ def quat_slerp(quat0, quat1, fraction, shortestpath=True):
260
+ """
261
+ Return spherical linear interpolation between two quaternions.
262
+
263
+ E.g.:
264
+ >>> q0 = random_quat()
265
+ >>> q1 = random_quat()
266
+ >>> q = quat_slerp(q0, q1, 0.0)
267
+ >>> np.allclose(q, q0)
268
+ True
269
+
270
+ >>> q = quat_slerp(q0, q1, 1.0)
271
+ >>> np.allclose(q, q1)
272
+ True
273
+
274
+ >>> q = quat_slerp(q0, q1, 0.5)
275
+ >>> angle = math.acos(np.dot(q0, q))
276
+ >>> np.allclose(2.0, math.acos(np.dot(q0, q1)) / angle) or \
277
+ np.allclose(2.0, math.acos(-np.dot(q0, q1)) / angle)
278
+ True
279
+
280
+ Args:
281
+ quat0 (np.array): (x,y,z,w) quaternion startpoint
282
+ quat1 (np.array): (x,y,z,w) quaternion endpoint
283
+ fraction (float): fraction of interpolation to calculate
284
+ shortestpath (bool): If True, will calculate the shortest path
285
+
286
+ Returns:
287
+ np.array: (x,y,z,w) quaternion distance
288
+ """
289
+ q0 = unit_vector(quat0[:4])
290
+ q1 = unit_vector(quat1[:4])
291
+ if fraction == 0.0:
292
+ return q0
293
+ elif fraction == 1.0:
294
+ return q1
295
+ d = np.dot(q0, q1)
296
+ if abs(abs(d) - 1.0) < EPS:
297
+ return q0
298
+ if shortestpath and d < 0.0:
299
+ # invert rotation
300
+ d = -d
301
+ q1 *= -1.0
302
+ angle = math.acos(np.clip(d, -1, 1))
303
+ if abs(angle) < EPS:
304
+ return q0
305
+ isin = 1.0 / math.sin(angle)
306
+ q0 *= math.sin((1.0 - fraction) * angle) * isin
307
+ q1 *= math.sin(fraction * angle) * isin
308
+ q0 += q1
309
+ return q0
310
+
311
+
312
+ @jit(nopython=True, cache=True)
313
+ def random_quaternion(num_quaternions=1):
314
+ """
315
+ Generate random rotation quaternions, uniformly distributed over SO(3).
316
+
317
+ Arguments:
318
+ num_quaternions (int): number of quaternions to generate (default: 1)
319
+
320
+ Returns:
321
+ np.array: A tensor of shape (num_quaternions, 4) containing random unit quaternions.
322
+ """
323
+ # Generate four random numbers between 0 and 1
324
+ rand = np.random.rand(num_quaternions, 4)
325
+
326
+ # Use the formula from Ken Shoemake's "Uniform Random Rotations"
327
+ r1 = np.sqrt(1.0 - rand[:, 0])
328
+ r2 = np.sqrt(rand[:, 0])
329
+ t1 = 2 * np.pi * rand[:, 1]
330
+ t2 = 2 * np.pi * rand[:, 2]
331
+
332
+ quaternions = np.stack((r1 * np.sin(t1), r1 * np.cos(t1), r2 * np.sin(t2), r2 * np.cos(t2)), axis=1)
333
+
334
+ return quaternions
335
+
336
+
337
+ def random_axis_angle(angle_limit=None, random_state=None):
338
+ """
339
+ Samples an axis-angle rotation by first sampling a random axis
340
+ and then sampling an angle. If @angle_limit is provided, the size
341
+ of the rotation angle is constrained.
342
+
343
+ If @random_state is provided (instance of np.random.RandomState), it
344
+ will be used to generate random numbers.
345
+
346
+ Args:
347
+ angle_limit (None or float): If set, determines magnitude limit of angles to generate
348
+ random_state (None or RandomState): RNG to use if specified
349
+
350
+ Raises:
351
+ AssertionError: [Invalid RNG]
352
+ """
353
+ if angle_limit is None:
354
+ angle_limit = 2.0 * np.pi
355
+
356
+ if random_state is not None:
357
+ assert isinstance(random_state, np.random.RandomState)
358
+ npr = random_state
359
+ else:
360
+ npr = np.random
361
+
362
+ # sample random axis using a normalized sample from spherical Gaussian.
363
+ # see (http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/)
364
+ # for why it works.
365
+ random_axis = npr.randn(3)
366
+ random_axis /= np.linalg.norm(random_axis)
367
+ random_angle = npr.uniform(low=0.0, high=angle_limit)
368
+ return random_axis, random_angle
369
+
370
+
371
+ def quat2mat(quaternion):
372
+ if quaternion.dtype != np.float32:
373
+ quaternion = quaternion.astype(np.float32)
374
+ return _quat2mat(quaternion)
375
+
376
+
377
+ @jit(nopython=True, cache=True)
378
+ def _quat2mat(quaternion):
379
+ """
380
+ Convert quaternions into rotation matrices.
381
+
382
+ Args:
383
+ quaternion (torch.Tensor): A tensor of shape (..., 4) representing batches of quaternions (x, y, z, w).
384
+
385
+ Returns:
386
+ torch.Tensor: A tensor of shape (..., 3, 3) representing batches of rotation matrices.
387
+ """
388
+ # broadcast array is necessary to use numba parallel mode
389
+ q1, q2 = np.broadcast_arrays(quaternion[..., np.newaxis], quaternion[..., np.newaxis, :])
390
+ outer = q1 * q2
391
+
392
+ # Extract the necessary components
393
+ xx = outer[..., 0, 0]
394
+ yy = outer[..., 1, 1]
395
+ zz = outer[..., 2, 2]
396
+ xy = outer[..., 0, 1]
397
+ xz = outer[..., 0, 2]
398
+ yz = outer[..., 1, 2]
399
+ xw = outer[..., 0, 3]
400
+ yw = outer[..., 1, 3]
401
+ zw = outer[..., 2, 3]
402
+
403
+ rotation_matrix = np.empty(quaternion.shape[:-1] + (3, 3), dtype=np.float32)
404
+
405
+ rotation_matrix[..., 0, 0] = 1 - 2 * (yy + zz)
406
+ rotation_matrix[..., 0, 1] = 2 * (xy - zw)
407
+ rotation_matrix[..., 0, 2] = 2 * (xz + yw)
408
+
409
+ rotation_matrix[..., 1, 0] = 2 * (xy + zw)
410
+ rotation_matrix[..., 1, 1] = 1 - 2 * (xx + zz)
411
+ rotation_matrix[..., 1, 2] = 2 * (yz - xw)
412
+
413
+ rotation_matrix[..., 2, 0] = 2 * (xz - yw)
414
+ rotation_matrix[..., 2, 1] = 2 * (yz + xw)
415
+ rotation_matrix[..., 2, 2] = 1 - 2 * (xx + yy)
416
+
417
+ return rotation_matrix
418
+
419
+
420
+ def mat2quat(rmat):
421
+ """
422
+ Converts given rotation matrix to quaternion.
423
+
424
+ Args:
425
+ rmat (np.array): (..., 3, 3) rotation matrix
426
+
427
+ Returns:
428
+ np.array: (..., 4) (x,y,z,w) float quaternion angles
429
+ """
430
+ return R.from_matrix(rmat).as_quat()
431
+
432
+
433
+ @jit(nopython=True, fastmath=True, cache=True)
434
+ def _norm_2d_final_dim(mat):
435
+ n_elements = mat.shape[0]
436
+ out = np.zeros(n_elements, dtype=np.float32)
437
+ for i in prange(n_elements):
438
+ vec = mat[i]
439
+ out[i] = np.sqrt(np.sum(vec * vec))
440
+ return out
441
+
442
+
443
+ @jit(nopython=True, cache=True)
444
+ def mat2quat_batch(rmat):
445
+ """
446
+ Converts given rotation matrix to quaternion.
447
+ Args:
448
+ rmat (torch.Tensor): (3, 3) or (..., 3, 3) rotation matrix
449
+ Returns:
450
+ torch.Tensor: (4,) or (..., 4) (x,y,z,w) float quaternion angles
451
+ """
452
+ batch_shape = rmat.shape[:-2]
453
+ mat_flat = rmat.reshape(-1, 3, 3)
454
+
455
+ m00, m01, m02 = mat_flat[:, 0, 0], mat_flat[:, 0, 1], mat_flat[:, 0, 2]
456
+ m10, m11, m12 = mat_flat[:, 1, 0], mat_flat[:, 1, 1], mat_flat[:, 1, 2]
457
+ m20, m21, m22 = mat_flat[:, 2, 0], mat_flat[:, 2, 1], mat_flat[:, 2, 2]
458
+
459
+ trace = m00 + m11 + m22
460
+
461
+ trace_positive = trace > 0
462
+ cond1 = (m00 > m11) & (m00 > m22) & ~trace_positive
463
+ cond2 = (m11 > m22) & ~(trace_positive | cond1)
464
+ cond3 = ~(trace_positive | cond1 | cond2)
465
+
466
+ # Trace positive condition
467
+ sq = np.where(trace_positive, np.sqrt(trace + 1.0) * 2.0, np.zeros_like(trace))
468
+ qw = np.where(trace_positive, 0.25 * sq, np.zeros_like(trace))
469
+ qx = np.where(trace_positive, (m21 - m12) / sq, np.zeros_like(trace))
470
+ qy = np.where(trace_positive, (m02 - m20) / sq, np.zeros_like(trace))
471
+ qz = np.where(trace_positive, (m10 - m01) / sq, np.zeros_like(trace))
472
+
473
+ # Condition 1
474
+ sq = np.where(cond1, np.sqrt(1.0 + m00 - m11 - m22) * 2.0, sq)
475
+ qw = np.where(cond1, (m21 - m12) / sq, qw)
476
+ qx = np.where(cond1, 0.25 * sq, qx)
477
+ qy = np.where(cond1, (m01 + m10) / sq, qy)
478
+ qz = np.where(cond1, (m02 + m20) / sq, qz)
479
+
480
+ # Condition 2
481
+ sq = np.where(cond2, np.sqrt(1.0 + m11 - m00 - m22) * 2.0, sq)
482
+ qw = np.where(cond2, (m02 - m20) / sq, qw)
483
+ qx = np.where(cond2, (m01 + m10) / sq, qx)
484
+ qy = np.where(cond2, 0.25 * sq, qy)
485
+ qz = np.where(cond2, (m12 + m21) / sq, qz)
486
+
487
+ # Condition 3
488
+ sq = np.where(cond3, np.sqrt(1.0 + m22 - m00 - m11) * 2.0, sq)
489
+ qw = np.where(cond3, (m10 - m01) / sq, qw)
490
+ qx = np.where(cond3, (m02 + m20) / sq, qx)
491
+ qy = np.where(cond3, (m12 + m21) / sq, qy)
492
+ qz = np.where(cond3, 0.25 * sq, qz)
493
+
494
+ quat = np.stack((qx, qy, qz, qw), axis=-1)
495
+
496
+ # Normalize the quaternion
497
+ quat = quat / _norm_2d_final_dim(quat)[..., np.newaxis]
498
+
499
+ # Reshape to match input batch shape
500
+ quat = quat.reshape(batch_shape + (4,))
501
+
502
+ return quat
503
+
504
+
505
+ def decompose_mat(hmat):
506
+ """Batched decompose_mat function - assumes input is already batched
507
+
508
+ Args:
509
+ hmat (np.ndarray): (B, 4, 4) batch of homogeneous matrices
510
+
511
+ Returns:
512
+ scale: (B, 3) scale factors
513
+ shear: (B, 3) shear factors
514
+ quat: (B, 4) quaternions
515
+ translate: (B, 3) translations
516
+ """
517
+ batch_size = hmat.shape[0]
518
+ M = np.array(hmat, dtype=np.float32).transpose(0, 2, 1) # (B, 4, 4) transposed
519
+
520
+ # Check M[3, 3] for all batch items
521
+ diag_vals = M[:, 3, 3] # (B,)
522
+ if np.any(np.abs(diag_vals) < EPS):
523
+ raise ValueError("Some M[3, 3] values are zero")
524
+
525
+ M = M / diag_vals[:, np.newaxis, np.newaxis] # (B, 4, 4)
526
+ P = M.copy()
527
+ P[:, :, 3] = np.array([0.0, 0.0, 0.0, 1.0])[np.newaxis, :].repeat(batch_size, axis=0)
528
+
529
+ det_P = np.linalg.det(P[:, :3, :3]) # (B,)
530
+ if np.any(np.abs(det_P) < EPS):
531
+ raise ValueError("Some matrices are singular and cannot be decomposed")
532
+
533
+ if not np.allclose(M[:, :3, 3], 0.0):
534
+ raise ValueError("Some matrices have perspective components")
535
+
536
+ scale = np.zeros((batch_size, 3))
537
+ shear = np.zeros((batch_size, 3))
538
+
539
+ translate = M[:, 3, :3].copy() # (B, 3)
540
+ M[:, 3, :3] = 0.0
541
+
542
+ row = M[:, :3, :3].copy() # (B, 3, 3)
543
+
544
+ # Scale and orthogonalize rows
545
+ scale[:, 0] = np.linalg.norm(row[:, 0], axis=-1) # (B,)
546
+ row[:, 0] = row[:, 0] / scale[:, 0, np.newaxis] # (B, 3)
547
+
548
+ shear[:, 0] = np.sum(row[:, 0] * row[:, 1], axis=-1) # (B,)
549
+ row[:, 1] = row[:, 1] - row[:, 0] * shear[:, 0, np.newaxis] # (B, 3)
550
+
551
+ scale[:, 1] = np.linalg.norm(row[:, 1], axis=-1) # (B,)
552
+ row[:, 1] = row[:, 1] / scale[:, 1, np.newaxis] # (B, 3)
553
+ shear[:, 0] = shear[:, 0] / scale[:, 1]
554
+
555
+ shear[:, 1] = np.sum(row[:, 0] * row[:, 2], axis=-1) # (B,)
556
+ row[:, 2] = row[:, 2] - row[:, 0] * shear[:, 1, np.newaxis] # (B, 3)
557
+
558
+ shear[:, 2] = np.sum(row[:, 1] * row[:, 2], axis=-1) # (B,)
559
+ row[:, 2] = row[:, 2] - row[:, 1] * shear[:, 2, np.newaxis] # (B, 3)
560
+
561
+ scale[:, 2] = np.linalg.norm(row[:, 2], axis=-1) # (B,)
562
+ row[:, 2] = row[:, 2] / scale[:, 2, np.newaxis] # (B, 3)
563
+ shear[:, 1:] = shear[:, 1:] / scale[:, 2, np.newaxis]
564
+
565
+ # Check orientation
566
+ cross_product = np.cross(row[:, 1], row[:, 2], axis=-1) # (B, 3)
567
+ dot_product = np.sum(row[:, 0] * cross_product, axis=-1) # (B,)
568
+ neg_mask = dot_product < 0 # (B,)
569
+
570
+ scale = np.where(neg_mask[:, np.newaxis], -scale, scale) # (B, 3)
571
+ row = np.where(neg_mask[:, np.newaxis, np.newaxis], -row, row) # (B, 3, 3)
572
+
573
+ # Convert to quaternions - assuming mat2quat can handle batched input
574
+ quat = mat2quat(row.transpose(0, 2, 1)) # (B, 4)
575
+
576
+ return scale, shear, quat, translate
577
+
578
+
579
+ def mat2pose(hmat):
580
+ """
581
+ Converts a homogeneous 4x4 matrix into pose.
582
+
583
+ Args:
584
+ hmat (np.array): a 4x4 homogeneous matrix
585
+
586
+ Returns:
587
+ 2-tuple:
588
+ - (np.array) (3,) position array in cartesian coordinates
589
+ - (np.array) (4,) orientation array in quaternion form
590
+ """
591
+ # Add batch dimension, process, then squeeze
592
+ hmat_batched = hmat[np.newaxis, ...] # (1, 4, 4)
593
+ _, _, quat, translate = decompose_mat(hmat_batched)
594
+ return translate.squeeze(0), quat.squeeze(0)
595
+
596
+
597
+ def mat2pose_batched(hmat):
598
+ """
599
+ Converts batched homogeneous 4x4 matrices into poses.
600
+
601
+ Args:
602
+ hmat (np.array): (B, 4, 4) batch of homogeneous matrices
603
+
604
+ Returns:
605
+ 2-tuple:
606
+ - (np.array) (B, 3) position arrays in cartesian coordinates
607
+ - (np.array) (B, 4) orientation arrays in quaternion form
608
+ """
609
+ _, _, quat, translate = decompose_mat(hmat)
610
+ return translate, quat
611
+
612
+
613
+ def vec2quat(vec, up=(0, 0, 1.0)):
614
+ """
615
+ Converts given 3d-direction vector @vec to quaternion orientation with respect to another direction vector @up
616
+
617
+ Args:
618
+ vec (3-array): (x,y,z) direction vector (possible non-normalized)
619
+ up (3-array): (x,y,z) direction vector representing the canonical up direction (possible non-normalized)
620
+ """
621
+ # See https://stackoverflow.com/questions/15873996/converting-a-direction-vector-to-a-quaternion-rotation
622
+ # Take cross product of @up and @vec to get @s_n, and then cross @vec and @s_n to get @u_n
623
+ # Then compose 3x3 rotation matrix and convert into quaternion
624
+ vec_n = vec / np.linalg.norm(vec) # x
625
+ up_n = up / np.linalg.norm(up)
626
+ s_n = np.cross(up_n, vec_n) # y
627
+ u_n = np.cross(vec_n, s_n) # z
628
+ return mat2quat(np.array([vec_n, s_n, u_n]).T)
629
+
630
+
631
+ def euler2quat(euler):
632
+ """
633
+ Converts extrinsic euler angles into quaternion form
634
+
635
+ Args:
636
+ euler (np.array): (r,p,y) angles
637
+
638
+ Returns:
639
+ np.array: (x,y,z,w) float quaternion angles
640
+
641
+ Raises:
642
+ AssertionError: [Invalid input shape]
643
+ """
644
+ return R.from_euler("xyz", euler).as_quat()
645
+
646
+
647
+ def quat2euler(quat):
648
+ """
649
+ Converts extrinsic euler angles into quaternion form
650
+
651
+ Args:
652
+ quat (np.array): (x,y,z,w) float quaternion angles
653
+
654
+ Returns:
655
+ np.array: (r,p,y) angles
656
+
657
+ Raises:
658
+ AssertionError: [Invalid input shape]
659
+ """
660
+ return R.from_quat(quat).as_euler("xyz")
661
+
662
+
663
+ def euler2mat(euler):
664
+ """
665
+ Converts extrinsic euler angles into rotation matrix form
666
+
667
+ Args:
668
+ euler (np.array): (r,p,y) angles
669
+
670
+ Returns:
671
+ np.array: 3x3 rotation matrix
672
+
673
+ Raises:
674
+ AssertionError: [Invalid input shape]
675
+ """
676
+
677
+ euler = np.asarray(euler, dtype=np.float64)
678
+ assert euler.shape[-1] == 3, "Invalid shaped euler {}".format(euler)
679
+
680
+ return R.from_euler("xyz", euler).as_matrix()
681
+
682
+
683
+ def mat2euler(rmat):
684
+ """
685
+ Converts given rotation matrix to extrinsic euler angles in radian.
686
+
687
+ Args:
688
+ rmat (np.array): 3x3 rotation matrix
689
+
690
+ Returns:
691
+ np.array: (r,p,y) converted extrinsic euler angles in radian vec3 float
692
+ """
693
+ M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3]
694
+ return R.from_matrix(M).as_euler("xyz")
695
+
696
+
697
+ @jit(nopython=True, cache=True)
698
+ def pose2mat(pose):
699
+ """
700
+ Converts pose to homogeneous matrix.
701
+
702
+ Args:
703
+ pose (2-tuple): a (pos, orn) tuple where pos is vec3 float cartesian, and
704
+ orn is vec4 float quaternion.
705
+
706
+ Returns:
707
+ np.array: 4x4 homogeneous matrix
708
+ """
709
+ homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
710
+ homo_pose_mat[:3, :3] = _quat2mat(pose[1])
711
+ homo_pose_mat[:3, 3] = pose[0]
712
+ homo_pose_mat[3, 3] = 1.0
713
+ return homo_pose_mat
714
+
715
+
716
+ def quat2axisangle(quat):
717
+ """
718
+ Converts quaternion to axis-angle format.
719
+ Returns a unit vector direction scaled by its angle in radians.
720
+
721
+ Args:
722
+ quat (np.array): (x,y,z,w) vec4 float angles
723
+
724
+ Returns:
725
+ np.array: (ax,ay,az) axis-angle exponential coordinates
726
+ """
727
+ return R.from_quat(quat).as_rotvec()
728
+
729
+
730
+ def axisangle2quat(vec):
731
+ """
732
+ Converts scaled axis-angle to quat.
733
+
734
+ Args:
735
+ vec (np.array): (ax,ay,az) axis-angle exponential coordinates
736
+
737
+ Returns:
738
+ np.array: (x,y,z,w) vec4 float angles
739
+ """
740
+ return R.from_rotvec(vec).as_quat()
741
+
742
+
743
+ def pose_in_A_to_pose_in_B(pose_A, pose_A_in_B):
744
+ """
745
+ Converts a homogenous matrix corresponding to a point C in frame A
746
+ to a homogenous matrix corresponding to the same point C in frame B.
747
+
748
+ Args:
749
+ pose_A (np.array): 4x4 matrix corresponding to the pose of C in frame A
750
+ pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B
751
+
752
+ Returns:
753
+ np.array: 4x4 matrix corresponding to the pose of C in frame B
754
+ """
755
+
756
+ # pose of A in B takes a point in A and transforms it to a point in C.
757
+
758
+ # pose of C in B = pose of A in B * pose of C in A
759
+ # take a point in C, transform it to A, then to B
760
+ # T_B^C = T_A^C * T_B^A
761
+ return pose_A_in_B.dot(pose_A)
762
+
763
+
764
+ def pose_inv(pose_mat):
765
+ if pose_mat.dtype != np.float32:
766
+ pose_mat = pose_mat.astype(np.float32)
767
+ return _pose_inv(pose_mat)
768
+
769
+
770
+ @jit(nopython=True, cache=True)
771
+ def _pose_inv(pose_mat):
772
+ """
773
+ Computes the inverse of a homogeneous matrix corresponding to the pose of some
774
+ frame B in frame A. The inverse is the pose of frame A in frame B.
775
+
776
+ Args:
777
+ pose_mat (np.array): 4x4 matrix for the pose to inverse
778
+
779
+ Returns:
780
+ np.array: 4x4 matrix for the inverse pose
781
+ """
782
+
783
+ # Note, the inverse of a pose matrix is the following
784
+ # [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]
785
+
786
+ # Intuitively, this makes sense.
787
+ # The original pose matrix translates by t, then rotates by R.
788
+ # We just invert the rotation by applying R-1 = R.T, and also translate back.
789
+ # Since we apply translation first before rotation, we need to translate by
790
+ # -t in the original frame, which is -R-1*t in the new frame, and then rotate back by
791
+ # R-1 to align the axis again.
792
+
793
+ pose_inv = np.zeros((4, 4), dtype=np.float32)
794
+ pose_inv[:3, :3] = pose_mat[:3, :3].T
795
+ pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose_mat[:3, 3])
796
+ pose_inv[3, 3] = 1.0
797
+ return pose_inv
798
+
799
+
800
+ def pose_transform(pos1, quat1, pos0, quat0):
801
+ """
802
+ Conducts forward transform from pose (pos0, quat0) to pose (pos1, quat1):
803
+
804
+ pose1 @ pose0, NOT pose0 @ pose1
805
+
806
+ Args:
807
+ pos1 (np.ndarray): (x,y,z) position to transform
808
+ quat1 (np.ndarray): (x,y,z,w) orientation to transform
809
+ pos0 (np.ndarray): (x,y,z) initial position
810
+ quat0 (np.ndarray): (x,y,z,w) initial orientation
811
+
812
+ Returns:
813
+ 2-tuple:
814
+ - (np.array) (x,y,z) position array in cartesian coordinates
815
+ - (np.array) (x,y,z,w) orientation array in quaternion form
816
+ """
817
+ # Get poses
818
+ mat0 = pose2mat((pos0, quat0))
819
+ mat1 = pose2mat((pos1, quat1))
820
+
821
+ # Multiply and convert back to pos, quat
822
+ return mat2pose(mat1 @ mat0)
823
+
824
+
825
+ def invert_pose_transform(pos, quat):
826
+ """
827
+ Inverts a pose transform
828
+
829
+ Args:
830
+ pos (np.ndarray): (x,y,z) position to transform
831
+ quat (np.ndarray): (x,y,z,w) orientation to transform
832
+
833
+ Returns:
834
+ 2-tuple:
835
+ - (np.array) (x,y,z) position array in cartesian coordinates
836
+ - (np.array) (x,y,z,w) orientation array in quaternion form
837
+ """
838
+ # Get pose
839
+ mat = pose2mat((pos, quat))
840
+
841
+ # Invert pose and convert back to pos, quat
842
+ return mat2pose(pose_inv(mat))
843
+
844
+
845
+ def relative_pose_transform(pos1, quat1, pos0, quat0):
846
+ """
847
+ Computes relative forward transform from pose (pos0, quat0) to pose (pos1, quat1), i.e.: solves:
848
+
849
+ pose1 = pose0 @ transform
850
+
851
+ Args:
852
+ pos1 (np.ndarray): (x,y,z) position to transform
853
+ quat1 (np.ndarray): (x,y,z,w) orientation to transform
854
+ pos0 (np.ndarray): (x,y,z) initial position
855
+ quat0 (np.ndarray): (x,y,z,w) initial orientation
856
+
857
+ Returns:
858
+ 2-tuple:
859
+ - (np.array) (x,y,z) position array in cartesian coordinates
860
+ - (np.array) (x,y,z,w) orientation array in quaternion form
861
+ """
862
+ # Get poses
863
+ mat0 = pose2mat((pos0, quat0))
864
+ mat1 = pose2mat((pos1, quat1))
865
+
866
+ # Invert pose0 and calculate transform
867
+ return mat2pose(pose_inv(mat0) @ mat1)
868
+
869
+
870
+ def _skew_symmetric_translation(pos_A_in_B):
871
+ """
872
+ Helper function to get a skew symmetric translation matrix for converting quantities
873
+ between frames.
874
+
875
+ Args:
876
+ pos_A_in_B (np.array): (x,y,z) position of A in frame B
877
+
878
+ Returns:
879
+ np.array: 3x3 skew symmetric translation matrix
880
+ """
881
+ return np.array(
882
+ [
883
+ 0.0,
884
+ -pos_A_in_B[2],
885
+ pos_A_in_B[1],
886
+ pos_A_in_B[2],
887
+ 0.0,
888
+ -pos_A_in_B[0],
889
+ -pos_A_in_B[1],
890
+ pos_A_in_B[0],
891
+ 0.0,
892
+ ]
893
+ ).reshape((3, 3))
894
+
895
+
896
+ def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B):
897
+ """
898
+ Converts linear and angular velocity of a point in frame A to the equivalent in frame B.
899
+
900
+ Args:
901
+ vel_A (np.array): (vx,vy,vz) linear velocity in A
902
+ ang_vel_A (np.array): (wx,wy,wz) angular velocity in A
903
+ pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B
904
+
905
+ Returns:
906
+ 2-tuple:
907
+
908
+ - (np.array) (vx,vy,vz) linear velocities in frame B
909
+ - (np.array) (wx,wy,wz) angular velocities in frame B
910
+ """
911
+ pos_A_in_B = pose_A_in_B[:3, 3]
912
+ rot_A_in_B = pose_A_in_B[:3, :3]
913
+ skew_symm = _skew_symmetric_translation(pos_A_in_B)
914
+ vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A))
915
+ ang_vel_B = rot_A_in_B.dot(ang_vel_A)
916
+ return vel_B, ang_vel_B
917
+
918
+
919
+ def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B):
920
+ """
921
+ Converts linear and rotational force at a point in frame A to the equivalent in frame B.
922
+
923
+ Args:
924
+ force_A (np.array): (fx,fy,fz) linear force in A
925
+ torque_A (np.array): (tx,ty,tz) rotational force (moment) in A
926
+ pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B
927
+
928
+ Returns:
929
+ 2-tuple:
930
+
931
+ - (np.array) (fx,fy,fz) linear forces in frame B
932
+ - (np.array) (tx,ty,tz) moments in frame B
933
+ """
934
+ pos_A_in_B = pose_A_in_B[:3, 3]
935
+ rot_A_in_B = pose_A_in_B[:3, :3]
936
+ skew_symm = _skew_symmetric_translation(pos_A_in_B)
937
+ force_B = rot_A_in_B.T.dot(force_A)
938
+ torque_B = -rot_A_in_B.T.dot(skew_symm.dot(force_A)) + rot_A_in_B.T.dot(torque_A)
939
+ return force_B, torque_B
940
+
941
+
942
+ def rotation_matrix(angle, direction, point=None):
943
+ """
944
+ Returns matrix to rotate about axis defined by point and direction.
945
+
946
+ E.g.:
947
+ >>> angle = (random.random() - 0.5) * (2 * math.pi)
948
+ >>> direc = numpy.random.random(3) - 0.5
949
+ >>> point = numpy.random.random(3) - 0.5
950
+ >>> R0 = rotation_matrix(angle, direc, point)
951
+ >>> R1 = rotation_matrix(angle - 2 * math.pi, direc, point)
952
+ >>> is_same_transform(R0, R1)
953
+ True
954
+
955
+ >>> R0 = rotation_matrix(angle, direc, point)
956
+ >>> R1 = rotation_matrix(-angle, -direc, point)
957
+ >>> is_same_transform(R0, R1)
958
+ True
959
+
960
+ >>> I = numpy.identity(4, numpy.float32)
961
+ >>> numpy.allclose(I, rotation_matrix(math.pi * 2, direc))
962
+ True
963
+
964
+ >>> numpy.allclose(2.0, numpy.trace(rotation_matrix(math.pi / 2, direc, point)))
965
+ True
966
+
967
+ Args:
968
+ angle (float): Magnitude of rotation
969
+ direction (np.array): (ax,ay,az) axis about which to rotate
970
+ point (None or np.array): If specified, is the (x,y,z) point about which the rotation will occur
971
+
972
+ Returns:
973
+ np.array: 4x4 homogeneous matrix that includes the desired rotation
974
+ """
975
+ sina = math.sin(angle)
976
+ cosa = math.cos(angle)
977
+ direction = unit_vector(direction[:3])
978
+ # rotation matrix around unit vector
979
+ R = np.array(((cosa, 0.0, 0.0), (0.0, cosa, 0.0), (0.0, 0.0, cosa)), dtype=np.float32)
980
+ R += np.outer(direction, direction) * (1.0 - cosa)
981
+ direction *= sina
982
+ R += np.array(
983
+ (
984
+ (0.0, -direction[2], direction[1]),
985
+ (direction[2], 0.0, -direction[0]),
986
+ (-direction[1], direction[0], 0.0),
987
+ ),
988
+ dtype=np.float32,
989
+ )
990
+ M = np.identity(4)
991
+ M[:3, :3] = R
992
+ if point is not None:
993
+ # rotation not around origin
994
+ point = np.array(point[:3], dtype=np.float32, copy=False)
995
+ M[:3, 3] = point - np.dot(R, point)
996
+ return M
997
+
998
+
999
+ def transformation_matrix(angle, direction, point=None):
1000
+ """
1001
+ Returns a 4x4 homogeneous transformation matrix to rotate about axis defined by point and direction.
1002
+ Args:
1003
+ angle (float): Magnitude of rotation in radians
1004
+ direction (np.array): (ax,ay,az) axis about which to rotate
1005
+ point (bool): If specified, is the (x,y,z) point about which the rotation will occur
1006
+
1007
+ Returns:
1008
+ np.array: 4x4 homogeneous transformation matrix
1009
+ """
1010
+ R = rotation_matrix(angle, direction)
1011
+
1012
+ M = np.eye(4)
1013
+ M[:3, :3] = R
1014
+
1015
+ if point is not None:
1016
+ # Rotation not about origin
1017
+ M[:3, 3] = point - R @ point
1018
+ return M
1019
+
1020
+
1021
+ def clip_translation(dpos, limit):
1022
+ """
1023
+ Limits a translation (delta position) to a specified limit
1024
+
1025
+ Scales down the norm of the dpos to 'limit' if norm(dpos) > limit, else returns immediately
1026
+
1027
+ Args:
1028
+ dpos (n-array): n-dim Translation being clipped (e,g.: (x, y, z)) -- numpy array
1029
+ limit (float): Value to limit translation by -- magnitude (scalar, in same units as input)
1030
+
1031
+ Returns:
1032
+ 2-tuple:
1033
+
1034
+ - (np.array) Clipped translation (same dimension as inputs)
1035
+ - (bool) whether the value was clipped or not
1036
+ """
1037
+ input_norm = np.linalg.norm(dpos)
1038
+ return (dpos * limit / input_norm, True) if input_norm > limit else (dpos, False)
1039
+
1040
+
1041
+ def clip_rotation(quat, limit):
1042
+ """
1043
+ Limits a (delta) rotation to a specified limit
1044
+
1045
+ Converts rotation to axis-angle, clips, then re-converts back into quaternion
1046
+
1047
+ Args:
1048
+ quat (np.array): (x,y,z,w) rotation being clipped
1049
+ limit (float): Value to limit rotation by -- magnitude (scalar, in radians)
1050
+
1051
+ Returns:
1052
+ 2-tuple:
1053
+
1054
+ - (np.array) Clipped rotation quaternion (x, y, z, w)
1055
+ - (bool) whether the value was clipped or not
1056
+ """
1057
+ clipped = False
1058
+
1059
+ # First, normalize the quaternion
1060
+ quat = quat / np.linalg.norm(quat)
1061
+
1062
+ den = np.sqrt(max(1 - quat[3] * quat[3], 0))
1063
+ if den == 0:
1064
+ # This is a zero degree rotation, immediately return
1065
+ return quat, clipped
1066
+ else:
1067
+ # This is all other cases
1068
+ x = quat[0] / den
1069
+ y = quat[1] / den
1070
+ z = quat[2] / den
1071
+ a = 2 * math.acos(quat[3])
1072
+
1073
+ # Clip rotation if necessary and return clipped quat
1074
+ if abs(a) > limit:
1075
+ a = limit * np.sign(a) / 2
1076
+ sa = math.sin(a)
1077
+ ca = math.cos(a)
1078
+ quat = np.array([x * sa, y * sa, z * sa, ca])
1079
+ clipped = True
1080
+
1081
+ return quat, clipped
1082
+
1083
+
1084
+ def make_pose(translation, rotation):
1085
+ """
1086
+ Makes a homogeneous pose matrix from a translation vector and a rotation matrix.
1087
+
1088
+ Args:
1089
+ translation (np.array): (x,y,z) translation value
1090
+ rotation (np.array): a 3x3 matrix representing rotation
1091
+
1092
+ Returns:
1093
+ pose (np.array): a 4x4 homogeneous matrix
1094
+ """
1095
+ pose = np.zeros((4, 4))
1096
+ pose[:3, :3] = rotation
1097
+ pose[:3, 3] = translation
1098
+ pose[3, 3] = 1.0
1099
+ return pose
1100
+
1101
+
1102
+ def get_orientation_error(target_orn, current_orn):
1103
+ """
1104
+ Returns the difference between two quaternion orientations as a 3 DOF numpy array.
1105
+ For use in an impedance controller / task-space PD controller.
1106
+
1107
+ Args:
1108
+ target_orn (np.array): (x, y, z, w) desired quaternion orientation
1109
+ current_orn (np.array): (x, y, z, w) current quaternion orientation
1110
+
1111
+ Returns:
1112
+ orn_error (np.array): (ax,ay,az) current orientation error, corresponds to
1113
+ (target_orn - current_orn)
1114
+ """
1115
+ current_orn = np.array([current_orn[3], current_orn[0], current_orn[1], current_orn[2]])
1116
+ target_orn = np.array([target_orn[3], target_orn[0], target_orn[1], target_orn[2]])
1117
+
1118
+ pinv = np.zeros((3, 4))
1119
+ pinv[0, :] = [-current_orn[1], current_orn[0], -current_orn[3], current_orn[2]]
1120
+ pinv[1, :] = [-current_orn[2], current_orn[3], current_orn[0], -current_orn[1]]
1121
+ pinv[2, :] = [-current_orn[3], -current_orn[2], current_orn[1], current_orn[0]]
1122
+ orn_error = 2.0 * pinv.dot(np.array(target_orn))
1123
+ return orn_error
1124
+
1125
+
1126
+ def get_orientation_diff_in_radian(orn0, orn1):
1127
+ """
1128
+ Returns the difference between two quaternion orientations in radian
1129
+
1130
+ Args:
1131
+ orn0 (np.array): (x, y, z, w)
1132
+ orn1 (np.array): (x, y, z, w)
1133
+
1134
+ Returns:
1135
+ orn_diff (float): orientation difference in radian
1136
+ """
1137
+ vec0 = quat2axisangle(orn0)
1138
+ vec0 /= np.linalg.norm(vec0)
1139
+ vec1 = quat2axisangle(orn1)
1140
+ vec1 /= np.linalg.norm(vec1)
1141
+ return np.arccos(np.dot(vec0, vec1))
1142
+
1143
+
1144
+ def get_pose_error(target_pose, current_pose):
1145
+ """
1146
+ Computes the error corresponding to target pose - current pose as a 6-dim vector.
1147
+ The first 3 components correspond to translational error while the last 3 components
1148
+ correspond to the rotational error.
1149
+
1150
+ Args:
1151
+ target_pose (np.array): a 4x4 homogenous matrix for the target pose
1152
+ current_pose (np.array): a 4x4 homogenous matrix for the current pose
1153
+
1154
+ Returns:
1155
+ np.array: 6-dim pose error.
1156
+ """
1157
+ error = np.zeros(6)
1158
+
1159
+ # compute translational error
1160
+ target_pos = target_pose[:3, 3]
1161
+ current_pos = current_pose[:3, 3]
1162
+ pos_err = target_pos - current_pos
1163
+
1164
+ # compute rotational error
1165
+ r1 = current_pose[:3, 0]
1166
+ r2 = current_pose[:3, 1]
1167
+ r3 = current_pose[:3, 2]
1168
+ r1d = target_pose[:3, 0]
1169
+ r2d = target_pose[:3, 1]
1170
+ r3d = target_pose[:3, 2]
1171
+ rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d))
1172
+
1173
+ error[:3] = pos_err
1174
+ error[3:] = rot_err
1175
+ return error
1176
+
1177
+
1178
+ def matrix_inverse(matrix):
1179
+ """
1180
+ Helper function to have an efficient matrix inversion function.
1181
+
1182
+ Args:
1183
+ matrix (np.array): 2d-array representing a matrix
1184
+
1185
+ Returns:
1186
+ np.array: 2d-array representing the matrix inverse
1187
+ """
1188
+ return np.linalg.inv(matrix)
1189
+
1190
+
1191
+ def vecs2axisangle(vec0, vec1):
1192
+ """
1193
+ Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into an axis-angle representation of the angle
1194
+
1195
+ Args:
1196
+ vec0 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1197
+ vec1 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1198
+ """
1199
+ # Normalize vectors
1200
+ vec0 = normalize(vec0, axis=-1)
1201
+ vec1 = normalize(vec1, axis=-1)
1202
+
1203
+ # Get cross product for direction of angle, and multiply by arcos of the dot product which is the angle
1204
+ return np.cross(vec0, vec1) * np.arccos((vec0 * vec1).sum(-1, keepdims=True))
1205
+
1206
+
1207
+ def vecs2quat(vec0, vec1, normalized=False):
1208
+ """
1209
+ Converts the angle from unnormalized 3D vectors @vec0 to @vec1 into a quaternion representation of the angle
1210
+
1211
+ Args:
1212
+ vec0 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1213
+ vec1 (np.array): (..., 3) (x,y,z) 3D vector, possibly unnormalized
1214
+ normalized (bool): If True, @vec0 and @vec1 are assumed to already be normalized and we will skip the
1215
+ normalization step (more efficient)
1216
+ """
1217
+ # Normalize vectors if requested
1218
+ if not normalized:
1219
+ vec0 = normalize(vec0, axis=-1)
1220
+ vec1 = normalize(vec1, axis=-1)
1221
+
1222
+ # Half-way Quaternion Solution -- see https://stackoverflow.com/a/11741520
1223
+ cos_theta = np.sum(vec0 * vec1, axis=-1, keepdims=True)
1224
+ quat_unnormalized = np.where(
1225
+ cos_theta == -1, np.array([1.0, 0, 0, 0]), np.concatenate([np.cross(vec0, vec1), 1 + cos_theta], axis=-1)
1226
+ )
1227
+ return quat_unnormalized / np.linalg.norm(quat_unnormalized, axis=-1, keepdims=True)
1228
+
1229
+
1230
+ def align_vector_sets(vec_set1, vec_set2):
1231
+ """
1232
+ Computes a single quaternion representing the rotation that best aligns vec_set1 to vec_set2.
1233
+
1234
+ Args:
1235
+ vec_set1 (np.array): (N, 3) tensor of N 3D vectors
1236
+ vec_set2 (np.array): (N, 3) tensor of N 3D vectors
1237
+
1238
+ Returns:
1239
+ np.array: (4,) Normalized quaternion representing the overall rotation
1240
+ """
1241
+ rot, _ = R.align_vectors(vec_set1, vec_set2)
1242
+ return rot.as_quat()
1243
+
1244
+
1245
+ def l2_distance(v1, v2):
1246
+ """Returns the L2 distance between vector v1 and v2."""
1247
+ return np.linalg.norm(np.array(v1) - np.array(v2))
1248
+
1249
+
1250
+ def cartesian_to_polar(x, y):
1251
+ """Convert cartesian coordinate to polar coordinate"""
1252
+ rho = np.sqrt(x**2 + y**2)
1253
+ phi = np.arctan2(y, x)
1254
+ return rho, phi
1255
+
1256
+
1257
+ def deg2rad(deg):
1258
+ return deg * np.pi / 180.0
1259
+
1260
+
1261
+ def rad2deg(rad):
1262
+ return rad * 180.0 / np.pi
1263
+
1264
+
1265
+ def check_quat_right_angle(quat, atol=5e-2):
1266
+ """
1267
+ Check by making sure the quaternion is some permutation of +/- (1, 0, 0, 0),
1268
+ +/- (0.707, 0.707, 0, 0), or +/- (0.5, 0.5, 0.5, 0.5)
1269
+ Because orientations are all normalized (same L2-norm), every orientation should have a unique L1-norm
1270
+ So we check the L1-norm of the absolute value of the orientation as a proxy for verifying these values
1271
+
1272
+ Args:
1273
+ quat (4-array): (x,y,z,w) quaternion orientation to check
1274
+ atol (float): Absolute tolerance permitted
1275
+
1276
+ Returns:
1277
+ bool: Whether the quaternion is a right angle or not
1278
+ """
1279
+ return np.any(np.isclose(np.abs(quat).sum(), np.array([1.0, 1.414, 2.0]), atol=atol))
1280
+
1281
+
1282
+ def z_angle_from_quat(quat):
1283
+ """Get the angle around the Z axis produced by the quaternion."""
1284
+ rotated_X_axis = R.from_quat(quat).apply([1, 0, 0])
1285
+ return np.arctan2(rotated_X_axis[1], rotated_X_axis[0])
1286
+
1287
+
1288
+ def integer_spiral_coordinates(n):
1289
+ """A function to map integers to 2D coordinates in a spiral pattern around the origin."""
1290
+ # Map integers from Z to Z^2 in a spiral pattern around the origin.
1291
+ # Sources:
1292
+ # https://www.reddit.com/r/askmath/comments/18vqorf/find_the_nth_coordinate_of_a_square_spiral/
1293
+ # https://oeis.org/A174344
1294
+ m = np.floor(np.sqrt(n))
1295
+ x = ((-1) ** m) * ((n - m * (m + 1)) * (np.floor(2 * np.sqrt(n)) % 2) - np.ceil(m / 2))
1296
+ y = ((-1) ** (m + 1)) * ((n - m * (m + 1)) * (np.floor(2 * np.sqrt(n) + 1) % 2) + np.ceil(m / 2))
1297
+ return int(x), int(y)
1298
+
1299
+
1300
+ @jit(nopython=True, cache=True)
1301
+ def transform_points(points, matrix, translate=True):
1302
+ """
1303
+ Returns points rotated by a homogeneous
1304
+ transformation matrix.
1305
+ If points are (n, 2) matrix must be (3, 3)
1306
+ If points are (n, 3) matrix must be (4, 4)
1307
+
1308
+ Arguments:
1309
+ points (np.array): (n, dim) where `dim` is 2 or 3.
1310
+ matrix (np.array): (3, 3) or (4, 4) homogeneous rotation matrix.
1311
+ translate (bool): whether to apply translation from matrix or not.
1312
+
1313
+ Returns:
1314
+ np.array: (n, dim) transformed points.
1315
+ """
1316
+ if len(points) == 0 or matrix is None:
1317
+ return points.copy()
1318
+
1319
+ count, dim = points.shape
1320
+ # Check if the matrix is close to an identity matrix
1321
+ identity = np.eye(dim + 1)
1322
+ if np.abs(matrix - identity[: dim + 1, : dim + 1]).max() < 1e-8:
1323
+ return points.copy()
1324
+
1325
+ if translate:
1326
+ stack = np.ascontiguousarray(np.concatenate((points, np.ones((count, 1))), axis=1))
1327
+ return (matrix @ stack.T).T[:, :dim]
1328
+ else:
1329
+ return (matrix[:dim, :dim] @ points.T).T
1330
+
1331
+
1332
+ def quaternions_close(q1, q2, atol=1e-3):
1333
+ """
1334
+ Whether two quaternions represent the same rotation,
1335
+ allowing for the possibility that one is the negative of the other.
1336
+
1337
+ Arguments:
1338
+ q1 (np.array): First quaternion
1339
+ q2 (np.array): Second quaternion
1340
+ atol (float): Absolute tolerance for comparison
1341
+
1342
+ Returns:
1343
+ bool: Whether the quaternions are close
1344
+ """
1345
+ return np.allclose(q1, q2, atol=atol) or np.allclose(q1, -q2, atol=atol)
1346
+
1347
+
1348
+ @jit(nopython=True, cache=True)
1349
+ def orientation_error(desired, current):
1350
+ """
1351
+ This function calculates a 3-dimensional orientation error vector for use in the
1352
+ impedance controller. It does this by computing the delta rotation between the
1353
+ inputs and converting that rotation to exponential coordinates (axis-angle
1354
+ representation, where the 3d vector is axis * angle).
1355
+ See https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation for more information.
1356
+ Optimized function to determine orientation error from matrices
1357
+
1358
+ Args:
1359
+ desired (tensor): (..., 3, 3) where final two dims are 2d array representing target orientation matrix
1360
+ current (tensor): (..., 3, 3) where final two dims are 2d array representing current orientation matrix
1361
+ Returns:
1362
+ tensor: (..., 3) where final dim is (ax, ay, az) axis-angle representing orientation error
1363
+ """
1364
+ # convert input shapes
1365
+ input_shape = desired.shape[:-2]
1366
+ desired = desired.reshape(-1, 3, 3)
1367
+ current = current.reshape(-1, 3, 3)
1368
+
1369
+ # grab relevant info
1370
+ rc1 = current[:, :, 0]
1371
+ rc2 = current[:, :, 1]
1372
+ rc3 = current[:, :, 2]
1373
+ rd1 = desired[:, :, 0]
1374
+ rd2 = desired[:, :, 1]
1375
+ rd3 = desired[:, :, 2]
1376
+
1377
+ error = 0.5 * (np.cross(rc1, rd1) + np.cross(rc2, rd2) + np.cross(rc3, rd3))
1378
+
1379
+ # Reshape
1380
+ error = error.reshape(*input_shape, 3)
1381
+
1382
+ return error
1383
+
1384
+
1385
+ def delta_rotation_matrix(omega, delta_t):
1386
+ """
1387
+ Compute the delta rotation matrix given angular velocity and time elapsed.
1388
+
1389
+ Arguments:
1390
+ omega (np.array): Angular velocity vector [omega_x, omega_y, omega_z].
1391
+ delta_t (float): Time elapsed.
1392
+
1393
+ Returns:
1394
+ np.array: 3x3 Delta rotation matrix.
1395
+ """
1396
+ # Magnitude of angular velocity (angular speed)
1397
+ omega_magnitude = np.linalg.norm(omega)
1398
+
1399
+ # If angular speed is zero, return identity matrix
1400
+ if omega_magnitude == 0:
1401
+ return np.eye(3)
1402
+
1403
+ # Rotation angle
1404
+ theta = omega_magnitude * delta_t
1405
+
1406
+ # Normalized axis of rotation
1407
+ axis = omega / omega_magnitude
1408
+
1409
+ # Skew-symmetric matrix K
1410
+ u_x, u_y, u_z = axis
1411
+ K = np.array([[0, -u_z, u_y], [u_z, 0, -u_x], [-u_y, u_x, 0]])
1412
+
1413
+ # Rodrigues' rotation formula
1414
+ R = np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K)
1415
+
1416
+ return R
1417
+
1418
+
1419
+ def mat2euler_intrinsic(rmat):
1420
+ """
1421
+ Converts given rotation matrix to intrinsic euler angles in radian.
1422
+
1423
+ Parameters:
1424
+ rmat (np.array): 3x3 rotation matrix
1425
+
1426
+ Returns:
1427
+ np.array: (r,p,y) converted intrinsic euler angles in radian vec3 float
1428
+ """
1429
+ return R.from_matrix(rmat).as_euler("XYZ")
1430
+
1431
+
1432
+ def euler_intrinsic2mat(euler):
1433
+ """
1434
+ Converts intrinsic euler angles into rotation matrix form
1435
+
1436
+ Parameters:
1437
+ euler (np.array): (r,p,y) angles
1438
+
1439
+ Returns:
1440
+ np.array: 3x3 rotation matrix
1441
+ """
1442
+ return R.from_euler("XYZ", euler).as_matrix()
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/ui_utils.py ADDED
@@ -0,0 +1,1171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper classes and functions for streamlining user interactions
3
+ """
4
+
5
+ import contextlib
6
+ import datetime
7
+ import logging
8
+ import math
9
+ import random
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import imageio
14
+ import matplotlib.path as mpath
15
+ import torch as th
16
+ from IPython import embed
17
+ from matplotlib.text import TextPath
18
+ from PIL import Image
19
+ from scipy.integrate import quad
20
+ from scipy.interpolate import CubicSpline
21
+ from scipy.spatial.transform import Rotation as R
22
+ from termcolor import colored
23
+
24
+ import omnigibson as og
25
+ import omnigibson.lazy as lazy
26
+ import omnigibson.utils.transform_utils as T
27
+ from omnigibson.macros import gm
28
+ from omnigibson.controllers import ControllerView
29
+
30
+
31
+ def print_icon():
32
+ raw_texts = [
33
+ # Lgrey, grey, lgrey, grey, red, lgrey, red
34
+ (" ___________", "", "", "", "", "", "_"),
35
+ (" / ", "", "", "", "", "", "/ \\"),
36
+ (" / ", "", "", "", "/ /", "__", ""),
37
+ (" / ", "", "", "", "", "", "/ / /\\"),
38
+ (" /", "__________", "", "", "/ /", "__", "/ \\"),
39
+ (" ", "\\ _____ ", "", "", "\\ \\", "__", "\\ /"),
40
+ (" ", "\\ \\ ", "/ ", "\\ ", "", "", "\\ \\_/ /"),
41
+ (" ", "\\ \\", "/", "___\\ ", "", "", "\\ /"),
42
+ (" ", "\\__________", "", "", "", "", "\\_/ "),
43
+ ]
44
+ for lgrey_text0, grey_text0, lgrey_text1, grey_text1, red_text0, lgrey_text2, red_text1 in raw_texts:
45
+ lgrey_text0 = colored(lgrey_text0, "light_grey", attrs=["bold"])
46
+ grey_text0 = colored(grey_text0, "light_grey", attrs=["bold", "dark"])
47
+ lgrey_text1 = colored(lgrey_text1, "light_grey", attrs=["bold"])
48
+ grey_text1 = colored(grey_text1, "light_grey", attrs=["bold", "dark"])
49
+ red_text0 = colored(red_text0, "light_red", attrs=["bold"])
50
+ lgrey_text2 = colored(lgrey_text2, "light_grey", attrs=["bold"])
51
+ red_text1 = colored(red_text1, "light_red", attrs=["bold"])
52
+ print(lgrey_text0 + grey_text0 + lgrey_text1 + grey_text1 + red_text0 + lgrey_text2 + red_text1)
53
+
54
+
55
+ def print_logo():
56
+ raw_texts = [
57
+ (" ___ _", " ____ _ _ "),
58
+ (r" / _ \ _ __ ___ _ __ (_)", r"/ ___(_) |__ ___ ___ _ __ "),
59
+ (r" | | | | '_ ` _ \| '_ \| |", r" | _| | '_ \/ __|/ _ \| '_ \ "),
60
+ (r" | |_| | | | | | | | | | |", r" |_| | | |_) \__ \ (_) | | | |"),
61
+ (r" \___/|_| |_| |_|_| |_|_|", r"\____|_|_.__/|___/\___/|_| |_|"),
62
+ ]
63
+ for grey_text, red_text in raw_texts:
64
+ grey_text = colored(grey_text, "light_grey", attrs=["bold", "dark"])
65
+ red_text = colored(red_text, "light_red", attrs=["bold"])
66
+ print(grey_text + red_text)
67
+
68
+
69
+ def logo_small():
70
+ grey_text = colored("Omni", "light_grey", attrs=["bold", "dark"])
71
+ red_text = colored("Gibson", "light_red", attrs=["bold"])
72
+ return grey_text + red_text
73
+
74
+
75
+ def dock_window(space, name, location, ratio=0.5):
76
+ """
77
+ Method for docking a specific GUI window in a specified location within the workspace
78
+
79
+ Args:
80
+ space (WindowHandle): Handle to the docking space to dock the window specified by @name
81
+ name (str): Name of a window to dock
82
+ location (omni.ui.DockPosition): docking position for placing the window specified by @name
83
+ ratio (float): Ratio when splitting the docking space between the pre-existing and newly added window
84
+
85
+ Returns:
86
+ WindowHandle: Handle to the docking space that the window specified by @name was placed in
87
+ """
88
+ window = lazy.omni.ui.Workspace.get_window(name)
89
+ if window and space:
90
+ window.dock_in(space, location, ratio=ratio)
91
+ return window
92
+
93
+
94
+ class KeyboardEventHandler:
95
+ """
96
+ Simple singleton class for handing keyboard events
97
+ """
98
+
99
+ # Global keyboard callbacks
100
+ KEYBOARD_CALLBACKS = dict()
101
+
102
+ # ID assigned to meta callback method for this class
103
+ _CALLBACK_ID = None
104
+
105
+ def __init__(self):
106
+ raise ValueError("Cannot create an instance of keyboard event handler!")
107
+
108
+ @classmethod
109
+ def initialize(cls):
110
+ """
111
+ Hook up a meta function callback to the omni backend
112
+ """
113
+ appwindow = lazy.omni.appwindow.get_default_app_window()
114
+ input_interface = lazy.carb.input.acquire_input_interface()
115
+ keyboard = appwindow.get_keyboard()
116
+ cls._CALLBACK_ID = input_interface.subscribe_to_keyboard_events(keyboard, cls._meta_callback)
117
+
118
+ @classmethod
119
+ def reset(cls):
120
+ """
121
+ Resets this callback interface by removing all current callback functions
122
+ """
123
+ appwindow = lazy.omni.appwindow.get_default_app_window()
124
+ input_interface = lazy.carb.input.acquire_input_interface()
125
+ keyboard = appwindow.get_keyboard()
126
+ input_interface.unsubscribe_to_keyboard_events(keyboard, cls._CALLBACK_ID)
127
+ cls.KEYBOARD_CALLBACKS = dict()
128
+ cls._CALLBACK_ID = None
129
+
130
+ @classmethod
131
+ def add_keyboard_callback(cls, key, callback_fn):
132
+ """
133
+ Registers a keyboard callback function with omni, mapping a keypress from @key to run the callback_function
134
+ @callback_fn
135
+
136
+ Args:
137
+ key (carb.input.KeyboardInput): key to associate with the callback
138
+ callback_fn (function): Callback function to call if the key @key is pressed or repeated. Note that this
139
+ function's signature should be:
140
+
141
+ callback_fn() --> None
142
+ """
143
+ # Initialize the interface if not initialized yet
144
+ if cls._CALLBACK_ID is None:
145
+ cls.initialize()
146
+ # Add the callback
147
+ cls.KEYBOARD_CALLBACKS[key] = callback_fn
148
+
149
+ @classmethod
150
+ def _meta_callback(cls, event, *args, **kwargs):
151
+ """
152
+ Meta callback function that is hooked up to omni's backend
153
+ """
154
+ # Check if we've received a key press or repeat
155
+ if (
156
+ event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS
157
+ or event.type == lazy.carb.input.KeyboardEventType.KEY_REPEAT
158
+ ):
159
+ # Run the specific callback
160
+ cls.KEYBOARD_CALLBACKS.get(event.input, lambda: None)()
161
+
162
+ # Always return True
163
+ return True
164
+
165
+ @classmethod
166
+ def xr_callback(cls, controller, button):
167
+ """
168
+ Meta callback function that is hooked up to omni's backend
169
+ """
170
+ # Check if we've received a key press or repeat
171
+ cls.KEYBOARD_CALLBACKS.get(f"{controller}_{button}", lambda: None)()
172
+
173
+
174
+ @contextlib.contextmanager
175
+ def suppress_omni_log(channels):
176
+ """
177
+ A context scope for temporarily suppressing logging for certain omni channels.
178
+
179
+ Args:
180
+ channels (None or list of str): Logging channel(s) to suppress. If None, will globally disable logger
181
+ """
182
+ # Record the state to restore to after the context exists
183
+ log = lazy.omni.log.get_log()
184
+
185
+ if gm.DEBUG:
186
+ # Do nothing
187
+ pass
188
+ elif channels is None:
189
+ # Globally disable log
190
+ log.enabled = False
191
+ else:
192
+ # For some reason, all enabled states always return False even if the logging is clearly enabled for the
193
+ # given channel, so we assume all channels are enabled
194
+ # We do, however, check what behavior was assigned to this channel, since we force an override during this context
195
+ channel_behavior = {channel: log.get_channel_enabled(channel)[2] for channel in channels}
196
+
197
+ # Suppress the channels
198
+ for channel in channels:
199
+ log.set_channel_enabled(channel, False, lazy.omni.log.SettingBehavior.OVERRIDE)
200
+
201
+ yield
202
+
203
+ if gm.DEBUG:
204
+ # Do nothing
205
+ pass
206
+ elif channels is None:
207
+ # Globally re-enable log
208
+ log.enabled = True
209
+ else:
210
+ # Unsuppress the channels
211
+ for channel in channels:
212
+ log.set_channel_enabled(channel, True, channel_behavior[channel])
213
+
214
+
215
+ @contextlib.contextmanager
216
+ def suppress_loggers(logger_names):
217
+ """
218
+ A context scope for temporarily suppressing logging for certain omni channels.
219
+
220
+ Args:
221
+ logger_names (list of str): Logger name(s) whose corresponding loggers should be suppressed
222
+ """
223
+ if not gm.DEBUG:
224
+ # Store prior states so we can restore them after this context exits
225
+ logger_levels = {name: logging.getLogger(name).getEffectiveLevel() for name in logger_names}
226
+
227
+ # Suppress the loggers (only output fatal messages)
228
+ for name in logger_names:
229
+ logging.getLogger(name).setLevel(logging.FATAL)
230
+
231
+ yield
232
+
233
+ if not gm.DEBUG:
234
+ # Unsuppress the loggers
235
+ for name in logger_names:
236
+ logging.getLogger(name).setLevel(logger_levels[name])
237
+
238
+
239
+ def create_module_logger(module_name):
240
+ """
241
+ Creates and returns a logger for logging statements from the module represented by @module_name
242
+
243
+ Args:
244
+ module_name (str): Module to create the logger for. Should be the module's `__name__` variable
245
+
246
+ Returns:
247
+ Logger: Created logger for the module
248
+ """
249
+ return logging.getLogger(module_name)
250
+
251
+
252
+ def disclaimer(msg):
253
+ """
254
+ 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
255
+ next release!
256
+ """
257
+ if gm.SHOW_DISCLAIMERS:
258
+ print("****** DISCLAIMER ******")
259
+ print("Isaac Sim / Omniverse has some significant limitations and bugs in its current release.")
260
+ print(
261
+ "This message has popped up because a potential feature in OmniGibson relies upon a feature in Omniverse that "
262
+ "is yet to be released publically. Currently, the expected behavior may not be fully functional, but "
263
+ "should be resolved by the next Isaac Sim release."
264
+ )
265
+ print(f"Exact Limitation: {msg}")
266
+ print("************************")
267
+
268
+
269
+ def debug_breakpoint(msg):
270
+ og.log.error(msg)
271
+ embed()
272
+
273
+
274
+ def choose_from_options(options, name, random_selection=False, selected_option=None):
275
+ """
276
+ Prints out options from a list, and returns the requested option.
277
+
278
+ Args:
279
+ options (dict or list): options to choose from. If dict, the value entries are assumed to be docstrings
280
+ explaining the individual options
281
+ name (str): name of the options
282
+ random_selection (bool): if the selection is random (for automatic demo execution). Default False
283
+ selected_option (str or None): if specified, directly return this option without prompting. Default None
284
+
285
+ Returns:
286
+ str: Requested option
287
+ """
288
+ # Select robot
289
+ print("\nHere is a list of available {}s:\n".format(name))
290
+
291
+ for k, option in enumerate(options):
292
+ docstring = ": {}".format(options[option]) if isinstance(options, dict) else ""
293
+ print("[{}] {}{}".format(k + 1, option, docstring))
294
+ print()
295
+
296
+ if selected_option is not None:
297
+ assert selected_option in options, "selected_option '{}' is not a valid {}.".format(selected_option, name)
298
+ return selected_option
299
+ elif not random_selection:
300
+ try:
301
+ s = input("Choose a {} (enter a number from 1 to {}): ".format(name, len(options)))
302
+ # parse input into a number within range
303
+ k = min(max(int(s), 1), len(options)) - 1
304
+ except ValueError:
305
+ k = 0
306
+ print("Input is not valid. Use {} by default.".format(list(options)[k]))
307
+ else:
308
+ if "pytest" in sys.modules:
309
+ local_rng = random.Random(0)
310
+ k = local_rng.choice(range(len(options)))
311
+ else:
312
+ k = random.choice(range(len(options)))
313
+ print("Choosing {}: {} randomly".format(k, list(options)[k]))
314
+
315
+ # Return requested option
316
+ return list(options)[k]
317
+
318
+
319
+ class CameraMover:
320
+ """
321
+ A helper class for manipulating a camera via the keyboard. Utilizes carb keyboard callbacks to move
322
+ the camera around.
323
+
324
+ Args:
325
+ cam (VisionSensor): The camera vision sensor to manipulate via the keyboard
326
+ delta (float): Change (m) per keypress when moving the camera
327
+ save_dir (str): Absolute path to where recorded images should be stored. Default is <OMNIGIBSON_PATH>/imgs
328
+ """
329
+
330
+ def __init__(self, cam, delta=0.25, save_dir=None):
331
+ if save_dir is None:
332
+ save_dir = f"{og.root_path}/../images"
333
+
334
+ self.cam = cam
335
+ self.delta = delta
336
+ self.light_val = gm.FORCE_LIGHT_INTENSITY
337
+ self.save_dir = save_dir
338
+
339
+ self._appwindow = lazy.omni.appwindow.get_default_app_window()
340
+ self._input = lazy.carb.input.acquire_input_interface()
341
+ self._keyboard = self._appwindow.get_keyboard()
342
+ self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event)
343
+
344
+ def clear(self):
345
+ """
346
+ Clears this camera mover. After this is called, the camera mover cannot be used.
347
+ """
348
+ self._input.unsubscribe_to_keyboard_events(self._keyboard, self._sub_keyboard)
349
+
350
+ def set_save_dir(self, save_dir):
351
+ """
352
+ Sets the absolute path corresponding to the image directory where recorded images from this CameraMover
353
+ should be saved
354
+
355
+ Args:
356
+ save_dir (str): Absolute path to where recorded images should be stored
357
+ """
358
+ self.save_dir = save_dir
359
+
360
+ def change_light(self, delta):
361
+ self.light_val += delta
362
+ self.set_lights(self.light_val)
363
+
364
+ def set_lights(self, intensity):
365
+ world = lazy.isaacsim.core.utils.prims.get_prim_at_path("/World")
366
+ for prim in world.GetChildren():
367
+ for prim_child in prim.GetChildren():
368
+ for prim_child_child in prim_child.GetChildren():
369
+ if "Light" in prim_child_child.GetPrimTypeInfo().GetTypeName():
370
+ prim_child_child.GetAttribute("inputs:intensity").Set(intensity)
371
+
372
+ def print_info(self):
373
+ """
374
+ Prints keyboard command info out to the user
375
+ """
376
+ print("*" * 40)
377
+ print("CameraMover! Commands:")
378
+ print()
379
+ print("\t Right Click + Drag: Rotate camera")
380
+ print("\t W / S : Move camera forward / backward")
381
+ print("\t A / D : Move camera left / right")
382
+ print("\t T / G : Move camera up / down")
383
+ print("\t 9 / 0 : Increase / decrease the lights")
384
+ print("\t P : Print current camera pose")
385
+ print("\t O: Save the current camera view as an image")
386
+
387
+ def print_cam_pose(self):
388
+ """
389
+ Prints out the camera pose as (position, quaternion) in the world frame
390
+ """
391
+ print(f"cam pose: {self.cam.get_position_orientation()}")
392
+
393
+ def get_image(self):
394
+ """
395
+ Helper function for quickly grabbing the currently viewed RGB image
396
+
397
+ Returns:
398
+ th.tensor: (H, W, 3) sized RGB image array
399
+ """
400
+ return self.cam.get_obs()[0]["rgb"][:, :, :-1]
401
+
402
+ def record_image(self, fpath=None):
403
+ """
404
+ Saves the currently viewed image and writes it to disk
405
+
406
+ Args:
407
+ fpath (None or str): If specified, the absolute fpath to the image save location. Default is located in
408
+ self.save_dir
409
+ """
410
+ og.log.info("Recording image...")
411
+
412
+ # Use default fpath if not specified
413
+ if fpath is None:
414
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
415
+ fpath = f"{self.save_dir}/og_{timestamp}.png"
416
+
417
+ # Make sure save path directory exists, and then save the image to that location
418
+ Path(Path(fpath).parent).mkdir(parents=True, exist_ok=True)
419
+ Image.fromarray(self.get_image().cpu().numpy()).save(fpath)
420
+ og.log.info(f"Saved current viewer camera image to {fpath}.")
421
+
422
+ def record_trajectory(self, poses, fps, steps_per_frame=1, fpath=None):
423
+ """
424
+ Moves the viewer camera through the poses specified by @poses and records the resulting trajectory to an mp4
425
+ video file on disk.
426
+
427
+ Args:
428
+ poses (list of 2-tuple): List of global (position, quaternion) values to set the viewer camera to defining
429
+ this trajectory
430
+ fps (int): Frames per second when recording this video
431
+ steps_per_frame (int): How many sim steps should occur between each frame being recorded. Minimum and
432
+ default is 1.
433
+ fpath (None or str): If specified, the absolute fpath to the video save location. Default is located in
434
+ self.save_dir
435
+ """
436
+ og.log.info("Recording trajectory...")
437
+
438
+ # Use default fpath if not specified
439
+ if fpath is None:
440
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
441
+ fpath = f"{self.save_dir}/og_{timestamp}.mp4"
442
+
443
+ # Make sure save path directory exists, and then create the video writer
444
+ Path(Path(fpath).parent).mkdir(parents=True, exist_ok=True)
445
+ video_writer = imageio.get_writer(fpath, fps=fps)
446
+
447
+ # Iterate through all desired poses, and record the trajectory
448
+ for i, (pos, quat) in enumerate(poses):
449
+ self.cam.set_position_orientation(position=pos, orientation=quat)
450
+ og.sim.step()
451
+ if i % steps_per_frame == 0:
452
+ video_writer.append_data(self.get_image().cpu().numpy())
453
+
454
+ # Close writer
455
+ video_writer.close()
456
+ og.log.info(f"Saved camera trajectory video to {fpath}.")
457
+
458
+ def record_trajectory_from_waypoints(self, waypoints, per_step_distance, fps, steps_per_frame=1, fpath=None):
459
+ """
460
+ Moves the viewer camera through the waypoints specified by @waypoints and records the resulting trajectory to
461
+ an mp4 video file on disk.
462
+
463
+ Args:
464
+ waypoints (th.tensor): (n, 3) global position waypoint values to set the viewer camera to defining this trajectory
465
+ per_step_distance (float): How much distance (in m) should be approximately covered per trajectory step.
466
+ This will determine the path length between individual waypoints
467
+ fps (int): Frames per second when recording this video
468
+ steps_per_frame (int): How many sim steps should occur between each frame being recorded. Minimum and
469
+ default is 1.
470
+ fpath (None or str): If specified, the absolute fpath to the video save location. Default is located in
471
+ self.save_dir
472
+ """
473
+ # Create splines and their derivatives
474
+ n_waypoints = len(waypoints)
475
+ if n_waypoints < 3:
476
+ og.log.error("Cannot generate trajectory from waypoints with less than 3 waypoints!")
477
+ return
478
+
479
+ splines = [CubicSpline(range(n_waypoints), waypoints[:, i], bc_type="clamped") for i in range(3)]
480
+ dsplines = [spline.derivative() for spline in splines]
481
+
482
+ # Function help get arc derivative
483
+ def arc_derivative(u):
484
+ return math.sqrt(sum(dspline(u) ** 2 for dspline in dsplines))
485
+
486
+ # Function to help get interpolated positions
487
+ def get_interpolated_positions(step):
488
+ assert step < n_waypoints - 1
489
+ dist = quad(func=arc_derivative, a=step, b=step + 1)[0]
490
+ path_length = int(dist / per_step_distance)
491
+ interpolated_points = th.zeros((path_length, 3))
492
+ for i in range(path_length):
493
+ curr_step = step + (i / path_length)
494
+ interpolated_points[i, :] = th.tensor([float(spline(curr_step)) for spline in splines])
495
+ return interpolated_points
496
+
497
+ # Iterate over all waypoints and infer the resulting trajectory, recording the resulting poses
498
+ poses = []
499
+ for i in range(n_waypoints - 1):
500
+ positions = get_interpolated_positions(step=i)
501
+ for j in range(len(positions) - 1):
502
+ # Get direction vector from the current to the following point
503
+ direction = positions[j + 1] - positions[j]
504
+ direction = direction / th.norm(direction)
505
+ # Infer tilt and pan angles from this direction
506
+ xy_direction = direction[:2] / th.norm(direction[:2])
507
+ z = direction[2]
508
+ pan_angle = th.arctan2(-xy_direction[0], xy_direction[1])
509
+ tilt_angle = th.arcsin(z)
510
+ # Infer global quat orientation from these angles
511
+ quat = T.euler2quat(th.tensor([math.pi / 2 + tilt_angle.item(), 0.0, pan_angle.item()]))
512
+ poses.append([positions[j], quat])
513
+
514
+ # Record the generated trajectory
515
+ self.record_trajectory(poses=poses, fps=fps, steps_per_frame=steps_per_frame, fpath=fpath)
516
+
517
+ def set_delta(self, delta):
518
+ """
519
+ Sets the delta value (how much the camera moves with each keypress) for this CameraMover
520
+
521
+ Args:
522
+ delta (float): Change (m) per keypress when moving the camera
523
+ """
524
+ self.delta = delta
525
+
526
+ def set_cam(self, cam):
527
+ """
528
+ Sets the active camera sensor for this CameraMover
529
+
530
+ Args:
531
+ cam (VisionSensor): The camera vision sensor to manipulate via the keyboard
532
+ """
533
+ self.cam = cam
534
+
535
+ @property
536
+ def input_to_function(self):
537
+ """
538
+ Returns:
539
+ dict: Mapping from relevant keypresses to corresponding function call to use
540
+ """
541
+ return {
542
+ lazy.carb.input.KeyboardInput.O: lambda: self.record_image(fpath=None),
543
+ lazy.carb.input.KeyboardInput.P: lambda: self.print_cam_pose(),
544
+ lazy.carb.input.KeyboardInput.KEY_9: lambda: self.change_light(delta=-2e4),
545
+ lazy.carb.input.KeyboardInput.KEY_0: lambda: self.change_light(delta=2e4),
546
+ }
547
+
548
+ @property
549
+ def input_to_command(self):
550
+ """
551
+ Returns:
552
+ dict: Mapping from relevant keypresses to corresponding delta command to apply to the camera pose
553
+ """
554
+ return {
555
+ lazy.carb.input.KeyboardInput.D: th.tensor([self.delta, 0, 0]),
556
+ lazy.carb.input.KeyboardInput.A: th.tensor([-self.delta, 0, 0]),
557
+ lazy.carb.input.KeyboardInput.W: th.tensor([0, 0, -self.delta]),
558
+ lazy.carb.input.KeyboardInput.S: th.tensor([0, 0, self.delta]),
559
+ lazy.carb.input.KeyboardInput.T: th.tensor([0, self.delta, 0]),
560
+ lazy.carb.input.KeyboardInput.G: th.tensor([0, -self.delta, 0]),
561
+ }
562
+
563
+ def _sub_keyboard_event(self, event, *args, **kwargs):
564
+ """
565
+ Handle keyboard events. Note: The signature is pulled directly from omni.
566
+
567
+ Args:
568
+ event (int): keyboard event type
569
+ """
570
+ if (
571
+ event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS
572
+ or event.type == lazy.carb.input.KeyboardEventType.KEY_REPEAT
573
+ ):
574
+ if event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS and event.input in self.input_to_function:
575
+ self.input_to_function[event.input]()
576
+
577
+ else:
578
+ command = self.input_to_command.get(event.input, None)
579
+
580
+ if command is not None:
581
+ # Convert to world frame to move the camera
582
+ pos, orn = self.cam.get_position_orientation()
583
+ transform = T.quat2mat(orn)
584
+ delta_pos_global = transform @ command
585
+ self.cam.set_position_orientation(position=pos + delta_pos_global)
586
+
587
+ return True
588
+
589
+
590
+ class KeyboardRobotController:
591
+ """
592
+ Simple class for controlling OmniGibson robots using keyboard commands
593
+ """
594
+
595
+ def __init__(self, robot):
596
+ """
597
+ Args:
598
+ robot (BaseRobot): robot to control
599
+ """
600
+ # Store relevant info from robot
601
+ self.robot = robot
602
+ self.action_dim = robot.action_dim
603
+ self.controller_info = dict()
604
+ self.joint_idx_to_group_key = dict()
605
+ idx = 0
606
+
607
+ for name, (group_key, _) in robot.controllers.items():
608
+ self.controller_info[name] = {
609
+ "name": ControllerView.get_controller_type_str(group_key),
610
+ "start_idx": idx,
611
+ "dofs": ControllerView.get_dof_idx(group_key),
612
+ "command_dim": ControllerView.get_command_dim(group_key),
613
+ }
614
+ idx += ControllerView.get_command_dim(group_key)
615
+ for i in ControllerView.get_dof_idx(group_key).tolist():
616
+ self.joint_idx_to_group_key[i] = group_key
617
+
618
+ # Other persistent variables we need to keep track of
619
+ self.joint_names = [name for name in robot.joints.keys()] # Ordered list of joint names belonging to the robot
620
+ self.joint_types = [joint.joint_type for joint in robot.joints.values()] # Ordered list of joint types
621
+ self.joint_command_idx = None # Indices of joints being directly controlled in the action array
622
+ self.joint_control_idx = None # Indices of joints being directly controlled in the actual joint array
623
+ self.active_joint_command_idx_idx = (
624
+ 0 # Which index within the joint_command_idx variable is being controlled by the user
625
+ )
626
+ self.current_joint = -1 # Active joint being controlled for joint control
627
+ self.ik_arms = [] # List of arm controller names to be controlled by IK
628
+ self.active_arm_idx = 0 # Which index within self.ik_arms is actively being controlled (only relevant for IK)
629
+ self.binary_grippers = [] # Grippers being controlled using multi-finger binary controller
630
+ self.active_gripper_idx = 0 # Which index within self.binary_grippers is actively being controlled
631
+ self.gripper_direction = None # Flips between -1 and 1, per arm controlled by multi-finger binary control
632
+ self.persistent_gripper_action = (
633
+ None # Persistent gripper commands, per arm controlled by multi-finger binary control
634
+ )
635
+ # i.e.: if using binary gripper control and when no keypress is active, the gripper action should still the last executed gripper action
636
+ self.keypress_mapping = None # Maps omni keybindings to information for controlling various parts of the robot
637
+ self.current_keypress = None # Current key that is being pressed
638
+ self.active_action = None # Current action information based on the current keypress
639
+ self._pending_release_key = None # Which key has a pending release (to handle batched events)
640
+ self.toggling_gripper = False # Whether we should toggle the gripper during the next action
641
+ self.custom_keymapping = None # Dictionary mapping custom keys to custom callback functions / info
642
+
643
+ # Populate the keypress mapping dictionary
644
+ self.populate_keypress_mapping()
645
+
646
+ # Register the keyboard callback function
647
+ self.register_keyboard_handler()
648
+
649
+ def register_keyboard_handler(self):
650
+ """
651
+ Sets up the keyboard callback functionality with omniverse
652
+ """
653
+ appwindow = lazy.omni.appwindow.get_default_app_window()
654
+ input_interface = lazy.carb.input.acquire_input_interface()
655
+ keyboard = appwindow.get_keyboard()
656
+ self._keyboard_sub = input_interface.subscribe_to_keyboard_events(keyboard, self.keyboard_event_handler)
657
+
658
+ def register_custom_keymapping(self, key, description, callback_fn):
659
+ """
660
+ Register a custom keymapping with corresponding callback function for this keyboard controller.
661
+ Note that this will automatically override any pre-existing callback that existed for that key.
662
+
663
+ Args:
664
+ key (carb.input.KeyboardInput): Key to map to callback function
665
+ description (str): Description for the callback function
666
+ callback_fn (function): Callback function, should have signature:
667
+
668
+ callback_fn() -> None
669
+ """
670
+ self.custom_keymapping[key] = {"description": description, "callback": callback_fn}
671
+
672
+ def generate_ik_keypress_mapping(self, controller_info):
673
+ """
674
+ Generates a dictionary for keypress mappings for IK control, based on the inputted @controller_info
675
+
676
+ Args:
677
+ controller_info (dict): Dictionary of controller information for the specific robot arm to control
678
+ with IK
679
+
680
+ Returns:
681
+ dict: Populated keypress mappings for IK to control the specified controller
682
+ """
683
+ mapping = {}
684
+
685
+ mapping[lazy.carb.input.KeyboardInput.UP] = {"idx": controller_info["start_idx"] + 0, "val": 0.1}
686
+ mapping[lazy.carb.input.KeyboardInput.DOWN] = {"idx": controller_info["start_idx"] + 0, "val": -0.1}
687
+ mapping[lazy.carb.input.KeyboardInput.RIGHT] = {"idx": controller_info["start_idx"] + 1, "val": -0.1}
688
+ mapping[lazy.carb.input.KeyboardInput.LEFT] = {"idx": controller_info["start_idx"] + 1, "val": 0.1}
689
+ mapping[lazy.carb.input.KeyboardInput.P] = {"idx": controller_info["start_idx"] + 2, "val": 0.1}
690
+ mapping[lazy.carb.input.KeyboardInput.SEMICOLON] = {"idx": controller_info["start_idx"] + 2, "val": -0.1}
691
+ mapping[lazy.carb.input.KeyboardInput.N] = {"idx": controller_info["start_idx"] + 3, "val": 0.1}
692
+ mapping[lazy.carb.input.KeyboardInput.B] = {"idx": controller_info["start_idx"] + 3, "val": -0.1}
693
+ mapping[lazy.carb.input.KeyboardInput.O] = {"idx": controller_info["start_idx"] + 4, "val": 0.1}
694
+ mapping[lazy.carb.input.KeyboardInput.U] = {"idx": controller_info["start_idx"] + 4, "val": -0.1}
695
+ mapping[lazy.carb.input.KeyboardInput.V] = {"idx": controller_info["start_idx"] + 5, "val": 0.1}
696
+ mapping[lazy.carb.input.KeyboardInput.C] = {"idx": controller_info["start_idx"] + 5, "val": -0.1}
697
+
698
+ return mapping
699
+
700
+ def generate_osc_keypress_mapping(self, controller_info):
701
+ """
702
+ Generates a dictionary for keypress mappings for OSC control, based on the inputted @controller_info
703
+
704
+ Args:
705
+ controller_info (dict): Dictionary of controller information for the specific robot arm to control
706
+ with OSC
707
+
708
+ Returns:
709
+ dict: Populated keypress mappings for IK to control the specified controller
710
+ """
711
+ mapping = {}
712
+
713
+ mapping[lazy.carb.input.KeyboardInput.UP] = {"idx": controller_info["start_idx"] + 0, "val": 0.25}
714
+ mapping[lazy.carb.input.KeyboardInput.DOWN] = {"idx": controller_info["start_idx"] + 0, "val": -0.25}
715
+ mapping[lazy.carb.input.KeyboardInput.RIGHT] = {"idx": controller_info["start_idx"] + 1, "val": -0.25}
716
+ mapping[lazy.carb.input.KeyboardInput.LEFT] = {"idx": controller_info["start_idx"] + 1, "val": 0.25}
717
+ mapping[lazy.carb.input.KeyboardInput.P] = {"idx": controller_info["start_idx"] + 2, "val": 0.25}
718
+ mapping[lazy.carb.input.KeyboardInput.SEMICOLON] = {"idx": controller_info["start_idx"] + 2, "val": -0.25}
719
+ mapping[lazy.carb.input.KeyboardInput.N] = {"idx": controller_info["start_idx"] + 3, "val": 0.25}
720
+ mapping[lazy.carb.input.KeyboardInput.B] = {"idx": controller_info["start_idx"] + 3, "val": -0.25}
721
+ mapping[lazy.carb.input.KeyboardInput.O] = {"idx": controller_info["start_idx"] + 4, "val": 0.25}
722
+ mapping[lazy.carb.input.KeyboardInput.U] = {"idx": controller_info["start_idx"] + 4, "val": -0.25}
723
+ mapping[lazy.carb.input.KeyboardInput.V] = {"idx": controller_info["start_idx"] + 5, "val": 0.25}
724
+ mapping[lazy.carb.input.KeyboardInput.C] = {"idx": controller_info["start_idx"] + 5, "val": -0.25}
725
+
726
+ return mapping
727
+
728
+ def populate_keypress_mapping(self):
729
+ """
730
+ Populates the mapping @self.keypress_mapping, which maps keypresses to action info:
731
+
732
+ keypress:
733
+ idx: <int>
734
+ val: <float>
735
+ """
736
+ self.keypress_mapping = {}
737
+ self.joint_command_idx = []
738
+ self.joint_control_idx = []
739
+ self.gripper_direction = {}
740
+ self.persistent_gripper_action = {}
741
+ self.custom_keymapping = {}
742
+
743
+ # Add mapping for joint control directions (no index because these are inferred at runtime)
744
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.RIGHT_BRACKET] = {"idx": None, "val": 0.1}
745
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.LEFT_BRACKET] = {"idx": None, "val": -0.1}
746
+
747
+ # Iterate over all controller info and populate mapping
748
+ for component, info in self.controller_info.items():
749
+ if info["name"] in ["JointController", "HolonomicBaseJointController"]:
750
+ for i in range(info["command_dim"]):
751
+ cmd_idx = info["start_idx"] + i
752
+ self.joint_command_idx.append(cmd_idx)
753
+ self.joint_control_idx += info["dofs"].tolist()
754
+ elif info["name"] == "DifferentialDriveController":
755
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.I] = {"idx": info["start_idx"] + 0, "val": 0.4}
756
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.K] = {"idx": info["start_idx"] + 0, "val": -0.4}
757
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.L] = {"idx": info["start_idx"] + 1, "val": -0.2}
758
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.J] = {"idx": info["start_idx"] + 1, "val": 0.2}
759
+ elif info["name"] == "InverseKinematicsController":
760
+ self.ik_arms.append(component)
761
+ self.keypress_mapping.update(self.generate_ik_keypress_mapping(controller_info=info))
762
+ elif info["name"] == "OperationalSpaceController":
763
+ self.ik_arms.append(component)
764
+ self.keypress_mapping.update(self.generate_osc_keypress_mapping(controller_info=info))
765
+ elif info["name"] == "MultiFingerGripperController":
766
+ if info["command_dim"] > 1:
767
+ for i in range(info["command_dim"]):
768
+ cmd_idx = info["start_idx"] + i
769
+ self.joint_command_idx.append(cmd_idx)
770
+ self.joint_control_idx += info["dofs"].tolist()
771
+ else:
772
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.T] = {"idx": info["start_idx"], "val": 1.0}
773
+ self.gripper_direction[component] = 1.0
774
+ self.persistent_gripper_action[component] = 1.0
775
+ self.binary_grippers.append(component)
776
+ elif info["name"] == "NullJointController":
777
+ # We won't send actions if using a null gripper controller
778
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.T] = {"idx": None, "val": None}
779
+ else:
780
+ raise ValueError("Unknown controller name received: {}".format(info["name"]))
781
+
782
+ def keyboard_event_handler(self, event, *args, **kwargs):
783
+ # Check if we've received a key press or repeat
784
+ if (
785
+ event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS
786
+ or event.type == lazy.carb.input.KeyboardEventType.KEY_REPEAT
787
+ ):
788
+ # Handle special cases
789
+ if (
790
+ event.input in {lazy.carb.input.KeyboardInput.KEY_1, lazy.carb.input.KeyboardInput.KEY_2}
791
+ and len(self.joint_control_idx) > 1
792
+ ):
793
+ # Update joint and print out new joint being controlled
794
+ self.active_joint_command_idx_idx = (
795
+ max(0, self.active_joint_command_idx_idx - 1)
796
+ if event.input == lazy.carb.input.KeyboardInput.KEY_1
797
+ else min(len(self.joint_control_idx) - 1, self.active_joint_command_idx_idx + 1)
798
+ )
799
+ print(
800
+ f"Now controlling joint {self.joint_names[self.joint_control_idx[self.active_joint_command_idx_idx]]}"
801
+ )
802
+
803
+ elif (
804
+ event.input in {lazy.carb.input.KeyboardInput.KEY_3, lazy.carb.input.KeyboardInput.KEY_4}
805
+ and len(self.ik_arms) > 1
806
+ ):
807
+ # Update arm, update keypress mapping, and print out new arm being controlled
808
+ self.active_arm_idx = (
809
+ max(0, self.active_arm_idx - 1)
810
+ if event.input == lazy.carb.input.KeyboardInput.KEY_3
811
+ else min(len(self.ik_arms) - 1, self.active_arm_idx + 1)
812
+ )
813
+ new_arm = self.ik_arms[self.active_arm_idx]
814
+ self.keypress_mapping.update(self.generate_ik_keypress_mapping(self.controller_info[new_arm]))
815
+ print(f"Now controlling arm {new_arm} EEF")
816
+
817
+ elif (
818
+ event.input in {lazy.carb.input.KeyboardInput.KEY_5, lazy.carb.input.KeyboardInput.KEY_6}
819
+ and len(self.binary_grippers) > 1
820
+ ):
821
+ # Update gripper, update keypress mapping, and print out new gripper being controlled
822
+ self.active_gripper_idx = (
823
+ max(0, self.active_gripper_idx - 1)
824
+ if event.input == lazy.carb.input.KeyboardInput.KEY_5
825
+ else min(len(self.binary_grippers) - 1, self.active_gripper_idx + 1)
826
+ )
827
+ print(f"Now controlling gripper {self.binary_grippers[self.active_gripper_idx]} with binary toggling")
828
+
829
+ elif event.input == lazy.carb.input.KeyboardInput.M:
830
+ # Render the sensor modalities from the robot's camera and lidar
831
+ self.robot.visualize_sensors()
832
+
833
+ elif event.input in self.custom_keymapping:
834
+ # Run custom press
835
+ self.custom_keymapping[event.input]["callback"]()
836
+
837
+ elif event.input == lazy.carb.input.KeyboardInput.ESCAPE:
838
+ # Terminate immediately
839
+ og.shutdown()
840
+
841
+ else:
842
+ # Handle all other actions and update accordingly
843
+ self.active_action = self.keypress_mapping.get(event.input, None)
844
+
845
+ if event.type == lazy.carb.input.KeyboardEventType.KEY_PRESS:
846
+ # Store the current keypress
847
+ self.current_keypress = event.input
848
+
849
+ # Also store whether we pressed the key for toggling gripper actions
850
+ if event.input == lazy.carb.input.KeyboardInput.T:
851
+ self.toggling_gripper = True
852
+
853
+ # If we release a key, mark release as pending (don't clear immediately to handle batched events)
854
+ elif event.type == lazy.carb.input.KeyboardEventType.KEY_RELEASE:
855
+ self._pending_release_key = event.input
856
+
857
+ # Callback always needs to return True
858
+ return True
859
+
860
+ def get_random_action(self):
861
+ """
862
+ Returns:
863
+ n-array: Generated random action vector (normalized)
864
+ """
865
+ action_lo, action_hi = -1, 1
866
+ return th.rand(self.action_dim) * (action_hi - action_lo) + action_lo
867
+
868
+ def get_teleop_action(self):
869
+ """
870
+ Returns:
871
+ n-array: Generated action vector based on received user inputs from the keyboard
872
+ """
873
+ action = th.zeros(self.action_dim)
874
+
875
+ # Handle the action if any key is actively being pressed
876
+ if self.active_action is not None:
877
+ idx, val = self.active_action["idx"], self.active_action["val"]
878
+
879
+ # Only handle the action if the value is specified
880
+ if val is not None:
881
+ # If there is no index, the user is controlling a joint with "[" and "]"
882
+ if idx is None and len(self.joint_command_idx) != 0:
883
+ idx = self.joint_command_idx[self.active_joint_command_idx_idx]
884
+
885
+ # Also potentially modify the value being deployed in we're controlling a prismatic joint
886
+ # Lower prismatic joint values modifying delta positions since 0.1m is very different from 0.1rad!
887
+ joint_idx = self.joint_control_idx[self.active_joint_command_idx_idx]
888
+
889
+ # Import here to avoid circular imports
890
+ from omnigibson.utils.constants import JointType
891
+
892
+ gk = self.joint_idx_to_group_key[joint_idx]
893
+ if (
894
+ self.joint_types[joint_idx] == JointType.JOINT_PRISMATIC
895
+ and ControllerView.get_use_delta_commands(gk)
896
+ and ControllerView.get_motor_type(gk) == "position"
897
+ ):
898
+ val *= 0.2
899
+
900
+ # Set the action
901
+ if idx is not None:
902
+ action[idx] = val
903
+
904
+ # Possibly set the persistent gripper action
905
+ if len(self.binary_grippers) > 0 and self.keypress_mapping[lazy.carb.input.KeyboardInput.T]["val"] is not None:
906
+ for i, binary_gripper in enumerate(self.binary_grippers):
907
+ # Possibly update the stored value if the toggle gripper key has been pressed and
908
+ # it's the active gripper being controlled
909
+ if self.toggling_gripper and i == self.active_gripper_idx:
910
+ # We toggle the gripper direction or this gripper
911
+ self.gripper_direction[binary_gripper] *= -1.0
912
+ self.persistent_gripper_action[binary_gripper] = (
913
+ self.keypress_mapping[lazy.carb.input.KeyboardInput.T]["val"]
914
+ * self.gripper_direction[binary_gripper]
915
+ )
916
+
917
+ # Clear the toggling gripper flag
918
+ self.toggling_gripper = False
919
+
920
+ # Set the persistent action
921
+ action[self.controller_info[binary_gripper]["start_idx"]] = self.persistent_gripper_action[
922
+ binary_gripper
923
+ ]
924
+
925
+ # TODO: this currently conflicts with omniverse logging and spams the window
926
+ # Print out the user what is being pressed / controlled
927
+ # sys.stdout.write("\033[K")
928
+ # keypress_str = self.current_keypress.__str__().split(".")[-1]
929
+ # print("Pressed {}. Action: {}".format(keypress_str, action.tolist()))
930
+ # sys.stdout.write("\033[F")
931
+
932
+ # Clear action after consuming if a key release was pending for the current key
933
+ if self._pending_release_key is not None and self._pending_release_key == self.current_keypress:
934
+ self.active_action = None
935
+ self.current_keypress = None
936
+ self._pending_release_key = None
937
+
938
+ # Return action
939
+ return action
940
+
941
+ def print_keyboard_teleop_info(self):
942
+ """
943
+ Prints out relevant information for teleop controlling a robot
944
+ """
945
+
946
+ def print_command(char, info):
947
+ char += " " * (10 - len(char))
948
+ print("{}\t{}".format(char, info))
949
+
950
+ print()
951
+ print("*" * 30)
952
+ print("Controlling the Robot Using the Keyboard")
953
+ print("*" * 30)
954
+ print()
955
+ print("Joint Control")
956
+ print_command("1, 2", "decrement / increment the joint to control")
957
+ print_command("[, ]", "move the joint backwards, forwards, respectively")
958
+ print()
959
+ print("Differential Drive Control")
960
+ print_command("j, l", "turn left, right")
961
+ print_command("i, k", "move forward, backwards")
962
+ print()
963
+ print("Inverse Kinematics Control")
964
+ print_command("3, 4", "toggle between the different arm(s) to control")
965
+ print_command("\u2190, \u2192", "translate arm eef along x-axis")
966
+ print_command("\u2191, \u2193", "translate arm eef along y-axis")
967
+ print_command("p, ;", "translate arm eef along z-axis")
968
+ print_command("n, b", "rotate arm eef about x-axis")
969
+ print_command("o, u", "rotate arm eef about y-axis")
970
+ print_command("v, c", "rotate arm eef about z-axis")
971
+ print()
972
+ print("Boolean Gripper Control")
973
+ print_command("5, 6", "toggle between the different gripper(s) using binary control")
974
+ print_command("t", "toggle gripper (open/close)")
975
+ print()
976
+ print("Sensor Rendering")
977
+ print_command(
978
+ "m", "render the onboard sensor modalities (RGB, Depth, Normals, Instance Segmentation, Occupancy Map)"
979
+ )
980
+ print()
981
+ if len(self.custom_keymapping) > 0:
982
+ print("Custom Keymappings")
983
+ for key, info in self.custom_keymapping.items():
984
+ key_str = key.__str__().split(".")[-1].lower()
985
+ print_command(key_str, info["description"])
986
+ print()
987
+ print("*" * 30)
988
+ print()
989
+
990
+
991
+ def generate_box_edges(center, extents):
992
+ """
993
+ Generate the edges of a box given its center and extents.
994
+
995
+ Parameters:
996
+ - center: Tuple of (x, y, z) coordinates for the box's center
997
+ - extents: Tuple of (width, height, depth) extents of the box
998
+
999
+ Returns:
1000
+ - A list of tuples, each containing two points (each a tuple of x, y, z) representing an edge of the box
1001
+ """
1002
+ x_c, y_c, z_c = center
1003
+ w, h, d = extents
1004
+
1005
+ # Calculate the corner points of the box
1006
+ corners = [
1007
+ (x_c - w, y_c - h, z_c - d),
1008
+ (x_c - w, y_c - h, z_c + d),
1009
+ (x_c - w, y_c + h, z_c - d),
1010
+ (x_c - w, y_c + h, z_c + d),
1011
+ (x_c + w, y_c - h, z_c - d),
1012
+ (x_c + w, y_c - h, z_c + d),
1013
+ (x_c + w, y_c + h, z_c - d),
1014
+ (x_c + w, y_c + h, z_c + d),
1015
+ ]
1016
+
1017
+ # Define the edges by connecting the corners
1018
+ edges = [
1019
+ (corners[0], corners[1]),
1020
+ (corners[0], corners[2]),
1021
+ (corners[1], corners[3]),
1022
+ (corners[2], corners[3]),
1023
+ (corners[4], corners[5]),
1024
+ (corners[4], corners[6]),
1025
+ (corners[5], corners[7]),
1026
+ (corners[6], corners[7]),
1027
+ (corners[0], corners[4]),
1028
+ (corners[1], corners[5]),
1029
+ (corners[2], corners[6]),
1030
+ (corners[3], corners[7]),
1031
+ ]
1032
+
1033
+ return edges
1034
+
1035
+
1036
+ def draw_text(
1037
+ text,
1038
+ position,
1039
+ orientation=None,
1040
+ color=(1.0, 0.0, 0.0, 1.0),
1041
+ font_size=12,
1042
+ line_size=1.0,
1043
+ anchor="center",
1044
+ max_height=th.inf,
1045
+ max_width=th.inf,
1046
+ ):
1047
+ """
1048
+ Draws text at a given position.
1049
+ """
1050
+
1051
+ # First, get the line segments corresponding to the text
1052
+ # font_family = "Ariel"
1053
+ # fp = FontProperties(family=font_family)
1054
+ path = TextPath((0, 0), text, size=font_size)
1055
+
1056
+ def _path_to_line_segments(path):
1057
+ line_segments = []
1058
+ subpath_start = None # Store the start point of the current subpath
1059
+
1060
+ for points, code in zip(path.vertices, path.codes):
1061
+ points = th.as_tensor(points, dtype=th.float32) # Ensure points is a tensor with float32 dtype
1062
+
1063
+ if code == mpath.Path.MOVETO:
1064
+ current_point = points
1065
+ subpath_start = points # Remember the start of the subpath
1066
+ elif code == mpath.Path.LINETO:
1067
+ start_point = current_point.clone() # Create copies to avoid reference issues
1068
+ end_point = points.clone()
1069
+ line_segments.append(
1070
+ [start_point.tolist(), end_point.tolist()]
1071
+ ) # Convert to list for consistent storage
1072
+ current_point = points
1073
+ elif code == mpath.Path.CURVE3 or code == mpath.Path.CURVE4:
1074
+ start_point = current_point.clone()
1075
+ end_point = points[:2].clone()
1076
+ line_segments.append([start_point.tolist(), end_point.tolist()])
1077
+ current_point = end_point
1078
+ elif code == mpath.Path.CLOSEPOLY:
1079
+ if not th.allclose(current_point, subpath_start):
1080
+ line_segments.append([current_point.tolist(), subpath_start.tolist()])
1081
+ current_point = subpath_start
1082
+ else:
1083
+ raise ValueError(f"Unsupported path code: {code}")
1084
+
1085
+ # Convert the entire list of segments to a tensor at once
1086
+ return th.tensor(line_segments, dtype=th.float32)
1087
+
1088
+ # Convert the Path to line segments
1089
+ line_segments = _path_to_line_segments(path)
1090
+
1091
+ # Transform the line segments to the desired position
1092
+ all_verts = line_segments.reshape(-1, 2)
1093
+ orig_min = th.min(all_verts, dim=0).values
1094
+ orig_max = th.max(all_verts, dim=0).values
1095
+ orig_ext = orig_max - orig_min
1096
+
1097
+ # Figure out the necessary scaling
1098
+ scale = 1.0
1099
+ max_dims = th.tensor([max_width, max_height])
1100
+ if th.any(th.isfinite(max_dims)):
1101
+ scale = th.min(max_dims / orig_ext)
1102
+ transformed_line_segments = line_segments * scale
1103
+
1104
+ # Recompute the extents
1105
+ transformed_verts = transformed_line_segments.reshape(-1, 2)
1106
+ min_pt = th.min(transformed_verts, dim=0).values
1107
+ max_pt = th.max(transformed_verts, dim=0).values
1108
+ center = (min_pt + max_pt) / 2
1109
+
1110
+ if anchor == "center":
1111
+ anchor_pt = center
1112
+ elif anchor == "bottomleft":
1113
+ anchor_pt = min_pt
1114
+ elif anchor == "topright":
1115
+ anchor_pt = max_pt
1116
+ elif anchor == "topleft":
1117
+ anchor_pt = th.tensor([min_pt[0], max_pt[1]])
1118
+ elif anchor == "bottomright":
1119
+ anchor_pt = th.tensor([max_pt[0], min_pt[1]])
1120
+ elif anchor == "bottomcenter":
1121
+ anchor_pt = th.tensor([center[0], min_pt[1]])
1122
+ elif anchor == "topcenter":
1123
+ anchor_pt = th.tensor([center[0], max_pt[1]])
1124
+ else:
1125
+ raise ValueError(f"Unknown anchor point {anchor}")
1126
+
1127
+ rotation = R.identity()
1128
+ if orientation is not None:
1129
+ rotation = R.from_quat(orientation)
1130
+
1131
+ def _transform_point(pt):
1132
+ centered_pt = pt - anchor_pt
1133
+ return rotation.apply([centered_pt[0], centered_pt[1], 0]) + position
1134
+
1135
+ # Then, draw the line segments
1136
+ for f, t in transformed_line_segments:
1137
+ draw_line(_transform_point(f), _transform_point(t), color=color, size=line_size)
1138
+
1139
+
1140
+ def draw_line(start, end, color=(1.0, 0.0, 0.0, 1.0), size=1.0):
1141
+ """
1142
+ Draws a single line between two points.
1143
+ """
1144
+ draw = lazy.isaacsim.util.debug_draw._debug_draw.acquire_debug_draw_interface()
1145
+ draw.draw_lines([start], [end], [color], [size])
1146
+
1147
+
1148
+ def draw_box(center, extents, color=(1.0, 0.0, 0.0, 1.0), size=1.0):
1149
+ """
1150
+ Draws a box defined by its center and extents.
1151
+ """
1152
+ edges = generate_box_edges(center, extents)
1153
+ for start, end in edges:
1154
+ draw_line(start, end, color, size)
1155
+
1156
+
1157
+ def draw_aabb(obj):
1158
+ """
1159
+ Draws the axis-aligned bounding box of a given object.
1160
+ """
1161
+ ctr = obj.aabb_center
1162
+ ext = obj.aabb_extent / 2.0
1163
+ draw_box(ctr, ext)
1164
+
1165
+
1166
+ def clear_debug_drawing():
1167
+ """
1168
+ Clears all debug drawings.
1169
+ """
1170
+ draw = lazy.isaacsim.util.debug_draw._debug_draw.acquire_debug_draw_interface()
1171
+ draw.clear_lines()
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdf_preprocessing.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ import xml.etree.ElementTree as ET
6
+ from pathlib import Path
7
+ from typing import Optional, Union
8
+
9
+ PathLike = Union[str, os.PathLike]
10
+
11
+
12
+ def _is_ascii(text: str) -> bool:
13
+ return all(ord(ch) < 128 for ch in text)
14
+
15
+
16
+ def _mesh_filenames(root: ET.Element) -> list[str]:
17
+ """Return every ``filename`` referenced by a ``<mesh>`` element, in document order."""
18
+ filenames = []
19
+ for mesh in root.iter("mesh"):
20
+ fn = mesh.get("filename")
21
+ if fn is not None:
22
+ filenames.append(fn)
23
+ return filenames
24
+
25
+
26
+ def _strip_uri_scheme(ref: str) -> str:
27
+ """Strip a leading ``file://`` scheme if present (kept verbatim otherwise)."""
28
+ if ref.startswith("file://"):
29
+ return ref[len("file://") :]
30
+ return ref
31
+
32
+
33
+ def _classify_mesh_ref(ref: str, urdf_dir: Path) -> str:
34
+ """Classify a single mesh reference.
35
+
36
+ Returns one of: ``"package"`` (package:// URI), ``"ok"`` (resolves on disk),
37
+ or ``"broken"`` (absolute/relative path that does not resolve).
38
+ """
39
+ if ref.startswith("package://"):
40
+ return "package"
41
+ candidate = _strip_uri_scheme(ref)
42
+ path = Path(candidate)
43
+ if not path.is_absolute():
44
+ path = urdf_dir / candidate
45
+ try:
46
+ exists = path.exists()
47
+ except OSError:
48
+ exists = False
49
+ return "ok" if exists else "broken"
50
+
51
+
52
+ def copy_robot_to_models(name: str, data_path: PathLike, dataset_name: str = "omnigibson-robot-assets") -> Path:
53
+ """Copy an imported robot from ``objects/robot/<name>/`` into ``models/<name>/`` (idempotent) so
54
+ ``REGISTERED_ROBOTS`` discovers it. The ``<name>.yaml`` definition is placed there separately.
55
+ Returns the destination ``models/<name>/`` directory.
56
+ """
57
+ src = Path(data_path) / dataset_name / "objects" / "robot" / name
58
+ dst = Path(data_path) / dataset_name / "models" / name
59
+ assert src.exists(), f"imported robot not found at {src} (run import_custom_robot.py first)"
60
+ dst.mkdir(parents=True, exist_ok=True)
61
+ for child in src.iterdir():
62
+ target = dst / child.name
63
+ if child.is_dir():
64
+ shutil.copytree(child, target, dirs_exist_ok=True)
65
+ else:
66
+ shutil.copy2(child, target)
67
+ return dst
68
+
69
+
70
+ def link_has_dedicated_collision(link_element: ET.Element) -> bool:
71
+ """True if the link ships a usable collision proxy: a ``<collision>`` that is a primitive, or a
72
+ mesh whose file differs from the link's visual meshes. Such collisions are preserved on import;
73
+ otherwise (missing, or the same mesh as the visual) one must be generated.
74
+ """
75
+ visual_mesh_files = {
76
+ mesh.get("filename") for vis in link_element.findall("visual") for mesh in vis.findall("geometry/mesh")
77
+ }
78
+ for col in link_element.findall("collision"):
79
+ geom = col.find("geometry/*")
80
+ if geom is None:
81
+ continue
82
+ if geom.tag != "mesh" or geom.get("filename") not in visual_mesh_files:
83
+ return True
84
+ return False
85
+
86
+
87
+ def override_joint_limits(tree: ET.ElementTree, limits: dict) -> int:
88
+ """Set ``<limit>`` attributes on named joints (in place), repairing zeroed/degenerate limits that
89
+ make a joint non-drivable. ``limits`` maps ``joint_name -> {attr: value}``. Returns the count updated.
90
+ """
91
+ root = tree.getroot()
92
+ updated = 0
93
+ for joint in root.findall("joint"):
94
+ name = joint.get("name")
95
+ if name in limits:
96
+ limit_el = joint.find("limit")
97
+ if limit_el is None:
98
+ limit_el = ET.SubElement(joint, "limit")
99
+ for attr, value in limits[name].items():
100
+ limit_el.set(attr, str(value))
101
+ updated += 1
102
+ return updated
103
+
104
+
105
+ def rewrite_mesh_paths(tree: ET.ElementTree, replacements) -> int:
106
+ """Apply ordered ``(old, new)`` substring replacements to every ``<mesh filename>`` (in place),
107
+ e.g. to turn ``package://`` URIs or broken relative paths into resolvable absolute paths.
108
+ Returns the count of references changed.
109
+ """
110
+ root = tree.getroot()
111
+ updated = 0
112
+ for mesh in root.iter("mesh"):
113
+ fn = mesh.get("filename")
114
+ if fn is None:
115
+ continue
116
+ new = fn
117
+ for old, repl in replacements:
118
+ new = new.replace(old, repl)
119
+ if new != fn:
120
+ mesh.set("filename", new)
121
+ updated += 1
122
+ return updated
123
+
124
+
125
+ def strip_mimic_joints(tree: ET.ElementTree) -> int:
126
+ """Remove every ``<mimic>`` element (in place); returns the count removed. The importer writes no
127
+ DriveAPI on a mimic joint, leaving that finger non-drivable -- drive both fingers at runtime instead.
128
+ """
129
+ root = tree.getroot()
130
+ removed = 0
131
+ for joint in root.findall("joint"):
132
+ for mimic in joint.findall("mimic"):
133
+ joint.remove(mimic)
134
+ removed += 1
135
+ return removed
136
+
137
+
138
+ def stage_meshes(tree: ET.ElementTree, dest_dir: PathLike, invalid_chars: str = " ()", replacement: str = "_") -> int:
139
+ """Copy every referenced mesh into ``dest_dir`` under a USD-safe basename (space/paren -> ``_``),
140
+ rewriting the references (in place); returns the number of files copied. Avoids the importer's
141
+ ill-formed-SdfPath failure on mesh filenames with spaces (it names geometry prims after the
142
+ basename). Run after `rewrite_mesh_paths` so refs resolve. Identical sources are copied
143
+ once; distinct sources colliding on a sanitized name get a numeric suffix.
144
+ """
145
+ dest = Path(dest_dir)
146
+ dest.mkdir(parents=True, exist_ok=True)
147
+ root = tree.getroot()
148
+
149
+ def _clean_base(name):
150
+ for ch in invalid_chars:
151
+ name = name.replace(ch, replacement)
152
+ return name
153
+
154
+ src_to_dest: dict = {} # absolute source -> staged absolute path
155
+ used_names: dict = {} # staged basename -> source (collision detection)
156
+ copied = 0
157
+ for mesh in root.iter("mesh"):
158
+ ref = mesh.get("filename")
159
+ if ref is None:
160
+ continue
161
+ src = Path(_strip_uri_scheme(ref))
162
+ if str(src) in src_to_dest:
163
+ mesh.set("filename", src_to_dest[str(src)])
164
+ continue
165
+ base = _clean_base(src.name)
166
+ # Disambiguate distinct sources that sanitize to the same basename.
167
+ if base in used_names and used_names[base] != str(src):
168
+ stem, suffix = Path(base).stem, Path(base).suffix
169
+ i = 1
170
+ while f"{stem}_{i}{suffix}" in used_names:
171
+ i += 1
172
+ base = f"{stem}_{i}{suffix}"
173
+ target = dest / base
174
+ if not src.exists():
175
+ raise FileNotFoundError(f"Mesh file referenced by URDF does not exist: {src}")
176
+ shutil.copy2(src, target)
177
+ copied += 1
178
+ used_names[base] = str(src)
179
+ src_to_dest[str(src)] = str(target)
180
+ mesh.set("filename", str(target))
181
+ return copied
182
+
183
+
184
+ def sanitize_names(tree: ET.ElementTree, invalid_chars: str = " ()", replacement: str = "_") -> dict:
185
+ """Replace ``invalid_chars`` (space/paren) with ``replacement`` in every link/joint name and all
186
+ parent/child/mimic references (in place). The importer otherwise renames these silently, breaking
187
+ downstream name matching. Returns the ``{old: new}`` map so callers can update their own references.
188
+ """
189
+ root = tree.getroot()
190
+
191
+ def _clean(name):
192
+ if name is None:
193
+ return None
194
+ out = name
195
+ for ch in invalid_chars:
196
+ out = out.replace(ch, replacement)
197
+ return out
198
+
199
+ renames: dict = {}
200
+ for link in root.findall("link"):
201
+ old = link.get("name")
202
+ new = _clean(old)
203
+ if new != old:
204
+ link.set("name", new)
205
+ renames[old] = new
206
+ for joint in root.findall("joint"):
207
+ old = joint.get("name")
208
+ new = _clean(old)
209
+ if new != old:
210
+ joint.set("name", new)
211
+ renames[old] = new
212
+ for tag in ("parent", "child"):
213
+ el = joint.find(tag)
214
+ if el is not None and el.get("link") is not None:
215
+ el.set("link", _clean(el.get("link")))
216
+ mimic = joint.find("mimic")
217
+ if mimic is not None and mimic.get("joint") is not None:
218
+ mimic.set("joint", _clean(mimic.get("joint")))
219
+ return renames
220
+
221
+
222
+ def set_joint_dynamics(tree: ET.ElementTree, joint_names, **attrs) -> int:
223
+ """Set ``<dynamics>`` attributes (e.g. ``friction=0``) on named joints (in place); returns the count updated."""
224
+ root = tree.getroot()
225
+ names = set(joint_names)
226
+ updated = 0
227
+ for joint in root.findall("joint"):
228
+ if joint.get("name") in names:
229
+ dyn = joint.find("dynamics")
230
+ if dyn is None:
231
+ dyn = ET.SubElement(joint, "dynamics")
232
+ for attr, value in attrs.items():
233
+ dyn.set(attr, str(value))
234
+ updated += 1
235
+ return updated
236
+
237
+
238
+ # Repair for Stretch sg3 gripper fingers shipped with zeroed limits (matches the OG stretch reference).
239
+ STRETCH_FINGER_LIMITS = {
240
+ "joint_gripper_finger_left": {"effort": 100, "lower": -0.6, "upper": 0.6, "velocity": 1.0},
241
+ "joint_gripper_finger_right": {"effort": 100, "lower": -0.6, "upper": 0.6, "velocity": 1.0},
242
+ }
243
+
244
+ # Stretch wheel joints whose axle friction is zeroed to match the OG reference.
245
+ STRETCH_WHEEL_JOINTS = ["joint_left_wheel", "joint_right_wheel"]
246
+
247
+
248
+ def urdf_audit(urdf_path: PathLike) -> dict:
249
+ """Return a deterministic, GPU-free fact sheet for a URDF (XML-aware, so multi-line tags count
250
+ correctly). Non-resolving mesh paths are reported as ``broken`` (never raised); ``package://`` URIs
251
+ counted separately. Keys: ``n_links``, ``n_joints``, ``joint_type_counts``, ``mimic_joints``,
252
+ ``mesh_refs``, ``mesh_formats``, ``package_uris``, ``nonascii_paths``, ``broken_relative_paths``,
253
+ ``links_without_inertial``, ``root_link``.
254
+ """
255
+ urdf_path = Path(urdf_path)
256
+ urdf_dir = urdf_path.parent
257
+ tree = ET.parse(urdf_path)
258
+ root = tree.getroot()
259
+
260
+ links = list(root.findall("link"))
261
+ joints = list(root.findall("joint"))
262
+
263
+ joint_type_counts: dict[str, int] = {}
264
+ mimic_joints = 0
265
+ child_link_names: set[str] = set()
266
+ for joint in joints:
267
+ jtype = joint.get("type", "unknown")
268
+ joint_type_counts[jtype] = joint_type_counts.get(jtype, 0) + 1
269
+ if joint.find("mimic") is not None:
270
+ mimic_joints += 1
271
+ child_el = joint.find("child")
272
+ if child_el is not None and child_el.get("link") is not None:
273
+ child_link_names.add(child_el.get("link"))
274
+
275
+ link_names = [link.get("name") for link in links if link.get("name") is not None]
276
+ links_without_inertial = sum(1 for link in links if link.find("inertial") is None)
277
+
278
+ # The root link is the one never referenced as a joint's child.
279
+ root_candidates = [name for name in link_names if name not in child_link_names]
280
+ root_link: Optional[str] = root_candidates[0] if len(root_candidates) == 1 else None
281
+
282
+ mesh_refs = _mesh_filenames(root)
283
+ mesh_formats: dict[str, int] = {}
284
+ package_uris = 0
285
+ nonascii_paths = 0
286
+ broken_relative_paths = 0
287
+ for ref in mesh_refs:
288
+ ext = Path(_strip_uri_scheme(ref).split("?")[0]).suffix.lower()
289
+ if ext:
290
+ mesh_formats[ext] = mesh_formats.get(ext, 0) + 1
291
+ if not _is_ascii(ref):
292
+ nonascii_paths += 1
293
+ kind = _classify_mesh_ref(ref, urdf_dir)
294
+ if kind == "package":
295
+ package_uris += 1
296
+ elif kind == "broken":
297
+ broken_relative_paths += 1
298
+
299
+ return {
300
+ "n_links": len(links),
301
+ "n_joints": len(joints),
302
+ "joint_type_counts": dict(sorted(joint_type_counts.items())),
303
+ "mimic_joints": mimic_joints,
304
+ "mesh_refs": len(mesh_refs),
305
+ "mesh_formats": dict(sorted(mesh_formats.items())),
306
+ "package_uris": package_uris,
307
+ "nonascii_paths": nonascii_paths,
308
+ "broken_relative_paths": broken_relative_paths,
309
+ "links_without_inertial": links_without_inertial,
310
+ "root_link": root_link,
311
+ }
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/urdfpy_utils.py ADDED
The diff for this file is too large to render. See raw diff
 
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/usd_utils.py ADDED
The diff for this file is too large to render. See raw diff
 
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/omnigibson/utils/vision_utils.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import colorsys
2
+
3
+ import torch as th
4
+ from PIL import Image, ImageDraw
5
+ import omnigibson as og
6
+ import omnigibson.utils.transform_utils as T
7
+ import omnigibson.lazy as lazy
8
+
9
+
10
+ def add_semantic_label(prim, label, instance_name="class"):
11
+ """
12
+ Helper function to add semantic labels to a prim.
13
+ This upgrades the prim semantics to labels and adds the specified label.
14
+
15
+ Args:
16
+ prim: The prim to add labels to
17
+ label (str): The semantic label to add (will be converted to a list internally)
18
+ instance_name (str): The instance name for the label. Defaults to "class"
19
+ """
20
+ with og.sim.editing_usd():
21
+ lazy.isaacsim.core.utils.semantics.upgrade_prim_semantics_to_labels(prim=prim)
22
+ lazy.isaacsim.core.utils.semantics.add_labels(prim=prim, labels=[label], instance_name=instance_name)
23
+
24
+
25
+ class RandomScale:
26
+ """Rescale the input PIL.Image to the given size.
27
+ Args:
28
+ minsize (sequence or int): Desired min output size. If size is a sequence like
29
+ (w, h), output size will be matched to this. If size is an int,
30
+ smaller edge of the image will be matched to this number.
31
+ i.e, if height > width, then image will be rescaled to
32
+ (size * height / width, size)
33
+ maxsize (sequence or int): Desired max output size. If size is a sequence like
34
+ (w, h), output size will be matched to this. If size is an int,
35
+ smaller edge of the image will be matched to this number.
36
+ i.e, if height > width, then image will be rescaled to
37
+ (size * height / width, size)
38
+ interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``
39
+ """
40
+
41
+ def __init__(self, minsize, maxsize, interpolation=Image.BILINEAR):
42
+ assert isinstance(minsize, int)
43
+ assert isinstance(maxsize, int)
44
+ self.minsize = minsize
45
+ self.maxsize = maxsize
46
+ self.interpolation = interpolation
47
+
48
+ def __call__(self, img):
49
+ """
50
+ Args:
51
+ img (PIL.Image): Image to be scaled.
52
+
53
+ Returns:
54
+ PIL.Image: Rescaled image.
55
+ """
56
+
57
+ size = th.randint(self.minsize, self.maxsize + 1)
58
+
59
+ if isinstance(size, int):
60
+ w, h = img.size
61
+ if (w <= h and w == size) or (h <= w and h == size):
62
+ return img
63
+ if w < h:
64
+ ow = size
65
+ oh = int(size * h / w)
66
+ return img.resize((ow, oh), self.interpolation)
67
+ else:
68
+ oh = size
69
+ ow = int(size * w / h)
70
+ return img.resize((ow, oh), self.interpolation)
71
+ else:
72
+ raise NotImplementedError()
73
+
74
+
75
+ class Remapper:
76
+ """
77
+ Remaps values in an image from old_mapping to new_mapping using an efficient key_array.
78
+ See more details in the remap method.
79
+ """
80
+
81
+ def __init__(self):
82
+ self.key_array = None # Will be initialized with the correct device on first use
83
+ self.known_ids = set()
84
+ self.unlabelled_ids = set()
85
+ self.warning_printed = set()
86
+
87
+ def clear(self):
88
+ """Resets the key_array to empty."""
89
+ self.key_array = None # Will be reinitialized with the correct device on next use
90
+ self.known_ids = set()
91
+ self.unlabelled_ids = set()
92
+
93
+ def remap(self, old_mapping, new_mapping, image, image_keys=None):
94
+ """
95
+ Remaps values in the given image from old_mapping to new_mapping using an efficient key_array.
96
+ If the image contains values that are not in old_mapping, they are remapped to the value in new_mapping
97
+ that corresponds to 'unlabelled'.
98
+
99
+ Args:
100
+ old_mapping (dict): The old mapping dictionary that maps a set of image values to labels
101
+ e.g. {1: 'desk', 2: 'chair'}.
102
+ new_mapping (dict): The new mapping dictionary that maps another set of image values to labels,
103
+ e.g. {5: 'desk', 7: 'chair', 100: 'unlabelled'}.
104
+ image (th.tensor): The 2D image to remap, e.g. [[1, 3], [1, 2]].
105
+ image_keys (th.tensor): The unique keys in the image, e.g. [1, 2, 3].
106
+
107
+ Returns:
108
+ th.tensor: The remapped image, e.g. [[5,100],[5,7]].
109
+ dict: The remapped labels dictionary, e.g. {5: 'desk', 7: 'chair', 100: 'unlabelled'}.
110
+ """
111
+ # Make sure that max int32 doesn't match any value in the new mapping
112
+ assert th.all(
113
+ th.tensor(list(new_mapping.keys())) != th.iinfo(th.int32).max
114
+ ), "New mapping contains default unmapped value!"
115
+ image_max_key = max(th.max(image).item(), max(old_mapping.keys()))
116
+
117
+ if self.key_array is None:
118
+ # First time initialization
119
+ self.key_array = th.full((image_max_key + 1,), th.iinfo(th.int32).max, dtype=th.int32, device=image.device)
120
+ else:
121
+ key_array_max_key = len(self.key_array) - 1
122
+ if image_max_key > key_array_max_key:
123
+ prev_key_array = self.key_array.clone()
124
+ # We build a new key array and use max int32 as the default value.
125
+ self.key_array = th.full(
126
+ (image_max_key + 1,), th.iinfo(th.int32).max, dtype=th.int32, device=image.device
127
+ )
128
+ # Copy the previous key array into the new key array
129
+ self.key_array[: len(prev_key_array)] = prev_key_array
130
+
131
+ # Retrospectively inspect our cached ids against the old mapping and update the key array
132
+ updated_ids = set()
133
+ for unlabelled_id in self.unlabelled_ids:
134
+ if unlabelled_id in old_mapping and old_mapping[unlabelled_id] != "unlabelled":
135
+ # If an object was previously unlabelled but now has a label, we need to update the key array
136
+ updated_ids.add(unlabelled_id)
137
+ self.unlabelled_ids -= updated_ids
138
+
139
+ # For updated ids, we need to update their key_array entries and then mark them as known
140
+ for updated_id in updated_ids:
141
+ label = old_mapping[updated_id]
142
+ new_key = next((k for k, v in new_mapping.items() if v == label), None)
143
+ assert new_key is not None, f"Could not find a new key for label {label} in new_mapping!"
144
+ self.key_array[updated_id] = new_key
145
+
146
+ # Add updated ids to known_ids since they now have valid mappings
147
+ self.known_ids.update(updated_ids)
148
+
149
+ # Check if any objects in known_ids have changed their labels and need updating
150
+ changed_known_ids = set()
151
+ for known_id in self.known_ids:
152
+ if known_id in old_mapping:
153
+ # Get the current label from old_mapping
154
+ current_label = old_mapping[known_id]
155
+ # Get the currently mapped value from key_array
156
+ current_mapped_value = self.key_array[known_id].item()
157
+ # Find what label this mapped value corresponds to
158
+ current_mapped_label = None
159
+ for k, v in new_mapping.items():
160
+ if k == current_mapped_value:
161
+ current_mapped_label = v
162
+ break
163
+
164
+ # If the labels don't match, we need to update this known_id
165
+ if current_mapped_label != current_label:
166
+ changed_known_ids.add(known_id)
167
+
168
+ # Update the key_array for changed known_ids
169
+ for changed_id in changed_known_ids:
170
+ label = old_mapping[changed_id]
171
+ new_key = next((k for k, v in new_mapping.items() if v == label), None)
172
+ assert new_key is not None, f"Could not find a new key for label {label} in new_mapping!"
173
+ self.key_array[changed_id] = new_key
174
+
175
+ new_keys = old_mapping.keys() - self.known_ids
176
+
177
+ if new_keys:
178
+ self.known_ids.update(new_keys)
179
+ # Populate key_array with new keys
180
+ for key in new_keys:
181
+ label = old_mapping[key]
182
+ new_key = next((k for k, v in new_mapping.items() if v == label), None)
183
+ assert new_key is not None, f"Could not find a new key for label {label} in new_mapping!"
184
+ self.key_array[key] = new_key
185
+ if label == "unlabelled":
186
+ # Some objects in the image might be unlabelled first but later get a valid label later, so we keep track of them
187
+ self.unlabelled_ids.add(key)
188
+
189
+ # For all the values that exist in the image but not in old_mapping.keys(), we map them to whichever key in
190
+ # new_mapping that equals to 'unlabelled'. This is needed because some values in the image don't necessarily
191
+ # show up in the old_mapping, i.e. particle systems.
192
+ for key in th.unique(image) if image_keys is None else image_keys:
193
+ if key.item() not in old_mapping.keys():
194
+ new_key = next((k for k, v in new_mapping.items() if v == "unlabelled"), None)
195
+ assert new_key is not None, "Could not find a new key for label 'unlabelled' in new_mapping!"
196
+ self.key_array[key] = new_key
197
+
198
+ # Apply remapping
199
+ remapped_img = self.key_array[image]
200
+ # Make sure all values are correctly remapped and not equal to the default value
201
+ assert th.all(remapped_img != th.iinfo(th.int32).max), "Not all keys in the image are in the key array!"
202
+ remapped_labels = {}
203
+ for key in th.unique(remapped_img):
204
+ remapped_labels[key.item()] = new_mapping[key.item()]
205
+
206
+ return remapped_img, remapped_labels
207
+
208
+
209
+ def randomize_colors(N, bright=True):
210
+ """
211
+ Modified from https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/visualize.py#L59
212
+ Generate random colors.
213
+ To get visually distinct colors, generate them in HSV space then
214
+ convert to RGB.
215
+
216
+ Args:
217
+ N (int): Number of colors to generate
218
+
219
+ Returns:
220
+ bright (bool): whether to increase the brightness of the colors or not
221
+ """
222
+ brightness = 1.0 if bright else 0.5
223
+ hsv = [(1.0 * i / N, 1, brightness) for i in range(N)]
224
+ colors = th.tensor(list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)))
225
+ colors = colors[th.randperm(colors.size(0))]
226
+ colors[0] = th.tensor([0, 0, 0], dtype=th.float32) # First color is black
227
+ return colors
228
+
229
+
230
+ def segmentation_to_rgb(seg_im, N, colors=None):
231
+ """
232
+ Helper function to visualize segmentations as RGB frames.
233
+ NOTE: assumes that geom IDs go up to N at most - if not,
234
+ multiple geoms might be assigned to the same color.
235
+
236
+ Args:
237
+ seg_im ((W, H)-array): Segmentation image
238
+ N (int): Maximum segmentation ID from @seg_im
239
+ colors (None or list of 3-array): If specified, colors to apply
240
+ to different segmentation IDs. Otherwise, will be generated randomly
241
+ """
242
+ # ensure all values lie within [0, N]
243
+ seg_im = th.fmod(seg_im, N).cpu()
244
+
245
+ if colors is None:
246
+ use_colors = randomize_colors(N=N, bright=True)
247
+ else:
248
+ use_colors = colors
249
+
250
+ if N <= 256:
251
+ return (255.0 * use_colors[seg_im]).to(th.uint8)
252
+ else:
253
+ return use_colors[seg_im]
254
+
255
+
256
+ def colorize_bboxes_3d(bbox_3d_data, rgb_image, camera_params):
257
+ """
258
+ Project 3D bounding box data onto 2D and colorize the bounding boxes for visualization.
259
+ Reference: https://forums.developer.nvidia.com/t/mathematical-definition-of-3d-bounding-boxes-annotator-nvidia-omniverse-isaac-sim/223416
260
+
261
+ Args:
262
+ bbox_3d_data (th.tensor): 3D bounding box data
263
+ rgb_image (th.tensor): RGB image
264
+ camera_params (dict): Camera parameters
265
+
266
+ Returns:
267
+ th.tensor: RGB image with 3D bounding boxes drawn
268
+ """
269
+
270
+ def world_to_image_pinhole(world_points, camera_params):
271
+ # Project corners to image space (assumes pinhole camera model)
272
+ proj_mat = camera_params["cameraProjection"].reshape(4, 4)
273
+ view_mat = camera_params["cameraViewTransform"].reshape(4, 4)
274
+ view_proj_mat = view_mat @ proj_mat
275
+ world_points_homo = th.nn.functional.pad(world_points, (0, 1, 0, 0), value=1.0)
276
+ tf_points = th.dot(world_points_homo, view_proj_mat)
277
+ tf_points = tf_points / (tf_points[..., -1:])
278
+ return 0.5 * (tf_points[..., :2] + 1)
279
+
280
+ def draw_lines_and_points_for_boxes(img, all_image_points):
281
+ width, height = img.size
282
+ draw = ImageDraw.Draw(img)
283
+
284
+ # Define connections between the corners of the bounding box
285
+ connections = [
286
+ (0, 1),
287
+ (1, 3),
288
+ (3, 2),
289
+ (2, 0), # Front face
290
+ (4, 5),
291
+ (5, 7),
292
+ (7, 6),
293
+ (6, 4), # Back face
294
+ (0, 4),
295
+ (1, 5),
296
+ (2, 6),
297
+ (3, 7), # Side edges connecting front and back faces
298
+ ]
299
+
300
+ # Calculate the number of bounding boxes
301
+ num_boxes = len(all_image_points) // 8
302
+
303
+ # Generate random colors for each bounding box
304
+ from omni.replicator.core import random_colours
305
+
306
+ box_colors = random_colours(num_boxes, enable_random=True, num_channels=3)
307
+
308
+ # Ensure colors are in the correct format for drawing (255 scale)
309
+ box_colors = [(int(r), int(g), int(b)) for r, g, b in box_colors]
310
+
311
+ # Iterate over each set of 8 points (each bounding box)
312
+ for i in range(0, len(all_image_points), 8):
313
+ image_points = all_image_points[i : i + 8]
314
+ image_points[:, 1] = height - image_points[:, 1] # Flip Y-axis to match image coordinates
315
+
316
+ # Use a distinct color for each bounding box
317
+ line_color = box_colors[i // 8]
318
+
319
+ # Draw lines for each connection
320
+ for start, end in connections:
321
+ draw.line(
322
+ (image_points[start][0], image_points[start][1], image_points[end][0], image_points[end][1]),
323
+ fill=line_color,
324
+ width=2,
325
+ )
326
+
327
+ rgb = Image.fromarray(rgb_image)
328
+
329
+ # Get 3D corners
330
+ from omni.syntheticdata.scripts.helpers import get_bbox_3d_corners
331
+
332
+ corners_3d = get_bbox_3d_corners(bbox_3d_data)
333
+ corners_3d = corners_3d.reshape(-1, 3)
334
+
335
+ # Project to image space
336
+ corners_2d = world_to_image_pinhole(corners_3d, camera_params)
337
+ width, height = rgb.size
338
+ corners_2d *= th.tensor([[width, height]])
339
+
340
+ # Now, draw all bounding boxes
341
+ draw_lines_and_points_for_boxes(rgb, corners_2d)
342
+
343
+ return th.tensor(rgb)
344
+
345
+
346
+ def change_pcd_frame(pcd: th.Tensor, rel_pose: th.Tensor) -> th.Tensor:
347
+ """
348
+ Transform point cloud from one frame to another frame.
349
+
350
+ Args:
351
+ pcd: (N, 6) point cloud tensor in world frame
352
+ rel_pose: (7) relative pose tensor [pos, quat] from current to target frame
353
+ Returns:
354
+ th.Tensor: (B, N, 6) point cloud tensor in target frame
355
+ """
356
+ rel_pos = rel_pose[:3]
357
+ rel_quat = rel_pose[3:]
358
+ rel_rot = T.quat2mat(rel_quat)
359
+
360
+ # Create transformation matrix
361
+ tf = th.eye(4)
362
+ tf[:3, :3] = rel_rot
363
+ tf[:3, 3] = rel_pos
364
+
365
+ # Add homogeneous coordinate to point cloud
366
+ xyz = pcd[..., 3:] # (N, 3)
367
+ xyz_homo = th.cat([xyz, th.ones_like(xyz[..., :1])], dim=-1) # (N, 4)
368
+
369
+ # Transform point cloud from camera frame to base frame
370
+ new_xyz = th.matmul(xyz_homo, th.inverse(tf).T) # (N, 4)
371
+ pcd[..., 3:] = new_xyz[..., :3]
372
+ return pcd
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/pyproject.toml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.pyright]
2
+ exclude = [
3
+ 'omnigibson/data',
4
+ 'omnigibson/docs',
5
+ 'omnigibson/docker'
6
+ ]
7
+
8
+ [tool.pytest.ini_options]
9
+ testpaths = [
10
+ "tests",
11
+ ]
12
+
13
+ [tool.ruff]
14
+ # Exclude a variety of commonly ignored directories.
15
+ extend-exclude = ["omnigibson/utils/pynvml_utils.py", "omnigibson/data"]
16
+
17
+ # Same as Black.
18
+ line-length = 120
19
+ indent-width = 4
20
+
21
+ # Assume Python 3.10
22
+ target-version = "py310"
23
+
24
+ [tool.ruff.lint]
25
+ # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
26
+ # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
27
+ # McCabe complexity (`C901`) by default.
28
+ select = ["E4", "E7", "E9", "F"]
29
+ ignore = [
30
+ "E731", # lambda expressions assigned to variables. this keeps some files short.
31
+ "E722", # bare except. We don't want to dig deep to find what exception is being raised.
32
+ "E741", # ambiguous variable name for the character 'l', but we use it a lot for length.
33
+ ]
34
+
35
+ [tool.ruff.format]
36
+ # Enable auto-formatting of code examples in docstrings. Markdown,
37
+ # reStructuredText code/literal blocks and doctests are all supported.
38
+ docstring-code-format = true
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/build_docs.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # Remove source directory and copy over source files to docs folder
4
+ rm -rf docs/src
5
+ mkdir docs/src
6
+ cp -r omnigibson/* docs/src
7
+
8
+ # Update code source references
9
+ rm -rf docs/reference
10
+ python docs/gen_ref_pages.py
11
+
12
+ # Build the docs (written to ./site)
13
+ mkdocs build
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/aggregate_lerobot_task_shards.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Aggregate completed LeRobot v3 replay shards into one dataset per task."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import os
10
+ import shutil
11
+ from pathlib import Path
12
+
13
+ import pandas as pd
14
+ from lerobot.datasets.aggregate import aggregate_datasets
15
+
16
+
17
+ def ensure_shared_permissions(path: Path) -> None:
18
+ resolved = path.resolve()
19
+ try:
20
+ resolved.relative_to("/vision/group/behavior")
21
+ except ValueError:
22
+ return
23
+
24
+ shutil.chown(resolved, group="behavior")
25
+ for child in resolved.rglob("*"):
26
+ shutil.chown(child, group="behavior")
27
+ mode = child.stat().st_mode
28
+ if child.is_dir():
29
+ child.chmod(mode | 0o2770)
30
+ else:
31
+ child.chmod(mode | 0o660)
32
+ resolved.chmod(resolved.stat().st_mode | 0o2770)
33
+
34
+
35
+ def load_task_mapping(data_root: Path) -> dict[str, int]:
36
+ task_mapping = {}
37
+ task_misc_path = data_root / "2026-challenge-task-instances" / "metadata" / "B100_task_misc.csv"
38
+ with task_misc_path.open(newline="", encoding="utf-8") as f:
39
+ for row in csv.DictReader(f):
40
+ task_mapping[row["Task"]] = int(row["Task ID"])
41
+
42
+ return task_mapping
43
+
44
+
45
+ def parse_task_names(args: argparse.Namespace, task_mapping: dict[str, int]) -> list[str]:
46
+ if args.task_names_file:
47
+ names = [
48
+ line.strip()
49
+ for line in Path(args.task_names_file).read_text().splitlines()
50
+ if line.strip() and not line.strip().startswith("#")
51
+ ]
52
+ elif args.tasks:
53
+ names = [name.strip() for name in args.tasks.split(",") if name.strip()]
54
+ else:
55
+ names = [name for name, _ in sorted(task_mapping.items(), key=lambda item: item[1])]
56
+
57
+ unknown = sorted(set(names) - set(task_mapping))
58
+ if task_mapping and unknown:
59
+ raise ValueError(f"Unknown task names: {unknown}")
60
+ if not task_mapping and not names:
61
+ raise RuntimeError("No task names provided and no challenge task metadata found")
62
+ return names
63
+
64
+
65
+ def shard_repo_id(task_name: str, shard_index: int) -> str:
66
+ return f"b1k_shards/{task_name}/shard-{shard_index:03d}"
67
+
68
+
69
+ def shard_complete(lerobot_shards_root: Path, task_name: str, shard_index: int) -> bool:
70
+ return (lerobot_shards_root / ".replay_status" / task_name / f"shard-{shard_index:03d}" / "complete").exists()
71
+
72
+
73
+ def episode_complete(lerobot_shards_root: Path, task_name: str, episode_root: Path) -> bool:
74
+ demo_id = episode_root.name.removeprefix("episode_")
75
+ return (lerobot_shards_root / ".replay_status" / task_name / f"shard-ep-{demo_id}" / "complete").exists()
76
+
77
+
78
+ def discover_inputs(args: argparse.Namespace, task_name: str) -> tuple[list[str], list[Path], list[str]]:
79
+ lerobot_shards_root = Path(args.lerobot_shards_root).resolve()
80
+
81
+ if args.per_episode:
82
+ shard_root = lerobot_shards_root / "b1k_shards" / task_name
83
+ roots = sorted(shard_root.glob("episode_*"))
84
+ missing = [
85
+ root.name
86
+ for root in roots
87
+ if args.require_complete and not episode_complete(lerobot_shards_root, task_name, root)
88
+ ]
89
+ repo_ids = [f"b1k_shards/{task_name}/{root.name}" for root in roots]
90
+ else:
91
+ repo_ids = [shard_repo_id(task_name, shard_index) for shard_index in range(args.num_shards)]
92
+ roots = [lerobot_shards_root / repo_id for repo_id in repo_ids]
93
+ missing = [
94
+ str(shard_index)
95
+ for shard_index, root in enumerate(roots)
96
+ if not root.exists()
97
+ or (args.require_complete and not shard_complete(lerobot_shards_root, task_name, shard_index))
98
+ ]
99
+
100
+ if args.expected_episodes is not None and len(roots) != args.expected_episodes:
101
+ missing.append(f"expected {args.expected_episodes} inputs, found {len(roots)}")
102
+
103
+ missing.extend(str(root) for root in roots if not root.exists())
104
+ return repo_ids, roots, missing
105
+
106
+
107
+ def verify_aggregate(output_root: Path, expected_episodes: int | None, require_packed: bool) -> None:
108
+ info_path = output_root / "meta" / "info.json"
109
+ if not info_path.exists():
110
+ raise FileNotFoundError(f"Missing {info_path}")
111
+
112
+ info = json.loads(info_path.read_text())
113
+ total_episodes = int(info.get("total_episodes", -1))
114
+ if expected_episodes is not None and total_episodes != expected_episodes:
115
+ raise RuntimeError(f"Expected {expected_episodes} episodes, got {total_episodes}")
116
+
117
+ episodes_path = output_root / "meta" / "episodes" / "chunk-000" / "file-000.parquet"
118
+ if not episodes_path.exists():
119
+ raise FileNotFoundError(f"Missing {episodes_path}")
120
+ episodes = pd.read_parquet(episodes_path)
121
+ if expected_episodes is not None and len(episodes) != expected_episodes:
122
+ raise RuntimeError(f"Expected {expected_episodes} episode rows, got {len(episodes)}")
123
+
124
+ data_files = list((output_root / "data").rglob("*.parquet"))
125
+ video_files = list((output_root / "videos").rglob("*.mp4"))
126
+ if not data_files:
127
+ raise RuntimeError("Aggregate has no data parquet files")
128
+ video_keys = sorted(
129
+ {
130
+ column.removeprefix("videos/").removesuffix("/chunk_index")
131
+ for column in episodes.columns
132
+ if column.startswith("videos/") and column.endswith("/chunk_index")
133
+ }
134
+ )
135
+ if video_keys and not video_files:
136
+ raise RuntimeError("Aggregate has video keys but no video files")
137
+
138
+ def format_ref(pattern: str, **values: int | str) -> str:
139
+ return pattern.format(**values)
140
+
141
+ data_refs = set()
142
+ if "data/file_path" in episodes.columns:
143
+ data_refs = set(episodes["data/file_path"].dropna().astype(str))
144
+ elif {"data/chunk_index", "data/file_index"}.issubset(episodes.columns):
145
+ data_pattern = info.get("data_path") or "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet"
146
+ for _, row in episodes[["data/chunk_index", "data/file_index"]].drop_duplicates().iterrows():
147
+ data_refs.add(
148
+ format_ref(
149
+ data_pattern,
150
+ chunk_index=int(row["data/chunk_index"]),
151
+ file_index=int(row["data/file_index"]),
152
+ )
153
+ )
154
+ else:
155
+ raise RuntimeError("Episode metadata does not contain data file references")
156
+
157
+ missing_refs = [ref for ref in sorted(data_refs) if not (output_root / ref).exists()]
158
+
159
+ video_refs = set()
160
+ file_path_cols = [col for col in episodes.columns if col.startswith("videos/") and col.endswith("/file_path")]
161
+ for col in file_path_cols:
162
+ video_refs.update(episodes[col].dropna().astype(str))
163
+
164
+ video_pattern = info.get("video_path") or "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4"
165
+ for video_key in video_keys:
166
+ chunk_col = f"videos/{video_key}/chunk_index"
167
+ file_col = f"videos/{video_key}/file_index"
168
+ if not {chunk_col, file_col}.issubset(episodes.columns):
169
+ continue
170
+ for _, row in episodes[[chunk_col, file_col]].dropna().drop_duplicates().iterrows():
171
+ video_refs.add(
172
+ format_ref(
173
+ video_pattern,
174
+ video_key=video_key,
175
+ chunk_index=int(row[chunk_col]),
176
+ file_index=int(row[file_col]),
177
+ )
178
+ )
179
+
180
+ missing_refs.extend(ref for ref in sorted(video_refs) if not (output_root / ref).exists())
181
+ if missing_refs:
182
+ raise RuntimeError(f"Missing {len(missing_refs)} referenced files, examples: {missing_refs[:5]}")
183
+
184
+ if require_packed and expected_episodes is not None:
185
+ if len(data_files) >= expected_episodes:
186
+ raise RuntimeError(f"Data files are not packed: {len(data_files)} files for {expected_episodes} episodes")
187
+ if video_keys and len(video_files) >= expected_episodes * len(video_keys):
188
+ raise RuntimeError(
189
+ f"Video files are not packed: {len(video_files)} files for {expected_episodes} episodes "
190
+ f"and {len(video_keys)} video keys"
191
+ )
192
+
193
+
194
+ def aggregate_task(args: argparse.Namespace, task_name: str) -> None:
195
+ output_root = Path(args.output_root).resolve() / "b1k" / task_name
196
+ repo_ids, roots, missing = discover_inputs(args, task_name)
197
+ if missing:
198
+ print(f"skip {task_name}: missing/incomplete shards {missing}")
199
+ return
200
+
201
+ print(f"{'aggregate' if args.run else 'dry-run aggregate'} {task_name}: {len(repo_ids)} shards -> {output_root}")
202
+ if not args.run:
203
+ return
204
+
205
+ if output_root.exists():
206
+ if not args.overwrite:
207
+ raise FileExistsError(f"Output dataset already exists: {output_root}")
208
+ shutil.rmtree(output_root)
209
+
210
+ aggregate_datasets(
211
+ repo_ids=repo_ids,
212
+ roots=roots,
213
+ aggr_repo_id=f"b1k/{task_name}",
214
+ aggr_root=output_root,
215
+ data_files_size_in_mb=args.data_files_size_in_mb,
216
+ video_files_size_in_mb=args.video_files_size_in_mb,
217
+ )
218
+ if args.verify:
219
+ verify_aggregate(output_root, args.expected_episodes, args.require_packed)
220
+ ensure_shared_permissions(output_root)
221
+
222
+
223
+ def main() -> None:
224
+ os.umask(0o002)
225
+ default_repo_root = Path(__file__).resolve().parents[3]
226
+ parser = argparse.ArgumentParser(description=__doc__)
227
+ parser.add_argument("--repo_root", default=str(default_repo_root))
228
+ parser.add_argument("--data_root", default=os.environ.get("OMNIGIBSON_DATA_PATH", "/vision/group/behavior"))
229
+ parser.add_argument("--lerobot_shards_root", required=True)
230
+ parser.add_argument("--output_root", required=True)
231
+ parser.add_argument("--tasks", default="", help="Comma-separated task names. Defaults to all tasks.")
232
+ parser.add_argument("--task_names_file", default="")
233
+ parser.add_argument("--num_shards", type=int, default=20)
234
+ parser.add_argument("--per_episode", action="store_true", help="Aggregate b1k_shards/<task>/episode_* roots.")
235
+ parser.add_argument("--expected_episodes", type=int, default=None)
236
+ parser.add_argument("--data_files_size_in_mb", type=int, default=None)
237
+ parser.add_argument("--video_files_size_in_mb", type=int, default=None)
238
+ parser.add_argument("--verify", action="store_true", help="Verify metadata references after aggregation.")
239
+ parser.add_argument(
240
+ "--require_packed", action="store_true", help="Fail verification if output remains one-file-per-episode."
241
+ )
242
+ parser.add_argument("--require_complete", action="store_true", default=True)
243
+ parser.add_argument("--allow_incomplete", action="store_false", dest="require_complete")
244
+ parser.add_argument("--overwrite", action="store_true")
245
+ parser.add_argument("--run", action="store_true", help="Actually aggregate. Default is dry-run.")
246
+ args = parser.parse_args()
247
+
248
+ task_mapping = load_task_mapping(Path(args.data_root).resolve())
249
+ for task_name in parse_task_names(args, task_mapping):
250
+ aggregate_task(args, task_name)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main()
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/benchmark.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ B1K LeRobot benchmark for the current upstream-depth integration path.
3
+
4
+ This is a focused counterpart to ``outputs/benchmark.py``. The original script
5
+ benchmarks many historical encoding variants laid out in the challenge-demo
6
+ ``videos/task-*`` tree. This script targets the current B1K integration combo:
7
+
8
+ - RGB: LeRobotDataset video features encoded by ``VideoEncoderConfig``
9
+ - Depth: LeRobotDataset depth video features encoded by ``DepthEncoderConfig``
10
+
11
+ It uses the official ``lerobot.datasets.LeRobotDataset`` read path for random
12
+ access speed and compares decoded depth frames against the original replay HDF5
13
+ observations for reconstruction error.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import time
21
+ from pathlib import Path
22
+
23
+ import h5py
24
+ import numpy as np
25
+ from lerobot.datasets import LeRobotDataset
26
+ from tqdm import tqdm
27
+
28
+
29
+ CAMERA_PREFIXES: dict[str, str] = {
30
+ "observation.depth_linear.left_realsense_link_camera_0": "robot_r1::robot_r1:left_realsense_link:Camera:0",
31
+ "observation.depth_linear.right_realsense_link_camera_0": "robot_r1::robot_r1:right_realsense_link:Camera:0",
32
+ "observation.depth_linear.zed_link_camera_0": "robot_r1::robot_r1:zed_link:Camera:0",
33
+ }
34
+
35
+ STAT_KEYS = ("mean", "median", "std", "min", "max", "p01", "p05", "p25", "p75", "p95", "p99")
36
+
37
+
38
+ def _stats(values: np.ndarray) -> dict[str, float]:
39
+ return {
40
+ "mean": float(np.mean(values)),
41
+ "median": float(np.median(values)),
42
+ "std": float(np.std(values)),
43
+ "min": float(np.min(values)),
44
+ "max": float(np.max(values)),
45
+ "p01": float(np.percentile(values, 1)),
46
+ "p05": float(np.percentile(values, 5)),
47
+ "p25": float(np.percentile(values, 25)),
48
+ "p75": float(np.percentile(values, 75)),
49
+ "p95": float(np.percentile(values, 95)),
50
+ "p99": float(np.percentile(values, 99)),
51
+ }
52
+
53
+
54
+ def _as_numpy_frame(value) -> np.ndarray:
55
+ if hasattr(value, "detach"):
56
+ value = value.detach().cpu().numpy()
57
+ else:
58
+ value = np.asarray(value)
59
+ if value.ndim == 3 and value.shape[0] == 1:
60
+ value = value[0]
61
+ return value.astype(np.float32, copy=False)
62
+
63
+
64
+ def _depth_unit(dataset: LeRobotDataset, depth_key: str) -> str:
65
+ feature_info = dataset.meta.features[depth_key].get("info") or {}
66
+ unit = feature_info.get("video.output_unit")
67
+ if unit is None:
68
+ raise ValueError(f"Depth feature {depth_key} is missing info['video.output_unit']")
69
+ if unit not in {"m", "mm"}:
70
+ raise ValueError(f"Unsupported depth unit for {depth_key}: {unit!r}")
71
+ return unit
72
+
73
+
74
+ def _to_meters(depth: np.ndarray, unit: str) -> np.ndarray:
75
+ if unit == "m":
76
+ return depth
77
+ return depth / 1000.0
78
+
79
+
80
+ def _resolve_hdf5_path(args: argparse.Namespace) -> Path:
81
+ if args.hdf5_path is not None:
82
+ return Path(args.hdf5_path).expanduser()
83
+
84
+ data_root = Path(args.data_folder).expanduser()
85
+ replayed = data_root / "replayed" / f"episode_{args.demo_id:08d}.hdf5"
86
+ if replayed.exists():
87
+ return replayed
88
+
89
+ raw_root = data_root / "2026-challenge-rawdata"
90
+ if args.task_id is not None:
91
+ return raw_root / f"task-{args.task_id:04d}" / f"episode_{args.demo_id:08d}.hdf5"
92
+
93
+ matches = sorted(raw_root.glob(f"task-*/episode_{args.demo_id:08d}.hdf5"))
94
+ if not matches:
95
+ raise FileNotFoundError(f"No episode_{args.demo_id:08d}.hdf5 found under {raw_root}/task-*")
96
+ if len(matches) > 1:
97
+ task_hint = args.task_name.replace("_", " ") if args.task_name else None
98
+ raise ValueError(
99
+ f"Found multiple HDF5 matches for demo_id={args.demo_id}: {matches}. "
100
+ f"Pass --task_id or --hdf5_path explicitly. task_name hint was {task_hint!r}."
101
+ )
102
+ return matches[0]
103
+
104
+
105
+ def _select_hdf5_demo(f: h5py.File) -> str:
106
+ demos = list(f["data"].keys())
107
+ return max(demos, key=lambda key: f["data"][key].attrs.get("num_samples", 0))
108
+
109
+
110
+ def _valid_depth_indices(obs: h5py.Group, hdf5_keys: list[str], max_len: int) -> np.ndarray:
111
+ valid_indices = []
112
+ for idx in range(max_len):
113
+ valid = True
114
+ for hdf5_key in hdf5_keys:
115
+ frame = np.asarray(obs[hdf5_key][idx])
116
+ if not np.isfinite(frame).all() or float(np.abs(frame).max()) == 0.0:
117
+ valid = False
118
+ break
119
+ if valid:
120
+ valid_indices.append(idx)
121
+
122
+ if not valid_indices:
123
+ raise ValueError("No valid nonzero HDF5 depth frames found for reconstruction benchmark.")
124
+ return np.asarray(valid_indices, dtype=np.int64)
125
+
126
+
127
+ def _dataset_summary(dataset: LeRobotDataset) -> None:
128
+ print("=" * 100)
129
+ print("Dataset")
130
+ print("=" * 100)
131
+ print(f"root : {dataset.root}")
132
+ print(f"frames : {dataset.num_frames}")
133
+ print(f"episodes : {dataset.num_episodes}")
134
+ print(f"video keys : {len(dataset.meta.video_keys)}")
135
+ print(f"depth keys : {dataset.meta.depth_keys}")
136
+ print(f"git hash : {dataset.meta.info.get('omnigibson_git_hash')}")
137
+ print(f"intrinsics : {sorted((dataset.meta.info.get('cam_intrinsics') or {}).keys())}")
138
+
139
+ print("\nVideo feature metadata:")
140
+ for key in dataset.meta.video_keys:
141
+ info = dataset.meta.features[key].get("info") or {}
142
+ print(
143
+ f" {key}: codec={info.get('video.codec')} pix_fmt={info.get('video.pix_fmt')} "
144
+ f"g={info.get('video.g')} crf={info.get('video.crf')} depth={info.get('is_depth_map', False)} "
145
+ f"output_unit={info.get('video.output_unit')}"
146
+ )
147
+
148
+
149
+ def benchmark_random_access_speed(dataset: LeRobotDataset, sample_count: int, seed: int) -> dict[str, float]:
150
+ print("\n" + "=" * 100)
151
+ print("Benchmark 1: LeRobotDataset Random-Access Decode Speed")
152
+ print("=" * 100)
153
+ rng = np.random.default_rng(seed)
154
+ n = min(sample_count, len(dataset))
155
+ indices = rng.permutation(len(dataset))[:n]
156
+
157
+ # Warm one item so any lazy decoder state is initialized outside the timed loop.
158
+ _ = dataset[int(indices[0])]
159
+
160
+ t0 = time.perf_counter()
161
+ for idx in tqdm(indices, desc="LeRobotDataset __getitem__", leave=False):
162
+ _ = dataset[int(idx)]
163
+ elapsed = time.perf_counter() - t0
164
+ fps = n / elapsed
165
+ print(f"samples : {n}")
166
+ print(f"elapsed_s : {elapsed:.3f}")
167
+ print(f"samples/s : {fps:.2f}")
168
+ return {"samples": float(n), "elapsed_s": elapsed, "samples_per_s": fps}
169
+
170
+
171
+ def benchmark_depth_reconstruction(
172
+ dataset: LeRobotDataset,
173
+ hdf5_path: Path,
174
+ sample_count: int,
175
+ seed: int,
176
+ ) -> dict[str, dict[str, float]]:
177
+ print("\n" + "=" * 130)
178
+ print("Benchmark 2: Depth Reconstruction Error vs HDF5 Ground Truth")
179
+ print("=" * 130)
180
+ print(f"hdf5 : {hdf5_path}")
181
+
182
+ rng = np.random.default_rng(seed)
183
+ results: dict[str, dict[str, float]] = {}
184
+ with h5py.File(hdf5_path, "r") as f:
185
+ demo_key = _select_hdf5_demo(f)
186
+ if "obs" not in f["data"][demo_key]:
187
+ raise KeyError(
188
+ f"{hdf5_path} has no data/{demo_key}/obs group. "
189
+ "Use a replayed observation HDF5, e.g. data_folder/replayed/episode_*.hdf5."
190
+ )
191
+ obs = f["data"][demo_key]["obs"]
192
+ print(f"demo : {demo_key}")
193
+
194
+ depth_to_hdf5_key = {}
195
+ for depth_key in dataset.meta.depth_keys:
196
+ prefix = CAMERA_PREFIXES.get(depth_key)
197
+ if prefix is None:
198
+ print(f"[WARN] No HDF5 camera mapping for {depth_key}; skipping")
199
+ continue
200
+ hdf5_key = f"{prefix}::depth_linear"
201
+ if hdf5_key not in obs:
202
+ print(f"[WARN] Missing HDF5 key {hdf5_key}; skipping")
203
+ continue
204
+ depth_to_hdf5_key[depth_key] = hdf5_key
205
+
206
+ valid_indices = _valid_depth_indices(obs, list(depth_to_hdf5_key.values()), len(dataset))
207
+ n = min(sample_count, len(valid_indices))
208
+ indices = rng.permutation(valid_indices)[:n]
209
+ print(f"valid frames: {len(valid_indices)} / {len(dataset)}")
210
+ print(f"samples : {n}")
211
+ results["_summary"] = {
212
+ "valid_frames": float(len(valid_indices)),
213
+ "total_frames": float(len(dataset)),
214
+ "samples": float(n),
215
+ }
216
+
217
+ header = f"{'depth_key':<58} {'samples':>8}"
218
+ for stat in STAT_KEYS:
219
+ header += f" {stat:>10}"
220
+ print(header)
221
+ print("-" * len(header))
222
+
223
+ for depth_key, hdf5_key in depth_to_hdf5_key.items():
224
+ errors: list[np.ndarray] = []
225
+ for idx in tqdm(indices, desc=depth_key, leave=False):
226
+ idx = int(idx)
227
+ item = dataset[idx]
228
+ decoded = _to_meters(_as_numpy_frame(item[depth_key]), _depth_unit(dataset, depth_key))
229
+ gt = np.asarray(obs[hdf5_key][idx], dtype=np.float32)
230
+ errors.append(np.abs(decoded - gt).ravel())
231
+
232
+ err = np.concatenate(errors)
233
+ stats = _stats(err)
234
+ results[depth_key] = stats
235
+ row = f"{depth_key:<58} {n:>8}"
236
+ for stat in STAT_KEYS:
237
+ row += f" {stats[stat]:>10.6f}"
238
+ print(row)
239
+
240
+ return results
241
+
242
+
243
+ def main() -> None:
244
+ parser = argparse.ArgumentParser(
245
+ description="Benchmark current B1K LeRobot streaming decode and depth reconstruction."
246
+ )
247
+ parser.add_argument("--root", default="/home/wsai/Documents/Files/behavior/lerobot/b1k/turning_on_radio")
248
+ parser.add_argument("--repo_id", default="b1k/turning_on_radio")
249
+ parser.add_argument("--data_folder", default="/home/wsai/Documents/Files/behavior")
250
+ parser.add_argument("--task_name", default="turning_on_radio")
251
+ parser.add_argument("--task_id", type=int, default=None)
252
+ parser.add_argument("--demo_id", type=int, default=10)
253
+ parser.add_argument("--hdf5_path", default=None)
254
+ parser.add_argument("--video_backend", default="pyav")
255
+ parser.add_argument("--speed_samples", type=int, default=256)
256
+ parser.add_argument("--error_samples", type=int, default=128)
257
+ parser.add_argument("--seed", type=int, default=42)
258
+ parser.add_argument("--json", default=None, help="Optional path to write machine-readable results.")
259
+ args = parser.parse_args()
260
+
261
+ dataset = LeRobotDataset(repo_id=args.repo_id, root=Path(args.root).expanduser(), video_backend=args.video_backend)
262
+ hdf5_path = _resolve_hdf5_path(args)
263
+ if not hdf5_path.exists():
264
+ raise FileNotFoundError(hdf5_path)
265
+
266
+ _dataset_summary(dataset)
267
+ speed = benchmark_random_access_speed(dataset, args.speed_samples, args.seed)
268
+ depth = benchmark_depth_reconstruction(dataset, hdf5_path, args.error_samples, args.seed)
269
+
270
+ result = {"speed": speed, "depth_reconstruction": depth}
271
+ if args.json is not None:
272
+ out = Path(args.json).expanduser()
273
+ out.parent.mkdir(parents=True, exist_ok=True)
274
+ out.write_text(json.dumps(result, indent=2))
275
+ print(f"\nWrote JSON results to {out}")
276
+
277
+
278
+ if __name__ == "__main__":
279
+ main()
source_data/pinned/behavior-1k-bddl/v3.9.3-post2/OmniGibson/scripts/learning/download_gcs_rawdata.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Download BEHAVIOR raw HDF5 demos from GCS into the challenge raw-data layout."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import os
9
+ import shutil
10
+ import signal
11
+ import subprocess
12
+ import urllib.parse
13
+ import urllib.request
14
+ import uuid
15
+ from concurrent.futures import ThreadPoolExecutor, as_completed
16
+ from pathlib import Path
17
+
18
+
19
+ DEFAULT_BUCKET_URI = "gs://behavior-demos"
20
+ DEFAULT_TARGET_ROOT = "/vision/group/behavior/2026-challenge-rawdata"
21
+ DEFAULT_SOURCE_TEMPLATE = "{bucket_uri}/task-{task_id:04d}/episode_{episode_id}.hdf5"
22
+
23
+
24
+ def format_episode_id(task_id: int, instance_id: int) -> str:
25
+ if task_id >= 50:
26
+ return f"{task_id:04d}{instance_id:03d}0"
27
+ return f"{task_id:04d}{instance_id:04d}"
28
+
29
+
30
+ def parse_ids(value: str) -> list[int]:
31
+ ids = []
32
+ for item in value.split(","):
33
+ item = item.strip()
34
+ if not item:
35
+ continue
36
+ ids.append(int(item))
37
+ return ids
38
+
39
+
40
+ def load_instance_ids(args: argparse.Namespace) -> list[int]:
41
+ if args.instance_ids:
42
+ return parse_ids(args.instance_ids)
43
+ if args.instance_ids_file:
44
+ ids = []
45
+ for line in Path(args.instance_ids_file).read_text().splitlines():
46
+ line = line.strip()
47
+ if not line or line.startswith("#"):
48
+ continue
49
+ ids.append(int(line.split(",")[0]))
50
+ return ids
51
+ return [args.first_instance_id + i * args.instance_stride for i in range(args.num_instances)]
52
+
53
+
54
+ def load_manifest_jobs(args: argparse.Namespace) -> list[tuple[int, str, str, Path]]:
55
+ jobs = []
56
+ bucket_uri = args.bucket_uri.rstrip("/")
57
+ task_dir = Path(args.target_root) / f"task-{args.task_id:04d}"
58
+ with Path(args.gcs_manifest_csv).open(newline="") as f:
59
+ reader = csv.DictReader(f)
60
+ for row in reader:
61
+ task_id = int(row["task_id"])
62
+ if task_id != args.task_id:
63
+ continue
64
+ instance_id = int(row["instance_id"])
65
+ episode_id = row.get("episode_id") or format_episode_id(task_id, instance_id)
66
+ object_name = row.get("object") or row.get("source")
67
+ if object_name is None:
68
+ raise ValueError(f"Manifest row lacks object/source column: {row}")
69
+ source = object_name if object_name.startswith("gs://") else f"{bucket_uri}/{object_name}"
70
+ dest = task_dir / f"episode_{episode_id}.hdf5"
71
+ jobs.append((instance_id, episode_id, source, dest))
72
+ return jobs
73
+
74
+
75
+ def resolve_tool(tool: str) -> str:
76
+ if tool in {"python", "python-gcs", "gcs-python"}:
77
+ return "python-gcs"
78
+ if tool != "auto":
79
+ return tool
80
+ for candidate in ("gcloud", "gsutil"):
81
+ path = shutil.which(candidate)
82
+ if path:
83
+ return path
84
+ return "python-gcs"
85
+
86
+
87
+ def parse_gs_uri(uri: str) -> tuple[str, str]:
88
+ if not uri.startswith("gs://"):
89
+ raise ValueError(f"Expected gs:// URI, got: {uri}")
90
+ bucket_and_object = uri[len("gs://") :]
91
+ bucket, _, object_name = bucket_and_object.partition("/")
92
+ if not bucket or not object_name:
93
+ raise ValueError(f"Expected gs://bucket/object URI, got: {uri}")
94
+ return bucket, object_name
95
+
96
+
97
+ class PythonGCSClient:
98
+ def __init__(self, credentials_path: str = "") -> None:
99
+ import google.auth
100
+ from google.auth.transport.requests import Request
101
+
102
+ scopes = ["https://www.googleapis.com/auth/devstorage.read_only"]
103
+ if credentials_path:
104
+ from google.auth import load_credentials_from_file
105
+
106
+ self.credentials, _ = load_credentials_from_file(credentials_path, scopes=scopes)
107
+ else:
108
+ self.credentials, _ = google.auth.default(scopes=scopes)
109
+ self.request = Request()
110
+
111
+ def _headers(self) -> dict[str, str]:
112
+ if not self.credentials.valid:
113
+ self.credentials.refresh(self.request)
114
+ return {"Authorization": f"Bearer {self.credentials.token}"}
115
+
116
+ def download(self, source: str, dest: Path) -> None:
117
+ bucket, object_name = parse_gs_uri(source)
118
+ encoded_object = urllib.parse.quote(object_name, safe="")
119
+ url = f"https://storage.googleapis.com/download/storage/v1/b/{bucket}/o/{encoded_object}?alt=media"
120
+ req = urllib.request.Request(url, headers=self._headers())
121
+ with urllib.request.urlopen(req, timeout=120) as response, dest.open("wb") as f:
122
+ shutil.copyfileobj(response, f, length=1024 * 1024)
123
+
124
+
125
+ def build_copy_command(tool: str, source: str, dest: Path) -> list[str]:
126
+ name = Path(tool).name
127
+ if name == "gsutil":
128
+ return [tool, "-q", "cp", source, str(dest)]
129
+ return [tool, "storage", "cp", "--quiet", source, str(dest)]
130
+
131
+
132
+ def chmod_group_writable(path: Path) -> None:
133
+ try:
134
+ path.chmod(0o664)
135
+ except PermissionError:
136
+ pass
137
+
138
+
139
+ def download_one(
140
+ tool: str,
141
+ client: PythonGCSClient | None,
142
+ source: str,
143
+ dest: Path,
144
+ dry_run: bool,
145
+ ) -> tuple[str, str, str]:
146
+ if dest.exists() and dest.stat().st_size > 0:
147
+ return ("exists", source, str(dest))
148
+
149
+ dest.parent.mkdir(parents=True, exist_ok=True)
150
+ tmp = dest.with_name(f".{dest.name}.part-{os.getpid()}-{uuid.uuid4().hex}")
151
+
152
+ if dry_run:
153
+ return ("dry-run", source, str(dest))
154
+
155
+ if tool == "python-gcs":
156
+ try:
157
+ assert client is not None
158
+ client.download(source, tmp)
159
+ except Exception as e:
160
+ if tmp.exists():
161
+ tmp.unlink()
162
+ return ("failed", source, f"{type(e).__name__}: {e}")
163
+ else:
164
+ cmd = build_copy_command(tool, source, tmp)
165
+ result = subprocess.run(cmd, text=True, capture_output=True)
166
+ if result.returncode != 0:
167
+ if tmp.exists():
168
+ tmp.unlink()
169
+ message = result.stderr.strip() or result.stdout.strip() or f"exit {result.returncode}"
170
+ return ("failed", source, message)
171
+
172
+ if not tmp.exists() or tmp.stat().st_size == 0:
173
+ if tmp.exists():
174
+ tmp.unlink()
175
+ return ("failed", source, "download produced an empty/missing file")
176
+
177
+ if dest.exists() and dest.stat().st_size > 0:
178
+ tmp.unlink()
179
+ return ("exists-after-download", source, str(dest))
180
+
181
+ tmp.replace(dest)
182
+ chmod_group_writable(dest)
183
+ return ("downloaded", source, str(dest))
184
+
185
+
186
+ def write_manifest_row(path: Path | None, row: dict[str, str]) -> None:
187
+ if path is None:
188
+ return
189
+ path.parent.mkdir(parents=True, exist_ok=True)
190
+ exists = path.exists()
191
+ with path.open("a", newline="") as f:
192
+ writer = csv.DictWriter(f, fieldnames=["task_id", "instance_id", "episode_id", "status", "source", "dest"])
193
+ if not exists:
194
+ writer.writeheader()
195
+ writer.writerow(row)
196
+
197
+
198
+ def main() -> None:
199
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
200
+
201
+ parser = argparse.ArgumentParser(description=__doc__)
202
+ parser.add_argument("--task_id", type=int, required=True)
203
+ parser.add_argument("--bucket_uri", default=DEFAULT_BUCKET_URI)
204
+ parser.add_argument("--target_root", default=DEFAULT_TARGET_ROOT)
205
+ parser.add_argument(
206
+ "--source_template",
207
+ default=DEFAULT_SOURCE_TEMPLATE,
208
+ help=(
209
+ "Python format template for source URI. Available fields: bucket_uri, " "task_id, instance_id, episode_id."
210
+ ),
211
+ )
212
+ parser.add_argument("--instance_ids", default="", help="Comma-separated instance ids.")
213
+ parser.add_argument("--instance_ids_file", default="", help="One instance id per line, or CSV with id first.")
214
+ parser.add_argument(
215
+ "--gcs_manifest_csv",
216
+ default="",
217
+ help="CSV with task_id, instance_id, episode_id, object columns from generate_gcs_rawdata_manifest.py.",
218
+ )
219
+ parser.add_argument("--first_instance_id", type=int, default=0)
220
+ parser.add_argument("--num_instances", type=int, default=200)
221
+ parser.add_argument("--instance_stride", type=int, default=1)
222
+ parser.add_argument("--workers", type=int, default=4)
223
+ parser.add_argument("--tool", default="auto", help="auto, python-gcs, gcloud, gsutil, or full path.")
224
+ parser.add_argument(
225
+ "--credentials",
226
+ default="",
227
+ help="Path to a Google credentials JSON file for --tool python-gcs. Defaults to ADC env/config.",
228
+ )
229
+ parser.add_argument("--manifest", default="", help="CSV status manifest path.")
230
+ parser.add_argument("--dry_run", action="store_true")
231
+ args = parser.parse_args()
232
+
233
+ tool = "python-gcs" if args.dry_run and args.tool == "auto" else resolve_tool(args.tool)
234
+ client = None if args.dry_run or tool != "python-gcs" else PythonGCSClient(args.credentials)
235
+ manifest = Path(args.manifest) if args.manifest else None
236
+
237
+ if args.gcs_manifest_csv:
238
+ jobs = load_manifest_jobs(args)
239
+ else:
240
+ bucket_uri = args.bucket_uri.rstrip("/")
241
+ task_dir = Path(args.target_root) / f"task-{args.task_id:04d}"
242
+ jobs = []
243
+ for instance_id in load_instance_ids(args):
244
+ episode_id = format_episode_id(args.task_id, instance_id)
245
+ source = args.source_template.format(
246
+ bucket_uri=bucket_uri,
247
+ task_id=args.task_id,
248
+ instance_id=instance_id,
249
+ episode_id=episode_id,
250
+ )
251
+ dest = task_dir / f"episode_{episode_id}.hdf5"
252
+ jobs.append((instance_id, episode_id, source, dest))
253
+
254
+ counts: dict[str, int] = {}
255
+ with ThreadPoolExecutor(max_workers=max(args.workers, 1)) as executor:
256
+ futures = {
257
+ executor.submit(download_one, tool, client, source, dest, args.dry_run): (
258
+ instance_id,
259
+ episode_id,
260
+ source,
261
+ dest,
262
+ )
263
+ for instance_id, episode_id, source, dest in jobs
264
+ }
265
+ for future in as_completed(futures):
266
+ instance_id, episode_id, source, dest = futures[future]
267
+ status, resolved_source, resolved_dest = future.result()
268
+ counts[status] = counts.get(status, 0) + 1
269
+ print(
270
+ f"{status}: task={args.task_id:04d} instance={instance_id:04d} {resolved_source} -> {resolved_dest}",
271
+ flush=True,
272
+ )
273
+ write_manifest_row(
274
+ manifest,
275
+ {
276
+ "task_id": f"{args.task_id:04d}",
277
+ "instance_id": f"{instance_id:04d}",
278
+ "episode_id": episode_id,
279
+ "status": status,
280
+ "source": source,
281
+ "dest": str(dest),
282
+ },
283
+ )
284
+
285
+ failed = counts.get("failed", 0)
286
+ print(f"summary task={args.task_id:04d} " + " ".join(f"{k}={v}" for k, v in sorted(counts.items())))
287
+ if failed:
288
+ raise SystemExit(1)
289
+
290
+
291
+ if __name__ == "__main__":
292
+ main()