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 reward_track_body_angular_velocities( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between the body's angular velocity and the reference motion's angular vel...
Computes a reward based on the difference between the body's angular velocity and the reference motion's angular velocity. This function is rewritten from _reward_teleop_body_ang_vel of legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the ...
reward_track_body_angular_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_position_extended( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between the body's extended position and the reference motion's extended po...
Computes a reward based on the difference between the body's extended position and the reference motion's extended position. This function is rewritten from _reward_teleop_body_position_extend of legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) represe...
reward_track_body_position_extended
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_position_vr_key_points( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between selected key points of the body's extended position and the re...
Computes a reward based on the difference between selected key points of the body's extended position and the reference motion's extended position. This function is rewritten from _reward_teleop_body_position_vr_3keypoints of legged_gym. Returns: torch.Tensor: A float tens...
reward_track_body_position_vr_key_points
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_rotation( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between the body's rotation and the reference motion's rotation. This function is r...
Computes a reward based on the difference between the body's rotation and the reference motion's rotation. This function is rewritten from _reward_teleop_body_rotation of legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed reward for eac...
reward_track_body_rotation
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 penalize_torques( self, articulation_data: ArticulationData, **kwargs, ) -> torch.Tensor: """ Computes the penalty on applied torques to minimize energy consumption. This function is adapted from _reward_torques in legged_gym. Returns: torch....
Computes the penalty on applied torques to minimize energy consumption. This function is adapted from _reward_torques in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_torques
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 penalize_joint_accelerations( self, articulation_data: ArticulationData, **kwargs, ) -> torch.Tensor: """ Computes the penalty on joint acceleration of each motor. This function is adapted from _reward_dof_acc in legged_gym. Returns: torch.Te...
Computes the penalty on joint acceleration of each motor. This function is adapted from _reward_dof_acc in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_joint_accelerations
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 penalize_joint_velocities( self, articulation_data: ArticulationData, **kwargs, ) -> torch.Tensor: """ Computes the penalty on joint velocity of each motor. This function is adapted from _reward_dof_vel in legged_gym. Returns: torch.Tensor: A...
Computes the penalty on joint velocity of each motor. This function is adapted from _reward_dof_vel in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_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 penalize_lower_body_action_changes( self, previous_actions: torch.Tensor, actions: torch.Tensor, **kwargs, ) -> torch.Tensor: """ Computes the penalty for action changes in the lower body. This function is adapted from _reward_lower_action_rate in legged_...
Computes the penalty for action changes in the lower body. This function is adapted from _reward_lower_action_rate in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_lower_body_action_changes
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 penalize_upper_body_action_changes( self, previous_actions: torch.Tensor, actions: torch.Tensor, **kwargs, ) -> torch.Tensor: """ Computes the penalty for action changes in the upper body. This function is adapted from _reward_upper_action_rate in legged_...
Computes the penalty for action changes in the upper body. This function is adapted from _reward_upper_action_rate in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_upper_body_action_changes
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 penalize_early_termination(self, reset_buf: torch.Tensor, timeout_buf: torch.Tensor, **kwargs): """ Computes the penalty for episodes that terminate before timeout. This function is adapted from `_reward_termination` in `legged_gym`. Returns: torch.Tensor: A tensor of s...
Computes the penalty for episodes that terminate before timeout. This function is adapted from `_reward_termination` in `legged_gym`. Returns: torch.Tensor: A tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_early_termination
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 penalize_stumble(self, **kwargs): """ Computes the penalty for stumbling. This function is adapted from _reward_stumble in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment. """ f...
Computes the penalty for stumbling. This function is adapted from _reward_stumble in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_stumble
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 penalize_slippage(self, body_state: BodyState, **kwargs): """ Computes the penalty for slippage. This function is adapted from _reward_slippage in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environmen...
Computes the penalty for slippage. This function is adapted from _reward_slippage in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_slippage
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 penalize_feet_orientation(self, body_state: BodyState, **kwargs): """ Computes the penalty on feet orientation to make no x and y projected gravity. This function is adapted from _reward_feet_ori in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) r...
Computes the penalty on feet orientation to make no x and y projected gravity. This function is adapted from _reward_feet_ori in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_feet_orientation
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 penalize_feet_air_time(self, ref_motion_state: ReferenceMotionState, **kwargs): """ Computes the penalty for the time that the feet are in the air before the newest contact with the terrain. This function is adapted from _reward_feet_air_time_teleop in legged_gym. Returns: ...
Computes the penalty for the time that the feet are in the air before the newest contact with the terrain. This function is adapted from _reward_feet_air_time_teleop in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each...
penalize_feet_air_time
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 penalize_both_feet_in_air(self, **kwargs): """ Computes the penalty for both feet being in the air. This function is adapted from _reward_in_the_air in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each envir...
Computes the penalty for both feet being in the air. This function is adapted from _reward_in_the_air in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_both_feet_in_air
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 penalize_orientation(self, articulation_data: ArticulationData, **kwarg): """ Computes the penalty based on a non-flat base orientation. This function is adapted from _reward_orientation in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representi...
Computes the penalty based on a non-flat base orientation. This function is adapted from _reward_orientation in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_orientation
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 penalize_max_feet_height_before_contact(self, body_state: BodyState, **kwargs): """ Computes the penalty based on the maximum height of the feet in the air before the current contact. This function is adapted from _reward_feet_max_height_for_this_air in legged_gym. Returns: ...
Computes the penalty based on the maximum height of the feet in the air before the current contact. This function is adapted from _reward_feet_max_height_for_this_air in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for eac...
penalize_max_feet_height_before_contact
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 deep_compare_dicts(dict1, dict2): """Recursively compare two dictionaries, including torch tensors.""" if dict1.keys() != dict2.keys(): return False for key in dict1: value1 = dict1[key] value2 = dict2[key] if isinstance(value1, dict) and isinstance(value2, dict): ...
Recursively compare two dictionaries, including torch tensors.
deep_compare_dicts
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/tests/test_neural_wbc_env_cfg.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/tests/test_neural_wbc_env_cfg.py
Apache-2.0
def position_pd_control(env: NeuralWBCEnv, pos_actions: torch.Tensor, joint_ids=None): """Calculates the PD control torque based on the network output position actions""" robot = env.robot joint_pos = robot.joint_positions joint_vel = robot.joint_velocities if joint_ids: joint_pos = joint_p...
Calculates the PD control torque based on the network output position actions
position_pd_control
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/control.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/control.py
Apache-2.0
def __init__( self, model_path: str, sim_dt: float = 0.005, enable_viewer: bool = False, num_instances: int = 1, device=torch.device("cuda" if torch.cuda.is_available() else "cpu"), ) -> None: """Initialize the underlying mujoco simulator Args: ...
Initialize the underlying mujoco simulator Args: model_path: Path to the Mujoco model xml file sim_dt: Simulation timestep enable_viewer: Whether to enable the viewer num_instances: Number of instances to simulate device: torch device to use for the t...
__init__
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def joint_names(self) -> list[str]: """Get the names of all joints in the model except the free floating joint. Returns: list[str]: List of joint names """ offset = 0 if self.has_free_joint: offset = 1 # base/world joint return [get_entity_name(s...
Get the names of all joints in the model except the free floating joint. Returns: list[str]: List of joint names
joint_names
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def joint_positions(self) -> torch.Tensor: """Get the joint positions of the robot as tensor Returns: torch.Tensor: Tensor of joint positions """ return ( torch.from_numpy(self._data.qpos[self.joint_pos_offset :].copy()) .to(dtype=torch.float32, devic...
Get the joint positions of the robot as tensor Returns: torch.Tensor: Tensor of joint positions
joint_positions
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def joint_velocities(self) -> torch.Tensor: """Get the joint velocities of the robot as tensor Returns: torch.Tensor: Tensor of joint velocities """ return ( torch.from_numpy(self._data.qvel[self.joint_vel_offset :].copy()) .to(dtype=torch.float32, de...
Get the joint velocities of the robot as tensor Returns: torch.Tensor: Tensor of joint velocities
joint_velocities
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def body_positions(self) -> torch.Tensor: """Get the body positions of the robot as tensor Returns: torch.Tensor: Tensor of body positions """ # NOTE: Global frame, https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html # Get the body positions, excluding...
Get the body positions of the robot as tensor Returns: torch.Tensor: Tensor of body positions
body_positions
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def body_rotations(self) -> torch.Tensor: """Get the body rotations of the robot as tensor Returns: torch.Tensor: Tensor of body rotations """ # NOTE: Global frame, https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html # Get the body positions, excluding...
Get the body rotations of the robot as tensor Returns: torch.Tensor: Tensor of body rotations
body_rotations
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def body_velocities(self) -> tuple[torch.Tensor, torch.Tensor]: """Get the body linear and angular velocities of the robot as a pair of tensors Returns: tuple[torch.Tensor, torch.Tensor]: Tuple of linear and angular body velocities """ linear_velocities = torch.zeros(self.nu...
Get the body linear and angular velocities of the robot as a pair of tensors Returns: tuple[torch.Tensor, torch.Tensor]: Tuple of linear and angular body velocities
body_velocities
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def step(self, actions: np.ndarray | None = None, nsteps: int = 1) -> None: """Step the simulation forward nsteps with the given action. Args: actions (np.ndarray | None, optional): Action to apply to the robot. Defaults to None. nsteps (int, optional): Number of steps to take. ...
Step the simulation forward nsteps with the given action. Args: actions (np.ndarray | None, optional): Action to apply to the robot. Defaults to None. nsteps (int, optional): Number of steps to take. Defaults to 1.
step
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def reset( self, qpos: np.ndarray | torch.Tensor | None = None, qvel: np.ndarray | torch.Tensor | None = None, ) -> None: """Reset the model to its initial state Args: qpos (np.ndarray | torch.Tensor | None, optional): Positions of the generalized coordinates. De...
Reset the model to its initial state Args: qpos (np.ndarray | torch.Tensor | None, optional): Positions of the generalized coordinates. Defaults to None. qvel (np.ndarray | torch.Tensor | None, optional): Velocities of the generalized coordinates. Defaults to None.
reset
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def set_robot_state( self, qpos: np.ndarray | torch.Tensor | None = None, qvel: np.ndarray | torch.Tensor | None = None ): """ Set robot state including positions and velocities of the generalized coordinates. Args: qpos (np.ndarray | torch.Tensor | None, optional): Posi...
Set robot state including positions and velocities of the generalized coordinates. Args: qpos (np.ndarray | torch.Tensor | None, optional): Positions of the generalized coordinates. Defaults to None. qvel (np.ndarray | torch.Tensor | None, optional): Velocities of the generaliz...
set_robot_state
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_body_ids(self, body_names: list[str] | None = None, free_joint_offset: int = 1) -> dict[str, int]: """Get the IDs of all bodies in the model, indexed after removing the world body. Args: body_names (list[str] | None, optional): Names of the bodies. Defaults to None. free...
Get the IDs of all bodies in the model, indexed after removing the world body. Args: body_names (list[str] | None, optional): Names of the bodies. Defaults to None. free_joint_offset (int, optional): Offset to remove the free joint. Defaults to 1. Returns: dict[str,...
get_body_ids
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_joint_ids(self, joint_names: list[str] | None = None, free_joint_offset: int = 1) -> 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. f...
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. free_joint_offset (int, optional): Offset to remove the free joint. Defaults to 1. Returns: dict[str...
get_joint_ids
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_body_pose(self, body_name: str = "pelvis") -> tuple[torch.Tensor, torch.Tensor]: """Get the position and quaternion of the base Args: body_name (str, optional): Name of the body. Defaults to 'pelvis'. Returns: tuple[torch.Tensor, torch.Tensor]: Position and quat...
Get the position and quaternion of the base Args: body_name (str, optional): Name of the body. Defaults to 'pelvis'. Returns: tuple[torch.Tensor, torch.Tensor]: Position and quaternion of the base
get_body_pose
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_base_projected_gravity(self, base_name: str = "pelvis") -> torch.Tensor: """Get the projection of the gravity vector to the base frame Args: base_name (str, optional): Name of the base. Defaults to 'pelvis'. Returns: torch.Tensor: Projection of the gravity vecto...
Get the projection of the gravity vector to the base frame Args: base_name (str, optional): Name of the base. Defaults to 'pelvis'. Returns: torch.Tensor: Projection of the gravity vector to the base frame
get_base_projected_gravity
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_contact_forces_with_floor(self, body_name: str) -> torch.Tensor: """Get the contact forces on a given body with the floor Args: body_name (str): Name of the body Returns: torch.Tensor: Contact forces, shape (num_envs, 3), i.e. normal and two tangent directions ...
Get the contact forces on a given body with the floor Args: body_name (str): Name of the body Returns: torch.Tensor: Contact forces, shape (num_envs, 3), i.e. normal and two tangent directions Notes: Only checks contacts with the floor, and thus assumes the...
get_contact_forces_with_floor
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def print_actuator_info(self, actuators_id: list[int] | None = None): """Utility function to print out actuator types in the model. Args: actuators_id (list[int] | None, optional): Actuator ids. Defaults to None. """ actuators_id_ = range(self.model.nu) if actuators_id is No...
Utility function to print out actuator types in the model. Args: actuators_id (list[int] | None, optional): Actuator ids. Defaults to None.
print_actuator_info
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def _check_actuator_consistency(self): """Check whether all the actuators share the same control mode.""" actuator_type_system = None for actuator_id in range(self.model.nu): actuator_type = self.model.actuator_trntype[actuator_id] if actuator_type_system is None: ...
Check whether all the actuators share the same control mode.
_check_actuator_consistency
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_entity_name(model: mj.MjModel, entity_type: str, entity_id: int) -> str: """Gets name of an entity based on ID Args: model (mj.MjModel): model entity_type (str): entity type entity_id (int): entity id Returns: str: entity name """ if entity_type == "body": ...
Gets name of an entity based on ID Args: model (mj.MjModel): model entity_type (str): entity type entity_id (int): entity id Returns: str: entity name
get_entity_name
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_utils.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_utils.py
Apache-2.0
def to_numpy(x): """ Check if input is a PyTorch tensor and convert to numpy array if true. Otherwise return the input unchanged. Args: x: Input to check and potentially convert Returns: numpy array if input was torch tensor, otherwise original input """ if isinstance(x, to...
Check if input is a PyTorch tensor and convert to numpy array if true. Otherwise return the input unchanged. Args: x: Input to check and potentially convert Returns: numpy array if input was torch tensor, otherwise original input
to_numpy
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
Apache-2.0
def squeeze_if_tensor(x, dim: int = 0): """ Check if input is a PyTorch tensor and squeeze along the given dim if true. Args: x: Input to check and potentially convert dim: Dimension to squeeze Returns: numpy array if input was torch tensor, otherwise original input """ ...
Check if input is a PyTorch tensor and squeeze along the given dim if true. Args: x: Input to check and potentially convert dim: Dimension to squeeze Returns: numpy array if input was torch tensor, otherwise original input
squeeze_if_tensor
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
Apache-2.0
def draw_reference_state(self, state: ReferenceMotionState): """Visualize the reference state in Mujoco.""" body_pos_np = np.squeeze(state.body_pos.detach().cpu().numpy()) body_pos_extend_np = np.squeeze(state.body_pos_extend.detach().cpu().numpy()) body_pos = np.vstack([body_pos_np, bo...
Visualize the reference state in Mujoco.
draw_reference_state
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/visualization.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/visualization.py
Apache-2.0
def _produce_actions(self, obs: dict) -> torch.Tensor: """ Roll out the environment with either the expert policy or the student policy, depending on the current state of training. """ if self._iterations + self.start_iteration >= self._cfg.student_rollout_iteration: ...
Roll out the environment with either the expert policy or the student policy, depending on the current state of training.
_produce_actions
python
NVlabs/HOVER
neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer.py
Apache-2.0
def save(self, file_path: str): """ Save the dataclass fields to a JSON file. Args: file_path (str): The path to the file where the JSON will be saved. """ # Convert the dataclass to a dictionary data_dict = { field_info.name: getattr(self, field_...
Save the dataclass fields to a JSON file. Args: file_path (str): The path to the file where the JSON will be saved.
save
python
NVlabs/HOVER
neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
Apache-2.0
def add_args_to_parser(parser: argparse.ArgumentParser, default_overwrites: dict = {}): """ Add the fields of the dataclass (except for `teacher_policy`) to an ArgumentParser. This method iterates over the fields of the StudentPolicyTrainerCfg dataclass and adds them as arguments to the...
Add the fields of the dataclass (except for `teacher_policy`) to an ArgumentParser. This method iterates over the fields of the StudentPolicyTrainerCfg dataclass and adds them as arguments to the provided ArgumentParser. The `teacher_policy` field is skipped. If a field has a default value or ...
add_args_to_parser
python
NVlabs/HOVER
neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
Apache-2.0
def load(filepath: str) -> "TeacherPolicyCfg": """Loads the configuration from a YAML file.""" with open(filepath, encoding="utf-8") as file: data = json.load(file) cfg = fromdict(TeacherPolicyCfg, data) return cfg
Loads the configuration from a YAML file.
load
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def add_args_to_parser(parser: argparse.ArgumentParser, default_overwrites: dict = {}): """Adds configuration fields to an ArgumentParser.""" group = parser.add_argument_group("Teacher policy configurations (RSL RL)") def add_fields_to_parser(fields): for field_info in fields: ...
Adds configuration fields to an ArgumentParser.
add_args_to_parser
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def from_argparse_args(args: argparse.Namespace) -> "TeacherPolicyCfg": """Creates an instance from argparse arguments.""" def extract_fields(cls: Type) -> dict: """Helper function to extract fields for a given dataclass type.""" extracted_fields = { field.name: ...
Creates an instance from argparse arguments.
from_argparse_args
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def extract_fields(cls: Type) -> dict: """Helper function to extract fields for a given dataclass type.""" extracted_fields = { field.name: getattr(args, TeacherPolicyCfg.args_prefix() + field.name) for field in fields(cls) if hasattr(args, Teacher...
Helper function to extract fields for a given dataclass type.
extract_fields
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def resolve_student_policy_path(root_path: str, teacher_policy: NeuralWBCTeacherPolicy, append_timestamp: bool): """ Generates a path for storing student policy configurations based on the root path and teacher policy. This function appends a timestamp and the teacher policy name to the given root path to ...
Generates a path for storing student policy configurations based on the root path and teacher policy. This function appends a timestamp and the teacher policy name to the given root path to create a unique path for storing student policy configurations. Args: root_path (str): The root directo...
resolve_student_policy_path
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def get_config_values_from_argparser(args: argparse.Namespace, teacher_policy: NeuralWBCTeacherPolicy): """ Extracts configuration values from command-line arguments based on a predefined prefix and field names. This function processes the command-line arguments, filters out those that match a specified pr...
Extracts configuration values from command-line arguments based on a predefined prefix and field names. This function processes the command-line arguments, filters out those that match a specified prefix, and returns a dictionary of configuration values that are relevant to the StudentPolicyTrainerCfg dat...
get_config_values_from_argparser
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def get_student_trainer_cfg(args: argparse.Namespace, env: NeuralWBCEnv, teacher_policy: NeuralWBCTeacherPolicy): """ Create an instance of StudentPolicyTrainerCfg from command-line arguments, environment configuration, and a teacher policy. This function processes the command-line arguments, extracts nece...
Create an instance of StudentPolicyTrainerCfg from command-line arguments, environment configuration, and a teacher policy. This function processes the command-line arguments, extracts necessary values, fills in any missing values using the environment configuration, and creates an instance of the Student...
get_student_trainer_cfg
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def load_student_policy_trainer_cfg(args: argparse.Namespace, teacher_policy: NeuralWBCTeacherPolicy): """ Loads the student policy trainer configuration from a specified resume path. This function checks if a resume path is provided in the command-line arguments. If so, it loads the configuration from...
Loads the student policy trainer configuration from a specified resume path. This function checks if a resume path is provided in the command-line arguments. If so, it loads the configuration from a config.json at the resume path, updates it with any new arguments provided, and returns an instance of ...
load_student_policy_trainer_cfg
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def get_customized_rsl_rl(): """Helper function to ensure the correct version of rsl_rl is imported. This function does the following: 1. Gets the installed rsl_rl package location and adds it to sys.path 2. Removes any existing rsl_rl and submodules from sys.modules to force reimporting """ im...
Helper function to ensure the correct version of rsl_rl is imported. This function does the following: 1. Gets the installed rsl_rl package location and adds it to sys.path 2. Removes any existing rsl_rl and submodules from sys.modules to force reimporting
get_customized_rsl_rl
python
NVlabs/HOVER
scripts/rsl_rl/utils.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/utils.py
Apache-2.0
def __init__(self, env: NeuralWBCEnv): """Initializes the wrapper. Note: The wrapper calls :meth:`reset` at the start since the RSL-RL runner does not call reset. Args: env: The environment to wrap around. """ super().__init__(mode=env.cfg.mode) ...
Initializes the wrapper. Note: The wrapper calls :meth:`reset` at the start since the RSL-RL runner does not call reset. Args: env: The environment to wrap around.
__init__
python
NVlabs/HOVER
scripts/rsl_rl/vecenv_wrapper.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/vecenv_wrapper.py
Apache-2.0
def test_save_and_load(self): """Test saving and loading the configuration to/from a file.""" # Create a temporary file to save the configuration with tempfile.NamedTemporaryFile(delete=False) as tmp_file: file_path = tmp_file.name # Save the configuration to the file ...
Test saving and loading the configuration to/from a file.
test_save_and_load
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def test_add_args_to_parser(self): """Test adding configuration fields to an argument parser.""" parser = argparse.ArgumentParser(description="RSL-RL configuration") TeacherPolicyCfg.add_args_to_parser(parser) # Create sample arguments args = [ "--teacher_policy.seed...
Test adding configuration fields to an argument parser.
test_add_args_to_parser
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def test_default_values(self): """Test the default values of the configuration.""" # Verify default values self.assertEqual(self.config.seed, 1) self.assertEqual(self.config.policy.init_noise_std, 1.0) self.assertEqual(self.config.policy.actor_hidden_dims, [512, 256, 128]) ...
Test the default values of the configuration.
test_default_values
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def test_add_args_to_parser_with_default_overwrites(self): """Test adding configuration fields to an argument parser with default overwrites.""" parser = argparse.ArgumentParser(description="RSL-RL configuration") default_overwrites = { "seed": 10, "init_noise_std": 0.5, ...
Test adding configuration fields to an argument parser with default overwrites.
test_add_args_to_parser_with_default_overwrites
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def format_seconds_to_human_readable(self, total_seconds): """Formats seconds into a human readable string with hours, minutes and seconds. Args: total_seconds (float): Number of seconds to format Returns: str: Formatted string in the format "Xh, Ym, Zs" where X=hours, ...
Formats seconds into a human readable string with hours, minutes and seconds. Args: total_seconds (float): Number of seconds to format Returns: str: Formatted string in the format "Xh, Ym, Zs" where X=hours, Y=minutes, Z=seconds
format_seconds_to_human_readable
python
NVlabs/HOVER
third_party/rsl_rl/rsl_rl/runners/on_policy_runner.py
https://github.com/NVlabs/HOVER/blob/master/third_party/rsl_rl/rsl_rl/runners/on_policy_runner.py
Apache-2.0
def split_and_pad_trajectories(tensor, dones): """ Splits trajectories at done indices. Then concatenates them and padds with zeros up to the length og the longest trajectory. Returns masks corresponding to valid parts of the trajectories Example: Input: [ [a1, a2, a3, a4 | a5, a6], ...
Splits trajectories at done indices. Then concatenates them and padds with zeros up to the length og the longest trajectory. Returns masks corresponding to valid parts of the trajectories Example: Input: [ [a1, a2, a3, a4 | a5, a6], [b1, b2 | b3, b4, b5 | b6] ] ...
split_and_pad_trajectories
python
NVlabs/HOVER
third_party/rsl_rl/rsl_rl/utils/utils.py
https://github.com/NVlabs/HOVER/blob/master/third_party/rsl_rl/rsl_rl/utils/utils.py
Apache-2.0
def convert( type: str, project: str, cloud: bool, workspace: str, logdir: str, tb_logdir: str, wb_project: str, wb_entity: str, wb_runid: str, mlflow_uri: str, mlflow_exp: str, **kwargs, ): """Convert the log files of o...
Convert the log files of other experiment tracking tools to SwanLab.
convert
python
SwanHubX/SwanLab
swanlab/cli/commands/converter/__init__.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/cli/commands/converter/__init__.py
Apache-2.0
def log( data: Dict[str, DataType], step: int = None, print_to_console: bool = False, ): """ Log a row of data to the current run. We recommend that you log data by SwanLabRun.log() method, but you can also use this function to log data. Parameters ---------- data : Dict[str, DataTy...
Log a row of data to the current run. We recommend that you log data by SwanLabRun.log() method, but you can also use this function to log data. Parameters ---------- data : Dict[str, DataType] Data must be a dict. The key must be a string with 0-9, a-z, A-Z, " ", "_", "-", "/". ...
log
python
SwanHubX/SwanLab
swanlab/data/sdk.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/sdk.py
Apache-2.0
def finish(state: SwanLabRunState = SwanLabRunState.SUCCESS, error=None): """ Finish the current run and close the current experiment Normally, swanlab will run this function automatically, but you can also execute it manually and mark the experiment as 'completed'. Once the experiment is marked as ...
Finish the current run and close the current experiment Normally, swanlab will run this function automatically, but you can also execute it manually and mark the experiment as 'completed'. Once the experiment is marked as 'completed', no more data can be logged to the experiment by 'swanlab.log'. I...
finish
python
SwanHubX/SwanLab
swanlab/data/sdk.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/sdk.py
Apache-2.0
def get_full_typename(o: Any) -> Any: """Determine types based on type names. Avoids needing to import (and therefore depend on) PyTorch, TensorFlow, etc. """ instance_name = o.__class__.__module__ + "." + o.__class__.__name__ if instance_name in ["builtins.module", "__builtin__.module"]: r...
Determine types based on type names. Avoids needing to import (and therefore depend on) PyTorch, TensorFlow, etc.
get_full_typename
python
SwanHubX/SwanLab
swanlab/data/modules/image/__init__.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/image/__init__.py
Apache-2.0
def __post_init__(self): """Validate input data after initialization. Checks: 1. File exists 2. Path points to a file 3. File has .glb extension Raises: FileNotFoundError: If GLB file does not exist ValueError: If path is not a file o...
Validate input data after initialization. Checks: 1. File exists 2. Path points to a file 3. File has .glb extension Raises: FileNotFoundError: If GLB file does not exist ValueError: If path is not a file or not a GLB file
__post_init__
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/model3d.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/model3d.py
Apache-2.0
def parse(self) -> Tuple[str, MediaBuffer]: """Convert model to buffer for transmission. This method reads the GLB file and prepares it for transmission. It: 1. Reads the file content into a buffer 2. Generates a unique hash from the content 3. Creates a unique filename using th...
Convert model to buffer for transmission. This method reads the GLB file and prepares it for transmission. It: 1. Reads the file content into a buffer 2. Generates a unique hash from the content 3. Creates a unique filename using the original name, step, and hash Returns: ...
parse
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/model3d.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/model3d.py
Apache-2.0
def from_mol(cls, mol: Mol, *, caption: Optional[str] = None, **kwargs) -> "Molecule": """Creates a Molecule instance from an RDKit Mol object. Args: mol: The RDKit Mol object. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance. ...
Creates a Molecule instance from an RDKit Mol object. Args: mol: The RDKit Mol object. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance. Raises: ImportError: If RDKit is not available. Examples: ...
from_mol
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/molecule.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/molecule.py
Apache-2.0
def from_pdb_file(cls, pdb_file: Union[Path, str], *, caption: Optional[str] = None, **kwargs) -> "Molecule": """Creates a Molecule instance from a PDB file by reading the file content directly. Args: pdb_file: Path to the PDB file. caption: Optional descriptive text. R...
Creates a Molecule instance from a PDB file by reading the file content directly. Args: pdb_file: Path to the PDB file. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance. Raises: ValueError: If RDKit is not available...
from_pdb_file
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/molecule.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/molecule.py
Apache-2.0
def from_sdf_file(cls, sdf_file: Path, *, caption: Optional[str] = None, **kwargs) -> "Molecule": """Creates a Molecule instance from an SDF file. Args: sdf_file: Path to the SDF file. caption: Optional descriptive text. Returns: Molecule: A new Molecule ins...
Creates a Molecule instance from an SDF file. Args: sdf_file: Path to the SDF file. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance. Raises: ImportError: If RDKit is not available.
from_sdf_file
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/molecule.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/molecule.py
Apache-2.0
def from_smiles(cls, smiles: str, *, caption: Optional[str] = None, **kwargs) -> "Molecule": """Creates a Molecule instance from a SMILES string. Args: smiles: The SMILES string. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance....
Creates a Molecule instance from a SMILES string. Args: smiles: The SMILES string. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance. Raises: ValueError: If RDKit is not available.
from_smiles
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/molecule.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/molecule.py
Apache-2.0
def from_mol_file(cls, mol_file: Path, *, caption: Optional[str] = None, **kwargs) -> "Molecule": """Creates a Molecule instance from a Mol file. Args: mol_file: Path to the Mol file. caption: Optional descriptive text. Returns: Molecule: A new Molecule inst...
Creates a Molecule instance from a Mol file. Args: mol_file: Path to the Mol file. caption: Optional descriptive text. Returns: Molecule: A new Molecule instance. Raises: ValueError: If RDKit is not available or the file cannot be read.
from_mol_file
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/molecule.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/molecule.py
Apache-2.0
def parse(self) -> Tuple[str, MediaBuffer]: """Convert Molecule PDB to buffer for transmission. Returns: Tuple containing: - File name with format: molecule-step{step}-{hash}.pdb - MediaBuffer containing the molecule pdb data """ data = self.pdb_data...
Convert Molecule PDB to buffer for transmission. Returns: Tuple containing: - File name with format: molecule-step{step}-{hash}.pdb - MediaBuffer containing the molecule pdb data
parse
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/molecule.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/molecule.py
Apache-2.0
def from_xyz(cls, points: ndarray, *, caption: Optional[str] = None, **kwargs) -> "PointCloud": """Create PointCloud from XYZ coordinates. Args: points: numpy array with shape (N, 3) containing XYZ coordinates caption: Optional description text Returns: Poin...
Create PointCloud from XYZ coordinates. Args: points: numpy array with shape (N, 3) containing XYZ coordinates caption: Optional description text Returns: PointCloud object with default green color Examples: >>> points = np.random.rand(100, 3) ...
from_xyz
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/point_cloud.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/point_cloud.py
Apache-2.0
def from_xyzc(cls, points: ndarray, *, caption: Optional[str] = None, **kwargs) -> "PointCloud": """Create PointCloud from XYZC format (XYZ coordinates + category). Args: points: numpy array with shape (N, 4) containing XYZC values where C is category index (integer) ...
Create PointCloud from XYZC format (XYZ coordinates + category). Args: points: numpy array with shape (N, 4) containing XYZC values where C is category index (integer) caption: Optional description text Returns: PointCloud object with colors mappe...
from_xyzc
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/point_cloud.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/point_cloud.py
Apache-2.0
def from_xyzrgb(cls, points: ndarray, *, caption: Optional[str] = None, **kwargs) -> "PointCloud": """Create PointCloud from XYZRGB format. Args: points: numpy array with shape (N, 6) containing XYZRGB values caption: Optional description text Returns: Point...
Create PointCloud from XYZRGB format. Args: points: numpy array with shape (N, 6) containing XYZRGB values caption: Optional description text Returns: PointCloud object Examples: >>> points = np.zeros((100, 6)) >>> points[:, :3] = co...
from_xyzrgb
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/point_cloud.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/point_cloud.py
Apache-2.0
def from_swanlab_pts(cls, data: Dict, *, caption: Optional[str] = None, **kwargs) -> "PointCloud": """Create PointCloud from SwanLab pts data dictionary. Args: data: A dictionary containing 'points' (required) and optionally 'boxes'. 'points' can be a list of lists (XYZ, X...
Create PointCloud from SwanLab pts data dictionary. Args: data: A dictionary containing 'points' (required) and optionally 'boxes'. 'points' can be a list of lists (XYZ, XYZC, or XYZRGB) or a NumPy array. 'boxes' is an optional list of dictionaries, each represen...
from_swanlab_pts
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/point_cloud.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/point_cloud.py
Apache-2.0
def from_swanlab_pts_json_file(cls, path: Path, *, caption: Optional[str] = None, **kwargs) -> "PointCloud": """Create PointCloud from SwanLab pts.json file. Args: path: Path to the .swanlab.pts.json file caption: Optional description text Returns: PointClou...
Create PointCloud from SwanLab pts.json file. Args: path: Path to the .swanlab.pts.json file caption: Optional description text Returns: PointCloud object Examples: >>> pc = PointCloud.from_swanlab_pts_json_file( ... Path("points...
from_swanlab_pts_json_file
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/point_cloud.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/point_cloud.py
Apache-2.0
def parse(self) -> Tuple[str, MediaBuffer]: """Convert point cloud to buffer for transmission. Returns: Tuple containing: - File name with format: pointcloud-step{step}-{hash}.swanlab.pts.json - MediaBuffer containing the point cloud data """ buffer =...
Convert point cloud to buffer for transmission. Returns: Tuple containing: - File name with format: pointcloud-step{step}-{hash}.swanlab.pts.json - MediaBuffer containing the point cloud data
parse
python
SwanHubX/SwanLab
swanlab/data/modules/object3d/point_cloud.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/modules/object3d/point_cloud.py
Apache-2.0
def get(self, name: str, default=None): """ Get the value of a configuration item. If the item does not exist, raise AttributeError. """ try: return self.__config[name] except KeyError: return default
Get the value of a configuration item. If the item does not exist, raise AttributeError.
get
python
SwanHubX/SwanLab
swanlab/data/run/config.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/config.py
Apache-2.0
def __setitem__(self, name: str, value: Any) -> None: """ Set the value of a configuration item. If the item does not exist, create it. User are not allowed to set private attributes. """ name = str(name) self.__config[name] = parse(value) self.__save()
Set the value of a configuration item. If the item does not exist, create it. User are not allowed to set private attributes.
__setitem__
python
SwanHubX/SwanLab
swanlab/data/run/config.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/config.py
Apache-2.0
def set(self, name: str, value: Any): """ Explicitly set the value of a configuration item and save it. Private attributes are not allowed to be set. """ name = str(name) self.__config[name] = parse(value) self.__save()
Explicitly set the value of a configuration item and save it. Private attributes are not allowed to be set.
set
python
SwanHubX/SwanLab
swanlab/data/run/config.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/config.py
Apache-2.0
def pop(self, name: str): """ Delete a configuration item; if the item does not exist, skip. """ try: t = self.__config[name] del self.__config[name] self.__save() return t except KeyError: return None
Delete a configuration item; if the item does not exist, skip.
pop
python
SwanHubX/SwanLab
swanlab/data/run/config.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/config.py
Apache-2.0
def update(self, __m: Union[MutableMapping, argparse.Namespace] = None, **kwargs): """ Update the configuration with the key/value pairs from __m, overwriting existing keys. """ if __m is not None: for k, v in parse(__m).items(): self.__config[k] = v f...
Update the configuration with the key/value pairs from __m, overwriting existing keys.
update
python
SwanHubX/SwanLab
swanlab/data/run/config.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/config.py
Apache-2.0
def clean(self): """ Clean the configuration. Attention: This method will reset the instance and instance will not automatically save the configuration. """ self.__config.clear() self.__on_setter = None
Clean the configuration. Attention: This method will reset the instance and instance will not automatically save the configuration.
clean
python
SwanHubX/SwanLab
swanlab/data/run/config.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/config.py
Apache-2.0
def __flatten_dict(self, d: dict, parent_key='', sep='.') -> dict: """Helper method to flatten nested dictionaries with dot notation""" items = [] for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.e...
Helper method to flatten nested dictionaries with dot notation
__flatten_dict
python
SwanHubX/SwanLab
swanlab/data/run/main.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/main.py
Apache-2.0
def get_url() -> Optional["str"]: """ Get the url of the current experiment. NOTE: return None if the experiment has not been initialized or mode is not 'cloud'. """ global run if run is None: return None return run.public.cloud.experiment_url
Get the url of the current experiment. NOTE: return None if the experiment has not been initialized or mode is not 'cloud'.
get_url
python
SwanHubX/SwanLab
swanlab/data/run/main.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/main.py
Apache-2.0
def get_project_url() -> Optional["str"]: """ Get the url of the current project. NOTE: return None if the experiment has not been initialized or mode is not 'cloud'. """ global run if run is None: return None return run.public.cloud.project_url
Get the url of the current project. NOTE: return None if the experiment has not been initialized or mode is not 'cloud'.
get_project_url
python
SwanHubX/SwanLab
swanlab/data/run/main.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/main.py
Apache-2.0
def __get_property_from_http(self, name: str): """ Get the property from the http object. if the http object is None, it will be initialized. if initialization fails, it will return None. """ if self.available: return getattr(self.__http, name) return ...
Get the property from the http object. if the http object is None, it will be initialized. if initialization fails, it will return None.
__get_property_from_http
python
SwanHubX/SwanLab
swanlab/data/run/public.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/public.py
Apache-2.0
def project_url(self): """ The url of the project. It is the url of the project page on the SwanLab. If swanlab is not running in cloud mode, it will return None. """ if not self.available: return None return self.__get_property_from_http("web_proj_url")
The url of the project. It is the url of the project page on the SwanLab. If swanlab is not running in cloud mode, it will return None.
project_url
python
SwanHubX/SwanLab
swanlab/data/run/public.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/public.py
Apache-2.0
def experiment_url(self): """ The url of the experiment. It is the url of the experiment page on the SwanLab. """ if not self.available: return None return self.__get_property_from_http("web_exp_url")
The url of the experiment. It is the url of the experiment page on the SwanLab.
experiment_url
python
SwanHubX/SwanLab
swanlab/data/run/public.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/public.py
Apache-2.0
def json(self): """ Return a dict of the public config. This method is used to serialize the public config to json. """ return { "project_name": self.project_name, "version": self.version, "run_id": self.run_id, "swanlog_dir": self....
Return a dict of the public config. This method is used to serialize the public config to json.
json
python
SwanHubX/SwanLab
swanlab/data/run/public.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/public.py
Apache-2.0
def parse_git_url(url): """Return the remote URL of a git repository.""" if url.startswith("git@"): parts = url[4:].split("/", 1) host, path = parts[0], parts[1] if len(parts) > 1 else "" if ":" in host: host, port = host.rsplit(":", 1) url = f"https://{host}:{por...
Return the remote URL of a git repository.
parse_git_url
python
SwanHubX/SwanLab
swanlab/data/run/metadata/runtime.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/metadata/runtime.py
Apache-2.0
def replace_second_colon(input_string, replacement): """Replace the second colon in a string.""" first_colon = input_string.find(":") second_colon = input_string.find(":", first_colon + 1) if first_colon != -1 else -1 return ( input_string[:second_colon] + replacement + input_string[second_colon...
Replace the second colon in a string.
replace_second_colon
python
SwanHubX/SwanLab
swanlab/data/run/metadata/runtime.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/data/run/metadata/runtime.py
Apache-2.0
def log(self, values: dict, step: Optional[int] = None, **kwargs): """ Logs `values` to the current run. Args: data : Dict[str, DataType] Data must be a dict. The key must be a string with 0-9, a-z, A-Z, " ", "_", "-", "/". The value must be a `float`...
Logs `values` to the current run. Args: data : Dict[str, DataType] Data must be a dict. The key must be a string with 0-9, a-z, A-Z, " ", "_", "-", "/". The value must be a `float`, `float convertible object`, `int` or `swanlab.data.BaseType`. step :...
log
python
SwanHubX/SwanLab
swanlab/integration/accelerate.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/accelerate.py
Apache-2.0
def log_images(self, values: dict, step: Optional[int] = None, **kwargs): """ Logs `images` to the current run. Args: values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): Values to be logged as key-value pairs. The values need to have type `List` of `n...
Logs `images` to the current run. Args: values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or step (`int`, *optional*): The run step. If ...
log_images
python
SwanHubX/SwanLab
swanlab/integration/accelerate.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/accelerate.py
Apache-2.0
def __init__(self, project: Optional[str] = None, workspace: Optional[str] = None, experiment_name: Optional[str] = None, description: Optional[str] = None, logdir: Optional[str] = None, mode: Optional[str] = None, **kwargs: Any,): """ To use the `...
To use the `SwanLabCallback`, pass it into the `callback` parameter when initializing the `transformers.Trainer`. This allows the Trainer to utilize SwanLab's logging and monitoring functionalities during the training process. Parameters same with `swanlab.init`. Finds more informations ...
__init__
python
SwanHubX/SwanLab
swanlab/integration/huggingface.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/huggingface.py
Apache-2.0
def add_config(self, config: Config, **kwargs) -> None: """Record the config to swanlab. Args: config (Config): The Config object """ def repack_dict(a, prefix=""): """ Unpack Nested Dictionary func """ new_dict = dict() ...
Record the config to swanlab. Args: config (Config): The Config object
add_config
python
SwanHubX/SwanLab
swanlab/integration/mmengine.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/mmengine.py
Apache-2.0
def add_image(self, name: str, image: np.ndarray, step: int = 0, **kwargs) -> None: """Record the image to swanlab. Args: name (str): The image identifier. image (np.ndarray): The image to be saved. The format should be RGB. Defaults to None. step (in...
Record the image to swanlab. Args: name (str): The image identifier. image (np.ndarray): The image to be saved. The format should be RGB. Defaults to None. step (int): Global step value to record. Defaults to 0.
add_image
python
SwanHubX/SwanLab
swanlab/integration/mmengine.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/mmengine.py
Apache-2.0
def add_scalars( self, scalar_dict: dict, step: int = 0, file_path: Optional[str] = None, **kwargs, ) -> None: """Record the scalars' data. Args: scalar_dict (dict): Key-value pair storing the tag and corresponding values. ...
Record the scalars' data. Args: scalar_dict (dict): Key-value pair storing the tag and corresponding values. step (int): Global step value to record. Defaults to 0. file_path (str, optional): The scalar's data will be saved to the `file_path` ...
add_scalars
python
SwanHubX/SwanLab
swanlab/integration/mmengine.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/mmengine.py
Apache-2.0
def __init__( self, project: Optional[str] = None, workspace: Optional[str] = None, experiment_name: Optional[str] = None, description: Optional[str] = None, logdir: Optional[str] = None, mode: Optional[str] = None, tags: Optional[List[str]] = None, ...
To use the `SwanLabCallback`, pass it into the `callback` parameter when initializing the `paddlenlp.Trainer`. This allows the Trainer to utilize SwanLab's logging and monitoring functionalities during the training process. Parameters same with `swanlab.init`. Finds more informations [...
__init__
python
SwanHubX/SwanLab
swanlab/integration/paddlenlp.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/paddlenlp.py
Apache-2.0
def setup(self, args, state, model, **kwargs): """ Setup the optional SwanLab (*swanlab*) integration. You can also override the following environment variables. Find more information about environment variables [here](https://docs.swanlab.cn/en/api/environment-variable.html#environment...
Setup the optional SwanLab (*swanlab*) integration. You can also override the following environment variables. Find more information about environment variables [here](https://docs.swanlab.cn/en/api/environment-variable.html#environment-variables) Environment: - **SWANLAB_API_...
setup
python
SwanHubX/SwanLab
swanlab/integration/paddlenlp.py
https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/paddlenlp.py
Apache-2.0