main
Drew Owens Add Phase 2 dual-engine MuJoCo/Drake sim2sim, 3D FEA, ngspice-42/adom-fields validation, STEP audit, and physical test… 3e356d3
#!/usr/bin/env python3
"""Coupled BAM XL330-M288-T Electro-Mechanical & Spine Power-Stage Model.

Bridges rigid-body joint mechanics (torques, speeds, backlash, stiction, armature)
with the real Microgoose electrical power tree:
  - 2S Sony NP-F550 Li-Ion pack (6.0 V empty to 8.4 V full, 2600 mAh, ESR + harness)
  - TI LMR33640DDDAR 400 kHz synchronous buck (4.0 A continuous rated, 5.2 A min /
    5.8 A typ high-side peak switch current limit, low-line dropout at D_max = 0.972)
  - Wurth WE-XHMI 74439346047 4.7 uH inductor (DCR = 14.5 mOhm, I_rated = 8.5 A, I_sat = 11.0 A)
  - Bourns CSS2H-2512R-L300F 0.30 mOhm INA226 current-sense shunt
  - Three 3-pin JST-GH (BM03B-GHS-TBT, 1.0 A rated/pin) servo branches:
      * J1: Left leg (dxlId 1..5, RL indices 0..4)
      * J2: Right leg (dxlId 6..10, RL indices 9..13)
      * J3: Neck/head/beak (dxlId 11..15, RL indices 5..8 + aux index 14)
  - Radxa Zero 3W companion SBC on J4 and STM32G431 + sensors on U2 (AP2114H-3.3).

Every physical constant is explicitly provenance-tagged ('datasheet', 'calculated',
or 'simulated') for independent engineering review.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, Tuple
import numpy as np


# Branch index slices in 15-joint vector [RL_0..RL_13, beak_14]
# RL_0..4 = Left leg (dxlId 1..5 -> J1)
# RL_5..8 = Neck/head (dxlId 11..14 -> J3)
# RL_9..13 = Right leg (dxlId 6..10 -> J2)
# Aux_14 = Beak pitch (dxlId 15 -> J3)
J1_INDICES = np.array([0, 1, 2, 3, 4], dtype=np.int32)
J2_INDICES = np.array([9, 10, 11, 12, 13], dtype=np.int32)
J3_INDICES = np.array([5, 6, 7, 8, 14], dtype=np.int32)


@dataclass(frozen=True)
class XL330Spec:
    """Robotis Dynamixel XL330-M288-T datasheet + BAM fitted constants at 5.0 V."""

    nominal_voltage_v: float = 5.0               # [datasheet] Robotis e-Manual XL330-M288-T
    max_operating_voltage_v: float = 6.0         # [datasheet] Absolute max 6.0 V (3.7-6.0 V range)
    min_operating_voltage_v: float = 3.7         # [datasheet] Min operating voltage
    stall_torque_5v_nm: float = 0.52             # [datasheet] 0.52 N.m @ 5.0 V, 1.47 A
    continuous_clamp_nm: float = 0.48            # [calculated] 92% PWM continuous protection ceiling
    stall_current_5v_a: float = 1.47             # [datasheet] 1.47 A @ 5.0 V stall
    standby_current_a: float = 0.040             # [datasheet] 40 mA MCU + H-bridge quiescent per servo
    no_load_speed_rpm_5v: float = 103.0          # [datasheet] 103 rev/min @ 5.0 V
    no_load_speed_rad_s_5v: float = 10.7861      # [calculated] 103 * 2*pi / 60
    gear_ratio: float = 288.4                    # [datasheet] 288.4 : 1 spur reduction
    winding_resistance_25c_ohm: float = 3.401    # [calculated] 5.0 V / 1.47 A = 3.401 Ohm
    kt_electromag_nm_per_a: float = 0.3636       # [calculated] 0.52 N.m / (1.47 - 0.04 A)
    kt_net_shaft_nm_per_a: float = 0.2857        # [simulated] BAM fitted net shaft torque/current
    ke_v_per_rad_s: float = 0.4360               # [calculated] (5.0 - 0.04*3.401) / 10.7861 (back-EMF)
    armature_kgm2: float = 3.443e-4              # [simulated] BAM fitted reflected rotor inertia
    coulomb_friction_nm: float = 0.0240          # [simulated] BAM fitted Coulomb stiction
    viscous_damping_nms_per_rad: float = 0.00673 # [simulated] BAM fitted viscous damping
    backlash_deadzone_rad: float = 0.004448      # [simulated] BAM fitted gear deadzone (0.255 deg)
    kp_servo_nm_per_rad: float = 4.4774          # [simulated] BAM fitted default P gain (KP=400)
    kd_servo_nms_per_rad: float = 0.11523        # [simulated] BAM fitted default D gain
    # Thermal 2-node lumped parameters for 20x34x26 mm 18g coreless micro-servo
    c_thermal_winding_j_per_k: float = 3.20      # [calculated] Copper + rotor thermal mass
    c_thermal_case_j_per_k: float = 18.50        # [calculated] Engineering plastic case + steel gears
    r_thermal_wind_to_case_k_per_w: float = 14.5 # [calculated] Air gap + brush/frame conduction
    r_thermal_case_to_amb_k_per_w: float = 28.0  # [calculated] Natural/walking convection on 29 cm^2 area
    shutdown_temp_c: float = 75.0                # [datasheet] Dynamixel default Temperature Limit (Addr 31)
    ambient_temp_c: float = 25.0                 # [calculated] Standard lab ambient


@dataclass(frozen=True)
class SpinePowerSpec:
    """Microgoose-Spine rev A + NP-F550 battery + cabling electrical specification."""

    # Battery: 2S Li-Ion NP-F550 (7.2/7.4 V nominal, 2600 mAh)
    bat_capacity_ah: float = 2.60                # [datasheet] Standard NP-F550 2S1P 18650 (2600 mAh)
    bat_max_cont_c_rate: float = 2.0             # [datasheet] 2.0C = 5.2 A continuous discharge rating
    bat_internal_r_ohm: float = 0.145            # [calculated] 2x 18650 cell DCIR (60 mOhm) + PCM MOSFETs (25 mOhm)
    bat_harness_mc_r_ohm: float = 0.020          # [calculated] Sled contacts + MC1/MC2 MachineContactMedium parallel
    # Buck regulator: TI LMR33640DDDAR (SNVSB26E) + Wurth 74439346047 4.7 uH
    buck_vout_nom_v: float = 5.00                # [calculated] 1.00 V * (1 + 80k/20k)
    buck_fsw_hz: float = 400_000.0               # [datasheet] LMR33640A/DDA 400 kHz fixed fSW
    buck_inductance_h: float = 4.7e-6            # [datasheet] Wurth 74439346047 4.7 uH +/-20%
    buck_inductor_dcr_ohm: float = 0.0145        # [datasheet] Wurth 74439346047 max DCR 14.5 mOhm
    buck_inductor_irated_a: float = 8.50         # [datasheet] Wurth 74439346047 Irated (dT=40K)
    buck_inductor_isat_a: float = 11.00          # [datasheet] Wurth 74439346047 Isat (30% L drop)
    buck_rated_cont_a: float = 4.00              # [datasheet] LMR33640 max continuous output current
    buck_hs_ilim_min_a: float = 5.20             # [datasheet] SNVSB26E Sec 7.5 HS peak switch limit min
    buck_hs_ilim_typ_a: float = 6.00             # [datasheet] SNVSB26E Sec 7.5 HS peak switch limit typ
    buck_ron_hs_ohm: float = 0.072               # [datasheet] SNVSB26E HS MOSFET RDS(on) typ 72 mOhm
    buck_ron_ls_ohm: float = 0.041               # [datasheet] SNVSB26E LS MOSFET RDS(on) typ 41 mOhm
    buck_max_duty: float = 0.972                 # [calculated] 1 - fSW * tOFF_min (70 ns @ 400 kHz)
    # Shunt & current monitor: INA226AIDGST + Bourns CSS2H-2512R-L300F
    shunt_r_ohm: float = 0.0003                  # [datasheet] 0.30 mOhm 1%
    ina226_vshunt_max_v: float = 0.08192         # [datasheet] +/-81.92 mV full-scale differential
    ina226_lsb_uv: float = 2.50                  # [datasheet] 2.5 uV/bit (16-bit signed)
    ina226_offset_max_uv: float = 10.0           # [datasheet] INA226AIDGST max Vos +/-10 uV
    # JST-GH 3-pin servo branches (BM03B-GHS-TBT, 1.25 mm pitch, 26 AWG)
    jst_gh_pin_rated_a: float = 1.00             # [datasheet] JST GHS series 1.0 A AC/DC @ 26 AWG
    branch_r_j1_ohm: float = 0.085               # [calculated] Contact (20 mOhm) + daisy-chain 26 AWG avg loop
    branch_r_j2_ohm: float = 0.085               # [calculated] Right leg symmetric daisy-chain loop
    branch_r_j3_ohm: float = 0.095               # [calculated] Longer S-neck 26 AWG harness loop
    # Non-servo 5V_BUS loads
    radxa_j4_idle_a: float = 0.42                # [calculated] Radxa Zero 3W (RK3566) Linux idle @ 5V
    radxa_j4_infer_a: float = 0.58               # [calculated] Radxa Zero 3W 50 Hz ONNX + WiFi telemetry @ 5V
    radxa_j4_burst_a: float = 0.92               # [calculated] Radxa Zero 3W 4-core CPU + WiFi TX peak @ 5V
    radxa_brownout_v: float = 4.55               # [datasheet] RK3566 / USB 5V rail brownout risk threshold
    ldo_u2_3v3_a: float = 0.115                  # [calculated] STM32G431 (68 mA) + VL53L5CX (35 mA) + BMI270/mic/XCVR
    ldo_u2_dropout_min_v: float = 4.05           # [datasheet] AP2114H-3.3 Vout 3.30V + 0.75V max dropout


DEFAULT_XL330 = XL330Spec()
DEFAULT_POWER = SpinePowerSpec()


def step_bam_power_stage(
    q_target_15: np.ndarray,
    q_cur_15: np.ndarray,
    dq_cur_15: np.ndarray,
    vbat_ocv: float = 7.4,
    kp_15: np.ndarray | None = None,
    kd_15: np.ndarray | None = None,
    deadzone_rad: float = DEFAULT_XL330.backlash_deadzone_rad,
    radxa_current_a: float = DEFAULT_POWER.radxa_j4_infer_a,
    use_worst_case_ilim: bool = False,
    winding_temps_c: np.ndarray | None = None,
    xl: XL330Spec = DEFAULT_XL330,
    pwr: SpinePowerSpec = DEFAULT_POWER,
) -> Tuple[np.ndarray, Dict[str, Any]]:
    """Compute 15-joint BAM electromagnetic torques and coupled Spine power-bus state.

    Returns:
      - tau_em_15: float64[15] electromagnetic torques applied to joints (before Coulomb/viscous)
      - telemetry: dict of per-servo currents, branch currents, VBAT sag, LMR33640 inductor peak,
        and regulated/foldback 5V_BUS voltage.
    """
    if kp_15 is None:
        kp = np.full(15, xl.kp_servo_nm_per_rad, dtype=np.float64)
    else:
        kp = np.asarray(kp_15, dtype=np.float64)
    if kd_15 is None:
        kd = np.full(15, xl.kd_servo_nms_per_rad, dtype=np.float64)
    else:
        kd = np.asarray(kd_15, dtype=np.float64)

    if winding_temps_c is not None:
        r_wind = xl.winding_resistance_25c_ohm * (1.0 + 0.00393 * (winding_temps_c - 25.0))
    else:
        r_wind = np.full(15, xl.winding_resistance_25c_ohm, dtype=np.float64)

    err = q_target_15 - q_cur_15
    abs_err = np.abs(err)
    err_eff = np.where(
        abs_err <= deadzone_rad,
        0.15 * err,
        err - np.copysign(0.85 * deadzone_rad, err),
    )
    tau_pd = kp * err_eff - kd * dq_cur_15

    # Pass 1: estimate servo currents at nominal 5.0 V rail INCLUDING motor back-EMF quadrant bound
    tau_pos_5v = (xl.kt_electromag_nm_per_a / r_wind) * (xl.nominal_voltage_v - xl.ke_v_per_rad_s * dq_cur_15)
    tau_neg_5v = (xl.kt_electromag_nm_per_a / r_wind) * (-xl.nominal_voltage_v - xl.ke_v_per_rad_s * dq_cur_15)
    tau_est = np.clip(tau_pd, tau_neg_5v, tau_pos_5v)
    tau_est = np.clip(tau_est, -xl.continuous_clamp_nm, xl.continuous_clamp_nm)
    i_motor_signed_est = tau_est / xl.kt_electromag_nm_per_a
    v_motor_est = r_wind * i_motor_signed_est + xl.ke_v_per_rad_s * dq_cur_15
    pwm_duty_est = np.clip(v_motor_est / xl.nominal_voltage_v, -1.0, 1.0)
    # H-bridge input supply current = quiescent + positive PWM motoring draw (filtered by local 47 uF servo bulk cap)
    i_servo_bus_est = xl.standby_current_a + np.maximum(0.0, pwm_duty_est * i_motor_signed_est)
    i_servo_bus_est = np.minimum(i_servo_bus_est, xl.stall_current_5v_a)

    i_j1_est = float(np.sum(i_servo_bus_est[J1_INDICES]))
    i_j2_est = float(np.sum(i_servo_bus_est[J2_INDICES]))
    i_j3_est = float(np.sum(i_servo_bus_est[J3_INDICES]))
    i_5v_demand = i_j1_est + i_j2_est + i_j3_est + radxa_current_a + pwr.ldo_u2_3v3_a

    # Coupled 2S NP-F550 + LMR33640 buck calculation
    r_bat_total = pwr.bat_internal_r_ohm + pwr.bat_harness_mc_r_ohm
    ilim_hs = pwr.buck_hs_ilim_min_a if use_worst_case_ilim else pwr.buck_hs_ilim_typ_a

    # Estimate buck efficiency (~90% at moderate load, ~85% near ILIM)
    eta_est = 0.89
    i_bat_est = (pwr.buck_vout_nom_v * min(i_5v_demand, ilim_hs)) / max(eta_est * vbat_ocv, 1.0)
    v_in_buck = max(3.5, vbat_ocv - r_bat_total * i_bat_est)

    # Inductor peak-to-peak ripple at operating point
    vout_target = min(pwr.buck_vout_nom_v, pwr.buck_max_duty * v_in_buck)
    duty_buck = min(pwr.buck_max_duty, vout_target / max(v_in_buck, 0.1))
    delta_il = ((v_in_buck - vout_target) * duty_buck) / (pwr.buck_fsw_hz * pwr.buck_inductance_h)
    delta_il = max(0.0, delta_il)

    # Max DC output current before peak inductor current hits high-side switch ILIM
    i_out_ilim_max = max(0.5, ilim_hs - 0.5 * delta_il)

    # Resistive path drop through LMR33640 MOSFETs + L1 DCR + 0.3 mOhm shunt
    i_5v_delivered = min(i_5v_demand, i_out_ilim_max)
    r_buck_cond = (
        duty_buck * pwr.buck_ron_hs_ohm
        + (1.0 - duty_buck) * pwr.buck_ron_ls_ohm
        + pwr.buck_inductor_dcr_ohm
        + pwr.shunt_r_ohm
    )
    v_dropout_ceil = pwr.buck_max_duty * v_in_buck - i_5v_delivered * r_buck_cond
    v_5v_reg = min(pwr.buck_vout_nom_v, max(2.5, v_dropout_ceil))

    # Cycle-by-cycle current-limit foldback if demand exceeds i_out_ilim_max
    foldback_active = bool(i_5v_demand > i_out_ilim_max)
    if foldback_active:
        v_5v_bus = max(2.5, v_5v_reg * (i_out_ilim_max / i_5v_demand))
    else:
        v_5v_bus = v_5v_reg

    # Per-branch voltage after JST-GH contact + 26 AWG harness drop
    v_branch = np.empty(15, dtype=np.float64)
    v_branch[J1_INDICES] = max(2.2, v_5v_bus - i_j1_est * pwr.branch_r_j1_ohm)
    v_branch[J2_INDICES] = max(2.2, v_5v_bus - i_j2_est * pwr.branch_r_j2_ohm)
    v_branch[J3_INDICES] = max(2.2, v_5v_bus - i_j3_est * pwr.branch_r_j3_ohm)

    # Pass 2: Quadrant-aware XL330 torque-speed limit at actual branch terminal voltage
    tau_max_pos = (xl.kt_electromag_nm_per_a / r_wind) * (v_branch - xl.ke_v_per_rad_s * dq_cur_15)
    tau_min_neg = (xl.kt_electromag_nm_per_a / r_wind) * (-v_branch - xl.ke_v_per_rad_s * dq_cur_15)
    clamp_vec = np.full(15, xl.continuous_clamp_nm * (v_branch / xl.nominal_voltage_v), dtype=np.float64)
    clamp_vec[14] = min(clamp_vec[14], 0.35)  # Beak mechanical stop gentle limit

    tau_em = np.clip(tau_pd, tau_min_neg, tau_max_pos)
    tau_em = np.clip(tau_em, -clamp_vec, clamp_vec)

    # Final realized winding & bus currents from delivered tau_em
    i_winding = tau_em / xl.kt_electromag_nm_per_a
    v_motor = r_wind * i_winding + xl.ke_v_per_rad_s * dq_cur_15
    pwm_duty = np.clip(v_motor / np.maximum(v_branch, 0.5), -1.0, 1.0)
    i_servo_bus = xl.standby_current_a + np.maximum(0.0, pwm_duty * i_winding)
    p_copper_w = (i_winding ** 2) * r_wind
    p_mech_w = tau_em * dq_cur_15

    i_j1 = float(np.sum(i_servo_bus[J1_INDICES]))
    i_j2 = float(np.sum(i_servo_bus[J2_INDICES]))
    i_j3 = float(np.sum(i_servo_bus[J3_INDICES]))
    i_5v_total = i_j1 + i_j2 + i_j3 + radxa_current_a + pwr.ldo_u2_3v3_a
    i_l1_peak = min(i_5v_total, i_out_ilim_max) + 0.5 * delta_il

    # Actual battery current from conservation of power + buck conduction/switching loss
    p_out_5v = v_5v_bus * min(i_5v_total, i_out_ilim_max)
    p_buck_sw_loss = 0.14 + 0.032 * min(i_5v_total, i_out_ilim_max) * (v_in_buck / 7.4)
    p_buck_cond_loss = (min(i_5v_total, i_out_ilim_max) ** 2) * r_buck_cond
    p_in_buck = p_out_5v + p_buck_sw_loss + p_buck_cond_loss
    i_bat = p_in_buck / max(v_in_buck, 3.0)
    v_bat_term = max(3.5, vbat_ocv - r_bat_total * i_bat)

    telemetry = {
        "vbat_ocv_v": float(vbat_ocv),
        "vbat_term_v": float(v_bat_term),
        "i_bat_a": float(i_bat),
        "v_5v_bus_v": float(v_5v_bus),
        "i_5v_demand_a": float(i_5v_demand),
        "i_5v_total_a": float(i_5v_total),
        "i_out_ilim_max_a": float(i_out_ilim_max),
        "i_l1_peak_a": float(i_l1_peak),
        "delta_il_a": float(delta_il),
        "foldback_active": foldback_active,
        "radxa_brownout_risk": bool(v_5v_bus < pwr.radxa_brownout_v),
        "i_branch_j1_a": i_j1,
        "i_branch_j2_a": i_j2,
        "i_branch_j3_a": i_j3,
        "i_branch_j4_a": float(radxa_current_a),
        "i_branch_u2_a": float(pwr.ldo_u2_3v3_a),
        "i_servo_bus_15_a": i_servo_bus,
        "i_winding_15_a": np.abs(i_winding),
        "p_copper_15_w": p_copper_w,
        "p_mech_15_w": p_mech_w,
        "p_buck_ic_loss_w": float(p_buck_sw_loss + (min(i_5v_total, i_out_ilim_max) ** 2) * (duty_buck * pwr.buck_ron_hs_ohm + (1.0 - duty_buck) * pwr.buck_ron_ls_ohm)),
        "p_inductor_loss_w": float((min(i_5v_total, i_out_ilim_max) ** 2) * pwr.buck_inductor_dcr_ohm),
    }
    return tau_em, telemetry


class ServoThermalIntegrator:
    """2-node (winding + case) thermal integrator for all 15 XL330-M288-T servos."""

    def __init__(self, n_servos: int = 15, xl: XL330Spec = DEFAULT_XL330) -> None:
        self.xl = xl
        self.n = n_servos
        self.t_winding_c = np.full(n_servos, xl.ambient_temp_c, dtype=np.float64)
        self.t_case_c = np.full(n_servos, xl.ambient_temp_c, dtype=np.float64)

    def reset(self, ambient_c: float | None = None) -> None:
        amb = self.xl.ambient_temp_c if ambient_c is None else float(ambient_c)
        self.t_winding_c.fill(amb)
        self.t_case_c.fill(amb)

    def step(self, p_copper_w: np.ndarray, p_friction_w: np.ndarray, dt_sec: float) -> Tuple[np.ndarray, np.ndarray]:
        """Advance winding and case temperatures by dt_sec."""
        xl = self.xl
        q_wc = (self.t_winding_c - self.t_case_c) / xl.r_thermal_wind_to_case_k_per_w
        q_ca = (self.t_case_c - xl.ambient_temp_c) / xl.r_thermal_case_to_amb_k_per_w
        # Quiescent electronics (5V * 40mA = 0.20 W) + gear friction heat enter the case node
        p_case = 0.20 + np.maximum(0.0, p_friction_w)
        dt_w = (p_copper_w - q_wc) / xl.c_thermal_winding_j_per_k
        dt_c = (q_wc + p_case - q_ca) / xl.c_thermal_case_j_per_k
        self.t_winding_c = self.t_winding_c + dt_sec * dt_w
        self.t_case_c = self.t_case_c + dt_sec * dt_c
        return self.t_winding_c.copy(), self.t_case_c.copy()