---
name: so100-robot-control
description: >-
  Control the SO100 follower arm for sim2real (ManiSkill/LeRobot) —
  return-to-home, full motor state reads, sim<->real joint calibration, real-policy
  evaluation with load tracking, and camera pose back-solve from a policy probe.
  Use when working in lerobot-sim2real, homing/resetting the SO100, diagnosing
  "torque but no motion", reading feetech motor state, aligning the real camera to
  sim, or grasping a cube on the real arm. Trigger keywords: SO100, so100_follower,
  sim2real, return to home, home robot, reset robot, feetech, joint calibration,
  camera back-solve, camera alignment, eval_real_probe, grasp cube, wrist_flex overload.
---

# SO100 sim2real robot control

Project: `/home/thomas/src/lerobot-sim2real`. Real arm = LeRobot `so100_follower`,
port `/dev/ttyACM1`, OpenCV camera index 6 (640x480). Sim = ManiSkill
`SO100GraspCube-v1`. Run everything with the project venv:
`uv --project . run python -u <script>` (the agent kernel lacks mani_skill/pandas).

Motors (order matters): `shoulder_pan, shoulder_lift, elbow_flex, wrist_flex,
wrist_roll, gripper`.

## Golden rules (learned the hard way)

- **Never command a big motion blind.** Interpolate slowly AND read
  `Present_Load` every few steps. Abort on stall (high load + no position change
  + still far from target). A joint already AT target drawing load is just
  holding (gripper fingers press at home) — NOT a stall.
- **Verify motion, don't assume it.** Read position before/after and grab a camera
  frame. "Torque engaged" does not mean "moved" (inspection-only runs enable
  torque but never command motion).
- **wrist_flex overload is a camera-gap symptom, NOT a hardware/sign blocker**
  (diagnosed 2026-11-14, `outputs/wrist_diag/FINDINGS.md`). The wrist moves FREE
  in the negative direction (to -27deg+, load 20-40) but stalls in positive
  (~18deg, load 1100-1900); holding rest costs ~1100 load (gravity pulls wrist -,
  rest is far from neutral). The SIM grasp uses wrist- (90->40deg) = the real FREE
  direction, and the QPOS_OFFSET wrist SIGN is correct (verified: sim wrist- moves
  TCP forward+up, real wrist- swings gripper the same way). A real-episode wrist(+)
  stall means the policy is commanding the WRONG direction because it misbehaves on
  the real camera view. Fix the camera gap, not the wrist. Motor is saturated at
  stall, so raising P_Coefficient (configure sets 16) does NOT help. Scripts:
  `diag_wrist.py` (range/load sweep), `diag_wrist_pitch.py` (sign check).
- **GPU is 8GB (RTX 3070 Laptop).** 512-env PPO training ~7.2GB; adding rendering
  eval envs OOMs PhysX (`GPU compressContactStage fail to launch kernel`). Use
  `--ppo.num-envs 256 --ppo.num-eval-envs 4` for fine-tuning. CPU render SEGFAULTS.
- Long jobs: `proc("start", cmd)` then poll `proc("log", pid=N)`. Never block the
  kernel on a sleep. Release a holding process with `proc("kill", pid=N, sig="INT")`.
- **The greenscreen bg.png MUST match the camera viewpoint.** A bg captured from an
  old camera position (tray on the wrong side) makes ANY camera re-alignment
  unlearnable — the rendered robot/cube sit on a mismatched background, and PPO
  never phase-transitions (stuck reach-only, success=0 past 11M steps). Diagnosed
  2026-11-14: old bg had tray LEFT, real camera tray RIGHT. Fix: swing the arm out
  of frame (`explore_hide_arm.py`, shoulder_pan=-85), capture the real background,
  inpaint the cube out, process center-crop(x80)->128 -> `bg_real.png`. VERIFY by
  rendering sim on the new bg and checking tray/table/floor/base align with real.
  Camera-DR cannot fix a fundamentally misaligned bg (the bg is a fixed 2D image).

## 1. Return to home (the first thing to do)

`lerobot_sim2real/scripts/home_robot.py` homes the arm in joint space to the env
rest pose and PROVES motion (read-back + before/after frames in `outputs/home/`).

```bash
uv --project . run python -u lerobot_sim2real/scripts/home_robot.py --read-only   # inspect, no motion
uv --project . run python -u lerobot_sim2real/scripts/home_robot.py --test-joint shoulder_pan --test-delta 6  # verify control path
uv --project . run python -u lerobot_sim2real/scripts/home_robot.py               # home + hold (torque ON, Ctrl-C releases)
uv --project . run python -u lerobot_sim2real/scripts/home_robot.py --torque-off  # home, verify, release (self-terminates)
```

Why joint-space, not IK: home is a KNOWN joint config (`rest_qpos`), so
interpolation avoids IK singularities/reachability failures. IK (ikpy/pinocchio)
is only worth it for a Cartesian TCP home with obstacle avoidance.

The rest pose is the "arm raised above table" lift pose, NOT gripper-down-at-cube.
It is not gravity-stable: a limp arm sags back to folded, so "home" only persists
with torque ON. The eval re-homes at startup anyway.

## 2. sim<->real joint calibration (REQUIRED)

`lerobot_sim2real/utils/calibration.py`:
```
sim_qpos = real_get_qpos + QPOS_OFFSET
QPOS_OFFSET = [0.075, 0.241, -0.024, 1.221, 0.314, 0.248]   # radians
```
`CalibratedRealAgent.get_qpos` adds the offset; `set_target_qpos` subtracts it.
ALSO: LeRobot applies an elbow convention fix — `get_qpos` subtracts 6.8 deg from
elbow_flex, `send_action` adds 6.8 deg. Account for BOTH when computing tracking
error from raw `Present_Position` (else elbow shows a false ~8 deg miss).

