main
Drew Owens Add Phase 2 dual-engine MuJoCo/Drake sim2sim, 3D FEA, ngspice-42/adom-fields validation, STEP audit, and physical test… 3e356d3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
#!/usr/bin/env python3
"""Independent Second Physics Engine: MIT/TRI Drake 1.58 MultibodyPlant Sim-to-Sim Env.

Uses Featherstone articulated-body multibody tree dynamics + Drake's discrete SAP
(Semi-Analytic Primal) convex contact solver on rl/assets/microgoose.urdf — completely
independent of MuJoCo's generalized-coordinate soft-contact solver and MJCF parser.

Implements:
  - Identical 61-dim float32 observation contract & 50 Hz (10 x 2 ms) control loop
  - Reflected rotor armature inertia (3.443e-4 kg*m^2) via Drake JointActuator
  - Explicit BAM Coulomb stiction (-0.024 N*m * tanh(dq / 0.025)) via generalized forces
    (since URDF <dynamics friction=.../> is ignored by Drake's URDF parser)
  - Coupled BAM XL330 + Microgoose-Spine power-stage model (step_bam_power_stage)
  - Terrain slope rotation, external planar push impulses, and full CoM/ZMP/contact telemetry.
"""

from __future__ import annotations

from collections import deque
import json
import logging
import math
from pathlib import Path
import sys
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
from pydrake.geometry import (
    AddContactMaterial,
    Box,
    CollisionFilterDeclaration,
    Ellipsoid,
    GeometrySet,
    ProximityProperties,
    Role,
    RoleAssign,
    Sphere,
)
from pydrake.math import RigidTransform
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import AddMultibodyPlantSceneGraph, CoulombFriction
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder

RL_DIR = Path(__file__).resolve().parent
if str(RL_DIR) not in sys.path:
    sys.path.insert(0, str(RL_DIR))

from bam.xl330_electromech import DEFAULT_POWER, DEFAULT_XL330, step_bam_power_stage


# Silence repetitive Drake URDF friction warnings (we inject Coulomb friction explicitly)
logging.getLogger("drake").setLevel(logging.ERROR)

ROOT_DIR = RL_DIR.parent
MECH_INTERFACE_PATH = ROOT_DIR / "design" / "mechanical-interface.json"
BAM_PARAMS_PATH = ROOT_DIR / "rl" / "bam" / "xl330_bam_params.json"
URDF_PATH = ROOT_DIR / "rl" / "assets" / "microgoose.urdf"

OBS_DIM = 61
ACT_DIM = 14
ACTION_SCALE = 0.25
ACTION_CLIP = 3.0
PHYSICS_DT = 0.002
DECIMATION = 10
CONTROL_DT = PHYSICS_DT * DECIMATION
GAIT_FREQ_HZ = 1.8
STANCE_DUTY = 0.55
GRAVITY_MAG = 9.81


