"""Direct joint-control fixed-line ascent on a physical alpine slope. This environment deliberately has no gait generator, inverse kinematics, reference trajectory, balance force, or phase machine. The policy commands the robot's 29 body joints through the stock G1 position actuators. MuJoCo handles motor torques, gravity, contacts, the flexible climbing rope, the prepared hand/ascender connection, and a unilateral ascender cam. """ from __future__ import annotations import os from typing import Any import gymnasium as gym import mujoco import numpy as np from gymnasium import spaces class G1LearnedFixedLineEnv(gym.Env): """PPO-ready environment whose actions are direct joint targets.""" metadata = {"render_modes": ["rgb_array", "human"], "render_fps": 50} POLICY_JOINTS = ( "left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint", "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint", "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint", "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint", "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint", "right_wrist_pitch_joint", "right_wrist_yaw_joint", ) # The released checkpoint was trained with ascent divided by 0.8 in its # observation. Keep that input contract independent of the longer pitch # used for success evaluation. POLICY_ASCENT_OBSERVATION_SCALE = 0.80 # The final task feature (after 9 rotation, 6 base-velocity, 58 joint, # 4 ascender, 8 foot, and 5 earlier task values) is signed lateral # position. Its sign tells the learned controller which direction moves # away from the rope; an absolute offset alone is ambiguous. SIGNED_LATERAL_OBSERVATION_INDEX = 90 # On a 28-degree slope, sin(28 deg) ~= 0.47 of body weight acts downhill. # A harness load in this band therefore arrests sliding while leaving the # boots responsible for the surface-normal load. Success requires this # support to persist; a single collision impulse is not load transfer. TARGET_LANYARD_SUPPORT_FRACTION = 0.47 MIN_LANYARD_SUPPORT_FRACTION = 0.40 MAX_LANYARD_SUPPORT_FRACTION = 0.56 REACH_SUPPORT_STREAK_STEPS = 8 SUPPORTED_MOTION_STREAK_STEPS = 12 BRACE_SUPPORT_STREAK_STEPS = 24 def __init__( self, model_path: str | None = None, frame_skip: int = 10, max_episode_steps: int = 700, target_ascent: float = 2.50, render_mode: str | None = None, randomize_reset: bool = True, action_filter: float = 0.95, prepared_settle_steps: int = 300, randomized_settle_steps: int = 20, randomization_scale: float = 1.0, curriculum_stage: str = "full", ) -> None: super().__init__() if model_path is None: model_path = os.path.join( os.path.dirname(__file__), "assets", "unitree_g1", "scene_fixed_line_learned.xml", ) self.model_path = os.path.abspath(model_path) self.model = mujoco.MjModel.from_xml_path(self.model_path) self.data = mujoco.MjData(self.model) self.frame_skip = int(frame_skip) self.max_episode_steps = int(max_episode_steps) self.target_ascent = float(target_ascent) self.render_mode = render_mode self.randomize_reset = bool(randomize_reset) self.action_filter = float(action_filter) self.prepared_settle_steps = int(prepared_settle_steps) self.randomized_settle_steps = int(randomized_settle_steps) self.randomization_scale = float(randomization_scale) if self.prepared_settle_steps < 0 or self.randomized_settle_steps < 0: raise ValueError("settle step counts must be non-negative") if self.randomization_scale < 0.0: raise ValueError("randomization_scale must be non-negative") if curriculum_stage not in { "reach", "lift", "brace", "swing", "land", "step", "sequence", "stabilize", "hold", "sustain", "endurance", "extend", "recover", "advance", "grounded", "bend", "flex", "catch", "pull", "rearm", "full", }: raise ValueError( "curriculum_stage must be 'reach', 'lift', 'brace', 'swing', " "'land', 'step', " "'sequence', 'stabilize', 'hold', 'sustain', 'endurance', 'extend', " "'recover', 'advance', 'grounded', " "'bend', 'flex', 'catch', 'pull', 'rearm', or 'full'" ) self.curriculum_stage = curriculum_stage self.policy_dt = self.frame_skip * self.model.opt.timestep angle = np.deg2rad(28.0) self.uphill = np.asarray([np.cos(angle), 0.0, np.sin(angle)]) self.slope_normal = np.asarray([-np.sin(angle), 0.0, np.cos(angle)]) self._actuator_names = [ mujoco.mj_id2name(self.model, mujoco.mjtObj.mjOBJ_ACTUATOR, index) or "" for index in range(self.model.nu) ] self._actuator_ids = { name: index for index, name in enumerate(self._actuator_names) } self._policy_actuator_ids = np.asarray( [self._actuator_ids[name] for name in self.POLICY_JOINTS], dtype=np.int32, ) self.action_dim = len(self.POLICY_JOINTS) self._actuator_joint_ids = self.model.actuator_trnid[:, 0].astype(np.int32) self._actuator_qpos_addresses = self.model.jnt_qposadr[ self._actuator_joint_ids ].astype(np.int32) self._actuator_dof_addresses = self.model.jnt_dofadr[ self._actuator_joint_ids ].astype(np.int32) self._policy_qpos_addresses = self._actuator_qpos_addresses[ self._policy_actuator_ids ] self._policy_dof_addresses = self._actuator_dof_addresses[ self._policy_actuator_ids ] self._base_joint_id = self._id( mujoco.mjtObj.mjOBJ_JOINT, "floating_base_joint" ) self._base_qpos_address = int( self.model.jnt_qposadr[self._base_joint_id] ) self._base_dof_address = int( self.model.jnt_dofadr[self._base_joint_id] ) self._slide_joint_id = self._id( mujoco.mjtObj.mjOBJ_JOINT, "ascender_slide" ) self._slide_qpos_address = int( self.model.jnt_qposadr[self._slide_joint_id] ) self._slide_dof_address = int( self.model.jnt_dofadr[self._slide_joint_id] ) self._grip_equality_id = self._id( mujoco.mjtObj.mjOBJ_EQUALITY, "prepared_ascender_grip" ) # The equality connects the center of the molded handle to a point # inside the prepared palm, between the curled index/middle fingers # and opposing thumb. This is a fixed grasp location, not a moving # target or a hand-motion controller. self._palm_grip_local = np.asarray( [0.115982, 0.033995, 0.020238], dtype=np.float64 ) self.model.eq_data[ self._grip_equality_id, 3:6 ] = self._palm_grip_local self._ratchet_original_range = self.model.jnt_range[ self._slide_joint_id ].copy() self.pelvis_body_id = self._id(mujoco.mjtObj.mjOBJ_BODY, "pelvis") self.torso_body_id = self._id(mujoco.mjtObj.mjOBJ_BODY, "torso_link") self.right_wrist_body_id = self._id( mujoco.mjtObj.mjOBJ_BODY, "right_wrist_yaw_link" ) self.ascender_body_id = self._id( mujoco.mjtObj.mjOBJ_BODY, "learned_ascender" ) self.ascender_grip_site_id = self._id( mujoco.mjtObj.mjOBJ_SITE, "ascender_grip_site" ) self._lanyard_tendon_id = self._id( mujoco.mjtObj.mjOBJ_TENDON, "ascender_harness_lanyard" ) self.ice_face_geom_id = self._id( mujoco.mjtObj.mjOBJ_GEOM, "learned_ice_face" ) self.rope_flex_id = self._id(mujoco.mjtObj.mjOBJ_FLEX, "rope") self._rope_vertex_address = int( self.model.flex_vertadr[self.rope_flex_id] ) self._rope_vertex_count = int( self.model.flex_vertnum[self.rope_flex_id] ) self._rope_edge_address = int( self.model.flex_edgeadr[self.rope_flex_id] ) self._rope_edge_count = int( self.model.flex_edgenum[self.rope_flex_id] ) self._ascender_rope_geom_ids = { self._id(mujoco.mjtObj.mjOBJ_GEOM, name) for name in ( "ascender_cam", "ascender_wear_plate", "ascender_channel_near", "ascender_channel_far", "ascender_channel_back", ) } self._foot_site_ids = { side: self._id(mujoco.mjtObj.mjOBJ_SITE, f"{side}_foot") for side in ("left", "right") } self._foot_body_ids = { side: self._id( mujoco.mjtObj.mjOBJ_BODY, f"{side}_ankle_roll_link" ) for side in ("left", "right") } self._robot_body_ids = { index for index in range(self.model.nbody) if int(self.model.body_rootid[index]) == self.pelvis_body_id } self._boot_body_ids = set(self._foot_body_ids.values()) self._elbow_qpos_addresses = { side: int( self._actuator_qpos_addresses[ self._actuator_ids[f"{side}_elbow_joint"] ] ) for side in ("left", "right") } self._nominal_ctrl = np.zeros(self.model.nu, dtype=np.float64) self._configure_prepared_pose() self._prepared_base = np.asarray( [0.080000, 0.0, 0.820000, 1.0, 0.0, 0.0, 0.0], dtype=np.float64, ) self._control_scale = self._make_control_scale() self.action_space = spaces.Box( low=-1.0, high=1.0, shape=(self.action_dim,), dtype=np.float32 ) # 9 orientation + 6 floating-base velocities + 2x29 policy-joint # states + 4 ascender + 8 physical foot/contact + 6 task + 29 previous # actions. The flexible cable's internal coordinates are deliberately # omitted; the robot senses the device load, not every rope element. self.obs_dim = 9 + 6 + 2 * self.action_dim + 4 + 8 + 6 + self.action_dim self.observation_space = spaces.Box( low=-np.inf, high=np.inf, shape=(self.obs_dim,), dtype=np.float32, ) self.total_mass = float(mujoco.mj_getTotalmass(self.model)) self._rope_body_ids = { index for index in range(self.model.nbody) if ( mujoco.mj_id2name( self.model, mujoco.mjtObj.mjOBJ_BODY, index ) or "" ).startswith("rope_") } leg_name_parts = ("hip_", "knee_", "ankle_") self._leg_body_ids = { index for index in range(self.model.nbody) if any( part in ( mujoco.mj_id2name( self.model, mujoco.mjtObj.mjOBJ_BODY, index ) or "" ) for part in leg_name_parts ) } # Exclude the rope from load normalization; the stock G1 is about 35 kg. rope_mass = sum( float(self.model.body_mass[index]) for index in self._rope_body_ids ) self.robot_weight = max((self.total_mass - rope_mass) * 9.81, 1.0) self._renderer: mujoco.Renderer | None = None self._step_count = 0 self._start_progress = 0.0 self._previous_progress = 0.0 self._previous_qualified_progress = 0.0 self._previous_lateral_offset = 0.0 self._high_water_progress = 0.0 self._start_slide = 0.0 self._previous_slide = 0.0 self._ratchet_high_water = 0.0 self._last_action = np.zeros(self.action_dim, dtype=np.float64) self._last_line_load = 0.0 self._last_lanyard_load = 0.0 self._previous_contacts = {"left": True, "right": True} self._last_landing_side: str | None = None self._landing_count = 0 self._alternating_landings = 0 self._post_second_grounded_streak = 0 self._post_third_grounded_streak = 0 self._last_landing_progress = {"left": 0.0, "right": 0.0} self._foot_high_water = {"left": 0.0, "right": 0.0} self._foot_air_steps = {"left": 0, "right": 0} self._initial_foot_progress = {"left": 0.0, "right": 0.0} self._maximum_boot_anchor_loss_m = 0.0 self._current_single_support_steps = 0 self._maximum_single_support_steps = 0 self._supported_single_support_streak = 0 self._maximum_supported_single_support_steps = 0 self._current_swing_advance = 0.0 self._maximum_swing_advance = 0.0 self._maximum_supported_swing_advance = 0.0 self._maximum_shaped_supported_swing_advance = 0.0 self._right_elbow_min = 0.0 self._right_elbow_max = 0.0 self._cycle_armed = False self._cycle_reach_elbow = 0.0 self._cycle_min_lead = 0.0 self._cycle_max_flexion = 0.0 self._cycle_peak_load = 0.0 self._cycle_landing_start = 0 self._technique_cycles = 0 self._airborne_streak = 0 self._maximum_airborne_streak = 0 self._grounded_steps = 0 self._double_support_steps = 0 self._nonfoot_snow_contact_steps = 0 self._line_loaded_steps = 0 self._target_lanyard_support_streak = 0 self._maximum_target_lanyard_support_streak = 0 self._lanyard_load_sum_n = 0.0 self._active_lanyard_load_sum_n = 0.0 self._active_lanyard_steps = 0 self._rope_leg_contact_steps = 0 self._rope_cam_lost_streak = 0 self._maximum_rope_cam_lost_streak = 0 self._cache_grounded_prepared_state() def _cache_grounded_prepared_state(self) -> None: """Settle the prepared grasp once and cache its grounded state. The original reset stopped after 0.16 s, exactly while the stiff boot contacts were rebounding. Both boots were airborne at the first policy step, so PPO was unintentionally trained to hang from the line. Settling once per environment (rather than once per episode) produces the intended static, two-boot initial condition without adding a gait, trajectory, or force controller. """ self.model.jnt_range[self._slide_joint_id] = self._ratchet_original_range mujoco.mj_resetData(self.model, self.data) self.data.qpos[ self._base_qpos_address : self._base_qpos_address + 7 ] = self._prepared_base self.data.qpos[self._actuator_qpos_addresses] = self._nominal_ctrl self.data.qpos[self._slide_qpos_address] = 0.0 self.data.ctrl[:] = self._nominal_ctrl mujoco.mj_forward(self.model, self.data) for _ in range(self.prepared_settle_steps): self.data.qfrc_applied.fill(0.0) mujoco.mj_step(self.model, self.data) mujoco.mj_forward(self.model, self.data) contacts, _loads = self._foot_contacts() if not (contacts["left"] and contacts["right"]): raise RuntimeError( "prepared fixed-line state did not settle onto both boots" ) self._prepared_qpos = self.data.qpos.copy() def _id(self, object_type: mujoco.mjtObj, name: str) -> int: result = mujoco.mj_name2id(self.model, object_type, name) if result < 0: raise ValueError(f"MuJoCo object not found: {name}") return int(result) def _set_named_targets(self, values: dict[str, float]) -> None: for name, value in values.items(): self._nominal_ctrl[self._actuator_ids[name]] = value def _configure_prepared_pose(self) -> None: for side in ("left", "right"): self._set_named_targets( { f"{side}_hip_pitch_joint": -0.30, f"{side}_hip_roll_joint": 0.0, f"{side}_hip_yaw_joint": 0.0, f"{side}_knee_joint": 0.60, # Match each boot sole to the 28-degree slope. The old # target left the boots nearly horizontal, so the robot # slowly folded onto its knees once the lanyard went # slack even though the short reset looked standing. f"{side}_ankle_pitch_joint": -0.60, f"{side}_ankle_roll_joint": 0.0, } ) self._set_named_targets( { "waist_yaw_joint": 0.0, "waist_roll_joint": 0.0, # A modest downhill/backward lean loads the fixed line while # the pelvis remains high enough for boot-only support. "waist_pitch_joint": -0.15, } ) arms = { "left": (-0.25, 0.25, 0.0, 0.65, 0.0, 0.02, 0.0), "right": ( -0.900000, -0.450000, -0.250000, 0.800000, 0.0, 0.0, 0.0, ), } arm_joints = ( "shoulder_pitch", "shoulder_roll", "shoulder_yaw", "elbow", "wrist_roll", "wrist_pitch", "wrist_yaw", ) for side, values in arms.items(): self._set_named_targets( { f"{side}_{joint}_joint": value for joint, value in zip(arm_joints, values) } ) # Finger joints hold a single prepared grasp. They never animate and # are not used to create locomotion; the policy controls every moving # body joint that can produce the pull and step technique. self._set_named_targets( { "left_hand_thumb_0_joint": 0.05, "left_hand_thumb_1_joint": 0.22, "left_hand_thumb_2_joint": 0.20, "left_hand_middle_0_joint": -0.25, "left_hand_middle_1_joint": -0.35, "left_hand_index_0_joint": -0.25, "left_hand_index_1_joint": -0.35, "right_hand_thumb_0_joint": -0.10, "right_hand_thumb_1_joint": -0.70, "right_hand_thumb_2_joint": -0.85, "right_hand_middle_0_joint": 0.85, "right_hand_middle_1_joint": 1.10, "right_hand_index_0_joint": 0.85, "right_hand_index_1_joint": 1.10, } ) def _make_control_scale(self) -> np.ndarray: scale_by_suffix = { "hip_pitch_joint": 0.75, "hip_roll_joint": 0.32, "hip_yaw_joint": 0.35, "knee_joint": 0.80, "ankle_pitch_joint": 0.30, "ankle_roll_joint": 0.20, "waist_yaw_joint": 0.30, "waist_roll_joint": 0.24, "waist_pitch_joint": 0.42, "shoulder_pitch_joint": 0.90, "shoulder_roll_joint": 0.70, "shoulder_yaw_joint": 0.85, "elbow_joint": 0.95, "wrist_roll_joint": 0.45, "wrist_pitch_joint": 0.45, "wrist_yaw_joint": 0.45, } result = [] for name in self.POLICY_JOINTS: match = next( value for suffix, value in scale_by_suffix.items() if name.endswith(suffix) ) result.append(match) return np.asarray(result, dtype=np.float64) def _progress(self) -> float: return float(np.dot(self.data.xpos[self.pelvis_body_id], self.uphill)) def _normal_height(self, position: np.ndarray) -> float: return float(np.dot(position, self.slope_normal)) def _object_linear_velocity(self, body_id: int) -> np.ndarray: velocity = np.zeros(6, dtype=np.float64) mujoco.mj_objectVelocity( self.model, self.data, mujoco.mjtObj.mjOBJ_BODY, body_id, velocity, 0, ) return velocity[3:].copy() def _foot_contacts(self) -> tuple[dict[str, bool], dict[str, float]]: contacts = {"left": False, "right": False} loads = {"left": 0.0, "right": 0.0} contact_force = np.zeros(6, dtype=np.float64) for index in range(self.data.ncon): contact = self.data.contact[index] if self.ice_face_geom_id not in (contact.geom1, contact.geom2): continue other_geom = ( contact.geom2 if contact.geom1 == self.ice_face_geom_id else contact.geom1 ) # A flex/plane contact uses geom id -1 on the flex side. if other_geom < 0: continue other_body = int(self.model.geom_bodyid[other_geom]) side = next( ( candidate for candidate, body_id in self._foot_body_ids.items() if body_id == other_body ), None, ) if side is None: continue mujoco.mj_contactForce(self.model, self.data, index, contact_force) contacts[side] = True loads[side] += max(float(contact_force[0]), 0.0) return contacts, loads def _nonfoot_snow_contact(self) -> bool: """Whether a robot link other than either boot touches the slope.""" for index in range(self.data.ncon): contact = self.data.contact[index] if self.ice_face_geom_id not in (contact.geom1, contact.geom2): continue other_geom = ( contact.geom2 if contact.geom1 == self.ice_face_geom_id else contact.geom1 ) if other_geom < 0: continue other_body = int(self.model.geom_bodyid[other_geom]) if ( other_body in self._robot_body_ids and other_body not in self._boot_body_ids ): return True return False def _lanyard_tension(self) -> float: """Return passive harness-lanyard tension from the tendon limit.""" tension = 0.0 tendon_limit_type = int(mujoco.mjtConstraint.mjCNSTR_LIMIT_TENDON) for index in range(self.data.nefc): if ( int(self.data.efc_type[index]) == tendon_limit_type and int(self.data.efc_id[index]) == self._lanyard_tendon_id ): tension = max(tension, float(self.data.efc_force[index])) return tension def rope_contact_audit(self) -> tuple[int, bool]: """Return rope/snow contact count and whether rope touches a leg.""" rope_snow_contacts = 0 rope_touches_leg = False for index in range(self.data.ncon): contact = self.data.contact[index] for rope_side, other_side in ((0, 1), (1, 0)): if int(contact.flex[rope_side]) != self.rope_flex_id: continue other_geom = int(contact.geom[other_side]) rope_snow_contacts += int( other_geom == self.ice_face_geom_id ) if other_geom >= 0: other_body = int(self.model.geom_bodyid[other_geom]) rope_touches_leg = ( rope_touches_leg or other_body in self._leg_body_ids ) return rope_snow_contacts, rope_touches_leg def rope_deformation_audit(self) -> dict[str, float]: """Measure physical flex-rope strain, lift, curvature, and cam contact.""" vertex_slice = slice( self._rope_vertex_address, self._rope_vertex_address + self._rope_vertex_count, ) vertices = self.data.flexvert_xpos[vertex_slice] edge_slice = slice( self._rope_edge_address, self._rope_edge_address + self._rope_edge_count, ) edges = self.model.flex_edge[edge_slice] edge_lengths = np.linalg.norm( self.data.flexvert_xpos[edges[:, 1]] - self.data.flexvert_xpos[edges[:, 0]], axis=1, ) rest_length = float(self.model.flexedge_length0[edge_slice].sum()) rope_length = float(edge_lengths.sum()) normal_height = vertices @ self.slope_normal baseline_height = float(np.quantile(normal_height, 0.20)) max_lift = max(float(normal_height.max()) - baseline_height, 0.0) if len(vertices) >= 3: midpoint_error = vertices[1:-1] - 0.5 * ( vertices[:-2] + vertices[2:] ) max_curvature = float( np.linalg.norm(midpoint_error, axis=1).max() ) else: max_curvature = 0.0 cam_contacts = 0 for index in range(self.data.ncon): contact = self.data.contact[index] for rope_side, other_side in ((0, 1), (1, 0)): if int(contact.flex[rope_side]) != self.rope_flex_id: continue cam_contacts += int( int(contact.geom[other_side]) in self._ascender_rope_geom_ids ) return { "rope_length_m": rope_length, "rope_strain": rope_length / max(rest_length, 1e-9) - 1.0, "rope_max_lift_m": max_lift, "rope_max_curvature_m": max_curvature, "rope_cam_contacts": float(cam_contacts), } def _rope_leg_center_clearance(self) -> float: """Continuous proxy for clearance before a rope/leg contact occurs.""" vertex_slice = slice( self._rope_vertex_address, self._rope_vertex_address + self._rope_vertex_count, ) vertices = self.data.flexvert_xpos[vertex_slice] leg_centers = self.data.xpos[np.fromiter( self._leg_body_ids, dtype=np.int32 )] return float( np.min( np.linalg.norm( vertices[:, np.newaxis, :] - leg_centers[np.newaxis, :, :], axis=2, ) ) ) def _metrics(self) -> dict[str, float]: pelvis = self.data.xpos[self.pelvis_body_id] torso_rotation = self.data.xmat[self.torso_body_id].reshape(3, 3) torso_forward = torso_rotation[:, 0] heading_tangent = torso_forward - np.dot( torso_forward, self.slope_normal ) * self.slope_normal heading_norm = max(float(np.linalg.norm(heading_tangent)), 1e-9) contacts, loads = self._foot_contacts() slide = float(self.data.qpos[self._slide_qpos_address]) grip_error = float( np.linalg.norm( self.data.site_xpos[self.ascender_grip_site_id] - ( self.data.xpos[self.right_wrist_body_id] + self.data.xmat[self.right_wrist_body_id].reshape(3, 3) @ self._palm_grip_local ) ) ) right_elbow = float( self.data.qpos[self._elbow_qpos_addresses["right"]] ) current_boot_anchor_loss = max( max( self._initial_foot_progress[side] - float( np.dot( self.data.site_xpos[self._foot_site_ids[side]], self.uphill, ) ), 0.0, ) for side in ("left", "right") ) metrics = { "ascent": self._progress() - self._start_progress, "high_water_ascent": self._high_water_progress - self._start_progress, "descent_from_high_water": self._high_water_progress - self._progress(), "ascender_advance": slide - self._start_slide, "ascender_ratchet_gap": self._ratchet_high_water - slide, "ascender_load_n": self._last_line_load, "lanyard_load_n": self._last_lanyard_load, "line_support_fraction": self._last_line_load / self.robot_weight, "lanyard_support_fraction": self._last_lanyard_load / self.robot_weight, "pelvis_normal_height": self._normal_height(pelvis), "lateral_offset": abs(float(pelvis[1])), "upright_score": float(torso_rotation[2, 2]), "line_heading_alignment": float( np.dot(heading_tangent / heading_norm, self.uphill) ), # Positive means the chest-forward axis points uphill and upward, # i.e. the torso is leaning backward/downhill into the rope. "backward_lean": float(torso_forward[2]), "left_boot_contact": float(contacts["left"]), "right_boot_contact": float(contacts["right"]), "left_boot_load_n": loads["left"], "right_boot_load_n": loads["right"], "current_boot_anchor_loss_m": current_boot_anchor_loss, "maximum_boot_anchor_loss_m": ( self._maximum_boot_anchor_loss_m ), "ground_load_n": loads["left"] + loads["right"], "grip_constraint_error_m": grip_error, "right_elbow_rad": right_elbow, "right_elbow_min_rad": self._right_elbow_min, "right_elbow_peak_rad": self._right_elbow_max, "right_elbow_excursion_rad": self._right_elbow_max - self._right_elbow_min, "physical_landings": float(self._landing_count), "alternating_landings": float(self._alternating_landings), "post_second_grounded_streak": float( self._post_second_grounded_streak ), "post_third_grounded_streak": float( self._post_third_grounded_streak ), "technique_cycles": float(self._technique_cycles), "rope_leg_contact_steps": float(self._rope_leg_contact_steps), "maximum_rope_cam_lost_streak": float( self._maximum_rope_cam_lost_streak ), "maximum_airborne_streak": float(self._maximum_airborne_streak), "maximum_single_support_steps": float( self._maximum_single_support_steps ), "current_single_support_steps": float( self._current_single_support_steps ), "supported_single_support_streak": float( self._supported_single_support_streak ), "maximum_supported_single_support_steps": float( self._maximum_supported_single_support_steps ), "current_swing_advance_m": self._current_swing_advance, "maximum_swing_advance_m": self._maximum_swing_advance, "maximum_supported_swing_advance_m": ( self._maximum_supported_swing_advance ), "maximum_shaped_supported_swing_advance_m": ( self._maximum_shaped_supported_swing_advance ), "grounded_fraction": self._grounded_steps / max(self._step_count, 1), "double_support_fraction": self._double_support_steps / max(self._step_count, 1), "nonfoot_snow_contact": float(self._nonfoot_snow_contact()), "nonfoot_snow_contact_steps": float( self._nonfoot_snow_contact_steps ), "line_loaded_fraction": self._line_loaded_steps / max(self._step_count, 1), "target_lanyard_support_streak": float( self._target_lanyard_support_streak ), "maximum_target_lanyard_support_streak": float( self._maximum_target_lanyard_support_streak ), "mean_lanyard_load_n": self._lanyard_load_sum_n / max(self._step_count, 1), "mean_active_lanyard_load_n": self._active_lanyard_load_sum_n / max(self._active_lanyard_steps, 1), "rope_leg_center_clearance_m": self._rope_leg_center_clearance(), } metrics.update(self.rope_deformation_audit()) return metrics def _get_obs(self) -> np.ndarray: pelvis_position = self.data.xpos[self.pelvis_body_id] rotation = self.data.xmat[self.pelvis_body_id].reshape(3, 3) base_velocity = self.data.qvel[ self._base_dof_address : self._base_dof_address + 6 ] joint_error = ( self.data.qpos[self._policy_qpos_addresses] - self._nominal_ctrl[self._policy_actuator_ids] ) / self._control_scale joint_velocity = self.data.qvel[self._policy_dof_addresses] * 0.08 slide = float(self.data.qpos[self._slide_qpos_address]) ascender = np.asarray( [ slide - self._start_slide, float(self.data.qvel[self._slide_dof_address]) * 0.20, (self._ratchet_high_water - slide) * 20.0, self._last_line_load / self.robot_weight, ] ) contacts, loads = self._foot_contacts() foot_positions = { side: self.data.site_xpos[site_id] for side, site_id in self._foot_site_ids.items() } foot_velocities = { side: self._object_linear_velocity(body_id) for side, body_id in self._foot_body_ids.items() } feet = np.asarray( [ float(contacts["left"]), float(contacts["right"]), loads["left"] / self.robot_weight, loads["right"] / self.robot_weight, float(np.dot(foot_positions["left"], self.uphill) - self._progress()), float(np.dot(foot_positions["right"], self.uphill) - self._progress()), float(np.dot(foot_velocities["left"], self.uphill)) * 0.25, float(np.dot(foot_velocities["right"], self.uphill)) * 0.25, ] ) metrics = self._metrics() task = np.asarray( [ metrics["ascent"] / self.POLICY_ASCENT_OBSERVATION_SCALE, metrics["descent_from_high_water"] * 5.0, metrics["pelvis_normal_height"], metrics["upright_score"], metrics["lateral_offset"] * 2.0, float(pelvis_position[1]) * 2.0, ] ) observation = np.concatenate( [ rotation.ravel(), base_velocity[:3] * 0.10, base_velocity[3:] * 0.25, joint_error, joint_velocity, ascender, feet, task, self._last_action, ] ) if observation.shape != (self.obs_dim,): raise RuntimeError( f"Observation contract is {observation.shape}, expected {(self.obs_dim,)}" ) return observation.astype(np.float32) def _advance_ratchet(self) -> None: slide = float(self.data.qpos[self._slide_qpos_address]) self._ratchet_high_water = max(self._ratchet_high_water, slide) # Updating a unilateral joint limit is the cam law. It can stop # downslope motion but cannot inject positive/uphill work. self.model.jnt_range[self._slide_joint_id, 0] = max( self._ratchet_original_range[0], self._ratchet_high_water - 0.002 ) def reset( self, *, seed: int | None = None, options: dict[str, Any] | None = None, ) -> tuple[np.ndarray, dict[str, Any]]: super().reset(seed=seed) options = options or {} randomized = bool(options.get("randomize", self.randomize_reset)) randomization_scale = float( options.get("randomization_scale", self.randomization_scale) ) if randomization_scale < 0.0: raise ValueError("randomization_scale must be non-negative") self.model.jnt_range[self._slide_joint_id] = self._ratchet_original_range mujoco.mj_resetData(self.model, self.data) self.data.qpos[:] = self._prepared_qpos self.data.qvel.fill(0.0) base = self.data.qpos[ self._base_qpos_address : self._base_qpos_address + 7 ].copy() if randomized: base[:3] += self.np_random.normal( 0.0, np.asarray([0.005, 0.006, 0.004]) ) * randomization_scale self.data.qpos[ self._base_qpos_address : self._base_qpos_address + 7 ] = base self.data.ctrl[:] = self._nominal_ctrl if randomized: noise = self.np_random.normal( 0.0, 0.006 * randomization_scale, self.action_dim ) self.data.qpos[self._policy_qpos_addresses] += noise self.data.qvel[self._policy_dof_addresses] = self.np_random.normal( 0.0, 0.006 * randomization_scale, self.action_dim ) mujoco.mj_forward(self.model, self.data) # Let small randomized reset perturbations settle with the cam open. # The deterministic reset uses the already-settled cached state. settle_steps = ( int(round(self.randomized_settle_steps * randomization_scale)) if randomized else 0 ) for _ in range(settle_steps): self.data.qfrc_applied.fill(0.0) mujoco.mj_step(self.model, self.data) mujoco.mj_forward(self.model, self.data) self._step_count = 0 self._start_progress = self._progress() self._previous_progress = self._start_progress self._previous_qualified_progress = 0.0 self._previous_lateral_offset = abs( float(self.data.xpos[self.pelvis_body_id, 1]) ) self._high_water_progress = self._start_progress self._start_slide = float(self.data.qpos[self._slide_qpos_address]) self._previous_slide = self._start_slide self._ratchet_high_water = self._start_slide self.model.jnt_range[self._slide_joint_id, 0] = ( self._ratchet_high_water - 0.002 ) self._last_action.fill(0.0) self._last_lanyard_load = self._lanyard_tension() self._last_line_load = self._last_lanyard_load contacts, _loads = self._foot_contacts() self._previous_contacts = contacts.copy() self._last_landing_side = None self._landing_count = 0 self._alternating_landings = 0 self._post_second_grounded_streak = 0 self._post_third_grounded_streak = 0 self._last_landing_progress = { side: float( np.dot(self.data.site_xpos[site_id], self.uphill) ) for side, site_id in self._foot_site_ids.items() } self._foot_high_water = self._last_landing_progress.copy() self._initial_foot_progress = self._last_landing_progress.copy() self._maximum_boot_anchor_loss_m = 0.0 self._foot_takeoff_progress = self._last_landing_progress.copy() self._foot_air_high_water = self._last_landing_progress.copy() self._previous_air_swing_displacement = { "left": 0.0, "right": 0.0, } self._foot_air_steps = {"left": 0, "right": 0} self._current_single_support_steps = 0 self._maximum_single_support_steps = 0 self._supported_single_support_streak = 0 self._maximum_supported_single_support_steps = 0 self._current_swing_advance = 0.0 self._maximum_swing_advance = 0.0 self._maximum_supported_swing_advance = 0.0 self._maximum_shaped_supported_swing_advance = 0.0 elbow = float(self.data.qpos[self._elbow_qpos_addresses["right"]]) self._right_elbow_min = elbow self._right_elbow_max = elbow self._cycle_armed = False self._cycle_reach_elbow = elbow self._cycle_min_lead = 0.0 self._cycle_max_flexion = 0.0 self._cycle_peak_load = 0.0 self._cycle_full_pull = False self._cycle_landing_start = 0 self._technique_cycles = 0 self._airborne_streak = 0 self._maximum_airborne_streak = 0 self._grounded_steps = 0 self._double_support_steps = 0 self._nonfoot_snow_contact_steps = 0 self._line_loaded_steps = 0 self._target_lanyard_support_streak = 0 self._maximum_target_lanyard_support_streak = 0 self._lanyard_load_sum_n = 0.0 self._active_lanyard_load_sum_n = 0.0 self._active_lanyard_steps = 0 self._rope_leg_contact_steps = 0 self._rope_cam_lost_streak = 0 self._maximum_rope_cam_lost_streak = 0 info = self._metrics() info.update({"success": False, "failure": False}) return self._get_obs(), info def step( self, action: np.ndarray ) -> tuple[np.ndarray, float, bool, bool, dict[str, Any]]: self._step_count += 1 command = np.clip(np.asarray(action, dtype=np.float64), -1.0, 1.0) # The actuator target has the same first-order response on every # policy step, including the first one after reset. Bypassing this # filter for step one let a policy produce an implausible, effectively # instantaneous reach before the physical motor response took over. filtered = self.action_filter * self._last_action + ( 1.0 - self.action_filter ) * command target = self._nominal_ctrl.copy() target[self._policy_actuator_ids] += self._control_scale * filtered self.data.ctrl[:] = np.clip( target, self.model.actuator_ctrlrange[:, 0], self.model.actuator_ctrlrange[:, 1], ) ascender_slide_load_peak = 0.0 lanyard_load_peak = 0.0 for _ in range(self.frame_skip): self._advance_ratchet() # This explicit zero is an audit guard: the environment applies no # hidden generalized forces to the robot or ascender. self.data.qfrc_applied.fill(0.0) mujoco.mj_step(self.model, self.data) ascender_slide_load_peak = max( ascender_slide_load_peak, abs(float(self.data.qfrc_constraint[self._slide_dof_address])), ) lanyard_load_peak = max( lanyard_load_peak, self._lanyard_tension() ) # The passive lanyard is the load path from the harness to the # ascender. The slide constraint is retained as a conservative # fallback for direct hand loading before the lanyard goes taut. line_load_peak = max(ascender_slide_load_peak, lanyard_load_peak) self._last_lanyard_load = lanyard_load_peak self._last_line_load = line_load_peak mujoco.mj_forward(self.model, self.data) progress_absolute = self._progress() self._high_water_progress = max( self._high_water_progress, progress_absolute ) slide = float(self.data.qpos[self._slide_qpos_address]) slide_delta = slide - self._previous_slide contacts, loads = self._foot_contacts() nonfoot_snow_contact = self._nonfoot_snow_contact() self._nonfoot_snow_contact_steps += int(nonfoot_snow_contact) # Count body-weight support only through the passive harness lanyard. # Direct hand/cam constraint impulses are useful for collision audit, # but they do not prove that the fixed line is carrying the robot. self._line_loaded_steps += int( lanyard_load_peak >= 0.30 * self.robot_weight ) self._lanyard_load_sum_n += lanyard_load_peak if lanyard_load_peak >= 0.10 * self.robot_weight: self._active_lanyard_load_sum_n += lanyard_load_peak self._active_lanyard_steps += 1 landing_bonus = 0.0 swing_advance_reward = 0.0 swing_displacement_delta = 0.0 landing_count_before = self._landing_count maximum_supported_single_support_before = ( self._maximum_supported_single_support_steps ) maximum_supported_swing_advance_before = ( self._maximum_supported_swing_advance ) maximum_shaped_supported_swing_advance_before = ( self._maximum_shaped_supported_swing_advance ) self._current_swing_advance = 0.0 for side in ("left", "right"): foot_progress = float( np.dot( self.data.site_xpos[self._foot_site_ids[side]], self.uphill, ) ) previous_foot_high_water = self._foot_high_water[side] self._foot_high_water[side] = max( previous_foot_high_water, foot_progress ) other = "right" if side == "left" else "left" if not contacts[side] and self._previous_contacts[side]: # Measure swing from the physical takeoff point, not from the # reset footprint. A precursor may first arrest some slip; # requiring it to erase all earlier displacement before any # swing reward made the missing airborne motion effectively # invisible. Later landing/ascent stages still require net # uphill progress and therefore cannot pass by sliding. self._foot_takeoff_progress[side] = foot_progress self._foot_air_high_water[side] = foot_progress self._previous_air_swing_displacement[side] = 0.0 if not contacts[side] and contacts[other]: # Dense credit comes from measured unsupported-foot motion. # No desired pose, limb order, or time phase is supplied. current_air_swing_displacement = ( foot_progress - self._foot_takeoff_progress[side] ) swing_displacement_delta += ( current_air_swing_displacement - self._previous_air_swing_displacement[side] ) self._previous_air_swing_displacement[side] = ( current_air_swing_displacement ) previous_air_high_water = self._foot_air_high_water[side] self._foot_air_high_water[side] = max( previous_air_high_water, foot_progress ) swing_advance_reward += 7.0 * max( self._foot_air_high_water[side] - previous_air_high_water, 0.0, ) self._maximum_swing_advance = max( self._maximum_swing_advance, self._foot_air_high_water[side] - self._foot_takeoff_progress[side], ) # Keep the instantaneous displacement signed. A downhill # unsupported-foot drift must remain distinguishable from a # neutral takeoff so black-box search and PPO have a gradient # toward the required uphill motion. Episode maxima below # remain one-sided success evidence. self._current_swing_advance = current_air_swing_displacement air_steps_before_landing = self._foot_air_steps[side] if not contacts[side]: self._foot_air_steps[side] += 1 if contacts[other]: self._maximum_single_support_steps = max( self._maximum_single_support_steps, self._foot_air_steps[side], ) if contacts[side] and not self._previous_contacts[side]: step_distance = foot_progress - self._last_landing_progress[side] if air_steps_before_landing >= 8 and step_distance > 0.045: self._last_landing_progress[side] = foot_progress self._landing_count += 1 base_landing_bonus = ( 0.50 + min(step_distance, 0.20) * 10.0 ) if self._last_landing_side is None: landing_bonus += base_landing_bonus elif side != self._last_landing_side: self._alternating_landings += 1 landing_bonus += base_landing_bonus + 12.00 else: # Same-side hopping is physically valid but is not the # alternating step pattern required by this task. Keep # its measured uphill-landing credit while withholding # the much larger alternation bonus; discarding the # base credit made a valid third landing score below a # two-step fall in the recovery curriculum. landing_bonus += base_landing_bonus - 0.50 self._last_landing_side = side self._foot_air_steps[side] = 0 if contacts["left"] != contacts["right"]: airborne_side = "right" if contacts["left"] else "left" self._current_single_support_steps = self._foot_air_steps[ airborne_side ] else: self._current_single_support_steps = 0 self._previous_contacts = contacts.copy() current_boot_anchor_loss = max( max( self._initial_foot_progress[side] - float( np.dot( self.data.site_xpos[self._foot_site_ids[side]], self.uphill, ) ), 0.0, ) for side in ("left", "right") ) self._maximum_boot_anchor_loss_m = max( self._maximum_boot_anchor_loss_m, current_boot_anchor_loss, ) if contacts["left"] or contacts["right"]: self._airborne_streak = 0 self._grounded_steps += 1 else: self._airborne_streak += 1 if contacts["left"] and contacts["right"]: self._double_support_steps += 1 if self._landing_count >= 2: if contacts["left"] or contacts["right"]: self._post_second_grounded_streak += 1 else: self._post_second_grounded_streak = 0 if self._landing_count >= 3: if contacts["left"] or contacts["right"]: self._post_third_grounded_streak += 1 else: self._post_third_grounded_streak = 0 self._maximum_airborne_streak = max( self._maximum_airborne_streak, self._airborne_streak ) right_elbow = float( self.data.qpos[self._elbow_qpos_addresses["right"]] ) self._right_elbow_min = min(self._right_elbow_min, right_elbow) self._right_elbow_max = max(self._right_elbow_max, right_elbow) metrics = self._metrics() new_second_landing = bool( landing_count_before < 2 <= self._landing_count ) new_third_landing = bool( landing_count_before < 3 <= self._landing_count ) _rope_snow_contacts, rope_touches_leg = self.rope_contact_audit() self._rope_leg_contact_steps += int(rope_touches_leg) if metrics["rope_cam_contacts"] > 0: self._rope_cam_lost_streak = 0 else: self._rope_cam_lost_streak += 1 self._maximum_rope_cam_lost_streak = max( self._maximum_rope_cam_lost_streak, self._rope_cam_lost_streak, ) rope_leg_proximity = float( np.clip( (0.10 - metrics["rope_leg_center_clearance_m"]) / 0.08, 0.0, 1.0, ) ) # Technique and uphill progress only earn positive credit while the # flexible line is inside the cam channel and clear of the legs. This # is an outcome constraint, not a pose, gait phase, or reference # motion: the policy remains free to discover how to maintain it. safe_line_motion = bool( not rope_touches_leg and not nonfoot_snow_contact and metrics["rope_cam_contacts"] > 0 and metrics["line_heading_alignment"] >= 0.70 ) grounded_technique_posture = bool( (contacts["left"] or contacts["right"]) and not nonfoot_snow_contact and metrics["upright_score"] >= 0.80 and metrics["pelvis_normal_height"] >= 0.55 and metrics["line_heading_alignment"] >= 0.75 # The mechanically relevant posture is line loading with boot # support. Torso pitch remains free to range from slightly # forward to moderately backward as the learner balances. and -0.12 <= metrics["backward_lean"] <= 0.35 and self._maximum_airborne_streak <= 15 ) lanyard_support_fraction = metrics["lanyard_support_fraction"] target_lanyard_support = bool( grounded_technique_posture and self.MIN_LANYARD_SUPPORT_FRACTION <= lanyard_support_fraction <= self.MAX_LANYARD_SUPPORT_FRACTION ) if target_lanyard_support: self._target_lanyard_support_streak += 1 self._maximum_supported_swing_advance = max( self._maximum_supported_swing_advance, self._current_swing_advance, ) else: self._target_lanyard_support_streak = 0 # Count only an uninterrupted, simultaneous one-boot stance inside # the strict posture and lanyard-load gate. The former implementation # copied the unsupported foot's total airborne age on any one valid # frame; a foot that had already been airborne for 89 collapsed frames # could therefore masquerade as 89 frames of supported stance. if target_lanyard_support and self._current_single_support_steps > 0: self._supported_single_support_streak += 1 else: self._supported_single_support_streak = 0 self._maximum_supported_single_support_steps = max( self._maximum_supported_single_support_steps, self._supported_single_support_streak, ) supported_swing_advance_milestone = ( self._maximum_supported_swing_advance - maximum_supported_swing_advance_before ) supported_single_support_milestone = ( self._maximum_supported_single_support_steps - maximum_supported_single_support_before ) self._maximum_target_lanyard_support_streak = max( self._maximum_target_lanyard_support_streak, self._target_lanyard_support_streak, ) metrics["target_lanyard_support_streak"] = float( self._target_lanyard_support_streak ) metrics["maximum_target_lanyard_support_streak"] = float( self._maximum_target_lanyard_support_streak ) metrics["current_single_support_steps"] = float( self._current_single_support_steps ) metrics["supported_single_support_streak"] = float( self._supported_single_support_streak ) metrics["maximum_supported_single_support_steps"] = float( self._maximum_supported_single_support_steps ) metrics["current_swing_advance_m"] = self._current_swing_advance metrics["maximum_supported_swing_advance_m"] = ( self._maximum_supported_swing_advance ) raw_support_target_score = float( np.exp( -0.5 * ( ( lanyard_support_fraction - self.TARGET_LANYARD_SUPPORT_FRACTION ) / 0.08 ) ** 2 ) ) # Preserve a dense route to the desired force even before the torso # is perfect. Boots and the no-fall gate prevent earning it by lying # on the slope; the strict uninterrupted streak above still requires # full climbing posture for success. support_target_score = raw_support_target_score * float( (contacts["left"] or contacts["right"]) and not nonfoot_snow_contact ) metrics["lanyard_support_target_score"] = support_target_score # The final supported-swing gate above is deliberately strict, but a # hard Boolean supplies no learning signal when a real uphill foot # correction occurs just below the height/load/posture boundary. Use # a smooth, contact-derived near-gate potential for optimization only. # It exposes no clock, foot order, desired pose, or reference action; # success still requires the unmodified simultaneous 6 cm gate. supported_motion_shaping_score = float( support_target_score * float(contacts["left"] != contacts["right"]) * float(safe_line_motion) * np.clip( (metrics["pelvis_normal_height"] - 0.42) / 0.13, 0.0, 1.0, ) * np.clip( (metrics["upright_score"] - 0.68) / 0.12, 0.0, 1.0, ) * np.clip( (metrics["line_heading_alignment"] - 0.55) / 0.20, 0.0, 1.0, ) ) shaped_supported_swing_advance = ( max(self._current_swing_advance, 0.0) * supported_motion_shaping_score ) self._maximum_shaped_supported_swing_advance = max( self._maximum_shaped_supported_swing_advance, shaped_supported_swing_advance, ) shaped_supported_swing_advance_milestone = ( self._maximum_shaped_supported_swing_advance - maximum_shaped_supported_swing_advance_before ) metrics["supported_motion_shaping_score"] = ( supported_motion_shaping_score ) metrics["maximum_shaped_supported_swing_advance_m"] = ( self._maximum_shaped_supported_swing_advance ) technique_cycle_bonus = 0.0 technique_dense_reward = 0.0 ascent = progress_absolute - self._start_progress ascender_advance = slide - self._start_slide ascender_lead = ascender_advance - ascent if not safe_line_motion: # Do not let an arm sequence that used the rope as leg support # resume later and cash in a nominally valid pull-step cycle. self._cycle_armed = False elif ( not self._cycle_armed and grounded_technique_posture and ascender_lead >= 0.16 # A real reach is not a locked elbow. Permit the modest bend # produced while the constrained palm advances the ascender; # completion still requires at least 0.50 rad of subsequent # flexion and an absolute 1.65 rad fully bent elbow. and right_elbow <= 1.20 ): self._cycle_armed = True self._cycle_reach_elbow = right_elbow self._cycle_min_lead = ascender_lead self._cycle_max_flexion = 0.0 self._cycle_peak_load = line_load_peak self._cycle_full_pull = False self._cycle_landing_start = self._landing_count elif self._cycle_armed and grounded_technique_posture: # Only physically supported pulling advances this state. A late # elbow bend during a fall is neither rewarded nor recorded as a # full pull, preventing PPO from exploiting the visual metric # after ground contact has already been lost. previous_min_lead = self._cycle_min_lead self._cycle_peak_load = max( self._cycle_peak_load, line_load_peak ) self._cycle_min_lead = min( self._cycle_min_lead, ascender_lead ) technique_dense_reward += 40.0 * max( previous_min_lead - self._cycle_min_lead, 0.0 ) self._cycle_reach_elbow = min( self._cycle_reach_elbow, right_elbow ) completed_step = self._landing_count > self._cycle_landing_start elbow_flexion = right_elbow - self._cycle_reach_elbow previous_max_flexion = self._cycle_max_flexion self._cycle_max_flexion = max( self._cycle_max_flexion, elbow_flexion ) technique_dense_reward += 12.0 * max( self._cycle_max_flexion - previous_max_flexion, 0.0 ) if ( not self._cycle_full_pull and right_elbow >= 1.65 and self._cycle_peak_load >= 0.40 * self.robot_weight ): self._cycle_full_pull = True technique_dense_reward += 15.0 if ( ascender_lead <= 0.12 and completed_step and self._cycle_full_pull and elbow_flexion >= 0.50 and self._cycle_peak_load >= 0.40 * self.robot_weight ): self._technique_cycles += 1 technique_cycle_bonus = 45.0 self._cycle_armed = False foot_slip = 0.0 for side in ("left", "right"): if contacts[side]: velocity = self._object_linear_velocity( self._foot_body_ids[side] ) tangential = velocity - np.dot( velocity, self.slope_normal ) * self.slope_normal foot_slip += float(np.linalg.norm(tangential)) action_cost = float(np.mean(np.square(filtered))) smoothness_cost = float( np.mean(np.square(filtered - self._last_action)) ) # Keep the climber beside the fixed line instead of letting the # equality-constrained hand drag the pelvis laterally over it. The # offset is already part of the observation, so this is an outcome # objective rather than a prescribed stance or motion reference. lateral_corridor_cost = float( np.clip((metrics["lateral_offset"] - 0.18) / 0.22, 0.0, 2.0) ) upright_deficit = float( np.clip((0.85 - metrics["upright_score"]) / 0.35, 0.0, 2.0) ) stance_height_deficit = float( np.clip( (0.58 - metrics["pelvis_normal_height"]) / 0.25, 0.0, 2.0, ) ) heading_deficit = float( np.clip( (0.85 - metrics["line_heading_alignment"]) / 0.65, 0.0, 2.0, ) ) backward_lean_deficit = float( max(-0.12 - metrics["backward_lean"], 0.0) / 0.20 + max(metrics["backward_lean"] - 0.35, 0.0) / 0.20 ) line_support_deficit = float( max(0.35 - metrics["line_support_fraction"], 0.0) / 0.35 ) line_support_overload = float( max(metrics["line_support_fraction"] - 0.70, 0.0) / 0.30 ) # The task potential is limited by whichever component is behind. An # arm-only reach cannot score sustained progress until the pelvis # follows it; once the pelvis catches up, the device must advance # again. This couples the two physical outcomes without prescribing a # pose, limb order, gait phase, or reference trajectory. task_progress = min(metrics["ascent"], metrics["ascender_advance"]) # Raw distance beyond the initial reach is only unlocked by complete # physical technique cycles. This prevents continuous shuffling or # sliding from overwhelming the pull-step objective. qualified_progress_cap = 0.25 + 0.75 * self._technique_cycles qualified_progress = min(task_progress, qualified_progress_cap) qualified_progress_delta = ( qualified_progress - self._previous_qualified_progress ) # Consume the task potential even during an unsafe step so the policy # cannot climb while entangled and collect the withheld progress after # moving clear. Negative deltas always remain penalties. qualified_progress_credit = min(qualified_progress_delta, 0.0) + ( float(safe_line_motion) * max(qualified_progress_delta, 0.0) ) lateral_recovery = ( self._previous_lateral_offset - metrics["lateral_offset"] ) full_reward = ( 240.0 * qualified_progress_credit + 6.0 * max(slide_delta, 0.0) * float(safe_line_motion) + 2.00 * landing_bonus * float(safe_line_motion) + 0.30 * swing_advance_reward * float(safe_line_motion) + technique_cycle_bonus + technique_dense_reward + 80.0 * lateral_recovery + 0.010 * float(contacts["left"] or contacts["right"]) + 0.005 * float(contacts["left"] and contacts["right"]) + 0.006 * float(np.clip(metrics["upright_score"], 0.0, 1.0)) + 0.006 * float(np.clip(line_load_peak / self.robot_weight, 0.0, 1.5)) - 0.020 * foot_slip - 0.003 * action_cost - 0.008 * smoothness_cost - 0.070 * float(not (contacts["left"] or contacts["right"])) - 3.00 * float(rope_touches_leg) - 1.50 * rope_leg_proximity - 2.00 * float(metrics["rope_cam_contacts"] <= 0) - 1.60 * lateral_corridor_cost - 0.80 * upright_deficit - 0.40 * stance_height_deficit - 0.030 ) full_success = bool( metrics["ascent"] >= self.target_ascent and metrics["ascender_advance"] >= 0.25 and self._landing_count >= 2 and self._alternating_landings >= 1 and self._technique_cycles >= 3 # The rope is collidable, so these are surface brushes rather than # penetration. Limit their total duration to 0.8 s. and self._rope_leg_contact_steps <= 12 and self._nonfoot_snow_contact_steps == 0 and metrics["lateral_offset"] <= 0.50 and metrics["line_heading_alignment"] >= 0.80 and metrics["upright_score"] >= 0.82 and metrics["pelvis_normal_height"] >= 0.55 and metrics["line_loaded_fraction"] >= 0.30 and metrics["right_elbow_peak_rad"] >= 1.65 and metrics["right_elbow_excursion_rad"] >= 0.65 and metrics["grip_constraint_error_m"] < 0.015 and self._maximum_airborne_streak <= 15 ) no_progress_timeout = bool( self._step_count >= 400 and task_progress < 0.025 ) common_failure = bool( metrics["ascent"] < -0.48 or metrics["pelvis_normal_height"] < 0.28 or metrics["lateral_offset"] > 0.70 or metrics["upright_score"] < -0.20 or self._airborne_streak > 35 # Once the rollout exceeds the task's 12-frame brush allowance it # can no longer succeed. Ending it here prevents PPO from using a # long entangled continuation as a locomotion shortcut. or self._rope_leg_contact_steps > 12 or self._nonfoot_snow_contact_steps > 2 or self._rope_cam_lost_streak > 12 or not np.isfinite(self.data.qpos).all() ) grounded = contacts["left"] or contacts["right"] double_support = contacts["left"] and contacts["right"] progress_delta = progress_absolute - self._previous_progress grounded_progress_credit = min(progress_delta, 0.0) + ( float(grounded and safe_line_motion) * max(progress_delta, 0.0) ) ground_load_score = float( np.clip( (loads["left"] + loads["right"]) / self.robot_weight, 0.0, 1.3, ) ) if self.curriculum_stage == "reach": safe_slide_credit = min(slide_delta, 0.0) + ( float(grounded and safe_line_motion) * max(slide_delta, 0.0) ) reward = ( 1500.0 * safe_slide_credit + 30.0 * grounded_progress_credit + 45.0 * lateral_recovery + 0.020 * float(grounded) + 0.010 * float(double_support) - 0.020 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.40 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.00 * lateral_corridor_cost - 0.70 * upright_deficit - 0.40 * stance_height_deficit - 0.010 ) success = bool( # The precursor only has to discover one full device reach. # Later pull/sequence stages require the body to catch up and # repeat it; asking for two reaches here hid the first useful # physical event behind a sparse threshold. metrics["ascender_advance"] >= 0.16 and metrics["grounded_fraction"] >= 0.80 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.38 and metrics["upright_score"] >= 0.50 and metrics["pelvis_normal_height"] >= 0.30 and metrics["right_elbow_excursion_rad"] >= 0.20 and self._maximum_airborne_streak <= 12 and metrics["line_support_fraction"] >= 0.30 ) no_progress_timeout = bool( self._step_count >= 300 and metrics["ascender_advance"] < 0.06 ) failure = common_failure or no_progress_timeout elif self.curriculum_stage in {"lift", "brace", "swing"}: # Split the sparse first step into physical outcomes. The # learner first discovers sustained one-boot support, then moves # that unsupported boot uphill. Neither stage exposes a clock, # desired joint configuration, limb order, or reference action. reward = ( 70.0 * grounded_progress_credit + 1500.0 * max(slide_delta, 0.0) * float(safe_line_motion) + 5.0 * supported_single_support_milestone # Before asking for foot translation, consolidate a sustained # loaded one-boot stance. This counter is an evaluator outcome # only and is not present in the policy observation. + float(self.curriculum_stage == "brace") * 2.0 * float( target_lanyard_support and self._current_single_support_steps > 0 and self._target_lanyard_support_streak <= self.BRACE_SUPPORT_STREAK_STEPS ) + float(self.curriculum_stage == "swing") * 900.0 * supported_swing_advance_milestone + float(self.curriculum_stage == "swing") * 3000.0 * shaped_supported_swing_advance_milestone # Pay a bounded maintenance term so the learner holds a real # uphill correction instead of cashing in its high-water mark # and immediately letting the unsupported boot fall back. + float(self.curriculum_stage == "swing") * 6.0 * float( np.clip( shaped_supported_swing_advance / 0.06, 0.0, 1.0, ) ) # Give a modest gradient for each measured uphill correction, # including recovery before the boot has crossed its takeoff # point. Keep the downhill term much smaller so exploratory # takeoff is not suppressed; the sparse 6 cm success gate and # large terminal reward still dominate any oscillatory motion. + float(self.curriculum_stage == "swing") * ( 120.0 * max(swing_displacement_delta, 0.0) + 120.0 * min(swing_displacement_delta, 0.0) ) * supported_motion_shaping_score # A capped potential leads into the required 12-frame load # window. Once the streak is complete it pays nothing, so a # stationary hang cannot outscore the physical swing. + float(self.curriculum_stage == "swing") * 2.0 * float( target_lanyard_support and self._target_lanyard_support_streak <= self.SUPPORTED_MOTION_STREAK_STEPS ) + 30.0 * lateral_recovery - 0.020 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 1.50 * upright_deficit - 2.00 * stance_height_deficit - 0.010 ) success = bool( metrics["ascender_advance"] >= 0.15 and self._maximum_supported_single_support_steps >= ( self.BRACE_SUPPORT_STREAK_STEPS if self.curriculum_stage == "brace" else 8 ) and ( self.curriculum_stage in {"lift", "brace"} or self._maximum_supported_swing_advance >= 0.06 ) and ( self.curriculum_stage != "brace" or self._maximum_target_lanyard_support_streak >= self.BRACE_SUPPORT_STREAK_STEPS ) and metrics["grounded_fraction"] >= 0.70 and self._rope_leg_contact_steps == 0 and metrics["lateral_offset"] <= 0.42 and metrics["upright_score"] >= 0.70 and metrics["pelvis_normal_height"] >= 0.48 and metrics["line_support_fraction"] >= 0.30 and self._maximum_airborne_streak <= 12 ) no_progress_timeout = bool( self._step_count >= 300 and ( metrics["ascender_advance"] < 0.10 or self._maximum_single_support_steps < 4 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage in {"land", "step"}: # A single learned stepping precursor turns coherent leg # exploration into an attainable physical outcome before asking # for the longer four-landing grounded climb. Every positive # term is measured from contact, unsupported-foot displacement, # or pelvis motion; no desired pose, foot order, or phase exists. reward = ( 160.0 * grounded_progress_credit # Retain the already-learned physical ascender reach while # PPO searches the much sparser foot-contact outcome. This # is measured one-way cam travel, not a desired arm pose or # reference action. Without it, the landing objective can # improve its return by forgetting the reach before it ever # samples a useful landing. + 600.0 * max(slide_delta, 0.0) * float(safe_line_motion) # A first sampled landing initially moves the pelvis downhill # and otherwise has lower return than simply falling without # landing. Give that sparse contact event enough potential # credit to be learnable; the success gate below still # requires net uphill pelvis motion and stable grounding. + 80.0 * landing_bonus * float(safe_line_motion) + 16.0 * swing_advance_reward * float(safe_line_motion) + 45.0 * lateral_recovery - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) if self.curriculum_stage == "land": # First learn to complete and recover one measured uphill # landing. A later stage adds net pelvis ascent; this stage # still rejects a fallen body, long flight, and rope contact. success = bool( metrics["ascent"] >= -0.30 and metrics["ascender_advance"] >= 0.15 and self._landing_count >= 1 and metrics["grounded_fraction"] >= 0.40 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.50 and metrics["upright_score"] >= -0.18 and metrics["pelvis_normal_height"] >= 0.18 and self._maximum_airborne_streak <= 30 ) no_progress_timeout = bool( self._step_count >= 300 and self._landing_count < 1 ) else: success = bool( metrics["ascent"] >= 0.12 and metrics["ascender_advance"] >= 0.25 and self._landing_count >= 1 and metrics["grounded_fraction"] >= 0.55 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.42 and metrics["upright_score"] >= 0.48 and metrics["pelvis_normal_height"] >= 0.28 and self._maximum_airborne_streak <= 25 ) no_progress_timeout = bool( self._step_count >= 350 and ( metrics["ascent"] < 0.05 or self._landing_count < 1 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage == "sequence": # Bridge the learned single landing to the longer climb with a # complete alternating two-foot sequence and physical recovery. # Credit still comes only from measured pelvis/foot outcomes; no # clock, gait phase, target pose, limb order, or reference motion # is exposed to the policy. reward = ( 260.0 * grounded_progress_credit + 60.0 * landing_bonus * float(safe_line_motion) + 12.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.30 and self._landing_count >= 2 and self._alternating_landings >= 1 and metrics["grounded_fraction"] >= 0.50 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.42 and metrics["upright_score"] >= 0.35 and metrics["pelvis_normal_height"] >= 0.25 and self._maximum_airborne_streak <= 30 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 1 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage == "stabilize": # Teach balance immediately after the already-learned alternating # pair, before asking for another step. The streak is a measured # outcome only: it is not observed by the policy and supplies no # phase, clock, pose target, or reference motion. after_second = float(self._landing_count >= 2) bounded_recovery_credit = float( grounded and 0 < self._post_second_grounded_streak <= 15 ) reward = ( 275.0 * grounded_progress_credit + 52.0 * landing_bonus * float(safe_line_motion) + 100.0 * float(new_second_landing and safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery + after_second * ( 2.00 * bounded_recovery_credit + 0.35 * float(double_support) + 0.20 * ground_load_score - 0.80 * upright_deficit - 0.50 * stance_height_deficit ) - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.24 and self._landing_count >= 2 and self._alternating_landings >= 1 and self._post_second_grounded_streak >= 10 and metrics["grounded_fraction"] >= 0.50 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.44 and metrics["upright_score"] >= 0.40 and metrics["pelvis_normal_height"] >= 0.28 and self._maximum_airborne_streak <= 20 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 1 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage == "hold": # Consolidate the recovered alternating pair before exposing the # actor to a longer support objective. Positive support credit is # capped, so it cannot be farmed indefinitely by standing still. after_second = float(self._landing_count >= 2) bounded_hold_credit = float( grounded and 0 < self._post_second_grounded_streak <= 20 ) reward = ( 275.0 * grounded_progress_credit + 52.0 * landing_bonus * float(safe_line_motion) + 100.0 * float(new_second_landing and safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery + after_second * ( 2.00 * bounded_hold_credit + 0.35 * float(double_support) + 0.20 * ground_load_score - 0.80 * upright_deficit - 0.50 * stance_height_deficit ) - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.24 and self._landing_count == 2 and self._alternating_landings >= 1 and self._post_second_grounded_streak >= 15 and metrics["grounded_fraction"] >= 0.55 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.44 and metrics["upright_score"] >= 0.45 and metrics["pelvis_normal_height"] >= 0.30 and self._maximum_airborne_streak <= 20 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 1 ) ) premature_third_landing = self._landing_count >= 3 failure = common_failure or no_progress_timeout or premature_third_landing elif self.curriculum_stage == "sustain": # Intermediate two-foot stability bridge before longer support. # The policy still sees only physical state, never this counter. after_second = float(self._landing_count >= 2) bounded_sustain_credit = float( grounded and 0 < self._post_second_grounded_streak <= 25 ) reward = ( 275.0 * grounded_progress_credit + 52.0 * landing_bonus * float(safe_line_motion) + 100.0 * float(new_second_landing and safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery + after_second * ( 2.00 * bounded_sustain_credit + 0.35 * float(double_support) + 0.20 * ground_load_score - 0.80 * upright_deficit - 0.50 * stance_height_deficit ) - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.24 and self._landing_count == 2 and self._alternating_landings >= 1 and self._post_second_grounded_streak >= 20 and metrics["grounded_fraction"] >= 0.57 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.44 and metrics["upright_score"] >= 0.45 and metrics["pelvis_normal_height"] >= 0.30 and self._maximum_airborne_streak <= 20 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 1 ) ) premature_third_landing = self._landing_count >= 3 failure = common_failure or no_progress_timeout or premature_third_landing elif self.curriculum_stage == "endurance": # Keep the learned two-foot recovery viable for 0.6 seconds. This # is still an outcome-only task: the counter is not observed and # the policy receives no clock, pose, gait phase, or reference. after_second = float(self._landing_count >= 2) bounded_endurance_credit = float( grounded and 0 < self._post_second_grounded_streak <= 35 ) reward = ( 275.0 * grounded_progress_credit + 52.0 * landing_bonus * float(safe_line_motion) + 100.0 * float(new_second_landing and safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery + after_second * ( 2.00 * bounded_endurance_credit + 0.35 * float(double_support) + 0.20 * ground_load_score - 0.80 * upright_deficit - 0.50 * stance_height_deficit ) - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.24 and self._landing_count == 2 and self._alternating_landings >= 1 and self._post_second_grounded_streak >= 30 and metrics["grounded_fraction"] >= 0.60 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.44 and metrics["upright_score"] >= 0.45 and metrics["pelvis_normal_height"] >= 0.30 and self._maximum_airborne_streak <= 20 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 1 ) ) premature_third_landing = self._landing_count >= 3 failure = common_failure or no_progress_timeout or premature_third_landing elif self.curriculum_stage == "extend": # Make the first continuation beyond the promoted two-step bridge # a reachable terminal event. This stage asks only for a third # measured uphill landing with a viable body/rope state; the next # stage still owns sustained grounding and upright recovery. reward = ( 280.0 * grounded_progress_credit + 50.0 * landing_bonus * float(safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.18 and self._landing_count >= 3 and self._alternating_landings >= 1 and metrics["grounded_fraction"] >= 0.32 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.45 and metrics["upright_score"] >= 0.00 and metrics["pelvis_normal_height"] >= 0.20 and self._maximum_airborne_streak <= 30 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 2 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage == "recover": # The three-landing precursor used to terminate on contact, so it # never exposed PPO to the physical state immediately afterward. # Require a sustained grounded recovery before advancing. The # policy receives no landing counter, clock, pose target, or # phase; this streak is only an outcome and reward gate. after_third = float(self._landing_count >= 3) reward = ( 290.0 * grounded_progress_credit + 48.0 * landing_bonus * float(safe_line_motion) + 120.0 * float(new_third_landing and safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery + after_third * ( 1.20 * float(grounded) + 0.50 * float(double_support) + 0.30 * ground_load_score - 0.80 * upright_deficit - 0.50 * stance_height_deficit ) - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.22 and self._landing_count >= 3 and self._alternating_landings >= 1 and self._post_third_grounded_streak >= 10 and metrics["grounded_fraction"] >= 0.48 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.44 and metrics["upright_score"] >= 0.40 and metrics["pelvis_normal_height"] >= 0.28 and self._maximum_airborne_streak <= 15 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.10 or self._landing_count < 2 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage == "advance": # Expose one more alternating contact after the recovered third # landing. Success is a measured physical event, with no desired # joint pose, limb-order input, clock, or reference trajectory. reward = ( 295.0 * grounded_progress_credit + 52.0 * landing_bonus * float(safe_line_motion) + 10.0 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.24 and self._landing_count >= 4 and self._alternating_landings >= 2 and metrics["grounded_fraction"] >= 0.42 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.44 and metrics["upright_score"] >= 0.40 and metrics["pelvis_normal_height"] >= 0.28 and self._maximum_airborne_streak <= 20 ) no_progress_timeout = bool( self._step_count >= 400 and ( metrics["ascent"] < 0.12 or self._landing_count < 3 ) ) failure = common_failure or no_progress_timeout elif self.curriculum_stage == "grounded": # Ground contact is a gate on useful motion, not a source of # stationary living reward. Earlier versions paid roughly # +0.65 per step for simply standing, so a zero-action policy # outscored every exploratory climbing policy. These terms are # potentials/high-water outcomes: they cannot be farmed while # remaining at the prepared reset pose. reward = ( 300.0 * grounded_progress_credit # The promoted bridge already makes two alternating # landings. Give a sampled third/fourth contact enough # potential credit to beat the otherwise shorter two-step # fall; final promotion still requires four landings plus # upright, grounded recovery. + 40.0 * landing_bonus * float(safe_line_motion) + 8.00 * swing_advance_reward * float(safe_line_motion) + 65.0 * lateral_recovery - 0.025 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.45 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.00 * float(metrics["rope_cam_contacts"] <= 0) - 2.20 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.010 ) success = bool( metrics["ascent"] >= 0.80 and self._landing_count >= 4 and self._alternating_landings >= 2 and metrics["grounded_fraction"] >= 0.72 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.42 and metrics["upright_score"] >= 0.50 and metrics["pelvis_normal_height"] >= 0.30 and self._maximum_airborne_streak <= 15 ) no_progress_timeout = bool( self._step_count >= 400 and metrics["ascent"] < 0.10 ) failure = common_failure or no_progress_timeout elif self.curriculum_stage in { "bend", "flex", "catch", "pull", "rearm", }: reward = ( 110.0 * grounded_progress_credit + 22.0 * max(slide_delta, 0.0) * float(safe_line_motion) + 2.00 * landing_bonus * float(safe_line_motion) + technique_cycle_bonus + 1.50 * technique_dense_reward + float( self.curriculum_stage == "catch" and self._landing_count >= 3 ) * ( 1.20 * float(grounded) + 0.50 * float(double_support) + 0.30 * ground_load_score - 0.80 * upright_deficit - 0.50 * stance_height_deficit ) + float( self.curriculum_stage == "rearm" and self._technique_cycles >= 1 ) * ( 2.00 * float(grounded) + 0.60 * float(double_support) + 0.40 * ground_load_score + 40.0 * max(slide_delta, 0.0) * float(safe_line_motion) - 1.00 * upright_deficit - 0.60 * stance_height_deficit ) + 0.25 * float(grounded) + 0.12 * float(double_support) + 35.0 * lateral_recovery - 0.020 * foot_slip - 0.004 * action_cost - 0.010 * smoothness_cost - 0.40 * float(not grounded) - 5.00 * float(rope_touches_leg) - 2.50 * rope_leg_proximity - 1.50 * float(metrics["rope_cam_contacts"] <= 0) - 2.00 * lateral_corridor_cost - 0.75 * upright_deficit - 0.45 * stance_height_deficit - 0.025 ) if self.curriculum_stage in {"bend", "flex"}: # Bridge the sparse full-cycle objective without supplying a # phase, clock, or reference action to the policy. A valid # outcome must first reach with the ascender, take another # physical step, then flex the elbow while grounded. The two # milestones progressively approach the strict pull stage, # which requires a 1.65-rad bend plus body catch-up. completed_step_after_reach = bool( self._landing_count > self._cycle_landing_start ) within_cycle_flexion = ( right_elbow - self._cycle_reach_elbow ) elbow_target = ( 1.35 if self.curriculum_stage == "bend" else 1.55 ) flexion_target = ( 0.20 if self.curriculum_stage == "bend" else 0.40 ) excursion_target = ( 0.35 if self.curriculum_stage == "bend" else 0.55 ) success = bool( metrics["ascent"] >= 0.20 and metrics["ascender_advance"] >= 0.45 and self._landing_count >= 3 and completed_step_after_reach and right_elbow >= elbow_target and within_cycle_flexion >= flexion_target and grounded and metrics["grounded_fraction"] >= 0.55 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.45 and metrics["upright_score"] >= 0.48 and metrics["pelvis_normal_height"] >= 0.28 and metrics["right_elbow_peak_rad"] >= elbow_target and metrics["right_elbow_excursion_rad"] >= excursion_target and self._maximum_airborne_streak <= 15 ) elif self.curriculum_stage == "catch": # After a supported full bend and third alternating landing, # remain physically grounded long enough for the body to # begin catching the ascender. This is an outcome-only bridge # to the complete cycle; no phase or desired pose is observed. success = bool( metrics["ascent"] >= 0.30 and metrics["ascender_advance"] >= 0.50 and ascender_lead <= 0.22 and self._landing_count >= 3 and self._alternating_landings >= 2 and self._cycle_full_pull and self._post_third_grounded_streak >= 10 and grounded and metrics["grounded_fraction"] >= 0.60 and self._rope_leg_contact_steps == 0 and metrics["lateral_offset"] <= 0.45 and metrics["upright_score"] >= 0.48 and metrics["pelvis_normal_height"] >= 0.30 and metrics["right_elbow_peak_rad"] >= 1.65 and metrics["right_elbow_excursion_rad"] >= 0.60 and self._maximum_airborne_streak <= 15 ) elif self.curriculum_stage == "rearm": # Bridge one complete supported pull-step to the next reach. # `_cycle_armed` is raised only when the body is grounded and # upright, the rope is still in the cam and clear of the legs, # the ascender leads the pelvis again, and the elbow has # physically reopened. No phase, pose target, or action is # supplied to the policy. success = bool( metrics["ascent"] >= 0.45 and metrics["ascender_advance"] >= 0.60 and self._technique_cycles >= 1 and self._cycle_armed and self._landing_count >= 3 and self._alternating_landings >= 2 and grounded and metrics["grounded_fraction"] >= 0.65 and self._rope_leg_contact_steps == 0 and metrics["lateral_offset"] <= 0.45 and metrics["upright_score"] >= 0.48 and metrics["pelvis_normal_height"] >= 0.28 and metrics["right_elbow_peak_rad"] >= 1.65 and metrics["right_elbow_excursion_rad"] >= 0.60 and self._maximum_airborne_streak <= 15 ) else: success = bool( metrics["ascent"] >= 0.45 and metrics["ascender_advance"] >= 0.55 and self._landing_count >= 1 and self._technique_cycles >= 1 and metrics["grounded_fraction"] >= 0.65 and self._rope_leg_contact_steps <= 12 and metrics["lateral_offset"] <= 0.45 and metrics["upright_score"] >= 0.48 and metrics["pelvis_normal_height"] >= 0.28 and metrics["right_elbow_peak_rad"] >= 1.65 and metrics["right_elbow_excursion_rad"] >= 0.60 and self._maximum_airborne_streak <= 15 ) no_progress_timeout = bool( self._step_count >= 450 and task_progress < 0.10 ) failure = common_failure or no_progress_timeout else: reward = full_reward success = full_success failure = common_failure or no_progress_timeout # Presentation-critical mechanics apply across the curriculum: useful # climbing faces the line, maintains the controlled backward lean, and # is supported by boots rather than knees, shins, hands, or torso. A # smooth force-band reward makes sustained harness loading learnable; # the success gate below still requires an uninterrupted measured # streak and cannot be satisfied by a one-frame impact. reward += 0.80 * support_target_score reward -= ( 1.20 * heading_deficit + 0.60 * backward_lean_deficit + 0.80 * line_support_deficit + 1.50 * line_support_overload # A loaded hand constraint must not drag the planted boots down # the slope. This is measured world-space contact drift, not a # desired joint pose or gait phase. Uphill steps have zero loss. + 2.50 * float( np.clip( metrics["current_boot_anchor_loss_m"] / 0.10, 0.0, 4.0, ) ) + 6.00 * float(nonfoot_snow_contact) ) if self.curriculum_stage in { "reach", "lift", "brace", "swing", "land", "step", "sequence", "stabilize", "hold", "sustain", "endurance", "extend", "recover", "advance", "grounded", "bend", "flex", "catch", "pull", "rearm", "full", }: required_support_streak = ( self.REACH_SUPPORT_STREAK_STEPS if self.curriculum_stage == "reach" else ( self.BRACE_SUPPORT_STREAK_STEPS if self.curriculum_stage == "brace" else self.SUPPORTED_MOTION_STREAK_STEPS ) ) success = bool( success and self._nonfoot_snow_contact_steps == 0 and metrics["line_heading_alignment"] >= 0.75 and metrics["upright_score"] >= 0.80 and metrics["pelvis_normal_height"] >= 0.52 and metrics["maximum_boot_anchor_loss_m"] <= 0.10 and target_lanyard_support and self._maximum_target_lanyard_support_streak >= required_support_streak ) terminated = success or failure truncated = self._step_count >= self.max_episode_steps if success: reward += 80.0 if failure: # Preserve a learning gradient toward a stable stance without # paying a per-step survival bonus that makes idling optimal. # An avoidable early failure is worse than reaching the stage's # no-progress deadline, while actual uphill progress can dominate # either outcome. failure_deadline = { "reach": 300, "lift": 300, "brace": 300, "swing": 300, "land": 300, "step": 350, "sequence": 400, "stabilize": 400, "hold": 400, "sustain": 400, "endurance": 400, "extend": 400, "recover": 400, "advance": 400, "grounded": 400, "bend": 450, "flex": 450, "catch": 450, "pull": 450, "rearm": 550, "full": self.max_episode_steps, }[self.curriculum_stage] remaining_steps = max(failure_deadline - self._step_count, 0) reward -= 70.0 + 0.25 * remaining_steps metrics.update( { "success": success, "failure": failure, "elapsed_policy_steps": self._step_count, "no_progress_timeout": no_progress_timeout, "left_boot_contact": float(contacts["left"]), "right_boot_contact": float(contacts["right"]), "left_boot_load_n": loads["left"], "right_boot_load_n": loads["right"], "physical_landings": float(self._landing_count), "alternating_landings": float(self._alternating_landings), "technique_cycles": float(self._technique_cycles), "rope_leg_contact_steps": float( self._rope_leg_contact_steps ), "maximum_rope_cam_lost_streak": float( self._maximum_rope_cam_lost_streak ), } ) self._previous_progress = progress_absolute self._previous_qualified_progress = qualified_progress self._previous_lateral_offset = metrics["lateral_offset"] self._previous_slide = slide self._last_action = filtered.copy() return self._get_obs(), float(reward), terminated, truncated, metrics def render(self) -> np.ndarray | None: if self.render_mode != "rgb_array": return None if self._renderer is None: self._renderer = mujoco.Renderer( self.model, height=720, width=1280 ) camera = mujoco.MjvCamera() camera.type = mujoco.mjtCamera.mjCAMERA_TRACKING camera.trackbodyid = self.pelvis_body_id camera.distance = 2.5 camera.azimuth = 118 camera.elevation = -13 self._renderer.update_scene(self.data, camera=camera) return self._renderer.render() def close(self) -> None: if self._renderer is not None: self._renderer.close() self._renderer = None G1FixedLineLearnedEnv = G1LearnedFixedLineEnv