Env rest pose (sim convention): `rest_qpos = [0, 0, 0, pi/2, pi/2, 0]`.
Home in real motor deg = `rad2deg(rest_qpos - QPOS_OFFSET)` (elbow +6.8 on send).

Without the offset the policy sweeps up into the tray and self-collides; with it,
it reaches down toward the cube. Always use `CalibratedRealAgent` (eval defaults
`--calibrated` True).

## 3. Read full motor state

feetech `bus.sync_read(reg)` works for all motors at once. Registers:
`Present_Position, Present_Load, Present_Current, Present_Velocity,
Present_Temperature, Present_Voltage, Status, Moving, Torque_Enable`.
`Status != 0` = error; `|Present_Load|` high = stall/contact/grasp. See
`eval_real_probe.py:read_state`. Load is the diagnostic core — qpos alone hides
stalls and grasps.

## 4. Real-policy evaluation with state tracking

`lerobot_sim2real/scripts/eval_real_probe.py` logs pos/vel/load/cur/temp/status
for all 6 motors EVERY step + start/event/end snapshots + load-tracked reset.
```bash
uv --project . run python -u lerobot_sim2real/scripts/eval_real_probe.py \
  --checkpoint runs/<run>/ckpt_N.pt --env-kwargs-json-path env_config_solved.json \
  --record-dir outputs/real_probe/runX --num-episodes 1 --max-episode-steps 80
```
Flags: `--state-only --hold-only --no-reset-to-rest --load-threshold --calibrated`.
Outputs `ep00_real.mp4` + `ep00_state.csv` + snapshots. Inspect frames critically
(use vision), don't box-tick.

## 5. Camera pose back-solve (the sim2real breakthrough)

Use the gripper as a calibration target: run a policy probe, record
(TCP_world from sim FK, gripper_pixel from real camera) correspondences at several
poses, then least-squares solve the real camera pose. Full method + SAPIEN camera
model + the divergence trap: see `references/camera-backsolve.md`. Working scripts
in `outputs/cam_backsolve/scripts/` (backsolve_cam.py, camproj.py, validate_cam.py).

Solved camera (this rig): pos `[-0.0126,-0.1788,0.4482]` (fixed platform),
target `[0.1773,-0.107,0.1631]`, fov `0.7567`. In `env_config_solved.json`.
A big camera jump (newcam/joint_refined) is UNLEARNABLE (0% success). The solved
camera is a small GEOMETRIC perturbation of gitold (+4 deg elevation) and is
learnable FROM SCRATCH — but a gitold-trained policy does NOT transfer to it:
eval ckpt_1551 gitold=0.81 success vs solved-cam=0.125 (camera alone; spawn shift
is minor). Fine-tuning ckpt_1551 on the solved cam DEGRADES it (unlearns the
grasp; both LR 1e-4 and 3e-5 fail). So train FROM SCRATCH with the solved camera,
don't fine-tune. Diagnostic: outputs/cam_backsolve/data/diag_camera_isolation.json.

## 6. Training / fine-tuning

`lerobot_sim2real/scripts/train_ppo_rgb.py --env-id SO100GraspCube-v1` (env-id is a
REQUIRED FLAG, not positional). Fine-tune from a good checkpoint:
```bash
uv --project . run python -u lerobot_sim2real/scripts/train_ppo_rgb.py \
  --env-id SO100GraspCube-v1 --env-kwargs-json-path env_config_solved.json \
  --ppo.exp-name ppo-solved-cam-ft --ppo.seed 3 \
  --ppo.checkpoint runs/ppo-SO100GraspCube-v1-rgb-aligned-s3/ckpt_1551.pt \
  --ppo.total-timesteps 2000000 --ppo.learning-rate 1e-4 \
  --ppo.num-envs 256 --ppo.num-eval-envs 4 --ppo.capture-video
```
`--ppo.checkpoint` loads weights with a FRESH optimizer. `track` defaults off
(omit; `--no-ppo.track` is NOT a valid flag). Monitor `runs/<exp>/` checkpoints +
TensorBoard eval/success_once. ckpt_1551 (gitold camera) = sim success 0.812.

**Phase-transition trap:** this task shows `success_once=0` for the first ~9-10M
env-steps, then a SHARP jump to ~0.8 (gitold aligned-s3 TB: 0 until 9.2M, 0.812 at
10.2M). A short run (e.g. 2M fine-tune or 8M scratch) ends BEFORE the grasp
emerges and looks like failure. Train from scratch to >=12-16M env-steps. Return
climbs steadily (8->17->23) long before success jumps — don't judge by early
success=0. Read the TB curve (`eval/success_once`) to calibrate.

**Eval-window trap:** `SO100GraspCube-v1` has `max_episode_steps=64` and does NOT
terminate on success (only truncates). The default `--ppo.num-eval-steps 50` is
SHORTER than 64, so no eval episode ever ends -> "Evaluated ... 0 episodes" and
NO success metric is printed (blind eval). Always set `--ppo.num-eval-steps 64`
(or more) so episodes truncate and `eval_success_once_mean` is reported. Verify
behavior by inspecting `runs/<exp>/videos/*.mp4` frames (vision), not just counts.

## Workflow to a real grasp

1. Home the arm (section 1), verify it moved.
2. Fine-tune the policy with the solved camera (section 6); watch sim success.
3. Eval on real with state tracking (section 4); inspect where TCP goes vs cube.
4. If it misses, back-solve the camera residual (section 5), update config, repeat.
5. Use the load signal to detect contact/grasp/stall. Iterate until real grasp.
