diff --git a/world-in-world/src/habitat-baselines/habitat-lab/MANIFEST.in b/world-in-world/src/habitat-baselines/habitat-lab/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..5fdf04293354a8fd859bf62d61848ad786f6c992 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/MANIFEST.in @@ -0,0 +1,6 @@ +graft habitat/config +graft habitat/utils/visualizations/assets +graft habitat/tasks/rearrange/multi_task/domain_configs +graft habitat/datasets/rearrange/configs +include habitat/py.typed +include requirements.txt diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/__init__.py b/world-in-world/src/habitat-baselines/habitat-lab/habitat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e51d8a8f68c0f9c649e135ef4dab5880f531efff --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/__init__.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from habitat.config import get_config, read_write +from habitat.core.agent import Agent +from habitat.core.benchmark import Benchmark +from habitat.core.challenge import Challenge +from habitat.core.dataset import Dataset +from habitat.core.embodied_task import EmbodiedTask, Measure, Measurements +from habitat.core.env import Env, RLEnv +from habitat.core.logging import logger +from habitat.core.registry import registry # noqa: F401 +from habitat.core.simulator import Sensor, SensorSuite, SensorTypes, Simulator +from habitat.core.vector_env import ThreadedVectorEnv, VectorEnv +from habitat.datasets import make_dataset +from habitat.version import VERSION as __version__ # noqa: F401 diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/CONFIG_KEYS.md b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/CONFIG_KEYS.md new file mode 100644 index 0000000000000000000000000000000000000000..8aa92f8cc1a61c884a51a617a1bebeaa05bc3fc8 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/CONFIG_KEYS.md @@ -0,0 +1,182 @@ +# Configuration Keys + +## Dataset +Configuration for the dataset of the task. +A dataset consists of episodes +(a start configuration for a task within a scene) and a scene dataset +(with all the assets needed to instantiate the task). +For a list of all the available datasets, see [this page](../../../DATASETS.md). + +| Key | Description | +| --- | --- | +| habitat.dataset.type | The key for the dataset class that will be used. Examples of such keys are `PointNav-v1`, `ObjectNav-v1`, `InstanceImageNav-v1` or `RearrangeDataset-v0`. Different datasets have different properties so you should use the dataset that fits your task. | +| habitat.dataset.scene_dir | The path to the directory containing the scenes that will be used. You should put all your scenes in the same folder (example `data/scene_datasets`) to avoid having to change it. | +|habitat.dataset.data_path | The path to the episode dataset. Episodes need to be compatible with the `type` argument (so they will load properly) and only use scenes that are present in the `scenes_dir`.| +|habitat.dataset.split | `data_path` can have a `split` in the path. For example: "data/datasets/pointnav/habitat-test-scenes/v1/{split}/{split}.json.gz" the value in "{split}" will be replaced by the value of the `split` argument. This allows to easily swap between training, validation and test episodes by only changing the split argument. | + +## Task +The definition of the task in Habitat. +There are many different Tasks determined by the `habitat.task.type` config: + - Point navigation : `Nav-0` The agent needs to navigate to a geometric goal position. + - Image navigation : `Nav-0` The agent needs to navigate to an object matching the type shown in a goal image. + - Instance image navigation:`InstanceImageNav-v1` The agent needs to navigate to an object matching the type shown in a goal image that is sampled from the current scene. + - Object navigation : `ObjectNav-v1` The agent needs to navigate to a specific type of object in the scene indicated by a categorical value. + - Rearrangement close drawer: `RearrangeCloseDrawerTask-v0` The agent must close the kitchen drawer in the scene. + - Rearrangement open drawer: `RearrangeOpenDrawerTask-v0` The agent must open the kitchen drawer in the scene. + - Rearrangement close fridge : `RearrangeCloseFridgeTask-v0` The agent must close the kitchen fridge in the scene. + - Rearrangement open fridge : `RearrangeOpenFridgeTask-v0` The agent must open the kitchen fridge in the scene. + - Rearrangement navigate to object : `NavToObjTask-v0` The agent must navigate to an object located at a known geometric position in the scene. + - Rearrangement pick : `RearrangePickTask-v0` The agent must pick up a specific object in the scene from given the object's geometric coordinates. + - Rearrangement place : `RearrangePlaceTask-v0` The agent must place a grasped object at a geometric set of coordinates. + - Rearrangement do nothing : `RearrangeEmptyTask-v0` The agent does not have to do anything. Useful for debugging. + - Rearrangement reach : `RearrangeReachTask-v0` The agent must place its end effector into a specific location defined by geometric coordinates. + - Rearrangement composite tasks : `RearrangePddlTask-v0` The agent must perform a sequence of sub-tasks in succession defined by a PDDL plan. + + +| Key | Description | +| --- | --- | +|habitat.task.type | The registered task that will be used. For example : `InstanceImageNav-v1` or `ObjectNav-v1`. +|habitat.task.physics_target_sps | The size of each simulator physics update will be 1 / physics_target_sps. | +|habitat.task.reward_measure | The name of the Measurement that will correspond to the reward of the robot. This value must be a key present in the dictionary of Measurements in the habitat configuration (under `habitat.task.measurements`, see below for a list of available measurements). For example, `distance_to_goal_reward` for navigation or `place_reward` for the rearrangement place task.| +|habitat.task.success_measure | The name of the Measurement that will correspond to the success criteria of the robot. This value must be a key present in the dictionary of Measurements in the habitat configuration (under `habitat.task.measurements`, see below for a list of available measurements). If the measurement has a non-zero value, the episode is considered a success. | +|habitat.task.end_on_success | If True, the episode will end when the success measure indicates success. Otherwise the episode will go on (this is useful when doing hierarchical learning and the robot has to explicitly decide when to change policies)| +|habitat.task.task_spec | When doing the `RearrangePddlTask-v0` only, will look for a pddl plan of that name to determine the sequence of sub-tasks that need to be completed. The format of the pddl plans files is undocumented.| +|habitat.task.task_spec_base_path | When doing the `RearrangePddlTask-v0` only, the relative path where the task_spec file will be searched.| +|habitat.task.spawn_max_dists_to_obj| For `RearrangePickTask-v0` task only. Controls the maximum distance the robot can be spawned from the target object. | +| habitat.task.base_angle_noise| For Rearrangement tasks only. Controls the standard deviation of the random normal noise applied to the base's rotation angle at the start of an episode.| +| habitat.task.base_noise| For Rearrangement tasks only. Controls the standard deviation of the random normal noise applied to the base's position at the start of an episode.| + +## Visual Agents +We define the visual agents as a bundle of sim sensors. They are a quick way to specify the visual observation space you need in your environment. You can inherit a default agent in your configuration. +Some sample agents are defined [here](./habitat/simulator/agents/) and are reused in many of our benchmarks. To use one of these agents, add +``` + - /habitat/simulator/agents@habitat.simulator.agents.main_agent: +``` +to your defaults list. All agents have a camera resolution of 256 by 256. +| Key | Description | +| --- | --- | +|depth_head_agent| An Agent with a single depth camera attached to its head.| +|rgb_head_agent| An Agent with a single RGB camera attached to its head.| +|rgbd_head_rgbd_arm_agent| An Agent with both a RGB and depth camera attached to its head and arm.| + + + +## Environment +Some habitat environment configurations. +| Key | Description | +| --- | --- | +|habitat.environment.max_episode_steps| The maximum number of environment steps before the episode ends.| +|habitat.environment.max_episode_seconds| The maximum number of wall-clock seconds before the episode ends.| + +## Discrete Navigation Actions +Actions are the means through an agent affects the environment. They are defined in the dictionary `habitat.task.actions`. All actions in this dictionary will be available for the agent to perform. Note that Navigation action space is discrete while the Rearrangement action space is continuous. The way one would add an action to a configuration file would be by adding to the `defaults` list. For example: +``` +defaults: + - /habitat/task/actions: + - move_forward + - turn_left +``` + +| Key | Description | +| --- | --- | +| habitat.task.actions.stop | In Navigation tasks only, the stop action is a discrete action. When called, the Agent will request to stop the navigation task. Note that this action is needed to succeed in a Navigation task since the Success is determined by the Agent calling the stop action within range of the target. Note that this is different from the RearrangeStopActionConfig that works for Rearrangement tasks only instead of the Navigation tasks.| +| habitat.task.actions.empty | In Navigation tasks only, the pass action. The robot will do nothing.| +| habitat.task.actions.move_forward | In Navigation tasks only, this discrete action will move the robot forward by a fixed amount determined by the `habitat.simulator.forward_step_size` amount. | +| habitat.task.actions.turn_left | In Navigation tasks only, this discrete action will rotate the robot to the left by a fixed amount determined by the `habitat.simulator.turn_angle` amount. | +| habitat.task.actions.turn_right | In Navigation tasks only, this discrete action will rotate the robot to the right by a fixed amount determined by the `habitat.simulator.turn_angle` amount. | +| habitat.task.actions.look_up | In Navigation tasks only, this discrete action will rotate the robot's camera up by a fixed amount determined by the `tilt_angle` amount of the look_up action. | +| habitat.task.actions.look_down | In Navigation tasks only, this discrete action will rotate the robot's camera down by a fixed amount determined by the `tilt_angle` amount of the look_down action. | + +## Navigation Measures +A measure is a way to collect data about the environment at each step that is not sensor information. Measures can contain privileged information for the user (like a top down map) or for training (like rewards). +The way one would add a measure to a configuration file would be by adding to the `defaults` list. For example: +``` +defaults: + - /habitat/task/measurements: + - articulated_agent_force + - force_terminate +``` + +| Key | Description | +| --- | --- | +| habitat.task.measurements.num_steps| In both Navigation and Rearrangement tasks, counts the number of steps since the start of the episode.| +| habitat.task.measurements.distance_to_goal | In Navigation tasks only, measures the geodesic distance to the goal.| +|habitat.task.measurements.distance_to_goal.distance_to | If 'POINT' measures the distance to the closest episode goal. If 'VIEW_POINTS' measures the distance to the episode's goal viewpoints (useful in image nav). | +|habitat.task.measurements.success | For Navigation tasks only, Measures 1.0 if the robot reached a success and 0 otherwise. A success is defined as calling the `habitat.task.actions.stop` when the `habitat.task.measurements.distance_to_goal` Measure is smaller than `success_distance`.| +|habitat.task.measurements.success.success_distance| The minimal distance the robot must be to the goal for a success.| +|habitat.task.measurements.spl| For Navigation tasks only, Measures the SPL (Success weighted by Path Length) ref: [On Evaluation of Embodied Agents - Anderson et. al](https://arxiv.org/pdf/1807.06757.pdf). Measure is always 0 except at success where it will be the ratio of the optimal distance from start to goal over the total distance traveled by the agent. Maximum value is 1. `SPL = success * optimal_distance_to_goal / distance_traveled_so_far` +|habitat.task.measurements.soft_spl | For Navigation tasks only, Similar to SPL, but instead of a boolean, success is now calculated as 1 - (ratio of distance covered to target). `SoftSPL = max(0, 1 - distance_to_goal / optimal_distance_to_goal) * optimal_distance_to_goal / distance_traveled_so_far` +|habitat.task.measurements.distance_to_goal_reward | In Navigation tasks only, measures a reward based on the distance towards the goal. The reward is `- (new_distance - previous_distance)` i.e. the decrease of distance to the goal. + +## Navigation Lab Sensors +Lab sensors are any non-rendered sensor observation, like geometric goal information. The way one would add a sensor to a configuration file would be by adding to the `defaults` list. For example: +``` +defaults: + - /habitat/task/lab_sensors: + - objectgoal_sensor + - compass_sensor +``` + +| Key | Description | +| --- | --- | +| habitat.task.lab_sensors.objectgoal_sensor| For Object Navigation tasks only. Generates a discrete observation containing the id of the goal object for the episode. | +| habitat.task.lab_sensors.objectgoal_sensor.goal_spec| A string that can take the value TASK_CATEGORY_ID or OBJECT_ID. If the value is TASK_CATEGORY_ID, then the observation will be the id of the `episode.object_category` attribute, if the value is OBJECT_ID, then the observation will be the id of the first goal object. | +| habitat.task.lab_sensors.objectgoal_sensor.goal_spec_max_val| If the ` habitat.task.lab_sensors.objectgoal_sensor.goal_spec` is OBJECT_ID, then `goal_spec_max_val` is the total number of different objects that can be goals. Note that this value must be greater than the largest episode goal category id. | +| habitat.task.lab_sensors.instance_imagegoal_sensor | Used only by the InstanceImageGoal Navigation task. The observation is a rendered image of the goal object within the scene.| +| habitat.task.lab_sensors. instance_imagegoal_hfov_sensor | Used only by the InstanceImageGoal Navigation task. The observation is a single float value corresponding to the Horizontal field of view (HFOV) in degrees of the image provided by the `habitat.task.lab_sensors.instance_imagegoal_sensor `.| +| habitat.task.lab_sensors.compass_sensor | For Navigation tasks only. The observation of the `EpisodicCompassSensor` is a single float value corresponding to the angle difference in radians between the current rotation of the robot and the start rotation of the robot along the vertical axis. | +| habitat.task.lab_sensors.gps_sensor | For Navigation tasks only. The observation of the EpisodicGPSSensor are two float values corresponding to the vector difference in the horizontal plane between the current position and the start position of the robot (in meters). | +| habitat.task.lab_sensors.pointgoal_with_gps_compass_sensor | Indicates the position of the point goal in the frame of reference of the robot. | + + +## Continuous Rearrangement Actions + +| Key | Description | +| --- | --- | +|habitat.task.actions.arm_action |In Rearrangement tasks only, the action that will move the robot arm around. The action represents to delta angle (in radians) of each joint. | +|habitat.task.actions.arm_action.grasp_thresh_dist| The grasp action will only work on the closest object if its distance to the end effector is smaller than this value. Only for `MagicGraspAction` grip_controller.| +|habitat.task.actions.arm_action.grip_controller| Can either be None, `MagicGraspAction` or `SuctionGraspAction`. If None, the arm will be unable to grip object. Magic grasp will grasp the object if the end effector is within grasp_thresh_dist of an object, with `SuctionGraspAction`, the object needs to be in contact with the end effector. | +|habitat.task.actions.base_velocity | In Rearrangement only. Corresponds to the base velocity. Contains two continuous actions, the first one controls forward and backward motion, the second the rotation. +|habitat.task.actions.rearrange_stop | In rearrangement tasks only, if the robot calls this action, the task will end.| +|habitat.task.actions.oracle_nav_action| Rearrangement Only, Oracle navigation action. This action takes as input a discrete ID which refers to an object in the PDDL domain. The oracle navigation controller then computes the actions to navigate to that desired object.| + + +## Rearrangement Sensors + + +| Key | Description | +| --- | --- | +|habitat.task.lab_sensors.relative_resting_pos_sensor | Rearrangement only. Sensor for the desired relative position of the end-effector's resting position, relative to the end-effector's current position. The three values correspond to the cartesian coordinates of the desired resting position in the frame of reference of the end effector. The desired resting position is determined by the habitat.task.desired_resting_position coordinates relative to the robot's base.| +| habitat.task.lab_sensors.is_holding_sensor | Rearrangement only. A single float sensor with value 1.0 if the robot is grasping any object and 0.0 otherwise.| +|habitat.task.lab_sensors.end_effector_sensor | Rearrangement only. the cartesian coordinates (3 floats) of the arm's end effector in the frame of reference of the robot's base.| +|habitat.task.lab_sensors.joint_sensor| Rearrangement only. Returns the joint positions of the robot.| +| habitat.task.lab_sensors.goal_sensor | Rearrangement only. Returns the relative position from end effector to a goal position in which the agent needs to place an object. | +| habitat.task.lab_sensors.target_start_gps_compass_sensor | Rearrangement only. Returns the initial position of every object that needs to be rearranged in composite tasks relative to the robot's start position, in 2D polar coordinates (distance and angle in the horizontal plane). | +| habitat.task.lab_sensors.target_goal_gps_compass_sensor | Rearrangement only. Returns the desired goal position of every object that needs to be rearranged in composite tasks relative to the robot's start position, in 2D polar coordinates (distance and angle in the horizontal plane). | + +## Rearrangement Measures +| Key | Description | +| --- | --- | +|habitat.task.measurements.end_effector_to_rest_distance | Rearrangement only. Distance between current end effector position and the resting position of the end effector. Requires that the RelativeRestingPositionSensor is attached to the agent (see Rearrangement Sensors above to see how to attach sensors). | +|habitat.task.measurements.articulated_agent_force | The amount of force in newton's applied by the robot. It computes both the instantaneous and accumulated force during the episode. | +|habitat.task.measurements.does_want_terminate | Rearrangement Only. Measures 1 if the agent has called the stop action and 0 otherwise. | +|habitat.task.measurements.force_terminate | If the force is greater than a certain threshold, this measure will be 1.0 and 0.0 otherwise. Note that if the measure is 1.0, the task will end as a result. | +|habitat.task.measurements.force_terminate.max_accum_force | The threshold for the accumulated force before calling termination. -1 is no threshold, i.e., force-based termination is never called. | +|habitat.task.measurements.force_terminate.max_instant_force | The threshold for the current, instantaneous force before calling termination. -1 is no threshold, i.e., force-based termination is never called. | +|habitat.task.measurements.object_to_goal_distance | In rearrangement only. The distance between the target object and the goal position for the object. | +|habitat.task.measurements.obj_at_goal | The measure is a dictionary of target indexes to float. The values are 1 if the object is within succ_thresh of the goal position for that object. | +|habitat.task.measurements.obj_at_goal.succ_thresh | The threshold distance below which an object is considered at the goal location. | +|habitat.task.measurements.art_obj_at_desired_state | Rearrangement open/close container tasks only. Whether the articulated object (fridge or cabinet door) is in a desired joint state (open or closed) as defined by the task. | +|habitat.task.measurements.rot_dist_to_goal | Rearrangement Navigation task only. The angle between the forward direction of the agent and the direction to the goal location. | +|habitat.task.measurements.composite_stage_goals | Composite Rearrangement only. 1.0 if the agent complete a particular stage defined in `stage_goals` and 0.0 otherwise. Stage goals are specified in the `pddl` task description. | +|habitat.task.measurements.nav_to_pos_succ | Rearrangement Navigation task only. The value is 1.0 if the robot is within success_distance of the goal position. | + +### Task defining rearrangement measures + +You can change the success and reward measures of a task by changing the `habitat.task.success_measure` and the `habitat.task.reward_measure` keys respectively. + +For Rearrangement Pick : `pick_success` | `place_reward` +For Rearrangement Place : `place_success` | `place_reward` +For Rearrangement Open / Close Articulated Object : `art_obj_success` | `art_obj_reward` +For Rearrangement Navigation : `nav_to_obj_success` | `nav_to_obj_reward` +For Composite Rearrangement using a PDDL plan : `pddl_compositesuccess` | ` move_objects_reward` diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/README.md b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3017180dd81edf8e4e04ac6d45984a075da78e --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/README.md @@ -0,0 +1,497 @@ +Habitat-Lab Configuration System +================================ +![Habitat with Hydra](/res/img/habitat_with_hydra.png) + +For a description of some of the most important configuration keys of the habitat benchmarks, refer to [this file](CONFIG_KEYS.md). + +Habitat-Lab's configuration system has been changed from [YACS](https://github.com/rbgirshick/yacs) +to [Hydra](https://hydra.cc). + +## Hydra Concepts used in Habitat-Lab + +With Hydra, the [Output Config](https://hydra.cc/docs/advanced/terminology/#output-config) +is composed dynamically at run time from +the [Input Configs](https://hydra.cc/docs/advanced/terminology/#input-configs) specified in +the [Defaults List](https://hydra.cc/docs/advanced/terminology/#defaults-list) and +[Overrides](https://hydra.cc/docs/advanced/terminology/#overrides) from the primary yaml config file or command line. + +Default config values and their types are defined via +[Structured Configs](https://hydra.cc/docs/advanced/terminology/#structured-config). Structured Configs are used as a +config validation schemas to ensure that all the required fields are set and match the required type, and also as a +configs, in place of configuration yaml files. All Structured Configs are registered in +the [ConfigStore](https://hydra.cc/docs/tutorials/structured_config/config_store/) - in-memory +Structured Configs registry. Habitat-Lab's Structured Configs are defined and registered to the ConfigStore in +[habitat-lab/habitat/config/default_structured_configs.py](default_structured_configs.py). + +Similar configs are grouped in [Config Groups](https://hydra.cc/docs/advanced/terminology/#config-group) +(placed in the same directories in the [Config Search Path](https://hydra.cc/docs/advanced/terminology/#config-search-path)). +These configs are also called [Config Group Options](https://hydra.cc/docs/advanced/terminology/#config-group-option). +For example, Embodied AI task specifications supported by Habitat-Lab are placed in the `habitat/task` Config Group +and to use the PointNav task just add `habitat/task: pointnav` line to your config's Defaults List. + +Each Input Config's position in the Output Config is determined via +[Package](https://hydra.cc/docs/advanced/terminology/#package). In other words, a Package is the path to node in a config. +By default, the Package of a Config Group Option is derived from the Config Group. e.g: task configs in `habitat/task` +will have the package `habitat.task` by default (i.e. will be placed under `habitat.task` in the final Output Config). + +To make all habitat configs visible to Hydra, the `habitat/config` path is added to Config Search Path by +extending [SearchPathPlugin](https://hydra.cc/docs/advanced/plugins/overview/#searchpathplugin) +(see `HabitatConfigPlugin` class in the [habitat-lab/habitat/config/default_structured_configs.py](default_structured_configs.py)). +`HabitatConfigPlugin` is registered by `register_hydra_plugin(HabitatConfigPlugin)` function call in Habitat-Lab's `get_config` +(see `get_config` definition in [habitat-lab/habitat/config/default.py](default.py)). + +Note, due to the fact that Habitat-Lab doesn't have a single entry point, but creates config objects in multiple places, +for example, Jupyter Notebooks, example scripts in the `/examples` folder, tests, etc. Hydra's +[Compose API](https://hydra.cc/docs/advanced/compose_api/) is used to create the config in the Habitat-Lab's +`get_config` function instead of `@hydra.main` decorator (used in most Hydra examples). + +For more detailed explanation of Hydra concepts visit Hydra's [website](https://hydra.cc/docs/intro/). + +## Config directory structure +``` +habitat-lab/habitat/config/ +| +|_benchmark # benchmark configs (primary configs to be used in habitat.get_config) +| |_nav +| |_rearrange +| +|_habitat # habitat configs (habitat config groups options) +| |_dataset +| |_simulator +| |_task +| +|_test # test configs +``` + + +## What's changed? +
+PointNav benchmark: Input Config. + +```yaml +# @package _global_ + +# defaults list: +defaults: + - /habitat: habitat_config_base + - /habitat/task: pointnav + - /habitat/simulator/agents: + - rgbd_agent + - /habitat/dataset/pointnav: gibson + - _self_ + +# config values overrides: +habitat: + environment: + max_episode_steps: 500 + simulator: + agents: + rgbd_agent: + sim_sensors: + rgb_sensor: + width: 256 + height: 256 + depth_sensor: + width: 256 + height: 256 +``` +
+ +
+PointNav benchmark: Output Config. + +```yaml +habitat: + seed: 100 + env_task: GymHabitatEnv + env_task_gym_dependencies: [] + env_task_gym_id: '' + environment: + max_episode_steps: 500 + max_episode_seconds: 10000000 + iterator_options: + cycle: true + shuffle: true + group_by_scene: true + num_episode_sample: -1 + max_scene_repeat_episodes: -1 + max_scene_repeat_steps: 10000 + step_repetition_range: 0.2 + simulator: + type: Sim-v0 + forward_step_size: 0.25 + turn_angle: 10 + create_renderer: false + requires_textures: true + lag_observations: 0 + auto_sleep: false + step_physics: true + concur_render: false + needs_markers: true + update_articulated_agent: true + scene: data/scene_datasets/habitat-test-scenes/van-gogh-room.glb + scene_dataset: default + additional_object_paths: [] + seed: ${habitat.seed} + default_agent_id: 0 + debug_render: false + debug_render_robot: false + kinematic_mode: false + debug_render_goal: true + robot_joint_start_noise: 0.0 + ctrl_freq: 120.0 + ac_freq_ratio: 4 + load_objs: true + hold_thresh: 0.09 + grasp_impulse: 1000.0 + agents: + rgbd_agent: + height: 1.5 + radius: 0.1 + sim_sensors: + rgb_sensor: + type: HabitatSimRGBSensor + height: 256 + width: 256 + position: + - 0.0 + - 1.25 + - 0.0 + orientation: + - 0.0 + - 0.0 + - 0.0 + hfov: 90 + sensor_subtype: PINHOLE + noise_model: None + noise_model_kwargs: {} + depth_sensor: + type: HabitatSimDepthSensor + height: 256 + width: 256 + position: + - 0.0 + - 1.25 + - 0.0 + orientation: + - 0.0 + - 0.0 + - 0.0 + hfov: 90 + sensor_subtype: PINHOLE + noise_model: None + noise_model_kwargs: {} + min_depth: 0.0 + max_depth: 10.0 + normalize_depth: true + is_set_start_state: false + start_position: + - 0.0 + - 0.0 + - 0.0 + start_rotation: + - 0.0 + - 0.0 + - 0.0 + - 1.0 + joint_start_noise: 0.0 + articulated_agent_urdf: data/robots/hab_fetch/robots/hab_fetch.urdf + articulated_agent_type: FetchRobot + ik_arm_urdf: data/robots/hab_fetch/robots/fetch_onlyarm.urdf + agents_order: + - rgbd_agent + habitat_sim_v0: + gpu_device_id: 0 + gpu_gpu: false + allow_sliding: true + frustum_culling: true + enable_physics: false + physics_config_file: ./data/default.physics_config.json + leave_context_with_background_renderer: false + enable_gfx_replay_save: false + ep_info: null + task: + reward_measure: distance_to_goal_reward + success_measure: spl + success_reward: 2.5 + slack_reward: -0.01 + end_on_success: true + type: Nav-v0 + lab_sensors: + pointgoal_with_gps_compass_sensor: + type: PointGoalWithGPSCompassSensor + goal_format: POLAR + dimensionality: 2 + measurements: + distance_to_goal: + type: DistanceToGoal + distance_to: POINT + success: + type: Success + success_distance: 0.2 + spl: + type: SPL + distance_to_goal_reward: + type: DistanceToGoalReward + goal_sensor_uuid: pointgoal_with_gps_compass + count_obj_collisions: true + settle_steps: 5 + constraint_violation_ends_episode: true + constraint_violation_drops_object: false + force_regenerate: false + should_save_to_cache: true + object_in_hand_sample_prob: 0.167 + render_target: true + ee_sample_factor: 0.2 + ee_exclude_region: 0.0 + base_angle_noise: 0.15 + base_noise: 0.05 + spawn_region_scale: 0.2 + joint_max_impulse: -1.0 + desired_resting_position: + - 0.5 + - 0.0 + - 1.0 + use_marker_t: true + cache_robot_init: false + success_state: 0.0 + easy_init: false + should_enforce_target_within_reach: false + task_spec_base_path: habitat/task/rearrange/pddl/ + task_spec: '' + pddl_domain_def: replica_cad + obj_succ_thresh: 0.3 + art_succ_thresh: 0.15 + robot_at_thresh: 2.0 + actions: + stop: + type: StopAction + move_forward: + type: MoveForwardAction + turn_left: + type: TurnLeftAction + turn_angle: 10 + turn_right: + type: TurnRightAction + turn_angle: 10 + dataset: + type: PointNav-v1 + split: train + scenes_dir: data/scene_datasets + content_scenes: + - '*' + data_path: data/datasets/pointnav/gibson/v1/{split}/{split}.json.gz + gym: + obs_keys: null + action_keys: null + achieved_goal_keys: [] + desired_goal_keys: [] +``` +
+ +- The configuration keys are lowercase and live under the `habitat` namespace. +- Embodied AI task specifications are separated from the benchmark configs (more general configs that include + task config as one of their sub-configs in the Defaults List). Task configs are grouped in the `habitat/task` + Config Group (located in [habitat-lab/config/habitat/task](habitat/task) directory) and benchmark configs + are placed in the [habitat-lab/config/benchmark](benchmark) directory. +- `agent.sensors` is renamed to `agent.sim_sensors`, `task.sensors` is renamed to `task.lab_sensors`. +- Actions, agents, measurements and sensors configs are not directly attached to the simulator, task or agent + config nodes but are added to `task.actions`, `simulator.agents`, `task.measurements`, `task.lab_sensors`, + `simulator..sim_sensors` sub-nodes of type `Dict[str, CorrespondingConfigNodeType]` + that can be updated dynamically. Consequently, Output Config contains only those config nodes that are listed in + `task.actions`, `simulator.agents`, `task.measurements`, `task.lab_sensors`, `simulator.agents.agent_name.sim_sensors` + (not all possible actions, agents, measurements and sensors config nodes). +- `task.possible_actions` is removed. + +### New functionality enabled +After the configuration system migration to Hydra, Habitat-Lab automatically supports all Hydra's +and [OmegaConf's](https://omegaconf.readthedocs.io/) features (note that Hydra is build on top of OmegaConf). +Some of new features are listed below: +- Config node reuse by redefining the config package. For example, it is possible to use the same agent config to + configure two agents of the same type: +```yaml +defaults: + - /habitat/simulator/sensor_setups@habitat.simulator.agents.agent_0: depth_head_agent + - /habitat/simulator/sensor_setups@habitat.simulator.agents.agent_1: depth_head_agent +``` +- [Variable interpolation](https://omegaconf.readthedocs.io/en/2.2_branch/usage.html#variable-interpolation). + For example, use the same seed value for `SimulatorConfig.seed` as in `HabitatConfig.seed` (see `SimulatorConfig` + in the [habitat-lab/habitat/config/default.py](default.py)): +```python +from omegaconf import II + +@dataclass +class SimulatorConfig(HabitatBaseConfig): + # Other SimulatorConfig keys are omitted in this code snippet + seed: int = II("habitat.seed") +``` +- [Parameter sweeping and multirun](https://hydra.cc/docs/tutorials/basic/running_your_app/multi-run/). For example, launching 3 experiments with three different learning rates: +```bash +python -u -m habitat_baselines.run --config-name=config.yaml \ +–-multirun habitat_baselines.rl.ppo.lr 2.5e-4,2.5e-5,2.5e-6 +``` +- Seamless [SLURM](https://slurm.schedmd.com/documentation.html) integration through + [Submitit Launcher](https://hydra.cc/docs/plugins/submitit_launcher/). + To enable the feature Submitit plugin should be installed: `pip install hydra-submitit-launcher --upgrade` + and `submitit_slurm` launcher specified in the command line `hydra/launcher=submitit_slurm`: +```bash +python -u -m habitat_baselines.run --config-name=config.yaml \ +hydra/launcher=submitit_slurm --multirun +``` +- Making the config key required by setting its value to `MISSING`. For example, we require the user to explicitly + set the `task` and the `dataset` in every Habitat-Lab benchmark config (see `HabitatConfig` Structured Config + in the [habitat-lab/habitat/config/default.py](default.py)): +```python +from omegaconf import MISSING + +@dataclass +class HabitatConfig(HabitatBaseConfig): + # Other HabitatConfig keys are omitted in this code snippet + task: TaskConfig = MISSING + dataset: DatasetConfig = MISSING +``` + + +But Hydra allows a lot more! Visit Hydra's [website](https://hydra.cc/docs/intro/) for mode details about Hydra's features. + +## How to ______? +### read the config +```python +import habitat + +config = habitat.get_config("benchmark/nav/pointnav/pointnav_gibson.yaml") +``` +### override the config +#### via command line +Override config values: +```bash +python -u -m habitat_baselines.run --config-name=pointnav/ddppo_pointnav.yaml \ +habitat.environment.max_episode_steps=250 \ +habitat_baselines.total_num_steps=100 +``` + +Override the Config Group Option value: +```bash +python -u -m habitat_baselines.run --config-name=pointnav/ddppo_pointnav.yaml \ +benchmark/nav/pointnav=pointnav_hm3d # overriding benchmark config to be pointnav_hm3d +``` + +#### via yaml +Yaml file definitions or overrides are defined after the Defaults List: +```yaml +# @package _global_ + +defaults: + - /habitat: habitat_config_base + - /habitat/task: pointnav + - /habitat/simulator/agents: + - rgbd_agent + - /habitat/dataset/pointnav: gibson + - _self_ + +# config values overrides: +habitat: + environment: + max_episode_steps: 500 + simulator: + agents: + rgbd_agent: + sim_sensors: + rgb_sensor: + width: 256 + height: 256 + depth_sensor: + width: 256 + height: 256 +``` +Note, that its also possible to override the Config Group Options in the Defaults list: +```yaml +# @package _global_ + +defaults: + - any_base_config + - override /habitat/dataset/pointnav: gibson # override the any_base_config dataset to gibson +``` + +#### via code +The config object returned from `habitat.get_config` is readonly. To be able to update the config object via code, wrap +it in the `read_write(config)` context manager: + +```python +from habitat.config.read_write import read_write + +with read_write(config): + config.habitat.simulator.concur_render = False + agent_config = get_agent_config(config.habitat.simulator) + agent_config.sim_sensors.update( + {"third_rgb_sensor": ThirdRGBSensorConfig(height=512, width=512)} + ) +``` + +### extend the config +pointnav_base.yaml +```yaml +# @package _global_ + +defaults: + - /habitat: habitat_config_base + - /habitat/task: pointnav + - /habitat/simulator/agents: + - rgbd_agent + - _self_ + +habitat: + environment: + max_episode_steps: 500 + simulator: + agents: + rgbd_agent: + sim_sensors: + rgb_sensor: + width: 256 + height: 256 + depth_sensor: + width: 256 + height: 256 +``` + +pointnav_habitat_test.yaml +```yaml +# @package _global_ + +defaults: + - pointnav_base + - /habitat/dataset/pointnav: habitat_test +``` + +pointnav_gibson.yaml +```yaml +# @package _global_ + +defaults: + - pointnav_base + - /habitat/dataset/pointnav: gibson +``` + +### define new structured config +In case, you directly work with code in the habitat-lab repository (for example, clone and extend), then to add new +custom Structured Config just define and add the class to the ConfigStore in the +[habitat-lab/habitat/config/default_structured_configs.py](default_structured_configs.py). + +```python +from dataclasses import dataclass +from hydra.core.config_store import ConfigStore + +@dataclass +class CustomStructuredConfig: + custom_config_key: KeyType = DefaultValue + +cs = ConfigStore.instance() +cs.store( + group="habitat/custom_structured_config", # config group + name="custom_structured_config", # config name + node=CustomStructuredConfig, + # Note, it is also possible to override the package (that's derived from the Config Group by default) + # package="habitat.new.custom_structured_config", +) +``` diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/__init__.py b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..570728e3a02076164ace6586be5e82cde432ccdb --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/__init__.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + + +from habitat.config.default import DictConfig, get_config +from habitat.config.read_write import read_write + +__all__ = ["get_config", "read_write", "default_structured_configs"] diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/default.py b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/default.py new file mode 100644 index 0000000000000000000000000000000000000000..a347a818b273d622a26bb9675f874b706e6157e7 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/default.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import inspect +import os.path as osp +import threading +from functools import partial +from typing import List, Optional + +from hydra import compose, initialize_config_dir +from omegaconf import DictConfig, OmegaConf + +from habitat.config.default_structured_configs import ( + AgentConfig, + HabitatConfigPlugin, + SimulatorConfig, + register_hydra_plugin, +) +from habitat.config.read_write import read_write + +_HABITAT_CFG_DIR = osp.dirname(inspect.getabsfile(inspect.currentframe())) +# Habitat config directory inside the installed package. +# Used to access default predefined configs. +# This is equivalent to doing osp.dirname(osp.abspath(__file__)) +# in editable install, this is pwd/habitat-lab/habitat/config +CONFIG_FILE_SEPARATOR = "," + + +def get_full_config_path(config_path: str, configs_dir: str) -> str: + r"""Returns absolute path to the yaml config file if exists, else raises RuntimeError. + + :param config_path: path to the yaml config file. + :param configs_dir: path to the config files root directory. + :return: absolute path to the yaml config file. + """ + if osp.exists(config_path): + return osp.abspath(config_path) + + proposed_full_path = osp.join(configs_dir, config_path) + if osp.exists(proposed_full_path): + return osp.abspath(proposed_full_path) + + raise RuntimeError(f"No file found for config '{config_path}'") + + +get_full_habitat_config_path = partial( + get_full_config_path, configs_dir=_HABITAT_CFG_DIR +) +get_full_habitat_config_path.__doc__ = r""" +Returns absolute path to the habitat yaml config file if exists, else raises RuntimeError. + +:param config_path: relative path to the habitat yaml config file. +:return: absolute config to the habitat yaml config file. +""" + + +def get_agent_config( + sim_config: SimulatorConfig, agent_id: Optional[int] = None +) -> AgentConfig: + r"""Returns agent's config node of default agent or based on index of the agent. + + :param sim_config: config of :ref:`habitat.core.simulator.Simulator`. + :param agent_id: index of the agent config (relevant for multi-agent setup). + :return: relevant agent's config. + """ + if agent_id is None: + agent_id = sim_config.default_agent_id + + agent_name = sim_config.agents_order[agent_id] + agent_config = sim_config.agents[agent_name] + + return agent_config + + +lock = threading.Lock() + + +def patch_config(cfg: DictConfig) -> DictConfig: + """ + Internal method only. Modifies a configuration by inferring some missing keys + and makes sure some keys are present and compatible with each other. + """ + # In the single-agent setup use the agent's key from `habitat.simulator.agents`. + sim_config = cfg.habitat.simulator + if len(sim_config.agents) == 1: + with read_write(sim_config): + sim_config.agents_order = list(sim_config.agents.keys()) + + # Check if the `habitat.simulator.agents_order` + # is set and matches the agents' keys in `habitat.simulator.agents`. + assert len(sim_config.agents_order) == len(sim_config.agents) and set( + sim_config.agents_order + ) == set(sim_config.agents.keys()), ( + "habitat.simulator.agents_order should be set explicitly " + "and match the agents' keys in habitat.simulator.agents.\n" + f"habitat.simulator.agents_order: {sim_config.agents_order}\n" + f"habitat.simulator.agents: {list(sim_config.agents.keys())}" + ) + + OmegaConf.set_readonly(cfg, True) + + return cfg + + +def register_configs(): + """ + This method will register the Habitat-lab benchmark configurations. + """ + register_hydra_plugin(HabitatConfigPlugin) + + +def get_config( + config_path: str, + overrides: Optional[List[str]] = None, + configs_dir: str = _HABITAT_CFG_DIR, +) -> DictConfig: + r"""Returns habitat config object composed of configs from yaml file (config_path) and overrides. + + :param config_path: path to the yaml config file. + :param overrides: list of config overrides. For example, :py:`overrides=["habitat.seed=1"]`. + :param configs_dir: path to the config files root directory (defaults to :ref:`_HABITAT_CFG_DIR`). + :return: composed config object. + """ + register_configs() + config_path = get_full_config_path(config_path, configs_dir) + # If get_config is called from different threads, Hydra might + # get initialized twice leading to issues. This lock fixes it. + with lock, initialize_config_dir( + version_base=None, + config_dir=osp.dirname(config_path), + ): + cfg = compose( + config_name=osp.basename(config_path), + overrides=overrides if overrides is not None else [], + ) + + return patch_config(cfg) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/default_structured_configs.py b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/default_structured_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..d462a71058271d98adae092295ec3cb79a37c601 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/default_structured_configs.py @@ -0,0 +1,2675 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional + +from hydra.core.config_store import ConfigStore +from omegaconf import II, MISSING + +# __all__ is used for documentation. Only put in this list the configurations +# that have proper documentation for. +__all__ = [ + # HABITAT + "HabitatConfig", + # DATASET + "DatasetConfig", + # TASK + "TaskConfig", + # ENVIRONMENT + "EnvironmentConfig", + # NAVIGATION ACTIONS + "StopActionConfig", + "MoveForwardActionConfig", + "TurnLeftActionConfig", + "TurnLeftActionConfig", + "TurnRightActionConfig", + "LookUpActionConfig", + "LookDownActionConfig", + # NAVIGATION MEASURES + "NumStepsMeasurementConfig", + "DistanceToGoalMeasurementConfig", + "SuccessMeasurementConfig", + "SPLMeasurementConfig", + "SoftSPLMeasurementConfig", + "DistanceToGoalRewardMeasurementConfig", + # NAVIGATION LAB SENSORS + "ObjectGoalSensorConfig", + "InstanceImageGoalSensorConfig", + "InstanceImageGoalHFOVSensorConfig", + "CompassSensorConfig", + "GPSSensorConfig", + "PointGoalWithGPSCompassSensorConfig", + "HumanoidDetectorSensorConfig", + "ArmDepthBBoxSensorConfig", + "SpotHeadStereoDepthSensorConfig", + # REARRANGEMENT ACTIONS + "EmptyActionConfig", + "ArmActionConfig", + "BaseVelocityActionConfig", + "HumanoidJointActionConfig", + "HumanoidPickActionConfig", + "RearrangeStopActionConfig", + "OracleNavActionConfig", + "SelectBaseOrArmActionConfig", + # REARRANGEMENT LAB SENSORS + "RelativeRestingPositionSensorConfig", + "IsHoldingSensorConfig", + "EEPositionSensorConfig", + "JointSensorConfig", + "HumanoidJointSensorConfig", + "TargetStartSensorConfig", + "GoalSensorConfig", + "TargetStartGpsCompassSensorConfig", + "InitialGpsCompassSensorConfig", + "TargetGoalGpsCompassSensorConfig", + # REARRANGEMENT MEASUREMENTS + "EndEffectorToRestDistanceMeasurementConfig", + "RobotForceMeasurementConfig", + "DoesWantTerminateMeasurementConfig", + "ForceTerminateMeasurementConfig", + "ObjectToGoalDistanceMeasurementConfig", + "ObjAtGoalMeasurementConfig", + "ArtObjAtDesiredStateMeasurementConfig", + "RotDistToGoalMeasurementConfig", + "PddlStageGoalsMeasurementConfig", + "NavToPosSuccMeasurementConfig", + "SocialNavStatsMeasurementConfig", + "NavSeekSuccessMeasurementConfig", + # REARRANGEMENT MEASUREMENTS TASK REWARDS AND MEASURES + "RearrangePickSuccessMeasurementConfig", + "RearrangePickRewardMeasurementConfig", + "PlaceSuccessMeasurementConfig", + "PlaceRewardMeasurementConfig", + "ArtObjSuccessMeasurementConfig", + "ArtObjRewardMeasurementConfig", + "NavToObjSuccessMeasurementConfig", + "NavToObjRewardMeasurementConfig", + "PddlSuccessMeasurementConfig", + # PROFILING MEASURES + "RuntimePerfStatsMeasurementConfig", +] + + +@dataclass +class HabitatBaseConfig: + pass + + +@dataclass +class IteratorOptionsConfig(HabitatBaseConfig): + cycle: bool = True + shuffle: bool = True + group_by_scene: bool = True + num_episode_sample: int = -1 + max_scene_repeat_episodes: int = -1 + max_scene_repeat_steps: int = int(1e4) + step_repetition_range: float = 0.2 + + +@dataclass +class EnvironmentConfig(HabitatBaseConfig): + r""" + Some habitat environment configurations. + + :property max_episode_steps: The maximum number of environment steps before the episode ends. + :property max_episode_seconds: The maximum number of wall-clock seconds before the episode ends. + """ + max_episode_steps: int = 1000 + max_episode_seconds: int = 10000000 + iterator_options: IteratorOptionsConfig = IteratorOptionsConfig() + + +# ----------------------------------------------------------------------------- +# # Actions +# ----------------------------------------------------------------------------- +@dataclass +class ActionConfig(HabitatBaseConfig): + type: str = MISSING + + +@dataclass +class StopActionConfig(ActionConfig): + r""" + In Navigation tasks only, the stop action is a discrete action. When called, the Agent + will request to stop the navigation task. Note that this action is needed to + succeed in a Navigation task since the Success is determined by the Agent calling + the stop action within range of the target. + Note that this is different from the RearrangeStopActionConfig that works for + Rearrangement tasks only instead of the Navigation tasks. + """ + type: str = "StopAction" + + +@dataclass +class EmptyActionConfig(ActionConfig): + r""" + In Navigation tasks only, the pass action. The robot will do nothing. + """ + type: str = "EmptyAction" + + +# ----------------------------------------------------------------------------- +# # NAVIGATION actions +# ----------------------------------------------------------------------------- + + +@dataclass +class DiscreteNavigationActionConfig(ActionConfig): + tilt_angle: int = 15 # angle to tilt the camera up or down in degrees + + +@dataclass +class MoveForwardActionConfig(DiscreteNavigationActionConfig): + r""" + In Navigation tasks only, this discrete action will move the robot forward by + a fixed amount determined by the SimulatorConfig.forward_step_size amount. + """ + type: str = "MoveForwardAction" + + +@dataclass +class TurnLeftActionConfig(DiscreteNavigationActionConfig): + r""" + In Navigation tasks only, this discrete action will rotate the robot to the left + by a fixed amount determined by the SimulatorConfig.turn_angle amount. + """ + type: str = "TurnLeftAction" + + +@dataclass +class TurnRightActionConfig(DiscreteNavigationActionConfig): + r""" + In Navigation tasks only, this discrete action will rotate the robot to the right + by a fixed amount determined by the SimulatorConfig.turn_angle amount. + """ + type: str = "TurnRightAction" + + +@dataclass +class LookUpActionConfig(DiscreteNavigationActionConfig): + r""" + In Navigation tasks only, this discrete action will rotate the robot's camera up + by a fixed amount determined by the SimulatorConfig.tilt_angle amount. + """ + type: str = "LookUpAction" + + +@dataclass +class LookDownActionConfig(DiscreteNavigationActionConfig): + r""" + In Navigation tasks only, this discrete action will rotate the robot's camera down + by a fixed amount determined by the SimulatorConfig.tilt_angle amount. + """ + type: str = "LookDownAction" + + +@dataclass +class TeleportActionConfig(ActionConfig): + type: str = "TeleportAction" + + +@dataclass +class VelocityControlActionConfig(ActionConfig): + type: str = "VelocityAction" + # meters/sec + lin_vel_range: List[float] = field(default_factory=lambda: [0.0, 0.25]) + # deg/sec + ang_vel_range: List[float] = field(default_factory=lambda: [-10.0, 10.0]) + min_abs_lin_speed: float = 0.025 # meters/sec + min_abs_ang_speed: float = 1.0 # # deg/sec + time_step: float = 1.0 # seconds + + +# ----------------------------------------------------------------------------- +# # REARRANGE actions +# ----------------------------------------------------------------------------- +@dataclass +class ArmActionConfig(ActionConfig): + r""" + In Rearrangement tasks only, the action that will move the robot arm around. The action represents to delta angle (in radians) of each joint. + + :property grasp_thresh_dist: The grasp action will only work on the closest object if its distance to the end effector is smaller than this value. Only for `MagicGraspAction` grip_controller. + :property grip_controller: Can either be None, `MagicGraspAction` or `SuctionGraspAction`. If None, the arm will be unable to grip object. Magic grasp will grasp the object if the end effector is within grasp_thresh_dist of an object, with `SuctionGraspAction`, the object needs to be in contact with the end effector. + :property arm_joint_limit: If the user specify the joint limits. The dimension needs to be the same as arm_joint_dimensionality. Format: [[min_limit, max_limit]] + :property gaze_distance_range: The gaze action will only work on the closet object if its distance to the end effector is smaller than this value. Only for `GazeGraspAction` grip_controller. + :property center_cone_angle_threshold: The threshold angle between the line of sight and center_cone_vector. Only for `GazeGraspAction` grip_controller. + :property center_cone_vector: The vector that the camera's line of sight should be when grasping the object. Only for `GazeGraspAction` grip_controller. + """ + type: str = "ArmAction" + arm_controller: str = "ArmRelPosAction" + grip_controller: Optional[str] = None + arm_joint_mask: Optional[List[int]] = None + arm_joint_dimensionality: int = 7 + arm_joint_limit: Optional[List[float]] = None + grasp_thresh_dist: float = 0.15 + disable_grip: bool = False + delta_pos_limit: float = 0.0125 + ee_ctrl_lim: float = 0.015 + should_clip: bool = False + render_ee_target: bool = False + gaze_distance_range: Optional[List[float]] = None + center_cone_angle_threshold: float = 0.0 + center_cone_vector: Optional[List[float]] = None + auto_grasp: bool = False + + +@dataclass +class BaseVelocityActionConfig(ActionConfig): + r""" + In Rearrangement only. Corresponds to the base velocity. Contains two continuous actions, the first one controls forward and backward motion, the second the rotation. + """ + type: str = "BaseVelAction" + lin_speed: float = 10.0 + ang_speed: float = 10.0 + allow_dyn_slide: bool = True + allow_back: bool = True + + +@dataclass +class BaseVelocityNonCylinderActionConfig(ActionConfig): + r""" + In Rearrangement only for the non cylinder shape of the robot. Corresponds to the base velocity. Contains two continuous actions, the first one controls forward and backward motion, the second the rotation. + """ + type: str = "BaseVelNonCylinderAction" + # The max longitudinal and lateral linear speeds of the robot + lin_speed: float = 10.0 + longitudinal_lin_speed: float = 10.0 + lateral_lin_speed: float = 10.0 + # The max angular speed of the robot + ang_speed: float = 10.0 + # If we want to do sliding or not + allow_dyn_slide: bool = False + # If we allow the robot to move back or not + allow_back: bool = True + # There is a collision if the difference between the clamped NavMesh position and target position + # is more than collision_threshold for any point. + collision_threshold: float = 1e-5 + # If we allow the robot to move laterally. + enable_lateral_move: bool = False + # If the condition of sliding includes the checking of rotation + enable_rotation_check_for_dyn_slide: bool = True + + +@dataclass +class HumanoidJointActionConfig(ActionConfig): + r""" + In Rearrangement only. Corresponds to actions to change the humanoid joints. Contains the parameter num_joints, indicating the joints that can be modified. + """ + type: str = "HumanoidJointAction" + num_joints: int = 54 + + +@dataclass +class HumanoidPickActionConfig(ActionConfig): + r""" + In rearrangement tasks only. Config for humanoid to reach objects using IK. For now only contains the number of joints. May be extended with duration of action + """ + type: str = "HumanoidPickAction" + # Number of joints in the humanoid body, 54 for SMPL-X, 17 for SMPL + num_joints: int = 54 + # The amount we should move on every call to humanoid pick action + dist_move_per_step: float = 0.04 + # The distance at which we will snap/desnap an object, and start retracting the hand + dist_to_snap: float = 0.02 + + +@dataclass +class RearrangeStopActionConfig(ActionConfig): + r""" + In rearrangement tasks only, if the robot calls this action, the task will end. + """ + type: str = "RearrangeStopAction" + + +@dataclass +class PddlApplyActionConfig(ActionConfig): + type: str = "PddlApplyAction" + + +@dataclass +class OracleNavActionConfig(ActionConfig): + """ + Rearrangement Only, Oracle navigation action. + This action takes as input a discrete ID which refers to an object in the + PDDL domain. The oracle navigation controller then computes the actions to + navigate to that desired object. + """ + + type: str = "OracleNavAction" + # Whether the motion is in the form of base_velocity or human_joints + motion_control: str = "base_velocity" + num_joints: int = 17 + turn_velocity: float = 1.0 + forward_velocity: float = 1.0 + turn_thresh: float = 0.1 + dist_thresh: float = 0.2 + lin_speed: float = 10.0 + ang_speed: float = 10.0 + allow_dyn_slide: bool = True + allow_back: bool = True + spawn_max_dist_to_obj: float = 2.0 + num_spawn_attempts: int = 200 + # For social nav training only. It controls the distance threshold + # between the robot and the human and decide if the human wants to walk or not + human_stop_and_walk_to_robot_distance_threshold: float = -1.0 + + +@dataclass +class SelectBaseOrArmActionConfig(ActionConfig): + r""" + In rearrangement tasks only, if the robot calls this action, the task will end. + """ + type: str = "SelectBaseOrArmAction" + + +# ----------------------------------------------------------------------------- +# # EQA actions +# ----------------------------------------------------------------------------- +@dataclass +class AnswerActionConfig(ActionConfig): + type: str = "AnswerAction" + + +# ----------------------------------------------------------------------------- +# # TASK_SENSORS +# ----------------------------------------------------------------------------- +@dataclass +class LabSensorConfig(HabitatBaseConfig): + type: str = MISSING + + +@dataclass +class PointGoalSensorConfig(LabSensorConfig): + type: str = "PointGoalSensor" + goal_format: str = "POLAR" + dimensionality: int = 2 + + +@dataclass +class PointGoalWithGPSCompassSensorConfig(PointGoalSensorConfig): + """ + Indicates the position of the point goal in the frame of reference of the robot. + """ + + type: str = "PointGoalWithGPSCompassSensor" + + +@dataclass +class HumanoidDetectorSensorConfig(LabSensorConfig): + r""" + Check if the human is in frame + """ + type: str = "HumanoidDetectorSensor" + # The default human id is 100 + human_id: int = 100 + # How many pixels needed to consider that human is in frame + human_pixel_threshold: int = 1000 + # Image based or binary based + return_image: bool = False + # Is the return image bounding box or not + is_return_image_bbox: bool = False + + +@dataclass +class ArmDepthBBoxSensorConfig(LabSensorConfig): + r""" + Bounding box sensor to check if the object is in frame + """ + type: str = "ArmDepthBBoxSensor" + height: int = 480 + width: int = 640 + + +@dataclass +class SpotHeadStereoDepthSensorConfig(LabSensorConfig): + r""" + For Spot only. Sensor fusion for inputs of Spot stereo pair depth sensor + """ + type: str = "SpotHeadStereoDepthSensor" + height: int = 240 + width: int = 228 + + +@dataclass +class ObjectGoalSensorConfig(LabSensorConfig): + r""" + For Object Navigation tasks only. Generates a discrete observation containing + the id of the goal object for the episode. + + :property goal_spec: A string that can take the value TASK_CATEGORY_ID or OBJECT_ID. If the value is TASK_CATEGORY_ID, then the observation will be the id of the `episode.object_category` attribute, if the value is OBJECT_ID, then the observation will be the id of the first goal object. + :property goal_spec_max_val: If the `goal_spec` is OBJECT_ID, then `goal_spec_max_val` is the total number of different objects that can be goals. Note that this value must be greater than the largest episode goal category id. + """ + type: str = "ObjectGoalSensor" + goal_spec: str = "TASK_CATEGORY_ID" + goal_spec_max_val: int = 50 + + +@dataclass +class ImageGoalSensorConfig(LabSensorConfig): + type: str = "ImageGoalSensor" + + +@dataclass +class InstanceImageGoalSensorConfig(LabSensorConfig): + r""" + Used only by the InstanceImageGoal Navigation task. The observation is a rendered + image of the goal object within the scene. + """ + type: str = "InstanceImageGoalSensor" + + +@dataclass +class InstanceImageGoalHFOVSensorConfig(LabSensorConfig): + r""" + Used only by the InstanceImageGoal Navigation task. The observation is a single + float value corresponding to the Horizontal field of view (HFOV) in degrees of + the image provided by the `InstanceImageGoalSensor`. + """ + type: str = "InstanceImageGoalHFOVSensor" + + +@dataclass +class HeadingSensorConfig(LabSensorConfig): + type: str = "HeadingSensor" + + +@dataclass +class CompassSensorConfig(LabSensorConfig): + r""" + For Navigation tasks only. The observation of the + `EpisodicCompassSensor` is a single float value corresponding to + the angle difference in radians between the current rotation of the robot and the + start rotation of the robot along the vertical axis. + """ + type: str = "CompassSensor" + + +@dataclass +class GPSSensorConfig(LabSensorConfig): + r""" + For Navigation tasks only. The observation of the EpisodicGPSSensor are two float values + corresponding to the vector difference in the horizontal plane between the current position + and the start position of the robot (in meters). + """ + type: str = "GPSSensor" + dimensionality: int = 2 + + +@dataclass +class ProximitySensorConfig(LabSensorConfig): + type: str = "ProximitySensor" + max_detection_radius: float = 2.0 + + +@dataclass +class JointSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Returns the joint positions of the robot. + """ + type: str = "JointSensor" + dimensionality: int = 7 + arm_joint_mask: Optional[List[int]] = None + + +@dataclass +class HumanoidJointSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Returns the joint positions of the robot. + """ + type: str = "HumanoidJointSensor" + dimensionality: int = 17 * 4 + + +@dataclass +class EEPositionSensorConfig(LabSensorConfig): + r""" + Rearrangement only. the cartesian coordinates (3 floats) of the arm's end effector in the frame of reference of the robot's base. + """ + type: str = "EEPositionSensor" + + +@dataclass +class IsHoldingSensorConfig(LabSensorConfig): + r""" + Rearrangement only. A single float sensor with value 1.0 if the robot is grasping any object and 0.0 otherwise. + """ + type: str = "IsHoldingSensor" + + +@dataclass +class RelativeRestingPositionSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Sensor for the relative position of the end-effector's resting position, relative to the end-effector's current position. + The three values correspond to the cartesian coordinates of the resting position in the frame of reference of the end effector. + The desired resting position is determined by the habitat.task.desired_resting_position coordinates relative to the robot's base. + """ + + type: str = "RelativeRestingPositionSensor" + + +@dataclass +class JointVelocitySensorConfig(LabSensorConfig): + type: str = "JointVelocitySensor" + dimensionality: int = 7 + + +@dataclass +class OracleNavigationActionSensorConfig(LabSensorConfig): + type: str = "OracleNavigationActionSensor" + + +@dataclass +class RestingPositionSensorConfig(LabSensorConfig): + type: str = "RestingPositionSensor" + + +@dataclass +class ArtJointSensorConfig(LabSensorConfig): + type: str = "ArtJointSensor" + + +@dataclass +class NavGoalSensorConfig(LabSensorConfig): + type: str = "NavGoalSensor" + + +@dataclass +class ArtJointSensorNoVelSensorConfig(LabSensorConfig): + type: str = "ArtJointSensorNoVel" # TODO: add "Sensor" suffix + + +@dataclass +class MarkerRelPosSensorConfig(LabSensorConfig): + type: str = "MarkerRelPosSensor" + + +@dataclass +class TargetStartSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Returns the relative position from end effector to a target object that needs to be picked up. + """ + type: str = "TargetStartSensor" + goal_format: str = "CARTESIAN" + dimensionality: int = 3 + + +@dataclass +class TargetCurrentSensorConfig(LabSensorConfig): + type: str = "TargetCurrentSensor" + goal_format: str = "CARTESIAN" + dimensionality: int = 3 + + +@dataclass +class GoalSensorConfig(LabSensorConfig): + """ + Rearrangement only. Returns the relative position from end effector to a goal position in which the agent needs to place an object. + """ + + type: str = "GoalSensor" + goal_format: str = "CARTESIAN" + dimensionality: int = 3 + + +@dataclass +class NavGoalPointGoalSensorConfig(LabSensorConfig): + type: str = "NavGoalPointGoalSensor" + goal_is_human: bool = False + human_agent_idx: int = 1 + + +@dataclass +class GlobalPredicatesSensorConfig(LabSensorConfig): + type: str = "GlobalPredicatesSensor" + + +@dataclass +class MultiAgentGlobalPredicatesSensorConfig(LabSensorConfig): + type: str = "MultiAgentGlobalPredicatesSensor" + + +@dataclass +class AreAgentsWithinThresholdConfig(LabSensorConfig): + type: str = "AreAgentsWithinThreshold" + x_len: Optional[float] = None + y_len: Optional[float] = None + agent_idx: int = 0 + + +@dataclass +class HasFinishedOracleNavSensorConfig(LabSensorConfig): + type: str = "HasFinishedOracleNavSensor" + + +@dataclass +class HasFinishedHumanoidPickSensorConfig(LabSensorConfig): + type: str = "HasFinishedHumanoidPickSensor" + + +@dataclass +class OtherAgentGpsConfig(LabSensorConfig): + type: str = "OtherAgentGps" + + +@dataclass +class TargetStartGpsCompassSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Returns the initial position of every object that needs to be rearranged in composite tasks, in 2D polar coordinates. + """ + type: str = "TargetStartGpsCompassSensor" + + +@dataclass +class InitialGpsCompassSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Returns the relative distance to the initial starting location of the agent in 2D polar coordinates. + """ + type: str = "InitialGpsCompassSensor" + + +@dataclass +class TargetGoalGpsCompassSensorConfig(LabSensorConfig): + r""" + Rearrangement only. Returns the desired goal position of every object that needs to be rearranged in composite tasks, in 2D polar coordinates. + """ + type: str = "TargetGoalGpsCompassSensor" + + +@dataclass +class NavToSkillSensorConfig(LabSensorConfig): + type: str = "NavToSkillSensor" + num_skills: int = 8 + + +@dataclass +class AbsTargetStartSensorConfig(LabSensorConfig): + type: str = "AbsTargetStartSensor" + goal_format: str = "CARTESIAN" + dimensionality: int = 3 + + +@dataclass +class AbsGoalSensorConfig(LabSensorConfig): + type: str = "AbsGoalSensor" + goal_format: str = "CARTESIAN" + dimensionality: int = 3 + + +@dataclass +class DistToNavGoalSensorConfig(LabSensorConfig): + type: str = "DistToNavGoalSensor" + + +@dataclass +class LocalizationSensorConfig(LabSensorConfig): + type: str = "LocalizationSensor" + + +@dataclass +class QuestionSensorConfig(LabSensorConfig): + type: str = "QuestionSensor" + + +@dataclass +class InstructionSensorConfig(LabSensorConfig): + type: str = "InstructionSensor" + instruction_sensor_uuid: str = "instruction" + + +# ----------------------------------------------------------------------------- +# Measurements +# ----------------------------------------------------------------------------- +@dataclass +class MeasurementConfig(HabitatBaseConfig): + type: str = MISSING + + +@dataclass +class SuccessMeasurementConfig(MeasurementConfig): + r""" + For Navigation tasks only, Measures 1.0 if the robot reached a success and 0 otherwise. + A success is defined as calling the `StopAction` when the `DistanceToGoal` + Measure is smaller than `success_distance`. + + :property success_distance: The minimal distance the robot must be to the goal for a success. + """ + type: str = "Success" + success_distance: float = 0.2 + + +@dataclass +class SPLMeasurementConfig(MeasurementConfig): + r""" + For Navigation tasks only, Measures the SPL (Success weighted by Path Length) + ref: On Evaluation of Embodied Agents - Anderson et. al + https://arxiv.org/pdf/1807.06757.pdf + Measure is always 0 except at success where it will be + the ratio of the optimal distance from start to goal over the total distance + traveled by the agent. Maximum value is 1. + SPL = success * optimal_distance_to_goal / distance_traveled_so_far + """ + type: str = "SPL" + + +@dataclass +class SoftSPLMeasurementConfig(MeasurementConfig): + r""" + For Navigation tasks only, Similar to SPL, but instead of a boolean, + success is now calculated as 1 - (ratio of distance covered to target). + SoftSPL = max(0, 1 - distance_to_goal / optimal_distance_to_goal) * optimal_distance_to_goal / distance_traveled_so_far + """ + type: str = "SoftSPL" + + +@dataclass +class FogOfWarConfig: + draw: bool = True + visibility_dist: float = 5.0 + fov: int = 90 + + +@dataclass +class TopDownMapMeasurementConfig(MeasurementConfig): + type: str = "TopDownMap" + max_episode_steps: int = ( + EnvironmentConfig().max_episode_steps + ) # TODO : Use OmegaConf II() + map_padding: int = 3 + map_resolution: int = 1024 + draw_source: bool = True + draw_border: bool = True + draw_shortest_path: bool = True + draw_view_points: bool = True + draw_goal_positions: bool = True + # axes aligned bounding boxes + draw_goal_aabbs: bool = True + fog_of_war: FogOfWarConfig = FogOfWarConfig() + + +@dataclass +class CollisionsMeasurementConfig(MeasurementConfig): + type: str = "Collisions" + + +@dataclass +class RuntimePerfStatsMeasurementConfig(MeasurementConfig): + """ + If added to the measurements, this will time various sections of code in + the simulator and task logic. If using with a multi-environment trainer + (like DD-PPO) it is recommended to only log this stat for one environment + since this metric can include many numbers. + """ + + type: str = "RuntimePerfStats" + disable_logging: bool = False + + +@dataclass +class RobotForceMeasurementConfig(MeasurementConfig): + r""" + The amount of force in newton's applied by the robot. It computes both the instant and accumulated. + """ + type: str = "RobotForce" + min_force: float = 20.0 + + +@dataclass +class ForceTerminateMeasurementConfig(MeasurementConfig): + r""" + If the force is greater than a certain threshold, this measure will be 1.0 and 0.0 otherwise. + Note that if the measure is 1.0, the task will end as a result. + + :property max_accum_force: The threshold for the accumulated force. -1 is no threshold. + :property max_instant_force: The threshold for the current, instant force. -1 is no threshold. + """ + type: str = "ForceTerminate" + max_accum_force: float = -1.0 + max_instant_force: float = -1.0 + + +@dataclass +class RobotCollisionsMeasurementConfig(MeasurementConfig): + type: str = "RobotCollisions" + + +@dataclass +class ObjectToGoalDistanceMeasurementConfig(MeasurementConfig): + r""" + In rearrangement only. The distance between the target object and the goal position for the object. + """ + type: str = "ObjectToGoalDistance" + + +@dataclass +class EndEffectorToObjectDistanceMeasurementConfig(MeasurementConfig): + type: str = "EndEffectorToObjectDistance" + # Normally, we compute the L2 distance between the gripper and the object. However, + # sometimes we also want to make sure that the gripper is facing the object with a right angle/orientation. + # For instance, the gripper could face vertically on top of the object. + if_consider_gaze_angle: bool = False + # The vector that the camera's line of sight should be when grasping the object. + center_cone_vector: Optional[List[float]] = None + # Normally, you want the L2 distance between the gripper and the object as small as possible. + # However, there are cases where you want to constrain the distance to be close to a specific value. + desire_distance_between_gripper_object: float = 0.0 + + +@dataclass +class BaseToObjectDistanceMeasurementConfig(MeasurementConfig): + """L2 distance between the base and the object""" + + type: str = "BaseToObjectDistance" + + +@dataclass +class EndEffectorToRestDistanceMeasurementConfig(MeasurementConfig): + """ + Rearrangement only. Distance between current end effector position + and the resting position of the end effector. Requires that the + RelativeRestingPositionSensor is attached to the agent. + """ + + type: str = "EndEffectorToRestDistance" + + +@dataclass +class EndEffectorToGoalDistanceMeasurementConfig(MeasurementConfig): + type: str = "EndEffectorToGoalDistance" + + +@dataclass +class ArtObjAtDesiredStateMeasurementConfig(MeasurementConfig): + r""" + Rearrangement open/close container tasks only. Whether the articulated object (fridge or cabinet door) towards a desired state (open or closed) as defined by the task. + """ + type: str = "ArtObjAtDesiredState" + use_absolute_distance: bool = True + success_dist_threshold: float = 0.05 + + +@dataclass +class GfxReplayMeasureMeasurementConfig(MeasurementConfig): + type: str = "GfxReplayMeasure" + + +@dataclass +class EndEffectorDistToMarkerMeasurementConfig(MeasurementConfig): + type: str = "EndEffectorDistToMarker" + + +@dataclass +class ArtObjStateMeasurementConfig(MeasurementConfig): + type: str = "ArtObjState" + + +@dataclass +class ArtObjSuccessMeasurementConfig(MeasurementConfig): + r""" + Rearrangement open/close container tasks only. Requires art_obj_at_desired_state. Is 1.0 if the articulated object is in desired state and the end effector is within rest_dist_threshold of the resting position. If must_call_stop is True, the robot must also call the rearrange_stop action. + """ + type: str = "ArtObjSuccess" + rest_dist_threshold: float = 0.15 + must_call_stop: bool = True + + +@dataclass +class ArtObjRewardMeasurementConfig(MeasurementConfig): + r""" + Rearrangement open/close container tasks only. Requires art_obj_at_desired_state. + + :property dist_reward: At each step, the measure adds dist_reward times the distance the end effector moved towards the articulated object. + :property wrong_grasp_end: If true, the task will end if the robot picks the wrong articulated object. + :property wrong_grasp_pen: The penalty for picking the wrong articulated object. + :property art_dist_reward: At each step, increments the reward by the amount the articulated moved in the correct direction. + :property art_at_desired_state_reward: The reward for putting the articulated object in the right state. + :property grasp_reward: The reward for grasping the correct articulated object. + """ + type: str = "ArtObjReward" + dist_reward: float = 1.0 + wrong_grasp_end: bool = False + wrong_grasp_pen: float = 5.0 + art_dist_reward: float = 10.0 + ee_dist_reward: float = 10.0 + marker_dist_reward: float = 0.0 + art_at_desired_state_reward: float = 5.0 + grasp_reward: float = 0.0 + # General Rearrange Reward config + constraint_violate_pen: float = 10.0 + force_pen: float = 0.0 + max_force_pen: float = 1.0 + force_end_pen: float = 10.0 + count_coll_pen: float = -1.0 + max_count_colls: int = -1 + count_coll_end_pen: float = 1.0 + + +@dataclass +class RotDistToGoalMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Navigation task only. The angle between the forward direction of the agent and the direction to the goal location. + """ + type: str = "RotDistToGoal" + + +@dataclass +class DistToGoalMeasurementConfig(MeasurementConfig): + type: str = "DistToGoal" + + +@dataclass +class BadCalledTerminateMeasurementConfig(MeasurementConfig): + type: str = "BadCalledTerminate" + bad_term_pen: float = 0.0 + decay_bad_term: bool = False + + +@dataclass +class NavToPosSuccMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Navigation task only. The value is 1.0 if the robot is within success_distance of the goal position. + """ + type: str = "NavToPosSucc" + success_distance: float = 1.5 + + +@dataclass +class SocialNavStatsMeasurementConfig(MeasurementConfig): + r""" + Social nav stats computation + """ + type: str = "SocialNavStats" + # Check if the human is inside the frame or not + check_human_in_frame: bool = False + # The safety distance + min_dis_human: float = 1.0 + max_dis_human: float = 2.0 + # The human id + human_id: int = 100 + # The pixel needed + human_detect_pixel_threshold: int = 1000 + # The total number of steps + total_steps: int = 1500 + # If we want to compute the shortest path to human + enable_shortest_path_computation: bool = False + # The min distance for considering backup and yield motions + dis_threshold_for_backup_yield: float = 1.5 + # The min vel for considering yield motion + min_abs_vel_for_yield: float = 1.0 + # The dot product value for considering that the robot is facing human + robot_face_human_threshold: float = 0.5 + # Agent ids + robot_idx: int = 0 + human_idx: int = 1 + + +@dataclass +class NavSeekSuccessMeasurementConfig(MeasurementConfig): + r""" + Social nav seek success measurement + """ + type: str = "SocialNavSeekSuccess" + # If the robot needs to look at the target + must_look_at_targ: bool = True + must_call_stop: bool = True + # distance in radians. + success_angle_dist: float = 0.261799 + # distance + following_step_succ_threshold: int = 800 + safe_dis_min: float = 1.0 + safe_dis_max: float = 2.0 + need_to_face_human: bool = False + use_geo_distance: bool = False + facing_threshold: float = 0.5 + # Set the agent ids + robot_idx: int = 0 + human_idx: int = 1 + + +@dataclass +class NavToObjRewardMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Navigation task only. The reward for rearrangement navigation. + + :property dist_reward: At each step, the measure adds dist_reward times the distance the robot's base moved towards the goal position. + :property should_reward_turn: If true, the robot receives a reward for turning towards the target position. + :property angle_dist_reward: The reward multiplier for the robot turning towards the goal position. + """ + type: str = "NavToObjReward" + # reward the agent for facing the object? + should_reward_turn: bool = True + # what distance do we start giving the reward for facing the object? + turn_reward_dist: float = 3.0 + # multiplier on the angle distance to the goal. + angle_dist_reward: float = 1.0 + dist_reward: float = 1.0 + constraint_violate_pen: float = 1.0 + force_pen: float = 0.0001 + max_force_pen: float = 0.01 + force_end_pen: float = 1.0 + count_coll_pen: float = -1.0 + max_count_colls: int = -1 + count_coll_end_pen: float = 1.0 + + +@dataclass +class NavToObjSuccessMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Navigation only. Takes the value 1.0 when the Robot successfully navigated to the target object. Depends on nav_to_pos_succ. + + :property must_look_at_targ: If true, the robot must be facing the correct object in addition to being close to it. + :property must_call_stop: If true, the robot must in addition, call the rearrange_stop action for this measure to be a success. + :property success_angle_dist: When the robot must look at the target, this is the maximum angle in radians the robot can have when facing the object. + """ + type: str = "NavToObjSuccess" + must_look_at_targ: bool = True + must_call_stop: bool = True + # distance in radians. + success_angle_dist: float = 0.261799 + + +@dataclass +class RearrangeReachRewardMeasurementConfig(MeasurementConfig): + type: str = "RearrangeReachReward" + scale: float = 1.0 + diff_reward: bool = True + sparse_reward: bool = False + + +@dataclass +class RearrangeReachSuccessMeasurementConfig(MeasurementConfig): + type: str = "RearrangeReachSuccess" + succ_thresh: float = 0.2 + + +@dataclass +class NumStepsMeasurementConfig(MeasurementConfig): + r""" + In both Navigation and Rearrangement tasks, counts the number of steps since + the start of the episode. + """ + type: str = "NumStepsMeasure" + + +@dataclass +class ZeroMeasurementConfig(MeasurementConfig): + r""" + Always returns 0. Can we used for a sparse reward or a task without any + success criteria. + """ + type: str = "ZeroMeasure" + + +@dataclass +class DidPickObjectMeasurementConfig(MeasurementConfig): + type: str = "DidPickObjectMeasure" + + +@dataclass +class DidViolateHoldConstraintMeasurementConfig(MeasurementConfig): + type: str = "DidViolateHoldConstraintMeasure" + + +@dataclass +class MoveObjectsRewardMeasurementConfig(MeasurementConfig): + type: str = "MoveObjectsReward" + pick_reward: float = 1.0 + success_dist: float = 0.15 + single_rearrange_reward: float = 1.0 + dist_reward: float = 1.0 + constraint_violate_pen: float = 10.0 + force_pen: float = 0.001 + max_force_pen: float = 1.0 + force_end_pen: float = 10.0 + count_coll_pen: float = -1.0 + max_count_colls: int = -1 + count_coll_end_pen: float = 1.0 + + +@dataclass +class RearrangePickRewardMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Only. Requires the end_effector_sensor lab sensor. The reward for the pick task. + + :property dist_reward: At each step, the measure adds dist_reward times the distance the end effector moved towards the target. + :property pick_reward: If the robot picks the target object, it receives pick_reward reward. + :property drop_pen: The penalty for dropping the object. + :property wrong_pick_pen: The penalty for picking the wrong object. + :property force_pen: At each step, adds a penalty of force_pen times the current force on the robot. + :property drop_obj_should_end: If true, the task will end if the robot drops the object. + :property wrong_pick_should_end: If true, the task will end if the robot picks the wrong object. + :property max_target_distance: default: -1. If it is positive, then we terminate the episode if the robot distance to object is above this value. + :property max_target_distance_pen: If the robot is too far away, then we terminate the episode by giving the penality. + :property non_desire_ee_local_pos_dis: default: -1. If positive, we terminate the episode if the robot moves the arm below this threshold + :property non_desire_ee_local_pos_pen: If the robot moves the arm there, then we terminate the episode by giving the penality. + :property non_desire_ee_local_pos: If given, we do not want the robot to move the arm there + :property camera_looking_down_angle: default: -1. If positive, we check the robot camera looking angle to the ground + :property camera_looking_down_pen: If the robot camera looking angle is too small (the robot looks down), we terminate the episode and with this much penality + """ + type: str = "RearrangePickReward" + dist_reward: float = 2.0 + pick_reward: float = 2.0 + constraint_violate_pen: float = 1.0 + drop_pen: float = 0.5 + wrong_pick_pen: float = 0.5 + force_pen: float = 0.0001 + max_force_pen: float = 0.01 + force_end_pen: float = 1.0 + use_diff: bool = True + drop_obj_should_end: bool = True + wrong_pick_should_end: bool = True + count_coll_pen: float = -1.0 + max_count_colls: int = -1 + count_coll_end_pen: float = 1.0 + max_target_distance: float = -1.0 + max_target_distance_pen: float = 1.0 + non_desire_ee_local_pos_dis: float = -1.0 + non_desire_ee_local_pos_pen: float = 1.0 + non_desire_ee_local_pos: Optional[List[float]] = None + camera_looking_down_angle: float = -1.0 + camera_looking_down_pen: float = 1.0 + + +@dataclass +class RearrangePickSuccessMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Only. Requires the end_effector_sensor lab sensor. 1.0 if the robot picked the target object. + + :property ee_resting_success_threshold: -1 if we do not consider resetting the arm to the resting location + """ + type: str = "RearrangePickSuccess" + ee_resting_success_threshold: float = 0.15 + + +@dataclass +class ObjAtGoalMeasurementConfig(MeasurementConfig): + r""" + The measure is a dictionary of target indexes to float. The values are 1 if the object is within succ_thresh of the goal position for that object. + + :property succ_thresh: The threshold distance below which an object is considered at the goal location. + """ + type: str = "ObjAtGoal" + succ_thresh: float = 0.15 + + +@dataclass +class PlaceRewardMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Only. Requires the end_effector_sensor lab sensor. The reward for the place task. + + :property dist_reward: At each step, the measure adds dist_reward times the distance the end effector moved towards the target. + :property place_reward: If the robot placed the target object correctly, it receives place_reward reward. + :property drop_pen: The penalty for dropping the object. + :property force_pen: At each step, adds a penalty of force_pen times the current force on the robot. + :property wrong_drop_should_end: If true, the task will end if the robot drops the object. + """ + type: str = "PlaceReward" + dist_reward: float = 2.0 + place_reward: float = 5.0 + drop_pen: float = 0.0 + use_diff: bool = True + use_ee_dist: bool = False + wrong_drop_should_end: bool = True + constraint_violate_pen: float = 0.0 + force_pen: float = 0.0001 + max_force_pen: float = 0.0 + force_end_pen: float = 1.0 + min_dist_to_goal: float = 0.15 + count_coll_pen: float = -1.0 + max_count_colls: int = -1 + count_coll_end_pen: float = 1.0 + + +@dataclass +class PlaceSuccessMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Only. Requires the end_effector_sensor lab sensor. 1.0 if the robot placed the target object on the goal position and has its end effector within ee_resting_success_threshold of its resting position. + """ + type: str = "PlaceSuccess" + ee_resting_success_threshold: float = 0.15 + + +@dataclass +class PddlStageGoalsMeasurementConfig(MeasurementConfig): + r""" + PDDL Rearrangement only. 1.0 if the agent complete a particular stage defined in `stage_goals` and 0.0 otherwise. Stage goals are specified in the `pddl` task description. + """ + type: str = "PddlStageGoals" + + +@dataclass +class PddlSuccessMeasurementConfig(MeasurementConfig): + r""" + PDDL rearrangement tasks only (rearrange, set_table, tidy_house). It uses a goal pddl expression to validate the success. + + :property must_call_stop: If true, the robot must in addition, call the rearrange_stop action for this measure to be a success. + """ + type: str = "PddlSuccess" + must_call_stop: bool = True + + +@dataclass +class PddlSubgoalReward(MeasurementConfig): + type: str = "PddlSubgoalReward" + stage_sparse_reward: float = 1.0 + + +@dataclass +class DidAgentsCollideConfig(MeasurementConfig): + type: str = "DidAgentsCollide" + + +@dataclass +class NumAgentsCollideConfig(MeasurementConfig): + type: str = "NumAgentsCollide" + + +@dataclass +class RearrangeCooperateRewardConfig(PddlSubgoalReward): + type: str = "RearrangeCooperateReward" + stage_sparse_reward: float = 1.0 + end_on_collide: bool = True + # Positive penalty means give negative reward. + collide_penalty: float = 1.0 + + +@dataclass +class CooperateSubgoalRewardConfig(PddlSubgoalReward): + type: str = "CooperateSubgoalReward" + stage_sparse_reward: float = 1.0 + end_on_collide: bool = True + # Positive penalty means give negative reward. + collide_penalty: float = 1.0 + + +@dataclass +class SocialNavReward(MeasurementConfig): + r""" + The reward for the social navigation tasks. + """ + type: str = "SocialNavReward" + # The safety distance between the robot and the human + safe_dis_min: float = 1.0 + safe_dis_max: float = 2.0 + # If the safety distance is within the threshold, then + # the agent receives this amount of reward + safe_dis_reward: float = 2.0 + # If the distance is below this threshold, the robot + # starts receiving an additional orientation reward + facing_human_dis: float = 3.0 + # -1 means that there is no facing_human_reward + facing_human_reward: float = -1.0 + # toward_human_reward default is 1.0 + toward_human_reward: float = 1.0 + # -1 means that there is no near_human_bonus + near_human_bonus: float = -1.0 + # -1 means that there is no exploration reward + explore_reward: float = -1.0 + # If we want to use geo distance to measure the distance + # between the robot and the human + use_geo_distance: bool = False + # Set the id of the agent + robot_idx: int = 0 + human_idx: int = 1 + constraint_violate_pen: float = 10.0 + force_pen: float = 0.0 + max_force_pen: float = 1.0 + force_end_pen: float = 10.0 + # Collision based penality for kinematic simulation + count_coll_pen: float = -1.0 + max_count_colls: int = -1 + count_coll_end_pen: float = 1.0 + collide_penalty: float = 1.0 + + +@dataclass +class DoesWantTerminateMeasurementConfig(MeasurementConfig): + r""" + Rearrangement Only. Measures 1 if the agent has called the stop action and 0 otherwise. + """ + type: str = "DoesWantTerminate" + + +@dataclass +class CorrectAnswerMeasurementConfig(MeasurementConfig): + type: str = "CorrectAnswer" + + +@dataclass +class EpisodeInfoMeasurementConfig(MeasurementConfig): + type: str = "EpisodeInfo" + + +@dataclass +class DistanceToGoalMeasurementConfig(MeasurementConfig): + r""" + In Navigation tasks only, measures the geodesic distance to the goal. + + :property distance_to: If 'POINT' measures the distance to the closest episode goal. If 'VIEW_POINTS' measures the distance to the episode's goal's viewpoint. + """ + type: str = "DistanceToGoal" + distance_to: str = "POINT" + + +@dataclass +class DistanceToGoalRewardMeasurementConfig(MeasurementConfig): + r""" + In Navigation tasks only, measures a reward based on the distance towards the goal. + The reward is `- (new_distance - previous_distance)` i.e. the + decrease of distance to the goal. + """ + type: str = "DistanceToGoalReward" + + +@dataclass +class AnswerAccuracyMeasurementConfig(MeasurementConfig): + type: str = "AnswerAccuracy" + + +@dataclass +class TaskConfig(HabitatBaseConfig): + r""" + The definition of the task in Habitat. + + :property type: The registered task that will be used. For example : `InstanceImageNav-v1` or `ObjectNav-v1` + :property physics_target_sps: The size of each simulator physics update will be 1 / physics_target_sps. + :property reward_measure: The name of the Measurement that will correspond to the reward of the robot. This value must be a key present in the dictionary of Measurements in the habitat configuration. For example, `distance_to_goal_reward` for navigation or `place_reward` for the rearrangement place task. + :property success_measure: The name of the Measurement that will correspond to the success criteria of the robot. This value must be a key present in the dictionary of Measurements in the habitat configuration. If the measurement has a non-zero value, the episode is considered a success. + :property end_on_success: If True, the episode will end when the success measure indicates success. Otherwise the episode will go on (this is useful when doing hierarchical learning and the robot has to explicitly decide when to change policies) + :property task_spec: When doing the `RearrangePddlTask-v0` only, will look for a pddl plan of that name to determine the sequence of tasks that need to be completed. The format of the pddl plans files is undocumented. + :property task_spec_base_path: When doing the `RearrangePddlTask-v0` only, the relative path where the task_spec file will be searched. + :property spawn_max_dists_to_obj: For `RearrangePickTask-v0` task only. Controls the maximum distance the robot can be spawned from the target object. + :property base_angle_noise: For Rearrangement tasks only. Controls the standard deviation of the random normal noise applied to the base's rotation angle at the start of an episode. + :property base_noise: For Rearrangement tasks only. Controls the standard deviation of the random normal noise applied to the base's position at the start of an episode. + + There are many different Tasks determined by the `habitat.task.type` config: + + - Point navigation : `Nav-0` + - Image navigation : `Nav-0` + - Instance image navigation:`InstanceImageNav-v1` + - Object navigation : `ObjectNav-v1` + - Rearrangement close drawer: `RearrangeCloseDrawerTask-v0` + - Rearrangement open drawer: `RearrangeOpenDrawerTask-v0` + - Rearrangement close fridge : `RearrangeCloseFridgeTask-v0` + - Rearrangement open fridge : `RearrangeOpenFridgeTask-v0` + - Rearrangement navigate to object : `NavToObjTask-v0` + - Rearrangement pick : `RearrangePickTask-v0` + - Rearrangement place : `RearrangePlaceTask-v0` + - Rearrangement do nothing : `RearrangeEmptyTask-v0` + - Rearrangement reach : `RearrangeReachTask-v0` + - Rearrangement composite tasks : `RearrangePddlTask-v0` + """ + physics_target_sps: float = 60.0 + reward_measure: Optional[str] = None + success_measure: Optional[str] = None + success_reward: float = 2.5 + slack_reward: float = -0.01 + end_on_success: bool = False + # NAVIGATION task + type: str = "Nav-v0" + # Temporary structure for sensors + lab_sensors: Dict[str, LabSensorConfig] = field(default_factory=dict) + measurements: Dict[str, MeasurementConfig] = field(default_factory=dict) + # Measures to only construct in the first environment of the first rank for + # vectorized environments. + rank0_env0_measure_names: List[str] = field( + default_factory=lambda: ["habitat_perf"] + ) + # Measures to only record in the first rank for vectorized environments. + rank0_measure_names: List[str] = field(default_factory=list) + goal_sensor_uuid: str = "pointgoal" + # REARRANGE task + count_obj_collisions: bool = True + settle_steps: int = 5 + constraint_violation_ends_episode: bool = True + constraint_violation_drops_object: bool = False + # Forced to regenerate the starts even if they are already cached + force_regenerate: bool = False + # Saves the generated starts to a cache if they are not already generated + should_save_to_cache: bool = False + object_in_hand_sample_prob: float = 0.167 + min_start_distance: float = 3.0 + gfx_replay_dir = "data/replays" + render_target: bool = True + # Spawn parameters + filter_colliding_states: bool = True + num_spawn_attempts: int = 200 + spawn_max_dist_to_obj: float = 2.0 + base_angle_noise: float = 0.523599 + spawn_max_dist_to_obj_delta: float = 0.02 + # Factor to shrink the receptacle sampling volume when predicates place + # objects on top of receptacles. + recep_place_shrink_factor: float = 0.8 + # EE sample parameters + ee_sample_factor: float = 0.2 + ee_exclude_region: float = 0.0 + base_noise: float = 0.05 + spawn_region_scale: float = 0.2 + joint_max_impulse: float = -1.0 + desired_resting_position: List[float] = field( + default_factory=lambda: [0.5, 0.0, 1.0] + ) + use_marker_t: bool = True + cache_robot_init: bool = False + success_state: float = 0.0 + # Measurements for composite tasks. + should_enforce_target_within_reach: bool = False + # COMPOSITE task CONFIG + task_spec_base_path: str = "habitat/task/rearrange/pddl/" + task_spec: str = "" + # PDDL domain params + pddl_domain_def: str = "replica_cad" + obj_succ_thresh: float = 0.3 + # Disable drop except for when the object is at its goal. + enable_safe_drop: bool = False + art_succ_thresh: float = 0.15 + robot_at_thresh: float = 2.0 + + # The minimum distance between the agents at start. If < 0 + # there is no minimal distance + min_distance_start_agents: float = -1.0 + actions: Dict[str, ActionConfig] = MISSING + + +@dataclass +class SimulatorSensorConfig(HabitatBaseConfig): + type: str = MISSING + height: int = 480 + width: int = 640 + position: List[float] = field(default_factory=lambda: [0.0, 1.25, 0.0]) + # Euler's angles: + orientation: List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0]) + + +@dataclass +class SimulatorCameraSensorConfig(SimulatorSensorConfig): + hfov: int = 90 # horizontal field of view in degrees + sensor_subtype: str = "PINHOLE" + noise_model: str = "None" + noise_model_kwargs: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class SimulatorDepthSensorConfig(SimulatorSensorConfig): + min_depth: float = 0.0 + max_depth: float = 10.0 + normalize_depth: bool = True + + +@dataclass +class HabitatSimRGBSensorConfig(SimulatorCameraSensorConfig): + type: str = "HabitatSimRGBSensor" + + +@dataclass +class HabitatSimDepthSensorConfig(SimulatorCameraSensorConfig): + type: str = "HabitatSimDepthSensor" + min_depth: float = 0.0 + max_depth: float = 10.0 + normalize_depth: bool = True + + +@dataclass +class HabitatSimSemanticSensorConfig(SimulatorCameraSensorConfig): + type: str = "HabitatSimSemanticSensor" + + +@dataclass +class HabitatSimEquirectangularRGBSensorConfig(SimulatorSensorConfig): + type: str = "HabitatSimEquirectangularRGBSensor" + + +@dataclass +class HabitatSimEquirectangularDepthSensorConfig(SimulatorDepthSensorConfig): + type: str = "HabitatSimEquirectangularDepthSensor" + + +@dataclass +class HabitatSimEquirectangularSemanticSensorConfig(SimulatorSensorConfig): + type: str = "HabitatSimEquirectangularSemanticSensor" + + +@dataclass +class SimulatorFisheyeSensorConfig(SimulatorSensorConfig): + type: str = "HabitatSimFisheyeSensor" + height: int = SimulatorSensorConfig().width + # The default value (alpha, xi) is set to match the lens "GoPro" found in + # Table 3 of this paper: Vladyslav Usenko, Nikolaus Demmel and + # Daniel Cremers: The Double Sphere Camera Model, + # The International Conference on 3D Vision (3DV), 2018 + # You can find the intrinsic parameters for the other lenses + # in the same table as well. + xi: float = -0.27 + alpha: float = 0.57 + focal_length: List[float] = field(default_factory=lambda: [364.84, 364.86]) + # Place camera at center of screen + # Can be specified, otherwise is calculated automatically. + # principal_point_offset defaults to (h/2,w/2) + principal_point_offset: Optional[List[float]] = None + sensor_model_type: str = "DOUBLE_SPHERE" + + +@dataclass +class HabitatSimFisheyeRGBSensorConfig(SimulatorFisheyeSensorConfig): + type: str = "HabitatSimFisheyeRGBSensor" + + +@dataclass +class SimulatorFisheyeDepthSensorConfig(SimulatorFisheyeSensorConfig): + type: str = "HabitatSimFisheyeDepthSensor" + min_depth: float = SimulatorDepthSensorConfig().min_depth + max_depth: float = SimulatorDepthSensorConfig().max_depth + normalize_depth: bool = SimulatorDepthSensorConfig().normalize_depth + + +@dataclass +class HabitatSimFisheyeSemanticSensorConfig(SimulatorFisheyeSensorConfig): + type: str = "HabitatSimFisheyeSemanticSensor" + + +@dataclass +class HeadRGBSensorConfig(HabitatSimRGBSensorConfig): + uuid: str = "head_rgb" + width: int = 256 + height: int = 256 + + +@dataclass +class HeadDepthSensorConfig(HabitatSimDepthSensorConfig): + uuid: str = "head_depth" + width: int = 256 + height: int = 256 + + +@dataclass +class HeadStereoLeftDepthSensorConfig(HabitatSimDepthSensorConfig): + uuid: str = "head_stereo_left_depth" + width: int = 256 + height: int = 256 + + +@dataclass +class HeadStereoRightDepthSensorConfig(HabitatSimDepthSensorConfig): + uuid: str = "head_stereo_right_depth" + width: int = 256 + height: int = 256 + + +@dataclass +class HeadPanopticSensorConfig(HabitatSimSemanticSensorConfig): + uuid: str = "head_panoptic" + width: int = 256 + height: int = 256 + + +@dataclass +class ArmPanopticSensorConfig(HabitatSimSemanticSensorConfig): + uuid: str = "articulated_agent_arm_panoptic" + width: int = 256 + height: int = 256 + + +@dataclass +class JawPanopticSensorConfig(HabitatSimSemanticSensorConfig): + uuid: str = "articulated_agent_jaw_panoptic" + width: int = 256 + height: int = 256 + + +@dataclass +class ArmRGBSensorConfig(HabitatSimRGBSensorConfig): + uuid: str = "articulated_agent_arm_rgb" + width: int = 256 + height: int = 256 + + +@dataclass +class ArmDepthSensorConfig(HabitatSimDepthSensorConfig): + uuid: str = "articulated_agent_arm_depth" + width: int = 256 + height: int = 256 + + +@dataclass +class JawRGBSensorConfig(HabitatSimRGBSensorConfig): + uuid: str = "articulated_agent_jaw_rgb" + width: int = 256 + height: int = 256 + + +@dataclass +class JawDepthSensorConfig(HabitatSimDepthSensorConfig): + uuid: str = "articulated_agent_jaw_depth" + width: int = 256 + height: int = 256 + + +@dataclass +class ThirdRGBSensorConfig(HabitatSimRGBSensorConfig): + uuid: str = "third_rgb" + width: int = 512 + height: int = 512 + + +@dataclass +class ThirdDepthSensorConfig(HabitatSimDepthSensorConfig): + uuid: str = "third_depth" # TODO: third_rgb on the main branch + # check if it won't cause any errors + + +@dataclass +class AgentConfig(HabitatBaseConfig): + height: float = 1.5 + radius: float = 0.1 + max_climb: float = 0.2 + max_slope: float = 45.0 + grasp_managers: int = 1 + sim_sensors: Dict[str, Any] = field(default_factory=dict) + is_set_start_state: bool = False + start_position: List[float] = field(default_factory=lambda: [0, 0, 0]) + start_rotation: List[float] = field(default_factory=lambda: [0, 0, 0, 1]) + joint_start_noise: float = 0.1 + joint_that_can_control: Optional[List[int]] = None + # Hard-code the robot joint start. `joint_start_noise` still applies. + joint_start_override: Optional[List[float]] = None + articulated_agent_urdf: Optional[str] = None + articulated_agent_type: Optional[str] = None + ik_arm_urdf: Optional[str] = None + # File to motion data, used to play pre-recorded motions + motion_data_path: str = "" + auto_update_sensor_transform: bool = True + """ + If `True`, the agent's sensor transforms are automatically updated every frame. + """ + # TODO: Remove this flag once sensors are decoupled from agents. + + +@dataclass +class RendererConfig(HabitatBaseConfig): + r"""Configuration for the renderer. + + :property enable_batch_renderer: [Experimental] Enables batch rendering, which accelerates rendering for concurrent environments. See env_batch_renderer.py for details. + :property composite_files: List of composite GLTF files to be pre-loaded by the batch renderer. + :property classic_replay_renderer: For debugging. Create a ClassicReplayRenderer instead of BatchReplayRenderer when enable_batch_renderer is active. + """ + + enable_batch_renderer: bool = False + composite_files: Optional[List[str]] = None + classic_replay_renderer: bool = False + + +@dataclass +class HabitatSimV0Config(HabitatBaseConfig): + gpu_device_id: int = 0 + # Use Habitat-Sim's GPU->GPU copy mode to return rendering results in + # pytorch tensors. Requires Habitat-Sim to be built with --with-cuda. + # This will generally imply sharing cuda tensors between processes. + # Read here: + # https://pytorch.org/docs/stable/multiprocessing.html#sharing-cuda-tensors + # for the caveats that results in + gpu_gpu: bool = False + # Whether the agent slides on collisions + allow_sliding: bool = True + frustum_culling: bool = True + enable_physics: bool = False + enable_hbao: bool = False + physics_config_file: str = "./data/default.physics_config.json" + # Possibly unstable optimization for extra performance + # with concurrent rendering + leave_context_with_background_renderer: bool = False + enable_gfx_replay_save: bool = False + + +@dataclass +class SimulatorConfig(HabitatBaseConfig): + type: str = "Sim-v0" + forward_step_size: float = 0.25 # in metres + turn_angle: int = 10 # angle to rotate left or right in degrees + create_renderer: bool = False + requires_textures: bool = True + # Sleep options + auto_sleep: bool = False + step_physics: bool = True + concur_render: bool = False + # If markers should be updated at every step: + needs_markers: bool = True + # If the articulated_agent camera positions should be updated at every step: + update_articulated_agent: bool = True + scene: str = "data/scene_datasets/habitat-test-scenes/van-gogh-room.glb" + # The scene dataset to load in the metadatamediator, + # should contain simulator.scene: + scene_dataset: str = "default" + # A list of directory or config paths to search in addition to the dataset + # for object configs. should match the generated episodes for the task: + additional_object_paths: List[str] = field(default_factory=list) + # Use config.seed (can't reference Config.seed) or define via code + # otherwise it leads to circular references: + # + seed: int = II("habitat.seed") + default_agent_id: int = 0 + debug_render: bool = False + debug_render_articulated_agent: bool = False + kinematic_mode: bool = False + # If False, will skip setting the semantic IDs of objects in + # `rearrange_sim.py` (there is overhead to this operation so skip if not + # using semantic information). + should_setup_semantic_ids: bool = True + # If in render mode a visualization of the rearrangement goal position + # should also be displayed + debug_render_goal: bool = True + robot_joint_start_noise: float = 0.0 + # Rearrange agent setup + ctrl_freq: float = 120.0 + ac_freq_ratio: int = 4 + load_objs: bool = True + # Rearrange agent grasping + hold_thresh: float = 0.15 + grasp_impulse: float = 10000.0 + # we assume agent(s) to be set explicitly + agents: Dict[str, AgentConfig] = MISSING + # agents_order specifies the order in which the agents + # are stored on the habitat-sim side. + # In other words, the order to return the observations and accept + # the actions when using the environment API. + # If the number of agents is greater than one, + # then agents_order has to be set explicitly. + agents_order: List[str] = MISSING + + # Simulator should use default navmesh settings from agent config + default_agent_navmesh: bool = True + # if default navmesh is used, should it include static objects + navmesh_include_static_objects: bool = False + + habitat_sim_v0: HabitatSimV0Config = HabitatSimV0Config() + # ep_info is added to the config in some rearrange tasks inside + # merge_sim_episode_with_object_config + ep_info: Optional[Any] = None + # The offset id values for the object + object_ids_start: int = 100 + # Configuration for rendering + renderer: RendererConfig = RendererConfig() + + +@dataclass +class LocobotConfig(HabitatBaseConfig): + actions: List[str] = field( + default_factory=lambda: ["base_actions", "camera_actions"] + ) + base_actions: List[str] = field( + default_factory=lambda: ["go_to_relative", "go_to_absolute"] + ) + camera_actions: List[str] = field( + default_factory=lambda: ["set_pan", "set_tilt", "set_pan_tilt"] + ) + + +@dataclass +class DatasetConfig(HabitatBaseConfig): + r"""Configuration for the dataset of the task. + + :property type: The key for the dataset class that will be used. Examples of such keys are `PointNav-v1`, `ObjectNav-v1`, `InstanceImageNav-v1` or `RearrangeDataset-v0`. Different datasets have different properties so you should use the dataset that fits your task. + :property scenes_dir: The path to the directory containing the scenes that will be used. You should put all your scenes in the same folder (example `data/scene_datasets`) to avoid having to change it. + :property data_path: The path to the episode dataset. Episodes need to be compatible with the `type` argument (so they will load properly) and only use scenes that are present in the `scenes_dir`. + :property split: `data_path` can have a `split` in the path. For example: "data/datasets/pointnav/habitat-test-scenes/v1/{split}/{split}.json.gz" the value in "{split}" will be replaced by the value of the `split` argument. This allows to easily swap between training, validation and test episodes by only changing the split argument. + :property metadata: Optional. Additional information for interpreting the dataset. + + A dataset consists of episodes + (a start configuration for a task within a scene) and a scene dataset + (with all the assets needed to instantiate the task) + """ + type: str = "PointNav-v1" + split: str = "train" + scenes_dir: str = "data/scene_datasets" + content_scenes: List[str] = field(default_factory=lambda: ["*"]) + data_path: str = ( + "data/datasets/pointnav/" + "habitat-test-scenes/v1/{split}/{split}.json.gz" + ) + # TODO: Make this field a structured dataclass. + metadata: Optional[Any] = None + + +@dataclass +class GymConfig(HabitatBaseConfig): + obs_keys: Optional[List[str]] = None + action_keys: Optional[List[str]] = None + achieved_goal_keys: List = field(default_factory=list) + desired_goal_keys: List[str] = field(default_factory=list) + + +@dataclass +class HabitatConfig(HabitatBaseConfig): + r""" + The entry point for the configuration of Habitat. It holds the environment, simulator, task and dataset configurations. + + :property seed: The seed the environment will be initialized with. + :property env_task: Indicates wether the environment is a Habitat gym environment (`GymHabitatEnv`) or a generic gym environment (`GymRegistryEnv`). + :property env_task_gym_id: if `env_task` is `GymRegistryEnv`, env_task_gym_id is the identifier of the generic gym environment + """ + seed: int = 100 + # GymHabitatEnv works for all Habitat tasks, including Navigation and + # Rearrange. To use a gym environment from the registry, use the + # GymRegistryEnv. Any other environment needs to be created and registered. + env_task: str = "GymHabitatEnv" + # The dependencies for launching the GymRegistryEnv environments. + # Modules listed here will be imported prior to making the environment with + # gym.make() + env_task_gym_dependencies: List = field(default_factory=list) + # The key of the gym environment in the registry to use in GymRegistryEnv + # for example: `Cartpole-v0` + env_task_gym_id: str = "" + environment: EnvironmentConfig = EnvironmentConfig() + simulator: SimulatorConfig = SimulatorConfig() + task: TaskConfig = MISSING + dataset: DatasetConfig = MISSING + gym: GymConfig = GymConfig() + + +# ----------------------------------------------------------------------------- +# Register configs in the Hydra ConfigStore +# ----------------------------------------------------------------------------- +cs = ConfigStore.instance() + +cs.store(group="habitat", name="habitat_config_base", node=HabitatConfig) +cs.store( + group="habitat.environment", + name="environment_config_schema", + node=EnvironmentConfig, +) +cs.store( + package="habitat.task", + group="habitat/task", + name="task_config_base", + node=TaskConfig, +) + +# Agent Config +cs.store( + group="habitat/simulator/agents", + name="agent_base", + node=AgentConfig, +) + +cs.store( + package="habitat.task.actions.stop", + group="habitat/task/actions", + name="stop", + node=StopActionConfig, +) +cs.store( + package="habitat.task.actions.move_forward", + group="habitat/task/actions", + name="move_forward", + node=MoveForwardActionConfig, +) +cs.store( + package="habitat.task.actions.turn_left", + group="habitat/task/actions", + name="turn_left", + node=TurnLeftActionConfig, +) +cs.store( + package="habitat.task.actions.turn_right", + group="habitat/task/actions", + name="turn_right", + node=TurnRightActionConfig, +) +cs.store( + package="habitat.task.actions.look_up", + group="habitat/task/actions", + name="look_up", + node=LookUpActionConfig, +) +cs.store( + package="habitat.task.actions.look_down", + group="habitat/task/actions", + name="look_down", + node=LookDownActionConfig, +) +cs.store( + package="habitat.task.actions.arm_action", + group="habitat/task/actions", + name="arm_action", + node=ArmActionConfig, +) +cs.store( + package="habitat.task.actions.base_velocity", + group="habitat/task/actions", + name="base_velocity", + node=BaseVelocityActionConfig, +) +cs.store( + package="habitat.task.actions.base_velocity_non_cylinder", + group="habitat/task/actions", + name="base_velocity_non_cylinder", + node=BaseVelocityNonCylinderActionConfig, +) +cs.store( + package="habitat.task.actions.humanoidjoint_action", + group="habitat/task/actions", + name="humanoidjoint_action", + node=HumanoidJointActionConfig, +) +cs.store( + package="habitat.task.actions.humanoid_pick_action", + group="habitat/task/actions", + name="humanoid_pick_action", + node=HumanoidPickActionConfig, +) +cs.store( + package="habitat.task.actions.velocity_control", + group="habitat/task/actions", + name="velocity_control", + node=VelocityControlActionConfig, +) +cs.store( + package="habitat.task.actions.empty", + group="habitat/task/actions", + name="empty", + node=EmptyActionConfig, +) +cs.store( + package="habitat.task.actions.rearrange_stop", + group="habitat/task/actions", + name="rearrange_stop", + node=RearrangeStopActionConfig, +) +cs.store( + package="habitat.task.actions.a_selection_of_base_or_arm", + group="habitat/task/actions", + name="a_selection_of_base_or_arm", + node=SelectBaseOrArmActionConfig, +) +cs.store( + package="habitat.task.actions.answer", + group="habitat/task/actions", + name="answer", + node=AnswerActionConfig, +) +cs.store( + package="habitat.task.actions.oracle_nav_action", + group="habitat/task/actions", + name="oracle_nav_action", + node=OracleNavActionConfig, +) +cs.store( + package="habitat.task.actions.pddl_apply_action", + group="habitat/task/actions", + name="pddl_apply_action", + node=PddlApplyActionConfig, +) + +# Dataset Config Schema +cs.store( + package="habitat.dataset", + group="habitat/dataset", + name="dataset_config_schema", + node=DatasetConfig, +) + +# Simulator Sensors +cs.store( + group="habitat/simulator/sim_sensors", + name="rgb_sensor", + node=HabitatSimRGBSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="depth_sensor", + node=HabitatSimDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="semantic_sensor", + node=HabitatSimSemanticSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="equirect_rgb_sensor", + node=HabitatSimEquirectangularRGBSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="equirect_depth_sensor", + node=HabitatSimEquirectangularDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="equirect_semantic_sensor", + node=HabitatSimEquirectangularSemanticSensorConfig, +) + + +cs.store( + group="habitat/simulator/sim_sensors", + name="arm_depth_sensor", + node=ArmDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="arm_rgb_sensor", + node=ArmRGBSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="jaw_depth_sensor", + node=JawDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="jaw_rgb_sensor", + node=JawRGBSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="head_depth_sensor", + node=HeadDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="head_stereo_right_depth_sensor", + node=HeadStereoRightDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="head_stereo_left_depth_sensor", + node=HeadStereoLeftDepthSensorConfig, +) + + +cs.store( + group="habitat/simulator/sim_sensors", + name="head_rgb_sensor", + node=HeadRGBSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="head_panoptic_sensor", + node=HeadPanopticSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="arm_panoptic_sensor", + node=ArmPanopticSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="jaw_panoptic_sensor", + node=JawPanopticSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="third_depth_sensor", + node=ThirdDepthSensorConfig, +) + +cs.store( + group="habitat/simulator/sim_sensors", + name="third_rgb_sensor", + node=ThirdRGBSensorConfig, +) + + +# Task Sensors +cs.store( + package="habitat.task.lab_sensors.gps_sensor", + group="habitat/task/lab_sensors", + name="gps_sensor", + node=GPSSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.compass_sensor", + group="habitat/task/lab_sensors", + name="compass_sensor", + node=CompassSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.pointgoal_with_gps_compass_sensor", + group="habitat/task/lab_sensors", + name="pointgoal_with_gps_compass_sensor", + node=PointGoalWithGPSCompassSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.humanoid_detector_sensor", + group="habitat/task/lab_sensors", + name="humanoid_detector_sensor", + node=HumanoidDetectorSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.arm_depth_bbox_sensor", + group="habitat/task/lab_sensors", + name="arm_depth_bbox_sensor", + node=ArmDepthBBoxSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.spot_head_stereo_depth_sensor", + group="habitat/task/lab_sensors", + name="spot_head_stereo_depth_sensor", + node=SpotHeadStereoDepthSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.objectgoal_sensor", + group="habitat/task/lab_sensors", + name="objectgoal_sensor", + node=ObjectGoalSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.imagegoal_sensor", + group="habitat/task/lab_sensors", + name="imagegoal_sensor", + node=ImageGoalSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.instance_imagegoal_sensor", + group="habitat/task/lab_sensors", + name="instance_imagegoal_sensor", + node=InstanceImageGoalSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.instance_imagegoal_hfov_sensor", + group="habitat/task/lab_sensors", + name="instance_imagegoal_hfov_sensor", + node=InstanceImageGoalHFOVSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.localization_sensor", + group="habitat/task/lab_sensors", + name="localization_sensor", + node=LocalizationSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.target_start_sensor", + group="habitat/task/lab_sensors", + name="target_start_sensor", + node=TargetStartSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.goal_sensor", + group="habitat/task/lab_sensors", + name="goal_sensor", + node=GoalSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.abs_target_start_sensor", + group="habitat/task/lab_sensors", + name="abs_target_start_sensor", + node=AbsTargetStartSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.abs_goal_sensor", + group="habitat/task/lab_sensors", + name="abs_goal_sensor", + node=AbsGoalSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.joint_sensor", + group="habitat/task/lab_sensors", + name="joint_sensor", + node=JointSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.humanoid_joint_sensor", + group="habitat/task/lab_sensors", + name="humanoid_joint_sensor", + node=HumanoidJointSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.end_effector_sensor", + group="habitat/task/lab_sensors", + name="end_effector_sensor", + node=EEPositionSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.is_holding_sensor", + group="habitat/task/lab_sensors", + name="is_holding_sensor", + node=IsHoldingSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.relative_resting_pos_sensor", + group="habitat/task/lab_sensors", + name="relative_resting_pos_sensor", + node=RelativeRestingPositionSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.instruction_sensor", + group="habitat/task/lab_sensors", + name="instruction_sensor", + node=InstructionSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.question_sensor", + group="habitat/task/lab_sensors", + name="question_sensor", + node=QuestionSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.object_sensor", + group="habitat/task/lab_sensors", + name="object_sensor", + node=TargetCurrentSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.joint_velocity_sensor", + group="habitat/task/lab_sensors", + name="joint_velocity_sensor", + node=JointVelocitySensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.target_start_gps_compass_sensor", + group="habitat/task/lab_sensors", + name="target_start_gps_compass_sensor", + node=TargetStartGpsCompassSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.initial_gps_compass_sensor", + group="habitat/task/lab_sensors", + name="initial_gps_compass_sensor", + node=InitialGpsCompassSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.multi_agent_all_predicates", + group="habitat/task/lab_sensors", + name="multi_agent_all_predicates", + node=MultiAgentGlobalPredicatesSensorConfig, +) + +cs.store( + package="habitat.task.lab_sensors.agents_within_threshold", + group="habitat/task/lab_sensors", + name="agents_within_threshold", + node=AreAgentsWithinThresholdConfig, +) +cs.store( + package="habitat.task.lab_sensors.has_finished_oracle_nav", + group="habitat/task/lab_sensors", + name="has_finished_oracle_nav", + node=HasFinishedOracleNavSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.has_finished_humanoid_pick", + group="habitat/task/lab_sensors", + name="has_finished_humanoid_pick", + node=HasFinishedHumanoidPickSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.other_agent_gps", + group="habitat/task/lab_sensors", + name="other_agent_gps", + node=OtherAgentGpsConfig, +) +cs.store( + package="habitat.task.lab_sensors.target_goal_gps_compass_sensor", + group="habitat/task/lab_sensors", + name="target_goal_gps_compass_sensor", + node=TargetGoalGpsCompassSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.nav_to_skill_sensor", + group="habitat/task/lab_sensors", + name="nav_to_skill_sensor", + node=NavToSkillSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.nav_goal_sensor", + group="habitat/task/lab_sensors", + name="nav_goal_sensor", + node=NavGoalPointGoalSensorConfig, +) +cs.store( + package="habitat.task.lab_sensors.all_predicates", + group="habitat/task/lab_sensors", + name="all_predicates", + node=GlobalPredicatesSensorConfig, +) + + +# Task Measurements +cs.store( + package="habitat.task.measurements.top_down_map", + group="habitat/task/measurements", + name="top_down_map", + node=TopDownMapMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.distance_to_goal", + group="habitat/task/measurements", + name="distance_to_goal", + node=DistanceToGoalMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.distance_to_goal_reward", + group="habitat/task/measurements", + name="distance_to_goal_reward", + node=DistanceToGoalRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.success", + group="habitat/task/measurements", + name="success", + node=SuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.spl", + group="habitat/task/measurements", + name="spl", + node=SPLMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.soft_spl", + group="habitat/task/measurements", + name="soft_spl", + node=SoftSPLMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.num_steps", + group="habitat/task/measurements", + name="num_steps", + node=NumStepsMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.zero", + group="habitat/task/measurements", + name="zero", + node=ZeroMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.articulated_agent_force", + group="habitat/task/measurements", + name="articulated_agent_force", + node=RobotForceMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.force_terminate", + group="habitat/task/measurements", + name="force_terminate", + node=ForceTerminateMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.end_effector_to_object_distance", + group="habitat/task/measurements", + name="end_effector_to_object_distance", + node=EndEffectorToObjectDistanceMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.base_to_object_distance", + group="habitat/task/measurements", + name="base_to_object_distance", + node=BaseToObjectDistanceMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.end_effector_to_rest_distance", + group="habitat/task/measurements", + name="end_effector_to_rest_distance", + node=EndEffectorToRestDistanceMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.end_effector_to_goal_distance", + group="habitat/task/measurements", + name="end_effector_to_goal_distance", + node=EndEffectorToGoalDistanceMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.did_pick_object", + group="habitat/task/measurements", + name="did_pick_object", + node=DidPickObjectMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.did_violate_hold_constraint", + group="habitat/task/measurements", + name="did_violate_hold_constraint", + node=DidViolateHoldConstraintMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.pick_reward", + group="habitat/task/measurements", + name="pick_reward", + node=RearrangePickRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.pick_success", + group="habitat/task/measurements", + name="pick_success", + node=RearrangePickSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.answer_accuracy", + group="habitat/task/measurements", + name="answer_accuracy", + node=AnswerAccuracyMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.episode_info", + group="habitat/task/measurements", + name="episode_info", + node=EpisodeInfoMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.collisions", + group="habitat/task/measurements", + name="collisions", + node=CollisionsMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.articulated_agent_colls", + group="habitat/task/measurements", + name="articulated_agent_colls", + node=RobotCollisionsMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.object_to_goal_distance", + group="habitat/task/measurements", + name="object_to_goal_distance", + node=ObjectToGoalDistanceMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.obj_at_goal", + group="habitat/task/measurements", + name="obj_at_goal", + node=ObjAtGoalMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.place_success", + group="habitat/task/measurements", + name="place_success", + node=PlaceSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.place_reward", + group="habitat/task/measurements", + name="place_reward", + node=PlaceRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.move_objects_reward", + group="habitat/task/measurements", + name="move_objects_reward", + node=MoveObjectsRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.does_want_terminate", + group="habitat/task/measurements", + name="does_want_terminate", + node=DoesWantTerminateMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.pddl_subgoal_reward", + group="habitat/task/measurements", + name="pddl_subgoal_reward", + node=PddlSubgoalReward, +) +cs.store( + package="habitat.task.measurements.rearrange_cooperate_reward", + group="habitat/task/measurements", + name="rearrange_cooperate_reward", + node=RearrangeCooperateRewardConfig, +) +cs.store( + package="habitat.task.measurements.social_nav_reward", + group="habitat/task/measurements", + name="social_nav_reward", + node=SocialNavReward, +) +cs.store( + package="habitat.task.measurements.did_agents_collide", + group="habitat/task/measurements", + name="did_agents_collide", + node=DidAgentsCollideConfig, +) +cs.store( + package="habitat.task.measurements.num_agents_collide", + group="habitat/task/measurements", + name="num_agents_collide", + node=NumAgentsCollideConfig, +) +cs.store( + package="habitat.task.measurements.pddl_success", + group="habitat/task/measurements", + name="pddl_success", + node=PddlSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.gfx_replay_measure", + group="habitat/task/measurements", + name="gfx_replay_measure", + node=GfxReplayMeasureMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.pddl_stage_goals", + group="habitat/task/measurements", + name="composite_stage_goals", + node=PddlStageGoalsMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.ee_dist_to_marker", + group="habitat/task/measurements", + name="ee_dist_to_marker", + node=EndEffectorDistToMarkerMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.art_obj_at_desired_state", + group="habitat/task/measurements", + name="art_obj_at_desired_state", + node=ArtObjAtDesiredStateMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.art_obj_state", + group="habitat/task/measurements", + name="art_obj_state", + node=ArtObjStateMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.art_obj_success", + group="habitat/task/measurements", + name="art_obj_success", + node=ArtObjSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.art_obj_reward", + group="habitat/task/measurements", + name="art_obj_reward", + node=ArtObjRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.nav_to_pos_succ", + group="habitat/task/measurements", + name="nav_to_pos_succ", + node=NavToPosSuccMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.social_nav_stats", + group="habitat/task/measurements", + name="social_nav_stats", + node=SocialNavStatsMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.social_nav_seek_success", + group="habitat/task/measurements", + name="social_nav_seek_success", + node=NavSeekSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.rot_dist_to_goal", + group="habitat/task/measurements", + name="rot_dist_to_goal", + node=RotDistToGoalMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.rearrange_nav_to_obj_success", + group="habitat/task/measurements", + name="rearrange_nav_to_obj_success", + node=NavToObjSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.rearrange_nav_to_obj_reward", + group="habitat/task/measurements", + name="rearrange_nav_to_obj_reward", + node=NavToObjRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.bad_called_terminate", + group="habitat/task/measurements", + name="bad_called_terminate", + node=BadCalledTerminateMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.dist_to_goal", + group="habitat/task/measurements", + name="dist_to_goal", + node=DistToGoalMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.rearrange_reach_reward", + group="habitat/task/measurements", + name="rearrange_reach_reward", + node=RearrangeReachRewardMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.rearrange_reach_success", + group="habitat/task/measurements", + name="rearrange_reach_success", + node=RearrangeReachSuccessMeasurementConfig, +) +cs.store( + package="habitat.task.measurements.habitat_perf", + group="habitat/task/measurements", + name="habitat_perf", + node=RuntimePerfStatsMeasurementConfig, +) + + +from hydra.core.config_search_path import ConfigSearchPath +from hydra.core.plugins import Plugins +from hydra.plugins.search_path_plugin import SearchPathPlugin + + +class HabitatConfigPlugin(SearchPathPlugin): + def manipulate_search_path(self, search_path: ConfigSearchPath) -> None: + search_path.append( + provider="habitat", + path="pkg://habitat/config/", + ) + + +def register_hydra_plugin(plugin) -> None: + """Hydra users should call this function before invoking @hydra.main""" + Plugins.instance().register(plugin) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/eqa/mp3d.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/eqa/mp3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..284ebb9c7719fc393a17bc6a4f5d79650062a8da --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/eqa/mp3d.yaml @@ -0,0 +1,11 @@ +# @package habitat.dataset + + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: MP3DEQA-v1 +split: train +data_path: "data/datasets/eqa/mp3d/v1/{split}/{split}.json.gz" +scenes_dir: "data/scene_datasets/" diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/imagenav/gibson.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/imagenav/gibson.yaml new file mode 100644 index 0000000000000000000000000000000000000000..22de63be53ab5bd0bd8186f8f263ea8206ff8934 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/imagenav/gibson.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/gibson/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/imagenav/mp3d.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/imagenav/mp3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79e413ce94cdd3d6b03a3ce541e88ded5905ebbb --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/imagenav/mp3d.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/mp3d/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/instance_imagenav/hm3d_v1.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/instance_imagenav/hm3d_v1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..93430ff127bd40ebc5231a890b868f0298e6b372 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/instance_imagenav/hm3d_v1.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: InstanceImageNav-v1 +split: train +data_path: data/datasets/instance_imagenav/hm3d/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/instance_imagenav/hm3d_v2.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/instance_imagenav/hm3d_v2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f12c8a1cfcba1529eda38f0f6e519eac81dcb44 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/instance_imagenav/hm3d_v2.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: InstanceImageNav-v1 +split: train +data_path: data/datasets/instance_imagenav/hm3d/v2/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/hm3d.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/hm3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fa710509f47305904ba3b5601581f5eb6b46289 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/hm3d.yaml @@ -0,0 +1,8 @@ +# @package habitat.dataset +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: ObjectNav-v1 +split: train +data_path: data/datasets/objectnav/hm3d/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/hssd-hab.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/hssd-hab.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5f4ec1d9517030bf72363a654dea7886c93cbfd --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/hssd-hab.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: ObjectNav-v1 +split: train +data_path: data/datasets/objectnav/hssd-hab/{split}/{split}.json.gz +scenes_dir: data/scene_datasets/hssd-hab/scenes diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/mp3d.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/mp3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..df33102601d3889e0eb99b6ddc00e7bb047b3c94 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/mp3d.yaml @@ -0,0 +1,8 @@ +# @package habitat.dataset +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: ObjectNav-v1 +split: train +data_path: data/datasets/objectnav/mp3d/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/procthor-hab.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/procthor-hab.yaml new file mode 100644 index 0000000000000000000000000000000000000000..22e51a8709eefec10b423141a0e3f8d45daab8de --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/objectnav/procthor-hab.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: ObjectNav-v1 +split: train +data_path: data/datasets/objectnav/procthor-hab/{split}/{split}.json.gz +scenes_dir: data/scene_datasets/ai2thor-hab/ai2thor-hab/configs/scenes/ProcTHOR/ diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson.yaml new file mode 100644 index 0000000000000000000000000000000000000000..22de63be53ab5bd0bd8186f8f263ea8206ff8934 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/gibson/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson_0_plus.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson_0_plus.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ec8a62c3633ec551abcb2dbf51ed1a4028ce45d --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson_0_plus.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train_extra_large +data_path: data/datasets/pointnav/gibson/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson_v2.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson_v2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d77fb2c719ab03962a12c04cc832383cc736fb9 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/gibson_v2.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/gibson/v2/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/habitat_test.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/habitat_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b905b290de0c418cbe4309ad4db38bab4186f219 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/habitat_test.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/habitat-test-scenes/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/hm3d.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/hm3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60fe2e1485f708b29fa04871283406d10d4af178 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/hm3d.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/hm3d/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/mp3d.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/mp3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79e413ce94cdd3d6b03a3ce541e88ded5905ebbb --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/pointnav/mp3d.yaml @@ -0,0 +1,9 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: PointNav-v1 +split: train +data_path: data/datasets/pointnav/mp3d/v1/{split}/{split}.json.gz diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/rearrangement/hssd.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/rearrangement/hssd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b66820fe14b78e63f93237cfd2673b745e07661 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/rearrangement/hssd.yaml @@ -0,0 +1,10 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: RearrangeDataset-v0 +split: train +data_path: data/datasets/rearrange_pick/replica_cad/v0/{split}/{split}_counter_L_analysis_5000_500.json.gz +scenes_dir: "data/scene_datasets/hssd-hab" diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/rearrangement/replica_cad.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/rearrangement/replica_cad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d058589701168cde791886a1a073d4b619c9c2f --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/rearrangement/replica_cad.yaml @@ -0,0 +1,10 @@ +# @package habitat.dataset + +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + +type: RearrangeDataset-v0 +split: train +data_path: data/datasets/rearrange_pick/replica_cad/v0/{split}/{split}_counter_L_analysis_5000_500.json.gz +scenes_dir: "data/replica_cad/" diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/vln/mp3d_r2r.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/vln/mp3d_r2r.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8805d3e9e2d5e611f06ba99bb14a593dfa9be1f7 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/dataset/vln/mp3d_r2r.yaml @@ -0,0 +1,10 @@ +# @package habitat.dataset +defaults: + - /habitat/dataset: dataset_config_schema + - _self_ + + +type: R2RVLN-v1 +split: train +data_path: "data/datasets/vln/mp3d/r2r/v1/{split}/{split}.json.gz" +scenes_dir: "data/scene_datasets/" diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/simulator/rearrange_sim.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/simulator/rearrange_sim.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95f7ad58ff12af8b25bebcad397854f06d9a2447 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/simulator/rearrange_sim.yaml @@ -0,0 +1,10 @@ +# @package habitat.simulator +type: RearrangeSim-v0 +additional_object_paths: +- data/objects/ycb/configs/ +debug_render_goal: False +concur_render: True +auto_sleep: True +habitat_sim_v0: + allow_sliding: False + enable_physics: True diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/simulator/sensor_setups/rgbd_head_agent.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/simulator/sensor_setups/rgbd_head_agent.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dff62423b2324a3ce400351c1fa6126ab40884b0 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/simulator/sensor_setups/rgbd_head_agent.yaml @@ -0,0 +1,5 @@ +# @package habitat.simulator.agents.rgb_head_agent + +defaults: + - /habitat/simulator/sim_sensors@sim_sensors.head_rgb_sensor: head_rgb_sensor + - /habitat/simulator/sim_sensors@sim_sensors.head_depth_sensor: head_depth_sensor diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/eqa.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/eqa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..23cdbf9a20d3b7d5dd3604d71fa9062e0c91c641 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/eqa.yaml @@ -0,0 +1,16 @@ +defaults: + - task_config_base + - actions: + - move_forward + - turn_left + - turn_right + - answer + - measurements: + - distance_to_goal + - episode_info + - answer_accuracy + - lab_sensors: + - question_sensor + - _self_ + +type: EQA-v0 diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/imagenav.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/imagenav.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cf1fae0c126306de8950f5d5736f098c242cb50 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/imagenav.yaml @@ -0,0 +1,21 @@ +defaults: + - task_config_base + - actions: + - stop + - move_forward + - turn_left + - turn_right + - measurements: + - distance_to_goal + - success + - spl + - distance_to_goal_reward + - top_down_map + - lab_sensors: + - imagegoal_sensor + - _self_ + +type: Nav-v0 +end_on_success: True +reward_measure: "distance_to_goal_reward" +success_measure: "spl" diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/instance_imagenav.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/instance_imagenav.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e1da59a275dc3639501e518e38984c664e607a5 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/instance_imagenav.yaml @@ -0,0 +1,39 @@ +defaults: + - task_config_base + - actions: + - stop + - move_forward + - turn_left + - turn_right + - look_up + - look_down + - measurements: + - num_steps + - distance_to_goal + - success + - spl + - soft_spl + - distance_to_goal_reward + - lab_sensors: + - instance_imagegoal_sensor + - instance_imagegoal_hfov_sensor + - compass_sensor + - gps_sensor + - _self_ + + +actions: + look_up: + tilt_angle: 30 + look_down: + tilt_angle: 30 +type: InstanceImageNav-v1 +end_on_success: True +reward_measure: distance_to_goal_reward +success_measure: spl +goal_sensor_uuid: instance_imagegoal +measurements: + distance_to_goal: + distance_to: VIEW_POINTS + success: + success_distance: 0.1 diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/objectnav.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/objectnav.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f44033ed3de12f986f2be0a4dd68226412e4648a --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/objectnav.yaml @@ -0,0 +1,41 @@ + +defaults: + - task_config_base + - actions: + - stop + - move_forward + - turn_left + - turn_right + - look_up + - look_down + - measurements: + - distance_to_goal + - success + - spl + - soft_spl + - distance_to_goal_reward + - lab_sensors: + - objectgoal_sensor + - compass_sensor + - gps_sensor + - _self_ + +actions: + look_up: + tilt_angle: 30 + look_down: + tilt_angle: 30 + +type: ObjectNav-v1 +end_on_success: True +reward_measure: "distance_to_goal_reward" +success_measure: "spl" + + +goal_sensor_uuid: objectgoal + +measurements: + distance_to_goal: + distance_to: VIEW_POINTS + success: + success_distance: 0.1 diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/pointnav.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/pointnav.yaml new file mode 100644 index 0000000000000000000000000000000000000000..320a636df1d6003f81afee0e50b9d18eb62defe5 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/pointnav.yaml @@ -0,0 +1,21 @@ +defaults: + - task_config_base + - actions: + - stop + - move_forward + - turn_left + - turn_right + - measurements: + - distance_to_goal + - success + - spl + - distance_to_goal_reward + - lab_sensors: + - pointgoal_with_gps_compass_sensor + - _self_ + +type: Nav-v0 +end_on_success: True +reward_measure: "distance_to_goal_reward" +success_measure: "spl" +goal_sensor_uuid: pointgoal_with_gps_compass diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/pointnav_franka.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/pointnav_franka.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9da1a70e96cc9dc357250d9521aae106ae6e3012 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/pointnav_franka.yaml @@ -0,0 +1,17 @@ +defaults: + - task_config_base + - actions: + - stop + - move_forward + - turn_left + - turn_right + - measurements: + - distance_to_goal + - success + - spl + - lab_sensors: + - pointgoal_with_gps_compass_sensor + - _self_ + +type: Nav-v0 +goal_sensor_uuid: pointgoal_with_gps_compass diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm.yaml new file mode 100644 index 0000000000000000000000000000000000000000..faf644ab274a1173e7000a1e928cd16019ad4563 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm.yaml @@ -0,0 +1,7 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - arm_action + - _self_ +arm_action: + grip_controller: SuctionGraspAction diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2ce4c42a951d83a42588a4e50687e00a24d3e32 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base.yaml @@ -0,0 +1,8 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - arm_action + - base_velocity + - _self_ +arm_action: + grip_controller: SuctionGraspAction diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base_empty.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base_empty.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8494591721eb7f9e5254a0a0c266535e3c3d0791 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base_empty.yaml @@ -0,0 +1,10 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - arm_action + - base_velocity + - rearrange_stop + - empty + - _self_ +arm_action: + grip_controller: SuctionGraspAction diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base_stop.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base_stop.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9cd384cc5eb525fc616a12dd0d509594a7b8148 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_arm_base_stop.yaml @@ -0,0 +1,9 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - arm_action + - base_velocity + - rearrange_stop + - _self_ +arm_action: + grip_controller: SuctionGraspAction diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_base_stop.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_base_stop.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c5469c209613d1fbba6998c6b6ff302e4056157 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/fetch_suction_base_stop.yaml @@ -0,0 +1,6 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - base_velocity + - rearrange_stop + - _self_ diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/spot_base_arm_empty.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/spot_base_arm_empty.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9f378155d3c502acb3b3169d819e5b0c16528e2 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/spot_base_arm_empty.yaml @@ -0,0 +1,26 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - base_velocity_non_cylinder + - arm_action + - empty + - _self_ +arm_action: + type: "ArmAction" + arm_controller: "ArmRelPosMaskAction" + grip_controller: "GazeGraspAction" + arm_joint_mask: [1,1,0,1,0,1,0] + arm_joint_dimensionality: 4 + grasp_thresh_dist: 0.15 + disable_grip: False + delta_pos_limit: 0.0872665 + ee_ctrl_lim: 0.015 + gaze_distance_range: [0.3, 0.75] + center_cone_angle_threshold: 20.0 +base_velocity_non_cylinder: + allow_dyn_slide: False + # There is a collision if the difference between the clamped NavMesh position and target position + # is more than than collision_threshold for any point + collision_threshold: 1e-5 + # If we allow the robot to move laterally + enable_lateral_move: False diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/stretch_base_arm_empty.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/stretch_base_arm_empty.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd54cead6f93037b80a5ca9c9d1b8f546a909645 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/actions/stretch_base_arm_empty.yaml @@ -0,0 +1,18 @@ +# @package habitat.task.actions +defaults: + - /habitat/task/actions: + - arm_action + - _self_ +arm_action: + type: "ArmAction" + arm_controller: "ArmRelPosKinematicReducedActionStretch" + grip_controller: "GazeGraspAction" + arm_joint_mask: [1,0,0,0,1,1,1,1,1,1] + arm_joint_dimensionality: 10 + grasp_thresh_dist: 0.15 + disable_grip: False + delta_pos_limit: 0.0125 + ee_ctrl_lim: 0.015 + gaze_distance_range: [0.1, 3.0] + center_cone_angle_threshold: 20.0 + center_cone_vector: [0.0, 1.0, 0.0] diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/prepare_groceries.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/prepare_groceries.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fd9f011cbbc5db65b8220b5d58b84cece02e1b9c --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/prepare_groceries.yaml @@ -0,0 +1,83 @@ +init: + - closed_cab(cab_push_point_4) + - closed_cab(cab_push_point_5) + - closed_cab(cab_push_point_6) + - closed_cab(cab_push_point_7) + - opened_fridge(fridge_push_point) + +goal: + expr_type: AND + sub_exprs: + - object_at(obj0_target|0,TARGET_obj0_target|0) + - object_at(obj1_target|1,TARGET_obj1_target|1) + - object_at(obj2_target|2,TARGET_obj2_target|2) + - not_holding(robot_0) + +objects: + - name: obj0_target|0 + expr_type: movable_entity_type + - name: TARGET_obj0_target|0 + expr_type: goal_entity_type + + - name: obj1_target|1 + expr_type: movable_entity_type + - name: TARGET_obj1_target|1 + expr_type: goal_entity_type + + - name: obj2_target|2 + expr_type: movable_entity_type + - name: TARGET_obj2_target|2 + expr_type: goal_entity_type + + - name: robot_0 + expr_type: robot_entity_type + +stage_goals: + stage_0_5: + expr_type: AND + sub_exprs: + - holding(obj0_target|0, robot_0) + stage_1: + expr_type: AND + sub_exprs: + - object_at(obj0_target|0,TARGET_obj0_target|0) + - not_holding(robot_0) + stage_1_5: + expr_type: AND + sub_exprs: + - object_at(obj0_target|0,TARGET_obj0_target|0) + - holding(obj1_target|1, robot_0) + stage_2: + expr_type: AND + sub_exprs: + - object_at(obj0_target|0,TARGET_obj0_target|0) + - object_at(obj1_target|1,TARGET_obj1_target|1) + - not_holding(robot_0) + stage_2_5: + expr_type: AND + sub_exprs: + - object_at(obj0_target|0,TARGET_obj0_target|0) + - object_at(obj1_target|1,TARGET_obj1_target|1) + - holding(obj2_target|2, robot_0) + stage_3: + expr_type: AND + sub_exprs: + - object_at(obj0_target|0,TARGET_obj0_target|0) + - object_at(obj1_target|1,TARGET_obj1_target|1) + - object_at(obj2_target|2,TARGET_obj2_target|2) + +solution: + - nav(obj0_target|0, robot_0) + - pick(obj0_target|0, robot_0) + - nav(TARGET_obj0_target|0, robot_0) + - place(obj0_target|0,TARGET_obj0_target|0, robot_0) + + - nav(obj1_target|1, robot_0) + - pick(obj1_target|1, robot_0) + - nav(TARGET_obj1_target|1, robot_0) + - place(obj1_target|1,TARGET_obj1_target|1, robot_0) + + - nav(obj2_target|2, robot_0) + - pick(obj2_target|2, robot_0) + - nav(TARGET_obj2_target|2, robot_0) + - place(obj2_target|2,TARGET_obj2_target|2, robot_0) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/rearrange.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/rearrange.yaml new file mode 100644 index 0000000000000000000000000000000000000000..473930a03a4429323c8a4e9a7d6bc0d6bf8adc0a --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/rearrange.yaml @@ -0,0 +1,23 @@ +objects: + - name: goal0|0 + expr_type: movable_entity_type + - name: TARGET_goal0|0 + expr_type: goal_entity_type + - name: robot_0 + expr_type: robot_entity_type + +goal: + expr_type: AND + sub_exprs: + - object_at(goal0|0,TARGET_goal0|0) + - not_holding(robot_0) + +stage_goals: + stage_0_5: + expr_type: AND + sub_exprs: + - holding(goal0|0, robot_0) + stage_1: + expr_type: AND + sub_exprs: + - object_at(goal0|0,TARGET_goal0|0) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/rearrange_easy.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/rearrange_easy.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da78ce73b0aa7d0f599cf6818560163fff9003d4 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/rearrange_easy.yaml @@ -0,0 +1,29 @@ +objects: + - name: goal0|0 + expr_type: movable_entity_type + - name: TARGET_goal0|0 + expr_type: goal_entity_type + - name: robot_0 + expr_type: robot_entity_type + +goal: + expr_type: AND + sub_exprs: + - object_at(goal0|0,TARGET_goal0|0) + - not_holding(robot_0) + +stage_goals: + stage_0_5: + expr_type: AND + sub_exprs: + - holding(goal0|0, robot_0) + stage_1: + expr_type: AND + sub_exprs: + - object_at(goal0|0,TARGET_goal0|0) + +solution: + - nav(goal0|0, robot_0) + - pick(goal0|0, robot_0) + - nav(TARGET_goal0|0, robot_0) + - place(goal0|0, TARGET_goal0|0, robot_0) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/set_table.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/set_table.yaml new file mode 100644 index 0000000000000000000000000000000000000000..651c75f6723a089075e672c8cba9c41c857b63a5 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/set_table.yaml @@ -0,0 +1,59 @@ +objects: + - name: bowl_target|0 + expr_type: movable_entity_type + - name: TARGET_bowl_target|0 + expr_type: goal_entity_type + - name: fruit_target|1 + expr_type: movable_entity_type + - name: TARGET_fruit_target|1 + expr_type: goal_entity_type + - name: robot_0 + expr_type: robot_entity_type + +init: + - closed_fridge(fridge_push_point) + - closed_cab(cab_push_point_4) + - closed_cab(cab_push_point_5) + - closed_cab(cab_push_point_6) + - closed_cab(cab_push_point_7) + +goal: + expr_type: AND + sub_exprs: + - object_at(bowl_target|0,TARGET_bowl_target|0) + - object_at(fruit_target|1,TARGET_fruit_target|1) + - not_holding(robot_0) +stage_goals: + stage_0_5: + expr_type: AND + sub_exprs: + - holding(bowl_target|0, robot_0) + stage_1: + expr_type: AND + sub_exprs: + - object_at(bowl_target|0,TARGET_bowl_target|0) + - not_holding(robot_0) + stage_1_5: + expr_type: AND + sub_exprs: + - object_at(bowl_target|0,TARGET_bowl_target|0) + - holding(fruit_target|1, robot_0) + stage_2: + expr_type: AND + sub_exprs: + - object_at(bowl_target|0,TARGET_bowl_target|0) + - object_at(fruit_target|1,TARGET_fruit_target|1) + +solution: + - nav_to_receptacle(cab_push_point_5,bowl_target|0, robot_0) + - open_cab(cab_push_point_5,bowl_target|0, robot_0) + - pick(bowl_target|0, robot_0) + - nav(TARGET_bowl_target|0, robot_0) + - place(bowl_target|0,TARGET_bowl_target|0, robot_0) + + - nav_to_receptacle(fridge_push_point,fruit_target|1, robot_0) + - open_fridge(fridge_push_point, fruit_target|1, robot_0) + - nav(fruit_target|1, robot_0) + - pick(fruit_target|1, robot_0) + - nav(TARGET_fruit_target|1, robot_0) + - place(fruit_target|1,TARGET_fruit_target|1, robot_0) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/tidy_house.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/tidy_house.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c8a788f2ae1fe913f96e89bf3e50f25fb114715 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/tidy_house.yaml @@ -0,0 +1,118 @@ +objects: + - name: any_targets|0 + expr_type: movable_entity_type + - name: TARGET_any_targets|0 + expr_type: goal_entity_type + - name: any_targets|1 + expr_type: movable_entity_type + - name: TARGET_any_targets|1 + expr_type: goal_entity_type + - name: any_targets|2 + expr_type: movable_entity_type + - name: TARGET_any_targets|2 + expr_type: goal_entity_type + - name: any_targets|3 + expr_type: movable_entity_type + - name: TARGET_any_targets|3 + expr_type: goal_entity_type + - name: any_targets|4 + expr_type: movable_entity_type + - name: TARGET_any_targets|4 + expr_type: goal_entity_type + - name: robot_0 + expr_type: robot_entity_type + + +init: + - closed_fridge(fridge_push_point) + + +goal: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - object_at(any_targets|2,TARGET_any_targets|2) + - object_at(any_targets|3,TARGET_any_targets|3) + - object_at(any_targets|4,TARGET_any_targets|4) + - not_holding(robot_0) + +stage_goals: + stage_0_5: + expr_type: AND + sub_exprs: + - holding(any_targets|0, robot_0) + stage_1: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - not_holding(robot_0) + stage_1_5: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - holding(any_targets|1, robot_0) + stage_2: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - not_holding(robot_0) + stage_2_5: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - holding(any_targets|2, robot_0) + stage_3: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - object_at(any_targets|2,TARGET_any_targets|2) + - not_holding(robot_0) + stage_3_5: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - object_at(any_targets|2,TARGET_any_targets|2) + - holding(any_targets|3, robot_0) + stage_4: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - object_at(any_targets|2,TARGET_any_targets|2) + - object_at(any_targets|3,TARGET_any_targets|3) + - not_holding(robot_0) + stage_4_5: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - object_at(any_targets|2,TARGET_any_targets|2) + - object_at(any_targets|3,TARGET_any_targets|3) + - object_at(any_targets|4,TARGET_any_targets|4) + +solution: + - nav(any_targets|0, robot_0) + - pick(any_targets|0, robot_0) + - nav(TARGET_any_targets|0, robot_0) + - place(any_targets|0,TARGET_any_targets|0, robot_0) + - nav(any_targets|1, robot_0) + - pick(any_targets|1, robot_0) + - nav(TARGET_any_targets|1, robot_0) + - place(any_targets|1,TARGET_any_targets|1, robot_0) + - nav(any_targets|2, robot_0) + - pick(any_targets|2, robot_0) + - nav(TARGET_any_targets|2, robot_0) + - place(any_targets|2,TARGET_any_targets|2, robot_0) + - nav(any_targets|3, robot_0) + - pick(any_targets|3, robot_0) + - nav(TARGET_any_targets|3, robot_0) + - place(any_targets|3,TARGET_any_targets|3, robot_0) + - nav(any_targets|4, robot_0) + - pick(any_targets|4, robot_0) + - nav(TARGET_any_targets|4, robot_0) + - place(any_targets|4,TARGET_any_targets|4, robot_0) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/tidy_house_2obj.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/tidy_house_2obj.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58d3b4128d24aad0131d181ab0598497ece26ef3 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/rearrange/pddl/tidy_house_2obj.yaml @@ -0,0 +1,45 @@ +objects: + - name: any_targets|0 + expr_type: movable_entity_type + - name: TARGET_any_targets|0 + expr_type: goal_entity_type + - name: any_targets|1 + expr_type: movable_entity_type + - name: TARGET_any_targets|1 + expr_type: goal_entity_type + - name: robot_0 + expr_type: robot_entity_type + +goal: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + - object_at(any_targets|1,TARGET_any_targets|1) + - not_holding(robot_0) + +stage_goals: + stage_1_1: + expr_type: AND + sub_exprs: + - holding(any_targets|0, robot_0) + stage_1_2: + expr_type: AND + sub_exprs: + - object_at(any_targets|0,TARGET_any_targets|0) + stage_2_1: + expr_type: AND + sub_exprs: + - holding(any_targets|1, robot_0) + stage_2_2: + expr_type: AND + sub_exprs: + - object_at(any_targets|1,TARGET_any_targets|1) +solution: + - nav_to_goal(any_targets|0, robot_0) + - pick(any_targets|0, robot_0) + - nav_to_obj(TARGET_any_targets|0, robot_0) + - place(any_targets|0,TARGET_any_targets|0, robot_0) + - nav_to_goal(any_targets|1, robot_0) + - pick(any_targets|1, robot_0) + - nav_to_obj(TARGET_any_targets|1, robot_0) + - place(any_targets|1,TARGET_any_targets|1, robot_0) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/vln_r2r.yaml b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/vln_r2r.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4880ccebd604529acdf653644ae569e0fdb7ccb6 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/habitat/task/vln_r2r.yaml @@ -0,0 +1,17 @@ +defaults: + - task_config_base + - actions: + - stop + - move_forward + - turn_left + - turn_right + - measurements: + - distance_to_goal + - success + - spl + - lab_sensors: + - instruction_sensor + - _self_ + + +type: VLN-v0 diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/read_write.py b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/read_write.py new file mode 100644 index 0000000000000000000000000000000000000000..a8125648164aa477f80efdeb1fa5616d45343d19 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/config/read_write.py @@ -0,0 +1,29 @@ +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from contextlib import contextmanager +from typing import Any, Generator + +from omegaconf import Container, OmegaConf +from omegaconf.base import Node + + +@contextmanager +def read_write(config: Any) -> Generator[Node, None, None]: + r""" + Temporarily authorizes the modification of a OmegaConf configuration + within a context. Use the 'with' statement to enter the context. + + :param config: The configuration object that should get writing access + """ + assert isinstance(config, Container) + prev_state_readonly = config._get_node_flag("readonly") + prev_state_struct = config._get_node_flag("struct") + try: + OmegaConf.set_struct(config, False) + OmegaConf.set_readonly(config, False) + yield config + finally: + OmegaConf.set_readonly(config, prev_state_readonly) + OmegaConf.set_struct(config, prev_state_struct) diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/py.typed b/world-in-world/src/habitat-baselines/habitat-lab/habitat/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..abe48a50ed08b42030da97044455c051f71146f5 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. This tells mypy that the package uses inline types. diff --git a/world-in-world/src/habitat-baselines/habitat-lab/habitat/version.py b/world-in-world/src/habitat-baselines/habitat-lab/habitat/version.py new file mode 100644 index 0000000000000000000000000000000000000000..85f8174fdc5818be0153a4b38369190097a74480 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/habitat/version.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +VERSION = "0.3.3" diff --git a/world-in-world/src/habitat-baselines/habitat-lab/requirements.txt b/world-in-world/src/habitat-baselines/habitat-lab/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f73e3471d73f2e8b9b771db089cc90696b60e958 --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/requirements.txt @@ -0,0 +1,16 @@ +gym>=0.22.0,<0.23.1 +numpy==1.26.4 +numpy-quaternion>=2019.3.18.14.33.20 +attrs>=19.1.0 +opencv-python>=3.3.0 +pickle5; python_version < '3.8' +# config dependencies +hydra-core>=1.2.0 +omegaconf>=2.2.3 +# acceleration dependencies +numba>=0.44.0 +# visualization optional dependencies +imageio>=2.2.0 +imageio-ffmpeg>=0.2.0 +scipy>=1.10.1 +tqdm>=4.0.0 diff --git a/world-in-world/src/habitat-baselines/habitat-lab/setup.py b/world-in-world/src/habitat-baselines/habitat-lab/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..924acf4475526b84dd63fa939f539ea8d9e613cc --- /dev/null +++ b/world-in-world/src/habitat-baselines/habitat-lab/setup.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + + +from setuptools import find_packages, setup + + +def read(file_path, *args, **kwargs): + with open(file_path, *args, **kwargs) as f: + content = f.read() + return content + + +def get_package_version(): + import os.path as osp + import sys + + sys.path.insert(0, osp.join(osp.dirname(__file__), "habitat")) + from version import VERSION + + return VERSION + + +def get_long_description(): + return """ +[![codecov](https://codecov.io/gh/facebookresearch/habitat-lab/branch/main/graph/badge.svg)](https://codecov.io/gh/facebookresearch/habitat-lab) +[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/facebookresearch/habitat-lab/blob/main/LICENSE) +[![GitHub release (latest by date)](https://img.shields.io/github/v/release/facebookresearch/habitat-lab)](https://github.com/facebookresearch/habitat-lab/releases/latest) +[![Supports Habitat_Sim](https://img.shields.io/static/v1?label=supports&message=Habitat%20Sim&color=informational&link=https://github.com/facebookresearch/habitat-sim)](https://github.com/facebookresearch/habitat-sim) +[![Python 3.7](https://img.shields.io/badge/python-3.7-blue.svg)](https://www.python.org/downloads/release/python-370/) +[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) +[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/) +[![Twitter Follow](https://img.shields.io/twitter/follow/ai_habitat?style=social)](https://twitter.com/ai_habitat) + +Habitat-Lab +============================== + +Habitat-Lab is a modular high-level library for end-to-end development in embodied AI -- +defining embodied AI tasks (e.g. navigation, rearrangement, instruction following, question answering), +configuring embodied agents (physical form, sensors, capabilities), training these agents (via imitation +or reinforcement learning, or no learning at all as in SensePlanAct pipelines), and benchmarking their +performance on the defined tasks using standard metrics. + +Habitat-Lab uses [`Habitat-Sim`](https://github.com/facebookresearch/habitat-sim) as the core simulator. +For documentation refer [here](https://aihabitat.org/docs/habitat-lab/). + +[![Habitat Demo](https://img.shields.io/static/v1?label=WebGL&message=Try%20AI%20Habitat%20In%20Your%20Browser%20&color=blue&logo=webgl&labelColor=%23990000&style=for-the-badge&link=https://aihabitat.org/demo)](https://aihabitat.org/demo) +""" + + +if __name__ == "__main__": + setup( + name="habitat-lab", + install_requires=read("requirements.txt").strip().split("\n"), + packages=find_packages(), + version=get_package_version(), + include_package_data=True, + description="Habitat-Lab: a modular high-level library for end-to-end development in Embodied AI.", + long_description=get_long_description(), + long_description_content_type="text/markdown", + author="Meta AI Research", + license="MIT License", + url="https://aihabitat.org", + project_urls={ + "GitHub repo": "https://github.com/facebookresearch/habitat-lab/", + "Bug Tracker": "https://github.com/facebookresearch/habitat-lab/issues", + }, + classifiers=[ + "Intended Audience :: Science/Research", + "Development Status :: 5 - Production/Stable", + "License :: OSI Approved :: MIT License", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + "Operating System :: MacOS", + "Operating System :: Unix", + ], + ) diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_all_sensors_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_all_sensors_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a2aa34486d2cda8bead7af6343f7acbc52fd1d51 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_all_sensors_test.yaml @@ -0,0 +1,24 @@ +# @package _global_ + +defaults: + - /habitat: habitat_config_base + - /habitat/task: pointnav + - /habitat/simulator/sensor_setups@habitat.simulator.agents.main_agent: rgbd_agent + - /habitat/dataset/pointnav: habitat_test + - _self_ + +habitat: + environment: + max_episode_steps: 10 + iterator_options: + shuffle: False + simulator: + agents: + main_agent: + sim_sensors: + rgb_sensor: + width: 256 + height: 256 + depth_sensor: + width: 256 + height: 256 diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_hm3d_instance_image_nav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_hm3d_instance_image_nav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32bbf3ddafdba24fbcbba1ed3bda155820ae4556 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_hm3d_instance_image_nav_test.yaml @@ -0,0 +1,13 @@ +# @package _global_ +defaults: + - /benchmark/nav/instance_imagenav/instance_imagenav_hm3d_v1.yaml + - _self_ + +habitat: + + dataset: + type: InstanceImageNav-v1 + split: minival + data_path: data/datasets/instance_imagenav/hm3d/v1/{split}/{split}.json.gz + scenes_dir: data/scene_datasets/ + content_scenes: ["*"] diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_hssd-hab_object_nav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_hssd-hab_object_nav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c30d261da23ce49985b42ed819d9149ebea562db --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_hssd-hab_object_nav_test.yaml @@ -0,0 +1,13 @@ +# @package _global_ +defaults: + - /benchmark/nav/objectnav/objectnav_hssd-hab.yaml + - _self_ + +habitat: + + dataset: + type: ObjectNav-v1 + split: val + data_path: data/datasets/objectnav/hssd-hab/{split}/{split}.json.gz + scenes_dir: data/scene_datasets/hssd-hab/scenes + content_scenes: ["*"] diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_mp3d_eqa_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_mp3d_eqa_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a97db87ea3c80ab836fb5ee822cbd2710dd78c9d --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_mp3d_eqa_test.yaml @@ -0,0 +1,30 @@ +# @package _global_ +defaults: + - /benchmark/nav/eqa_mp3d.yaml + - _self_ + +habitat: + environment: + max_episode_steps: 1000 + iterator_options: + shuffle: False + + simulator: + scene: data/scene_datasets/mp3d/17DRP5sb8fy/17DRP5sb8fy.glb + forward_step_size: 0.1 + turn_angle: 9 + agents: + main_agent: + sim_sensors: + rgb_sensor: + height: 512 + width: 512 + hfov: 45 + position: [0, 1.09, 0] + type: HabitatSimRGBSensor + + dataset: + type: MP3DEQA-v1 + split: val + data_path: "data/datasets/eqa/mp3d/v1/{split}/{split}.json.gz" + scenes_dir: "data/scene_datasets/" diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_mp3d_object_nav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_mp3d_object_nav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..040997744da5121a3701c797fe92f63f9f15db6a --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_mp3d_object_nav_test.yaml @@ -0,0 +1,14 @@ +# @package _global_ + +defaults: + - /benchmark/nav/objectnav/objectnav_mp3d.yaml + - _self_ + +habitat: + + dataset: + type: ObjectNav-v1 + split: val + content_scenes: ["*"] + data_path: "data/datasets/objectnav/mp3d/v1/{split}/{split}.json.gz" + scenes_dir: "data/scene_datasets/" diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_procthor-hab_object_nav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_procthor-hab_object_nav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8553bd6d9329070e334e170d1840c89360030236 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_procthor-hab_object_nav_test.yaml @@ -0,0 +1,13 @@ +# @package _global_ +defaults: + - /benchmark/nav/objectnav/objectnav_procthor-hab.yaml + - _self_ + +habitat: + + dataset: + type: ObjectNav-v1 + split: val + data_path: data/datasets/objectnav/procthor-hab/{split}/{split}.json.gz + scenes_dir: data/scene_datasets/ai2thor-hab/ai2thor-hab/configs/scenes/ProcTHOR/ + content_scenes: ["*"] diff --git a/world-in-world/src/habitat-baselines/test/config/habitat/habitat_r2r_vln_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_r2r_vln_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..989c2ac5e3f38a22441b71ba436c295b02d80171 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat/habitat_r2r_vln_test.yaml @@ -0,0 +1,16 @@ +# @package _global_ + +defaults: + - /benchmark/nav/vln_r2r.yaml + - _self_ + +habitat: + task: + measurements: + success: + success_distance: 0.1 + dataset: + type: R2RVLN-v1 + split: val_seen + data_path: "data/datasets/vln/mp3d/r2r/v1/{split}/{split}.json.gz" + scenes_dir: "data/scene_datasets/" diff --git a/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_imagenav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_imagenav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d3bda180e56996632dd3a4f2403ff2430cc925f3 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_imagenav_test.yaml @@ -0,0 +1,72 @@ +# @package _global_ + +defaults: + - /benchmark/nav/imagenav: imagenav_test + - /habitat_baselines: habitat_baselines_rl_config_base + - _self_ + +habitat_baselines: + trainer_name: "ddppo" + torch_gpu_id: 0 + tensorboard_dir: "" + video_dir: "" + eval_ckpt_path_dir: "data/test_checkpoints/ddppo/imagenav/ckpt.0.pth" + num_environments: 1 + checkpoint_folder: "data/test_checkpoints/ddppo/imagenav/" + num_updates: 2 + log_interval: 100 + num_checkpoints: 2 + test_episode_count: 2 + # Force PyTorch to be single threaded as + # this improves performance considerably + force_torch_single_threaded: True + + + rl: + policy: + main_agent: + name: "PointNavResNetPolicy" + + ppo: + # ppo params + clip_param: 0.2 + ppo_epoch: 2 + num_mini_batch: 1 + value_loss_coef: 0.5 + entropy_coef: 0.01 + lr: 2.5e-4 + eps: 1e-5 + max_grad_norm: 0.2 + num_steps: 16 + use_gae: True + gamma: 0.99 + tau: 0.95 + use_linear_clip_decay: False + use_linear_lr_decay: False + reward_window_size: 50 + + use_normalized_advantage: False + + hidden_size: 512 + + ddppo: + sync_frac: 0.6 + # The PyTorch distributed backend to use + distrib_backend: GLOO + # Visual encoder backbone + pretrained_weights: data/ddppo-models/gibson-2plus-resnet50.pth + # Initialize with pretrained weights + pretrained: False + # Initialize just the visual encoder backbone with pretrained weights + pretrained_encoder: False + # Whether the visual encoder backbone will be trained. + train_encoder: True + # Whether to reset the critic linear layer + reset_critic: True + + # Model parameters + backbone: resnet18 + rnn_type: LSTM + num_recurrent_layers: 2 + + force_distributed: True diff --git a/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_instance_imagenav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_instance_imagenav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3965b343f487467faef62c4e0c6753b1822d960 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_instance_imagenav_test.yaml @@ -0,0 +1,84 @@ +# @package _global_ + +defaults: + - /benchmark/nav/instance_imagenav: instance_imagenav_hm3d_v2 + - /habitat_baselines: habitat_baselines_rl_config_base + - /habitat_baselines/rl/policy/obs_transforms: + - resize_shortest_edge_base + - center_cropper_base + - _self_ + +habitat: + dataset: + split: minival + task: + success_reward: 2.5 + slack_reward: -1e-3 + +habitat_baselines: + torch_gpu_id: 0 + tensorboard_dir: "" + video_dir: "" + test_episode_count: 2 + eval_ckpt_path_dir: data/test_checkpoints/ddppo/instance_imagenav/ckpt.0.pth + num_environments: 1 + checkpoint_folder: data/test_checkpoints/ddppo/instance_imagenav + trainer_name: ddppo + num_updates: 2 + log_interval: 10 + num_checkpoints: 2 + # Force PyTorch to be single threaded as + # this improves performance considerably + force_torch_single_threaded: True + + rl: + policy: + main_agent: + name: PointNavResNetPolicy + obs_transforms: + resize_shortest_edge: + trans_keys: [rgb, depth, semantic, instance_imagegoal] + + ppo: + # ppo params + clip_param: 0.2 + ppo_epoch: 2 + num_mini_batch: 1 + value_loss_coef: 0.5 + entropy_coef: 0.01 + lr: 2.5e-4 + eps: 1e-5 + max_grad_norm: 0.2 + num_steps: 16 + use_gae: True + gamma: 0.99 + tau: 0.95 + use_linear_clip_decay: False + use_linear_lr_decay: False + reward_window_size: 50 + + use_normalized_advantage: False + + hidden_size: 512 + + ddppo: + sync_frac: 0.6 + # The PyTorch distributed backend to use + distrib_backend: GLOO + # Visual encoder backbone + pretrained_weights: data/ddppo-models/gibson-2plus-resnet50.pth + # Initialize with pretrained weights + pretrained: False + # Initialize just the visual encoder backbone with pretrained weights + pretrained_encoder: False + # Whether the visual encoder backbone will be trained. + train_encoder: True + # Whether to reset the critic linear layer + reset_critic: True + + # Model parameters + backbone: resnet18 + rnn_type: LSTM + num_recurrent_layers: 2 + + force_distributed: True diff --git a/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_pointnav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_pointnav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac7f4939fa66547996090f204b6a49ad826cfd21 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ddppo_pointnav_test.yaml @@ -0,0 +1,74 @@ +# @package _global_ + +defaults: + - /benchmark/nav/pointnav: pointnav_habitat_test + - /habitat_baselines: habitat_baselines_rl_config_base + - _self_ + +habitat: + task: + success_reward: 2.5 + +habitat_baselines: + trainer_name: "ddppo" + torch_gpu_id: 0 + tensorboard_dir: "" + eval_ckpt_path_dir: "data/test_checkpoints/ddppo/pointnav/ckpt.0.pth" + num_environments: 1 + checkpoint_folder: "data/test_checkpoints/ddppo/pointnav/" + num_updates: 2 + num_checkpoints: 2 + log_interval: 100 + test_episode_count: 2 + # Force PyTorch to be single threaded as + # this improves performance considerably + force_torch_single_threaded: True + + rl: + policy: + main_agent: + name: "PointNavResNetPolicy" + + ppo: + # ppo params + clip_param: 0.2 + ppo_epoch: 2 + num_mini_batch: 1 + value_loss_coef: 0.5 + entropy_coef: 0.01 + lr: 2.5e-4 + eps: 1e-5 + max_grad_norm: 0.2 + num_steps: 16 + use_gae: True + gamma: 0.99 + tau: 0.95 + use_linear_clip_decay: False + use_linear_lr_decay: False + reward_window_size: 50 + + use_normalized_advantage: False + + hidden_size: 512 + + ddppo: + sync_frac: 0.6 + # The PyTorch distributed backend to use + distrib_backend: GLOO + # Visual encoder backbone + pretrained_weights: data/ddppo-models/gibson-2plus-resnet50.pth + # Initialize with pretrained weights + pretrained: False + # Initialize just the visual encoder backbone with pretrained weights + pretrained_encoder: False + # Whether the visual encoder backbone will be trained. + train_encoder: True + # Whether to reset the critic linear layer + reset_critic: True + + # Model parameters + backbone: resnet18 + rnn_type: LSTM + num_recurrent_layers: 2 + + force_distributed: True diff --git a/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ppo_imagenav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ppo_imagenav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cb44948d053d45da17f15ce0669cd428f3fef895 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ppo_imagenav_test.yaml @@ -0,0 +1,41 @@ +# @package _global_ + +defaults: + - /benchmark/nav/imagenav: imagenav_test + - /habitat_baselines: habitat_baselines_rl_config_base + - _self_ + +habitat_baselines: + trainer_name: "ppo" + torch_gpu_id: 0 + tensorboard_dir: "" + eval_ckpt_path_dir: "data/test_checkpoints/ppo/imagenav/ckpt.0.pth" + num_environments: 1 + checkpoint_folder: "data/test_checkpoints/ppo/imagenav/" + num_updates: 2 + log_interval: 100 + num_checkpoints: 2 + test_episode_count: 2 + # Force PyTorch to be single threaded as + # this improves performance considerably + force_torch_single_threaded: True + + rl: + ppo: + # ppo params + clip_param: 0.1 + ppo_epoch: 4 + num_mini_batch: 1 + value_loss_coef: 0.5 + entropy_coef: 0.01 + lr: 2.5e-4 + eps: 1e-5 + max_grad_norm: 0.5 + num_steps: 16 + hidden_size: 512 + use_gae: True + gamma: 0.99 + tau: 0.95 + use_linear_clip_decay: True + use_linear_lr_decay: True + reward_window_size: 50 diff --git a/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ppo_pointnav_test.yaml b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ppo_pointnav_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6637856bffeb5124c1379c8cbd5cc32c806e6d0 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/config/habitat_baselines/ppo_pointnav_test.yaml @@ -0,0 +1,45 @@ +# @package _global_ + +defaults: + - /benchmark/nav/pointnav: pointnav_habitat_test + - /habitat_baselines: habitat_baselines_rl_config_base + - _self_ + +habitat_baselines: + trainer_name: "ppo" + torch_gpu_id: 0 + video_dir: "data/test_checkpoints/ppo/pointnav/video" + tensorboard_dir: "" + eval_ckpt_path_dir: "data/test_checkpoints/ppo/pointnav/ckpt.0.pth" + num_environments: 1 + checkpoint_folder: "data/test_checkpoints/ppo/pointnav/" + num_updates: 2 + log_interval: 100 + num_checkpoints: 2 + test_episode_count: 2 + # Force PyTorch to be single threaded as + # this improves performance considerably + force_torch_single_threaded: True + + eval: + video_option: ["disk"] + + rl: + ppo: + # ppo params + clip_param: 0.1 + ppo_epoch: 4 + num_mini_batch: 1 + value_loss_coef: 0.5 + entropy_coef: 0.01 + lr: 2.5e-4 + eps: 1e-5 + max_grad_norm: 0.5 + num_steps: 16 + hidden_size: 512 + use_gae: True + gamma: 0.99 + tau: 0.95 + use_linear_clip_decay: True + use_linear_lr_decay: True + reward_window_size: 50 diff --git a/world-in-world/src/habitat-baselines/test/data/habitat-sim_trajectory_data.json b/world-in-world/src/habitat-baselines/test/data/habitat-sim_trajectory_data.json new file mode 100644 index 0000000000000000000000000000000000000000..beb502e1347f81cac71a61edbc7885d1d51848d9 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/data/habitat-sim_trajectory_data.json @@ -0,0 +1 @@ +{"positions": [[2.9085702896118164, 0.07244700193405151, 0.13949552178382874], [2.692063808441162, 0.17669875919818878, 0.014495700597763062], [2.475557327270508, 0.17669875919818878, -0.11050412058830261], [2.2590508460998535, 0.17669875919818878, -0.12059974670410156], [2.042544364929199, 0.17669875919818878, -0.12059974670410156], [1.826037883758545, 0.17669875919818878, -0.12059974670410156], [1.6095314025878906, 0.17669875919818878, -0.12059974670410156], [1.3930249214172363, 0.17669875919818878, -0.12059974670410156], [1.176518440246582, 0.17669875919818878, -0.12059974670410156], [1.176518440246582, 0.17669875919818878, -0.12059974670410156], [0.941595196723938, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156], [0.8741309642791748, 0.17669875919818878, -0.12059974670410156]], "rotations": [[0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000003576278687, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.5000002980232239, 0.0, 0.8660252094268799], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.5735767483711243, 0.0, 0.8191518187522888], [0.0, 0.573576807975769, 0.0, 0.8191518187522888], [0.0, 0.6427879929542542, 0.0, 0.7660441398620605], [0.0, 0.6427879929542542, 0.0, 0.7660441398620605], [0.0, 0.6427879929542542, 0.0, 0.7660441398620605], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7071071863174438, 0.0, 0.707106351852417], [0.0, 0.7660449147224426, 0.0, 0.6427870988845825], [0.0, 0.7660449743270874, 0.0, 0.6427870392799377], [0.0, 0.7660449743270874, 0.0, 0.642786979675293], [0.0, 0.8191525340080261, 0.0, 0.5735757350921631], [0.0, 0.8191525340080261, 0.0, 0.5735757350921631], [0.0, 0.8191525340080261, 0.0, 0.5735757350921631], [0.0, 0.8191525340080261, 0.0, 0.5735757350921631], [0.0, 0.8660258650779724, 0.0, 0.4999992549419403], [0.0, 0.8660258650779724, 0.0, 0.4999992549419403], [0.0, 0.8660258650779724, 0.0, 0.4999992549419403], [0.0, 0.8660258650779724, 0.0, 0.4999992549419403], [0.0, 0.8660258650779724, 0.0, 0.4999992549419403], [0.0, 0.8660258650779724, 0.0, 0.4999992549419403]], "actions": ["move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "turn_left", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "turn_left", "move_forward", "move_forward", "turn_left", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "turn_left", "move_forward", "move_forward", "turn_left", "move_forward", "move_forward", "move_forward", "turn_left", "move_forward", "move_forward", "move_forward", "move_forward", "move_forward", "stop"], "distances_to_obstacles": [null, 0.2564087510108948, 0.010195869952440262, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]} diff --git a/world-in-world/src/habitat-baselines/test/data/test-sim-geodesic-distance-test-golden.json b/world-in-world/src/habitat-baselines/test/data/test-sim-geodesic-distance-test-golden.json new file mode 100644 index 0000000000000000000000000000000000000000..a3a0ab0c22141497a265d1a8518049c9e391faaa --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/data/test-sim-geodesic-distance-test-golden.json @@ -0,0 +1 @@ +{"single_end": [{"start": [4.037322044372559, 0.17669875919818878, -0.23804163932800293], "end": [2.5792133808135986, 0.17669875919818878, -0.4069739878177643], "expected": 1.4678621292114258}, {"start": [1.7050966024398804, 0.850846529006958, -0.7110730409622192], "end": [1.6032905578613281, 0.8653902411460876, -0.7250872850418091], "expected": 0.10379011929035187}, {"start": [1.5123053789138794, 0.8783881664276123, -0.49398791790008545], "end": [2.9792256355285645, 0.17669875919818878, 0.858018696308136], "expected": Infinity}, {"start": [1.668128490447998, 0.17669875919818878, 0.6336665153503418], "end": [3.3843514919281006, 0.17669875919818878, 0.7407974004745483], "expected": 1.7195634841918945}, {"start": [2.7329232692718506, 0.17669875919818878, -1.4133919477462769], "end": [2.8786423206329346, 0.17669875919818878, 0.3134367763996124], "expected": 1.7329660654067993}, {"start": [2.563307046890259, 0.17669875919818878, 0.909062922000885], "end": [3.675917148590088, 0.17669875919818878, 1.054469347000122], "expected": 1.122071385383606}, {"start": [4.004800796508789, 0.17669875919818878, 0.5141764879226685], "end": [0.6324083209037781, 1.1235064268112183, -1.3417372703552246], "expected": Infinity}, {"start": [3.2524852752685547, 0.17669875919818878, -0.06666716933250427], "end": [2.773023843765259, 0.17669875919818878, -1.3392752408981323], "expected": 1.3599318265914917}, {"start": [2.9571542739868164, 0.17669875919818878, -0.0902959480881691], "end": [1.7745393514633179, 0.17669875919818878, 0.9635447263717651], "expected": 1.5840322971343994}, {"start": [3.5489964485168457, 0.17669875919818878, 0.8011412620544434], "end": [1.3991484642028809, 0.17669875919818878, 1.2949700355529785], "expected": 2.2345314025878906}], "multi_end": [{"start": [3.544208526611328, 0.17669875919818878, -1.41517972946167], "ends": [[3.521932363510132, 0.17669875919818878, 0.7296927571296692], [2.730733871459961, 0.17669875919818878, -0.5273106098175049], [3.1161608695983887, 0.17669875919818878, 0.07737593352794647], [2.7823123931884766, 0.17669875919818878, 0.5482414960861206], [3.5699496269226074, 0.17669875919818878, 0.5463329553604126], [1.8619900941848755, 0.8307491540908813, -1.2049251794815063], [3.2307140827178955, 0.17669875919818878, 0.6126762628555298], [3.6708688735961914, 0.17669875919818878, 0.7956723570823669], [2.0713467597961426, 0.7985250949859619, -0.5255419611930847], [2.9021413326263428, 0.17669875919818878, -1.2789204120635986]], "expected": 0.6563664078712463}, {"start": [1.8526794910430908, 0.8297632932662964, -0.8264407515525818], "ends": [[3.9620230197906494, 0.17669875919818878, -0.856576144695282], [2.0347423553466797, 0.8037543296813965, -0.8717583417892456], [1.6483498811721802, 0.8589532375335693, -0.9404497146606445], [1.5917786359786987, 0.8670347929000854, -0.9419161081314087], [3.1552112102508545, 0.17669875919818878, 0.6074334383010864], [3.355802536010742, 0.17669875919818878, -1.1638051271438599], [3.418046712875366, 0.17669875919818878, -0.7616501450538635], [1.549034595489502, 0.17669875919818878, 1.4259990453720093], [3.6226768493652344, 0.17669875919818878, -0.12488168478012085], [3.2269439697265625, 0.17669875919818878, 1.112937569618225]], "expected": 0.18941235542297363}, {"start": [0.8193789720535278, 1.0211834907531738, -0.8889061212539673], "ends": [[2.564119338989258, 0.17669875919818878, -0.438992440700531], [2.9484076499938965, 0.17669875919818878, 0.7632013559341431], [1.7659375667572021, 0.17669875919818878, 0.6230194568634033], [1.743850588798523, 0.8453102707862854, -0.8829933404922485], [1.7375985383987427, 0.17669875919818878, 0.23923079669475555], [3.0381407737731934, 0.17669875919818878, 0.9857368469238281], [4.010539531707764, 0.17669875919818878, 1.491629719734192], [0.7745168209075928, 1.0093865394592285, -0.557742178440094], [3.841386556625366, 0.17669875919818878, -0.8741586208343506], [1.4050216674804688, 0.17669875919818878, 0.7606305480003357]], "expected": 0.33439698815345764}, {"start": [3.5690805912017822, 0.17669875919818878, 0.6812951564788818], "ends": [[1.3310660123825073, 0.9093267917633057, -0.8726937174797058], [1.3012155294418335, 0.17669875919818878, 1.4444442987442017], [2.255032539367676, 0.17669875919818878, 0.8752166628837585], [1.440248966217041, 0.17669875919818878, 0.8333883285522461], [4.032251834869385, 0.17669875919818878, 0.9518351554870605], [1.4166719913482666, 0.89205002784729, -0.48725029826164246], [1.5315741300582886, 0.8952614665031433, -1.375150203704834], [1.7477754354476929, 0.17669875919818878, 1.5820434093475342], [1.5671463012695312, 0.870553731918335, -0.6097143292427063], [3.2990524768829346, 0.17669875919818878, -0.42325806617736816]], "expected": 0.5363948941230774}, {"start": [2.995229959487915, 0.17669875919818878, 0.29812443256378174], "ends": [[1.8211901187896729, 0.17669875919818878, -0.04829436540603638], [3.79548978805542, 0.17669875919818878, -1.191503643989563], [2.60290265083313, 0.17669875919818878, 0.6940752863883972], [3.371999502182007, 0.17669875919818878, -0.1872195303440094], [2.6815378665924072, 0.17669875919818878, -1.235860824584961], [3.4348154067993164, 0.17669875919818878, -0.7104426622390747], [3.3797435760498047, 0.17669875919818878, 0.16160768270492554], [1.8795522451400757, 0.17669875919818878, 0.2864430248737335], [3.296427011489868, 0.17669875919818878, -0.8100904822349548], [1.2782912254333496, 0.9118187427520752, -0.41459980607032776]], "expected": 0.40802884101867676}, {"start": [4.180734634399414, 0.17669875919818878, 1.365483283996582], "ends": [[1.8713263273239136, 0.17669875919818878, 0.5408008098602295], [1.5510540008544922, 0.17669875919818878, 0.2028655707836151], [1.3495702743530273, 0.17669875919818878, 1.10086190700531], [1.7793582677841187, 0.17669875919818878, 0.19185835123062134], [3.4216606616973877, 0.17669875919818878, -1.244666337966919], [1.9289309978485107, 0.17669875919818878, 0.4518055319786072], [3.1165847778320312, 0.17669875919818878, 0.7173597812652588], [0.9095644354820251, 0.9767820835113525, -0.7304283380508423], [1.2739722728729248, 0.9410917162895203, -1.4000232219696045], [2.633979082107544, 0.17669875919818878, -0.1734899878501892]], "expected": 1.2459851503372192}, {"start": [1.6736913919448853, 0.8553329706192017, -0.9071687459945679], "ends": [[3.516659736633301, 0.17669875919818878, 0.17189672589302063], [3.927156925201416, 0.17669875919818878, 0.23320698738098145], [1.1335248947143555, 0.17669875919818878, 0.3726574778556824], [2.504218339920044, 0.17669875919818878, 0.06016254797577858], [3.14448881149292, 0.17669875919818878, 0.5501950979232788], [2.873000144958496, 0.17669875919818878, 1.0750404596328735], [3.255852699279785, 0.17669875919818878, -0.8344844579696655], [3.1559338569641113, 0.17669875919818878, -0.004399538040161133], [3.173886775970459, 0.17669875919818878, 1.1263200044631958], [3.5776305198669434, 0.17669875919818878, 1.1739460229873657]], "expected": Infinity}, {"start": [2.7284677028656006, 0.17669875919818878, 0.14024531841278076], "ends": [[2.555941581726074, 0.17669875919818878, 1.5085395574569702], [2.687814712524414, 0.17669875919818878, -0.33587518334388733], [3.4542040824890137, 0.17669875919818878, -0.6949514746665955], [3.896925687789917, 0.17669875919818878, -1.257703423500061], [0.6303458213806152, 1.0743591785430908, -0.5141727328300476], [1.8069920539855957, 0.8362900614738464, -0.5766603946685791], [3.929680585861206, 0.17669875919818878, 1.6014347076416016], [2.861459493637085, 0.17669875919818878, 0.13020926713943481], [0.9655500650405884, 0.9610695838928223, -0.5871159434318542], [3.1372978687286377, 0.17669875919818878, 0.8947721719741821]], "expected": 0.13336993753910065}, {"start": [2.1949660778045654, 0.7808651924133301, -0.6982868909835815], "ends": [[0.7539876699447632, 1.0557118654251099, -1.0320557355880737], [2.9706034660339355, 0.17669875919818878, -1.1788238286972046], [4.153510093688965, 0.17669875919818878, 1.4543215036392212], [2.563261032104492, 0.17669875919818878, 1.450569748878479], [2.509915351867676, 0.17669875919818878, -0.16886363923549652], [1.6272252798080444, 0.8675953149795532, -1.1087474822998047], [1.6528584957122803, 0.17669875919818878, 0.9294744729995728], [4.111237525939941, 0.17669875919818878, 0.7561463117599487], [0.5348877906799316, 1.1360671520233154, -0.982720673084259], [1.4812554121017456, 0.8828238248825073, -0.8495296835899353]], "expected": 0.7059246897697449}, {"start": [3.0449154376983643, 0.17669875919818878, -0.37294435501098633], "ends": [[3.728013515472412, 0.17669875919818878, -0.5662829875946045], [1.8191591501235962, 0.8345518708229065, -1.0111876726150513], [1.892622947692871, 0.832504391670227, -1.375971794128418], [1.3125849962234497, 0.17669875919818878, 0.18399712443351746], [3.1143784523010254, 0.17669875919818878, -1.229229211807251], [1.0501415729522705, 0.9559258222579956, -0.8181776404380798], [3.508554458618164, 0.17669875919818878, 0.0482138991355896], [1.2275488376617432, 0.17669875919818878, 0.031936973333358765], [3.2061545848846436, 0.17669875919818878, 0.565402090549469], [3.399303436279297, 0.17669875919818878, -0.27292314171791077]], "expected": 0.368232399225235}]} diff --git a/world-in-world/src/habitat-baselines/test/test_baseline_resnet.py b/world-in-world/src/habitat-baselines/test/test_baseline_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..5867a6dd937dc5672ccfa8a573ed68d51bf8ea1d --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_baseline_resnet.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import pytest +from gym import spaces + +try: + import torch + import torch.distributed + + from habitat_baselines.rl.ddppo.policy.resnet import resnet18, resnet50 + from habitat_baselines.rl.ddppo.policy.resnet_policy import ResNetEncoder + + baseline_installed = True +except ImportError: + baseline_installed = False + + +def _npobs_dict_to_tensorobs_dict(npobs_dict): + result = {} + for k, v in npobs_dict.items(): + result[k] = torch.as_tensor(v).unsqueeze(0) + return result + + +@pytest.mark.skipif( + not baseline_installed, reason="baseline sub-module not installed" +) +@pytest.mark.parametrize( + "observation_space", + [ + spaces.Dict( + { + "rgb_1": spaces.Box(low=0, high=1, shape=(62, 30, 3)), + "rgb_2": spaces.Box(low=0, high=1, shape=(62, 30, 2)), + }, + ), + spaces.Dict( + { + "rgb_1": spaces.Box(low=0, high=1, shape=(63, 84, 1)), + "depth_1": spaces.Box(low=0, high=1, shape=(63, 84, 2)), + }, + ), + spaces.Dict( + { + "rgb_1": spaces.Box(low=0, high=1, shape=(64, 128, 3)), + }, + ), + spaces.Dict( + { + "rgb_1": spaces.Box(low=0, high=1, shape=(65, 30, 3)), + "rgb_2": spaces.Box(low=0, high=1, shape=(65, 30, 1)), + "depth_1": spaces.Box(low=0, high=1, shape=(65, 30, 2)), + }, + ), + spaces.Dict( + { + "rgb_1": spaces.Box(low=0, high=1, shape=(66, 64, 3)), + "depth_2": spaces.Box(low=0, high=1, shape=(66, 64, 2)), + }, + ), + ], +) +@pytest.mark.parametrize("backbone", [resnet18, resnet50]) +def test_resnetencoder_initialization(observation_space, backbone): + encoder = ResNetEncoder(observation_space, make_backbone=backbone) + obs = observation_space.sample() + t_obs = _npobs_dict_to_tensorobs_dict(obs) + out = encoder.forward(t_obs) + assert out.shape == (1, *encoder.output_shape) diff --git a/world-in-world/src/habitat-baselines/test/test_config.py b/world-in-world/src/habitat-baselines/test/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e194feab968d65b6a6ac8e42302fbc172195373d --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_config.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from habitat.config.default import get_config + +CFG_TEST = "test/config/habitat/habitat_all_sensors_test.yaml" +MAX_TEST_STEPS_LIMIT = 3 + + +def test_overwrite_options(): + for steps_limit in range(MAX_TEST_STEPS_LIMIT): + config = get_config( + config_path=CFG_TEST, + overrides=[f"habitat.environment.max_episode_steps={steps_limit}"], + ) + assert ( + config.habitat.environment.max_episode_steps == steps_limit + ), "Overwriting of config options failed." diff --git a/world-in-world/src/habitat-baselines/test/test_habitat_env.py b/world-in-world/src/habitat-baselines/test/test_habitat_env.py new file mode 100644 index 0000000000000000000000000000000000000000..4a536e5f38a6c5787dd691447cdac4747aa54856 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_habitat_env.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import itertools +import multiprocessing as mp +import os +from typing import List + +import numpy as np +import pytest +from gym import Wrapper + +import habitat +from habitat.config.default import get_agent_config, get_config +from habitat.core.batch_rendering.env_batch_renderer_constants import ( + KEYFRAME_OBSERVATION_KEY, +) +from habitat.core.simulator import AgentState +from habitat.datasets.pointnav.pointnav_dataset import PointNavDatasetV1 +from habitat.gym.gym_definitions import make_gym_from_config +from habitat.gym.gym_wrapper import HabGymWrapper +from habitat.tasks.nav.nav import NavigationEpisode, NavigationGoal +from habitat.utils.test_utils import ( + sample_non_stop_action, + sample_non_stop_action_gym, +) + +CFG_TEST = "test/config/habitat/habitat_all_sensors_test.yaml" +NUM_ENVS = 4 + + +class DummyRLEnv(habitat.RLEnv): + def __init__(self, config, dataset=None): + super(DummyRLEnv, self).__init__(config, dataset) + + def get_reward_range(self): + return -1.0, 1.0 + + def get_reward(self, observations): + return 0.0 + + def get_done(self, observations): + done = False + if self._env.episode_over: + done = True + return done + + def get_info(self, observations): + return {} + + +class CallTestEnvWrapper(Wrapper): + def __init__(self, env, env_ind=0): + super(CallTestEnvWrapper, self).__init__(env) + self._dummy_variable = env_ind + + def get_env_ind(self): + return self._dummy_variable + + def set_env_ind(self, new_env_ind): + self._dummy_variable = new_env_ind + + +def _load_test_data(): + configs = [] + datasets = [] + for _ in range(NUM_ENVS): + config = get_config(CFG_TEST) + if not PointNavDatasetV1.check_config_paths_exist( + config.habitat.dataset + ): + pytest.skip("Please download Habitat test data to data folder.") + + datasets.append( + habitat.make_dataset( + id_dataset=config.habitat.dataset.type, + config=config.habitat.dataset, + ) + ) + + with habitat.config.read_write(config): + config.habitat.simulator.scene = datasets[-1].episodes[0].scene_id + # remove the teleport action that makes the action space continuous + if "teleport" in config.habitat.task.actions: + del config.habitat.task.actions["teleport"] + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip( + "Please download Habitat test data to data folder." + ) + configs.append(config) + + return configs, datasets + + +def _vec_env_test_fn(configs, datasets, multiprocessing_start_method, gpu2gpu): + num_envs = len(configs) + for cfg in configs: + with habitat.config.read_write(cfg): + cfg.habitat.simulator.habitat_sim_v0.gpu_gpu = gpu2gpu + + env_fn_args = tuple(zip(configs, datasets, range(num_envs))) + with habitat.VectorEnv( + make_env_fn=_make_dummy_env_func, + env_fn_args=env_fn_args, + multiprocessing_start_method=multiprocessing_start_method, + ) as envs: + envs.reset() + + for _ in range(2 * configs[0].habitat.environment.max_episode_steps): + observations = envs.step( + sample_non_stop_action_gym(envs.action_spaces[0], num_envs) + ) + assert len(observations) == num_envs + + +@pytest.mark.parametrize( + "multiprocessing_start_method,gpu2gpu", + itertools.product(["forkserver", "spawn", "fork"], [True, False]), +) +def test_vectorized_envs(multiprocessing_start_method, gpu2gpu): + import habitat_sim + + if gpu2gpu and not habitat_sim.cuda_enabled: + pytest.skip("GPU-GPU requires CUDA") + + configs, datasets = _load_test_data() + if multiprocessing_start_method == "fork": + if gpu2gpu: + pytest.skip("Fork does not support gpu2gpu") + + # 'fork' works in a process that has yet to use the GPU + # this test uses spawns a new python instance, which allows us to fork + mp_ctx = mp.get_context("spawn") + p = mp_ctx.Process( + target=_vec_env_test_fn, + args=(configs, datasets, multiprocessing_start_method, gpu2gpu), + ) + p.start() + p.join() + assert p.exitcode == 0 + else: + _vec_env_test_fn( + configs, datasets, multiprocessing_start_method, gpu2gpu + ) + + +def test_with_scope(): + configs, _ = _load_test_data() + env_fn_args = tuple((c,) for c in configs) + with habitat.VectorEnv( + make_env_fn=make_gym_from_config, + env_fn_args=env_fn_args, + multiprocessing_start_method="forkserver", + ) as envs: + envs.reset() + + assert envs._is_closed + + +def test_number_of_episodes(): + configs, _ = _load_test_data() + env_fn_args = tuple((c,) for c in configs) + with habitat.VectorEnv( + make_env_fn=make_gym_from_config, + env_fn_args=env_fn_args, + multiprocessing_start_method="forkserver", + ) as envs: + assert envs.number_of_episodes == [10000, 10000, 10000, 10000] + + +def test_threaded_vectorized_env(): + configs, datasets = _load_test_data() + num_envs = len(configs) + env_fn_args = tuple((c,) for c in configs) + with habitat.ThreadedVectorEnv( + make_env_fn=make_gym_from_config, env_fn_args=env_fn_args + ) as envs: + envs.reset() + + for _ in range(2 * configs[0].habitat.environment.max_episode_steps): + observations = envs.step( + sample_non_stop_action_gym(envs.action_spaces[0], num_envs) + ) + assert len(observations) == num_envs + + +@pytest.mark.parametrize("gpu2gpu", [False, True]) +def test_env(gpu2gpu): + import habitat_sim + + if gpu2gpu and not habitat_sim.cuda_enabled: + pytest.skip("GPU-GPU requires CUDA") + + config = get_config(CFG_TEST) + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + + with habitat.config.read_write(config): + config.habitat.simulator.habitat_sim_v0.gpu_gpu = gpu2gpu + # remove the teleport action that makes the action space continuous + if "teleport" in config.habitat.task.actions: + del config.habitat.task.actions["teleport"] + with habitat.Env(config=config, dataset=None) as env: + env.episodes = [ + NavigationEpisode( + episode_id="0", + scene_id=config.habitat.simulator.scene, + start_position=[-3.0133917, 0.04623024, 7.3064547], + start_rotation=[0, 0.163276, 0, 0.98658], + goals=[ + NavigationGoal( + position=[ + -3.0133917 + 0.01, + 0.04623024, + 7.3064547 + 0.01, + ] + ) + ], + info={"geodesic_distance": 0.001}, + ) + ] + env.reset() + + for _ in range(config.habitat.environment.max_episode_steps): + env.step(sample_non_stop_action(env.action_space)) + + # check for steps limit on environment + assert env.episode_over is True, ( + "episode should be over after " "max_episode_steps" + ) + + env.reset() + + env.step(action=0) + # check for stop action + assert ( + env.episode_over is True + ), "episode should be over after stop action" + + +@pytest.mark.parametrize("gpu2gpu", [False, True]) +def test_rl_vectorized_envs(gpu2gpu): + import habitat_sim + + if gpu2gpu and not habitat_sim.cuda_enabled: + pytest.skip("GPU-GPU requires CUDA") + + configs, datasets = _load_test_data() + for config in configs: + with habitat.config.read_write(config): + config.habitat.simulator.habitat_sim_v0.gpu_gpu = gpu2gpu + agent_config = get_agent_config(config.habitat.simulator) + # Only keep the rgb_sensor + agent_config.sim_sensors = { + "rgb_sensor": agent_config.sim_sensors["rgb_sensor"] + } + + num_envs = len(configs) + env_fn_args = tuple(zip(configs, datasets, range(num_envs))) + with habitat.VectorEnv( + make_env_fn=_make_dummy_env_func, env_fn_args=env_fn_args + ) as envs: + envs.reset() + + for i in range(2 * configs[0].habitat.environment.max_episode_steps): + outputs = envs.step( + sample_non_stop_action_gym(envs.action_spaces[0], num_envs) + ) + observations, rewards, dones, infos = [ + list(x) for x in zip(*outputs) + ] + assert len(observations) == num_envs + assert len(rewards) == num_envs + assert len(dones) == num_envs + assert len(infos) == num_envs + + tiled_img = envs.render(mode="rgb_array") + new_height = int(np.ceil(np.sqrt(NUM_ENVS))) + new_width = int(np.ceil(float(NUM_ENVS) / new_height)) + h, w, c = observations[0]["rgb"].shape + assert tiled_img.shape == ( + h * new_height, + w * new_width, + c, + ), "vector env render is broken" + + if (i + 1) % configs[0].habitat.environment.max_episode_steps == 0: + assert all( + dones + ), "dones should be true after max_episode steps" + + +@pytest.mark.parametrize("classic_replay_renderer", [False, True]) +@pytest.mark.parametrize("sensor_uuid", ["rgb_sensor", "depth_sensor"]) +@pytest.mark.parametrize("gpu2gpu", [False]) +def test_rl_vectorized_envs_batch_renderer( + gpu2gpu: bool, sensor_uuid: str, classic_replay_renderer: bool +): + import habitat_sim + + if gpu2gpu and not habitat_sim.cuda_enabled: + pytest.skip("GPU-GPU requires CUDA") + + if sensor_uuid == "rgb_sensor": + obs_key = "rgb" + elif sensor_uuid == "depth_sensor": + obs_key = "depth" + else: + pytest.fail("Unknown sensor uuid: " + sensor_uuid) + + configs, datasets = _load_test_data() + for config in configs: + with habitat.config.read_write(config): + config.habitat.simulator.renderer.enable_batch_renderer = True + config.habitat.simulator.renderer.classic_replay_renderer = ( + classic_replay_renderer + ) + config.habitat.simulator.habitat_sim_v0.enable_gfx_replay_save = ( + True + ) + config.habitat.simulator.create_renderer = False + config.habitat.simulator.habitat_sim_v0.gpu_gpu = gpu2gpu + agent_config = get_agent_config(config.habitat.simulator) + ## Only keep one sensor + agent_config.sim_sensors = { + sensor_uuid: agent_config.sim_sensors[sensor_uuid] + } + + num_envs = len(configs) + env_fn_args = tuple(zip(configs, datasets, range(num_envs))) + with habitat.VectorEnv( + make_env_fn=_make_dummy_env_func, env_fn_args=env_fn_args + ) as envs: + envs.initialize_batch_renderer(configs[0]) + observations = envs.reset() + for env_obs in observations: + assert KEYFRAME_OBSERVATION_KEY in env_obs + + observations = envs.post_step(observations) + for env_obs in observations: + assert KEYFRAME_OBSERVATION_KEY not in env_obs + + assert len(observations) == num_envs + + # TODO: Add screenshot tests. Image stats are compared until then. + threshold: float = 0.01 + if sensor_uuid == "rgb_sensor": + baseline_mean = [126.23, 126.84, 126.62, 125.63] + baseline_std_dev = [26.54, 26.16, 25.80, 26.56] + elif sensor_uuid == "depth_sensor": + baseline_mean = [0.4852, 0.4886, 0.4920, 0.4956] + baseline_std_dev = [0.0107, 0.0112, 0.0117, 0.0122] + for env_idx in range(num_envs): + env_obs = observations[env_idx][obs_key] + mean = float(np.mean(env_obs[env_idx])) + std_dev = float(np.std(env_obs[env_idx])) + assert abs(baseline_mean[env_idx] - mean) < threshold + assert abs(baseline_std_dev[env_idx] - std_dev) < threshold + + for _ in range(2 * configs[0].habitat.environment.max_episode_steps): + outputs = envs.step( + sample_non_stop_action_gym(envs.action_spaces[0], num_envs) + ) + observations, rewards, dones, infos = [ + list(x) for x in zip(*outputs) + ] + + for env_obs in observations: + assert KEYFRAME_OBSERVATION_KEY in env_obs + + observations = envs.post_step(observations) + + for env_obs in observations: + assert KEYFRAME_OBSERVATION_KEY not in env_obs + + assert len(observations) == num_envs + assert len(rewards) == num_envs + assert len(dones) == num_envs + assert len(infos) == num_envs + + # Note: Uncomment this line to visualize: + # envs.render(mode="human") + + tiled_img = envs.render(mode="rgb_array") + new_height = int(np.ceil(np.sqrt(NUM_ENVS))) + new_width = int(np.ceil(float(NUM_ENVS) / new_height)) + h, w, _ = observations[0][obs_key].shape + assert tiled_img.shape == ( + h * new_height, + w * new_width, + 3, + ), "vector env render is broken" + + +@pytest.mark.parametrize("gpu2gpu", [False, True]) +def test_rl_env(gpu2gpu): + import habitat_sim + + if gpu2gpu and not habitat_sim.cuda_enabled: + pytest.skip("GPU-GPU requires CUDA") + + config = get_config(CFG_TEST) + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + + with habitat.config.read_write(config): + config.habitat.simulator.habitat_sim_v0.gpu_gpu = gpu2gpu + # remove the teleport action that makes the action space continuous + if "teleport" in config.habitat.task.actions: + del config.habitat.task.actions["teleport"] + + with _make_dummy_env_func(config=config, dataset=None) as env: + env.episodes = [ + NavigationEpisode( + episode_id="0", + scene_id=config.habitat.simulator.scene, + start_position=[-3.0133917, 0.04623024, 7.3064547], + start_rotation=[0, 0.163276, 0, 0.98658], + goals=[ + NavigationGoal( + position=[ + -3.0133917 + 0.01, + 0.04623024, + 7.3064547 + 0.01, + ] + ) + ], + info={"geodesic_distance": 0.001}, + ) + ] + + done = False + env.reset() + + for _ in range(config.habitat.environment.max_episode_steps): + observation, reward, done, info = env.step( + action=sample_non_stop_action_gym(env.action_space) + ) + + # check for steps limit on environment + assert done is True, "episodes should be over after max_episode_steps" + + env.reset() + observation, reward, done, info = env.step(action=0) + assert done is True, "done should be true after stop action" + + +def _make_dummy_env_func(config, dataset=None, env_id=0, rank=0): + r"""Constructor for dummy habitat Env. + :param config: configurations for environment + :param dataset: dataset for environment + :param rank: rank for setting seeds for environment + :return: constructed habitat Env + """ + env = DummyRLEnv(config=config, dataset=dataset) + env.seed(config.habitat.seed + rank) + env = HabGymWrapper(env=env) + env = CallTestEnvWrapper(env, env_id) + return env + + +def test_vec_env_call_func(): + configs, datasets = _load_test_data() + num_envs = len(configs) + env_fn_args = tuple(zip(configs, datasets, range(num_envs))) + true_env_ids = list(range(num_envs)) + with habitat.VectorEnv( + make_env_fn=_make_dummy_env_func, + env_fn_args=env_fn_args, + multiprocessing_start_method="forkserver", + ) as envs: + envs.reset() + env_ids = envs.call(["get_env_ind"] * num_envs) + assert env_ids == true_env_ids + + env_id = envs.call_at(1, "get_env_ind") + assert env_id == true_env_ids[1] + + envs.call_at(2, "set_env_ind", {"new_env_ind": 20}) + true_env_ids[2] = 20 + env_ids = envs.call(["get_env_ind"] * num_envs) + assert env_ids == true_env_ids + + envs.call_at(2, "set_env_ind", {"new_env_ind": 2}) + true_env_ids[2] = 2 + env_ids = envs.call(["get_env_ind"] * num_envs) + assert env_ids == true_env_ids + + envs.pause_at(0) + true_env_ids.pop(0) + env_ids = envs.call(["get_env_ind"] * num_envs) + assert env_ids == true_env_ids + + envs.pause_at(0) + true_env_ids.pop(0) + env_ids = envs.call(["get_env_ind"] * num_envs) + assert env_ids == true_env_ids + + envs.resume_all() + env_ids = envs.call(["get_env_ind"] * num_envs) + assert env_ids == list(range(num_envs)) + + +def test_close_with_paused(): + configs, _ = _load_test_data() + env_fn_args = tuple((c,) for c in configs) + with habitat.VectorEnv( + make_env_fn=make_gym_from_config, + env_fn_args=env_fn_args, + multiprocessing_start_method="forkserver", + ) as envs: + envs.reset() + + envs.pause_at(3) + envs.pause_at(0) + + assert envs._is_closed + + +# TODO Bring back this test for the greedy follower +@pytest.mark.skip +def test_action_space_shortest_path(): + config = get_config("benchmark/nav/pointnav/pointnav_habitat_test.yaml") + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + + env = habitat.Env(config=config, dataset=None) + + # action space shortest path + source_position = env.sim.sample_navigable_point() + angles = list(range(-180, 180, config.habitat.simulator.turn_angle)) + angle = np.radians(np.random.choice(angles)) + source_rotation = [0, np.sin(angle / 2), 0, np.cos(angle / 2)] + source = AgentState(source_position, source_rotation) + + reachable_targets: List[AgentState] = [] + unreachable_targets: List[AgentState] = [] + while len(reachable_targets) < 5: + position = env.sim.sample_navigable_point() + angles = list(range(-180, 180, config.habitat.simulator.turn_angle)) + angle = np.radians(np.random.choice(angles)) + rotation = [0, np.sin(angle / 2), 0, np.cos(angle / 2)] + if env.sim.geodesic_distance(source_position, [position]) != np.inf: + reachable_targets.append(AgentState(position, rotation)) + + while len(unreachable_targets) < 3: + position = env.sim.sample_navigable_point() + # Change height of the point to make it unreachable + position[1] = 100 + angles = list(range(-180, 180, config.habitat.simulator.turn_angle)) + angle = np.radians(np.random.choice(angles)) + rotation = [0, np.sin(angle / 2), 0, np.cos(angle / 2)] + if env.sim.geodesic_distance(source_position, [position]) == np.inf: + unreachable_targets.append(AgentState(position, rotation)) + + targets = reachable_targets + shortest_path1 = env.action_space_shortest_path( # type: ignore[attr-defined] + source, targets + ) + assert shortest_path1 != [] + + targets = unreachable_targets + shortest_path2 = env.action_space_shortest_path( # type: ignore[attr-defined] + source, targets + ) + assert shortest_path2 == [] + env.close() + + +@pytest.mark.parametrize("set_method", ["current", "list", "iter"]) +def test_set_episodes(set_method): + config = get_config("benchmark/nav/pointnav/pointnav_habitat_test.yaml") + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + + with habitat.Env(config=config, dataset=None) as env: + all_episodes = list(env.episodes) + target_episode = all_episodes[10] + + if set_method == "current": + env.current_episode = target_episode + elif set_method == "list": + env.episodes = [target_episode] + elif set_method == "iter": + env.episode_iterator = iter([target_episode] + all_episodes) + else: + raise RuntimeError( + f"Test does not support setting episodes with {set_method}" + ) + + env.reset() + assert env.current_episode is target_episode diff --git a/world-in-world/src/habitat-baselines/test/test_habitat_sim.py b/world-in-world/src/habitat-baselines/test/test_habitat_sim.py new file mode 100644 index 0000000000000000000000000000000000000000..6454ee3874c4668e21c78b5b0d3a7d8518853946 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_habitat_sim.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import json +import os + +import numpy as np +import pytest + +from habitat.config import read_write +from habitat.config.default import get_agent_config, get_config +from habitat.sims import make_sim +from habitat.sims.habitat_simulator.actions import HabitatSimActions + + +def init_sim(): + config = get_config("benchmark/nav/pointnav/pointnav_habitat_test.yaml") + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + return make_sim( + config.habitat.simulator.type, config=config.habitat.simulator + ) + + +def test_sim_trajectory(): + with open("test/data/habitat-sim_trajectory_data.json", "r") as f: + test_trajectory = json.load(f) + with init_sim() as sim: + sim.reset() + sim.set_agent_state( + position=test_trajectory["positions"][0], + rotation=test_trajectory["rotations"][0], + ) + + # remove last stop action as Sim has no stop action anymore + for i, action in enumerate(test_trajectory["actions"][:-1]): + action = HabitatSimActions[action] + if i > 0: # ignore first step as habitat-sim doesn't update + # agent until then + state = sim.get_agent_state() + assert ( + np.allclose( + np.array( + test_trajectory["positions"][i], dtype=np.float32 + ), + state.position, + ) + is True + ), "mismatch in position " "at step {}".format(i) + assert ( + np.allclose( + np.array( + test_trajectory["rotations"][i], dtype=np.float32 + ), + np.array([*state.rotation.imag, state.rotation.real]), + ) + is True + ), "mismatch in rotation " "at step {}".format(i) + + max_search_radius = 2.0 + dist_to_obs = sim.distance_to_closest_obstacle( + state.position, max_search_radius + ) + assert np.isclose( + dist_to_obs, test_trajectory["distances_to_obstacles"][i] + ) + + assert sim.action_space.contains(action) + + sim.step(action) + + +def test_sim_no_sensors(): + config = get_config("benchmark/nav/pointnav/pointnav_habitat_test.yaml") + with read_write(config): + agent_config = get_agent_config(config.habitat.simulator) + agent_config.sim_sensors = {} + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + with make_sim( + config.habitat.simulator.type, config=config.habitat.simulator + ) as sim: + sim.reset() + + +def test_sim_geodesic_distance(): + config = get_config("benchmark/nav/pointnav/pointnav_habitat_test.yaml") + if not os.path.exists(config.habitat.simulator.scene): + pytest.skip("Please download Habitat test data to data folder.") + with make_sim( + config.habitat.simulator.type, config=config.habitat.simulator + ) as sim: + sim.reset() + + with open( + os.path.join( + os.path.dirname(__file__), + "data", + "test-sim-geodesic-distance-test-golden.json", + ), + "r", + ) as f: + test_data = json.load(f) + + for test_case in test_data["single_end"]: + assert np.isclose( + sim.geodesic_distance(test_case["start"], test_case["end"]), + test_case["expected"], + ), "Geodesic distance mechanism has been changed" + + for test_case in test_data["multi_end"]: + assert np.isclose( + sim.geodesic_distance(test_case["start"], test_case["ends"]), + test_case["expected"], + ), "Geodesic distance mechanism has been changed" + + assert np.isclose( + sim.geodesic_distance(test_case["start"], test_case["ends"]), + np.min( + [ + sim.geodesic_distance(test_case["start"], end) + for end in test_case["ends"] + ] + ), + ), "Geodesic distance for multi target setup isn't equal to separate single target calls." diff --git a/world-in-world/src/habitat-baselines/test/test_humanoid.py b/world-in-world/src/habitat-baselines/test/test_humanoid.py new file mode 100644 index 0000000000000000000000000000000000000000..dd667e85540b2f4118100e9d1274bae5171cb4e6 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_humanoid.py @@ -0,0 +1,533 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from os import path as osp + +import gym +import magnum as mn +import numpy as np +import pytest +from omegaconf import DictConfig + +import habitat.articulated_agents.humanoids.kinematic_humanoid as kinematic_humanoid +import habitat_sim +import habitat_sim.agent +from habitat.articulated_agent_controllers import ( + HumanoidRearrangeController, + HumanoidSeqPoseController, +) + +default_sim_settings = { + # settings shared by example.py and benchmark.py + "max_frames": 1000, + "width": 640, + "height": 480, + "default_agent": 0, + "sensor_height": 1.5, + "hfov": 90, + "color_sensor": True, # RGB sensor (default: ON) + "semantic_sensor": False, # semantic sensor (default: OFF) + "depth_sensor": False, # depth sensor (default: OFF) + "seed": 1, + "silent": False, # do not print log info (default: OFF) + # settings exclusive to example.py + "save_png": False, # save the pngs to disk (default: OFF) + "print_semantic_scene": False, + "print_semantic_mask_stats": False, + "compute_shortest_path": False, + "compute_action_shortest_path": False, + "scene": "data/scene_datasets/habitat-test-scenes/skokloster-castle.glb", + "test_scene_data_url": "http://dl.fbaipublicfiles.com/habitat/habitat-test-scenes.zip", + "goal_position": [5.047, 0.199, 11.145], + "enable_physics": False, + "enable_gfx_replay_save": False, + "physics_config_file": "./data/default.physics_config.json", + "num_objects": 10, + "test_object_index": 0, + "frustum_culling": True, +} + + +# build SimulatorConfiguration +def make_cfg(settings): + sim_cfg = habitat_sim.SimulatorConfiguration() + if "scene_dataset_config_file" in settings: + sim_cfg.scene_dataset_config_file = settings[ + "scene_dataset_config_file" + ] + sim_cfg.frustum_culling = settings.get("frustum_culling", False) + if "enable_physics" in settings: + sim_cfg.enable_physics = settings["enable_physics"] + if "physics_config_file" in settings: + sim_cfg.physics_config_file = settings["physics_config_file"] + if not settings["silent"]: + print("sim_cfg.physics_config_file = " + sim_cfg.physics_config_file) + if "scene_light_setup" in settings: + sim_cfg.scene_light_setup = settings["scene_light_setup"] + sim_cfg.gpu_device_id = 0 + if not hasattr(sim_cfg, "scene_id"): + raise RuntimeError( + "Error: Please upgrade habitat-sim. SimulatorConfig API version mismatch" + ) + sim_cfg.scene_id = settings["scene"] + + # define default sensor parameters (see src/esp/Sensor/Sensor.h) + sensor_specs = [] + + def create_camera_spec(**kw_args): + camera_sensor_spec = habitat_sim.CameraSensorSpec() + camera_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR + camera_sensor_spec.resolution = [settings["height"], settings["width"]] + camera_sensor_spec.position = [0.0, settings["sensor_height"], 0.0] + for k in kw_args: + setattr(camera_sensor_spec, k, kw_args[k]) + return camera_sensor_spec + + if settings["color_sensor"]: + color_sensor_spec = create_camera_spec( + uuid="color_sensor", + hfov=settings["hfov"], + sensor_type=habitat_sim.SensorType.COLOR, + sensor_subtype=habitat_sim.SensorSubType.PINHOLE, + ) + sensor_specs.append(color_sensor_spec) + + if settings["depth_sensor"]: + depth_sensor_spec = create_camera_spec( + uuid="depth_sensor", + hfov=settings["hfov"], + sensor_type=habitat_sim.SensorType.DEPTH, + channels=1, + sensor_subtype=habitat_sim.SensorSubType.PINHOLE, + ) + sensor_specs.append(depth_sensor_spec) + + if settings["semantic_sensor"]: + semantic_sensor_spec = create_camera_spec( + uuid="semantic_sensor", + hfov=settings["hfov"], + sensor_type=habitat_sim.SensorType.SEMANTIC, + channels=1, + sensor_subtype=habitat_sim.SensorSubType.PINHOLE, + ) + sensor_specs.append(semantic_sensor_spec) + + # create agent specifications + agent_cfg = habitat_sim.agent.AgentConfiguration() + agent_cfg.sensor_specifications = sensor_specs + agent_cfg.action_space = { + "move_forward": habitat_sim.agent.ActionSpec( + "move_forward", habitat_sim.agent.ActuationSpec(amount=0.25) + ), + "turn_left": habitat_sim.agent.ActionSpec( + "turn_left", habitat_sim.agent.ActuationSpec(amount=10.0) + ), + "turn_right": habitat_sim.agent.ActionSpec( + "turn_right", habitat_sim.agent.ActuationSpec(amount=10.0) + ), + } + + # override action space to no-op to test physics + if sim_cfg.enable_physics: + agent_cfg.action_space = { + "move_forward": habitat_sim.agent.ActionSpec( + "move_forward", habitat_sim.agent.ActuationSpec(amount=0.0) + ) + } + + return habitat_sim.Configuration(sim_cfg, [agent_cfg]) + + +def simulate(sim, dt, get_observations=False): + r"""Runs physics simulation at 60FPS for a given duration (dt) optionally collecting and returning sensor observations.""" + observations = [] + target_time = sim.get_world_time() + dt + while sim.get_world_time() < target_time: + sim.step_physics(0.1 / 60.0) + if get_observations: + observations.append(sim.get_sensor_observations()) + return observations + + +@pytest.mark.parametrize( + "humanoid_name", + ["female_2"], +) +def test_humanoid_controller(humanoid_name): + """Test the humanoid controller""" + + # loading the physical scene + produce_debug_video = False + num_steps = 100 + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + epsilon = 1e-4 + + observations = [] + hab_cfg = make_cfg(cfg_settings) + with habitat_sim.Simulator(hab_cfg) as sim: + obj_template_mgr = sim.get_object_template_manager() + rigid_obj_mgr = sim.get_rigid_object_manager() + + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add a ground plane + cube_handle = obj_template_mgr.get_template_handles("cubeSolid")[0] + cube_template_cpy = obj_template_mgr.get_template_by_handle( + cube_handle + ) + cube_template_cpy.scale = np.array([5.0, 0.2, 5.0]) + obj_template_mgr.register_template(cube_template_cpy) + ground_plane = rigid_obj_mgr.add_object_by_template_handle(cube_handle) + ground_plane.translation = [0.0, -0.2, 0.0] + ground_plane.motion_type = habitat_sim.physics.MotionType.STATIC + + # compute a navmesh on the ground plane + navmesh_settings = habitat_sim.NavMeshSettings() + navmesh_settings.set_defaults() + navmesh_settings.include_static_objects = True + sim.recompute_navmesh(sim.pathfinder, navmesh_settings) + sim.navmesh_visualization = True + + # add the humanoid to the world via the wrapper + humanoid_path = f"data/humanoids/humanoid_data/{humanoid_name}/{humanoid_name}.urdf" + walk_pose_path = f"data/humanoids/humanoid_data/{humanoid_name}/{humanoid_name}_motion_data_smplx.pkl" + + agent_config = DictConfig( + { + "articulated_agent_urdf": humanoid_path, + "motion_data_path": walk_pose_path, + "auto_update_sensor_transform": True, + } + ) + if not osp.exists(humanoid_path): + pytest.skip(f"No humanoid file {humanoid_path}") + kin_humanoid = kinematic_humanoid.KinematicHumanoid(agent_config, sim) + kin_humanoid.reconfigure() + kin_humanoid.update() + assert ( + kin_humanoid.get_robot_sim_id() == 2 + ) # 0 is the stage and 1 is the ground plane + print(kin_humanoid.get_link_and_joint_names()) + observations += simulate(sim, 1.0, produce_debug_video) + + # set base ground position from navmesh + # NOTE: because the navmesh floats above the collision geometry we should see a pop/settle with dynamics and no fixed base + target_base_pos = sim.pathfinder.snap_point( + kin_humanoid.sim_obj.translation + ) + kin_humanoid.base_pos = target_base_pos + assert kin_humanoid.base_pos == target_base_pos + observations += simulate(sim, 1.0, produce_debug_video) + + # Test controller + humanoid_controller = HumanoidRearrangeController(walk_pose_path) + + init_pos = kin_humanoid.base_pos + base_trans = kin_humanoid.base_transformation + target_pos = init_pos + mn.Vector3(1.5, 0, 0) + step_count = 0 + humanoid_controller.reset(base_trans) + while step_count < num_steps: + pose_diff = target_pos - kin_humanoid.base_pos + humanoid_controller.calculate_walk_pose(pose_diff) + new_pose = humanoid_controller.get_pose() + + new_joints = new_pose[:-16] + new_pos_transform_base = new_pose[-16:] + new_pos_transform_offset = new_pose[-32:-16] + + # When the array is all 0, this indicates we are not setting + # the human joint + if np.array(new_pos_transform_offset).sum() != 0: + vecs_base = [ + mn.Vector4(new_pos_transform_base[i * 4 : (i + 1) * 4]) + for i in range(4) + ] + vecs_offset = [ + mn.Vector4(new_pos_transform_offset[i * 4 : (i + 1) * 4]) + for i in range(4) + ] + new_transform_offset = mn.Matrix4(*vecs_offset) + new_transform_base = mn.Matrix4(*vecs_base) + kin_humanoid.set_joint_transform( + new_joints, new_transform_offset, new_transform_base + ) + observations += simulate(sim, 0.01, produce_debug_video) + step_count += 1 + + assert pose_diff.length() < epsilon + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_humanoid_wrapper", + open_vid=True, + ) + + +@pytest.mark.skipif( + not osp.exists("data/humanoids/humanoid_data/female_2/female_2.urdf"), + reason="Test requires female 2 humanoid URDF and assets.", +) +@pytest.mark.skipif( + not habitat_sim.built_with_bullet, + reason="Robot wrapper API requires Bullet physics.", +) +def test_base_rot(): + # set this to output test results as video for easy investigation + produce_debug_video = False + observations = [] + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + # loading the physical scene + hab_cfg = make_cfg(cfg_settings) + + with habitat_sim.Simulator(hab_cfg) as sim: + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add the humanoid to the world via the wrapper + humanoid_path = "data/humanoids/humanoid_data/female_2/female_2.urdf" + walk_pose_path = "data/humanoids/humanoid_data/female_2/female_2_motion_data_smplx.pkl" + + agent_config = DictConfig( + { + "articulated_agent_urdf": humanoid_path, + "motion_data_path": walk_pose_path, + "auto_update_sensor_transform": True, + } + ) + if not osp.exists(humanoid_path): + pytest.skip(f"No humanoid file {humanoid_path}") + kin_humanoid = kinematic_humanoid.KinematicHumanoid(agent_config, sim) + kin_humanoid.reconfigure() + kin_humanoid.update() + + # check that for range (-pi, pi) getter and setter are consistent + num_samples = 100 + for i in range(1, num_samples): + angle = -math.pi + (math.pi * 2 * i) / num_samples + kin_humanoid.base_rot = angle + assert np.allclose(angle, kin_humanoid.base_rot, atol=1e-5) + if produce_debug_video: + observations.append(sim.get_sensor_observations()) + + # check that for range [-2pi, 2pi] increment is accurate + kin_humanoid.base_rot = -math.pi * 2 + inc = (math.pi * 4) / num_samples + rot_check = -math.pi * 2 + for _ in range(0, num_samples): + kin_humanoid.base_rot = kin_humanoid.base_rot + inc + rot_check += inc + # NOTE: here we check that the angle is accurate (allow an offset of one full rotation to cover redundant options) + accurate_angle = False + for offset in [0, math.pi * 2, math.pi * -2]: + if np.allclose( + rot_check, kin_humanoid.base_rot + offset, atol=1e-5 + ): + accurate_angle = True + break + assert ( + accurate_angle + ), f"should be {rot_check}, but was {kin_humanoid.base_rot}." + if produce_debug_video: + observations.append(sim.get_sensor_observations()) + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_base_rot", + open_vid=True, + ) + + +@pytest.mark.skipif( + not osp.exists("data/humanoids/humanoid_data/female_2/female_2.urdf"), + reason="Test requires a human armature.", +) +@pytest.mark.skipif( + not osp.exists( + "data/humanoids/humanoid_data/female_2/female_2_motion_data_smplx.pkl" + ), + reason="Test requires motion files.", +) +def test_gym_humanoid(): + """Test Gym with the humanoid""" + config_file = "benchmark/rearrange/skills/pick.yaml" + overrides = [ + "~habitat.task.actions.arm_action", + "~habitat.task.actions.base_velocity", + "++habitat.task.actions={humanoidjoint_action:{type:HumanoidJointAction}}", + "++habitat.task.actions.humanoidjoint_action.num_joints=17", + "habitat.simulator.agents.main_agent.articulated_agent_urdf=data/humanoids/humanoid_data/female_2/female_2.urdf", + "habitat.simulator.agents.main_agent.articulated_agent_type=KinematicHumanoid", + "habitat.simulator.agents.main_agent.motion_data_path=data/humanoids/humanoid_data/female_2/female_2_motion_data_smplx.pkl", + "habitat.simulator.ac_freq_ratio=1", + "habitat.task.measurements.force_terminate.max_accum_force=-1.0", + "habitat.task.measurements.force_terminate.max_instant_force=-1.0", + "habitat.simulator.kinematic_mode=True", + "habitat.simulator.ac_freq_ratio=1", + ] + + hab_gym = gym.make( + "Habitat-v0", + cfg_file_path=config_file, + override_options=overrides, + use_render_mode=True, + ) + hab_gym.reset() + hab_gym.step(hab_gym.action_space.sample()) + hab_gym.close() + + hab_gym = gym.make( + "HabitatRender-v0", + cfg_file_path=config_file, + ) + hab_gym.reset() + hab_gym.step(hab_gym.action_space.sample()) + hab_gym.render("rgb_array") + hab_gym.close() + + +@pytest.mark.parametrize( + "humanoid_name", + ["female_2"], +) +def test_humanoid_seqpose_controller(humanoid_name): + """Test the humanoid controller""" + + # loading the physical scene + produce_debug_video = False + num_steps = 1000 + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + observations = [] + hab_cfg = make_cfg(cfg_settings) + with habitat_sim.Simulator(hab_cfg) as sim: + obj_template_mgr = sim.get_object_template_manager() + rigid_obj_mgr = sim.get_rigid_object_manager() + + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, 0.0, 2.0] + + # add a ground plane + cube_handle = obj_template_mgr.get_template_handles("cubeSolid")[0] + cube_template_cpy = obj_template_mgr.get_template_by_handle( + cube_handle + ) + cube_template_cpy.scale = np.array([5.0, 0.2, 5.0]) + obj_template_mgr.register_template(cube_template_cpy) + ground_plane = rigid_obj_mgr.add_object_by_template_handle(cube_handle) + ground_plane.translation = [0.0, -0.2, 0.0] + ground_plane.motion_type = habitat_sim.physics.MotionType.STATIC + + # compute a navmesh on the ground plane + navmesh_settings = habitat_sim.NavMeshSettings() + navmesh_settings.set_defaults() + navmesh_settings.include_static_objects = True + sim.recompute_navmesh(sim.pathfinder, navmesh_settings) + sim.navmesh_visualization = True + + # add the humanoid to the world via the wrapper + humanoid_path = f"data/humanoids/humanoid_data/{humanoid_name}/{humanoid_name}.urdf" + walk_pose_path = f"data/humanoids/humanoid_data/{humanoid_name}/{humanoid_name}_motion_data_smplx.pkl" + + agent_config = DictConfig( + { + "articulated_agent_urdf": humanoid_path, + "motion_data_path": walk_pose_path, + "auto_update_sensor_transform": True, + } + ) + if not osp.exists(humanoid_path): + pytest.skip(f"No humanoid file {humanoid_path}") + kin_humanoid = kinematic_humanoid.KinematicHumanoid(agent_config, sim) + kin_humanoid.reconfigure() + kin_humanoid.update() + assert ( + kin_humanoid.get_robot_sim_id() == 2 + ) # 0 is the stage and 1 is the ground plane + + # set base ground position from navmesh + # NOTE: because the navmesh floats above the collision geometry we should see a pop/settle with dynamics and no fixed base + target_base_pos = sim.pathfinder.snap_point( + kin_humanoid.sim_obj.translation + ) + kin_humanoid.base_pos = target_base_pos + assert kin_humanoid.base_pos == target_base_pos + observations += simulate(sim, 0.01, produce_debug_video) + + # Test controller + motion_path = ( + "data/humanoids/humanoid_data/walk_motion/CMU_10_04_stageii.pkl" + ) + + if not osp.exists(motion_path): + pytest.skip( + f"No motion file {motion_path}. You can create this file by using humanoid_utils.py" + ) + humanoid_controller = HumanoidSeqPoseController(motion_path) + + base_trans = kin_humanoid.base_transformation + step_count = 0 + humanoid_controller.reset(base_trans) + while step_count < num_steps: + humanoid_controller.calculate_pose() + humanoid_controller.next_pose(cycle=True) + new_pose = humanoid_controller.get_pose() + + new_joints = new_pose[:-16] + new_pos_transform_base = new_pose[-16:] + new_pos_transform_offset = new_pose[-32:-16] + + # When the array is all 0, this indicates we are not setting + # the human joint + if np.array(new_pos_transform_offset).sum() != 0: + vecs_base = [ + mn.Vector4(new_pos_transform_base[i * 4 : (i + 1) * 4]) + for i in range(4) + ] + vecs_offset = [ + mn.Vector4(new_pos_transform_offset[i * 4 : (i + 1) * 4]) + for i in range(4) + ] + new_transform_offset = mn.Matrix4(*vecs_offset) + new_transform_base = mn.Matrix4(*vecs_base) + kin_humanoid.set_joint_transform( + new_joints, new_transform_offset, new_transform_base + ) + observations += simulate(sim, 0.0001, produce_debug_video) + + step_count += 1 + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_humanoid_wrapper", + open_vid=True, + ) diff --git a/world-in-world/src/habitat-baselines/test/test_pointnav_dataset.py b/world-in-world/src/habitat-baselines/test/test_pointnav_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..bc3918462619099a3649fe1c2f9303fd741f1f04 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_pointnav_dataset.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +import random +import time + +import numpy as np +import pytest + +import habitat +from habitat.config.default import get_config +from habitat.core.embodied_task import Episode +from habitat.core.logging import logger +from habitat.datasets import make_dataset +from habitat.datasets.pointnav import pointnav_generator as pointnav_generator +from habitat.datasets.pointnav.pointnav_dataset import ( + DEFAULT_SCENE_PATH_PREFIX, + PointNavDatasetV1, +) +from habitat.utils.geometry_utils import ( + angle_between_quaternions, + quaternion_from_coeff, +) + +CFG_TEST = "test/config/habitat/habitat_all_sensors_test.yaml" +CFG_MULTI_TEST = "benchmark/nav/pointnav/pointnav_gibson.yaml" +PARTIAL_LOAD_SCENES = 3 +NUM_EPISODES = 10 + + +def check_json_serialization(dataset: habitat.Dataset): + start_time = time.time() + json_str = str(dataset.to_json()) + logger.info( + "JSON conversion finished. {} sec".format((time.time() - start_time)) + ) + decoded_dataset = dataset.__class__() + decoded_dataset.from_json(json_str) + assert len(decoded_dataset.episodes) > 0 + episode = decoded_dataset.episodes[0] + assert isinstance(episode, Episode) + assert ( + decoded_dataset.to_json() == json_str + ), "JSON dataset encoding/decoding isn't consistent" + + +def test_single_pointnav_dataset(): + dataset_config = get_config( + "benchmark/nav/pointnav/pointnav_habitat_test.yaml" + ).habitat.dataset + if not PointNavDatasetV1.check_config_paths_exist(dataset_config): + pytest.skip("Test skipped as dataset files are missing.") + scenes = PointNavDatasetV1.get_scenes_to_load(config=dataset_config) + assert ( + len(scenes) > 0 + ), "Expected dataset contains separate episode file per scene." + dataset = PointNavDatasetV1(config=dataset_config) + assert len(dataset.episodes) > 0, "The dataset shouldn't be empty." + assert ( + len(dataset.scene_ids) == 2 + ), "The test dataset scenes number is wrong." + check_json_serialization(dataset) + + +def test_multiple_files_scene_path(): + dataset_config = get_config(CFG_MULTI_TEST).habitat.dataset + if not PointNavDatasetV1.check_config_paths_exist(dataset_config): + pytest.skip("Test skipped as dataset files are missing.") + scenes = PointNavDatasetV1.get_scenes_to_load(config=dataset_config) + assert ( + len(scenes) > 0 + ), "Expected dataset contains separate episode file per scene." + with habitat.config.read_write(dataset_config): + dataset_config.content_scenes = scenes[:PARTIAL_LOAD_SCENES] + dataset_config.scenes_dir = os.path.join( + os.getcwd(), DEFAULT_SCENE_PATH_PREFIX + ) + partial_dataset = make_dataset( + id_dataset=dataset_config.type, config=dataset_config + ) + assert ( + len(partial_dataset.scene_ids) == PARTIAL_LOAD_SCENES + ), "Number of loaded scenes doesn't correspond." + print(partial_dataset.episodes[0].scene_id) + assert os.path.exists( + partial_dataset.episodes[0].scene_id + ), "Scene file {} doesn't exist using absolute path".format( + partial_dataset.episodes[0].scene_id + ) + + +def test_multiple_files_pointnav_dataset(): + dataset_config = get_config(CFG_MULTI_TEST).habitat.dataset + if not PointNavDatasetV1.check_config_paths_exist(dataset_config): + pytest.skip("Test skipped as dataset files are missing.") + scenes = PointNavDatasetV1.get_scenes_to_load(config=dataset_config) + assert ( + len(scenes) > 0 + ), "Expected dataset contains separate episode file per scene." + with habitat.config.read_write(dataset_config): + dataset_config.content_scenes = scenes[:PARTIAL_LOAD_SCENES] + partial_dataset = make_dataset( + id_dataset=dataset_config.type, config=dataset_config + ) + assert ( + len(partial_dataset.scene_ids) == PARTIAL_LOAD_SCENES + ), "Number of loaded scenes doesn't correspond." + check_json_serialization(partial_dataset) + + +@pytest.mark.parametrize("split", ["train", "val"]) +def test_dataset_splitting(split): + dataset_config = get_config(CFG_MULTI_TEST).habitat.dataset + with habitat.config.read_write(dataset_config): + dataset_config.split = split + + if not PointNavDatasetV1.check_config_paths_exist(dataset_config): + pytest.skip("Test skipped as dataset files are missing.") + + scenes = PointNavDatasetV1.get_scenes_to_load(config=dataset_config) + assert ( + len(scenes) > 0 + ), "Expected dataset contains separate episode file per scene." + + dataset_config.content_scenes = scenes[:PARTIAL_LOAD_SCENES] + full_dataset = make_dataset( + id_dataset=dataset_config.type, config=dataset_config + ) + full_episodes = { + (ep.scene_id, ep.episode_id) for ep in full_dataset.episodes + } + + dataset_config.content_scenes = scenes[: PARTIAL_LOAD_SCENES // 2] + split1_dataset = make_dataset( + id_dataset=dataset_config.type, config=dataset_config + ) + split1_episodes = { + (ep.scene_id, ep.episode_id) for ep in split1_dataset.episodes + } + + dataset_config.content_scenes = scenes[ + PARTIAL_LOAD_SCENES // 2 : PARTIAL_LOAD_SCENES + ] + split2_dataset = make_dataset( + id_dataset=dataset_config.type, config=dataset_config + ) + split2_episodes = { + (ep.scene_id, ep.episode_id) for ep in split2_dataset.episodes + } + + assert full_episodes == split1_episodes.union( + split2_episodes + ), "Split dataset is not equal to full dataset" + assert ( + len(split1_episodes.intersection(split2_episodes)) == 0 + ), "Intersection of split datasets is not the empty set" + + +def check_shortest_path(env, episode): + def check_state(agent_state, position, rotation): + assert ( + angle_between_quaternions( + agent_state.rotation, quaternion_from_coeff(rotation) + ) + < 1e-5 + ), "Agent's rotation diverges from the shortest path." + + assert np.allclose( + agent_state.position, position + ), "Agent's position position diverges from the shortest path's one." + + assert len(episode.goals) == 1, "Episode has no goals or more than one." + assert ( + len(episode.shortest_paths) == 1 + ), "Episode has no shortest paths or more than one." + + env.episode_iterator = iter([episode]) + env.reset() + start_state = env.sim.get_agent_state() + check_state(start_state, episode.start_position, episode.start_rotation) + + for point in episode.shortest_paths[0]: + cur_state = env.sim.get_agent_state() + check_state(cur_state, point.position, point.rotation) + env.step(point.action) + + +def test_pointnav_episode_generator(): + config = get_config(CFG_TEST) + with habitat.config.read_write(config): + config.habitat.dataset.split = "val" + config.habitat.environment.max_episode_steps = 500 + if not PointNavDatasetV1.check_config_paths_exist(config.habitat.dataset): + pytest.skip("Test skipped as dataset files are missing.") + with habitat.Env(config) as env: + env.seed(config.habitat.seed) + random.seed(config.habitat.seed) + generator = pointnav_generator.generate_pointnav_episode( + sim=env.sim, + shortest_path_success_distance=config.habitat.task.measurements.success.success_distance, + shortest_path_max_steps=config.habitat.environment.max_episode_steps, + ) + episodes = [] + for _ in range(NUM_EPISODES): + episode = next(generator) + episodes.append(episode) + + for episode in pointnav_generator.generate_pointnav_episode( + sim=env.sim, + num_episodes=NUM_EPISODES, + shortest_path_success_distance=config.habitat.task.measurements.success.success_distance, + shortest_path_max_steps=config.habitat.environment.max_episode_steps, + geodesic_to_euclid_min_ratio=0, + ): + episodes.append(episode) + + assert len(episodes) == 2 * NUM_EPISODES + env.episode_iterator = iter(episodes) + + for episode in episodes: + check_shortest_path(env, episode) + + dataset: habitat.Dataset = habitat.Dataset() + dataset.episodes = episodes + assert ( + dataset.to_json() + ), "Generated episodes aren't json serializable." diff --git a/world-in-world/src/habitat-baselines/test/test_rearrange_task.py b/world-in-world/src/habitat-baselines/test/test_rearrange_task.py new file mode 100644 index 0000000000000000000000000000000000000000..ba741f04e07cabaf2f863501fe1bfe790bf53767 --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_rearrange_task.py @@ -0,0 +1,548 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import json +import os.path as osp +import random +import time +from glob import glob + +import magnum as mn +import numpy as np +import pytest +from omegaconf import DictConfig, OmegaConf + +import habitat +import habitat.datasets.rearrange.run_episode_generator as rr_gen +import habitat.datasets.rearrange.samplers.receptacle as hab_receptacle +import habitat.sims.habitat_simulator.sim_utilities as sutils +import habitat.tasks.rearrange.rearrange_sim +import habitat.tasks.rearrange.rearrange_task +import habitat.utils.env_utils +import habitat_sim +from habitat.config.default import get_config +from habitat.core.embodied_task import Episode +from habitat.core.environments import get_env_class +from habitat.core.logging import logger +from habitat.datasets.rearrange.rearrange_dataset import RearrangeDatasetV0 +from habitat.utils.geometry_utils import is_point_in_triangle + +CFG_TEST = "benchmark/rearrange/skills/pick.yaml" +GEN_TEST_CFG = ( + "habitat-lab/habitat/datasets/rearrange/configs/test_config.yaml" +) +EPISODES_LIMIT = 6 +MAX_PER_TASK_TEST_STEPS = 500 + + +def check_binary_serialization(dataset: RearrangeDatasetV0): + start_time = time.time() + bin_dict = dataset.to_binary() + logger.info( + "Binary conversion finished. {} sec".format((time.time() - start_time)) + ) + decoded_dataset = RearrangeDatasetV0() + decoded_dataset.from_binary(bin_dict) + decoded_dataset.config = dataset.config + assert len(decoded_dataset.episodes) == len(dataset.episodes) + episode = decoded_dataset.episodes[0] + assert isinstance(episode, Episode) + dataset_decoded_bin = decoded_dataset.to_binary() + # check that the expected keys are present in both encoded Dicts + expected_keys = ["all_transforms", "idx_to_name", "all_eps"] + for key in expected_keys: + assert key in bin_dict + assert key in dataset_decoded_bin + + # use JSON serialization to test integrety of dataset binary serialization -> deserialization + assert json.loads(decoded_dataset.to_json()) == json.loads( + dataset.to_json() + ), "JSON dataset encoding of binary decoding isn't consistent." + + +def check_json_serialization(dataset: RearrangeDatasetV0): + start_time = time.time() + json_str = dataset.to_json() + logger.info( + "JSON conversion finished. {} sec".format((time.time() - start_time)) + ) + decoded_dataset = RearrangeDatasetV0() + decoded_dataset.from_json(json_str) + decoded_dataset.config = dataset.config + assert len(decoded_dataset.episodes) == len(dataset.episodes) + episode = decoded_dataset.episodes[0] + assert isinstance(episode, Episode) + + # The strings won't match exactly as dictionaries don't have an order for the keys + # Thus we need to parse the json strings and compare the serialized forms + assert json.loads(decoded_dataset.to_json()) == json.loads( + json_str + ), "JSON dataset encoding/decoding isn't consistent" + + +def test_rearrange_dataset(): + dataset_config = get_config(CFG_TEST).habitat.dataset + if not RearrangeDatasetV0.check_config_paths_exist(dataset_config): + pytest.skip( + "Please download ReplicaCAD RearrangeDataset Dataset to data folder." + ) + + dataset = habitat.make_dataset( + id_dataset=dataset_config.type, config=dataset_config + ) + assert dataset + dataset.episodes = dataset.episodes[0:EPISODES_LIMIT] + check_json_serialization(dataset) + check_binary_serialization(dataset) + + +def _get_test_pddl(): + """ + Helper to get a test PDDL instance. + """ + + config = get_config( + "habitat-lab/habitat/config/benchmark/rearrange/multi_task/rearrange_easy.yaml", + [ + # Concurrent rendering can cause problems on CI. + "habitat.simulator.concur_render=False", + "habitat.dataset.split=val", + ], + ) + env_class = get_env_class(config.habitat.env_task) + env = habitat.utils.env_utils.make_env_fn( + env_class=env_class, config=config + ) + env.reset() + return env.env.env._env.task.pddl_problem # type: ignore + + +def test_pddl_actions(): + """ + Checks we can execute all PDDL actions. + """ + + pddl = _get_test_pddl() + sim_info = pddl.sim_info + + poss_actions = pddl.get_possible_actions() + for action in poss_actions: + action.apply_if_true(sim_info) + pddl._sim_info.sim.close() + + +def test_pddl_action_postconds(): + """ + Tests the PDDL system action post conditions have the expected outcome in + the simulator. + """ + + pddl = _get_test_pddl() + sim_info = pddl.sim_info + + # Check that the predicates are registering that the robot is not holding + # anything at the start. + true_preds = pddl.get_true_predicates() + assert any(x.name == "not_holding" for x in true_preds) + + poss_actions = pddl.get_possible_actions() + ac_strs = [x.compact_str for x in poss_actions] + + # Make sure we can't do an action if the precondition is not satisfied. + place_ac = poss_actions[ + ac_strs.index("place(goal0|0,TARGET_goal0|0,robot_0)") + ] + assert not place_ac.apply_if_true(sim_info) + + # Make sure we can do an action that does have satisifed preconditions. + nav_ac = poss_actions[ac_strs.index("nav(goal0|0,robot_0)")] + assert nav_ac.apply_if_true(sim_info) + + # Now test preconditions hold for a longer chain of actions + pick_ac = poss_actions[ac_strs.index("pick(goal0|0,robot_0)")] + nav_to_goal_ac = poss_actions[ac_strs.index("nav(TARGET_goal0|0,robot_0)")] + assert pick_ac.apply_if_true(sim_info) + assert nav_to_goal_ac.apply_if_true(sim_info) + assert place_ac.apply_if_true(sim_info) + + # Check the object registers at the goal now. + true_preds = pddl.get_true_predicates() + assert any( + x.compact_str == "object_at(goal0|0,TARGET_goal0|0)" + for x in true_preds + ) + sim_info.sim.close() + + +TEST_CFG_PATHS = list( + glob( + "habitat-lab/habitat/config/benchmark/rearrange/**/*.yaml", + recursive=True, + ), +) +NO_TEST_CONFIGS = [ + "habitat-lab/habitat/config/benchmark/rearrange/hab3_bench/single_agent_bench.yaml", + "habitat-lab/habitat/config/benchmark/rearrange/hab3_bench/multi_agent_bench.yaml", + "habitat-lab/habitat/config/benchmark/rearrange/hab3_bench/spot_spot_oracle.yaml", + "habitat-lab/habitat/config/benchmark/rearrange/hab3_bench/spot_oracle.yaml", + "habitat-lab/habitat/config/benchmark/rearrange/hab3_bench/humanoid_oracle.yaml", + "habitat-lab/habitat/config/benchmark/rearrange/hab3_bench/spot_humanoid_oracle.yaml", +] +for config_file_name in NO_TEST_CONFIGS: + TEST_CFG_PATHS.remove(config_file_name) + + +@pytest.mark.parametrize("test_cfg_path", TEST_CFG_PATHS) +def test_rearrange_tasks(test_cfg_path): + """ + Iterates through all the Habitat Rearrangement tasks. + """ + + config = get_config( + test_cfg_path, + [ + # Concurrent rendering can cause problems on CI. + "habitat.simulator.concur_render=False", + "habitat.dataset.split=val", + ], + ) + + for agent_config in config.habitat.simulator.agents.values(): + if ( + agent_config.articulated_agent_type == "KinematicHumanoid" + and not osp.exists(agent_config.motion_data_path) + ): + pytest.skip( + "This test should only be run if we have the motion data files." + ) + + if ( + config.habitat.dataset.data_path + == "data/ep_datasets/bench_scene.json.gz" + ): + pytest.skip( + "This config is only useful for examples and does not have the generated dataset" + ) + env_class = get_env_class(config.habitat.env_task) + + env = habitat.utils.env_utils.make_env_fn( + env_class=env_class, config=config + ) + + for _ in range(2): + env.reset() + for _ in range(MAX_PER_TASK_TEST_STEPS): + action = env.action_space.sample() + _, _, done, _ = env.step( # type:ignore[assignment] + action=action + ) + if done: + break + + env.close() + + +# NOTE: set 'debug_visualization' = True to produce videos showing receptacles and final simulation state +@pytest.mark.parametrize("debug_visualization", [False]) +@pytest.mark.parametrize("num_episodes", [2]) +@pytest.mark.parametrize("config", [GEN_TEST_CFG]) +def test_rearrange_episode_generator( + debug_visualization, num_episodes, config +): + cfg = rr_gen.get_config_defaults() + override_config = OmegaConf.load(config) + cfg = OmegaConf.merge(cfg, override_config) + assert isinstance(cfg, DictConfig) + dataset = RearrangeDatasetV0() + with rr_gen.RearrangeEpisodeGenerator( + cfg=cfg, debug_visualization=debug_visualization + ) as ep_gen: + start_time = time.time() + dataset.episodes += ep_gen.generate_episodes(num_episodes) + + # test serialization of freshly generated dataset + check_json_serialization(dataset) + check_binary_serialization(dataset) + + logger.info( + f"successful_ep = {len(dataset.episodes)} generated in {time.time()-start_time} seconds." + ) + + +@pytest.mark.skipif( + not osp.exists("data/test_assets/"), + reason="This test requires habitat-sim test assets.", +) +def test_receptacle_parsing(): + # 1. Load the parameterized scene + sim_settings = habitat_sim.utils.settings.default_sim_settings.copy() + sim_settings[ + "scene" + ] = "data/test_assets/scenes/simple_room.stage_config.json" + sim_settings["sensor_height"] = 0 + sim_settings["enable_physics"] = True + cfg = habitat_sim.utils.settings.make_cfg(sim_settings) + with habitat_sim.Simulator(cfg) as sim: + # load test assets + sim.metadata_mediator.object_template_manager.load_configs( + "data/test_assets/objects/chair.object_config.json" + ) + # TODO: add an AO w/ receptacles also + + # test quick receptacle listing: + list_receptacles = hab_receptacle.get_all_scenedataset_receptacles(sim) + print(f"list_receptacles = {list_receptacles}") + # receptacles from stage configs: + assert ( + "receptacle_aabb_simpleroom_test" + in list_receptacles["stage"][ + "data/test_assets/scenes/simple_room.stage_config.json" + ] + ) + assert ( + "receptacle_mesh_simpleroom_test" + in list_receptacles["stage"][ + "data/test_assets/scenes/simple_room.stage_config.json" + ] + ) + # receptacles from rigid object configs: + assert ( + "receptacle_aabb_chair_test" + in list_receptacles["rigid"][ + "data/test_assets/objects/chair.object_config.json" + ] + ) + assert ( + "receptacle_mesh_chair_test" + in list_receptacles["rigid"][ + "data/test_assets/objects/chair.object_config.json" + ] + ) + # TODO: receptacles from articulated object configs: + # assert "" in list_receptacles["articulated"] + + # add the chair to the scene + chair_template_handle = ( + sim.metadata_mediator.object_template_manager.get_template_handles( + "chair" + )[0] + ) + chair_obj = ( + sim.get_rigid_object_manager().add_object_by_template_handle( + chair_template_handle + ) + ) + + def randomize_obj_state(): + chair_obj.translation = np.random.random(3) + chair_obj.rotation = habitat_sim.utils.common.random_quaternion() + # TODO: also randomize AO state here + + # parse the metadata into Receptacle objects + test_receptacles = hab_receptacle.find_receptacles(sim) + + # test receptacle filtering in find + random_receptacle = random.choice(test_receptacles) + exclude_unique_name = random_receptacle.unique_name + test_filtered_receptacles = hab_receptacle.find_receptacles( + sim, exclude_filter_strings=[exclude_unique_name] + ) + assert len(test_filtered_receptacles) == len(test_receptacles) - 1 + assert ( + len( + [ + rec + for rec in test_filtered_receptacles + if rec.unique_name == random_receptacle.unique_name + ] + ) + == 0 + ) + + # test the Receptacle instances + num_test_samples = 10 + for receptacle in test_receptacles: + # check for contents and correct type parsing + if receptacle.name == "receptacle_aabb_chair_test": + assert type(receptacle) is hab_receptacle.AABBReceptacle + elif receptacle.name == "receptacle_mesh_chair_test.0000": + assert ( + type(receptacle) is hab_receptacle.TriangleMeshReceptacle + ) + elif receptacle.name == "receptacle_aabb_simpleroom_test": + assert type(receptacle) is hab_receptacle.AABBReceptacle + elif receptacle.name == "receptacle_mesh_simpleroom_test.0000": + assert ( + type(receptacle) is hab_receptacle.TriangleMeshReceptacle + ) + else: + # TODO: add AO receptacles + raise AssertionError( + f"Unknown Receptacle '{receptacle.name}' detected. Update unit test golden values if this is expected." + ) + + for _six in range(num_test_samples): + randomize_obj_state() + # check that parenting and global transforms are as expected: + parent_object = None + expected_global_transform = mn.Matrix4.identity_init() + global_transform = receptacle.get_global_transform(sim) + if receptacle.parent_object_handle is not None: + parent_object = None + if receptacle.parent_link is not None: + # articulated object + assert receptacle.is_parent_object_articulated + parent_object = sim.get_articulated_object_manager().get_object_by_handle( + receptacle.parent_object_handle + ) + expected_global_transform = ( + parent_object.get_link_scene_node( + receptacle.parent_link + ).absolute_transformation() + ) + else: + # rigid object + assert not receptacle.is_parent_object_articulated + parent_object = sim.get_rigid_object_manager().get_object_by_handle( + receptacle.parent_object_handle + ) + # NOTE: we use absolute transformation from the 2nd visual node (scaling node) and root of all render assets to correctly account for any COM shifting, re-orienting, or scaling which has been applied. + expected_global_transform = ( + parent_object.visual_scene_nodes[ + 1 + ].absolute_transformation() + ) + assert parent_object is not None + assert np.allclose( + global_transform, expected_global_transform, atol=1e-06 + ) + else: + # this is a stage Receptacle (global transform) + if type(receptacle) is not hab_receptacle.AABBReceptacle: + assert np.allclose( + global_transform, + expected_global_transform, + atol=1e-06, + ) + else: + # NOTE: global AABB Receptacles have special handling here which is not explicitly tested. See AABBReceptacle.get_global_transform() + expected_global_transform = global_transform + + for _six2 in range(num_test_samples): + sample_point = receptacle.sample_uniform_global( + sim, sample_region_scale=1.0 + ) + expected_local_sample_point = ( + expected_global_transform.inverted().transform_point( + sample_point + ) + ) + if type(receptacle) is hab_receptacle.AABBReceptacle: + # check that the world->local sample point is contained in the local AABB + assert receptacle.bounds.contains( + expected_local_sample_point + ) + elif ( + type(receptacle) + is hab_receptacle.TriangleMeshReceptacle + ): + # check that the local point is within a mesh triangle + in_mesh = False + for f_ix in range( + int(len(receptacle.mesh_data.indices) / 3) + ): + verts = receptacle.get_face_verts(f_ix) + if is_point_in_triangle( + expected_local_sample_point, + verts[0], + verts[1], + verts[2], + ): + in_mesh = True + break + assert ( + in_mesh + ), "The point must belong to a triangle of the local mesh to be valid." + + +@pytest.mark.skipif( + not osp.exists("data/replica_cad/replicaCAD.scene_dataset_config.json"), + reason="This test requires replica cad SceneDataset.", +) +@pytest.mark.skipif( + not habitat_sim.bindings.built_with_bullet, + reason="Bullet physics used for validation.", +) +def test_any_object_receptacle(): + sim_settings = habitat_sim.utils.settings.default_sim_settings.copy() + sim_settings["scene"] = "apt_0" + sim_settings[ + "scene_dataset_config_file" + ] = "data/replica_cad/replicaCAD.scene_dataset_config.json" + cfg = habitat_sim.utils.settings.make_cfg(sim_settings) + with habitat_sim.Simulator(cfg) as sim: + # get an object which does not have a Receptacle defined + stool_object = sutils.get_obj_from_handle( + sim, "frl_apartment_stool_02_:0000" + ) + # get an ArticulatedObject and an ArticulatedLink to try + counter_ao = sutils.get_obj_from_handle(sim, "kitchen_counter_:0000") + drawer_link_id = 6 + drawer_obj_id = 125 + + stool_receptacle = hab_receptacle.AnyObjectReceptacle( + "stool_rec", stool_object.handle + ) + counter_receptacle = hab_receptacle.AnyObjectReceptacle( + "counter_rec", counter_ao.handle + ) + drawer_receptacle = hab_receptacle.AnyObjectReceptacle( + "drawer_rec", counter_ao.handle, parent_link=drawer_link_id + ) + + down = mn.Vector3(0, -1, 0) + + def validate_rec_with_raycast_samples(rec, parent_obj_id): + samples = [rec.sample_uniform_global(sim, 1.0) for _ in range(100)] + # NOTE: we bump the ray origin up to account for collision object inflation around the bounding volume. + sample_raycast_results = [ + sim.cast_ray( + habitat_sim.geo.Ray(sample + mn.Vector3(0, 0.2, 0), down) + ) + for sample in samples + ] + samples_over_obj = len( + [ + True + for raycast_result in sample_raycast_results + if ( + raycast_result.has_hits() + and parent_obj_id + in [hit.object_id for hit in raycast_result.hits] + ) + ] + ) + assert ( + samples_over_obj > 75 + ), "75 percent of samples should be above the object in question for this scene with high statistical likelihood." + + for rec, parent_obj_id in [ + (stool_receptacle, stool_object.object_id), + (counter_receptacle, counter_ao.object_id), + (drawer_receptacle, drawer_obj_id), + ]: + validate_rec_with_raycast_samples(rec, parent_obj_id) + # test that samples in a scaled Receptacle region align with the global bounding box center + center_sample = rec.sample_uniform_global(sim, 0.01) + global_keypoints = sutils.get_global_keypoints_from_object_id( + sim, parent_obj_id + ) + sample_to_center = mn.Vector3(global_keypoints[0] - center_sample) + assert mn.math.dot(sample_to_center.normalized(), down) >= 0.99 + # check that the global keypoints all fit inside the rec computed bounding box + rec_global_bb = rec._get_global_bb(sim).padded(mn.Vector3(0.001)) + for keypoint in global_keypoints: + assert rec_global_bb.contains(keypoint) diff --git a/world-in-world/src/habitat-baselines/test/test_robot_wrapper.py b/world-in-world/src/habitat-baselines/test/test_robot_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..ec76080d6b25b7c811b26dcfa2bbe8b09fbfa9ec --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_robot_wrapper.py @@ -0,0 +1,939 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from os import path as osp + +import numpy as np +import pytest +from omegaconf import DictConfig + +import habitat.articulated_agents.robots.fetch_robot as fetch_robot +import habitat.articulated_agents.robots.franka_robot as franka_robot +import habitat.articulated_agents.robots.spot_robot as spot_robot +import habitat.articulated_agents.robots.stretch_robot as stretch_robot +import habitat_sim +import habitat_sim.agent +from habitat.tasks.rearrange.utils import set_agent_base_via_obj_trans + +default_sim_settings = { + # settings shared by example.py and benchmark.py + "max_frames": 1000, + "width": 640, + "height": 480, + "default_agent": 0, + "sensor_height": 1.5, + "hfov": 90, + "color_sensor": True, # RGB sensor (default: ON) + "semantic_sensor": False, # semantic sensor (default: OFF) + "depth_sensor": False, # depth sensor (default: OFF) + "ortho_rgba_sensor": False, # Orthographic RGB sensor (default: OFF) + "ortho_depth_sensor": False, # Orthographic depth sensor (default: OFF) + "ortho_semantic_sensor": False, # Orthographic semantic sensor (default: OFF) + "fisheye_rgba_sensor": False, + "fisheye_depth_sensor": False, + "fisheye_semantic_sensor": False, + "equirect_rgba_sensor": False, + "equirect_depth_sensor": False, + "equirect_semantic_sensor": False, + "seed": 1, + "silent": False, # do not print log info (default: OFF) + # settings exclusive to example.py + "save_png": False, # save the pngs to disk (default: OFF) + "print_semantic_scene": False, + "print_semantic_mask_stats": False, + "compute_shortest_path": False, + "compute_action_shortest_path": False, + "scene": "data/scene_datasets/habitat-test-scenes/skokloster-castle.glb", + "test_scene_data_url": "http://dl.fbaipublicfiles.com/habitat/habitat-test-scenes.zip", + "goal_position": [5.047, 0.199, 11.145], + "enable_physics": False, + "enable_gfx_replay_save": False, + "physics_config_file": "./data/default.physics_config.json", + "num_objects": 10, + "test_object_index": 0, + "frustum_culling": True, +} + + +# build SimulatorConfiguration +def make_cfg(settings): + sim_cfg = habitat_sim.SimulatorConfiguration() + if "scene_dataset_config_file" in settings: + sim_cfg.scene_dataset_config_file = settings[ + "scene_dataset_config_file" + ] + sim_cfg.frustum_culling = settings.get("frustum_culling", False) + if "enable_physics" in settings: + sim_cfg.enable_physics = settings["enable_physics"] + if "physics_config_file" in settings: + sim_cfg.physics_config_file = settings["physics_config_file"] + if not settings["silent"]: + print("sim_cfg.physics_config_file = " + sim_cfg.physics_config_file) + if "scene_light_setup" in settings: + sim_cfg.scene_light_setup = settings["scene_light_setup"] + sim_cfg.gpu_device_id = 0 + if not hasattr(sim_cfg, "scene_id"): + raise RuntimeError( + "Error: Please upgrade habitat-sim. SimulatorConfig API version mismatch" + ) + sim_cfg.scene_id = settings["scene"] + + # define default sensor parameters (see src/esp/Sensor/Sensor.h) + sensor_specs = [] + + def create_camera_spec(**kw_args): + camera_sensor_spec = habitat_sim.CameraSensorSpec() + camera_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR + camera_sensor_spec.resolution = [settings["height"], settings["width"]] + camera_sensor_spec.position = [0.0, settings["sensor_height"], 0.0] + for k in kw_args: + setattr(camera_sensor_spec, k, kw_args[k]) + return camera_sensor_spec + + if settings["color_sensor"]: + color_sensor_spec = create_camera_spec( + uuid="color_sensor", + hfov=settings["hfov"], + sensor_type=habitat_sim.SensorType.COLOR, + sensor_subtype=habitat_sim.SensorSubType.PINHOLE, + ) + sensor_specs.append(color_sensor_spec) + + if settings["depth_sensor"]: + depth_sensor_spec = create_camera_spec( + uuid="depth_sensor", + hfov=settings["hfov"], + sensor_type=habitat_sim.SensorType.DEPTH, + channels=1, + sensor_subtype=habitat_sim.SensorSubType.PINHOLE, + ) + sensor_specs.append(depth_sensor_spec) + + if settings["semantic_sensor"]: + semantic_sensor_spec = create_camera_spec( + uuid="semantic_sensor", + hfov=settings["hfov"], + sensor_type=habitat_sim.SensorType.SEMANTIC, + channels=1, + sensor_subtype=habitat_sim.SensorSubType.PINHOLE, + ) + sensor_specs.append(semantic_sensor_spec) + + if settings["ortho_rgba_sensor"]: + ortho_rgba_sensor_spec = create_camera_spec( + uuid="ortho_rgba_sensor", + sensor_type=habitat_sim.SensorType.COLOR, + sensor_subtype=habitat_sim.SensorSubType.ORTHOGRAPHIC, + ) + sensor_specs.append(ortho_rgba_sensor_spec) + + if settings["ortho_depth_sensor"]: + ortho_depth_sensor_spec = create_camera_spec( + uuid="ortho_depth_sensor", + sensor_type=habitat_sim.SensorType.DEPTH, + channels=1, + sensor_subtype=habitat_sim.SensorSubType.ORTHOGRAPHIC, + ) + sensor_specs.append(ortho_depth_sensor_spec) + + if settings["ortho_semantic_sensor"]: + ortho_semantic_sensor_spec = create_camera_spec( + uuid="ortho_semantic_sensor", + sensor_type=habitat_sim.SensorType.SEMANTIC, + channels=1, + sensor_subtype=habitat_sim.SensorSubType.ORTHOGRAPHIC, + ) + sensor_specs.append(ortho_semantic_sensor_spec) + + # TODO Figure out how to implement copying of specs + def create_fisheye_spec(**kw_args): + fisheye_sensor_spec = habitat_sim.FisheyeSensorDoubleSphereSpec() + fisheye_sensor_spec.uuid = "fisheye_sensor" + fisheye_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR + fisheye_sensor_spec.sensor_model_type = ( + habitat_sim.FisheyeSensorModelType.DOUBLE_SPHERE + ) + + # The default value (alpha, xi) is set to match the lens "GoPro" found in Table 3 of this paper: + # Vladyslav Usenko, Nikolaus Demmel and Daniel Cremers: The Double Sphere + # Camera Model, The International Conference on 3D Vision (3DV), 2018 + # You can find the intrinsic parameters for the other lenses in the same table as well. + fisheye_sensor_spec.xi = -0.27 + fisheye_sensor_spec.alpha = 0.57 + fisheye_sensor_spec.focal_length = [364.84, 364.86] + + fisheye_sensor_spec.resolution = [ + settings["height"], + settings["width"], + ] + # The default principal_point_offset is the middle of the image + fisheye_sensor_spec.principal_point_offset = None + # default: fisheye_sensor_spec.principal_point_offset = [i/2 for i in fisheye_sensor_spec.resolution] + fisheye_sensor_spec.position = [0.0, settings["sensor_height"], 0.0] + for k in kw_args: + setattr(fisheye_sensor_spec, k, kw_args[k]) + return fisheye_sensor_spec + + if settings["fisheye_rgba_sensor"]: + fisheye_rgba_sensor_spec = create_fisheye_spec( + uuid="fisheye_rgba_sensor" + ) + sensor_specs.append(fisheye_rgba_sensor_spec) + if settings["fisheye_depth_sensor"]: + fisheye_depth_sensor_spec = create_fisheye_spec( + uuid="fisheye_depth_sensor", + sensor_type=habitat_sim.SensorType.DEPTH, + channels=1, + ) + sensor_specs.append(fisheye_depth_sensor_spec) + if settings["fisheye_semantic_sensor"]: + fisheye_semantic_sensor_spec = create_fisheye_spec( + uuid="fisheye_semantic_sensor", + sensor_type=habitat_sim.SensorType.SEMANTIC, + channels=1, + ) + sensor_specs.append(fisheye_semantic_sensor_spec) + + def create_equirect_spec(**kw_args): + equirect_sensor_spec = habitat_sim.EquirectangularSensorSpec() + equirect_sensor_spec.uuid = "equirect_rgba_sensor" + equirect_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR + equirect_sensor_spec.resolution = [ + settings["height"], + settings["width"], + ] + equirect_sensor_spec.position = [0.0, settings["sensor_height"], 0.0] + for k in kw_args: + setattr(equirect_sensor_spec, k, kw_args[k]) + return equirect_sensor_spec + + if settings["equirect_rgba_sensor"]: + equirect_rgba_sensor_spec = create_equirect_spec( + uuid="equirect_rgba_sensor" + ) + sensor_specs.append(equirect_rgba_sensor_spec) + + if settings["equirect_depth_sensor"]: + equirect_depth_sensor_spec = create_equirect_spec( + uuid="equirect_depth_sensor", + sensor_type=habitat_sim.SensorType.DEPTH, + channels=1, + ) + sensor_specs.append(equirect_depth_sensor_spec) + + if settings["equirect_semantic_sensor"]: + equirect_semantic_sensor_spec = create_equirect_spec( + uuid="equirect_semantic_sensor", + sensor_type=habitat_sim.SensorType.SEMANTIC, + channels=1, + ) + sensor_specs.append(equirect_semantic_sensor_spec) + + # create agent specifications + agent_cfg = habitat_sim.agent.AgentConfiguration() + agent_cfg.sensor_specifications = sensor_specs + agent_cfg.action_space = { + "move_forward": habitat_sim.agent.ActionSpec( + "move_forward", habitat_sim.agent.ActuationSpec(amount=0.25) + ), + "turn_left": habitat_sim.agent.ActionSpec( + "turn_left", habitat_sim.agent.ActuationSpec(amount=10.0) + ), + "turn_right": habitat_sim.agent.ActionSpec( + "turn_right", habitat_sim.agent.ActuationSpec(amount=10.0) + ), + } + + # override action space to no-op to test physics + if sim_cfg.enable_physics: + agent_cfg.action_space = { + "move_forward": habitat_sim.agent.ActionSpec( + "move_forward", habitat_sim.agent.ActuationSpec(amount=0.0) + ) + } + + return habitat_sim.Configuration(sim_cfg, [agent_cfg]) + + +def simulate(sim, dt, get_observations=False): + r"""Runs physics simulation at 60FPS for a given duration (dt) optionally collecting and returning sensor observations.""" + observations = [] + target_time = sim.get_world_time() + dt + while sim.get_world_time() < target_time: + sim.step_physics(1.0 / 60.0) + if get_observations: + observations.append(sim.get_sensor_observations()) + return observations + + +@pytest.mark.skipif( + not osp.exists("data/robots/hab_fetch"), + reason="Test requires Fetch robot URDF and assets.", +) +@pytest.mark.parametrize("fixed_base", [True, False]) +def test_fetch_robot_wrapper(fixed_base): + """Test the fetch robot.""" + # set this to output test results as video for easy investigation + produce_debug_video = False + observations = [] + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + # loading the physical scene + hab_cfg = make_cfg(cfg_settings) + + with habitat_sim.Simulator(hab_cfg) as sim: + obj_template_mgr = sim.get_object_template_manager() + rigid_obj_mgr = sim.get_rigid_object_manager() + + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add a ground plane + cube_handle = obj_template_mgr.get_template_handles("cubeSolid")[0] + cube_template_cpy = obj_template_mgr.get_template_by_handle( + cube_handle + ) + cube_template_cpy.scale = np.array([5.0, 0.2, 5.0]) + obj_template_mgr.register_template(cube_template_cpy) + ground_plane = rigid_obj_mgr.add_object_by_template_handle(cube_handle) + ground_plane.translation = [0.0, -0.2, 0.0] + ground_plane.motion_type = habitat_sim.physics.MotionType.STATIC + + # compute a navmesh on the ground plane + navmesh_settings = habitat_sim.NavMeshSettings() + navmesh_settings.set_defaults() + navmesh_settings.include_static_objects = True + sim.recompute_navmesh(sim.pathfinder, navmesh_settings) + sim.navmesh_visualization = True + + # add the robot to the world via the wrapper + robot_path = "data/robots/hab_fetch/robots/hab_fetch.urdf" + agent_config = DictConfig({"articulated_agent_urdf": robot_path}) + fetch = fetch_robot.FetchRobot( + agent_config, sim, fixed_base=fixed_base + ) + fetch.reconfigure() + fetch.update() + assert fetch.get_robot_sim_id() == ground_plane.object_id + 1 + print(fetch.get_link_and_joint_names()) + observations += simulate(sim, 1.0, produce_debug_video) + + # retract the arm + observations += fetch._interpolate_arm_control( + [1.2299035787582397, 2.345386505126953], + [ + fetch.params.arm_joints[1], + fetch.params.arm_joints[3], + ], + 1, + 30, + produce_debug_video, + ) + + # ready the arm + observations += fetch._interpolate_arm_control( + [-0.45, 0.1], + [ + fetch.params.arm_joints[1], + fetch.params.arm_joints[3], + ], + 1, + 30, + produce_debug_video, + ) + + # setting arm motor positions + fetch.arm_motor_pos = np.zeros(len(fetch.params.arm_joints)) + observations += simulate(sim, 1.0, produce_debug_video) + + # set base ground position using object transformation approach + target_base_pos = sim.pathfinder.snap_point(fetch.sim_obj.translation) + # Note, don't test equivalency of pi, because that is the wrap point and is often negated. + target_base_rots = [0.0, np.pi * 0.25, np.pi * 0.50, np.pi * 0.99] + for target_base_rot in target_base_rots: + set_agent_base_via_obj_trans( + target_base_pos, target_base_rot, fetch + ) + assert fetch.base_pos == target_base_pos + assert fetch.base_rot == pytest.approx(target_base_rot, 0.001) + + # set base ground position from navmesh + # NOTE: because the navmesh floats above the collision geometry we should see a pop/settle with dynamics and no fixed base + target_base_pos = sim.pathfinder.snap_point(fetch.sim_obj.translation) + fetch.base_pos = target_base_pos + assert fetch.base_pos == target_base_pos + observations += simulate(sim, 1.0, produce_debug_video) + if fixed_base: + assert np.allclose(fetch.base_pos, target_base_pos) + else: + assert not np.allclose(fetch.base_pos, target_base_pos) + + # arm joint queries and setters + print(f" Arm joint velocities = {fetch.arm_velocity}") + fetch.arm_joint_pos = np.ones(len(fetch.params.arm_joints)) + fetch.arm_motor_pos = np.ones(len(fetch.params.arm_joints)) + print(f" Arm joint positions (should be ones) = {fetch.arm_joint_pos}") + print(f" Arm joint limits = {fetch.arm_joint_limits}") + fetch.arm_motor_pos = fetch.arm_motor_pos + observations += simulate(sim, 1.0, produce_debug_video) + + # test gripper state + fetch.open_gripper() + observations += simulate(sim, 1.0, produce_debug_video) + assert fetch.is_gripper_open + assert not fetch.is_gripper_closed + fetch.close_gripper() + observations += simulate(sim, 1.0, produce_debug_video) + assert fetch.is_gripper_closed + assert not fetch.is_gripper_open # type: ignore[unreachable] + + # halfway open + fetch.set_gripper_target_state(0.5) + observations += simulate(sim, 0.5, produce_debug_video) + assert not fetch.is_gripper_open + assert not fetch.is_gripper_closed + + # kinematic open/close (checked before simulation) + fetch.gripper_joint_pos = fetch.params.gripper_open_state + assert np.allclose( + fetch.gripper_joint_pos, + fetch.params.gripper_open_state, + ) + assert fetch.is_gripper_open + observations += simulate(sim, 0.2, produce_debug_video) + fetch.gripper_joint_pos = fetch.params.gripper_closed_state + assert fetch.is_gripper_closed + observations += simulate(sim, 0.2, produce_debug_video) + + # end effector queries + print(f" End effector link id = {fetch.ee_link_id}") + print(f" End effector local offset = {fetch.ee_local_offset}") + print(f" End effector transform = {fetch.ee_transform}") + print( + f" End effector translation (at current state) = {fetch.calculate_ee_forward_kinematics(fetch.sim_obj.joint_positions)}" + ) + invalid_ef_target = np.array([100.0, 200.0, 300.0]) + print( + f" Clip end effector target ({invalid_ef_target}) to reach = {fetch.clip_ee_to_workspace(invalid_ef_target)}" + ) + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_fetch_robot_wrapper__fixed_base=" + str(fixed_base), + open_vid=True, + ) + + +@pytest.mark.skipif( + not osp.exists("data/robots/franka_panda"), + reason="Test requires Franka robot URDF and assets.", +) +@pytest.mark.skipif( + not habitat_sim.built_with_bullet, + reason="Robot wrapper API requires Bullet physics.", +) +def test_franka_robot_wrapper(): + """Test the franka robot.""" + # set this to output test results as video for easy investigation + produce_debug_video = False + observations = [] + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + # loading the physical scene + hab_cfg = make_cfg(cfg_settings) + + with habitat_sim.Simulator(hab_cfg) as sim: + obj_template_mgr = sim.get_object_template_manager() + rigid_obj_mgr = sim.get_rigid_object_manager() + + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add a ground plane + cube_handle = obj_template_mgr.get_template_handles("cubeSolid")[0] + cube_template_cpy = obj_template_mgr.get_template_by_handle( + cube_handle + ) + cube_template_cpy.scale = np.array([5.0, 0.2, 5.0]) + obj_template_mgr.register_template(cube_template_cpy) + ground_plane = rigid_obj_mgr.add_object_by_template_handle(cube_handle) + ground_plane.translation = [0.0, -0.2, 0.0] + ground_plane.motion_type = habitat_sim.physics.MotionType.STATIC + + # compute a navmesh on the ground plane + navmesh_settings = habitat_sim.NavMeshSettings() + navmesh_settings.set_defaults() + navmesh_settings.include_static_objects = True + sim.recompute_navmesh(sim.pathfinder, navmesh_settings) + sim.navmesh_visualization = True + + # add the robot to the world via the wrapper + robot_path = "data/robots/franka_panda/panda_arm.urdf" + franka = franka_robot.FrankaRobot(urdf_path=robot_path, sim=sim) + franka.reconfigure() + franka.update() + assert franka.get_robot_sim_id() == ground_plane.object_id + 1 + print(franka.get_link_and_joint_names()) + observations += simulate(sim, 1.0, produce_debug_video) + + # move the arm + observations += franka._interpolate_arm_control( + [1.2299035787582397, 2.345386505126953], + [ + franka.params.arm_joints[1], + franka.params.arm_joints[3], + ], + 1, + 30, + produce_debug_video, + ) + + # move the arm + observations += franka._interpolate_arm_control( + [-0.45, 0.1], + [ + franka.params.arm_joints[1], + franka.params.arm_joints[3], + ], + 1, + 30, + produce_debug_video, + ) + + # setting arm motor positions + franka.arm_motor_pos = np.zeros(len(franka.params.arm_joints)) + observations += simulate(sim, 1.0, produce_debug_video) + assert np.allclose( + franka.arm_motor_pos, + np.zeros(len(franka.params.arm_joints)), + ) + + # arm joint queries and setters + print(f" Arm joint velocities = {franka.arm_velocity}") + franka.arm_joint_pos = np.ones(len(franka.params.arm_joints)) + franka.arm_motor_pos = np.ones(len(franka.params.arm_joints)) + print( + f" Arm joint positions (should be ones) = {franka.arm_joint_pos}" + ) + print(f" Arm joint limits = {franka.arm_joint_limits}") + franka.arm_motor_pos = franka.arm_motor_pos + observations += simulate(sim, 1.0, produce_debug_video) + + # end effector queries + print(f" End effector link id = {franka.ee_link_id}") + print(f" End effector local offset = {franka.ee_local_offset}") + print(f" End effector transform = {franka.ee_transform}") + print( + f" End effector translation (at current state) = {franka.calculate_ee_forward_kinematics(franka.sim_obj.joint_positions)}" + ) + invalid_ef_target = np.array([100.0, 200.0, 300.0]) + print( + f" Clip end effector target ({invalid_ef_target}) to reach = {franka.clip_ee_to_workspace(invalid_ef_target)}" + ) + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_franka_robot_wrapper", + open_vid=True, + ) + + +@pytest.mark.skipif( + not osp.exists("data/robots/hab_spot_arm"), + reason="Test requires Spot w/ arm robot URDF and assets.", +) +@pytest.mark.skipif( + not habitat_sim.built_with_bullet, + reason="Robot wrapper API requires Bullet physics.", +) +@pytest.mark.parametrize("fixed_base", [True, False]) +def test_spot_robot_wrapper(fixed_base): + # set this to output test results as video for easy investigation + produce_debug_video = False + observations = [] + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + # loading the physical scene + hab_cfg = make_cfg(cfg_settings) + + with habitat_sim.Simulator(hab_cfg) as sim: + obj_template_mgr = sim.get_object_template_manager() + rigid_obj_mgr = sim.get_rigid_object_manager() + + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add a ground plane + cube_handle = obj_template_mgr.get_template_handles("cubeSolid")[0] + cube_template_cpy = obj_template_mgr.get_template_by_handle( + cube_handle + ) + cube_template_cpy.scale = np.array([5.0, 0.2, 5.0]) + obj_template_mgr.register_template(cube_template_cpy) + ground_plane = rigid_obj_mgr.add_object_by_template_handle(cube_handle) + ground_plane.translation = [0.0, -0.2, 0.0] + ground_plane.motion_type = habitat_sim.physics.MotionType.STATIC + + # compute a navmesh on the ground plane + navmesh_settings = habitat_sim.NavMeshSettings() + navmesh_settings.set_defaults() + navmesh_settings.include_static_objects = True + sim.recompute_navmesh(sim.pathfinder, navmesh_settings) + sim.navmesh_visualization = True + # add the robot to the world via the wrapper + robot_path = "data/robots/hab_spot_arm/urdf/hab_spot_arm.urdf" + agent_config = DictConfig({"articulated_agent_urdf": robot_path}) + spot = spot_robot.SpotRobot(agent_config, sim, fixed_base=fixed_base) + spot.reconfigure() + spot.update() + assert spot.get_robot_sim_id() == ground_plane.object_id + 1 + print(spot.get_link_and_joint_names()) + + # set the motor angles + spot.leg_joint_pos = [0.0, 0.7, -1.5] * 4 + + # set base ground position using object transformation approach + target_base_pos = sim.pathfinder.snap_point(spot.sim_obj.translation) + # Note, don't test equivalency of pi, because that is the wrap point and is often negated. + target_base_rots = [0.0, np.pi * 0.25, np.pi * 0.50, np.pi * 0.99] + for target_base_rot in target_base_rots: + set_agent_base_via_obj_trans( + target_base_pos, target_base_rot, spot + ) + assert spot.base_pos == target_base_pos + assert spot.base_rot == pytest.approx(target_base_rot, 0.001) + + # set base ground position from navmesh + spot.base_pos = target_base_pos + assert spot.base_pos == target_base_pos + observations += simulate(sim, 1.0, produce_debug_video) + if fixed_base: + assert np.allclose(spot.base_pos, target_base_pos) + else: + assert not np.allclose(spot.base_pos, target_base_pos) + + # ready the arm + observations += spot._interpolate_arm_control( + [0.0, 0.0], + [spot.params.arm_joints[1], spot.params.arm_joints[3]], + 1, + 30, + produce_debug_video, + ) + + # retract the arm + observations += spot._interpolate_arm_control( + [-3.14, 3.0], + [spot.params.arm_joints[1], spot.params.arm_joints[3]], + 1, + 30, + produce_debug_video, + ) + + # setting arm motor positions to fully extend + spot.arm_motor_pos = np.zeros(len(spot.params.arm_joints)) + observations += simulate(sim, 1.0, produce_debug_video) + + # test gripper state + spot.open_gripper() + observations += simulate(sim, 1.0, produce_debug_video) + assert spot.is_gripper_open + assert not spot.is_gripper_closed + spot.close_gripper() + observations += simulate(sim, 1.0, produce_debug_video) + assert spot.is_gripper_closed + assert not spot.is_gripper_open # type: ignore[unreachable] + + # halfway open + spot.set_gripper_target_state(0.5) + observations += simulate(sim, 0.5, produce_debug_video) + assert not spot.is_gripper_open + assert not spot.is_gripper_closed + + # kinematic open/close (checked before simulation) + spot.gripper_joint_pos = spot.params.gripper_open_state + assert np.allclose( + spot.gripper_joint_pos, spot.params.gripper_open_state + ) + assert spot.is_gripper_open + observations += simulate(sim, 0.2, produce_debug_video) + spot.gripper_joint_pos = spot.params.gripper_closed_state + assert spot.is_gripper_closed + observations += simulate(sim, 0.2, produce_debug_video) + + # end effector queries + print(f" End effector link id = {spot.ee_link_id}") + print(f" End effector local offset = {spot.ee_local_offset}") + print(f" End effector transform = {spot.ee_transform}") + print( + f" End effector translation (at current state) = {spot.calculate_ee_forward_kinematics(spot.sim_obj.joint_positions)}" + ) + invalid_ef_target = np.array([100.0, 200.0, 300.0]) + print( + f" Clip end effector target ({invalid_ef_target}) to reach = {spot.clip_ee_to_workspace(invalid_ef_target)}" + ) + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_spot_robot_wrapper__fixed_base=" + str(fixed_base), + open_vid=True, + ) + + +@pytest.mark.skipif( + not osp.exists("data/robots/hab_spot_arm"), + reason="Test requires Spot w/ arm robot URDF and assets.", +) +@pytest.mark.skipif( + not habitat_sim.built_with_bullet, + reason="Robot wrapper API requires Bullet physics.", +) +def test_base_rot(): + # set this to output test results as video for easy investigation + produce_debug_video = False + observations = [] + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + # loading the physical scene + hab_cfg = make_cfg(cfg_settings) + + with habitat_sim.Simulator(hab_cfg) as sim: + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add the robot to the world via the wrapper + robot_path = "data/robots/hab_spot_arm/urdf/hab_spot_arm.urdf" + agent_config = DictConfig({"articulated_agent_urdf": robot_path}) + spot = spot_robot.SpotRobot(agent_config, sim) + spot.reconfigure() + spot.update() + + # check that for range (-pi, pi) getter and setter are consistent + num_samples = 100 + for i in range(1, num_samples): + angle = -math.pi + (math.pi * 2 * i) / num_samples + spot.base_rot = angle + assert np.allclose(angle, spot.base_rot, atol=1e-5) + if produce_debug_video: + observations.append(sim.get_sensor_observations()) + + # check that for range [-2pi, 2pi] increment is accurate + spot.base_rot = -math.pi * 2 + inc = (math.pi * 4) / num_samples + rot_check = -math.pi * 2 + for _ in range(0, num_samples): + spot.base_rot = spot.base_rot + inc + rot_check += inc + # NOTE: here we check that the angle is accurate (allow an offset of one full rotation to cover redundant options) + accurate_angle = False + for offset in [0, math.pi * 2, math.pi * -2]: + if np.allclose(rot_check, spot.base_rot + offset, atol=1e-5): + accurate_angle = True + break + assert ( + accurate_angle + ), f"should be {rot_check}, but was {spot.base_rot}." + if produce_debug_video: + observations.append(sim.get_sensor_observations()) + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_base_rot", + open_vid=True, + ) + + +@pytest.mark.skipif( + not osp.exists("data/robots/hab_stretch"), + reason="Test requires Stretch w/ robot URDF and assets.", +) +@pytest.mark.skipif( + not habitat_sim.built_with_bullet, + reason="Robot wrapper API requires Bullet physics.", +) +@pytest.mark.parametrize("fixed_base", [True, False]) +def test_stretch_robot_wrapper(fixed_base): + # set this to output test results as video for easy investigation + produce_debug_video = False + observations = [] + cfg_settings = default_sim_settings.copy() + cfg_settings["scene"] = "NONE" + cfg_settings["enable_physics"] = True + + # loading the physical scene + hab_cfg = make_cfg(cfg_settings) + + with habitat_sim.Simulator(hab_cfg) as sim: + obj_template_mgr = sim.get_object_template_manager() + rigid_obj_mgr = sim.get_rigid_object_manager() + + # setup the camera for debug video (looking at 0,0,0) + sim.agents[0].scene_node.translation = [0.0, -1.0, 2.0] + + # add a ground plane + cube_handle = obj_template_mgr.get_template_handles("cubeSolid")[0] + cube_template_cpy = obj_template_mgr.get_template_by_handle( + cube_handle + ) + cube_template_cpy.scale = np.array([5.0, 0.2, 5.0]) + obj_template_mgr.register_template(cube_template_cpy) + ground_plane = rigid_obj_mgr.add_object_by_template_handle(cube_handle) + ground_plane.translation = [0.0, -0.6, 0.0] + ground_plane.motion_type = habitat_sim.physics.MotionType.STATIC + + # compute a navmesh on the ground plane + navmesh_settings = habitat_sim.NavMeshSettings() + navmesh_settings.set_defaults() + navmesh_settings.include_static_objects = True + sim.recompute_navmesh(sim.pathfinder, navmesh_settings) + sim.navmesh_visualization = True + # add the robot to the world via the wrapper + robot_path = "data/robots/hab_stretch/urdf/hab_stretch.urdf" + agent_config = DictConfig({"articulated_agent_urdf": robot_path}) + stretch = stretch_robot.StretchRobot( + agent_config, sim, fixed_base=fixed_base + ) + stretch.reconfigure() + stretch.update() + assert stretch.get_robot_sim_id() == ground_plane.object_id + 1 + + # set base ground position using object transformation approach + target_base_pos = sim.pathfinder.snap_point( + stretch.sim_obj.translation + ) + # Note, don't test equivalency of pi, because that is the wrap point and is often negated. + target_base_rots = [0.0, np.pi * 0.25, np.pi * 0.50, np.pi * 0.99] + for target_base_rot in target_base_rots: + set_agent_base_via_obj_trans( + target_base_pos, target_base_rot, stretch + ) + assert stretch.base_pos == target_base_pos + assert stretch.base_rot == pytest.approx(target_base_rot, 0.001) + + # set base ground position from navmesh + target_base_pos = sim.pathfinder.snap_point( + stretch.sim_obj.translation + ) + stretch.base_pos = target_base_pos + assert stretch.base_pos == target_base_pos + observations += simulate(sim, 1.0, produce_debug_video) + if fixed_base: + assert np.allclose(stretch.base_pos, target_base_pos) + else: + assert not np.allclose(stretch.base_pos, target_base_pos) + + observations += stretch._interpolate_arm_control( + [0.0], + [ + stretch.params.arm_joints[0], + stretch.params.arm_joints[1], + stretch.params.arm_joints[2], + stretch.params.arm_joints[3], + ], + 1, + 30, + produce_debug_video, + ) + + observations += stretch._interpolate_arm_control( + [0.15], + [ + stretch.params.arm_joints[0], + stretch.params.arm_joints[1], + stretch.params.arm_joints[2], + stretch.params.arm_joints[3], + ], + 1, + 30, + produce_debug_video, + ) + + stretch.arm_motor_pos = np.zeros(len(stretch.params.arm_joints)) + observations += simulate(sim, 1.0, produce_debug_video) + + # test gripper state + stretch.open_gripper() + observations += simulate(sim, 1.0, produce_debug_video) + assert stretch.is_gripper_open + assert not stretch.is_gripper_closed + stretch.close_gripper() + observations += simulate(sim, 1.0, produce_debug_video) + assert stretch.is_gripper_closed + assert not stretch.is_gripper_open # type: ignore[unreachable] + + # halfway open + stretch.set_gripper_target_state(0.5) + observations += simulate(sim, 0.5, produce_debug_video) + assert not stretch.is_gripper_open + assert not stretch.is_gripper_closed + + # kinematic open/close (checked before simulation) + stretch.gripper_joint_pos = stretch.params.gripper_open_state + assert np.allclose( + stretch.gripper_joint_pos, stretch.params.gripper_open_state + ) + assert stretch.is_gripper_open + observations += simulate(sim, 0.2, produce_debug_video) + stretch.gripper_joint_pos = stretch.params.gripper_closed_state + assert stretch.is_gripper_closed + observations += simulate(sim, 0.2, produce_debug_video) + + # end effector queries + print(f" End effector link id = {stretch.ee_link_id}") + print(f" End effector local offset = {stretch.ee_local_offset}") + print(f" End effector transform = {stretch.ee_transform}") + print( + f" End effector translation (at current state) = {stretch.calculate_ee_forward_kinematics(stretch.sim_obj.joint_positions)}" + ) + invalid_ef_target = np.array([100.0, 200.0, 300.0]) + print( + f" Clip end effector target ({invalid_ef_target}) to reach = {stretch.clip_ee_to_workspace(invalid_ef_target)}" + ) + + # produce some test debug video + if produce_debug_video: + from habitat_sim.utils import viz_utils as vut + + vut.make_video( + observations, + "color_sensor", + "color", + "test_stretch_robot_wrapper__fixed_base=" + str(fixed_base), + open_vid=True, + ) diff --git a/world-in-world/src/habitat-baselines/test/test_spaces.py b/world-in-world/src/habitat-baselines/test/test_spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..ad7db5b94e1b1696641ac686b128aef84049c45d --- /dev/null +++ b/world-in-world/src/habitat-baselines/test/test_spaces.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 + +# Copyright (c) Meta Platforms, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import gym + +from habitat.core.spaces import ActionSpace, EmptySpace, ListSpace + + +def test_empty_space(): + space = EmptySpace() + assert space.contains(space.sample()) + assert space.contains(None) + assert not space.contains(0) + + +def test_action_space(): + space = ActionSpace( + { + "move": gym.spaces.Dict( + { + "position": gym.spaces.Discrete(2), + "velocity": gym.spaces.Discrete(3), + } + ), + "move_forward": EmptySpace(), + } + ) + assert space.contains(space.sample()) + assert space.contains( + {"action": "move", "action_args": {"position": 0, "velocity": 1}} + ) + assert space.contains({"action": "move_forward"}) + assert not space.contains([0, 1, 2]) + assert not space.contains({"zero": None}) + assert not space.contains({"action": "bad"}) + assert not space.contains({"action": "move"}) + assert not space.contains( + {"action": "move", "action_args": {"position": 0}} + ) + assert not space.contains( + {"action": "move_forward", "action_args": {"position": 0}} + ) + + +def test_list_space(): + space = ListSpace(gym.spaces.Discrete(2), 5, 10) + assert space.contains(space.sample()) + assert not space.contains(0) + assert not space.contains([0] * 4) + assert not space.contains([2] * 5) + assert not space.contains([1] * 11)