File size: 4,226 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""Reachability check: damped least-squares IK from the home pose to every square and the bin.

Target: gripperframe site at square centre + the selected mesh's grasp height.
This is a kinematic check only, not a collision-free pick-and-place validation.
Reports position error and tilt for each square. Run:  .venv/bin/python sim/check_reach.py
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import mujoco
import numpy as np

HERE = Path(__file__).resolve().parent
POS_TOL = 0.003
TILT_TOL_DEG = 45.0
APPROACH_TILTS = (0, 15, 30, 40)   # degrees forward from vertical
ARM_DOF = 5          # pan, lift, elbow, wrist_flex, wrist_roll


def ik(m, d, site_id, target_pos, target_axis=np.array([0, 0, -1.0]), iters=300, damping=1e-4):
    lo, hi = m.jnt_range[:ARM_DOF, 0], m.jnt_range[:ARM_DOF, 1]
    jacp = np.zeros((3, m.nv)); jacr = np.zeros((3, m.nv))
    for _ in range(iters):
        mujoco.mj_forward(m, d)
        p = d.site_xpos[site_id]
        R = d.site_xmat[site_id].reshape(3, 3)
        a = R[:, 0]                       # gripper axis in world
        e_pos = target_pos - p
        e_rot = np.cross(a, target_axis)  # small-angle rotation aligning a to target
        mujoco.mj_jacSite(m, d, jacp, jacr, site_id)
        J = np.vstack([jacp[:, :ARM_DOF], 0.3 * jacr[:, :ARM_DOF]])
        e = np.concatenate([e_pos, 0.3 * e_rot])
        dq = J.T @ np.linalg.solve(J @ J.T + damping * np.eye(6), e)
        dq = np.clip(dq, -0.15, 0.15)
        d.qpos[:ARM_DOF] = np.clip(d.qpos[:ARM_DOF] + dq, lo, hi)
    mujoco.mj_forward(m, d)
    p = d.site_xpos[site_id]; a = d.site_xmat[site_id].reshape(3, 3)[:, 0]
    tilt = np.degrees(np.arccos(np.clip(a @ target_axis, -1, 1)))
    return np.linalg.norm(target_pos - p), tilt, d.qpos[:ARM_DOF].copy()


def main():
    pieces = json.loads((HERE / "assets/chess/manifest.json").read_text())["pieces"]
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--piece", choices=pieces, default="pawn")
    args = ap.parse_args()
    grasp_h = pieces[args.piece]["grasp_z_m"]
    m = mujoco.MjModel.from_xml_path(str(HERE / "chess_scene.xml"))
    d = mujoco.MjData(m)
    home = m.key("home").qpos[:ARM_DOF].copy()
    sid = m.site("gripperframe").id
    mujoco.mj_forward(m, d)

    targets = {}
    for f in "abcdefgh":
        for r in range(1, 9):
            targets[f"{f}{r}"] = m.site(f"sq_{f}{r}").pos + m.body("board").pos + [0, 0, grasp_h]
    targets["bin"] = m.body("bin").pos + [0, 0, 0.06]

    ok, bad = [], []
    grid = {}
    for name, t in targets.items():
        best = None
        # try a vertical approach first, then progressively tilt the gripper forward (toward the human)
        for tilt_deg in APPROACH_TILTS:
            th = np.radians(tilt_deg)
            axis = np.array([np.sin(th), 0.0, -np.cos(th)])
            for seed in (home, np.array([0, -0.5, 0.8, 1.2, 0]), np.array([0, 0.3, 0.3, 1.2, 0]), np.array([0, 0.8, -0.3, 1.0, 0])):
                d.qpos[:ARM_DOF] = seed
                err, tilt, q = ik(m, d, sid, t, target_axis=axis)
                tilt_total = np.degrees(np.arccos(np.clip(-d.site_xmat[sid].reshape(3, 3)[2, 0], -1, 1)))
                if best is None or err < best[0]:
                    best = (err, tilt_total, q)
            if best[0] < POS_TOL:
                break
        err, tilt, q = best
        good = err < POS_TOL and tilt < TILT_TOL_DEG
        (ok if good else bad).append(name)
        grid[name] = (err, tilt)

    print(f"{args.piece}: grasp height {grasp_h*1000:.2f} mm; kinematic reach only")
    print("rank  " + "  ".join(f"  {f}   " for f in "abcdefgh") + "   (pos err mm / gripper tilt from vertical deg)")
    for r in range(8, 0, -1):
        row = []
        for f in "abcdefgh":
            err, tilt = grid[f"{f}{r}"]
            mark = " " if f"{f}{r}" in ok else "X"
            row.append(f"{err*1000:4.1f}/{tilt:2.0f}{mark}")
        print(f"  {r}   " + " ".join(row))
    e, t = grid["bin"]
    print(f"bin: {e*1000:.1f} mm / {t:.0f} deg {'ok' if 'bin' in ok else 'X'}")
    print(f"\nreachable: {len(ok)}/{len(targets)}   unreachable: {bad if bad else 'none'}")


if __name__ == "__main__":
    main()