main
Drew Owens Publish Microgoose Rev A full-stack hardware, CAD, datasheet, and 7-stage RL stack e843249
"""Mechanical, electrical, and RL observation constants for Microgoose."""

from __future__ import annotations

import json
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Tuple

import numpy as np

SPINE_HZ: int = 200
SPINE_DT_SEC: float = 1.0 / SPINE_HZ  # 0.005 s (5.0 ms)

CONTROL_HZ: int = 50
CONTROL_DT_SEC: float = 1.0 / CONTROL_HZ  # 0.020 s (20.0 ms)

LOCOMOTION_DOF: int = 14
AUX_DOF: int = 1
TOTAL_DOF: int = 15
BEAK_JOINT_INDEX: int = 14

OBSERVATION_DIM: int = 61
ACTION_DIM: int = 14

# Safety supervisor thresholds required by Stage 6 specification
MAX_TILT_RAD: float = 0.75               # |roll| > 0.75 rad or |pitch| > 0.75 rad (~42.97 deg)
MIN_VBAT_V: float = 6.10                 # 2S Li-ion NP-F550 low-voltage cutoff
MAX_BUS_CURRENT_A: float = 4.20          # 5V_BUS continuous current threshold
OVERCURRENT_PERSIST_SEC: float = 0.100   # > 100 ms sustained overcurrent trips protection
SPINE_WATCHDOG_TIMEOUT_SEC: float = 0.100
STAND_RAMP_DURATION_SEC: float = 1.50    # Smooth 1.5 s minimum-jerk startup ramp
CROUCH_ROLLBACK_TICKS: int = 6           # 120 ms damped crouch absorption before torque cut
MAX_JOINT_STEP_RAD_PER_TICK: float = 0.22

DEFAULT_SOCK_DIR: str = "/tmp"
SPINE_SOCK_NAME: str = "microgoose-spine.sock"
POLICY_SOCK_NAME: str = "microgoose-policy.sock"
SPINE_PID_NAME: str = "microgoose-spine.pid"
POLICY_PID_NAME: str = "microgoose-policy.pid"


@dataclass(frozen=True)
class JointSpec:
    index: int
    dxl_id: int
    name: str
    branch: str
    min_rad: float
    max_rad: float
    default_rad: float


# Canonical connector branch DXL IDs on microgoose-spine:
#   J1 Left Leg  (RL indices 0..4)  -> DXL IDs 1..5
#   J2 Right Leg (RL indices 9..13) -> DXL IDs 6..10
#   J3 Neck/Head (RL indices 5..8)  -> DXL IDs 11..14
#   J3 Beak aux  (RL index 14)      -> DXL ID 15
_CANONICAL_DXL_ID_BY_NAME = {
    "left_hip_yaw": 1,
    "left_hip_roll": 2,
    "left_hip_pitch": 3,
    "left_knee_pitch": 4,
    "left_ankle_pitch": 5,
    "right_hip_yaw": 6,
    "right_hip_roll": 7,
    "right_hip_pitch": 8,
    "right_knee_pitch": 9,
    "right_ankle_pitch": 10,
    "neck_pitch": 11,
    "head_pitch": 12,
    "head_yaw": 13,
    "head_roll": 14,
    "beak_pitch": 15,
}

_FALLBACK_JOINTS: Tuple[JointSpec, ...] = (
    JointSpec(0, 1, "left_hip_yaw", "left_leg", math.radians(-45.0), math.radians(45.0), 0.0),
    JointSpec(1, 2, "left_hip_roll", "left_leg", math.radians(-35.0), math.radians(35.0), 0.0),
    JointSpec(2, 3, "left_hip_pitch", "left_leg", math.radians(-75.0), math.radians(75.0), -0.35),
    JointSpec(3, 4, "left_knee_pitch", "left_leg", math.radians(0.0), math.radians(110.0), 0.70),
    JointSpec(4, 5, "left_ankle_pitch", "left_leg", math.radians(-65.0), math.radians(65.0), -0.35),
    JointSpec(5, 11, "neck_pitch", "neck_head", math.radians(-55.0), math.radians(65.0), 0.20),
    JointSpec(6, 12, "head_pitch", "neck_head", math.radians(-65.0), math.radians(65.0), -0.20),
    JointSpec(7, 13, "head_yaw", "neck_head", math.radians(-80.0), math.radians(80.0), 0.0),
    JointSpec(8, 14, "head_roll", "neck_head", math.radians(-40.0), math.radians(40.0), 0.0),
    JointSpec(9, 6, "right_hip_yaw", "right_leg", math.radians(-45.0), math.radians(45.0), 0.0),
    JointSpec(10, 7, "right_hip_roll", "right_leg", math.radians(-35.0), math.radians(35.0), 0.0),
    JointSpec(11, 8, "right_hip_pitch", "right_leg", math.radians(-75.0), math.radians(75.0), -0.35),
    JointSpec(12, 9, "right_knee_pitch", "right_leg", math.radians(0.0), math.radians(110.0), 0.70),
    JointSpec(13, 10, "right_ankle_pitch", "right_leg", math.radians(-65.0), math.radians(65.0), -0.35),
    JointSpec(14, 15, "beak_pitch", "neck_head", math.radians(0.0), math.radians(38.0), 0.05),
)


