"""Scaled-Asimov MuJoCo harness for the $1k study. Derived from Menlo Research's Asimov 1 MJCF (CERN-OHL-S-2.0).
Scaling: lengths x s, masses x mf (uniform), inertias x mf*s^2. Gains scaled for dynamic similarity:
kp x (mf*s), kd x (mf*s*sqrt(s)). Test timings and push durations x sqrt(s) (Froude), push force x mf."""
import mujoco, numpy as np
XML = '/workspace/asimov-port/src/sim-model/asimov_1_25dof/xml/asimov_1_25dof.xml'
J = ['left_hip_pitch','left_hip_roll','left_hip_yaw','left_knee','left_ankle_pitch','left_ankle_roll',
     'right_hip_pitch','right_hip_roll','right_hip_yaw','right_knee','right_ankle_pitch','right_ankle_roll',
     'waist_yaw','neck_yaw','neck_pitch',
     'left_shoulder_pitch','left_shoulder_roll','left_shoulder_yaw','left_elbow','left_wrist_yaw',
     'right_shoulder_pitch','right_shoulder_roll','right_shoulder_yaw','right_elbow','right_wrist_yaw']
J = [j + '_joint' for j in J]
def gains(j):
    if any(k in j for k in ['hip', 'knee', 'ankle']): return 250., 8.
    if 'waist' in j: return 200., 6.
    if 'neck' in j: return 30., 1.
    return 80., 3.
def build(s=1.0, mf=1.0, armature=None, lim=None):
    spec = mujoco.MjSpec.from_file(XML)
    for b in spec.bodies:
        if b.name == 'world': continue
        b.pos = np.array(b.pos) * s; b.ipos = np.array(b.ipos) * s
        b.mass = b.mass * mf
        b.inertia = np.array(b.inertia) * mf * s * s
        b.fullinertia = np.array(b.fullinertia) * mf * s * s
    for g in spec.geoms:
        g.pos = np.array(g.pos) * s
        if g.type != mujoco.mjtGeom.mjGEOM_MESH: g.size = np.array(g.size) * s
        if not np.any(np.isnan(g.fromto)): g.fromto = np.array(g.fromto) * s
    for m in spec.meshes: m.scale = np.array(m.scale) * s
    for st in spec.sites: st.pos = np.array(st.pos) * s
    for jt in spec.joints:
        jt.pos = np.array(jt.pos) * s
        jt.armature = jt.armature * mf * s * s
        jt.damping = jt.damping * mf * s * np.sqrt(s); jt.stiffness = jt.stiffness * mf * s
    for j in J:
        a = spec.add_actuator(); a.name = j[:-6]; a.target = j; a.trntype = mujoco.mjtTrn.mjTRN_JOINT
        a.gainprm[0] = 1; a.ctrllimited = 0
        jt = spec.joint(j)
        cap = lim[j][0] if lim else None
        if cap is None or cap > 1e3: jt.actfrclimited = 0
        else: jt.actfrclimited = 1; jt.actfrcrange = [-cap, cap]
    if armature:
        for j, v in armature.items(): spec.joint(j).armature = v
    m = spec.compile(); m.opt.timestep = 0.002
    return m
def mirror(L):
    q = {}
    for k, v in L.items(): q['left_' + k + '_joint'] = v; q['right_' + k + '_joint'] = -v
    return q
def pose(t, test, ts):
    a = 0.15; arms = {'shoulder_pitch': 0.0, 'shoulder_roll': -0.15, 'elbow': 0.3}; q = {}; extra = {}
    T1 = 1.0 * ts
    if test == 'squat':
        s = 0.5 - 0.5 * np.cos(2 * np.pi * max(0, t - T1) / (1.6 * ts)) if t > T1 else 0; a = 0.15 + 0.20 * s
    elif test == 'squat_fast':
        s = 0.5 - 0.5 * np.cos(2 * np.pi * max(0, t - T1) / (0.8 * ts)) if t > T1 else 0; a = 0.15 + 0.20 * s
    elif test == 'arms':
        s = np.clip((t - T1) / (0.5 * ts), 0, 1) - np.clip((t - 3 * ts) / (0.5 * ts), 0, 1); arms['shoulder_pitch'] = -1.57 * s
    elif test == 'arms_slow':
        s = np.clip((t - T1) / (1.0 * ts), 0, 1) - np.clip((t - 3.5 * ts) / (1.0 * ts), 0, 1); arms['shoulder_pitch'] = -1.57 * s
    elif test == 'sway':
        s = np.sin(2 * np.pi * max(0, t - T1) / (2.0 * ts)) if t > T1 else 0
        extra = {k: 0.05 * s for k in ['left_hip_roll_joint', 'right_hip_roll_joint', 'left_ankle_roll_joint', 'right_ankle_roll_joint']}
    q.update(mirror({'hip_pitch': -a, 'knee': 2 * a, 'ankle_pitch': -a})); q.update(mirror(arms)); q.update(extra)
    return q
