code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def update(
self,
episode: Episode,
episode_gt: Episode,
success_ids: list,
):
"""Update and compute metrics for trajectories from all simulation instances in one episode."""
self.num_motions += episode.num_envs
# First, compute metrics on trajectories from al... | Update and compute metrics for trajectories from all simulation instances in one episode. | update | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _compute_link_metrics(
self,
body_pos: list[torch.Tensor],
body_pos_gt: list[torch.Tensor],
storage: dict[str, dict[str, list[float]]],
):
"""Compute metrics of trajectories and save them by their means and number of elements (as weights)."""
# compute_metrics_lit... | Compute metrics of trajectories and save them by their means and number of elements (as weights). | _compute_link_metrics | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def compute_joint_tracking_error(
joint_pos: torch.Tensor, joint_pos_gt: torch.Tensor, frame_weights: torch.Tensor, num_envs: int
) -> float:
"""Compute weighted mean absolute joint position error across environments.
For each environment:
1. Take absolute differ... | Compute weighted mean absolute joint position error across environments.
For each environment:
1. Take absolute difference between predicted and ground truth joint positions
2. Weight the differences by frame_weights to normalize across varying trajectory lengths
3. Take... | compute_joint_tracking_error | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def compute_height_error(
root_pos: torch.Tensor, root_pos_gt: torch.Tensor, frame_weights: torch.Tensor, num_envs: int
) -> float:
"""Compute weighted mean absolute height error across environments.
For each environment:
1. Takes absolute difference between pred... | Compute weighted mean absolute height error across environments.
For each environment:
1. Takes absolute difference between predicted and ground truth root z-coordinates
2. Weights the differences by frame_weights to normalize across varying trajectory lengths
3. Takes m... | compute_height_error | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def compute_vel_error(
vel: torch.Tensor,
rot: torch.Tensor,
vel_gt: torch.Tensor,
rot_gt: torch.Tensor,
frame_weights: torch.Tensor,
num_envs: int,
) -> float:
"""Compute weighted mean velocity tracking error across environment... | Compute weighted mean velocity tracking error across environments.
For each environment:
1. Convert velocities to local frame using inverse rotation
2. Take L2 norm of difference between predicted and ground truth local velocities
3. Weight by frame_weights and average a... | compute_vel_error | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _compute_root_rot_tracking_error(
self,
root_rot: torch.Tensor,
root_rot_gt: torch.Tensor,
frame_weights: torch.Tensor,
num_envs: int,
storage: dict[str, dict[str, list[float]]],
):
"""Compute root rotation tracking error.
Args:
root_r... | Compute root rotation tracking error.
Args:
root_rot: Root rotation quaternions
root_rot_gt: Ground truth root rotation quaternions
Returns:
dict: Dictionary containing roll, pitch, yaw errors
| _compute_root_rot_tracking_error | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def compute_rot_tracking_error(
quat1: torch.Tensor, quat2: torch.Tensor, frame_weights: torch.Tensor, num_envs: int
) -> tuple[float, float, float]:
"""Compute weighted mean rotation tracking error across environments.
For each environment:
1. Compute quaternion... | Compute weighted mean rotation tracking error across environments.
For each environment:
1. Compute quaternion difference between predicted and ground truth rotations
2. Convert difference quaternion to Euler angles (roll, pitch, yaw)
3. Take absolute value of angles and... | compute_rot_tracking_error | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _record_metrics(self, name: str, mean: float, weight: int, storage: dict[str, dict[str, list[float]]]):
"""Record metrics by their means and number of elements (as weights)."""
if name not in storage:
storage[name] = {"means": [], "weights": []}
storage[name]["means"].append(mean... | Record metrics by their means and number of elements (as weights). | _record_metrics | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def conclude(self):
"""At the end of the evaluation, computes the metrics over all tasks."""
self.all_metrics = {
key: np.average(value["means"], weights=value["weights"])
for key, value in self._all_metrics_by_episode.items()
}
self.success_metrics = {
... | At the end of the evaluation, computes the metrics over all tasks. | conclude | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def save(self, directory: str):
"""Saves metrics to a time-stamped json file in ``directory``.
Args:
directory (str): Directory to stored the file to.
"""
file_dir = Path(directory)
file_dir.mkdir(parents=True, exist_ok=True)
timestamp = time.strftime("%Y%m%d... | Saves metrics to a time-stamped json file in ``directory``.
Args:
directory (str): Directory to stored the file to.
| save | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def __init__(
self,
env_wrapper: EnvironmentWrapper,
metrics_path: str | None = None,
):
"""Initializes the evaluator.
Args:
env_wrapper (EnvironmentWrapper): The environment that the evaluation is taking place.
metrics_path (str | None, optional): Th... | Initializes the evaluator.
Args:
env_wrapper (EnvironmentWrapper): The environment that the evaluation is taking place.
metrics_path (str | None, optional): The directory that the metrics will be saved to. Defaults to None.
| __init__ | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def collect(self, dones: torch.Tensor, info: dict) -> bool:
"""Collects data from a step and updates internal states.
Args:
dones (torch.Tensor): environments that are terminated (failed) or truncated (timed out).
info (dict): Extra information collected from a step.
Re... | Collects data from a step and updates internal states.
Args:
dones (torch.Tensor): environments that are terminated (failed) or truncated (timed out).
info (dict): Extra information collected from a step.
Returns:
bool: Whether all current reference motions are eval... | collect | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _collect_step_data(self, newly_terminated: torch.Tensor, info: dict):
"""Collects data after each step.
Args:
newly_terminated(torch.Tensor(bool)): Newly terminated env
info (dict): Extra information collected from a step.
"""
state_data = info["data"]["stat... | Collects data after each step.
Args:
newly_terminated(torch.Tensor(bool)): Newly terminated env
info (dict): Extra information collected from a step.
| _collect_step_data | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _build_frame(
self, data: dict, mask: torch.Tensor, num_envs: int, upper_joint_ids: list, lower_joint_ids: list
) -> Frame:
"""Builds a frame from the data and mask.
Args:
data (dict): Dictionary containing trajectory data including body positions, joint positions, etc.
... | Builds a frame from the data and mask.
Args:
data (dict): Dictionary containing trajectory data including body positions, joint positions, etc.
mask (torch.Tensor): Boolean mask array indicating which bodies to include in masked data.
num_envs (int): Number of environments.
... | _build_frame | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _update_failure_metrics(self, newly_terminated: torch.Tensor, info: dict):
"""Updates failure metrics based on termination conditions."""
start_id = self._ref_motion_start_id
end_id = min(self._ref_motion_start_id + self._num_envs, self._num_unique_ref_motions)
counted_envs = end_id ... | Updates failure metrics based on termination conditions. | _update_failure_metrics | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _reset_data_buffer(self):
"""Resets data buffer for new episodes."""
self._terminated[:] = False
self._pbar.update(1)
self._pbar.refresh()
self._ref_motion_frames = self._ref_motion_mgr.get_motion_num_steps()
self._episode = Episode(max_frames_per_env=self._ref_motion... | Resets data buffer for new episodes. | _reset_data_buffer | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def _update_status_bar(self):
"""Updates status bar in the console to display current progress and selected metrics."""
update_str = (
f"Terminated: {self._terminated.sum().item()} | max frames: {self._ref_motion_frames.max()} | steps"
f" {self._curr_steps} | Start: {self._ref_m... | Updates status bar in the console to display current progress and selected metrics. | _update_status_bar | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def conclude(self):
"""Concludes evaluation by computing, printing and optionally saving metrics."""
self._pbar.close()
self._metrics.conclude()
self._metrics.print()
if self._metrics_path:
self._metrics.save(self._metrics_path) | Concludes evaluation by computing, printing and optionally saving metrics. | conclude | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def forward_motion_samples(self):
"""Steps forward in the list of reference motions.
All simulated environments must be reset following this function call.
"""
self._ref_motion_start_id += self._num_envs
self._ref_motion_mgr.load_motions(random_sample=False, start_idx=self._ref_... | Steps forward in the list of reference motions.
All simulated environments must be reset following this function call.
| forward_motion_samples | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/evaluator.py | Apache-2.0 |
def create_mask_element_names(body_names: list[str], joint_names: list[str]):
"""Get a name for each element of the mask."""
body_names = [name + "_local_pos_" for name in body_names]
joint_names = [name + "_joint_pos" for name in joint_names]
root_reference_names = [
"root_linear_velocity_x",
... | Get a name for each element of the mask. | create_mask_element_names | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/mask.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/mask.py | Apache-2.0 |
def create_mask(
num_envs: int,
mask_element_names: list[str],
mask_modes: dict[str, dict[str, list[str]]],
enable_sparsity_randomization: bool,
device: torch.device,
) -> torch.Tensor:
"""
Create a mask where all enabled states are set to 1.
This mask can be used directly or multiplied ... |
Create a mask where all enabled states are set to 1.
This mask can be used directly or multiplied with 0.5 and then be used as the probability of
a state being enabled.
Args:
mask_element_names: The name corresponding to every element in the mask.
mask_modes: A nested dictionary config... | create_mask | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/mask.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/mask.py | Apache-2.0 |
def quat_box_minus(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""The box-minus operator (quaternion difference) between two quaternions.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (N, 4).
q2: The second quaternion in (w, x, y, z). Shape is (N, 4).
Returns:
T... | The box-minus operator (quaternion difference) between two quaternions.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (N, 4).
q2: The second quaternion in (w, x, y, z). Shape is (N, 4).
Returns:
The difference between the two quaternions. Shape is (N, 3).
| quat_box_minus | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/math_utils.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/math_utils.py | Apache-2.0 |
def quat_rotate(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Rotate a vector by a quaternion along the last dimension of q and v.
Args:
q: The quaternion in (w, x, y, z). Shape is (..., 4).
v: The vector in (x, y, z). Shape is (..., 3).
Returns:
The rotated vector in (x, y... | Rotate a vector by a quaternion along the last dimension of q and v.
Args:
q: The quaternion in (w, x, y, z). Shape is (..., 4).
v: The vector in (x, y, z). Shape is (..., 3).
Returns:
The rotated vector in (x, y, z). Shape is (..., 3).
| quat_rotate | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/math_utils.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/math_utils.py | Apache-2.0 |
def quat_rotate_inverse(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Rotate a vector by the inverse of a quaternion along the last dimension of q and v.
Args:
q: The quaternion in (w, x, y, z). Shape is (..., 4).
v: The vector in (x, y, z). Shape is (..., 3).
Returns:
The ... | Rotate a vector by the inverse of a quaternion along the last dimension of q and v.
Args:
q: The quaternion in (w, x, y, z). Shape is (..., 4).
v: The vector in (x, y, z). Shape is (..., 3).
Returns:
The rotated vector in (x, y, z). Shape is (..., 3).
| quat_rotate_inverse | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/math_utils.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/math_utils.py | Apache-2.0 |
def __init__(
self,
ref_motion: dict,
body_ids: List[int] | None = None,
joint_ids: List[int] | None = None,
):
"""Represents the state of a reference motion frame.
Args:
ref_motion (dict): Reference motion data at a specific point in time, loaded from th... | Represents the state of a reference motion frame.
Args:
ref_motion (dict): Reference motion data at a specific point in time, loaded from the dataset.
body_ids (List[int] | None, optional): Desired ordering of the bodies. Defaults to None.
joint_ids (List[int] | None, option... | __init__ | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/reference_motion.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/reference_motion.py | Apache-2.0 |
def __init__(
self,
cfg: ReferenceMotionManagerCfg,
device: torch.device,
num_envs: int,
random_sample: bool,
extend_head: bool,
dt: float,
):
"""Initializes a reference motion manager that loads and queries a motion dataset.
Args:
... | Initializes a reference motion manager that loads and queries a motion dataset.
Args:
cfg (ReferenceMotionManagerCfg): Configuration that specifies dataset and skeleton paths.
device (torch.device): Device to host tensors on.
num_envs (int): Number of environments/instances.... | __init__ | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/reference_motion.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/reference_motion.py | Apache-2.0 |
def load_motions(self, random_sample: bool, start_idx: int):
"""Loads motions from the motion dataset."""
self._motion_lib.load_motions(
skeleton_trees=self._skeleton_trees,
gender_betas=[torch.zeros(17)] * self._num_envs,
limb_weights=[np.zeros(10)] * self._num_envs,... | Loads motions from the motion dataset. | load_motions | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/reference_motion.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/reference_motion.py | Apache-2.0 |
def reset_motion_start_times(self, env_ids: torch.Tensor, sample: bool):
"""Resets the time at which the reference motions start playing."""
if sample:
self._motion_start_times[env_ids] = self._motion_lib.sample_time(self._motion_ids[env_ids])
else:
self._motion_start_tim... | Resets the time at which the reference motions start playing. | reset_motion_start_times | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/reference_motion.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/reference_motion.py | Apache-2.0 |
def episodes_exceed_motion_length(
self, episode_times: torch.Tensor, env_ids: torch.Tensor | None = None
) -> torch.Tensor:
"""Checks if the reference motion has reached to the end."""
if env_ids is None:
return (episode_times + self._motion_start_times) > self._motion_len
... | Checks if the reference motion has reached to the end. | episodes_exceed_motion_length | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/reference_motion.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/reference_motion.py | Apache-2.0 |
def get_state_from_motion_lib_cache(
self,
episode_length_buf: torch.Tensor,
terrain_heights: torch.Tensor | None = None,
offset: torch.Tensor | None = None,
quaternion_is_xyzw=True,
) -> ReferenceMotionState:
"""Query a reference motion frame from motion lib."""
... | Query a reference motion frame from motion lib. | get_state_from_motion_lib_cache | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/reference_motion.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/reference_motion.py | Apache-2.0 |
def check_termination_conditions(
training_mode: bool,
projected_gravity: torch.Tensor,
gravity_x_threshold: float,
gravity_y_threshold: float,
ref_motion_mgr: ReferenceMotionManager,
episode_times: torch.Tensor,
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
max_ref_... |
Evaluates termination conditions.
This function checks various termination conditions and returns a boolean tensor of shape (num_env,)
indicating whether any condition has been met. Additionally, it provides a dictionary mapping
each condition's name to its activation state, with each state represente... | check_termination_conditions | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/termination.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/termination.py | Apache-2.0 |
def terminate_by_gravity(
projected_gravity: torch.Tensor,
gravity_x_threshold: float,
gravity_y_threshold: float,
) -> torch.Tensor:
"""
Checks termination condition based on robot balance.
This function evaluates whether the robot is unbalanced due to gravity and returns
a boolean tensor ... |
Checks termination condition based on robot balance.
This function evaluates whether the robot is unbalanced due to gravity and returns
a boolean tensor of shape (num_env, 1). Each element in the tensor indicates whether
the unbalanced condition is active for the corresponding environment.
Return... | terminate_by_gravity | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/termination.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/termination.py | Apache-2.0 |
def terminate_by_undesired_contact(
net_contact_forces: torch.Tensor, undesired_contact_body_ids: torch.Tensor
) -> torch.Tensor:
"""
Checks termination condition based on contact forces.
This function evaluates whether undesired bodies of the robot are in contact and returns a
boolean tensor of sh... |
Checks termination condition based on contact forces.
This function evaluates whether undesired bodies of the robot are in contact and returns a
boolean tensor of shape (num_env, 1). Each element in the tensor indicates whether the contact
termination condition is active for the corresponding environm... | terminate_by_undesired_contact | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/termination.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/termination.py | Apache-2.0 |
def terminate_by_reference_motion_length(
ref_motion_mgr: ReferenceMotionManager, episode_times: torch.Tensor
) -> torch.Tensor:
"""Checks if the reference motion has ended for each environment.
This function returns a boolean tensor of shape (num_env, 1), where each element indicates
whether the refer... | Checks if the reference motion has ended for each environment.
This function returns a boolean tensor of shape (num_env, 1), where each element indicates
whether the reference motion has ended for the corresponding environment.
Returns:
torch.tensor: A boolean tensor of shape (num_env, 1) where `T... | terminate_by_reference_motion_length | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/termination.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/termination.py | Apache-2.0 |
def terminate_by_reference_motion_distance(
training_mode: bool,
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
max_ref_motion_dist: float,
in_recovery: torch.Tensor | None,
mask: torch.Tensor,
) -> torch.Tensor:
"""
Determines if the distance between current body positio... |
Determines if the distance between current body positions and reference motion positions exceeds the allowed threshold.
Args:
is_training (bool): Flag indicating if the system is in training mode.
body_state (BodyState): Current state of the humanoid bodies.
ref_motion_state (Reference... | terminate_by_reference_motion_distance | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/termination.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/termination.py | Apache-2.0 |
def assert_equal(lhs: any, rhs: any, name: str):
"""Assert that 2 values are equal and provide a useful error if not.
Args:
lhs: First value to compare
rhs: Second value to compare
name: Description of what is being compared, used in error messages
"""
# Handle dictionary compar... | Assert that 2 values are equal and provide a useful error if not.
Args:
lhs: First value to compare
rhs: Second value to compare
name: Description of what is being compared, used in error messages
| assert_equal | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/util.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/util.py | Apache-2.0 |
def _assert_dicts_equal(lhs: dict, rhs: dict, name: str):
"""Compare two dictionaries and raise assertion error with details if not equal."""
lhs_keys = set(lhs.keys())
rhs_keys = set(rhs.keys())
# Check for missing keys
only_in_lhs = lhs_keys - rhs_keys
only_in_rhs = rhs_keys - lhs_keys
#... | Compare two dictionaries and raise assertion error with details if not equal. | _assert_dicts_equal | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/util.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/util.py | Apache-2.0 |
def _get_differing_values(lhs: dict, rhs: dict, common_keys: set) -> dict:
"""Compare values for common keys between two dicts, return dict of differences."""
diff_values = {}
for key in common_keys:
if isinstance(lhs[key], (int, float)) and isinstance(rhs[key], (int, float)):
if abs(lhs... | Compare values for common keys between two dicts, return dict of differences. | _get_differing_values | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/util.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/util.py | Apache-2.0 |
def _assert_numbers_equal(lhs: float, rhs: float, name: str):
"""Assert that two numbers are equal within a small tolerance."""
if abs(lhs - rhs) >= 1e-6:
raise AssertionError(f"{name}: Values are not equal within tolerance: {lhs} != {rhs}") | Assert that two numbers are equal within a small tolerance. | _assert_numbers_equal | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/util.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/util.py | Apache-2.0 |
def _assert_values_equal(lhs: any, rhs: any, name: str):
"""Assert that two non-numeric values are exactly equal."""
if lhs != rhs:
raise AssertionError(f"{name}: Values are not equal: {lhs} != {rhs}") | Assert that two non-numeric values are exactly equal. | _assert_values_equal | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/util.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/util.py | Apache-2.0 |
def get_matching_indices(patterns: list[str], values: list[str], allow_empty: bool = False) -> list[int]:
"""Get indices of all elements in values that match any of the regex patterns."""
all_indices = set()
for pattern in patterns:
regex = re.compile(pattern)
indices = [i for i, v in enumer... | Get indices of all elements in values that match any of the regex patterns. | get_matching_indices | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/util.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/util.py | Apache-2.0 |
def create_dummy_warp_module():
"""Creates a dummy 'warp' module with necessary attributes and submodules.
This function is created because the 'warp' module can only be properly imported
when Isaac Sim is also launched, which is not always required when running unit
tests or simulations with other sim... | Creates a dummy 'warp' module with necessary attributes and submodules.
This function is created because the 'warp' module can only be properly imported
when Isaac Sim is also launched, which is not always required when running unit
tests or simulations with other simulators. By creating a dummy module, we... | create_dummy_warp_module | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/__init__.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/__init__.py | Apache-2.0 |
def __init__(self, num_envs: int, device: torch.device, entry_length: int, max_entries: int):
"""
Args:
env (EnvironmentWrapper): An instance of the environment wrapper.
entry_length (int): The length of a single entry.
max_entries (int): The maximum number of entries... |
Args:
env (EnvironmentWrapper): An instance of the environment wrapper.
entry_length (int): The length of a single entry.
max_entries (int): The maximum number of entries to keep in the history.
| __init__ | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_history.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_history.py | Apache-2.0 |
def update(self, obs_dict: dict[str, torch.Tensor]):
"""Updates the history with a new entry.
Args:
obs_dict (dict[str, torch.Tensor]): A dictionary containing the latest student observations.
Expected keys are "distilled_robot_state" and "distilled_last_action".
Ra... | Updates the history with a new entry.
Args:
obs_dict (dict[str, torch.Tensor]): A dictionary containing the latest student observations.
Expected keys are "distilled_robot_state" and "distilled_last_action".
Raises:
AssertionError: If the new entry does not matc... | update | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_history.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_history.py | Apache-2.0 |
def reset(self, env_ids: torch.Tensor | None):
"""Resets the history for specified environments.
Args:
env_ids (torch.Tensor | None): A tensor containing the IDs of the environments to reset.
If None, all environments are reset.
Example:
... | Resets the history for specified environments.
Args:
env_ids (torch.Tensor | None): A tensor containing the IDs of the environments to reset.
If None, all environments are reset.
Example:
history.reset(None) # Resets history for all e... | reset | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_history.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_history.py | Apache-2.0 |
def compute_distilled_imitation_observations(
ref_motion_state: ReferenceMotionState,
body_state: BodyState,
mask: torch.Tensor,
ref_episodic_offset: torch.Tensor | None,
) -> torch.Tensor:
"""Computes the reference goal state used in the observation of the student."""
# First we get all referen... | Computes the reference goal state used in the observation of the student. | compute_distilled_imitation_observations | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_observations.py | Apache-2.0 |
def compute_kinematic_command(
ref_motion_state: ReferenceMotionState,
body_state: BodyState,
ref_episodic_offset: torch.Tensor | None,
) -> torch.Tensor:
"""
Compute the link position command used in the observation of the student.
The link position command consists of:
- the delta between... |
Compute the link position command used in the observation of the student.
The link position command consists of:
- the delta between the current root position and the target link positions
| compute_kinematic_command | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_observations.py | Apache-2.0 |
def compute_joint_command(ref_motion_state: ReferenceMotionState, body_state: BodyState) -> torch.Tensor:
"""
Compute the joint command used in the observation of the student.
The joint reference is the delta between the current joint position/velocity and the target
joint position/velocity.
"""
... |
Compute the joint command used in the observation of the student.
The joint reference is the delta between the current joint position/velocity and the target
joint position/velocity.
| compute_joint_command | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_observations.py | Apache-2.0 |
def compute_root_command(ref_motion_state: ReferenceMotionState, body_state: BodyState) -> torch.Tensor:
"""
Compute the root command used in the observation of the student.
The root command consists of
- the target root velocity (in the root frame)
- the target root roll and pitch
- the delta ... |
Compute the root command used in the observation of the student.
The root command consists of
- the target root velocity (in the root frame)
- the target root roll and pitch
- the delta between the current root yaw and the target root yaw
- the root height.
| compute_root_command | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_observations.py | Apache-2.0 |
def compute_distilled_robot_state_observation(
body_state: BodyState,
base_id: int,
projected_gravity: torch.Tensor,
local_base_ang_velocity: torch.Tensor | None = None,
) -> torch.Tensor:
"""Root body state in the robot root frame."""
# for normalization
joint_pos = body_state.joint_pos.clo... | Root body state in the robot root frame. | compute_distilled_robot_state_observation | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/student_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/student_observations.py | Apache-2.0 |
def compute_teacher_observations(
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
tracked_body_ids: list[int],
last_actions: torch.Tensor,
ref_episodic_offset: torch.Tensor | None = None,
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
"""Computes the observations for the teach... | Computes the observations for the teacher model based on the current body state, reference motion state,
and other relevant parameters.
Args:
body_state (BodyState): The current state of the humanoid bodies.
ref_motion_state (ReferenceMotionState): The reference motion state for the humanoid to... | compute_teacher_observations | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/teacher_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/teacher_observations.py | Apache-2.0 |
def compute_robot_state_observation(
body_state: BodyState,
) -> torch.Tensor:
"""Computes the robot state observation in the robot root frame.
Args:
body_state (BodyState): The current state of the humanoid bodies.
"""
# for normalization
root_pos = body_state.body_pos_extend[:, 0, :].... | Computes the robot state observation in the robot root frame.
Args:
body_state (BodyState): The current state of the humanoid bodies.
| compute_robot_state_observation | python | NVlabs/HOVER | neural_wbc/core/neural_wbc/core/observations/teacher_observations.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/neural_wbc/core/observations/teacher_observations.py | Apache-2.0 |
def test_zero_metrics(self):
"""
Test the metrics when all bodies have zero error.
"""
(
success_ids,
episode,
episode_gt,
) = self._create_data()
self.metrics.update(
success_ids=success_ids,
episode=episode,
... |
Test the metrics when all bodies have zero error.
| test_zero_metrics | python | NVlabs/HOVER | neural_wbc/core/tests/test_evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/tests/test_evaluator.py | Apache-2.0 |
def test_offset_metrics(self):
"""
Test the metrics when all bodies have only a translation error to GT.
Then we expect the global error to b the translation, the local error should be 0.
"""
(
success_ids,
episode,
episode_gt,
) = sel... |
Test the metrics when all bodies have only a translation error to GT.
Then we expect the global error to b the translation, the local error should be 0.
| test_offset_metrics | python | NVlabs/HOVER | neural_wbc/core/tests/test_evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/tests/test_evaluator.py | Apache-2.0 |
def test_masked_metrics(self):
"""
Test the metrics when only the masked bodies have an offset. We expect the masked error to
be greater than the unmasked error.
"""
(
success_ids,
episode,
episode_gt,
) = self._create_data()
o... |
Test the metrics when only the masked bodies have an offset. We expect the masked error to
be greater than the unmasked error.
| test_masked_metrics | python | NVlabs/HOVER | neural_wbc/core/tests/test_evaluator.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/core/tests/test_evaluator.py | Apache-2.0 |
def get_data_path(rel_path: str) -> str:
"""
Get the absolute path to a data file located in the 'neural_wbc/data/data' directory.
Args:
rel_path (str): The relative path to the data file from the data directory.
Returns:
str: The absolute path to the data file.
Raises:
Fi... |
Get the absolute path to a data file located in the 'neural_wbc/data/data' directory.
Args:
rel_path (str): The relative path to the data file from the data directory.
Returns:
str: The absolute path to the data file.
Raises:
FileNotFoundError: If the specified file does not ... | get_data_path | python | NVlabs/HOVER | neural_wbc/data/neural_wbc/data/__init__.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/data/neural_wbc/data/__init__.py | Apache-2.0 |
def __init__(
self,
cfg: Any,
) -> None:
"""Initializes a new instance of the H1SDKWrapper class.
Args:
cfg (Any): The configuration object.
"""
self.cfg = cfg
self._low_cmd = unitree_go_msg_dds__LowCmd_()
self._low_cmd_lock = RLock()
... | Initializes a new instance of the H1SDKWrapper class.
Args:
cfg (Any): The configuration object.
| __init__ | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def _cmd_publisher(self):
"""Publishes the low-level command to the SDK."""
with self._low_cmd_lock:
if not self._cmd_received:
return
self._lowcmd_publisher.Write(self._low_cmd) | Publishes the low-level command to the SDK. | _cmd_publisher | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def _init_sdk(self):
"""Initializes the SDK for the H1 robot.
This function initializes the SDK using the required configuration.
Args:
None
"""
ChannelFactoryInitialize(0, self.cfg.network_interface)
# Create publisher
self._lowcmd_publisher = Chann... | Initializes the SDK for the H1 robot.
This function initializes the SDK using the required configuration.
Args:
None
| _init_sdk | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def publish_joint_position_cmd(self, cmd_joint_positions: np.ndarray):
"""Publishes joint position commands to the low-level command publisher.
Args:
cmd_joint_positions (np.ndarray): An array of joint positions to be published.
"""
with self._low_cmd_lock:
for j... | Publishes joint position commands to the low-level command publisher.
Args:
cmd_joint_positions (np.ndarray): An array of joint positions to be published.
| publish_joint_position_cmd | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def publish_joint_torque_cmd(self, cmd_joint_torques: np.ndarray):
"""Publishes joint torque commands to the low-level command publisher.
Args:
cmd_joint_torques (np.ndarray): An array of joint torques to be published.
"""
with self._low_cmd_lock:
for joint_idx i... | Publishes joint torque commands to the low-level command publisher.
Args:
cmd_joint_torques (np.ndarray): An array of joint torques to be published.
| publish_joint_torque_cmd | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def reset(self, desired_joint_positions: np.ndarray | None = None) -> None:
"""Resets the robot to the given joint positions.
Args:
desired_joint_positions (np.ndarray | None, optional): An array of desired joint positions.
Defaults to None: The robot will be reset to the 0 ... | Resets the robot to the given joint positions.
Args:
desired_joint_positions (np.ndarray | None, optional): An array of desired joint positions.
Defaults to None: The robot will be reset to the 0 initial pose.
| reset | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def _init_cmd(self):
"""Initializes the low-level command.
This function sets the values of the low-level command based on the configuration.
"""
self._low_cmd.head[0] = self.cfg.head0
self._low_cmd.head[1] = self.cfg.head1
self._low_cmd.level_flag = self.cfg.level_flag
... | Initializes the low-level command.
This function sets the values of the low-level command based on the configuration.
| _init_cmd | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def state_handler(self, msg: LowState_):
"""
Update the joint positions and velocities based on the low state message.
Saves them as per the joint sequence of isaac lab and mujoco.
Args:
msg (LowState_): The low state message containing the motor states.
"""
... |
Update the joint positions and velocities based on the low state message.
Saves them as per the joint sequence of isaac lab and mujoco.
Args:
msg (LowState_): The low state message containing the motor states.
| state_handler | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/h1_sdk_wrapper.py | Apache-2.0 |
def update(self, obs_dict: dict[str, torch.Tensor]) -> None:
"""Update the underlying model based on the observations from the environment/real robot.
Args:
obs_dict (dict[str, torch.Tensor]): A dictionary containing the latest robot observations.
"""
# TODO (pulkitg): Chang... | Update the underlying model based on the observations from the environment/real robot.
Args:
obs_dict (dict[str, torch.Tensor]): A dictionary containing the latest robot observations.
| update | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | Apache-2.0 |
def reset(self, **kwargs) -> None:
"""Resets the wrapper
Args:
kwargs (dict[str, Any], optional): key-word arguments to pass to underlying models. Defaults to None.
"""
qpos = kwargs.get("qpos")
qvel = kwargs.get("qvel")
self._kinematic_model.reset(qpos=qpos,... | Resets the wrapper
Args:
kwargs (dict[str, Any], optional): key-word arguments to pass to underlying models. Defaults to None.
| reset | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | Apache-2.0 |
def get_joint_ids(self, joint_names: list[str] | None = None) -> dict[str, int]:
"""Get the IDs of all joints in the model, indexed after removing the free joint.
Args:
joint_names (list[str] | None, optional): Names of the joints. Defaults to None.
Returns:
dict[str, i... | Get the IDs of all joints in the model, indexed after removing the free joint.
Args:
joint_names (list[str] | None, optional): Names of the joints. Defaults to None.
Returns:
dict[str, int]: Mapping from joint name to joint id.
| get_joint_ids | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | Apache-2.0 |
def get_base_projected_gravity(self, base_name: str = "torso_link") -> torch.Tensor:
"""Get the projection of the gravity vector to the base frame
Args:
base_name (str, optional): Name of the base. Defaults to 'torso_link'.
Returns:
torch.Tensor: Projection of the gravi... | Get the projection of the gravity vector to the base frame
Args:
base_name (str, optional): Name of the base. Defaults to 'torso_link'.
Returns:
torch.Tensor: Projection of the gravity vector to the base frame
| get_base_projected_gravity | python | NVlabs/HOVER | neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/hw_wrappers/unitree_h1.py | Apache-2.0 |
def test_get_base_projected_gravity_upright(self):
"""Test gravity projection when robot is upright"""
# Set upright orientation (identity quaternion)
self.robot._h1_sdk.torso_orientation = np.array([1.0, 0.0, 0.0, 0.0])
# Call the function
gravity = self.robot.get_base_projecte... | Test gravity projection when robot is upright | test_get_base_projected_gravity_upright | python | NVlabs/HOVER | neural_wbc/hw_wrappers/tests/test_unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/tests/test_unitree_h1.py | Apache-2.0 |
def test_get_base_projected_gravity_rotated_90x(self):
"""Test gravity projection when robot is rotated 90 degrees around x-axis"""
# Create quaternion for 90-degree rotation around x-axis
quat = R.from_euler("x", 90, degrees=True).as_quat(scalar_first=True)
# Convert to scalar-first for... | Test gravity projection when robot is rotated 90 degrees around x-axis | test_get_base_projected_gravity_rotated_90x | python | NVlabs/HOVER | neural_wbc/hw_wrappers/tests/test_unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/tests/test_unitree_h1.py | Apache-2.0 |
def test_get_base_projected_gravity_rotated_45y(self):
"""Test gravity projection when robot is rotated 45 degrees around y-axis"""
# Create quaternion for 45-degree rotation around y-axis
quat = R.from_euler("y", 45, degrees=True).as_quat(scalar_first=True)
# Convert to scalar-first for... | Test gravity projection when robot is rotated 45 degrees around y-axis | test_get_base_projected_gravity_rotated_45y | python | NVlabs/HOVER | neural_wbc/hw_wrappers/tests/test_unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/tests/test_unitree_h1.py | Apache-2.0 |
def test_get_base_projected_gravity_inverted(self):
"""Test gravity projection when robot is completely inverted"""
# Create quaternion for 180-degree rotation around x-axis
quat = R.from_euler("x", 180, degrees=True).as_quat(scalar_first=True)
self.robot._h1_sdk.torso_orientation = quat... | Test gravity projection when robot is completely inverted | test_get_base_projected_gravity_inverted | python | NVlabs/HOVER | neural_wbc/hw_wrappers/tests/test_unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/tests/test_unitree_h1.py | Apache-2.0 |
def test_get_base_projected_gravity_rotated_90z(self):
"""Test gravity projection when robot is rotated 90 degrees around z-axis"""
# Create quaternion for 90-degree rotation around z-axis
quat = R.from_euler("z", 90, degrees=True).as_quat(scalar_first=True)
self.robot._h1_sdk.torso_orie... | Test gravity projection when robot is rotated 90 degrees around z-axis | test_get_base_projected_gravity_rotated_90z | python | NVlabs/HOVER | neural_wbc/hw_wrappers/tests/test_unitree_h1.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/hw_wrappers/tests/test_unitree_h1.py | Apache-2.0 |
def __init__(
self,
args_cli: argparse.Namespace,
env_cfg: NeuralWBCEnvCfg,
custom_config: dict[str, Any] | None = None,
demo_mode: bool = False,
):
"""
Args:
args_cli: command line arguments
custom_config: custom configuration for the ... |
Args:
args_cli: command line arguments
custom_config: custom configuration for the environment
demo_mode (bool): whether to run in demo mode, without need for student policy
Note:
The *demo_mode* allows setting of joint manually for e.g. debugging purpos... | __init__ | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/deployment_player.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/deployment_player.py | Apache-2.0 |
def play_once(self, ext_actions: torch.Tensor | None = None):
"""Advances the environment one time step after generating observations"""
obs = self.env.get_observations()
with torch.inference_mode():
if ext_actions is not None:
actions = ext_actions
else:
... | Advances the environment one time step after generating observations | play_once | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/deployment_player.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/deployment_player.py | Apache-2.0 |
def _update_env_cfg(self, env_cfg, custom_config: dict[str, Any]):
"""Update the default environment config if user provides a custom config. See readme for detailed usage."""
for key, value in custom_config.items():
obj = env_cfg
attrs = key.split(".")
try:
... | Update the default environment config if user provides a custom config. See readme for detailed usage. | _update_env_cfg | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/deployment_player.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/deployment_player.py | Apache-2.0 |
def __init__(
self,
cfg: NeuralWBCEnvCfg,
render_mode: str | None = None,
device=torch.device("cuda" if torch.cuda.is_available() else "cpu"),
) -> None:
"""Initializes the environment.
Args:
cfg (NeuralWBCEnvCfgH1): Environment configuration.
... | Initializes the environment.
Args:
cfg (NeuralWBCEnvCfgH1): Environment configuration.
render_mode (str | None, optional): Render mode. Defaults to None.
device (torch.device, optional): torch device to use. Defaults to 'cuda'.
| __init__ | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def step(self, actions: torch.Tensor) -> tuple[dict, torch.Tensor, torch.Tensor, dict]:
"""Performs one step of simulation.
Args:
actions (torch.Tensor): Actions of shape (num_envs, num_actions)
Returns:
* Observations as a dict or an object.
* Rewards of sh... | Performs one step of simulation.
Args:
actions (torch.Tensor): Actions of shape (num_envs, num_actions)
Returns:
* Observations as a dict or an object.
* Rewards of shape (num_envs,)
* "Dones": a boolean tensor representing termination of an episode in e... | step | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _pre_physics_step(self, actions: torch.Tensor):
"""Prepares the robot for the next physics step.
Args:
actions (torch.Tensor): Actions of shape (num_envs, num_actions)
"""
# update history
if self.cfg.mode.is_distill_mode():
obs_dic = self._compute_ob... | Prepares the robot for the next physics step.
Args:
actions (torch.Tensor): Actions of shape (num_envs, num_actions)
| _pre_physics_step | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def reset(self, env_ids: list | torch.Tensor | None = None):
"""Resets environment specified by env_ids.
Args:
env_ids (list | torch.Tensor | None, optional): Environment ids. Defaults to None.
"""
env_ids = self._env_ids if env_ids is None else env_ids
self._reset_... | Resets environment specified by env_ids.
Args:
env_ids (list | torch.Tensor | None, optional): Environment ids. Defaults to None.
| reset | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _reset_robot_state_and_motion(self, env_ids: list | torch.Tensor | None = None):
"""Resets the robot state and the reference motion.
Args:
env_ids (list | torch.Tensor | None, optional): Environment ids. Defaults to None.
"""
env_ids = env_ids if env_ids is not None else... | Resets the robot state and the reference motion.
Args:
env_ids (list | torch.Tensor | None, optional): Environment ids. Defaults to None.
| _reset_robot_state_and_motion | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _update_robot_default_state(self):
"""Loads the default initial state of the robot."""
# Read the default values from the mujoco data first.
robot_init_state = self.cfg.robot_init_state
state_update_dict = {}
root_pos_offset = 3
if "base_pos" in robot_init_state:
... | Loads the default initial state of the robot. | _update_robot_default_state | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _apply_action(self):
"""Applies the current action to the robot."""
actions_scaled = self.actions * self.cfg.action_scale + self.default_joint_pos
self._processed_action = self._control_fn(self, actions_scaled)
self._processed_action = self._apply_limits(self._processed_action)
... | Applies the current action to the robot. | _apply_action | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _compose_body_state(
self, extend_body_pos: torch.Tensor | None = None, extend_body_parent_ids: list[int] | None = None
) -> BodyState:
"""Compose the Body state from the robot/articulation data.
Args:
extend_body_pos (torch.Tensor | None, optional): Extended body positions.... | Compose the Body state from the robot/articulation data.
Args:
extend_body_pos (torch.Tensor | None, optional): Extended body positions. Defaults to None.
extend_body_parent_ids (list[int] | None, optional): Extended body parent ids. Defaults to None.
Returns:
BodyS... | _compose_body_state | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _compute_observations(self):
"""Compute the observations
Returns:
dict: Observations
"""
self._robot.update({})
# NOTE: not including the privileged observations so far
obs_dict = {}
ref_motion_state = self.reference_motion_manager.get_state_from... | Compute the observations
Returns:
dict: Observations
| _compute_observations | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
"""Get the done flags.
Returns:
tuple[torch.Tensor, torch.Tensor]: Should terminate flags and time out flags
"""
time_out = self.episode_length_buf >= self.max_episode_length - 1
ref_motion_state = self.refe... | Get the done flags.
Returns:
tuple[torch.Tensor, torch.Tensor]: Should terminate flags and time out flags
| _get_dones | python | NVlabs/HOVER | neural_wbc/inference_env/inference_env/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/inference_env/inference_env/neural_wbc_env.py | Apache-2.0 |
def build_body_state(
data: ArticulationData,
root_id: int,
body_ids: list[int] | None = None,
joint_ids: list[int] | None = None,
extend_body_pos: torch.Tensor | None = None,
extend_body_parent_ids: list[int] | None = None,
) -> BodyState:
"""Creates a body state from Isaac Lab articulation... | Creates a body state from Isaac Lab articulation data.
Args:
data (ArticulationData): Articulation data containing robot's body and joint states.
body_ids (list[int] | None, optional): The desired order of bodies. If not, the order in body states is preserved.
... | build_body_state | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/body_state.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/body_state.py | Apache-2.0 |
def _reset_mask(self, env_ids: torch.Tensor | None = None):
"""
Reset the mask used to select which parts of the reference state should
be tracked. Every environment uses a different mask.
"""
if self.cfg.mode.is_distill_mode() or self.cfg.mode.is_distill_test_mode():
... |
Reset the mask used to select which parts of the reference state should
be tracked. Every environment uses a different mask.
| _reset_mask | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/neural_wbc_env.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/neural_wbc_env.py | Apache-2.0 |
def convert_tensors_and_slices_to_serializable(d):
"""Recursively convert torch tensors to lists and handle slice objects in a nested dictionary, including lists and tuples."""
if isinstance(d, dict):
return {k: convert_tensors_and_slices_to_serializable(v) for k, v in d.items()}
elif isinstance(d, ... | Recursively convert torch tensors to lists and handle slice objects in a nested dictionary, including lists and tuples. | convert_tensors_and_slices_to_serializable | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/utils.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/utils.py | Apache-2.0 |
def convert_serializable_to_tensors_and_slices(d):
"""Recursively convert lists back to torch tensors and dictionaries back to slice objects."""
if isinstance(d, dict):
if "__type__" in d:
if d["__type__"] == "tensor":
return torch.tensor(d["data"])
elif d["__type... | Recursively convert lists back to torch tensors and dictionaries back to slice objects. | convert_serializable_to_tensors_and_slices | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/utils.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/utils.py | Apache-2.0 |
def randomize_body_com(
env: NeuralWBCEnv,
env_ids: torch.Tensor | None,
asset_cfg: SceneEntityCfg,
distribution_params: tuple[float, float] | tuple[torch.Tensor, torch.Tensor],
operation: Literal["add", "abs", "scale"],
distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform",
):... | Randomize the com of the bodies by adding, scaling or setting random values.
This function allows randomizing the center of mass of the bodies of the asset. The function samples random values from the
given distribution parameters and adds, scales or sets the values into the physics simulation based on the ope... | randomize_body_com | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | Apache-2.0 |
def randomize_pd_scale(
env: NeuralWBCEnv,
env_ids: torch.Tensor | None,
distribution_params: tuple[float, float],
operation: Literal["add", "abs", "scale"],
distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform",
):
"""Randomize the scale of the pd gains by adding, scaling or s... | Randomize the scale of the pd gains by adding, scaling or setting random values.
This function allows randomizing the scale of the pd gain. The function samples random values from the
given distribution parameters and adds, or sets the values into the simulation based on the operation.
| randomize_pd_scale | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | Apache-2.0 |
def randomize_action_noise_range(
env: NeuralWBCEnv,
env_ids: torch.Tensor | None,
distribution_params: tuple[float, float],
operation: Literal["add", "abs", "scale"],
distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform",
):
"""Randomize the sample range of the added action no... | Randomize the sample range of the added action noise by adding, scaling or setting random values.
This function allows randomizing the scale of the sample range of the added action noise. The function
samples random values from the given distribution parameters and adds, scales or sets the values into the
... | randomize_action_noise_range | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | Apache-2.0 |
def randomize_motion_ref_xyz(
env: NeuralWBCEnv,
env_ids: torch.Tensor | None,
distribution_params: tuple[float, float] | tuple[torch.Tensor, torch.Tensor],
operation: Literal["add", "abs", "scale"],
distribution: Literal["uniform", "log_uniform", "gaussian"] = "uniform",
):
"""Randomize the mot... | Randomize the motion reference x,y,z offset by adding, scaling or setting random values.
This function allows randomizing the motion reference x,y,z offset. The function samples
random values from the given distribution parameters and adds, scales or sets the values into the
simulation based on the operati... | randomize_motion_ref_xyz | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | Apache-2.0 |
def reset_robot_state_and_motion(
env: NeuralWBCEnv,
env_ids: torch.Tensor,
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Reset the robot and reference motion.
The full reset percess is:
1. Reset the robot root state to the origin position of its terrain.
2. Reset motion refere... | Reset the robot and reference motion.
The full reset percess is:
1. Reset the robot root state to the origin position of its terrain.
2. Reset motion reference to random time step.
3. Moving the motion reference trajectory to the current robot position.
4. Reset the robot joint to reference motion'... | reset_robot_state_and_motion | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | Apache-2.0 |
def update_curriculum(
env: NeuralWBCEnv,
env_ids: torch.Tensor | None,
penalty_level_down_threshold: float,
penalty_level_up_threshold: float,
penalty_level_degree: float,
min_penalty_scale: float,
max_penalty_scale: float,
num_compute_average_epl: float,
):
"""
Update average e... |
Update average episode length and in turn penalty curriculum.
This function is rewritten from update_average_episode_length of legged_gym.
When the policy is not able to track the motions, we reduce the penalty to help it explore more actions. When the
policy is able to track the motions, we increase... | update_curriculum | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/events/events.py | Apache-2.0 |
def compute_reward(
self,
articulation_data: ArticulationData,
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
previous_actions: torch.Tensor,
actions: torch.Tensor,
reset_buf: torch.Tensor,
timeout_buf: torch.Tensor,
penalty_scale: ... |
Computes the total reward for the given environment and reference motion state.
This function calculates the weighted sum of individual rewards specified in the environment's
reward configuration. Each reward is computed using a corresponding reward function defined
within the class. T... | compute_reward | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | Apache-2.0 |
def reward_track_joint_positions(
self,
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
**kwargs,
) -> torch.Tensor:
"""
Computes the reward for tracking the joint positions of the reference motion.
This function is rewritten from _reward_teleo... |
Computes the reward for tracking the joint positions of the reference motion.
This function is rewritten from _reward_teleop_selected_joint_position of legged_gym.
Returns:
torch.Tensor: A float tensor of shape (num_envs) representing the computed reward for each environment.
... | reward_track_joint_positions | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | Apache-2.0 |
def reward_track_joint_velocities(
self,
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
**kwargs,
) -> torch.Tensor:
"""
Computes the reward for tracking the joint velocities of the reference motion.
This function is rewritten from _reward_tel... |
Computes the reward for tracking the joint velocities of the reference motion.
This function is rewritten from _reward_teleop_selected_joint_vel of legged_gym.
Returns:
torch.Tensor: A float tensor of shape (num_envs) representing the computed reward for each environment.
| reward_track_joint_velocities | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | Apache-2.0 |
def reward_track_body_velocities(
self,
body_state: BodyState,
ref_motion_state: ReferenceMotionState,
**kwargs,
) -> torch.Tensor:
"""
Computes a reward based on the difference between the body's velocity and the reference motion's velocity.
This function is... |
Computes a reward based on the difference between the body's velocity and the reference motion's velocity.
This function is rewritten from _reward_teleop_body_vel of legged_gym.
Returns:
torch.Tensor: A float tensor of shape (num_envs) representing the computed reward for each env... | reward_track_body_velocities | python | NVlabs/HOVER | neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.