def load_joint_specs() -> Tuple[JointSpec, ...]:
    """Load 15-DoF joint table from design/mechanical-interface.json with J1/J2/J3 DXL IDs."""
    repo_root = Path(__file__).resolve().parents[2]
    iface_path = repo_root / "design" / "mechanical-interface.json"
    if not iface_path.is_file():
        return _FALLBACK_JOINTS

    data = json.loads(iface_path.read_text(encoding="utf-8"))
    specs = []
    for item in data.get("joints", []):
        r_min, r_max = item["rangeDeg"]
        name = str(item["name"])
        dxl_id = _CANONICAL_DXL_ID_BY_NAME.get(name, int(item["dxlId"]))
        specs.append(
            JointSpec(
                index=int(item["index"]),
                dxl_id=dxl_id,
                name=name,
                branch=str(item["branch"]),
                min_rad=math.radians(float(r_min)),
                max_rad=math.radians(float(r_max)),
                default_rad=float(item["defaultRad"]),
            )
        )
    for aux in data.get("auxiliaryJoints", []):
        r_min, r_max = aux["rangeDeg"]
        name = str(aux["name"])
        dxl_id = _CANONICAL_DXL_ID_BY_NAME.get(name, int(aux["dxlId"]))
        specs.append(
            JointSpec(
                index=len(specs),
                dxl_id=dxl_id,
                name=name,
                branch=str(aux["branch"]),
                min_rad=math.radians(float(r_min)),
                max_rad=math.radians(float(r_max)),
                default_rad=float(aux["defaultRad"]),
            )
        )
    if len(specs) != TOTAL_DOF:
        return _FALLBACK_JOINTS
    return tuple(specs)


ALL_JOINTS: Tuple[JointSpec, ...] = load_joint_specs()
JOINT_NAMES_15: Tuple[str, ...] = tuple(j.name for j in ALL_JOINTS)
DXL_IDS_15: Tuple[int, ...] = tuple(j.dxl_id for j in ALL_JOINTS)

DEFAULT_RAD_15: np.ndarray = np.array([j.default_rad for j in ALL_JOINTS], dtype=np.float32)
DEFAULT_RAD_14: np.ndarray = DEFAULT_RAD_15[:LOCOMOTION_DOF].copy()
MIN_RAD_15: np.ndarray = np.array([j.min_rad for j in ALL_JOINTS], dtype=np.float32)
MAX_RAD_15: np.ndarray = np.array([j.max_rad for j in ALL_JOINTS], dtype=np.float32)

# Low-CG damped crouch pose used during attitude fault rollback before torque drop
CROUCH_RAD_15: np.ndarray = np.array(
    [
        0.00, 0.00, -0.58, 1.12, -0.54,
        0.28, -0.28, 0.00, 0.00,
        0.00, 0.00, -0.58, 1.12, -0.54,
        0.05,
    ],
    dtype=np.float32,
)

# Observation vector slice map matching design/mechanical-interface.json
OBSERVATION_SLICES = (
    ("base_ang_vel", 0, 3),
    ("projected_gravity", 3, 6),
    ("velocity_commands_xy_yaw", 6, 9),
    ("joint_pos_rel_14", 9, 23),
    ("joint_vel_14", 23, 37),
    ("last_actions_14", 37, 51),
    ("gait_phase_cos_sin", 51, 55),
    ("head_pitch_yaw_roll_cmd_and_stand_flag", 55, 59),
    ("foot_contact_estimate_lr", 59, 61),
)


def min_jerk_alpha(elapsed_sec: float, duration_sec: float) -> float:
    """Evaluate 5th-order minimum-jerk interpolation scalar in [0.0, 1.0]."""
    if duration_sec <= 1e-6:
        return 1.0
    u = max(0.0, min(1.0, elapsed_sec / duration_sec))
    return float(u * u * u * (10.0 + u * (-15.0 + 6.0 * u)))