def run(m, lim, test, s=1.0, mf=1.0, push=None, locked=(), T=6.0):
    ts = np.sqrt(s); T = T * ts; tf = mf * s
    d = mujoco.MjData(m)
    jid = [m.joint(j).id for j in J]; qa = [m.jnt_qposadr[i] for i in jid]; va = [m.jnt_dofadr[i] for i in jid]
    q0 = pose(0, test, ts)
    for j, i in zip(J, qa): d.qpos[i] = q0.get(j, 0.)
    mujoco.mj_forward(m, d)
    zmin = min(d.geom_xpos[g][2] - m.geom_size[g][0] for g in range(m.ngeom) if 'foot' in (m.geom(g).name or ''))
    d.qpos[2] -= zmin - 0.0005; mujoco.mj_forward(m, d)
    n = int(T / m.opt.timestep); tau = np.zeros((n, len(J))); vel = np.zeros((n, len(J))); sat = np.zeros(len(J)); err = np.zeros(len(J))
    pel = m.body('pelvis_link').id; lf = m.body('left_ankle_roll_link').id; rf = m.body('right_ankle_roll_link').id
    z0 = d.xpos[pel][2]; fell = False; minz = 9
    mujoco.mj_subtreeVel(m, d)
    for k in range(n):
        t = k * m.opt.timestep; qt = pose(t, test, ts)
        com = d.subtree_com[0]; cv = d.subtree_linvel[0]
        fc = 0.5 * (d.xpos[lf] + d.xpos[rf]) + np.array([0.035 * s, 0, 0])
        ex = com[0] - fc[0]; ey = com[1] - fc[1]
        bp = np.clip((3.0 * ex + 0.5 * cv[0] * np.sqrt(s)) / s, -0.3, 0.3); br = np.clip((3.0 * ey + 0.5 * cv[1] * np.sqrt(s)) / s, -0.1, 0.1)
        qt['left_ankle_pitch_joint'] = qt.get('left_ankle_pitch_joint', 0) + bp
        qt['right_ankle_pitch_joint'] = qt.get('right_ankle_pitch_joint', 0) - bp
        qt['left_ankle_roll_joint'] = qt.get('left_ankle_roll_joint', 0) + br
        qt['right_ankle_roll_joint'] = qt.get('right_ankle_roll_joint', 0) + br
        for c, (j, i, v) in enumerate(zip(J, qa, va)):
            kp, kd = gains(j); kp *= tf; kd *= tf * np.sqrt(s)
            if j in locked: kp *= 20; kd *= 5; qt[j] = q0.get(j, 0.)
            u = kp * (qt.get(j, 0.) - d.qpos[i]) - kd * d.qvel[v] + d.qfrc_bias[v]
            pk, w0, wn = lim[j]
            w = abs(d.qvel[v]); cap = pk if w <= w0 else max(0., pk * (wn - w) / max(wn - w0, 1e-6))
            if abs(u) > cap: sat[c] += 1; u = np.sign(u) * cap
            d.ctrl[c] = u; tau[k, c] = u; vel[k, c] = d.qvel[v]
            if t > ts: err[c] = max(err[c], abs(qt.get(j, 0.) - d.qpos[i]))
        if push and push[0] * ts <= t < (push[0] + push[1]) * ts: d.xfrc_applied[pel, :3] = np.array(push[2]) * mf
        else: d.xfrc_applied[pel, :3] = 0
        mujoco.mj_step(m, d); mujoco.mj_subtreeVel(m, d)
        minz = min(minz, d.xpos[pel][2])
        if d.xpos[pel][2] < 0.55 * z0: fell = True; break
    k = max(k, 1); tau = tau[:k]; vel = vel[:k]; s0 = int(ts / m.opt.timestep)
    res = {}
    for c, j in enumerate(J):
        tt = tau[s0:, c] if k > s0 else tau[:, c]; vv = vel[s0:, c] if k > s0 else vel[:, c]
        res[j] = dict(peak=float(np.max(np.abs(tt))), rms=float(np.sqrt(np.mean(tt ** 2))), vpk=float(np.max(np.abs(vv))), sat=float(sat[c] / k), err=float(err[c]))
    return dict(fell=fell, minz=float(minz), z0=float(z0), joints=res, mass=float(sum(m.body_mass)))