class MicrogooseDrakeEnv:
    """MIT/TRI Drake 1.58 MultibodyPlant + SAP discrete contact environment."""

    def __init__(
        self,
        friction_mu: float = 0.85,
        slope_deg: float = 0.0,
        vbat_ocv: float = 7.40,
        latency_substeps: int = 1,
        deadzone_rad: Optional[float] = None,
        mass_scale: float = 1.0,
        use_worst_case_ilim: bool = False,
        allow_fall_termination: bool = True,
        max_episode_steps: int = 500,
    ) -> None:
        with open(MECH_INTERFACE_PATH, "r", encoding="utf-8") as f:
            mech = json.load(f)
        with open(BAM_PARAMS_PATH, "r", encoding="utf-8") as f:
            bam_json = json.load(f)
        self.bam_nom = bam_json["fitted_params"]

        self.friction_mu = float(friction_mu)
        self.slope_deg = float(slope_deg)
        self.vbat_ocv = float(vbat_ocv)
        self.latency_substeps = int(np.clip(latency_substeps, 0, 4))
        self.deadzone_rad = (
            float(self.bam_nom["backlash_deadzone_rad"]) if deadzone_rad is None else float(deadzone_rad)
        )
        self.mass_scale = float(mass_scale)
        self.use_worst_case_ilim = bool(use_worst_case_ilim)
        self.allow_fall_termination = bool(allow_fall_termination)
        self.max_episode_steps = int(max_episode_steps)
        self.radxa_current_a = DEFAULT_POWER.radxa_j4_infer_a

        self.loco_joint_names = [j["name"] for j in mech["joints"]]
        self.all_15_joint_names = self.loco_joint_names + ["beak_pitch"]
        self.q_default_14 = np.array([float(j["defaultRad"]) for j in mech["joints"]], dtype=np.float64)
        self.beak_default = float(mech["auxiliaryJoints"][0]["defaultRad"])
        self.q_default_15 = np.append(self.q_default_14, self.beak_default)

        self.kp_15 = np.full(15, float(self.bam_nom["kp_servo_nm_per_rad"]), dtype=np.float64)
        self.kd_15 = np.full(15, float(self.bam_nom["kd_servo_nms_per_rad"]), dtype=np.float64)
        self.coulomb_tau = float(self.bam_nom["coulomb_friction_nm"])
        self.armature = float(self.bam_nom["armature_kgm2"])

        self._build_plant()

        self.step_count = 0
        self.sim_time = 0.0
        self.gait_phase_l = 0.0
        self.vel_cmd = np.zeros(3, dtype=np.float64)
        self.head_cmd = np.zeros(3, dtype=np.float64)
        self.stand_flag = 0.0
        self.beak_target_rad = self.beak_default
        self.last_actions = np.zeros(ACT_DIM, dtype=np.float64)
        self.last_foot_contacts = np.ones(2, dtype=np.float64)
        self.q_des_ring: deque[np.ndarray] = deque([self.q_default_15.copy() for _ in range(6)], maxlen=6)
        self.last_power_telemetry: Dict[str, Any] = {}
        self.last_tau_15 = np.zeros(15, dtype=np.float64)

    def _build_plant(self) -> None:
        builder = DiagramBuilder()
        plant, sg = AddMultibodyPlantSceneGraph(builder, time_step=PHYSICS_DT)
        model_inst = Parser(plant).AddModels(str(URDF_PATH))[0]
        self.model_inst = model_inst

        # Register JointActuators in exact all_15_joint_names order with BAM reflected rotor inertia
        for jname in self.all_15_joint_names:
            j = plant.GetMutableJointByName(jname)
            act = plant.AddJointActuator(f"act_{jname}", j)
            act.set_default_gear_ratio(1.0)
            act.set_default_rotor_inertia(self.armature)

        # Assign crisp Coulomb friction & point-contact stiffness to all robot collision shapes
        robot_geoms = GeometrySet()
        for b_idx in plant.GetBodyIndices(model_inst):
            body = plant.get_body(b_idx)
            is_foot = "foot" in body.name()
            stiff = 28000.0 if is_foot else 6500.0
            diss = 6.0 if is_foot else 7.5
            for g_id in plant.GetCollisionGeometriesForBody(body):
                robot_geoms.Add(g_id)
                props = ProximityProperties()
                AddContactMaterial(
                    dissipation=diss,
                    point_stiffness=stiff,
                    friction=CoulombFriction(self.friction_mu, self.friction_mu),
                    properties=props,
                )
                sg.AssignRole(plant.get_source_id(), g_id, props, RoleAssign.kReplace)

        # Replace coarse URDF bounding boxes on torso, head, and knees with exact CAD shapes
        exact_shapes = [
            ("torso", [-0.004, 0.0, 0.012], Ellipsoid(0.048, 0.038, 0.034), "torso_ellipsoid_col"),
            ("head_roll_link", [0.004, 0.0, 0.002], Ellipsoid(0.023, 0.018, 0.020), "head_ellipsoid_col"),
            ("left_shank_link", [0.004, 0.0, 0.002], Sphere(0.012), "left_knee_sphere_col"),
            ("right_shank_link", [0.004, 0.0, 0.002], Sphere(0.012), "right_knee_sphere_col"),
        ]
        for bname, xyz, shape_obj, cname in exact_shapes:
            b_ref = plant.GetBodyByName(bname)
            for g_id in list(plant.GetCollisionGeometriesForBody(b_ref)):
                sg.RemoveRole(plant.get_source_id(), g_id, Role.kProximity)
            s_props = ProximityProperties()
            AddContactMaterial(
                dissipation=7.5,
                point_stiffness=6500.0,
                friction=CoulombFriction(self.friction_mu, self.friction_mu),
                properties=s_props,
            )
            new_gid = plant.RegisterCollisionGeometry(
                b_ref,
                RigidTransform(xyz),
                shape_obj,
                cname,
                s_props,
            )
            robot_geoms.Add(new_gid)

        # Exclude robot-to-robot internal link self-collisions (matching MJCF contype/conaffinity)
        sg.collision_filter_manager().Apply(CollisionFilterDeclaration().ExcludeWithin(robot_geoms))

        # Register ground plane slab (top face at z = 0.0)
        floor_props = ProximityProperties()
        AddContactMaterial(
            dissipation=6.0,
            point_stiffness=28000.0,
            friction=CoulombFriction(self.friction_mu, self.friction_mu),
            properties=floor_props,
        )
        self.floor_gid = plant.RegisterCollisionGeometry(
            plant.world_body(),
            RigidTransform([0.0, 0.0, -0.10]),
            Box(20.0, 20.0, 0.20),
            "floor",
            floor_props,
        )

        # Set slope-rotated gravity vector
        alpha = math.radians(self.slope_deg)
        self.g_unit_world = np.array([-math.sin(alpha), 0.0, -math.cos(alpha)], dtype=np.float64)
        plant.mutable_gravity_field().set_gravity_vector(GRAVITY_MAG * self.g_unit_world)

        plant.Finalize()
        self.diagram = builder.Build()
        self.plant = plant
        self.sg = sg

        # Cache body & joint indices AFTER Finalize()
        self.torso_body = plant.GetBodyByName("torso")
        self.l_foot_body = plant.GetBodyByName("left_foot_link")
        self.r_foot_body = plant.GetBodyByName("right_foot_link")
        self.l_shank_body = plant.GetBodyByName("left_shank_link")
        self.r_shank_body = plant.GetBodyByName("right_shank_link")
        self.head_body = plant.GetBodyByName("head_roll_link")
        self.beak_body = plant.GetBodyByName("beak_link")

        self.l_foot_body_idx = self.l_foot_body.index()
        self.r_foot_body_idx = self.r_foot_body.index()
        self.l_shank_body_idx = self.l_shank_body.index()
        self.r_shank_body_idx = self.r_shank_body.index()
        self.torso_body_idx = self.torso_body.index()
        self.head_body_idx = self.head_body.index()
        self.beak_body_idx = self.beak_body.index()

        q_idx: List[int] = []
        v_idx: List[int] = []
        qmin_list: List[float] = []
        qmax_list: List[float] = []
        for jname in self.all_15_joint_names:
            j = plant.GetJointByName(jname)
            q_idx.append(int(j.position_start()))
            v_idx.append(int(j.velocity_start()))
            qmin_list.append(float(j.position_lower_limits()[0]))
            qmax_list.append(float(j.position_upper_limits()[0]))

        self.all_q_idx = np.array(q_idx, dtype=np.int32)
        self.all_v_idx = np.array(v_idx, dtype=np.int32)
        self.all_qmin = np.array(qmin_list, dtype=np.float64)
        self.all_qmax = np.array(qmax_list, dtype=np.float64)
        self.loco_q_idx = self.all_q_idx[0:ACT_DIM]
        self.loco_v_idx = self.all_v_idx[0:ACT_DIM]
        self.loco_qmin = self.all_qmin[0:ACT_DIM]
        self.loco_qmax = self.all_qmax[0:ACT_DIM]
        self.beak_qmin = float(self.all_qmin[14])
        self.beak_qmax = float(self.all_qmax[14])

        self.simulator = Simulator(self.diagram)
        self.root_ctx = self.simulator.get_mutable_context()
        self.p_ctx = self.plant.GetMyMutableContextFromRoot(self.root_ctx)

        if abs(self.mass_scale - 1.0) > 1e-6:
            for b_idx in self.plant.GetBodyIndices(model_inst):
                body = self.plant.get_body(b_idx)
                m0 = body.default_mass()
                if m0 > 0:
                    body.SetMass(self.p_ctx, m0 * self.mass_scale)

    def set_command(
        self,
        vx: float,
        vy: float = 0.0,
        wz: float = 0.0,
        stand_flag: Optional[float] = None,
        head_pitch: float = 0.0,
        head_yaw: float = 0.0,
        head_roll: float = 0.0,
        beak_rad: Optional[float] = None,
    ) -> None:
        self.vel_cmd[:] = [vx, vy, wz]
        if stand_flag is None:
            self.stand_flag = 1.0 if (abs(vx) < 0.015 and abs(vy) < 0.015 and abs(wz) < 0.03) else 0.0
        else:
            self.stand_flag = float(stand_flag)
        self.head_cmd[:] = [head_pitch, head_yaw, head_roll]
        if beak_rad is not None:
            self.beak_target_rad = float(beak_rad)

    def reset(
        self,
        root_pos_xyz: Tuple[float, float, float] = (0.0, 0.0, 0.135),
        root_quat_wxyz: Tuple[float, float, float, float] = (1.0, 0.0, 0.0, 0.0),
        q_init_15: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        self.simulator = Simulator(self.diagram)
        self.root_ctx = self.simulator.get_mutable_context()
        self.p_ctx = self.plant.GetMyMutableContextFromRoot(self.root_ctx)
        if abs(self.mass_scale - 1.0) > 1e-6:
            for b_idx in self.plant.GetBodyIndices(self.model_inst):
                body = self.plant.get_body(b_idx)
                m0 = body.default_mass()
                if m0 > 0:
                    body.SetMass(self.p_ctx, m0 * self.mass_scale)

        q = self.plant.GetPositions(self.p_ctx).copy()
        # Drake floating base position ordering: [qw, qx, qy, qz, x, y, z]
        q[0:4] = root_quat_wxyz
        q[4:7] = root_pos_xyz
        q15 = self.q_default_15 if q_init_15 is None else np.asarray(q_init_15, dtype=np.float64)
        q[self.all_q_idx] = np.clip(q15, self.all_qmin, self.all_qmax)

        self.plant.SetPositions(self.p_ctx, q)
        self.plant.SetVelocities(self.p_ctx, np.zeros(self.plant.num_velocities(), dtype=np.float64))
        self.plant.get_actuation_input_port().FixValue(self.p_ctx, np.zeros(15, dtype=np.float64))
        self.plant.get_applied_generalized_force_input_port().FixValue(
            self.p_ctx, np.zeros(self.plant.num_velocities(), dtype=np.float64)
        )

        self.step_count = 0
        self.sim_time = 0.0
        self.gait_phase_l = 0.0
        self.last_actions.fill(0.0)
        self.q_des_ring = deque([q[self.all_q_idx].copy() for _ in range(6)], maxlen=6)
        self.simulator.Initialize()

        l_con, r_con, _, _ = self._detect_contacts_and_forces()
        self.last_foot_contacts[:] = [l_con, r_con]
        return self.get_obs()

    def apply_planar_push(self, dvx_world: float, dvy_world: float, dvz_world: float = 0.0) -> None:
        """Apply instantaneous world-frame translational velocity impulse to floating torso."""
        v = self.plant.GetVelocities(self.p_ctx).copy()
        # Drake floating base velocity ordering: v[0:3] = w_W, v[3:6] = v_W
        v[3] += dvx_world
        v[4] += dvy_world
        v[5] += dvz_world
        self.plant.SetVelocities(self.p_ctx, v)

    def _detect_contacts_and_forces(self) -> Tuple[float, float, bool, Dict[str, float]]:
        cr = self.plant.get_contact_results_output_port().Eval(self.p_ctx)
        l_con = 0.0
        r_con = 0.0
        bad_con = False
        forces = {
            "left_foot_fn": 0.0,
            "left_foot_ft": 0.0,
            "right_foot_fn": 0.0,
            "right_foot_ft": 0.0,
            "knee_fn": 0.0,
            "torso_fn": 0.0,
            "head_beak_fn": 0.0,
        }
        world_idx = self.plant.world_body().index()
        for k in range(cr.num_point_pair_contacts()):
            info = cr.point_pair_contact_info(k)
            b_a = info.bodyA_index()
            b_b = info.bodyB_index()
            if b_a == world_idx or b_b == world_idx:
                other = b_b if b_a == world_idx else b_a
                f_vec = info.contact_force()
                fn = abs(float(f_vec[2]))
                ft = math.hypot(float(f_vec[0]), float(f_vec[1]))
                if other == self.l_foot_body_idx:
                    l_con = 1.0
                    forces["left_foot_fn"] += fn
                    forces["left_foot_ft"] += ft
                elif other == self.r_foot_body_idx:
                    r_con = 1.0
                    forces["right_foot_fn"] += fn
                    forces["right_foot_ft"] += ft
                elif other in (self.l_shank_body_idx, self.r_shank_body_idx):
                    forces["knee_fn"] += fn
                elif other == self.torso_body_idx:
                    bad_con = True
                    forces["torso_fn"] += fn
                elif other in (self.head_body_idx, self.beak_body_idx):
                    bad_con = True
                    forces["head_beak_fn"] += fn
        return l_con, r_con, bad_con, forces

    def compute_com_and_zmp(self) -> Dict[str, Any]:
        com_pos = np.asarray(self.plant.CalcCenterOfMassPositionInWorld(self.p_ctx, [self.model_inst]), dtype=np.float64)
        cr = self.plant.get_contact_results_output_port().Eval(self.p_ctx)
        sum_fz = 0.0
        sum_px_fz = 0.0
        sum_py_fz = 0.0
        world_idx = self.plant.world_body().index()
        for k in range(cr.num_point_pair_contacts()):
            info = cr.point_pair_contact_info(k)
            if info.bodyA_index() == world_idx or info.bodyB_index() == world_idx:
                fz = abs(float(info.contact_force()[2]))
                pt = info.contact_point()
                sum_fz += fz
                sum_px_fz += float(pt[0]) * fz
                sum_py_fz += float(pt[1]) * fz

        if sum_fz > 0.25:
            zmp_xy = np.array([sum_px_fz / sum_fz, sum_py_fz / sum_fz], dtype=np.float64)
        else:
            zmp_xy = com_pos[0:2].copy()

        X_WL = self.plant.EvalBodyPoseInWorld(self.p_ctx, self.l_foot_body)
        X_WR = self.plant.EvalBodyPoseInWorld(self.p_ctx, self.r_foot_body)
        l_site = X_WL.multiply(np.array([0.012, 0.004, -0.014]))
        r_site = X_WR.multiply(np.array([0.012, -0.004, -0.014]))

        l_con = self.last_foot_contacts[0] > 0.5
        r_con = self.last_foot_contacts[1] > 0.5
        hx, hy = 0.042, 0.032
        if l_con and r_con:
            xmin = min(l_site[0], r_site[0]) - hx
            xmax = max(l_site[0], r_site[0]) + hx
            ymin = min(l_site[1], r_site[1]) - hy
            ymax = max(l_site[1], r_site[1]) + hy
        elif l_con:
            xmin, xmax = l_site[0] - hx, l_site[0] + hx
            ymin, ymax = l_site[1] - hy, l_site[1] + hy
        elif r_con:
            xmin, xmax = r_site[0] - hx, r_site[0] + hx
            ymin, ymax = r_site[1] - hy, r_site[1] + hy
        else:
            xmin = xmax = com_pos[0]
            ymin = ymax = com_pos[1]

        zmp_margin_m = float(min(zmp_xy[0] - xmin, xmax - zmp_xy[0], zmp_xy[1] - ymin, ymax - zmp_xy[1]))
        return {
            "com_xyz_m": com_pos,
            "zmp_xy_m": zmp_xy,
            "zmp_margin_m": zmp_margin_m,
            "total_grf_z_n": sum_fz,
            "foot_z_lr": (max(0.0, float(l_site[2])), max(0.0, float(r_site[2]))),
        }

    def get_obs(self) -> np.ndarray:
        X_WB = self.plant.EvalBodyPoseInWorld(self.p_ctx, self.torso_body)
        R_WB = X_WB.rotation().matrix()
        V_WB = self.plant.EvalBodySpatialVelocityInWorld(self.p_ctx, self.torso_body)
        ang_vel_b = R_WB.T @ np.asarray(V_WB.rotational(), dtype=np.float64)
        grav_b = R_WB.T @ self.g_unit_world

        q = self.plant.GetPositions(self.p_ctx)
        v = self.plant.GetVelocities(self.p_ctx)
        q_meas_14 = q[self.loco_q_idx]
        dq_meas_14 = v[self.loco_v_idx]

        phi_l = self.gait_phase_l
        phi_r = (phi_l + 0.5) % 1.0
        gait_cs = np.array(
            [
                math.cos(2.0 * math.pi * phi_l),
                math.sin(2.0 * math.pi * phi_l),
                math.cos(2.0 * math.pi * phi_r),
                math.sin(2.0 * math.pi * phi_r),
            ],
            dtype=np.float64,
        )
        head_and_stand = np.array(
            [self.head_cmd[0], self.head_cmd[1], self.head_cmd[2], self.stand_flag],
            dtype=np.float64,
        )

        obs = np.empty(OBS_DIM, dtype=np.float32)
        obs[0:3] = ang_vel_b
        obs[3:6] = grav_b
        obs[6:9] = self.vel_cmd
        obs[9:23] = q_meas_14 - self.q_default_14
        obs[23:37] = dq_meas_14
        obs[37:51] = self.last_actions
        obs[51:55] = gait_cs
        obs[55:59] = head_and_stand
        obs[59:61] = self.last_foot_contacts
        return obs

    def step(
        self,
        raw_actions: np.ndarray,
        q_override_15: Optional[np.ndarray] = None,
        kp_scale_override: float = 1.0,
    ) -> Tuple[np.ndarray, float, bool, bool, Dict[str, Any]]:
        act = np.clip(np.asarray(raw_actions, dtype=np.float64), -ACTION_CLIP, ACTION_CLIP)
        if q_override_15 is not None:
            q_des_now_15 = np.clip(np.asarray(q_override_15, dtype=np.float64), self.all_qmin, self.all_qmax)
        else:
            q_des_14 = np.clip(
                self.q_default_14 + ACTION_SCALE * act,
                self.loco_qmin,
                self.loco_qmax,
            )
            q_des_now_15 = np.append(q_des_14, np.clip(self.beak_target_rad, self.beak_qmin, self.beak_qmax))

        kp_eff = self.kp_15 * kp_scale_override if kp_scale_override != 1.0 else self.kp_15
        nv = self.plant.num_velocities()
        gen_forces = np.zeros(nv, dtype=np.float64)

        sum_i_5v = 0.0
        sum_i_5v_demand = 0.0
        peak_i_5v = 0.0
        peak_i_5v_demand = 0.0
        min_v_5v = 10.0
        any_foldback = False
        max_forces = {
            "left_foot_fn": 0.0,
            "left_foot_ft": 0.0,
            "right_foot_fn": 0.0,
            "right_foot_ft": 0.0,
            "knee_fn": 0.0,
            "torso_fn": 0.0,
            "head_beak_fn": 0.0,
        }
        telem_last: Dict[str, Any] = {}
        tau_em_last = np.zeros(15, dtype=np.float64)

        for _sub in range(DECIMATION):
            self.q_des_ring.append(q_des_now_15.copy())
            q_target_15 = self.q_des_ring[-1 - self.latency_substeps]

            q_full = self.plant.GetPositions(self.p_ctx)
            v_full = self.plant.GetVelocities(self.p_ctx)
            q_cur_15 = q_full[self.all_q_idx]
            dq_cur_15 = v_full[self.all_v_idx]

            tau_em_15, telem = step_bam_power_stage(
                q_target_15=q_target_15,
                q_cur_15=q_cur_15,
                dq_cur_15=dq_cur_15,
                vbat_ocv=self.vbat_ocv,
                kp_15=kp_eff,
                kd_15=self.kd_15,
                deadzone_rad=self.deadzone_rad,
                radxa_current_a=self.radxa_current_a,
                use_worst_case_ilim=self.use_worst_case_ilim,
            )

            # Inject BAM Stribeck/Coulomb joint friction explicitly (URDF damping is already in plant)
            tau_coulomb_15 = -self.coulomb_tau * np.tanh(dq_cur_15 / 0.030)
            gen_forces.fill(0.0)
            gen_forces[self.all_v_idx] = tau_coulomb_15

            self.plant.get_actuation_input_port().FixValue(self.p_ctx, tau_em_15)
            self.plant.get_applied_generalized_force_input_port().FixValue(self.p_ctx, gen_forces)

            self.sim_time += PHYSICS_DT
            self.simulator.AdvanceTo(self.sim_time)

            sum_i_5v += telem["i_5v_total_a"]
            sum_i_5v_demand += telem["i_5v_demand_a"]
            peak_i_5v = max(peak_i_5v, telem["i_5v_total_a"])
            peak_i_5v_demand = max(peak_i_5v_demand, telem["i_5v_demand_a"])
            min_v_5v = min(min_v_5v, telem["v_5v_bus_v"])
            any_foldback = any_foldback or telem["foldback_active"]
            telem_last = telem
            tau_em_last = tau_em_15

            _, _, _, sub_f = self._detect_contacts_and_forces()
            for fk, fv in sub_f.items():
                if fv > max_forces[fk]:
                    max_forces[fk] = fv

        self.last_power_telemetry = telem_last
        self.last_tau_15 = tau_em_last.copy()
        self.step_count += 1
        if self.stand_flag < 0.5:
            self.gait_phase_l = (self.gait_phase_l + CONTROL_DT * GAIT_FREQ_HZ) % 1.0
        self.last_actions[:] = act

        X_WB = self.plant.EvalBodyPoseInWorld(self.p_ctx, self.torso_body)
        R_WB = X_WB.rotation().matrix()
        V_WB = self.plant.EvalBodySpatialVelocityInWorld(self.p_ctx, self.torso_body)
        vel_b = R_WB.T @ np.asarray(V_WB.translational(), dtype=np.float64)
        ang_vel_b = R_WB.T @ np.asarray(V_WB.rotational(), dtype=np.float64)
        grav_b = R_WB.T @ self.g_unit_world
        torso_z = float(X_WB.translation()[2])

        l_con, r_con, bad_con, _ = self._detect_contacts_and_forces()
        self.last_foot_contacts[:] = [l_con, r_con]

        cos_tilt = max(-1.0, min(1.0, -float(grav_b[2])))
        tilt_rad = math.acos(cos_tilt)

        q_full = self.plant.GetPositions(self.p_ctx)
        v_full = self.plant.GetVelocities(self.p_ctx)
        nan_detected = bool(not np.isfinite(q_full).all() or not np.isfinite(v_full).all())
        fell = bool(nan_detected or bad_con or torso_z < 0.075 or tilt_rad > 0.65)
        terminated = bool(nan_detected or (self.allow_fall_termination and fell))
        truncated = bool((not terminated) and (self.step_count >= self.max_episode_steps))

        cz = self.compute_com_and_zmp()
        obs = np.zeros(OBS_DIM, dtype=np.float32) if nan_detected else self.get_obs()
        info = {
            "vx_body": float(vel_b[0]),
            "vy_body": float(vel_b[1]),
            "wz_body": float(ang_vel_b[2]),
            "vx_cmd": float(self.vel_cmd[0]),
            "vy_cmd": float(self.vel_cmd[1]),
            "wz_cmd": float(self.vel_cmd[2]),
            "vx_abs_err": abs(float(vel_b[0] - self.vel_cmd[0])),
            "wz_abs_err": abs(float(ang_vel_b[2] - self.vel_cmd[2])),
            "tilt_rad": tilt_rad,
            "grav_b": grav_b.copy(),
            "torso_z": torso_z,
            "root_xy": np.asarray(X_WB.translation()[0:2], dtype=np.float64).copy(),
            "v_bus": float(telem_last["v_5v_bus_v"]),
            "min_v_5v_step": min_v_5v,
            "mean_i_5v_step": sum_i_5v / DECIMATION,
            "mean_i_5v_demand_step": sum_i_5v_demand / DECIMATION,
            "peak_i_5v_step": peak_i_5v,
            "peak_i_5v_demand_step": peak_i_5v_demand,
            "foldback_step": any_foldback,
            "tau_em_15": tau_em_last.copy(),
            "q_15": q_full[self.all_q_idx].copy(),
            "dq_15": v_full[self.all_v_idx].copy(),
            "power": telem_last,
            "contact_forces": max_forces,
            "com_zmp": cz,
            "foot_z_lr": cz["foot_z_lr"],
            "fell": fell,
            "step_count": self.step_count,
        }
        return obs, 0.0, terminated, truncated, info