diff --git a/.gitignore b/.gitignore index 02b3355..33d58d8 100644 --- a/.gitignore +++ b/.gitignore @@ -24,8 +24,8 @@ outputs/ *.safetensors *.onnx reports/ -assets/urdf/*/kinematics/user/*.yaml -assets/urdf/*/*_calib.urdf +assets/urdf/*/*/kinematics/user/*.yaml +assets/urdf/*/*/*_calib.urdf assets/urdf/**/visual_glb_raw/ assets/urdf/**/visual_glb_src/ assets/urdf/**/relocalize_metrics.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 51748af..235fc78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.3.11] — 2026-11-28 + +### Added + +- Published the pretrained `xArm6` + `Gripper G2` Pick & Place RL checkpoint (`pick_place/xarm6-pick-place/seed-7/model_best.pt`, `C10` recipe, early-stopped at `650` iterations) to Hugging Face (`UFACTORY-Developer/ufactory_genesis_rl`): `100%` dual-holdout (`64/64` on seed `17000`, `128/128` on seed `17500`), `100%` (`64/64`) blind evaluation on seed `18007` (`max_press = 0.477 mm`, mean/median target error `6.98 / 6.14 mm`), and `GLB B=1` replay PASS; across the 10-seed `C10` benchmark (`seeds 1..10`), `8/10` seeds passed strict blind evaluation and `GLB` replay (`508/512 = 99.22%` combined blind success across passing seeds, `0.00` IK rejects). Updated bilingual RL docs with Hugging Face download and inference instructions. + +- Added full `vacuum_gripper` (5-cup xArm/UF850) integration to `ufactory-pick-place` (`assets/configs/runtime/grippers/vacuum_gripper.yaml`, `assets/manifest.json`, `VacuumProfileAdapter` with midpoint binary edge deduplication and `shutdown_real`, `--gripper vacuum_gripper` and `--vacuum-hardware-version {1,2}`, 0-DOF `SafetyGate` collision handling), verified end-to-end on real `xArm5` (`XF130505D43A02`, firmware `v2.8.2`, plug-in hardware version 1, `tcp_offset=[0, 0, 126, 0, 0, 0] mm`, `tcp_load=[0.61 kg, [0, 0, 53] mm]`): 3-cycle IO test (`0.38–0.76 ms` send, `21–22 ms` TGPIO output flip, zero arm drift), `dry-run` / `sdk-sim`, and real empty-grasp `servo_j` (`max_lateness=0.321 ms`) + `servo_cartesian` (`max_lateness=0.596 ms`) with zero deadline misses and zero errors. +- **Breaking (config `sha256`):** Added 6D `gripper.tcp_offset` (`[x_mm, y_mm, z_mm, roll_deg, pitch_deg, yaw_deg]`, matching `xarm-python-sdk` default and UFACTORY Studio) to all runtime robot/gripper YAMLs (`assets/configs/runtime/{robots,grippers}/*.yaml`, refreshed `assets/manifest.json`), unified planning TCP-to-flange conversion and fail-closed real-mode controller TCP consistency validation (`10 mm / 2°`, `ufactory.manipulation.tcp`), decoupled headless `servo_j` compilation in `ufactory-pick-place` and `ufactory-packaging-showcase` from Genesis/`build_scene` via pure-NumPy `ArmIKContext` / `solve_arm_home_q`, and generalized `build_scene` / `TrajKinematicMirror` / `KinematicCarryTracker` to support 0-DOF end effectors (`vacuum_gripper`, `lite6_vacuum_gripper`, and `bare` arm without finger links or gripper DOFs). +- Enabled `--executor servo_j` (`dry-run` / `sdk-sim` / `real`) and real-mode `--visual` kinematic mirror support for `bio_gripper_g2` in `ufactory-pick-place` via generic scene support (`_robot_urdf_for_visual_model`, `gripper_dof_multipliers`, `build_scene(..., home_xy_base=...)`, `drive_for_gap_m`), symmetric mirror multiplier handling (`_set_kinematic_pose`, `gap_m_from_drive`), and empty-grasp carry opt-out (`_mirror_attach_dist_m`) on `xarm6`. +- Added the UFACTORY AI1500 six-axis force/torque sensor asset (`assets/urdf/accessories/ft_sensor_ai1500/`, `+58.6 mm` flange lift, `0.6 kg`, CoM `(0, 0, 22) mm`, multi-material Draco GLB, visual STL, watertight convex hull, and exporter `dev/accessories/ai1500/export_ft_sensor_ai1500.py`), upgraded `assets/urdf/assembly.yaml` to `schema_version: 6` with `ft_sensors` stacking (`xarm5/6/7` and `uf850` flange below optional camera stand, adapter, and end effector), added `--ft-sensor` to `examples/visualization/view_robot.py` and `ft_sensor_ai1500` to `examples/visualization/view_tool.py`, and updated `assets/manifest.json`. +- Added real-robot six-axis F/T sensor control wrapper `ufactory.hardware.ft_sensor` (`XArmFTSensor`, `XArmTransport.ft_sensor()`, validated `FTAdmittanceParams` / `FTForceControlParams` / `FTLoadOffset` / `FTCollisionConfig` / `FTSensorConfigSnapshot` / `FTSensorReading`, fail-closed safety gates with `--confirm-real`, `set_state(0)` mode-activation sequencing, `xarm-python-sdk 1.18.4` SN/version fallback, and guaranteed `mode=0` teardown contexts) and post-install diagnostic CLI `scripts/ft_sensor_check.py` (`enable` / `disable` / `status` / `zero` / `identify-load` / `admittance-test` / `force-test`). +- Added real-controller support for `bio_gripper_g2` in `ufactory-pick-place` (`--mode dry-run / sdk-sim / real --executor servo_cartesian`, gated to `xarm6` via `bio_g2_controller_mode_error` with `servo_j` / `--visual` blocked until generic scene support is added), including runtime overlay [bio_gripper_g2.yaml](assets/configs/runtime/grippers/bio_gripper_g2.yaml), `BIO_GRIPPER_G2_TCP_IN_FLANGE_M`, and `BIO_GRIPPER_G2_GRIPPER_PARAMS`. +- Added `ufactory.grippers.vacuum` (`VacuumGripperAdapter`, `vacuum_io_pins` for hardware versions 1 and 2) and hardware test scripts under `dev/end_effectors/bio_gripper_g2/hardware/` and `dev/end_effectors/vacuum_gripper/hardware/`. + +### Fixed + +- Fixed two real-hardware `xArm v2.8.2` vacuum-gripper issues discovered on `xArm5`: (1) keep SDK default `sync=True` on `set_vacuum_gripper` because `sync=False` in `MODE_SERVO` drops one of the two back-to-back TGPIO writes (leaving `[1, 1]` energized), while `sync=True` completes in `< 0.8 ms` with 100% reliability; (2) avoid calling `@xarm_wait_until_not_pause`-decorated `set_vacuum_gripper` in `VacuumProfileAdapter.shutdown_real` after `execute_real` enters `state=3` (paused), checking live `get_tgpio_output_digital` first and falling back to raw `arm_cmd.tgpio_set_digital` if suction is still active while paused/stopped. +- Fixed `_update_mirror_entities` in `ufactory/trajectory/mirror_executor.py` for Genesis 1.4.7+ (which replaced `RigidSolver._vgeoms_render_T` / `_geoms_render_T` with `RasterizerContext.rigid_geoms_T(solver, is_visual)`) and Genesis 1.5+ (falling back to `context.update(force_render=True)` when `rigid_nodes` is absent), restoring live `--visual` real-robot mirror rendering. +- Hardened `BioG2Adapter` (`speed_rpm` / `force_percent` validation, `wait=False` and `wait_motion=False` on `set_bio_gripper_g2_position`, sub-0.05 mm command deduplication, and `get_bio_gripper_g2_position` pre-caching in `prepare_real`). +- Added a runtime `` fallback in `PinocchioCollisionBackend` (`ufactory/safety/adapters/pinocchio.py`) when Pinocchio `mimic=True` fails on URDFs where a mimic joint precedes its parent joint (such as `bio_gripper_g2`), keeping collision finger symmetry without modifying URDF assets. +- Added `err_warn` and `state` diagnostics when `sdk_sim_feedback` fails before stopping the virtual controller. +- Split the Lite6 `link6` collision mesh into three exact watertight convex hulls (`lite6_link6_col_00..02.stl`: flange body, recessed neck, and side aviation connector; `0.000 mm` surface bloat / `0.000 mm` leak vs `visual/link6.stl`) and updated `lite6.urdf`, `lite6_visual.glb.urdf`, and `assets/manifest.json`. Previously, the single 66-vertex hull bridged across the concave neck and connector steps by up to 1.08 mm, pushing calibrated Lite6 `link4`/`link6` clearance below the 5 mm preflight margin (`4.990 mm` vs `5.539 mm` visual surface) in pick-place and packaging while near-limit contact at `|q5| ≈ 2.16 rad` remains detected. +- `scripts/gen_kinematics_params.py` now identifies the per-unit joint origins from the controller's own forward kinematics instead of copying the register-8 export. The register-8 values were wrong on three models: the xArm5 export uses different frames (its YAML was 0.55–1.15 m off), and UF850 / Lite6 do not compensate the joint-1 tilt in joint 2 (1.92–3.06 mm off). The script reads the zero pose and single-joint sweeps (31–43 read-only `get_forward_kinematics` queries, plus 100 for verification; nothing is enabled or moved), removes the controller TCP offset, and writes the file only if 100 random held-out configurations match within the FK validation limits (1 mm, 0.5°). A non-zero controller world offset is refused. Measured on five arms (2026-11-26): held-out max error 0.07 mm (UF850), 0.42 mm (xArm5, xArm7), 0.43 mm (xArm6), 0.45 mm (Lite6); Pinocchio and Genesis reproduce the same values. The remaining error is the flange centre sitting 38–240 µm off the last joint axis, which joint origins cannot express; the model is exact whenever the last joint is at 0, like the register-8 form. New module `ufactory.kinematics.controller_fk`. + +### Changed + +- Upgraded `examples/rl/pick_place` to the `C10` seed-stability pure-PPO recipe (`examples/rl/pick_place/{env.py,recipe.yaml,train.py}`, `ufactory/training/pick_place_config.py`): pad-derived flange height limits (`PRE_LIFT_PAD_FLOOR_Z`, `TOUCHDOWN_REF_MARGIN_Z`), finite-horizon timeout handling (`time_outs=False`), zero-penalty outer-margin linear spring envelope (`alpha=0.16`), target-table unclamping ratchet (`unclamping_at_table`), single-episode `touchdown_rewarded` latch, `pre_lift` lift-drive / stall-penalty / `< 15 mm` XY-damping fixes, `std_range: [0.16, 0.65]` guard, and 192-episode dual-validation early stopping (`--eval-start-iteration`), keeping `env_version=3` (70 obs / 4 actions) unchanged. +- Updated the material of the three mounting plates (`assets/urdf/mounts/{xarm,uf850,lite6}_mounting_plate`) in both GLBs (`plate_anodized_aluminum`) and URDFs (`PlateAluminum`) to match the arm end-flange `FLANGE_METAL` (`[0.952941, 0.952941, 0.949020, 1.0]`, `metallic = 0.80`, `roughness = 0.640131`) and refreshed `assets/manifest.json` hashes. +- **Breaking:** Categorized `assets/urdf/` into `robots/`, `end_effectors/`, `cameras/`, `mounts/`, `objects/`, and `accessories/` (created for upcoming linear rails and sensors), keeping `assets/urdf/assembly.yaml` at the root. Updated `ufactory.robots.{registry,assembly,paths}`, `ufactory.grippers.lite6`, `ufactory.simulation.{bio_g2_microplate,bio_g2_model}`, `scripts/gen_kinematics_params.py`, `assets/urdf/assembly.yaml`, `assets/configs/runtime/robots/*.yaml`, `assets/manifest.json`, `.gitignore`, tests, and README links. Source URDF contents and `sha256` digests are unchanged, while composed URDF mesh paths and `sha256` digests change (downstream composed-URDF hash bindings such as safety allowlists, RL checkpoint manifests, and trajectory reports must be regenerated). +- Updated the `link_base` inertial parameters in both UF850 URDFs (`assets/urdf/uf850/uf850.urdf` and `uf850_visual.glb.urdf`) using the SolidWorks mass-properties evaluation of the `Arm850_P01` base assembly (`5.869631 kg`, CoM `(-0.762, -0.044, 117.610) mm`, `Ixx/Iyy/Izz = 0.032711870245 / 0.03295126767 / 0.013458380527 kg·m²`, `Ixy/Ixz/Iyz = 8.0733473e-05 / -0.000343329636 / -1.0328638e-05 kg·m²` in standard URDF negative product-of-inertia convention) and refreshed `assets/manifest.json`. Fixed-base arm joint dynamics are unchanged, while the bare-arm total mass (`16.2434 → 19.844631 kg`) and moving-base inertia match the CAD assembly; `urdf_sha256` bindings of UF850 and composed UF850 URDFs change accordingly. +- Updated `uf850_mounting_plate` (`0.9142 → 1.056 kg`) and `robotiq_mounting` (`0.1097 → 0.118 kg`) URDF inertials to physical measured masses (uniformly scaled over each part's CAD volume with unchanged CoM and geometry) and refreshed `assets/manifest.json`. Measured `lite6_mounting_plate` (`0.2431 kg`) and `xarm_mounting_plate` (`0.3554 kg`) matched simulation and remain unchanged. +- SDK simulation evidence (`schema_version` 2) compares a redundant arm (more than six joints, i.e. xArm7) by end-effector pose instead of joint by joint, because its firmware may resolve the elbow differently from the host IK. Every arm must now also match end-effector rotation within `max_shadow_joint_error_rad`, and the firmware stream must stay inside the joint limits less `joint_limit_margin_rad` (required for a redundant arm, and checked for any caller that passes `joint_lower_rad` / `joint_upper_rad`, as pick-place and packaging do). New evidence fields `max_ee_rotation_error_rad` and `self_motion_allowed`. + ## [0.3.10] — 2026-11-25 ### Added diff --git a/README.md b/README.md index baf17b5..25b7584 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ufactory_genesis -![Python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Version](https://img.shields.io/badge/version-0.3.10-orange) ![Genesis](https://img.shields.io/badge/genesis-1.4.7-lightgrey) ![CI](https://github.com/xArm-Developer/ufactory_genesis/actions/workflows/ci.yml/badge.svg) +![Python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Version](https://img.shields.io/badge/version-0.3.11-orange) ![Genesis](https://img.shields.io/badge/genesis-1.4.7-lightgrey) ![CI](https://github.com/xArm-Developer/ufactory_genesis/actions/workflows/ci.yml/badge.svg) UFACTORY robot simulation and reinforcement learning examples built on Genesis. @@ -26,7 +26,7 @@ Installation and complete commands are in the [examples guide](examples/README.m Simulation-only training and inference on Linux/NVIDIA GPUs. See the [RL index](examples/rl/README.md) for the task progression and guides. 1. **[Reach: target reaching](examples/rl/reach/README.md)** — Move the end effector of a bare-arm robot (`xarm5`, `xarm6`, `xarm7`, `uf850`, `lite6`) to a target with a success distance strictly below **5 mm**. Supports single-arm and four-arm real-time GLB inference, with [pretrained checkpoints on Hugging Face](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl). -2. **[Pick & Place: tabletop](examples/rl/pick_place/README.md)** — xArm6 + Gripper G2 grasps and transfers a cube sampled uniformly in `x ∈ [300, 500] mm`, `y ∈ [-200, 200] mm` to a fixed target at `(300, 300) mm`, trained from scratch with pure PPO. +2. **[Pick & Place: tabletop](examples/rl/pick_place/README.md)** — xArm6 + Gripper G2 grasps and transfers a cube sampled uniformly in `x ∈ [300, 500] mm`, `y ∈ [-200, 200] mm` to a fixed target at `(300, 300) mm`, trained from scratch with pure PPO, with a [pretrained checkpoint on Hugging Face](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl). diff --git a/README_zh.md b/README_zh.md index 7ba32b0..7a0b95a 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,6 +1,6 @@ # ufactory_genesis -![Python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Version](https://img.shields.io/badge/version-0.3.10-orange) ![Genesis](https://img.shields.io/badge/genesis-1.4.7-lightgrey) ![CI](https://github.com/xArm-Developer/ufactory_genesis/actions/workflows/ci.yml/badge.svg) +![Python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Version](https://img.shields.io/badge/version-0.3.11-orange) ![Genesis](https://img.shields.io/badge/genesis-1.4.7-lightgrey) ![CI](https://github.com/xArm-Developer/ufactory_genesis/actions/workflows/ci.yml/badge.svg) 基于 Genesis 的 UFACTORY 机械臂仿真与强化学习示例。 @@ -26,7 +26,7 @@ 在 Linux/NVIDIA GPU 上进行仿真训练与推理。学习顺序及各任务指南见 [RL 索引](examples/rl/README_zh.md)。 1. **[Reach:目标到达](examples/rl/reach/README_zh.md)**:让未安装夹爪的机械臂(`xarm5`、`xarm6`、`xarm7`、`uf850`、`lite6`)末端到达目标点,成功距离严格小于 **5 mm**。支持单臂、四臂 GLB 实时推理,提供 [Hugging Face 预训练检查点](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl)。 -2. **[Pick & Place:桌面抓放](examples/rl/pick_place/README_zh.md)**:xArm6 + Gripper G2 抓取在 `x ∈ [300, 500] mm`、`y ∈ [-200, 200] mm` 内均匀随机采样的方块并搬运到桌面固定目标位置 `(300, 300) mm`,以纯 PPO 从零训练策略。 +2. **[Pick & Place:桌面抓放](examples/rl/pick_place/README_zh.md)**:xArm6 + Gripper G2 抓取在 `x ∈ [300, 500] mm`、`y ∈ [-200, 200] mm` 内均匀随机采样的方块并搬运到桌面固定目标位置 `(300, 300) mm`,以纯 PPO 从零训练策略,提供 [Hugging Face 预训练检查点](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl)。 diff --git a/SECURITY.md b/SECURITY.md index 0569e94..82dd094 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ ## Supported version -Only the current `0.3.10` development line receives security fixes. This is Alpha robotics software and is not safety-certified. +Only the current `0.3.11` development line receives security fixes. This is Alpha robotics software and is not safety-certified. ## Reporting diff --git a/assets/configs/runtime/grippers/bio_gripper_g2.yaml b/assets/configs/runtime/grippers/bio_gripper_g2.yaml new file mode 100644 index 0000000..365d561 --- /dev/null +++ b/assets/configs/runtime/grippers/bio_gripper_g2.yaml @@ -0,0 +1,33 @@ +schema_version: 1 +robot: + urdf: assembly:bio_gripper_g2 +task: + parameters: + fixed_object_position_m: [0.38, -0.12, 0.015] + fixed_target_position_m: [0.38, 0.12, 0.015] + default_ee_position_m: [0.38, -0.12, 0.30] +gripper: + adapter: bio_g2 + drive_joint: bio_gripper_g2_right_finger_joint + all_joint_names: [bio_gripper_g2_right_finger_joint, bio_gripper_g2_left_finger_joint] + finger_link_names: [bio_gripper_g2_left_finger, bio_gripper_g2_right_finger] + open_drive: 0.0395 + closed_drive: 0.0 + open_gap_m: 0.150 + closed_gap_m: 0.071 + kp: 16000.0 + kv: 40.0 + force_lower_n: -20.0 + force_upper_n: 20.0 + damping: 0.1 + frictionloss: 0.0 + real_command: true + feedback: true + closed_loop: false + allowed_contact_links: [bio_gripper_g2_left_finger, bio_gripper_g2_right_finger] + tool_tip_offset_z_m: 0.0595 + finger_pad_below_center_m: 0.0 + finger_close_descent_m: 0.0 + grasp_table_clearance_m: 0.100 + grasp_height_extra_m: 0.0 + tcp_offset: [157.64, 0.0, 59.5, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/grippers/robotiq_2f_140.yaml b/assets/configs/runtime/grippers/robotiq_2f_140.yaml index 551c30c..7846391 100644 --- a/assets/configs/runtime/grippers/robotiq_2f_140.yaml +++ b/assets/configs/runtime/grippers/robotiq_2f_140.yaml @@ -35,6 +35,7 @@ gripper: finger_close_descent_m: 0.0253 grasp_table_clearance_m: 0.01 grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 246.1, 0.0, 0.0, 0.0] task: parameters: default_ee_position_m: [0.30, 0.00, 0.36] diff --git a/assets/configs/runtime/grippers/robotiq_2f_85.yaml b/assets/configs/runtime/grippers/robotiq_2f_85.yaml index eb7de94..4597e9b 100644 --- a/assets/configs/runtime/grippers/robotiq_2f_85.yaml +++ b/assets/configs/runtime/grippers/robotiq_2f_85.yaml @@ -35,3 +35,4 @@ gripper: finger_close_descent_m: 0.0135 grasp_table_clearance_m: 0.01 grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 173.8, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/grippers/vacuum_gripper.yaml b/assets/configs/runtime/grippers/vacuum_gripper.yaml new file mode 100644 index 0000000..1218ad5 --- /dev/null +++ b/assets/configs/runtime/grippers/vacuum_gripper.yaml @@ -0,0 +1,33 @@ +schema_version: 1 +robot: + urdf: assembly:vacuum_gripper +task: + parameters: + fixed_object_position_m: [0.30, 0.00, 0.015] + fixed_target_position_m: [0.30, 0.25, 0.015] + default_ee_position_m: [0.30, 0.00, 0.30] +gripper: + adapter: vacuum_gripper + drive_joint: "" + all_joint_names: [] + finger_link_names: [] + open_drive: 0.0 + closed_drive: 0.0 + open_gap_m: 1.0 + closed_gap_m: 0.0 + kp: 0.0 + kv: 0.0 + force_lower_n: 0.0 + force_upper_n: 0.0 + damping: 0.0 + frictionloss: 0.0 + real_command: true + feedback: false + closed_loop: false + allowed_contact_links: [xarm_vacuum_gripper_link] + tool_tip_offset_z_m: 0.126 + finger_pad_below_center_m: 0.0 + finger_close_descent_m: 0.0 + grasp_table_clearance_m: 0.050 + grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 126.0, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/motion/default.yaml b/assets/configs/runtime/motion/default.yaml index 06d877b..2200b2c 100644 --- a/assets/configs/runtime/motion/default.yaml +++ b/assets/configs/runtime/motion/default.yaml @@ -1,8 +1,11 @@ schema_version: 1 motion: + # Mode 1 servo streaming rate (Hz); xArm SDK supports 30-250 Hz (default 50 Hz). rate_hz: 50.0 joint_speed_rad_s: 1.0 joint_acceleration_rad_s2: 12.0 cartesian_speed_m_s: 0.15 cartesian_acceleration_m_s2: 0.8 gripper_duration_s: 2.0 + # Firmware-aligned set_allow_approx_motion(bool) singularity avoidance (disabled by default). + allow_approx_motion: false diff --git a/assets/configs/runtime/robots/lite6.yaml b/assets/configs/runtime/robots/lite6.yaml index 0269dce..1f5abe7 100644 --- a/assets/configs/runtime/robots/lite6.yaml +++ b/assets/configs/runtime/robots/lite6.yaml @@ -6,7 +6,7 @@ robot: dof: 6 joint_names: [joint1, joint2, joint3, joint4, joint5, joint6] ee_link: link6 - assets_dir: assets/urdf/lite6 + assets_dir: assets/urdf/robots/lite6 urdf: "assembly:lite6_gripper:stl" capabilities: [servo_j, servo_cartesian, lite6_gripper, sdk_sim, hardware_gripper] environment_contact_pairs: [[link_base, table]] @@ -44,3 +44,4 @@ gripper: finger_close_descent_m: 0.0 grasp_table_clearance_m: 0.006 grasp_height_extra_m: 0.015 + tcp_offset: [0.0, 0.0, 75.3, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/robots/uf850.yaml b/assets/configs/runtime/robots/uf850.yaml index 749a1cb..6b0c936 100644 --- a/assets/configs/runtime/robots/uf850.yaml +++ b/assets/configs/runtime/robots/uf850.yaml @@ -6,7 +6,7 @@ robot: dof: 6 joint_names: [joint1, joint2, joint3, joint4, joint5, joint6] ee_link: link6 - assets_dir: assets/urdf/uf850 + assets_dir: assets/urdf/robots/uf850 urdf: "assembly:gripper_g2" capabilities: [servo_j, servo_cartesian, gripper_g2, sdk_sim] environment_contact_pairs: [[link_base, table]] @@ -41,3 +41,4 @@ gripper: finger_close_descent_m: 0.015 grasp_table_clearance_m: 0.010 grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 178.6, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/robots/xarm5_1305.yaml b/assets/configs/runtime/robots/xarm5_1305.yaml index 8932058..af16098 100644 --- a/assets/configs/runtime/robots/xarm5_1305.yaml +++ b/assets/configs/runtime/robots/xarm5_1305.yaml @@ -6,7 +6,7 @@ robot: dof: 5 joint_names: [joint1, joint2, joint3, joint4, joint5] ee_link: link5 - assets_dir: assets/urdf/xarm5 + assets_dir: assets/urdf/robots/xarm5 urdf: "assembly:gripper_g2" capabilities: [servo_j, servo_cartesian, gripper_g2, sdk_sim] environment_contact_pairs: [[link_base, table]] @@ -41,3 +41,4 @@ gripper: finger_close_descent_m: 0.015 grasp_table_clearance_m: 0.010 grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 178.6, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/robots/xarm6_1305.yaml b/assets/configs/runtime/robots/xarm6_1305.yaml index 63a7147..167de2a 100644 --- a/assets/configs/runtime/robots/xarm6_1305.yaml +++ b/assets/configs/runtime/robots/xarm6_1305.yaml @@ -6,7 +6,7 @@ robot: dof: 6 joint_names: [joint1, joint2, joint3, joint4, joint5, joint6] ee_link: link6 - assets_dir: assets/urdf/xarm6 + assets_dir: assets/urdf/robots/xarm6 urdf: "assembly:gripper_g2" capabilities: [servo_j, servo_cartesian, gripper_g2, sdk_sim, hardware_gripper] environment_contact_pairs: [[link_base, table]] @@ -41,3 +41,4 @@ gripper: finger_close_descent_m: 0.015 grasp_table_clearance_m: 0.010 grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 178.6, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/robots/xarm7_1305.yaml b/assets/configs/runtime/robots/xarm7_1305.yaml index 7344bdb..8bbfa75 100644 --- a/assets/configs/runtime/robots/xarm7_1305.yaml +++ b/assets/configs/runtime/robots/xarm7_1305.yaml @@ -6,7 +6,7 @@ robot: dof: 7 joint_names: [joint1, joint2, joint3, joint4, joint5, joint6, joint7] ee_link: link7 - assets_dir: assets/urdf/xarm7 + assets_dir: assets/urdf/robots/xarm7 urdf: "assembly:gripper_g2" capabilities: [servo_j, servo_cartesian, gripper_g2, sdk_sim] environment_contact_pairs: [[link_base, table]] @@ -41,3 +41,4 @@ gripper: finger_close_descent_m: 0.015 grasp_table_clearance_m: 0.010 grasp_height_extra_m: 0.0 + tcp_offset: [0.0, 0.0, 178.6, 0.0, 0.0, 0.0] diff --git a/assets/configs/runtime/simulation/default.yaml b/assets/configs/runtime/simulation/default.yaml index 363df61..1c5ec18 100644 --- a/assets/configs/runtime/simulation/default.yaml +++ b/assets/configs/runtime/simulation/default.yaml @@ -3,6 +3,8 @@ simulation: backend: gpu precision: "32" seed: 1 + # Configurable Genesis physics step rate (Hz); defaults to 50 Hz. + rate_hz: 50.0 # Conservative 32-substep production margin for G2 contact scenes at 50 Hz. # The compliant mimic equality profile is the primary numerical-stability fix. substeps: 32 diff --git a/assets/manifest.json b/assets/manifest.json index ef74cd7..53a7168 100644 --- a/assets/manifest.json +++ b/assets/manifest.json @@ -1,5 +1,5 @@ { - "manifest_version": "0.3.10", + "manifest_version": "0.3.11", "required_paths": [ "assets/configs/runtime/motion/default.yaml", "assets/configs/runtime/safety/default.yaml", @@ -17,40 +17,45 @@ "assets/configs/runtime/robots/lite6.yaml", "assets/scenes/packaging_showcase/textures/cardboard.jpg", "assets/scenes/packaging_showcase/meshes/uv_box.obj", - "assets/urdf/lite6_gripper/meshes/visual/visual_glb/shell.glb", + "assets/urdf/end_effectors/lite6_gripper/meshes/visual/visual_glb/shell.glb", "assets/configs/runtime/tasks/robots/lite6_reach.yaml", "assets/configs/runtime/tasks/robots/uf850_reach.yaml", "assets/configs/runtime/tasks/robots/xarm5_1305_reach.yaml", "assets/configs/runtime/tasks/robots/xarm7_1305_reach.yaml", - "assets/urdf/lite6/lite6.urdf", - "assets/urdf/uf850/uf850.urdf", - "assets/urdf/xarm5/xarm5_1305.urdf", - "assets/urdf/xarm6/xarm6_1305.urdf", - "assets/urdf/xarm7/xarm7_1305.urdf", + "assets/urdf/robots/lite6/lite6.urdf", + "assets/urdf/robots/uf850/uf850.urdf", + "assets/urdf/robots/xarm5/xarm5_1305.urdf", + "assets/urdf/robots/xarm6/xarm6_1305.urdf", + "assets/urdf/robots/xarm7/xarm7_1305.urdf", "assets/urdf/assembly.yaml", - "assets/urdf/gripper_g2/gripper_g2_movable_visual.urdf", - "assets/urdf/lite6_gripper/lite6_gripper_movable_visual.urdf", - "assets/urdf/xarm_mounting_plate/xarm_mounting_plate.urdf", - "assets/urdf/uf850_mounting_plate/uf850_mounting_plate.urdf", - "assets/urdf/lite6_mounting_plate/lite6_mounting_plate.urdf", - "assets/urdf/robotiq_mounting/robotiq_mounting.urdf", - "assets/urdf/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf", - "assets/urdf/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf", + "assets/urdf/end_effectors/gripper_g2/gripper_g2_movable_visual.urdf", + "assets/urdf/end_effectors/lite6_gripper/lite6_gripper_movable_visual.urdf", + "assets/urdf/mounts/xarm_mounting_plate/xarm_mounting_plate.urdf", + "assets/urdf/mounts/uf850_mounting_plate/uf850_mounting_plate.urdf", + "assets/urdf/mounts/lite6_mounting_plate/lite6_mounting_plate.urdf", + "assets/urdf/mounts/robotiq_mounting/robotiq_mounting.urdf", + "assets/urdf/end_effectors/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf", + "assets/urdf/end_effectors/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf", + "assets/configs/runtime/grippers/bio_gripper_g2.yaml", "assets/configs/runtime/grippers/robotiq_2f_85.yaml", - "assets/configs/runtime/grippers/robotiq_2f_140.yaml" + "assets/configs/runtime/grippers/robotiq_2f_140.yaml", + "assets/configs/runtime/grippers/vacuum_gripper.yaml", + "assets/urdf/accessories/ft_sensor_ai1500/ft_sensor_ai1500.urdf" ], "schema_version": 1, "sha256": { - "assets/configs/runtime/grippers/robotiq_2f_140.yaml": "918933a1cb2fc666c2c8dee8398d6c3e37d9ab2043b522dddfdcfc558e47cdb5", - "assets/configs/runtime/grippers/robotiq_2f_85.yaml": "b718cdf17fb6112d2c06a71850a9a07d7da58cd6ed1501da0992c4713e5d6bc5", - "assets/configs/runtime/motion/default.yaml": "ce961bb044f0c95a803fac693bffb7c75b3e78df61ce90e4ab2644e79be73f03", - "assets/configs/runtime/robots/lite6.yaml": "ca2815d2aee06fe359af4d3f6becb7254a022b9363d603fc3611e355c9638fc3", - "assets/configs/runtime/robots/uf850.yaml": "c828d4c0b18c07839711e1b27f699bd08ebd7264a1e4c3aef78c4e3b224e5498", - "assets/configs/runtime/robots/xarm5_1305.yaml": "1969ac6f1bedbbd731aadfa1bfab43d4640459cc4f3c4c5124c0aa9bbb644059", - "assets/configs/runtime/robots/xarm6_1305.yaml": "6f022eec1d0d1625464792ed7249ece0b35bf895397981ebdecf599a14c12597", - "assets/configs/runtime/robots/xarm7_1305.yaml": "d0193f14373d6588f935417f2d1132b2d65486c9ed34448b63cb06908846fc52", + "assets/configs/runtime/grippers/bio_gripper_g2.yaml": "a8633c7235103025b953147aa9809a735d3e344ceb76d01516812f665fdbf3b8", + "assets/configs/runtime/grippers/robotiq_2f_140.yaml": "5e6710b68986dd09f4deccc41628d58e3038305b9bb87624fe11de9c1059478d", + "assets/configs/runtime/grippers/robotiq_2f_85.yaml": "6b345a42335e6fbef6fa99e5dba4457a86731dd16684d2871d1a93fee235c482", + "assets/configs/runtime/grippers/vacuum_gripper.yaml": "97d5b535817b694d7d26b1ccd364cdba3bd3c4c69a3b94aeabc0c42fb7ab944a", + "assets/configs/runtime/motion/default.yaml": "c28ba3e95eac42bd4ca688705f13ec345139973a3dbc18dcd741979051ac3d92", + "assets/configs/runtime/robots/lite6.yaml": "98a2d246aab432b49c1a2d51a9834b77dcd9d8d9f9ba9737cf5eb2a1cd9120b9", + "assets/configs/runtime/robots/uf850.yaml": "214eb13dfce0c261e87e0e70403695074e2d26fe73a2bca0fbd864fab3850453", + "assets/configs/runtime/robots/xarm5_1305.yaml": "6434202d721fe11db94ab1de0da07b993e9b6173fce50a6c9df464a590e993d2", + "assets/configs/runtime/robots/xarm6_1305.yaml": "c81a0db916bc1f28cc6c6a1006f87158459b598027f682f3d5898f65473a22dd", + "assets/configs/runtime/robots/xarm7_1305.yaml": "e9e9b6d474d53818d9efa7bfc4ee5bd0704af228e906105b59a0606f8bbf274d", "assets/configs/runtime/safety/default.yaml": "29fd72f5863759e2b9167b34fe25723868fc5a633cf1837e7776e12112d71c06", - "assets/configs/runtime/simulation/default.yaml": "56e052faa63898969418ed48845ab6b24774b9de04bbc1ea94dce4b22739cbc3", + "assets/configs/runtime/simulation/default.yaml": "b779c272ecd951d555be22a7420cfa284ad08e678624ca1eff7da7a66ff75bea", "assets/configs/runtime/tasks/packaging_showcase.yaml": "164aff6a872a60bd241a7edb2b807371b26616a3c154f6ea672e37e7b57f203a", "assets/configs/runtime/tasks/pick_place.yaml": "269ae8ad342132a7907609d8fff7b4147f6399727bf60266a9483729a8958f9e", "assets/configs/runtime/tasks/reach.yaml": "15fce661d05c20b2e179eb54f5e585d6bcdbee70a0a0df0893c07c5fc934cd82", @@ -63,20 +68,21 @@ "assets/configs/runtime/tasks/robots/xarm7_1305_reach.yaml": "5059ce9b53123689726e2d3846f43c18ba92db7ca8bba7e87f9dccea9c4fc4d7", "assets/scenes/packaging_showcase/meshes/uv_box.obj": "901c6efc7a1e1b4947af16ed95b9e76b2b1d053fd117d36641a9e770768e35cc", "assets/scenes/packaging_showcase/textures/cardboard.jpg": "4d6b57827d7398b7679e4d5d8687ae18ed5ba179e2d62d66e209aac800cf591b", - "assets/urdf/assembly.yaml": "cb368b90a0d62af1498531bb77ed4b4c85104fc769284848d824ef1a1d4e20e1", - "assets/urdf/gripper_g2/gripper_g2_movable_visual.urdf": "1088891ca89d14b1912ac62bd00c1ae0bebc287e7663821c372bfc32984c1bea", - "assets/urdf/lite6/lite6.urdf": "0045071263238025da9c0719e5a12f8ef68881bd7c45105acbefedae2fd1748e", - "assets/urdf/lite6_gripper/lite6_gripper_movable_visual.urdf": "d4013937766d7bdb1bd83f82f66cd4720f0ac2fb10ad179889b4bf3b50db1ede", - "assets/urdf/lite6_gripper/meshes/visual/visual_glb/shell.glb": "1ae8f67d1ddfa3b5a7f09265aa680eff72bc05f4c817470ac885333dde1cce57", - "assets/urdf/lite6_mounting_plate/lite6_mounting_plate.urdf": "b66a6e2ae2a7a1a2b33b05df12cdda51b912b29da69dba38ea404d4e2739363f", - "assets/urdf/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf": "9152fcfe21356c0ec1a12df7ff2599e791737b53dfe13bdb57c049f2008543b3", - "assets/urdf/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf": "6b4981c2c9236137d843d6f22c936bbbf5cdf99bba1d08672ad6cd19eeec76f9", - "assets/urdf/robotiq_mounting/robotiq_mounting.urdf": "b69dad60533c59c52a2f3bd5df4e8833bd47c3114a83f49c3ef3253dccf6b385", - "assets/urdf/uf850/uf850.urdf": "5f5b83d084b78411267886b53420e004ef13ea9ec95c0af471cd7d6f0f6c9d67", - "assets/urdf/uf850_mounting_plate/uf850_mounting_plate.urdf": "56f59238805905cd3ed835b1e4c45eed18a76541b6ed3a66e85553ce833abce3", - "assets/urdf/xarm5/xarm5_1305.urdf": "62325923a392dadd79c901135476b6422c5f375bc7a6a43343c025a45c0e0350", - "assets/urdf/xarm6/xarm6_1305.urdf": "c42cb8dd772a3eb155dbbc2141c96f3721155830c18408f7dd47a6eaf3a7ab2a", - "assets/urdf/xarm7/xarm7_1305.urdf": "703c66329704ea79ffa5fe7ff88394ea72f96be9c9100c44e3b201dc9c671517", - "assets/urdf/xarm_mounting_plate/xarm_mounting_plate.urdf": "34b9e4a8e2a0760e96c4adb4a4c80683aebc597688ce429bef47c5b9c0bcb5a0" + "assets/urdf/accessories/ft_sensor_ai1500/ft_sensor_ai1500.urdf": "55b35db04ac4eebbed383b03ba8326620732b04e97257d5b5597550e1774d162", + "assets/urdf/assembly.yaml": "3f676b74a333535e055739eb839e0437c836257970ae36b41205690cce82a7f9", + "assets/urdf/end_effectors/gripper_g2/gripper_g2_movable_visual.urdf": "1088891ca89d14b1912ac62bd00c1ae0bebc287e7663821c372bfc32984c1bea", + "assets/urdf/end_effectors/lite6_gripper/lite6_gripper_movable_visual.urdf": "d4013937766d7bdb1bd83f82f66cd4720f0ac2fb10ad179889b4bf3b50db1ede", + "assets/urdf/end_effectors/lite6_gripper/meshes/visual/visual_glb/shell.glb": "1ae8f67d1ddfa3b5a7f09265aa680eff72bc05f4c817470ac885333dde1cce57", + "assets/urdf/end_effectors/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf": "9152fcfe21356c0ec1a12df7ff2599e791737b53dfe13bdb57c049f2008543b3", + "assets/urdf/end_effectors/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf": "6b4981c2c9236137d843d6f22c936bbbf5cdf99bba1d08672ad6cd19eeec76f9", + "assets/urdf/mounts/lite6_mounting_plate/lite6_mounting_plate.urdf": "d2f3d010554be07cf92cb9b02f00ce6989da886a690ad5e7935b9a6a0d0cec3b", + "assets/urdf/mounts/robotiq_mounting/robotiq_mounting.urdf": "fd864a1e4061f4ba5d65bcc4234c34e099a4ccf6b9b4caa79dacb7a1d7fed808", + "assets/urdf/mounts/uf850_mounting_plate/uf850_mounting_plate.urdf": "b292a29d8ef3630c4eac49372bc9632a8ca5ced276940e2c19a2cda58953b658", + "assets/urdf/mounts/xarm_mounting_plate/xarm_mounting_plate.urdf": "9bfd40e2034fdf02d78b231ecdc835190982ea3586485517e284ee3165001bdc", + "assets/urdf/robots/lite6/lite6.urdf": "8b8a64aae696811f7e10be9e2d583704ab1edd679b8bdd3a3127e3a1e6e78508", + "assets/urdf/robots/uf850/uf850.urdf": "93638fa86db8ca2ad918540764f6c4aee003c1876502cd08ac86326e6023372d", + "assets/urdf/robots/xarm5/xarm5_1305.urdf": "62325923a392dadd79c901135476b6422c5f375bc7a6a43343c025a45c0e0350", + "assets/urdf/robots/xarm6/xarm6_1305.urdf": "c42cb8dd772a3eb155dbbc2141c96f3721155830c18408f7dd47a6eaf3a7ab2a", + "assets/urdf/robots/xarm7/xarm7_1305.urdf": "703c66329704ea79ffa5fe7ff88394ea72f96be9c9100c44e3b201dc9c671517" } } diff --git a/assets/urdf/accessories/README.md b/assets/urdf/accessories/README.md new file mode 100644 index 0000000..931cdf7 --- /dev/null +++ b/assets/urdf/accessories/README.md @@ -0,0 +1,5 @@ +# Accessories + +Accessories (such as force/torque sensors and linear rails like the AL0700) belong here. + +- [`ft_sensor_ai1500/`](ft_sensor_ai1500/README.md): UFACTORY AI1500 six-axis force/torque sensor (`xArm5`/`6`/`7` & `UF850`, `+58.6 mm` tool lift, `0.6 kg`). diff --git a/assets/urdf/accessories/ft_sensor_ai1500/README.md b/assets/urdf/accessories/ft_sensor_ai1500/README.md new file mode 100644 index 0000000..fd3b073 --- /dev/null +++ b/assets/urdf/accessories/ft_sensor_ai1500/README.md @@ -0,0 +1,51 @@ +# UFACTORY 6-Axis Force/Torque Sensor (AI1500) + +UFACTORY AI1500 six-axis force/torque sensor for the **xArm5 / xArm6 / xArm7 / UF850** tool flange (`flange: xarm`, ISO 9409-1-50-4-M6; **not compatible with Lite 6**). + +## Mechanical & Inertial Parameters + +Frame: `ft_sensor_ai1500`, origin at the arm tool flange centre on the mating plane (`z = 0`, `+Z` pointing outward along the tool axis). + +- **Tool lift (`ft_sensor_ai1500_output`)**: `+58.6 mm` along flange `+Z` (matching the default UFACTORY Studio TCP Z offset `(0, 0, 58.6 mm, 0, 0, 0)`). +- **Mass**: `0.6 kg` (official specification including flange mounting hardware). +- **Centre of mass**: `(0, 0, 22) mm` in the flange frame. +- **Inertia at CoM** (uniform cylinder approximation `R = 38.8 mm`, `H = 63.6 mm`, matching the `ufactory_mujoco` AI1500 sandbox): + `ixx = 0.000428064`, `iyy = 0.000428064`, `izz = 0.000451632 kg·m²`, `ixy = ixz = iyz = 0`. +- **Outer envelope**: `Ø77.6 mm` (`r_max = 38.8 mm`), `z ∈ [-5.0, +58.6] mm` (bottom locating spigot reaches `-5.0 mm`; mounting skirt covers `z ∈ [-3.0, 0.0] mm` around the arm flange). +- **Reference frames**: + - `ft_sensor_ai1500_flange_mount`: `(0, 0, 0)` mm + - `ft_sensor_ai1500_output`: `(0, 0, 58.6)` mm (downstream parts attach here) + - `ft_sensor_ai1500_measurement`: `(0, 0, 58.6)` mm (nominal six-axis sensing frame) + +## Stacking Order + +Because the AI1500 bottom skirt (`r ∈ [31.5, 38.8] mm`, `z ∈ [-3.0, 0.0] mm`) wraps around the arm flange, the camera stand cannot sit below the sensor. Downstream parts always stack onto `ft_sensor_ai1500_output` in this order: + +`arm flange -> ft_sensor_ai1500 (+58.6 mm) -> [camera_stand (+3.0 mm) + camera] -> [robotiq_mounting (+11.0 mm)] -> end_effector` + +> **Real-robot note**: When mounting a camera stand/camera downstream of the AI1500, its mass is supported by the sensor and included during `iden_ft_sensor_load_offset`; secure the camera cable to minimize tugging disturbances. + +## Sensor Specifications (Reference) + +- **Sampling rate**: `200 Hz` +- **Rated range**: `±400 N` (`Fx/Fy/Fz`), `±20 N·m` (`Tx/Ty/Tz`) +- **Overload limit**: `±600 N`, `±30 N·m` +- **Resolution**: `0.4 N` (force), `0.01 N·m` (torque) + +> **Hardware verification status (`xArm6`, controller `v2.8.2`, AI1500 `SN=AI15000626001F`, `v1.1.1`)**: Bare-sensor communication, `enable`/`disable`, SN/firmware readback, stationary zeroing (`±0.05 N` / `±0.001 N·m` noise), ±45° tilt gravity sign convention (external force applied to distal flange in tool frame, `+Z` outward; bare distal cap mass ~154 g), admittance hold (`ft_mode=1`), and constant-force closed-loop sign/gain (`ft_mode=2`, `coord=TOOL`, `f_ref=-2 N` moves along tool `-Z` at `2.0 mm/s` for `kp=0.005`) have been verified via `scripts/ft_sensor_check.py`. Mounted-tool payload identification (`identify-load`, which requires a non-trivial external payload downstream of the sensor) and dynamic inertia calibration remain pending. + +## Files + +``` +ft_sensor_ai1500/ +├── ft_sensor_ai1500.urdf # Part URDF (GLB visual + 1 convex collision hull + reference frames) +└── meshes/ + ├── collision/ft_sensor_ai1500_col_00.stl # Watertight convex hull (48 vertices, 92 faces) + └── visual/ + ├── ft_sensor_ai1500.glb # Multi-material Draco-compressed GLB + └── ft_sensor_ai1500.stl # Merged meter-scale visual STL (visual="stl") +``` + +## Source + +Exported via [dev/accessories/ai1500/export_ft_sensor_ai1500.py](../../../dev/accessories/ai1500/export_ft_sensor_ai1500.py) from the frozen source snapshots (`model.glb`, `collision.json`, derived from `6 Axis Force Torque Sensor(AI1500)_20260413.STEP`, SHA-256 verified) copied from `ufactory_mujoco`. diff --git a/assets/urdf/accessories/ft_sensor_ai1500/ft_sensor_ai1500.urdf b/assets/urdf/accessories/ft_sensor_ai1500/ft_sensor_ai1500.urdf new file mode 100644 index 0000000..1f8a3a3 --- /dev/null +++ b/assets/urdf/accessories/ft_sensor_ai1500/ft_sensor_ai1500.urdf @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/urdf/accessories/ft_sensor_ai1500/meshes/collision/ft_sensor_ai1500_col_00.stl b/assets/urdf/accessories/ft_sensor_ai1500/meshes/collision/ft_sensor_ai1500_col_00.stl new file mode 100644 index 0000000..3bf8ba3 Binary files /dev/null and b/assets/urdf/accessories/ft_sensor_ai1500/meshes/collision/ft_sensor_ai1500_col_00.stl differ diff --git a/assets/urdf/accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.glb b/assets/urdf/accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.glb new file mode 100644 index 0000000..bab7ded Binary files /dev/null and b/assets/urdf/accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.glb differ diff --git a/assets/urdf/accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.stl b/assets/urdf/accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.stl new file mode 100644 index 0000000..2e3e6e5 Binary files /dev/null and b/assets/urdf/accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.stl differ diff --git a/assets/urdf/assembly.yaml b/assets/urdf/assembly.yaml index 2bf90f6..4036a05 100644 --- a/assets/urdf/assembly.yaml +++ b/assets/urdf/assembly.yaml @@ -29,11 +29,16 @@ # source, base_link, mount_joint, flange, mount, glb_visuals, stl_visuals, stl_materials: as for end_effectors # tool_lift_m the end effector mount moves this far along flange +Z (added on top of any spacer tool_lift_m) # -# spacers.: a plate clamped between the flange and the end effector (it may carry a camera) +# spacers.: a plate clamped between the flange (or F/T sensor output) and the end effector (it may carry a camera) # source, base_link, mount_joint, flange (or flanges), mount, stl_visuals, stl_materials: as for end_effectors # tool_lift_m the adapter/end effector mount (or the arm's link_eef when there is none) moves this far along flange +Z # end_effectors end effectors that fit on the spacer; the bare arm always does # +# ft_sensors.: a six-axis force/torque sensor mounted on the arm flange (below any spacer, adapter, or end effector) +# source, base_link, mount_joint, flange, mount, glb_visuals, stl_visuals, stl_materials: as for end_effectors +# output_link link on the sensor where downstream spacers, adapters, and end effectors attach +# tool_lift_m cumulative tool offset added along flange +Z when counting bare link_eef lift +# # cameras.: a camera on a spacer # source, base_link, mount_joint, stl_materials: as for end_effectors; visual "stl" draws the collision boxes # spacer spacer the camera mounts on; robots and end effectors are the spacer's @@ -45,7 +50,7 @@ # robots robot profile keys fitting this plate (each robot appears in at most one mounting plate) # thickness_m plate thickness (m); the plate occupies z in [-thickness_m, 0] # mount base_link pose {xyz, rpy} in the arm's link_base frame -schema_version: 5 +schema_version: 6 flanges: xarm: # One part on xArm5/6/7; same layout on UF850: PCD 50 mm, 4 x M6 at 45/135/225/315 deg, @@ -56,18 +61,18 @@ flanges: robots: [lite6] end_effectors: gripper_g2: - source: gripper_g2/gripper_g2_movable_visual.urdf + source: end_effectors/gripper_g2/gripper_g2_movable_visual.urdf base_link: xarm_gripper_base_link mount_joint: gripper_fix flange: xarm # The base collides as 10 convex hulls, so its STL visual is the full mesh rather than its collision geometry. stl_visuals: - xarm_gripper_base_link: gripper_g2/meshes/visual/base_link.stl + xarm_gripper_base_link: end_effectors/gripper_g2/meshes/visual/base_link.stl stl_materials: xarm_gripper_base_link: White "*": Silver bio_gripper_g2: - source: bio_gripper_g2/bio_gripper_g2_movable_visual.urdf + source: end_effectors/bio_gripper_g2/bio_gripper_g2_movable_visual.urdf base_link: bio_gripper_g2_base_link mount_joint: bio_gripper_g2_attach flange: xarm @@ -79,71 +84,86 @@ end_effectors: # from the flange axis (CAD reference 157.5 mm). mount: {xyz: [0.022642, 0.000814, 0.002516], rpy: [0.0, 0.0, -0.00628537]} vacuum_gripper: - source: vacuum_gripper/vacuum_gripper.urdf + source: end_effectors/vacuum_gripper/vacuum_gripper.urdf base_link: xarm_vacuum_gripper_link mount_joint: vacuum_gripper_fix flange: xarm stl_visuals: - xarm_vacuum_gripper_link: vacuum_gripper/meshes/visual/vacuum_gripper_visual.stl + xarm_vacuum_gripper_link: end_effectors/vacuum_gripper/meshes/visual/vacuum_gripper_visual.stl robotiq_2f_85: - source: robotiq_2f_85/robotiq_2f_85_movable_visual.urdf + source: end_effectors/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf base_link: robotiq_2f_85_base_link mount_joint: robotiq_2f_85_fix flange: xarm adapter: robotiq_mounting stl_visuals: - robotiq_2f_85_base_link: robotiq_2f_85/meshes/visual/robotiq_2f_85_base.stl + robotiq_2f_85_base_link: end_effectors/robotiq_2f_85/meshes/visual/robotiq_2f_85_base.stl stl_materials: robotiq_2f_85_left_inner_knuckle: Silver robotiq_2f_85_right_inner_knuckle: Silver "*": DarkGrey robotiq_2f_140: - source: robotiq_2f_140/robotiq_2f_140_movable_visual.urdf + source: end_effectors/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf base_link: robotiq_2f_140_base_link mount_joint: robotiq_2f_140_fix flange: xarm adapter: robotiq_mounting stl_visuals: - robotiq_2f_140_base_link: robotiq_2f_140/meshes/visual/robotiq_2f_140_base.stl + robotiq_2f_140_base_link: end_effectors/robotiq_2f_140/meshes/visual/robotiq_2f_140_base.stl stl_materials: robotiq_2f_140_left_inner_knuckle: Silver robotiq_2f_140_right_inner_knuckle: Silver "*": DarkGrey lite6_gripper: - source: lite6_gripper/lite6_gripper_movable_visual.urdf + source: end_effectors/lite6_gripper/lite6_gripper_movable_visual.urdf base_link: uflite_gripper_link mount_joint: gripper_fix flange: lite6 stl_materials: uflite_gripper_link: White lite6_vacuum_gripper: - source: lite6_vacuum_gripper/lite6_vacuum_gripper.urdf + source: end_effectors/lite6_vacuum_gripper/lite6_vacuum_gripper.urdf base_link: uflite_vacuum_gripper_link mount_joint: vacuum_gripper_fix flange: lite6 glb_visuals: - uflite_vacuum_gripper_link: lite6_vacuum_gripper/meshes/visual/lite6_vacuum_gripper_visual_link6.glb + uflite_vacuum_gripper_link: end_effectors/lite6_vacuum_gripper/meshes/visual/lite6_vacuum_gripper_visual_link6.glb adapters: robotiq_mounting: # UFACTORY 11 mm silver anodized aluminium xArm-to-Robotiq flange adapter (OD 75 mm, 109.7 g, Ø31.5 x 5.6 mm # centring boss). Fits xArm5/6/7 and UF850 (ISO 9409-1-50-4-M6 flange; not Lite 6) and adapts to Robotiq # 2F-85 / 2F-140 (4 x M4 at (+/-16, +/-27) mm, Ø4 mm locating pin at (0, -30.5) mm, Ø71 mm centring recess). - source: robotiq_mounting/robotiq_mounting.urdf + source: mounts/robotiq_mounting/robotiq_mounting.urdf base_link: robotiq_mounting mount_joint: robotiq_mounting_fix flange: xarm tool_lift_m: 0.011 stl_visuals: - robotiq_mounting: robotiq_mounting/meshes/visual/robotiq_mounting.stl + robotiq_mounting: mounts/robotiq_mounting/meshes/visual/robotiq_mounting.stl stl_materials: robotiq_mounting: AdapterAluminum +ft_sensors: + ft_sensor_ai1500: + # UFACTORY AI1500 six-axis force/torque sensor (0.6 kg, CoM [0, 0, 22] mm, +58.6 mm tool lift). + # Mounts onto the xArm/UF850 ISO 9409-1-50-4-M6 flange (not Lite 6); downstream camera stands, + # adapters, and end effectors stack on ft_sensor_ai1500_output. + source: accessories/ft_sensor_ai1500/ft_sensor_ai1500.urdf + base_link: ft_sensor_ai1500 + output_link: ft_sensor_ai1500_output + mount_joint: ft_sensor_ai1500_fix + flange: xarm + tool_lift_m: 0.0586 + stl_visuals: + ft_sensor_ai1500: accessories/ft_sensor_ai1500/meshes/visual/ft_sensor_ai1500.stl + stl_materials: + ft_sensor_ai1500: FtSensorAluminum spacers: camera_stand: # UFACTORY 3 mm aluminium camera stand, 48 g. Its frame has the plate thickness along +Y, so the mount turns # +Y onto flange +Z. Fits both xarm and lite6 (ISO 9409-1-50-4-M6 flange). Camera holes around (67.5, 3, 0) mm: # 2 x M3 at 20 mm and at 45 mm, and a 20 x 20 mm square of 4 x M3. Bio Gripper G2 is excluded: its body # reaches x = 59.22 mm and hits D405/D435. - source: camera_stand/camera_stand.urdf + source: mounts/camera_stand/camera_stand.urdf base_link: camera_stand mount_joint: camera_stand_fix flanges: [xarm, lite6] @@ -151,7 +171,7 @@ spacers: tool_lift_m: 0.003 end_effectors: [gripper_g2, vacuum_gripper, robotiq_2f_85, robotiq_2f_140, lite6_gripper, lite6_vacuum_gripper] stl_visuals: - camera_stand: camera_stand/meshes/visual/camera_stand.stl + camera_stand: mounts/camera_stand/meshes/visual/camera_stand.stl stl_materials: camera_stand: StandAluminum cameras: @@ -159,7 +179,7 @@ cameras: # camera looks along flange +Z with its top towards flange +X. d405: # Rear 2 x M3 at 20 mm. - source: d405/d405.urdf + source: cameras/d405/d405.urdf base_link: d405_body mount_joint: d405_fix spacer: camera_stand @@ -168,7 +188,7 @@ cameras: stl_materials: {"*": d405_housing} d435: # Rear 2 x M3 at 45 mm; 0.055 mm gap because the ROS mesh pokes 0.0547 mm past its nominal rear face. - source: d435/d435.urdf + source: cameras/d435/d435.urdf base_link: d435_body mount_joint: d435_fix spacer: camera_stand @@ -177,7 +197,7 @@ cameras: stl_materials: {"*": d435_housing} gemini_305: # Rear 2 x M3 at 20 mm. - source: gemini_305/gemini_305.urdf + source: cameras/gemini_305/gemini_305.urdf base_link: gemini_305_body mount_joint: gemini_305_fix spacer: camera_stand @@ -186,7 +206,7 @@ cameras: stl_materials: {"*": gemini_305_housing} zed_x_nano: # Rear 20 x 20 mm square of 4 x M3; the GMSL2 connector passes through the stand's centre opening. - source: zed_x_nano/zed_x_nano.urdf + source: cameras/zed_x_nano/zed_x_nano.urdf base_link: zed_x_nano_body mount_joint: zed_x_nano_fix spacer: camera_stand @@ -196,7 +216,7 @@ cameras: mounting_plates: xarm_mounting_plate: # UFACTORY 8 mm aluminium mounting plate (136 x 185 mm, long edge along Y, two-chamfered tongue facing +X). - source: xarm_mounting_plate/xarm_mounting_plate.urdf + source: mounts/xarm_mounting_plate/xarm_mounting_plate.urdf base_link: xarm_mounting_plate mount_joint: mounting_plate_fix robots: [xarm5_1305, xarm6_1305, xarm7_1305] @@ -205,7 +225,7 @@ mounting_plates: stl_materials: {"*": PlateAluminum} uf850_mounting_plate: # UFACTORY 10 mm aluminium mounting plate (190 x 260 mm, long edge along Y). - source: uf850_mounting_plate/uf850_mounting_plate.urdf + source: mounts/uf850_mounting_plate/uf850_mounting_plate.urdf base_link: uf850_mounting_plate mount_joint: mounting_plate_fix robots: [uf850] @@ -215,7 +235,7 @@ mounting_plates: lite6_mounting_plate: # UFACTORY 5 mm aluminium mounting plate (130 x 190 mm, long edge along Y). # Lite 6's four base mounting holes are centred at (-3, 0) mm in link_base. - source: lite6_mounting_plate/lite6_mounting_plate.urdf + source: mounts/lite6_mounting_plate/lite6_mounting_plate.urdf base_link: lite6_mounting_plate mount_joint: mounting_plate_fix robots: [lite6] diff --git a/assets/urdf/d405/LICENSE b/assets/urdf/cameras/d405/LICENSE similarity index 100% rename from assets/urdf/d405/LICENSE rename to assets/urdf/cameras/d405/LICENSE diff --git a/assets/urdf/d405/README.md b/assets/urdf/cameras/d405/README.md similarity index 89% rename from assets/urdf/d405/README.md rename to assets/urdf/cameras/d405/README.md index 1b4623b..3fa9cbc 100644 --- a/assets/urdf/d405/README.md +++ b/assets/urdf/cameras/d405/README.md @@ -1,6 +1,6 @@ # Intel RealSense D405 -Short-range stereo depth camera for the [camera stand](../camera_stand/README.md). Static part, no joints. +Short-range stereo depth camera for the [camera stand](../../mounts/camera_stand/README.md). Static part, no joints. ## Parameters @@ -36,5 +36,5 @@ python examples/visualization/view_robot.py --robot xarm6 --gripper-g2 --movable ## Source / License -- Mesh: [realsense-ros `d405.stl`](https://github.com/realsenseai/realsense-ros/tree/ros2-master/realsense2_description/meshes) (Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](../../../NOTICE)). +- Mesh: [realsense-ros `d405.stl`](https://github.com/realsenseai/realsense-ros/tree/ros2-master/realsense2_description/meshes) (Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](../../../../NOTICE)). - Mass and size: Intel RealSense D400 series datasheet. diff --git a/assets/urdf/d405/d405.urdf b/assets/urdf/cameras/d405/d405.urdf similarity index 100% rename from assets/urdf/d405/d405.urdf rename to assets/urdf/cameras/d405/d405.urdf diff --git a/assets/urdf/d405/meshes/visual/d405.glb b/assets/urdf/cameras/d405/meshes/visual/d405.glb similarity index 100% rename from assets/urdf/d405/meshes/visual/d405.glb rename to assets/urdf/cameras/d405/meshes/visual/d405.glb diff --git a/assets/urdf/d435/LICENSE b/assets/urdf/cameras/d435/LICENSE similarity index 100% rename from assets/urdf/d435/LICENSE rename to assets/urdf/cameras/d435/LICENSE diff --git a/assets/urdf/d435/README.md b/assets/urdf/cameras/d435/README.md similarity index 90% rename from assets/urdf/d435/README.md rename to assets/urdf/cameras/d435/README.md index bc373af..0312d88 100644 --- a/assets/urdf/d435/README.md +++ b/assets/urdf/cameras/d435/README.md @@ -1,6 +1,6 @@ # Intel RealSense D435 -Stereo depth camera for the [camera stand](../camera_stand/README.md). Static part, no joints. +Stereo depth camera for the [camera stand](../../mounts/camera_stand/README.md). Static part, no joints. ## Parameters @@ -36,5 +36,5 @@ python examples/visualization/view_robot.py --robot xarm6 --gripper-g2 --movable ## Source / License -- Mesh: [realsense-ros `d435.dae`](https://github.com/realsenseai/realsense-ros/tree/ros2-master/realsense2_description/meshes) (Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](../../../NOTICE)). +- Mesh: [realsense-ros `d435.dae`](https://github.com/realsenseai/realsense-ros/tree/ros2-master/realsense2_description/meshes) (Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](../../../../NOTICE)). - Mass and size: Intel RealSense D400 series datasheet. diff --git a/assets/urdf/d435/d435.urdf b/assets/urdf/cameras/d435/d435.urdf similarity index 100% rename from assets/urdf/d435/d435.urdf rename to assets/urdf/cameras/d435/d435.urdf diff --git a/assets/urdf/d435/meshes/visual/d435.glb b/assets/urdf/cameras/d435/meshes/visual/d435.glb similarity index 100% rename from assets/urdf/d435/meshes/visual/d435.glb rename to assets/urdf/cameras/d435/meshes/visual/d435.glb diff --git a/assets/urdf/gemini_305/README.md b/assets/urdf/cameras/gemini_305/README.md similarity index 93% rename from assets/urdf/gemini_305/README.md rename to assets/urdf/cameras/gemini_305/README.md index c26a975..7389ef9 100644 --- a/assets/urdf/gemini_305/README.md +++ b/assets/urdf/cameras/gemini_305/README.md @@ -1,6 +1,6 @@ # Orbbec Gemini 305 -Stereo depth camera for the [camera stand](../camera_stand/README.md). Static part, no joints. +Stereo depth camera for the [camera stand](../../mounts/camera_stand/README.md). Static part, no joints. ## Parameters diff --git a/assets/urdf/gemini_305/gemini_305.urdf b/assets/urdf/cameras/gemini_305/gemini_305.urdf similarity index 100% rename from assets/urdf/gemini_305/gemini_305.urdf rename to assets/urdf/cameras/gemini_305/gemini_305.urdf diff --git a/assets/urdf/gemini_305/meshes/visual/gemini_305.glb b/assets/urdf/cameras/gemini_305/meshes/visual/gemini_305.glb similarity index 100% rename from assets/urdf/gemini_305/meshes/visual/gemini_305.glb rename to assets/urdf/cameras/gemini_305/meshes/visual/gemini_305.glb diff --git a/assets/urdf/zed_x_nano/README.md b/assets/urdf/cameras/zed_x_nano/README.md similarity index 95% rename from assets/urdf/zed_x_nano/README.md rename to assets/urdf/cameras/zed_x_nano/README.md index 6e82dc9..d07a76e 100644 --- a/assets/urdf/zed_x_nano/README.md +++ b/assets/urdf/cameras/zed_x_nano/README.md @@ -1,6 +1,6 @@ # Stereolabs ZED X Nano -Stereo camera for the [camera stand](../camera_stand/README.md). Static part, no joints. +Stereo camera for the [camera stand](../../mounts/camera_stand/README.md). Static part, no joints. ## Parameters diff --git a/assets/urdf/zed_x_nano/meshes/visual/zed_x_nano.glb b/assets/urdf/cameras/zed_x_nano/meshes/visual/zed_x_nano.glb similarity index 100% rename from assets/urdf/zed_x_nano/meshes/visual/zed_x_nano.glb rename to assets/urdf/cameras/zed_x_nano/meshes/visual/zed_x_nano.glb diff --git a/assets/urdf/zed_x_nano/zed_x_nano.urdf b/assets/urdf/cameras/zed_x_nano/zed_x_nano.urdf similarity index 100% rename from assets/urdf/zed_x_nano/zed_x_nano.urdf rename to assets/urdf/cameras/zed_x_nano/zed_x_nano.urdf diff --git a/assets/urdf/bio_gripper_g2/README.md b/assets/urdf/end_effectors/bio_gripper_g2/README.md similarity index 93% rename from assets/urdf/bio_gripper_g2/README.md rename to assets/urdf/end_effectors/bio_gripper_g2/README.md index 3c20ff2..a4ddfb6 100644 --- a/assets/urdf/bio_gripper_g2/README.md +++ b/assets/urdf/end_effectors/bio_gripper_g2/README.md @@ -33,7 +33,7 @@ bio_gripper_g2/ ## Frames and mount - The part frame is not at the adapter. In `bio_gripper_g2_base_link` the adapter centre is at (−22.636, −0.956, −2.516) mm with rpy (0.031, 0.254, 0.360)°. Joints, TCP, inertials and hulls are defined in this frame; the mount compensates. -- Mount (`bio_gripper_g2.mount` in [`assembly.yaml`](../assembly.yaml), the same on every robot of the flange): xyz (22.642, 0.814, 2.516) mm, rpy (0, 0, −0.00628537) rad. It puts the adapter centre on the flange axis and the adapter face at z = 0, with the adapter's two M6 through-holes over the flange's 135°/225° holes (Ø50 mm PCD, < 0.04 mm off). +- Mount (`bio_gripper_g2.mount` in [`assembly.yaml`](../../assembly.yaml), the same on every robot of the flange): xyz (22.642, 0.814, 2.516) mm, rpy (0, 0, −0.00628537) rad. It puts the adapter centre on the flange axis and the adapter face at z = 0, with the adapter's two M6 through-holes over the flange's 135°/225° holes (Ø50 mm PCD, < 0.04 mm off). - Yaw only. The GLB is tilted 0.25° in the part frame, a placement artifact (two flat faces in contact cannot tilt). Compensating it would make TCP-down poses unreachable on xArm5 and near-singular on xArm6. The adapter-face edge therefore shows ±0.16 mm of unevenness. - In the flange frame: TCP (`bio_gripper_g2_tcp_link`) at (157.6, 0.0, 57.5) mm; grasp point (`GRASP_OFFSET_IN_BASE_LINK`) at (150.6, 0.0, 52.5) mm; visual fingertips 157.9 (right) / 158.5 (left) mm from the flange axis (CAD: 157.5 mm). - The vendor xarm_ros2 model has its origin at the adapter, but its fingers sit about 12 mm off the CAD (tips at 170.5 mm). This repository follows the CAD. @@ -65,7 +65,7 @@ Adapter frame: contact face at z = 0, +Z toward the housing; the plate is 5 mm t - The two M6 countersunk screws in the 135°/225° holes are removed; the real part has through-holes there. - The curved faces (rim, centre bore, the four M6 holes, the lugs with their holes and screws, the stepped pin hole at −90°) lie on their analytic shapes within 0.015 mm, with analytic normals. - The contact face and the plate top end at round hole rims. All other vertices are unchanged from the export. -- Checks: `test_bio_gripper_g2_adapter_circles_are_round`, `test_bio_gripper_g2_adapter_has_through_holes_not_screws`, `test_bio_gripper_g2_adapter_faces_stop_at_hole_rims`. History: [CHANGELOG](../../../CHANGELOG.md). +- Checks: `test_bio_gripper_g2_adapter_circles_are_round`, `test_bio_gripper_g2_adapter_has_through_holes_not_screws`, `test_bio_gripper_g2_adapter_faces_stop_at_hole_rims`. History: [CHANGELOG](../../../../CHANGELOG.md). ## Usage @@ -93,5 +93,5 @@ python examples/visualization/view_robot.py --robot xarm6 --bio-gripper-g2 --gri ## Source / License -- The vendor URDF and the meshes derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../NOTICE)). +- The vendor URDF and the meshes derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../../NOTICE)). - This repository maintains the part URDF, the mount, the collision hulls and the Draco-compressed GLBs. diff --git a/assets/urdf/bio_gripper_g2/bio_gripper_g2.urdf b/assets/urdf/end_effectors/bio_gripper_g2/bio_gripper_g2.urdf similarity index 100% rename from assets/urdf/bio_gripper_g2/bio_gripper_g2.urdf rename to assets/urdf/end_effectors/bio_gripper_g2/bio_gripper_g2.urdf diff --git a/assets/urdf/bio_gripper_g2/bio_gripper_g2_movable_visual.urdf b/assets/urdf/end_effectors/bio_gripper_g2/bio_gripper_g2_movable_visual.urdf similarity index 100% rename from assets/urdf/bio_gripper_g2/bio_gripper_g2_movable_visual.urdf rename to assets/urdf/end_effectors/bio_gripper_g2/bio_gripper_g2_movable_visual.urdf diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_base_link_convex_0.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_base_link_convex_0.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_base_link_convex_0.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_base_link_convex_0.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_0.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_0.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_0.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_0.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_1.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_1.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_1.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_1.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_2.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_2.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_2.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_2.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_3.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_3.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_3.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_3.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_4.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_4.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_4.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_left_finger_convex_4.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_0.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_0.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_0.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_0.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_1.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_1.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_1.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_1.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_2.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_2.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_2.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_2.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_3.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_3.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_3.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_3.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_4.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_4.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_4.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/collision/bio_gripper_g2_right_finger_convex_4.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/visual/bio_gripper_g2_left_finger.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/bio_gripper_g2_left_finger.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/visual/bio_gripper_g2_left_finger.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/bio_gripper_g2_left_finger.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/visual/bio_gripper_g2_link_base.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/bio_gripper_g2_link_base.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/visual/bio_gripper_g2_link_base.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/bio_gripper_g2_link_base.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/visual/bio_gripper_g2_right_finger.stl b/assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/bio_gripper_g2_right_finger.stl similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/visual/bio_gripper_g2_right_finger.stl rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/bio_gripper_g2_right_finger.stl diff --git a/assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_base.glb b/assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_base.glb similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_base.glb rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_base.glb diff --git a/assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_left_finger.glb b/assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_left_finger.glb similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_left_finger.glb rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_left_finger.glb diff --git a/assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_right_finger.glb b/assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_right_finger.glb similarity index 100% rename from assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_right_finger.glb rename to assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_right_finger.glb diff --git a/assets/urdf/gripper_g2/README.md b/assets/urdf/end_effectors/gripper_g2/README.md similarity index 96% rename from assets/urdf/gripper_g2/README.md rename to assets/urdf/end_effectors/gripper_g2/README.md index 42a50ff..d61816b 100644 --- a/assets/urdf/gripper_g2/README.md +++ b/assets/urdf/end_effectors/gripper_g2/README.md @@ -18,7 +18,7 @@ gripper_g2/ └── visual_glb/ # per-link GLBs: base, fingers, knuckles ``` -The GLBs are Draco-compressed, 0.21 MB in total (test budget < 1 MB). With `visual="stl"` the base shows `visual/base_link.stl` (`stl_visuals` in [`assembly.yaml`](../assembly.yaml)); the fingers and knuckles show their collision STLs. +The GLBs are Draco-compressed, 0.21 MB in total (test budget < 1 MB). With `visual="stl"` the base shows `visual/base_link.stl` (`stl_visuals` in [`assembly.yaml`](../../assembly.yaml)); the fingers and knuckles show their collision STLs. ## Model @@ -47,5 +47,5 @@ python examples/visualization/view_robot.py --robot xarm6 --gripper-g2 --gripper ## Source / License -- Meshes derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../NOTICE)). +- Meshes derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../../NOTICE)). - This repository maintains the part URDF, the flange-frame meshes and the Draco-compressed GLBs. diff --git a/assets/urdf/gripper_g2/gripper_g2_movable_visual.urdf b/assets/urdf/end_effectors/gripper_g2/gripper_g2_movable_visual.urdf similarity index 100% rename from assets/urdf/gripper_g2/gripper_g2_movable_visual.urdf rename to assets/urdf/end_effectors/gripper_g2/gripper_g2_movable_visual.urdf diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_00.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_00.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_00.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_00.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_01.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_01.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_01.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_01.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_02.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_02.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_02.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_02.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_03.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_03.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_03.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_03.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_04.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_04.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_04.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_04.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_05.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_05.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_05.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_05.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_06.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_06.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_06.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_06.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_07.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_07.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_07.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_07.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_08.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_08.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_08.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_08.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/base_link_col_09.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_09.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/base_link_col_09.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/base_link_col_09.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/left_finger.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/left_finger.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/left_finger.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/left_finger.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/left_inner_knuckle.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/left_inner_knuckle.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/left_inner_knuckle.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/left_inner_knuckle.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/left_outer_knuckle.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/left_outer_knuckle.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/left_outer_knuckle.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/left_outer_knuckle.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/right_finger.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/right_finger.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/right_finger.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/right_finger.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/right_inner_knuckle.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/right_inner_knuckle.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/right_inner_knuckle.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/right_inner_knuckle.stl diff --git a/assets/urdf/gripper_g2/meshes/collision/right_outer_knuckle.stl b/assets/urdf/end_effectors/gripper_g2/meshes/collision/right_outer_knuckle.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/collision/right_outer_knuckle.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/collision/right_outer_knuckle.stl diff --git a/assets/urdf/gripper_g2/meshes/visual/base_link.stl b/assets/urdf/end_effectors/gripper_g2/meshes/visual/base_link.stl similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/base_link.stl rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/base_link.stl diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/base.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/base.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/base.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/base.glb diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/left_finger.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/left_finger.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/left_finger.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/left_finger.glb diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/left_inner_knuckle.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/left_inner_knuckle.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/left_inner_knuckle.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/left_inner_knuckle.glb diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/left_outer_knuckle.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/left_outer_knuckle.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/left_outer_knuckle.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/left_outer_knuckle.glb diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/right_finger.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/right_finger.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/right_finger.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/right_finger.glb diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/right_inner_knuckle.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/right_inner_knuckle.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/right_inner_knuckle.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/right_inner_knuckle.glb diff --git a/assets/urdf/gripper_g2/meshes/visual/visual_glb/right_outer_knuckle.glb b/assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/right_outer_knuckle.glb similarity index 100% rename from assets/urdf/gripper_g2/meshes/visual/visual_glb/right_outer_knuckle.glb rename to assets/urdf/end_effectors/gripper_g2/meshes/visual/visual_glb/right_outer_knuckle.glb diff --git a/assets/urdf/lite6_gripper/README.md b/assets/urdf/end_effectors/lite6_gripper/README.md similarity index 98% rename from assets/urdf/lite6_gripper/README.md rename to assets/urdf/end_effectors/lite6_gripper/README.md index 115954c..627fa6d 100644 --- a/assets/urdf/lite6_gripper/README.md +++ b/assets/urdf/end_effectors/lite6_gripper/README.md @@ -39,5 +39,5 @@ python examples/visualization/view_robot.py --robot lite6 --lite6-gripper --grip ## Source / License -- Meshes derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../NOTICE)). +- Meshes derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../../NOTICE)). - This repository maintains the part URDF and the Draco-compressed GLBs. diff --git a/assets/urdf/lite6_gripper/lite6_gripper_movable_visual.urdf b/assets/urdf/end_effectors/lite6_gripper/lite6_gripper_movable_visual.urdf similarity index 100% rename from assets/urdf/lite6_gripper/lite6_gripper_movable_visual.urdf rename to assets/urdf/end_effectors/lite6_gripper/lite6_gripper_movable_visual.urdf diff --git a/assets/urdf/lite6_gripper/meshes/collision/finger1.stl b/assets/urdf/end_effectors/lite6_gripper/meshes/collision/finger1.stl similarity index 100% rename from assets/urdf/lite6_gripper/meshes/collision/finger1.stl rename to assets/urdf/end_effectors/lite6_gripper/meshes/collision/finger1.stl diff --git a/assets/urdf/lite6_gripper/meshes/collision/finger2.stl b/assets/urdf/end_effectors/lite6_gripper/meshes/collision/finger2.stl similarity index 100% rename from assets/urdf/lite6_gripper/meshes/collision/finger2.stl rename to assets/urdf/end_effectors/lite6_gripper/meshes/collision/finger2.stl diff --git a/assets/urdf/lite6_gripper/meshes/collision/shell.stl b/assets/urdf/end_effectors/lite6_gripper/meshes/collision/shell.stl similarity index 100% rename from assets/urdf/lite6_gripper/meshes/collision/shell.stl rename to assets/urdf/end_effectors/lite6_gripper/meshes/collision/shell.stl diff --git a/assets/urdf/lite6_gripper/meshes/visual/visual_glb/shell.glb b/assets/urdf/end_effectors/lite6_gripper/meshes/visual/visual_glb/shell.glb similarity index 100% rename from assets/urdf/lite6_gripper/meshes/visual/visual_glb/shell.glb rename to assets/urdf/end_effectors/lite6_gripper/meshes/visual/visual_glb/shell.glb diff --git a/assets/urdf/lite6_vacuum_gripper/README.md b/assets/urdf/end_effectors/lite6_vacuum_gripper/README.md similarity index 84% rename from assets/urdf/lite6_vacuum_gripper/README.md rename to assets/urdf/end_effectors/lite6_vacuum_gripper/README.md index b8c67e0..b7f4da9 100644 --- a/assets/urdf/lite6_vacuum_gripper/README.md +++ b/assets/urdf/end_effectors/lite6_vacuum_gripper/README.md @@ -14,7 +14,7 @@ lite6_vacuum_gripper/ ## Usage -`compose_robot_urdf("lite6", "lite6_vacuum_gripper")` replaces the STL visual with the GLB (`glb_visuals` in [`assembly.yaml`](../assembly.yaml)); `visual="stl"` keeps the STL. The collision mesh is always `vacuum_gripper_lite.stl`. +`compose_robot_urdf("lite6", "lite6_vacuum_gripper")` replaces the STL visual with the GLB (`glb_visuals` in [`assembly.yaml`](../../assembly.yaml)); `visual="stl"` keeps the STL. The collision mesh is always `vacuum_gripper_lite.stl`. ```bash python examples/visualization/view_tool.py --tool lite6_vacuum_gripper # standalone (GLB, flange up) @@ -23,5 +23,5 @@ python examples/visualization/view_robot.py --robot lite6 --lite6-vacuum-gripper ## Source / License -- URDF and STL come from upstream [xarm_ros2](https://github.com/xArm-Developer/xarm_ros2) (see [NOTICE](../../../NOTICE)). +- URDF and STL come from upstream [xarm_ros2](https://github.com/xArm-Developer/xarm_ros2) (see [NOTICE](../../../../NOTICE)). - This repository maintains the Draco-compressed GLB. diff --git a/assets/urdf/lite6_vacuum_gripper/lite6_vacuum_gripper.urdf b/assets/urdf/end_effectors/lite6_vacuum_gripper/lite6_vacuum_gripper.urdf similarity index 100% rename from assets/urdf/lite6_vacuum_gripper/lite6_vacuum_gripper.urdf rename to assets/urdf/end_effectors/lite6_vacuum_gripper/lite6_vacuum_gripper.urdf diff --git a/assets/urdf/lite6_vacuum_gripper/meshes/visual/lite6_vacuum_gripper_visual_link6.glb b/assets/urdf/end_effectors/lite6_vacuum_gripper/meshes/visual/lite6_vacuum_gripper_visual_link6.glb similarity index 100% rename from assets/urdf/lite6_vacuum_gripper/meshes/visual/lite6_vacuum_gripper_visual_link6.glb rename to assets/urdf/end_effectors/lite6_vacuum_gripper/meshes/visual/lite6_vacuum_gripper_visual_link6.glb diff --git a/assets/urdf/lite6_vacuum_gripper/meshes/visual/vacuum_gripper_lite.stl b/assets/urdf/end_effectors/lite6_vacuum_gripper/meshes/visual/vacuum_gripper_lite.stl similarity index 100% rename from assets/urdf/lite6_vacuum_gripper/meshes/visual/vacuum_gripper_lite.stl rename to assets/urdf/end_effectors/lite6_vacuum_gripper/meshes/visual/vacuum_gripper_lite.stl diff --git a/assets/urdf/robotiq_2f_140/LICENSE b/assets/urdf/end_effectors/robotiq_2f_140/LICENSE similarity index 100% rename from assets/urdf/robotiq_2f_140/LICENSE rename to assets/urdf/end_effectors/robotiq_2f_140/LICENSE diff --git a/assets/urdf/robotiq_2f_140/README.md b/assets/urdf/end_effectors/robotiq_2f_140/README.md similarity index 84% rename from assets/urdf/robotiq_2f_140/README.md rename to assets/urdf/end_effectors/robotiq_2f_140/README.md index 9702071..cb34473 100644 --- a/assets/urdf/robotiq_2f_140/README.md +++ b/assets/urdf/end_effectors/robotiq_2f_140/README.md @@ -19,4 +19,4 @@ This directory holds the standalone movable URDF, collision STL meshes, and visu - Master actuated joint: `robotiq_2f_140_drive_joint` (`0.003859` rad open at 140 mm gap to `0.766594` rad closed at 0 mm gap). - Five coupled mimic joints (`multiplier=1`, `offset=0`) drive the four-bar parallel finger linkage symmetrically. - `robotiq_2f_140_tcp_link` sits at `(0, 0, 0.234466)` m relative to `robotiq_2f_140_base_link` (base mounting face at `z = 0`). -- When composed onto `xarm5`/`xarm6`/`xarm7`/`uf850` via `assets/urdf/assembly.yaml`, the 11 mm [`robotiq_mounting`](../robotiq_mounting/README.md) flange adapter is inserted automatically (not supported on `lite6`), placing `robotiq_2f_140_tcp_link` at `245.466 mm` from the arm flange (`248.466 mm` with the 3 mm `camera_stand`). +- When composed onto `xarm5`/`xarm6`/`xarm7`/`uf850` via `assets/urdf/assembly.yaml`, the 11 mm [`robotiq_mounting`](../../mounts/robotiq_mounting/README.md) flange adapter is inserted automatically (not supported on `lite6`), placing `robotiq_2f_140_tcp_link` at `245.466 mm` from the arm flange (`248.466 mm` with the 3 mm `camera_stand`). diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_base_col_00.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_base_col_00.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_base_col_00.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_base_col_00.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_body.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_body.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_body.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_body.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_pad.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_pad.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_pad.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_finger_pad.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_inner_knuckle.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_inner_knuckle.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_inner_knuckle.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_inner_knuckle.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_finger_col_1.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_finger_col_1.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_finger_col_1.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_finger_col_1.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_knuckle_col_0.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_knuckle_col_0.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_knuckle_col_0.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_left_outer_knuckle_col_0.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_body.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_body.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_body.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_body.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_pad.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_pad.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_pad.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_finger_pad.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_inner_knuckle.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_inner_knuckle.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_inner_knuckle.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_inner_knuckle.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_finger_col_1.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_finger_col_1.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_finger_col_1.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_finger_col_1.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_knuckle_col_0.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_knuckle_col_0.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_knuckle_col_0.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/collision/robotiq_2f_140_right_outer_knuckle_col_0.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/robotiq_2f_140_base.stl b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/robotiq_2f_140_base.stl similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/robotiq_2f_140_base.stl rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/robotiq_2f_140_base.stl diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/base.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/base.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/base.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/base.glb diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/left_finger.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/left_finger.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/left_finger.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/left_finger.glb diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/left_inner_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/left_inner_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/left_inner_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/left_inner_knuckle.glb diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/left_outer_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/left_outer_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/left_outer_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/left_outer_knuckle.glb diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/right_finger.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/right_finger.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/right_finger.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/right_finger.glb diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/right_inner_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/right_inner_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/right_inner_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/right_inner_knuckle.glb diff --git a/assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/right_outer_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/right_outer_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_140/meshes/visual/visual_glb/right_outer_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_140/meshes/visual/visual_glb/right_outer_knuckle.glb diff --git a/assets/urdf/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf b/assets/urdf/end_effectors/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf similarity index 100% rename from assets/urdf/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf rename to assets/urdf/end_effectors/robotiq_2f_140/robotiq_2f_140_movable_visual.urdf diff --git a/assets/urdf/robotiq_2f_85/LICENSE b/assets/urdf/end_effectors/robotiq_2f_85/LICENSE similarity index 100% rename from assets/urdf/robotiq_2f_85/LICENSE rename to assets/urdf/end_effectors/robotiq_2f_85/LICENSE diff --git a/assets/urdf/robotiq_2f_85/README.md b/assets/urdf/end_effectors/robotiq_2f_85/README.md similarity index 84% rename from assets/urdf/robotiq_2f_85/README.md rename to assets/urdf/end_effectors/robotiq_2f_85/README.md index cd22c49..2ae2ac6 100644 --- a/assets/urdf/robotiq_2f_85/README.md +++ b/assets/urdf/end_effectors/robotiq_2f_85/README.md @@ -19,4 +19,4 @@ This directory holds the standalone movable URDF, collision STL meshes, and visu - Master actuated joint: `robotiq_2f_85_drive_joint` (`0.0` rad open at 85 mm gap to `0.801433` rad closed at 0 mm gap). - Five coupled mimic joints (`multiplier=1`, `offset=0`) drive the four-bar parallel finger linkage symmetrically. - `robotiq_2f_85_tcp_link` sits at `(0, 0, 0.162253)` m relative to `robotiq_2f_85_base_link` (base mounting face at `z = 0`). -- When composed onto `xarm5`/`xarm6`/`xarm7`/`uf850` via `assets/urdf/assembly.yaml`, the 11 mm [`robotiq_mounting`](../robotiq_mounting/README.md) flange adapter is inserted automatically (not supported on `lite6`), placing `robotiq_2f_85_tcp_link` at `173.253 mm` from the arm flange (`176.253 mm` with the 3 mm `camera_stand`). +- When composed onto `xarm5`/`xarm6`/`xarm7`/`uf850` via `assets/urdf/assembly.yaml`, the 11 mm [`robotiq_mounting`](../../mounts/robotiq_mounting/README.md) flange adapter is inserted automatically (not supported on `lite6`), placing `robotiq_2f_85_tcp_link` at `173.253 mm` from the arm flange (`176.253 mm` with the 3 mm `camera_stand`). diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_base_col_00.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_base_col_00.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_base_col_00.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_base_col_00.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_body.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_body.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_body.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_body.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_pad.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_pad.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_pad.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_finger_pad.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_inner_knuckle.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_inner_knuckle.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_inner_knuckle.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_inner_knuckle.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_finger_col_1.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_finger_col_1.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_finger_col_1.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_finger_col_1.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_knuckle_col_0.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_knuckle_col_0.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_knuckle_col_0.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_left_outer_knuckle_col_0.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_body.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_body.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_body.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_body.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_pad.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_pad.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_pad.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_finger_pad.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_inner_knuckle.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_inner_knuckle.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_inner_knuckle.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_inner_knuckle.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_finger_col_1.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_finger_col_1.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_finger_col_1.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_finger_col_1.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_knuckle_col_0.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_knuckle_col_0.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_knuckle_col_0.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/collision/robotiq_2f_85_right_outer_knuckle_col_0.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/robotiq_2f_85_base.stl b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/robotiq_2f_85_base.stl similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/robotiq_2f_85_base.stl rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/robotiq_2f_85_base.stl diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/base.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/base.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/base.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/base.glb diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/left_finger.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/left_finger.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/left_finger.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/left_finger.glb diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/left_inner_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/left_inner_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/left_inner_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/left_inner_knuckle.glb diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/left_outer_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/left_outer_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/left_outer_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/left_outer_knuckle.glb diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/right_finger.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/right_finger.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/right_finger.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/right_finger.glb diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/right_inner_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/right_inner_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/right_inner_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/right_inner_knuckle.glb diff --git a/assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/right_outer_knuckle.glb b/assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/right_outer_knuckle.glb similarity index 100% rename from assets/urdf/robotiq_2f_85/meshes/visual/visual_glb/right_outer_knuckle.glb rename to assets/urdf/end_effectors/robotiq_2f_85/meshes/visual/visual_glb/right_outer_knuckle.glb diff --git a/assets/urdf/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf b/assets/urdf/end_effectors/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf similarity index 100% rename from assets/urdf/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf rename to assets/urdf/end_effectors/robotiq_2f_85/robotiq_2f_85_movable_visual.urdf diff --git a/assets/urdf/vacuum_gripper/README.md b/assets/urdf/end_effectors/vacuum_gripper/README.md similarity index 98% rename from assets/urdf/vacuum_gripper/README.md rename to assets/urdf/end_effectors/vacuum_gripper/README.md index 1740713..08b5439 100644 --- a/assets/urdf/vacuum_gripper/README.md +++ b/assets/urdf/end_effectors/vacuum_gripper/README.md @@ -44,5 +44,5 @@ python examples/visualization/view_robot.py --robot uf850 --vacuum-gripper ## Source / License -- URDF parameters and STL come from upstream [xArm-Developer/xarm_ros2](https://github.com/xArm-Developer/xarm_ros2) (BSD-3-Clause; see [NOTICE](../../../NOTICE)). +- URDF parameters and STL come from upstream [xArm-Developer/xarm_ros2](https://github.com/xArm-Developer/xarm_ros2) (BSD-3-Clause; see [NOTICE](../../../../NOTICE)). - This repository maintains the Draco-compressed GLB and the 33 collision hulls. diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_000_flange.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_000_flange.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_000_flange.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_000_flange.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_001_body.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_001_body.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_001_body.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_001_body.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_002_body.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_002_body.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_002_body.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_002_body.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_003_body.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_003_body.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_003_body.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_003_body.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_004_body.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_004_body.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_004_body.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_004_body.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_005_body.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_005_body.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_005_body.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_005_body.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_006_body.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_006_body.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_006_body.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_006_body.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_007_cover.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_007_cover.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_007_cover.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_007_cover.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_008_cup_01.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_008_cup_01.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_008_cup_01.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_008_cup_01.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_009_cup_01.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_009_cup_01.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_009_cup_01.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_009_cup_01.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_010_cup_01.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_010_cup_01.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_010_cup_01.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_010_cup_01.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_011_cup_01.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_011_cup_01.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_011_cup_01.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_011_cup_01.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_012_cup_01.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_012_cup_01.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_012_cup_01.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_012_cup_01.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_013_cup_02.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_013_cup_02.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_013_cup_02.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_013_cup_02.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_014_cup_02.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_014_cup_02.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_014_cup_02.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_014_cup_02.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_015_cup_02.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_015_cup_02.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_015_cup_02.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_015_cup_02.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_016_cup_02.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_016_cup_02.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_016_cup_02.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_016_cup_02.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_017_cup_02.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_017_cup_02.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_017_cup_02.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_017_cup_02.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_018_cup_03.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_018_cup_03.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_018_cup_03.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_018_cup_03.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_019_cup_03.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_019_cup_03.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_019_cup_03.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_019_cup_03.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_020_cup_03.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_020_cup_03.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_020_cup_03.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_020_cup_03.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_021_cup_03.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_021_cup_03.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_021_cup_03.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_021_cup_03.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_022_cup_03.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_022_cup_03.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_022_cup_03.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_022_cup_03.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_023_cup_04.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_023_cup_04.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_023_cup_04.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_023_cup_04.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_024_cup_04.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_024_cup_04.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_024_cup_04.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_024_cup_04.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_025_cup_04.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_025_cup_04.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_025_cup_04.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_025_cup_04.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_026_cup_04.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_026_cup_04.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_026_cup_04.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_026_cup_04.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_027_cup_04.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_027_cup_04.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_027_cup_04.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_027_cup_04.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_028_cup_05.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_028_cup_05.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_028_cup_05.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_028_cup_05.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_029_cup_05.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_029_cup_05.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_029_cup_05.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_029_cup_05.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_030_cup_05.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_030_cup_05.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_030_cup_05.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_030_cup_05.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_031_cup_05.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_031_cup_05.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_031_cup_05.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_031_cup_05.stl diff --git a/assets/urdf/vacuum_gripper/meshes/collision/convex/hull_032_cup_05.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_032_cup_05.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/collision/convex/hull_032_cup_05.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/collision/convex/hull_032_cup_05.stl diff --git a/assets/urdf/vacuum_gripper/meshes/visual/vacuum_gripper.glb b/assets/urdf/end_effectors/vacuum_gripper/meshes/visual/vacuum_gripper.glb similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/visual/vacuum_gripper.glb rename to assets/urdf/end_effectors/vacuum_gripper/meshes/visual/vacuum_gripper.glb diff --git a/assets/urdf/vacuum_gripper/meshes/visual/vacuum_gripper_visual.stl b/assets/urdf/end_effectors/vacuum_gripper/meshes/visual/vacuum_gripper_visual.stl similarity index 100% rename from assets/urdf/vacuum_gripper/meshes/visual/vacuum_gripper_visual.stl rename to assets/urdf/end_effectors/vacuum_gripper/meshes/visual/vacuum_gripper_visual.stl diff --git a/assets/urdf/vacuum_gripper/vacuum_gripper.urdf b/assets/urdf/end_effectors/vacuum_gripper/vacuum_gripper.urdf similarity index 100% rename from assets/urdf/vacuum_gripper/vacuum_gripper.urdf rename to assets/urdf/end_effectors/vacuum_gripper/vacuum_gripper.urdf diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link6_col_00.stl b/assets/urdf/lite6/meshes/lite6/collision/lite6_link6_col_00.stl deleted file mode 100644 index 15c6086..0000000 Binary files a/assets/urdf/lite6/meshes/lite6/collision/lite6_link6_col_00.stl and /dev/null differ diff --git a/assets/urdf/camera_stand/README.md b/assets/urdf/mounts/camera_stand/README.md similarity index 93% rename from assets/urdf/camera_stand/README.md rename to assets/urdf/mounts/camera_stand/README.md index eee6e5d..354acf9 100644 --- a/assets/urdf/camera_stand/README.md +++ b/assets/urdf/mounts/camera_stand/README.md @@ -1,6 +1,6 @@ # Camera Stand -UFACTORY 3 mm aluminium camera stand. It is clamped between the ISO 9409-1-50-4-M6 tool flange (xArm5/6/7, UF850, Lite 6) and the end effector, and carries one camera: [D405](../d405/README.md), [D435](../d435/README.md), [Gemini 305](../gemini_305/README.md) or [ZED X Nano](../zed_x_nano/README.md). Static part, no joints. +UFACTORY 3 mm aluminium camera stand. It is clamped between the ISO 9409-1-50-4-M6 tool flange (xArm5/6/7, UF850, Lite 6) and the end effector, and carries one camera: [D405](../../cameras/d405/README.md), [D435](../../cameras/d435/README.md), [Gemini 305](../../cameras/gemini_305/README.md) or [ZED X Nano](../../cameras/zed_x_nano/README.md). Static part, no joints. ## Parameters diff --git a/assets/urdf/camera_stand/camera_stand.urdf b/assets/urdf/mounts/camera_stand/camera_stand.urdf similarity index 100% rename from assets/urdf/camera_stand/camera_stand.urdf rename to assets/urdf/mounts/camera_stand/camera_stand.urdf diff --git a/assets/urdf/camera_stand/meshes/collision/piece_000.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_000.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_000.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_000.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_001.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_001.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_001.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_001.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_002.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_002.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_002.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_002.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_003.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_003.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_003.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_003.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_004.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_004.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_004.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_004.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_005.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_005.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_005.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_005.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_006.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_006.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_006.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_006.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_007.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_007.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_007.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_007.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_008.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_008.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_008.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_008.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_009.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_009.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_009.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_009.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_010.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_010.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_010.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_010.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_011.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_011.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_011.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_011.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_012.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_012.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_012.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_012.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_013.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_013.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_013.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_013.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_014.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_014.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_014.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_014.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_015.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_015.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_015.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_015.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_016.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_016.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_016.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_016.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_017.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_017.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_017.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_017.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_018.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_018.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_018.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_018.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_019.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_019.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_019.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_019.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_020.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_020.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_020.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_020.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_021.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_021.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_021.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_021.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_022.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_022.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_022.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_022.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_023.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_023.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_023.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_023.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_024.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_024.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_024.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_024.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_025.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_025.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_025.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_025.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_026.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_026.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_026.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_026.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_027.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_027.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_027.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_027.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_028.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_028.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_028.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_028.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_029.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_029.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_029.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_029.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_030.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_030.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_030.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_030.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_031.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_031.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_031.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_031.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_032.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_032.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_032.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_032.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_033.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_033.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_033.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_033.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_034.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_034.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_034.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_034.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_035.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_035.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_035.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_035.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_036.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_036.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_036.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_036.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_037.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_037.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_037.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_037.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_038.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_038.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_038.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_038.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_039.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_039.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_039.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_039.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_040.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_040.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_040.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_040.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_041.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_041.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_041.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_041.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_042.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_042.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_042.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_042.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_043.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_043.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_043.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_043.stl diff --git a/assets/urdf/camera_stand/meshes/collision/piece_044.stl b/assets/urdf/mounts/camera_stand/meshes/collision/piece_044.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/collision/piece_044.stl rename to assets/urdf/mounts/camera_stand/meshes/collision/piece_044.stl diff --git a/assets/urdf/camera_stand/meshes/visual/camera_stand.glb b/assets/urdf/mounts/camera_stand/meshes/visual/camera_stand.glb similarity index 100% rename from assets/urdf/camera_stand/meshes/visual/camera_stand.glb rename to assets/urdf/mounts/camera_stand/meshes/visual/camera_stand.glb diff --git a/assets/urdf/camera_stand/meshes/visual/camera_stand.stl b/assets/urdf/mounts/camera_stand/meshes/visual/camera_stand.stl similarity index 100% rename from assets/urdf/camera_stand/meshes/visual/camera_stand.stl rename to assets/urdf/mounts/camera_stand/meshes/visual/camera_stand.stl diff --git a/assets/urdf/lite6_mounting_plate/README.md b/assets/urdf/mounts/lite6_mounting_plate/README.md similarity index 100% rename from assets/urdf/lite6_mounting_plate/README.md rename to assets/urdf/mounts/lite6_mounting_plate/README.md diff --git a/assets/urdf/lite6_mounting_plate/lite6_mounting_plate.urdf b/assets/urdf/mounts/lite6_mounting_plate/lite6_mounting_plate.urdf similarity index 98% rename from assets/urdf/lite6_mounting_plate/lite6_mounting_plate.urdf rename to assets/urdf/mounts/lite6_mounting_plate/lite6_mounting_plate.urdf index c68bf27..185fb25 100644 --- a/assets/urdf/lite6_mounting_plate/lite6_mounting_plate.urdf +++ b/assets/urdf/mounts/lite6_mounting_plate/lite6_mounting_plate.urdf @@ -2,7 +2,7 @@ - + diff --git a/assets/urdf/lite6_mounting_plate/meshes/collision/lite6_mounting_plate_col_00.stl b/assets/urdf/mounts/lite6_mounting_plate/meshes/collision/lite6_mounting_plate_col_00.stl similarity index 100% rename from assets/urdf/lite6_mounting_plate/meshes/collision/lite6_mounting_plate_col_00.stl rename to assets/urdf/mounts/lite6_mounting_plate/meshes/collision/lite6_mounting_plate_col_00.stl diff --git a/assets/urdf/lite6_mounting_plate/meshes/visual/lite6_mounting_plate.glb b/assets/urdf/mounts/lite6_mounting_plate/meshes/visual/lite6_mounting_plate.glb similarity index 98% rename from assets/urdf/lite6_mounting_plate/meshes/visual/lite6_mounting_plate.glb rename to assets/urdf/mounts/lite6_mounting_plate/meshes/visual/lite6_mounting_plate.glb index 2012568..094623a 100644 Binary files a/assets/urdf/lite6_mounting_plate/meshes/visual/lite6_mounting_plate.glb and b/assets/urdf/mounts/lite6_mounting_plate/meshes/visual/lite6_mounting_plate.glb differ diff --git a/assets/urdf/robotiq_mounting/README.md b/assets/urdf/mounts/robotiq_mounting/README.md similarity index 91% rename from assets/urdf/robotiq_mounting/README.md rename to assets/urdf/mounts/robotiq_mounting/README.md index 9e283af..c1e879f 100644 --- a/assets/urdf/robotiq_mounting/README.md +++ b/assets/urdf/mounts/robotiq_mounting/README.md @@ -6,8 +6,8 @@ UFACTORY 11 mm silver anodized aluminium coupling adapter for mounting **Robotiq Frame: `robotiq_mounting`, origin at the flange centre on the xArm/UF850 mating plane (`z = 0`), with `+Z` pointing toward the Robotiq gripper. -- Estimated mass `0.1097 kg` (exact B-Rep volume `40.638 cm³` × uniform 6061 aluminium density `2700 kg/m³`); centre of mass at `(0.00, -0.80, 4.46) mm`. -- Inertia at the centre of mass (kg·m²): `ixx = 4.1165e-5`, `iyy = 4.6473e-5`, `izz = 8.3857e-5`, `ixy = 0`, `ixz = 0`, `iyz = 6.7024e-8`. +- Measured mass `0.118 kg` (uniformly scaled over the exact B-Rep volume `40.638 cm³`, effective density `2903.72 kg/m³`); centre of mass at `(0.00, -0.80, 4.46) mm`. +- Inertia at the centre of mass (kg·m²): `ixx = 4.4271e-5`, `iyy = 4.9980e-5`, `izz = 9.0184e-5`, `ixy = 0`, `ixz = 0`, `iyz = 7.2081e-8`. - Envelope: outer diameter `Ø75.0 mm` (`x, y ∈ [-37.5, +37.5] mm`), axial extent `z ∈ [-5.6, +13.9] mm`. - **xArm / UF850 side (`z = 0`)**: `Ø31.5 × 5.6 mm` centring boss (`z ∈ [-5.6, 0.0] mm`, fits inside the 6 mm arm flange recess and passes through the 3 mm `camera_stand` `Ø34.5 mm` centre bore), 4 × M6 counterbored bolt holes on PCD 50 mm at `(±17.68, ±17.68) mm` (`robotiq_mounting_xarm_hole_0..3`), `Ø6.0 mm` locating-pin hole at `(0, -25.0) mm` (`robotiq_mounting_xarm_pin`), and tool Pogo-Pin pass-through slot at `(0, +23.0) mm`. - **Robotiq side (`z = +11.0 mm`)**: flat seating plane at `z = +11.0 mm` (`robotiq_mounting_tool_mount`) surrounded by a `Ø71.0 mm` inner / `Ø75.0 mm` outer centring rim (`z ∈ [+11.0, +13.9] mm`), 4 × M4 clearance through-holes at `(±16.0, ±27.0) mm` (`robotiq_mounting_robotiq_hole_0..3`), and a `Ø4.0 mm` blind locating-pin hole at `(0, -30.5) mm` (`robotiq_mounting_robotiq_pin`). diff --git a/assets/urdf/robotiq_mounting/meshes/collision/robotiq_mounting_col_00.stl b/assets/urdf/mounts/robotiq_mounting/meshes/collision/robotiq_mounting_col_00.stl similarity index 100% rename from assets/urdf/robotiq_mounting/meshes/collision/robotiq_mounting_col_00.stl rename to assets/urdf/mounts/robotiq_mounting/meshes/collision/robotiq_mounting_col_00.stl diff --git a/assets/urdf/robotiq_mounting/meshes/collision/robotiq_mounting_col_01.stl b/assets/urdf/mounts/robotiq_mounting/meshes/collision/robotiq_mounting_col_01.stl similarity index 100% rename from assets/urdf/robotiq_mounting/meshes/collision/robotiq_mounting_col_01.stl rename to assets/urdf/mounts/robotiq_mounting/meshes/collision/robotiq_mounting_col_01.stl diff --git a/assets/urdf/robotiq_mounting/meshes/visual/robotiq_mounting.glb b/assets/urdf/mounts/robotiq_mounting/meshes/visual/robotiq_mounting.glb similarity index 100% rename from assets/urdf/robotiq_mounting/meshes/visual/robotiq_mounting.glb rename to assets/urdf/mounts/robotiq_mounting/meshes/visual/robotiq_mounting.glb diff --git a/assets/urdf/robotiq_mounting/meshes/visual/robotiq_mounting.stl b/assets/urdf/mounts/robotiq_mounting/meshes/visual/robotiq_mounting.stl similarity index 100% rename from assets/urdf/robotiq_mounting/meshes/visual/robotiq_mounting.stl rename to assets/urdf/mounts/robotiq_mounting/meshes/visual/robotiq_mounting.stl diff --git a/assets/urdf/robotiq_mounting/robotiq_mounting.urdf b/assets/urdf/mounts/robotiq_mounting/robotiq_mounting.urdf similarity index 96% rename from assets/urdf/robotiq_mounting/robotiq_mounting.urdf rename to assets/urdf/mounts/robotiq_mounting/robotiq_mounting.urdf index da1dec0..32ef131 100644 --- a/assets/urdf/robotiq_mounting/robotiq_mounting.urdf +++ b/assets/urdf/mounts/robotiq_mounting/robotiq_mounting.urdf @@ -13,8 +13,8 @@ - - + + diff --git a/assets/urdf/uf850_mounting_plate/README.md b/assets/urdf/mounts/uf850_mounting_plate/README.md similarity index 84% rename from assets/urdf/uf850_mounting_plate/README.md rename to assets/urdf/mounts/uf850_mounting_plate/README.md index a0844e0..d3c7c79 100644 --- a/assets/urdf/uf850_mounting_plate/README.md +++ b/assets/urdf/mounts/uf850_mounting_plate/README.md @@ -6,8 +6,8 @@ Official UFACTORY 10 mm aluminium mounting plate for **UF850**. Static part, no Frame: `uf850_mounting_plate`, origin at the centre of the Ø130 mm central bore on the top mounting plane (`z = 0`). The plate spans `z ∈ [-10, 0] mm`, with its long edge parallel to `Y`. The runtime composer attaches it below `link_base` at `xyz = (0, 0, 0)` with `mounting_plate_fix`. -- Estimated mass `0.9142 kg` (uniform 6061 aluminium density `2700 kg/m³` integrated over the watertight CAD mesh; fixed-base arm dynamics are unaffected); centre of mass at `(0.00, 0.00, -5.00) mm`. -- Inertia at the centre of mass (kg·m²): `ixx = 6.4877e-3`, `iyy = 3.2775e-3`, `izz = 9.7500e-3`, `ixy = 2.45e-9`, `ixz = 7.71e-11`, `iyz = -1.87e-11`. +- Measured mass `1.056 kg` (uniformly scaled over the watertight CAD mesh volume `338.578 cm³`, effective density `3118.92 kg/m³`; fixed-base arm dynamics are unaffected); centre of mass at `(0.00, 0.00, -5.00) mm`. +- Inertia at the centre of mass (kg·m²): `ixx = 7.4944e-3`, `iyy = 3.7860e-3`, `izz = 1.1263e-2`, `ixy = 2.83e-9`, `ixz = 8.91e-11`, `iyz = -2.16e-11`. - Envelope `190 × 260 × 10 mm`: `x ∈ [-95.0, +95.0] mm`, `y ∈ [-130.0, +130.0] mm`, `z ∈ [-10.0, 0.0] mm` (corner radius 20 mm). - Features: Ø130 mm central through-bore, 4 × Ø6.8 mm arm mounting holes at `(±60.104, ±60.104) mm` (`uf850_mounting_plate_hole_0..3`), and 8 outer mounting slots (`(±70, ±115)` mm and `(±80, ±85)` mm). - Fits: `uf850` (bare arm or any compatible end effector / camera assembly). diff --git a/assets/urdf/uf850_mounting_plate/meshes/collision/uf850_mounting_plate_col_00.stl b/assets/urdf/mounts/uf850_mounting_plate/meshes/collision/uf850_mounting_plate_col_00.stl similarity index 100% rename from assets/urdf/uf850_mounting_plate/meshes/collision/uf850_mounting_plate_col_00.stl rename to assets/urdf/mounts/uf850_mounting_plate/meshes/collision/uf850_mounting_plate_col_00.stl diff --git a/assets/urdf/uf850_mounting_plate/meshes/visual/uf850_mounting_plate.glb b/assets/urdf/mounts/uf850_mounting_plate/meshes/visual/uf850_mounting_plate.glb similarity index 99% rename from assets/urdf/uf850_mounting_plate/meshes/visual/uf850_mounting_plate.glb rename to assets/urdf/mounts/uf850_mounting_plate/meshes/visual/uf850_mounting_plate.glb index 22a89c6..80e320e 100644 Binary files a/assets/urdf/uf850_mounting_plate/meshes/visual/uf850_mounting_plate.glb and b/assets/urdf/mounts/uf850_mounting_plate/meshes/visual/uf850_mounting_plate.glb differ diff --git a/assets/urdf/uf850_mounting_plate/uf850_mounting_plate.urdf b/assets/urdf/mounts/uf850_mounting_plate/uf850_mounting_plate.urdf similarity index 91% rename from assets/urdf/uf850_mounting_plate/uf850_mounting_plate.urdf rename to assets/urdf/mounts/uf850_mounting_plate/uf850_mounting_plate.urdf index 35afe3e..993dcfa 100644 --- a/assets/urdf/uf850_mounting_plate/uf850_mounting_plate.urdf +++ b/assets/urdf/mounts/uf850_mounting_plate/uf850_mounting_plate.urdf @@ -2,7 +2,7 @@ - + @@ -13,8 +13,8 @@ - - + + diff --git a/assets/urdf/xarm_mounting_plate/README.md b/assets/urdf/mounts/xarm_mounting_plate/README.md similarity index 100% rename from assets/urdf/xarm_mounting_plate/README.md rename to assets/urdf/mounts/xarm_mounting_plate/README.md diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_00.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_00.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_00.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_00.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_01.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_01.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_01.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_01.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_02.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_02.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_02.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_02.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_03.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_03.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_03.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_03.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_04.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_04.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_04.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_04.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_05.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_05.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_05.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_05.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_06.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_06.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_06.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_06.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_07.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_07.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_07.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_07.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_08.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_08.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_08.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_08.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_09.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_09.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_09.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_09.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_10.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_10.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_10.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_10.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_11.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_11.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_11.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_11.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_12.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_12.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_12.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_12.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_13.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_13.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_13.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_13.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_14.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_14.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_14.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_14.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_15.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_15.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_15.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_15.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_16.stl b/assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_16.stl similarity index 100% rename from assets/urdf/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_16.stl rename to assets/urdf/mounts/xarm_mounting_plate/meshes/collision/xarm_mounting_plate_col_16.stl diff --git a/assets/urdf/xarm_mounting_plate/meshes/visual/xarm_mounting_plate.glb b/assets/urdf/mounts/xarm_mounting_plate/meshes/visual/xarm_mounting_plate.glb similarity index 99% rename from assets/urdf/xarm_mounting_plate/meshes/visual/xarm_mounting_plate.glb rename to assets/urdf/mounts/xarm_mounting_plate/meshes/visual/xarm_mounting_plate.glb index 45f45da..8d13b85 100644 Binary files a/assets/urdf/xarm_mounting_plate/meshes/visual/xarm_mounting_plate.glb and b/assets/urdf/mounts/xarm_mounting_plate/meshes/visual/xarm_mounting_plate.glb differ diff --git a/assets/urdf/xarm_mounting_plate/xarm_mounting_plate.urdf b/assets/urdf/mounts/xarm_mounting_plate/xarm_mounting_plate.urdf similarity index 99% rename from assets/urdf/xarm_mounting_plate/xarm_mounting_plate.urdf rename to assets/urdf/mounts/xarm_mounting_plate/xarm_mounting_plate.urdf index ece1c31..b262b9d 100644 --- a/assets/urdf/xarm_mounting_plate/xarm_mounting_plate.urdf +++ b/assets/urdf/mounts/xarm_mounting_plate/xarm_mounting_plate.urdf @@ -2,7 +2,7 @@ - + diff --git a/assets/urdf/microplate/LICENSE.txt b/assets/urdf/objects/microplate/LICENSE.txt similarity index 100% rename from assets/urdf/microplate/LICENSE.txt rename to assets/urdf/objects/microplate/LICENSE.txt diff --git a/assets/urdf/microplate/README.md b/assets/urdf/objects/microplate/README.md similarity index 100% rename from assets/urdf/microplate/README.md rename to assets/urdf/objects/microplate/README.md diff --git a/assets/urdf/microplate/SBS_96_well_plate.json b/assets/urdf/objects/microplate/SBS_96_well_plate.json similarity index 100% rename from assets/urdf/microplate/SBS_96_well_plate.json rename to assets/urdf/objects/microplate/SBS_96_well_plate.json diff --git a/assets/urdf/microplate/manifest.json b/assets/urdf/objects/microplate/manifest.json similarity index 100% rename from assets/urdf/microplate/manifest.json rename to assets/urdf/objects/microplate/manifest.json diff --git a/assets/urdf/microplate/sbs_96_well.glb b/assets/urdf/objects/microplate/sbs_96_well.glb similarity index 100% rename from assets/urdf/microplate/sbs_96_well.glb rename to assets/urdf/objects/microplate/sbs_96_well.glb diff --git a/assets/urdf/microplate/sbs_96_well.urdf b/assets/urdf/objects/microplate/sbs_96_well.urdf similarity index 100% rename from assets/urdf/microplate/sbs_96_well.urdf rename to assets/urdf/objects/microplate/sbs_96_well.urdf diff --git a/assets/urdf/microplate/sbs_96_well_convex.stl b/assets/urdf/objects/microplate/sbs_96_well_convex.stl similarity index 100% rename from assets/urdf/microplate/sbs_96_well_convex.stl rename to assets/urdf/objects/microplate/sbs_96_well_convex.stl diff --git a/assets/urdf/lite6/README.md b/assets/urdf/robots/lite6/README.md similarity index 51% rename from assets/urdf/lite6/README.md rename to assets/urdf/robots/lite6/README.md index 527eda6..5f3174d 100644 --- a/assets/urdf/lite6/README.md +++ b/assets/urdf/robots/lite6/README.md @@ -10,20 +10,22 @@ Lite6 arm description. | `lite6_visual.glb.urdf` | GLB visuals. Same physics, except that the `link_base` inertia tensor is zero (fixed base, no effect on dynamics) | | `meshes/lite6/visual/*.stl` | STL visuals (7) | | `meshes/lite6/visual_glb/*.glb` | Draco-compressed GLB visuals (7), 0.75 MB in total (test budget < 1 MB); `link_base.glb` sits flush at `z = 0` matching `link_base.stl` | -| `meshes/lite6/collision/lite6_link*_col_*.stl` | Convex collision hulls (17) | +| `meshes/lite6/collision/lite6_link*_col_*.stl` | Convex collision hulls (19) | | `kinematics/user/` | Per-unit calibration `_kinematics_.yaml` (Git-ignored), read by `ufactory/kinematics/calibration.py` | -End effectors for the `lite6` flange: [`lite6_gripper`](../lite6_gripper/README.md) and [`lite6_vacuum_gripper`](../lite6_vacuum_gripper/README.md). No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../assembly.yaml), e.g. `compose_robot_urdf("lite6", "lite6_gripper")`. The runtime configuration uses `assembly:lite6_gripper:stl` (STL visuals). +End effectors for the `lite6` flange: [`lite6_gripper`](../../end_effectors/lite6_gripper/README.md) and [`lite6_vacuum_gripper`](../../end_effectors/lite6_vacuum_gripper/README.md). No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../../assembly.yaml), e.g. `compose_robot_urdf("lite6", "lite6_gripper")`. The runtime configuration uses `assembly:lite6_gripper:stl` (STL visuals). ## Collision meshes | Link | link_base | link1 | link2 | link3 | link4 | link5 | link6 | |---|---|---|---|---|---|---|---| -| Hulls | 3 | 2 | 4 | 2 | 4 | 1 | 1 | +| Hulls | 3 | 2 | 4 | 2 | 4 | 1 | 3 | -Why the links use several hulls: see [xArm6 collision meshes](../xarm6/README.md#collision-meshes). +`link6` is split into three exact convex hulls from `visual/link6.stl` (flange body `col_00`, recessed neck `col_01`, and side connector boss `col_02`) so the convex envelope does not bridge across the concave neck/connector steps and falsely reduce the `link4`/`link6` wrist clearance below 5 mm under per-unit calibration. + +Why the other links use several hulls: see [xArm6 collision meshes](../xarm6/README.md#collision-meshes). ## Source / License -- URDF and STL derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../NOTICE)). +- URDF and STL derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../../NOTICE)). - This repository maintains the GLB visuals, the collision hulls and the Draco compression. Code is MIT; asset attribution is in NOTICE. diff --git a/assets/urdf/lite6/kinematics/user/.gitkeep b/assets/urdf/robots/lite6/kinematics/user/.gitkeep similarity index 100% rename from assets/urdf/lite6/kinematics/user/.gitkeep rename to assets/urdf/robots/lite6/kinematics/user/.gitkeep diff --git a/assets/urdf/lite6/lite6.urdf b/assets/urdf/robots/lite6/lite6.urdf similarity index 95% rename from assets/urdf/lite6/lite6.urdf rename to assets/urdf/robots/lite6/lite6.urdf index f784106..fc1bd9e 100644 --- a/assets/urdf/lite6/lite6.urdf +++ b/assets/urdf/robots/lite6/lite6.urdf @@ -257,6 +257,18 @@ + + + + + + + + + + + + diff --git a/assets/urdf/lite6/lite6_visual.glb.urdf b/assets/urdf/robots/lite6/lite6_visual.glb.urdf similarity index 95% rename from assets/urdf/lite6/lite6_visual.glb.urdf rename to assets/urdf/robots/lite6/lite6_visual.glb.urdf index cd7039e..b91aca1 100644 --- a/assets/urdf/lite6/lite6_visual.glb.urdf +++ b/assets/urdf/robots/lite6/lite6_visual.glb.urdf @@ -257,6 +257,18 @@ + + + + + + + + + + + + diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link1_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link1_col_00.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link1_col_00.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link1_col_00.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link1_col_01.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link1_col_01.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link1_col_01.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link1_col_01.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_00.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_00.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_00.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_01.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_01.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_01.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_01.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_02.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_02.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_02.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_02.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_03.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_03.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link2_col_03.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link2_col_03.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link3_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link3_col_00.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link3_col_00.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link3_col_00.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link3_col_01.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link3_col_01.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link3_col_01.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link3_col_01.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_00.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_00.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_00.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_01.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_01.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_01.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_01.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_02.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_02.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_02.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_02.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_03.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_03.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link4_col_03.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link4_col_03.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link5_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link5_col_00.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link5_col_00.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link5_col_00.stl diff --git a/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_00.stl new file mode 100644 index 0000000..be8e3f2 Binary files /dev/null and b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_00.stl differ diff --git a/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_01.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_01.stl new file mode 100644 index 0000000..a505093 Binary files /dev/null and b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_01.stl differ diff --git a/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_02.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_02.stl new file mode 100644 index 0000000..09af4ce Binary files /dev/null and b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link6_col_02.stl differ diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link_base_col_00.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link_base_col_00.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link_base_col_00.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link_base_col_00.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link_base_col_01.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link_base_col_01.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link_base_col_01.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link_base_col_01.stl diff --git a/assets/urdf/lite6/meshes/lite6/collision/lite6_link_base_col_02.stl b/assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link_base_col_02.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/collision/lite6_link_base_col_02.stl rename to assets/urdf/robots/lite6/meshes/lite6/collision/lite6_link_base_col_02.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link1.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link1.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link1.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link1.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link2.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link2.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link2.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link2.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link3.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link3.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link3.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link3.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link4.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link4.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link4.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link4.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link5.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link5.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link5.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link5.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link6.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link6.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link6.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link6.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual/link_base.stl b/assets/urdf/robots/lite6/meshes/lite6/visual/link_base.stl similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual/link_base.stl rename to assets/urdf/robots/lite6/meshes/lite6/visual/link_base.stl diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link1.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link1.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link1.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link1.glb diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link2.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link2.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link2.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link2.glb diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link3.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link3.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link3.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link3.glb diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link4.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link4.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link4.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link4.glb diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link5.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link5.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link5.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link5.glb diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link6.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link6.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link6.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link6.glb diff --git a/assets/urdf/lite6/meshes/lite6/visual_glb/link_base.glb b/assets/urdf/robots/lite6/meshes/lite6/visual_glb/link_base.glb similarity index 100% rename from assets/urdf/lite6/meshes/lite6/visual_glb/link_base.glb rename to assets/urdf/robots/lite6/meshes/lite6/visual_glb/link_base.glb diff --git a/assets/urdf/uf850/README.md b/assets/urdf/robots/uf850/README.md similarity index 59% rename from assets/urdf/uf850/README.md rename to assets/urdf/robots/uf850/README.md index 4a51c39..768bfe1 100644 --- a/assets/urdf/uf850/README.md +++ b/assets/urdf/robots/uf850/README.md @@ -13,7 +13,7 @@ UF850 arm description. | `meshes/uf850/collision/uf850_link*_col_*.stl` | Convex collision hulls (27) | | `kinematics/user/` | Per-unit calibration `_kinematics_.yaml` (Git-ignored), read by `ufactory/kinematics/calibration.py` | -The UF850 has the same `xarm` tool flange as xArm5/6/7, so it takes the same end effectors: [`gripper_g2`](../gripper_g2/README.md), [`bio_gripper_g2`](../bio_gripper_g2/README.md) and [`vacuum_gripper`](../vacuum_gripper/README.md). No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../assembly.yaml), e.g. `compose_robot_urdf("uf850", "gripper_g2")`. +The UF850 has the same `xarm` tool flange as xArm5/6/7, so it takes the same end effectors: [`gripper_g2`](../../end_effectors/gripper_g2/README.md), [`bio_gripper_g2`](../../end_effectors/bio_gripper_g2/README.md) and [`vacuum_gripper`](../../end_effectors/vacuum_gripper/README.md). No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../../assembly.yaml), e.g. `compose_robot_urdf("uf850", "gripper_g2")`. ## Collision meshes @@ -23,7 +23,11 @@ The UF850 has the same `xarm` tool flange as xArm5/6/7, so it takes the same end Why the links use several hulls: see [xArm6 collision meshes](../xarm6/README.md#collision-meshes). +## Base inertial + +`uf850.urdf` and `uf850_visual.glb.urdf` share the `link_base` inertial parameters evaluated in SolidWorks on the `Arm850_P01` base assembly (`5.869631 kg`, CoM `(-0.762, -0.044, 117.610) mm`, standard URDF negative off-diagonal product-of-inertia convention; total bare-arm mass `19.844631 kg`). + ## Source / License -- URDF and STL derive from the upstream UFACTORY / xArm ROS descriptions (see [NOTICE](../../../NOTICE)). +- URDF and STL derive from the upstream UFACTORY / xArm ROS descriptions (see [NOTICE](../../../../NOTICE)). - This repository maintains the GLB visuals, the collision hulls and the Draco compression. Code is MIT; asset attribution is in NOTICE. diff --git a/assets/urdf/uf850/kinematics/user/.gitkeep b/assets/urdf/robots/uf850/kinematics/user/.gitkeep similarity index 100% rename from assets/urdf/uf850/kinematics/user/.gitkeep rename to assets/urdf/robots/uf850/kinematics/user/.gitkeep diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_01.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_01.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_01.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_01.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_02.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_02.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_02.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_02.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_03.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_03.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link1_col_03.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link1_col_03.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_01.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_01.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_01.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_01.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_02.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_02.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_02.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_02.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_03.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_03.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_03.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_03.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_04.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_04.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_04.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_04.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_05.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_05.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_05.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_05.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_06.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_06.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link2_col_06.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link2_col_06.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_01.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_01.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_01.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_01.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_02.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_02.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_02.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_02.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_03.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_03.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_03.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_03.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_04.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_04.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link3_col_04.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link3_col_04.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_01.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_01.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_01.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_01.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_02.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_02.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_02.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_02.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_03.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_03.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_03.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_03.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_04.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_04.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link4_col_04.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link4_col_04.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link5_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link5_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link5_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link5_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link5_col_01.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link5_col_01.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link5_col_01.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link5_col_01.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link6_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link6_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link6_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link6_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link_base_col_00.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link_base_col_00.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link_base_col_00.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link_base_col_00.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link_base_col_01.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link_base_col_01.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link_base_col_01.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link_base_col_01.stl diff --git a/assets/urdf/uf850/meshes/uf850/collision/uf850_link_base_col_02.stl b/assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link_base_col_02.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/collision/uf850_link_base_col_02.stl rename to assets/urdf/robots/uf850/meshes/uf850/collision/uf850_link_base_col_02.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link1.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link1.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link1.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link1.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link2.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link2.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link2.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link2.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link3.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link3.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link3.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link3.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link4.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link4.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link4.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link4.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link5.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link5.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link5.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link5.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link6.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link6.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link6.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link6.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual/link_base.stl b/assets/urdf/robots/uf850/meshes/uf850/visual/link_base.stl similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual/link_base.stl rename to assets/urdf/robots/uf850/meshes/uf850/visual/link_base.stl diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link1.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link1.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link1.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link1.glb diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link2.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link2.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link2.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link2.glb diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link3.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link3.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link3.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link3.glb diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link4.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link4.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link4.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link4.glb diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link5.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link5.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link5.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link5.glb diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link6.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link6.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link6.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link6.glb diff --git a/assets/urdf/uf850/meshes/uf850/visual_glb/link_base.glb b/assets/urdf/robots/uf850/meshes/uf850/visual_glb/link_base.glb similarity index 100% rename from assets/urdf/uf850/meshes/uf850/visual_glb/link_base.glb rename to assets/urdf/robots/uf850/meshes/uf850/visual_glb/link_base.glb diff --git a/assets/urdf/uf850/uf850.urdf b/assets/urdf/robots/uf850/uf850.urdf similarity index 97% rename from assets/urdf/uf850/uf850.urdf rename to assets/urdf/robots/uf850/uf850.urdf index 944904e..1b4390f 100644 --- a/assets/urdf/uf850/uf850.urdf +++ b/assets/urdf/robots/uf850/uf850.urdf @@ -20,9 +20,9 @@ - - - + + + diff --git a/assets/urdf/uf850/uf850_visual.glb.urdf b/assets/urdf/robots/uf850/uf850_visual.glb.urdf similarity index 97% rename from assets/urdf/uf850/uf850_visual.glb.urdf rename to assets/urdf/robots/uf850/uf850_visual.glb.urdf index 067e3bd..5c211df 100644 --- a/assets/urdf/uf850/uf850_visual.glb.urdf +++ b/assets/urdf/robots/uf850/uf850_visual.glb.urdf @@ -20,9 +20,9 @@ - - - + + + diff --git a/assets/urdf/xarm5/README.md b/assets/urdf/robots/xarm5/README.md similarity index 91% rename from assets/urdf/xarm5/README.md rename to assets/urdf/robots/xarm5/README.md index 2a53952..9ded215 100644 --- a/assets/urdf/xarm5/README.md +++ b/assets/urdf/robots/xarm5/README.md @@ -10,7 +10,7 @@ xArm5 arm description (1305 variant). The xArm5 is an xArm6 whose J4 harmonic jo | `xarm5_1305_visual.glb.urdf` | Same physics, GLB visuals | | `kinematics/user/` | Per-unit calibration `_kinematics_.yaml` (Git-ignored), read by `ufactory/kinematics/calibration.py` | -No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../assembly.yaml), e.g. `compose_robot_urdf("xarm5_1305", "gripper_g2")`. +No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../../assembly.yaml), e.g. `compose_robot_urdf("xarm5_1305", "gripper_g2")`. ## Link mapping @@ -28,5 +28,5 @@ No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them ## Source / License -- URDF derives from the upstream xArm ROS descriptions (see [NOTICE](../../../NOTICE); typically BSD-3-Clause). +- URDF derives from the upstream xArm ROS descriptions (see [NOTICE](../../../../NOTICE); typically BSD-3-Clause). - Meshes: see [xArm6](../xarm6/README.md). Code is MIT; asset attribution is in NOTICE. diff --git a/assets/urdf/xarm5/kinematics/user/.gitkeep b/assets/urdf/robots/xarm5/kinematics/user/.gitkeep similarity index 100% rename from assets/urdf/xarm5/kinematics/user/.gitkeep rename to assets/urdf/robots/xarm5/kinematics/user/.gitkeep diff --git a/assets/urdf/xarm5/xarm5_1305.urdf b/assets/urdf/robots/xarm5/xarm5_1305.urdf similarity index 100% rename from assets/urdf/xarm5/xarm5_1305.urdf rename to assets/urdf/robots/xarm5/xarm5_1305.urdf diff --git a/assets/urdf/xarm5/xarm5_1305_visual.glb.urdf b/assets/urdf/robots/xarm5/xarm5_1305_visual.glb.urdf similarity index 100% rename from assets/urdf/xarm5/xarm5_1305_visual.glb.urdf rename to assets/urdf/robots/xarm5/xarm5_1305_visual.glb.urdf diff --git a/assets/urdf/xarm6/README.md b/assets/urdf/robots/xarm6/README.md similarity index 93% rename from assets/urdf/xarm6/README.md rename to assets/urdf/robots/xarm6/README.md index dcb5577..f583d43 100644 --- a/assets/urdf/xarm6/README.md +++ b/assets/urdf/robots/xarm6/README.md @@ -13,7 +13,7 @@ xArm6 arm description. 1305 is the only xArm6 variant in this tree. | `meshes/xarm6_1305/collision/xarm6_link*_col_*.stl` | Convex collision hulls (22) | | `kinematics/user/` | Per-unit calibration `_kinematics_.yaml` (Git-ignored), read by `ufactory/kinematics/calibration.py` | -No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../assembly.yaml), e.g. `compose_robot_urdf("xarm6_1305", "gripper_g2")`. +No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../../assembly.yaml), e.g. `compose_robot_urdf("xarm6_1305", "gripper_g2")`. ## Collision meshes @@ -34,5 +34,5 @@ The base is the production version A: flat top at z = 150.35 mm, body Ø95.4 mm. ## Source / License -- URDF and STL derive from the upstream xArm ROS descriptions (see [NOTICE](../../../NOTICE); typically BSD-3-Clause). +- URDF and STL derive from the upstream xArm ROS descriptions (see [NOTICE](../../../../NOTICE); typically BSD-3-Clause). - This repository maintains the GLB visuals, the collision hulls and the Draco compression. Code is MIT; asset attribution is in NOTICE. diff --git a/assets/urdf/xarm6/kinematics/user/.gitkeep b/assets/urdf/robots/xarm6/kinematics/user/.gitkeep similarity index 100% rename from assets/urdf/xarm6/kinematics/user/.gitkeep rename to assets/urdf/robots/xarm6/kinematics/user/.gitkeep diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_01.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_01.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_01.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link1_col_01.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_01.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_01.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_01.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_01.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_02.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_02.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_02.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_02.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_03.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_03.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_03.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_03.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_04.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_04.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_04.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link2_col_04.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_01.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_01.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_01.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_01.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_02.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_02.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_02.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_02.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_03.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_03.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_03.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_03.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_04.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_04.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_04.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link3_col_04.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_01.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_01.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_01.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_01.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_02.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_02.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_02.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_02.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_03.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_03.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_03.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_03.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_04.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_04.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_04.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link4_col_04.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_01.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_01.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_01.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link5_col_01.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link6_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link6_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link6_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link6_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_00.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_00.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_00.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_00.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_01.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_01.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_01.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/collision/xarm6_link_base_col_01.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link1.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link1.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link1.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link1.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link2.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link2.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link2.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link2.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link3.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link3.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link3.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link3.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link4.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link4.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link4.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link4.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link5.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link5.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link5.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link5.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link6.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link6.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link6.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link6.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual/link_base.stl b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link_base.stl similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual/link_base.stl rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual/link_base.stl diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link1.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link1.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link1.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link1.glb diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link2.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link2.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link2.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link2.glb diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link3.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link3.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link3.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link3.glb diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link4.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link4.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link4.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link4.glb diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link5.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link5.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link5.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link5.glb diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link6.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link6.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link6.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link6.glb diff --git a/assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link_base.glb b/assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link_base.glb similarity index 100% rename from assets/urdf/xarm6/meshes/xarm6_1305/visual_glb/link_base.glb rename to assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb/link_base.glb diff --git a/assets/urdf/xarm6/xarm6_1305.urdf b/assets/urdf/robots/xarm6/xarm6_1305.urdf similarity index 100% rename from assets/urdf/xarm6/xarm6_1305.urdf rename to assets/urdf/robots/xarm6/xarm6_1305.urdf diff --git a/assets/urdf/xarm6/xarm6_1305_visual.glb.urdf b/assets/urdf/robots/xarm6/xarm6_1305_visual.glb.urdf similarity index 100% rename from assets/urdf/xarm6/xarm6_1305_visual.glb.urdf rename to assets/urdf/robots/xarm6/xarm6_1305_visual.glb.urdf diff --git a/assets/urdf/xarm7/README.md b/assets/urdf/robots/xarm7/README.md similarity index 92% rename from assets/urdf/xarm7/README.md rename to assets/urdf/robots/xarm7/README.md index 7c55e15..3c02225 100644 --- a/assets/urdf/xarm7/README.md +++ b/assets/urdf/robots/xarm7/README.md @@ -13,7 +13,7 @@ xArm7 arm description (1305 variant). | `meshes/xarm7_1305/collision/xarm7_link*_col_*.stl` | Convex collision hulls of link1–link6 (23) | | `kinematics/user/` | Per-unit calibration `_kinematics_.yaml` (Git-ignored), read by `ufactory/kinematics/calibration.py` | -`link_base` and the flange link `link7` use xArm6 meshes (see [Shared parts](#shared-parts)). No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../assembly.yaml), e.g. `compose_robot_urdf("xarm7_1305", "gripper_g2")`. +`link_base` and the flange link `link7` use xArm6 meshes (see [Shared parts](#shared-parts)). No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them at runtime from [`assembly.yaml`](../../assembly.yaml), e.g. `compose_robot_urdf("xarm7_1305", "gripper_g2")`. ## Collision meshes @@ -29,5 +29,5 @@ xArm7 arm description (1305 variant). ## Source / License -- URDF and STL derive from the upstream xArm ROS descriptions (see [NOTICE](../../../NOTICE); typically BSD-3-Clause). +- URDF and STL derive from the upstream xArm ROS descriptions (see [NOTICE](../../../../NOTICE); typically BSD-3-Clause). - This repository maintains the GLB visuals, the collision hulls and the Draco compression. Code is MIT; asset attribution is in NOTICE. diff --git a/assets/urdf/xarm7/kinematics/user/.gitkeep b/assets/urdf/robots/xarm7/kinematics/user/.gitkeep similarity index 100% rename from assets/urdf/xarm7/kinematics/user/.gitkeep rename to assets/urdf/robots/xarm7/kinematics/user/.gitkeep diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_00.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_00.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_00.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_00.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_01.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_01.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_01.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link1_col_01.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_00.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_00.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_00.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_00.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_01.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_01.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_01.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_01.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_02.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_02.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_02.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_02.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_03.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_03.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_03.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_03.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_04.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_04.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_04.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link2_col_04.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_00.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_00.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_00.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_00.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_01.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_01.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_01.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_01.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_02.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_02.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_02.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_02.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_03.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_03.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_03.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link3_col_03.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_00.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_00.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_00.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_00.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_01.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_01.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_01.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_01.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_02.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_02.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_02.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_02.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_03.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_03.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_03.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_03.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_04.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_04.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_04.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link4_col_04.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_00.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_00.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_00.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_00.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_01.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_01.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_01.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_01.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_02.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_02.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_02.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_02.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_03.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_03.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_03.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_03.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_04.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_04.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_04.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link5_col_04.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_00.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_00.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_00.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_00.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_01.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_01.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_01.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/collision/xarm7_link6_col_01.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual/link1.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link1.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual/link1.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link1.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual/link2.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link2.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual/link2.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link2.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual/link3.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link3.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual/link3.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link3.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual/link4.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link4.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual/link4.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link4.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual/link5.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link5.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual/link5.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link5.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual/link6.stl b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link6.stl similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual/link6.stl rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual/link6.stl diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link1.glb b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link1.glb similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link1.glb rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link1.glb diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link2.glb b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link2.glb similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link2.glb rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link2.glb diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link3.glb b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link3.glb similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link3.glb rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link3.glb diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link4.glb b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link4.glb similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link4.glb rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link4.glb diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link5.glb b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link5.glb similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link5.glb rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link5.glb diff --git a/assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link6.glb b/assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link6.glb similarity index 100% rename from assets/urdf/xarm7/meshes/xarm7_1305/visual_glb/link6.glb rename to assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb/link6.glb diff --git a/assets/urdf/xarm7/xarm7_1305.urdf b/assets/urdf/robots/xarm7/xarm7_1305.urdf similarity index 100% rename from assets/urdf/xarm7/xarm7_1305.urdf rename to assets/urdf/robots/xarm7/xarm7_1305.urdf diff --git a/assets/urdf/xarm7/xarm7_1305_visual.glb.urdf b/assets/urdf/robots/xarm7/xarm7_1305_visual.glb.urdf similarity index 100% rename from assets/urdf/xarm7/xarm7_1305_visual.glb.urdf rename to assets/urdf/robots/xarm7/xarm7_1305_visual.glb.urdf diff --git a/examples/README.md b/examples/README.md index 11d7fac..5ea12aa 100644 --- a/examples/README.md +++ b/examples/README.md @@ -71,26 +71,28 @@ See the [RL index](rl/README.md) for the learning sequence and training/inferenc | `uf850` | Gripper G2, Bio Gripper G2, Robotiq 2F-85, Robotiq 2F-140, Vacuum Gripper | Bare arm, Gripper G2, Robotiq 2F-85, Robotiq 2F-140, Vacuum Gripper (not Bio Gripper G2) | Yes | — | | `lite6` | Lite6 Gripper, Lite6 Vacuum Gripper | Bare arm, Lite6 Gripper, Lite6 Vacuum Gripper | Yes | Lite6 Gripper | -All robots accept the [camera stand](../assets/urdf/camera_stand/README.md) (alone or with one depth camera looking along the tool axis), which moves the end effector and its TCP 3 mm along the tool axis: +All robots accept the [camera stand](../assets/urdf/mounts/camera_stand/README.md) (alone or with one depth camera looking along the tool axis), which moves the end effector and its TCP 3 mm along the tool axis: | Accessory key | Name | Notes | |---|---|---| -| `camera_stand` | [Camera Stand](../assets/urdf/camera_stand/README.md) | 3 mm aluminium stand (48 g) | -| `d405` | [Intel RealSense D405](../assets/urdf/d405/README.md) | Stand + D405 short-range stereo depth camera (58 g) | -| `d435` | [Intel RealSense D435](../assets/urdf/d435/README.md) | Stand + D435 stereo depth camera (75 g) | -| `gemini_305` | [Orbbec Gemini 305](../assets/urdf/gemini_305/README.md) | Stand + Gemini 305 stereo depth camera (68 g) | -| `zed_x_nano` | [Stereolabs ZED X Nano](../assets/urdf/zed_x_nano/README.md) | Stand + ZED X Nano stereo camera (75 g) | +| `camera_stand` | [Camera Stand](../assets/urdf/mounts/camera_stand/README.md) | 3 mm aluminium stand (48 g) | +| `d405` | [Intel RealSense D405](../assets/urdf/cameras/d405/README.md) | Stand + D405 short-range stereo depth camera (58 g) | +| `d435` | [Intel RealSense D435](../assets/urdf/cameras/d435/README.md) | Stand + D435 stereo depth camera (75 g) | +| `gemini_305` | [Orbbec Gemini 305](../assets/urdf/cameras/gemini_305/README.md) | Stand + Gemini 305 stereo depth camera (68 g) | +| `zed_x_nano` | [Stereolabs ZED X Nano](../assets/urdf/cameras/zed_x_nano/README.md) | Stand + ZED X Nano stereo camera (75 g) | -- Configuration URDF references: `assembly:gripper_g2+d435`, `assembly:lite6_gripper+d435`, `assembly:bare+camera_stand`, `assembly:bare+mounting_plate`, or `assembly:gripper_g2+d435+mounting_plate`. +- Configuration URDF references: `assembly:gripper_g2+d435`, `assembly:gripper_g2+ft_sensor_ai1500+d435`, `assembly:lite6_gripper+d435`, `assembly:bare+ft_sensor_ai1500`, `assembly:bare+camera_stand`, `assembly:bare+mounting_plate`, or `assembly:gripper_g2+d435+mounting_plate`. - Real packaging details: [Hardware & Real Robot](#hardware--real-robot). G2 simulations use `g2_calibrated_v1`; see the [pick-place RL guide](rl/pick_place/README.md) for training and the current v3 checkpoint contract. +`xarm5`, `xarm6`, `xarm7`, and `uf850` also accept the [AI1500 six-axis force/torque sensor](../assets/urdf/accessories/ft_sensor_ai1500/README.md) directly on the tool flange (`+58.6 mm` along flange `+Z`, `0.6 kg`), below any camera stand, adapter, or end effector. + All robots also accept their official aluminium mounting plate (mounted below `link_base`, top face at `z = 0`, keeping kinematics unchanged): | Mounting plate | Robots | Envelope (mm) | Standalone `--tool` | |---|---|---|---| -| [xArm Mounting Plate](../assets/urdf/xarm_mounting_plate/README.md) | `xarm5`, `xarm6`, `xarm7` | `136 × 185 × 8` | `xarm_mounting_plate` | -| [UF850 Mounting Plate](../assets/urdf/uf850_mounting_plate/README.md) | `uf850` | `190 × 260 × 10` | `uf850_mounting_plate` | -| [Lite 6 Mounting Plate](../assets/urdf/lite6_mounting_plate/README.md) | `lite6` | `130 × 190 × 5` | `lite6_mounting_plate` | +| [xArm Mounting Plate](../assets/urdf/mounts/xarm_mounting_plate/README.md) | `xarm5`, `xarm6`, `xarm7` | `136 × 185 × 8` | `xarm_mounting_plate` | +| [UF850 Mounting Plate](../assets/urdf/mounts/uf850_mounting_plate/README.md) | `uf850` | `190 × 260 × 10` | `uf850_mounting_plate` | +| [Lite 6 Mounting Plate](../assets/urdf/mounts/lite6_mounting_plate/README.md) | `lite6` | `130 × 190 × 5` | `lite6_mounting_plate` | ## Visualization @@ -135,11 +137,15 @@ python examples/visualization/view_robot.py --robot lite6 --lite6-vacuum-gripper # xArm6 + Gripper G2 + D435 + mounting plate python examples/visualization/view_robot.py --robot xarm6 --gripper-g2 --camera d435 --mounting-plate -# Standalone tool, adapter, and mounting-plate preview +# xArm6 + AI1500 F/T sensor + D435 + Gripper G2 +python examples/visualization/view_robot.py --robot xarm6 --ft-sensor --gripper-g2 --camera d435 --gripper-demo + +# Standalone tool, adapter, F/T sensor, and mounting-plate preview python examples/visualization/view_tool.py --tool gripper_g2 python examples/visualization/view_tool.py --tool robotiq_2f_85 python examples/visualization/view_tool.py --tool robotiq_2f_140 python examples/visualization/view_tool.py --tool robotiq_mounting +python examples/visualization/view_tool.py --tool ft_sensor_ai1500 python examples/visualization/view_tool.py --tool bio_gripper_g2 python examples/visualization/view_tool.py --tool lite6_gripper python examples/visualization/view_tool.py --tool vacuum_gripper @@ -156,6 +162,7 @@ python examples/visualization/view_tool.py --tool lite6_mounting_plate | `--robot` | Required profile key | | `--gripper-g2` / `--bio-gripper-g2` / `--robotiq-2f-85` / `--robotiq-2f-140` / `--vacuum-gripper` / `--lite6-gripper` / `--lite6-vacuum-gripper` | End-effector combo (at most one) | | `--camera` | `camera_stand`, `d405`, `d435`, `gemini_305` or `zed_x_nano`: the camera stand, alone or with that camera (all robots; bare arm or any end effector except `--bio-gripper-g2`) | +| `--ft-sensor` | Mount `ft_sensor_ai1500` on the tool flange (`xarm5`, `xarm6`, `xarm7`, `uf850`; optional value defaults to `ft_sensor_ai1500`) | | `--mounting-plate` | Mount the robot's official aluminium mounting plate below `link_base` | | `--movable` | Compatibility no-op (grippers always use per-link movable GLBs) | | `--gripper-demo` | Cycle open/close with a 0.5 s hold after reaching each endpoint (requires a gripper flag) | @@ -165,7 +172,7 @@ python examples/visualization/view_tool.py --tool lite6_mounting_plate | `--headless` | No viewer window | | `--backend` | `cpu` / `gpu` (default `gpu`; use `cpu` without a supported GPU) | -`view_tool.py` accepts `--tool {gripper_g2,robotiq_2f_85,robotiq_2f_140,robotiq_mounting,bio_gripper_g2,lite6_gripper,vacuum_gripper,lite6_vacuum_gripper,xarm_mounting_plate,uf850_mounting_plate,lite6_mounting_plate}`, `--headless`, `--backend`, and calibrated gripper tuning flags (`--position-mm`, `--speed-percent`, `--force-percent`, plus `--speed-mm-s` for `bio_gripper_g2`). +`view_tool.py` accepts `--tool {gripper_g2,robotiq_2f_85,robotiq_2f_140,robotiq_mounting,ft_sensor_ai1500,bio_gripper_g2,lite6_gripper,vacuum_gripper,lite6_vacuum_gripper,xarm_mounting_plate,uf850_mounting_plate,lite6_mounting_plate}`, `--headless`, `--backend`, and calibrated gripper tuning flags (`--position-mm`, `--speed-percent`, `--force-percent`, plus `--speed-mm-s` for `bio_gripper_g2`). ## Kinematics & Dynamics Simulation @@ -239,6 +246,14 @@ dynamics-sim-collision-check --robot xarm6 --ip python examples/simulation/packaging/run.py \ --robot lite6 --mode sdk-sim --executor servo_cartesian \ --ip --calibration path/to/exact.yaml + +# xArm6 + Bio Gripper G2: pick-place controller-internal simulation (sdk-sim, servo_j or servo_cartesian) +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode sdk-sim --executor servo_j \ + --ip --calibration path/to/exact.yaml +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode sdk-sim --executor servo_cartesian \ + --ip --calibration path/to/exact.yaml ``` ### 2. Physical Motion Commands (Drives Robot & Gripper) @@ -254,6 +269,14 @@ XARM_IP= python examples/simulation/pick_place/run.py \ --robot xarm6 --mode real --executor servo_j \ --calibration path/to/exact.yaml --confirm-real +# xArm6 + Bio Gripper G2: real empty pick-place motion (servo_j or servo_cartesian, optional --visual mirror; requires per-unit calibration + --confirm-real) +XARM_IP= python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode real --executor servo_j --visual \ + --calibration path/to/exact.yaml --confirm-real +XARM_IP= python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode real --executor servo_cartesian \ + --calibration path/to/exact.yaml --confirm-real + # Lite6 + Lite6 Gripper: real packaging motion (enabled for xArm6 + Gripper G2 and Lite6 + Lite6 Gripper; requires per-unit calibration + --confirm-real) XARM_IP= python examples/simulation/packaging/run.py \ --robot lite6 --mode real --executor servo_j \ diff --git a/examples/README_zh.md b/examples/README_zh.md index 076249b..aea42ad 100644 --- a/examples/README_zh.md +++ b/examples/README_zh.md @@ -70,26 +70,28 @@ python examples/visualization/view_robot.py --robot xarm6 | `uf850` | Gripper G2、Bio Gripper G2、Robotiq 2F-85、Robotiq 2F-140、Vacuum Gripper | 裸臂、Gripper G2、Robotiq 2F-85、Robotiq 2F-140、Vacuum Gripper(不适配 Bio Gripper G2) | 支持 | — | | `lite6` | Lite6 Gripper、Lite6 Vacuum Gripper | 裸臂、Lite6 Gripper、Lite6 Vacuum Gripper | 支持 | Lite6 Gripper | -所有机械臂均支持加装[相机支架](../assets/urdf/camera_stand/README.md)(可单独安装或搭载一台视野沿工具轴方向的深度相机);装上支架后,末端及其 TCP 沿工具轴前移 3 mm: +所有机械臂均支持加装[相机支架](../assets/urdf/mounts/camera_stand/README.md)(可单独安装或搭载一台视野沿工具轴方向的深度相机);装上支架后,末端及其 TCP 沿工具轴前移 3 mm: | 配件 key | 名称 | 说明 | |---|---|---| -| `camera_stand` | [相机支架](../assets/urdf/camera_stand/README.md) | 3 mm 铝合金支架(48 g) | -| `d405` | [Intel RealSense D405](../assets/urdf/d405/README.md) | 支架 + D405 短距双目深度相机(58 g) | -| `d435` | [Intel RealSense D435](../assets/urdf/d435/README.md) | 支架 + D435 双目深度相机(75 g) | -| `gemini_305` | [奥比中光 Gemini 305](../assets/urdf/gemini_305/README.md) | 支架 + Gemini 305 双目深度相机(68 g) | -| `zed_x_nano` | [Stereolabs ZED X Nano](../assets/urdf/zed_x_nano/README.md) | 支架 + ZED X Nano 双目相机(75 g) | +| `camera_stand` | [相机支架](../assets/urdf/mounts/camera_stand/README.md) | 3 mm 铝合金支架(48 g) | +| `d405` | [Intel RealSense D405](../assets/urdf/cameras/d405/README.md) | 支架 + D405 短距双目深度相机(58 g) | +| `d435` | [Intel RealSense D435](../assets/urdf/cameras/d435/README.md) | 支架 + D435 双目深度相机(75 g) | +| `gemini_305` | [奥比中光 Gemini 305](../assets/urdf/cameras/gemini_305/README.md) | 支架 + Gemini 305 双目深度相机(68 g) | +| `zed_x_nano` | [Stereolabs ZED X Nano](../assets/urdf/cameras/zed_x_nano/README.md) | 支架 + ZED X Nano 双目相机(75 g) | -- 配置中的 URDF 引用示例:`assembly:gripper_g2+d435`、`assembly:lite6_gripper+d435`、`assembly:bare+camera_stand`、`assembly:bare+mounting_plate` 或 `assembly:gripper_g2+d435+mounting_plate`。 +- 配置中的 URDF 引用示例:`assembly:gripper_g2+d435`、`assembly:gripper_g2+ft_sensor_ai1500+d435`、`assembly:lite6_gripper+d435`、`assembly:bare+ft_sensor_ai1500`、`assembly:bare+camera_stand`、`assembly:bare+mounting_plate` 或 `assembly:gripper_g2+d435+mounting_plate`。 - 真机说明与安全约束见[真机操作与硬件校验](#真机操作与硬件校验);G2 仿真使用 `g2_calibrated_v1`,策略训练与当前 v3 检查点契约见[抓放 RL 指南](rl/pick_place/README_zh.md)。 +`xarm5`、`xarm6`、`xarm7` 与 `uf850` 均支持在末端法兰上加装 [AI1500 六维力矩传感器](../assets/urdf/accessories/ft_sensor_ai1500/README.md)(沿法兰 `+Z` 抬升 `58.6 mm`、`0.6 kg`,位于相机支架、转接板及末端执行器之前)。 + 全部 5 款机械臂均支持加装对应铝合金安装底板(安装在 `link_base` 下方,上安装面 `z = 0`,不改变机械臂运动学坐标): | 安装底板 | 适配机型 | 外形包络(mm) | 独立查看 `--tool` | |---|---|---|---| -| [xArm 安装底板](../assets/urdf/xarm_mounting_plate/README.md) | `xarm5`、`xarm6`、`xarm7` | `136 × 185 × 8` | `xarm_mounting_plate` | -| [UF850 安装底板](../assets/urdf/uf850_mounting_plate/README.md) | `uf850` | `190 × 260 × 10` | `uf850_mounting_plate` | -| [Lite 6 安装底板](../assets/urdf/lite6_mounting_plate/README.md) | `lite6` | `130 × 190 × 5` | `lite6_mounting_plate` | +| [xArm 安装底板](../assets/urdf/mounts/xarm_mounting_plate/README.md) | `xarm5`、`xarm6`、`xarm7` | `136 × 185 × 8` | `xarm_mounting_plate` | +| [UF850 安装底板](../assets/urdf/mounts/uf850_mounting_plate/README.md) | `uf850` | `190 × 260 × 10` | `uf850_mounting_plate` | +| [Lite 6 安装底板](../assets/urdf/mounts/lite6_mounting_plate/README.md) | `lite6` | `130 × 190 × 5` | `lite6_mounting_plate` | ## 可视化 @@ -134,11 +136,15 @@ python examples/visualization/view_robot.py --robot lite6 --lite6-vacuum-gripper # xArm6 + Gripper G2 + D435 + 安装底板 python examples/visualization/view_robot.py --robot xarm6 --gripper-g2 --camera d435 --mounting-plate -# 末端工具、转接件与安装底板独立查看 +# xArm6 + AI1500 六维力矩传感器 + D435 + Gripper G2 +python examples/visualization/view_robot.py --robot xarm6 --ft-sensor --gripper-g2 --camera d435 --gripper-demo + +# 末端工具、转接件、力矩传感器与安装底板独立查看 python examples/visualization/view_tool.py --tool gripper_g2 python examples/visualization/view_tool.py --tool robotiq_2f_85 python examples/visualization/view_tool.py --tool robotiq_2f_140 python examples/visualization/view_tool.py --tool robotiq_mounting +python examples/visualization/view_tool.py --tool ft_sensor_ai1500 python examples/visualization/view_tool.py --tool bio_gripper_g2 python examples/visualization/view_tool.py --tool lite6_gripper python examples/visualization/view_tool.py --tool vacuum_gripper @@ -155,6 +161,7 @@ python examples/visualization/view_tool.py --tool lite6_mounting_plate | `--robot` | 必选机型 key | | `--gripper-g2` / `--bio-gripper-g2` / `--robotiq-2f-85` / `--robotiq-2f-140` / `--vacuum-gripper` / `--lite6-gripper` / `--lite6-vacuum-gripper` | 末端组合(最多选一个) | | `--camera` | `camera_stand`、`d405`、`d435`、`gemini_305` 或 `zed_x_nano`:加装相机支架,可单独装支架,也可再装对应相机(适配所有机型,支持裸臂及除 `--bio-gripper-g2` 外的末端) | +| `--ft-sensor` | 在末端法兰加装六维力矩传感器(适配 `xarm5`/`xarm6`/`xarm7`/`uf850`;不填值时默认 `ft_sensor_ai1500`) | | `--mounting-plate` | 在 `link_base` 下方加装对应铝合金安装底板 | | `--movable` | 兼容保留(所有夹爪默认均使用逐连杆可动 GLB) | | `--gripper-demo` | 循环开合,到位后保持 0.5 s 切换(需配合夹爪标志) | @@ -164,7 +171,7 @@ python examples/visualization/view_tool.py --tool lite6_mounting_plate | `--headless` | 不打开查看器窗口 | | `--backend` | `cpu` / `gpu`(默认 `gpu`;无支持显卡时用 `cpu`) | -`view_tool.py` 支持 `--tool {gripper_g2,robotiq_2f_85,robotiq_2f_140,robotiq_mounting,bio_gripper_g2,lite6_gripper,vacuum_gripper,lite6_vacuum_gripper,xarm_mounting_plate,uf850_mounting_plate,lite6_mounting_plate}`、`--headless`、`--backend`,以及标定夹爪调参选项(`--position-mm`、`--speed-percent`、`--force-percent`,其中 `bio_gripper_g2` 另支持 `--speed-mm-s`)。 +`view_tool.py` 支持 `--tool {gripper_g2,robotiq_2f_85,robotiq_2f_140,robotiq_mounting,ft_sensor_ai1500,bio_gripper_g2,lite6_gripper,vacuum_gripper,lite6_vacuum_gripper,xarm_mounting_plate,uf850_mounting_plate,lite6_mounting_plate}`、`--headless`、`--backend`,以及标定夹爪调参选项(`--position-mm`、`--speed-percent`、`--force-percent`,其中 `bio_gripper_g2` 另支持 `--speed-mm-s`)。 @@ -246,6 +253,14 @@ dynamics-sim-collision-check --robot xarm6 --ip python examples/simulation/packaging/run.py \ --robot lite6 --mode sdk-sim --executor servo_cartesian \ --ip --calibration path/to/exact.yaml + +# xArm6 + Bio Gripper G2:抓放控制器内部虚拟仿真(sdk-sim,支持 servo_j / servo_cartesian) +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode sdk-sim --executor servo_j \ + --ip --calibration path/to/exact.yaml +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode sdk-sim --executor servo_cartesian \ + --ip --calibration path/to/exact.yaml ``` @@ -263,6 +278,14 @@ XARM_IP= python examples/simulation/pick_place/run.py \ --robot xarm6 --mode real --executor servo_j \ --calibration path/to/exact.yaml --confirm-real +# xArm6 + Bio Gripper G2:抓放真机物理运动(支持 servo_j / servo_cartesian,可选 --visual 镜像;需实机标定文件与 --confirm-real) +XARM_IP= python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode real --executor servo_j --visual \ + --calibration path/to/exact.yaml --confirm-real +XARM_IP= python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode real --executor servo_cartesian \ + --calibration path/to/exact.yaml --confirm-real + # Lite6 + Lite6 Gripper:装箱真机物理运动(当前仅支持 xArm6 + Gripper G2、Lite6 + Lite6 Gripper;需实机标定文件与 --confirm-real) XARM_IP= python examples/simulation/packaging/run.py \ --robot lite6 --mode real --executor servo_j \ diff --git a/examples/rl/README.md b/examples/rl/README.md index 7210634..920441d 100644 --- a/examples/rl/README.md +++ b/examples/rl/README.md @@ -2,10 +2,10 @@ Follow the examples in increasing order of difficulty. These workflows run in simulation; run their commands as modules from the repository root. -Policy weights are not committed to Git. Pretrained Reach checkpoints are hosted on Hugging Face ([`UFACTORY-Developer/ufactory_genesis_rl`](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl)); Pick & Place must be trained locally. Training artifacts are saved under `outputs/rl/` (ignored by Git). +Policy weights are not committed to Git. Pretrained Reach and Pick & Place checkpoints are hosted on Hugging Face ([`UFACTORY-Developer/ufactory_genesis_rl`](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl)). Training artifacts are saved under `outputs/rl/` (ignored by Git). 1. **[Reach — target reaching](reach/README.md)**: move the bare-arm end effector (`xarm5`, `xarm6`, `xarm7`, `uf850`, `lite6`) to a target without a gripper. Success requires a distance strictly below **5 mm**; the default training seed is 7. The guide covers downloading pretrained checkpoints, training, checkpoint selection, acceptance and real-time GLB inference. -2. **[Pick & Place — tabletop](pick_place/README.md)**: use xArm6 + Gripper G2 to grasp, lift and transfer a cube, then set it down and release it at a tabletop target. The cube start position is sampled uniformly at random in `x ∈ [300, 500] mm`, `y ∈ [-200, 200] mm` with a fixed target at `(300, 300) mm`. The guide covers local training, evaluation and real-time GLB inference. +2. **[Pick & Place — tabletop](pick_place/README.md)**: use xArm6 + Gripper G2 to grasp, lift and transfer a cube, then set it down and release it at a tabletop target. The cube start position is sampled uniformly at random in `x ∈ [300, 500] mm`, `y ∈ [-200, 200] mm` with a fixed target at `(300, 300) mm`. The guide covers downloading the pretrained checkpoint, local training, evaluation and real-time GLB inference. 3. **Box packing — planned**: place an object inside a box, adding box geometry and contact constraints. The RL environment and training/inference entries remain to be implemented. The existing [packaging showcase](../simulation/packaging/README.md) uses trajectory control. diff --git a/examples/rl/README_zh.md b/examples/rl/README_zh.md index 0366b8a..e294b60 100644 --- a/examples/rl/README_zh.md +++ b/examples/rl/README_zh.md @@ -2,10 +2,10 @@ 按以下顺序从易到难运行示例。所有流程均在仿真中执行,请在项目根目录通过模块方式运行指令。 -仓库内不直接提交策略权重文件。Reach 预训练检查点托管于 Hugging Face([`UFACTORY-Developer/ufactory_genesis_rl`](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl));Pick & Place 需在本地训练。训练产物保存在 Git 忽略的 `outputs/rl/` 下。 +仓库内不直接提交策略权重文件。Reach 与 Pick & Place 预训练检查点托管于 Hugging Face([`UFACTORY-Developer/ufactory_genesis_rl`](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl))。训练产物保存在 Git 忽略的 `outputs/rl/` 下。 1. **[Reach:目标到达](reach/README_zh.md)**:不装夹爪,让机械臂(`xarm5`、`xarm6`、`xarm7`、`uf850`、`lite6`)末端到达目标点。成功距离严格小于 **5 mm**,默认训练种子 7。指南提供预训练检查点下载、训练、筛选、验收和 GLB 实时推理指令。 -2. **[Pick & Place:桌面抓放](pick_place/README_zh.md)**:使用 xArm6 + Gripper G2 抓取、抬升并搬运方块,在桌面目标位置放下、松爪。方块起点在 `x ∈ [300, 500] mm`、`y ∈ [-200, 200] mm` 矩形区域内均匀随机采样,目标点固定在 `(300, 300) mm`。指南提供本地训练、评估和 GLB 实时推理指令。 +2. **[Pick & Place:桌面抓放](pick_place/README_zh.md)**:使用 xArm6 + Gripper G2 抓取、抬升并搬运方块,在桌面目标位置放下、松爪。方块起点在 `x ∈ [300, 500] mm`、`y ∈ [-200, 200] mm` 矩形区域内均匀随机采样,目标点固定在 `(300, 300) mm`。指南提供预训练检查点下载、本地训练、评估和 GLB 实时推理指令。 3. **装箱:待实现**:将物体放入箱内,增加箱体几何与接触约束。RL 环境及训练、推理入口尚未实现。 现有[装箱展示](../simulation/packaging/README_zh.md)采用轨迹控制。 diff --git a/examples/rl/pick_place/README.md b/examples/rl/pick_place/README.md index e0db3e7..78efca9 100644 --- a/examples/rl/pick_place/README.md +++ b/examples/rl/pick_place/README.md @@ -29,7 +29,7 @@ python -m examples.rl.pick_place.run_seeds \ --seeds 1 2 3 -B 2048 --max-iterations 2000 ``` -Trains three seeds sequentially, runs an independent 64-episode evaluation, and records a single-environment replay. Evaluates every 50 iterations and updates `model_best.pt`; stops early after two consecutive evaluations with ≥98% success rate and ≤1 mm maximum pressing. Outputs are saved under each `pick_place_e2e_s/` directory, with the overall summary in `e2e_validation/summary.json`. Exits with a non-zero code if validation fails. +Trains three seeds sequentially, runs an independent 64-episode evaluation, and records a single-environment replay. Evaluates every 50 iterations (with dual-set holdout validation on seeds `17000` + `17500` totaling 192 episodes, requiring combined success rate ≥99.4%, max pressing ≤0.8 mm, and recent training stability) and updates `model_best.pt`; stops early after two consecutive passing evaluations. Outputs are saved under each `pick_place_e2e_s/` directory, with the overall summary in `e2e_validation/summary.json`. Exits with a non-zero code if validation fails. ### Single-seed training or resume @@ -46,22 +46,39 @@ python -m examples.rl.pick_place.train \ -e pick_place_e2e_s1_resume --seed 1 -B 2048 --max-iterations 200 ``` -`-B` is the number of parallel environments; reduce it if VRAM is insufficient. `--max-iterations` caps the training iterations; `--early-stop-evaluations 0` disables early stopping. Existing experiment directories are not overwritten; pass `-e` to use a new directory for standalone runs. +`-B` is the number of parallel environments; reduce it if VRAM is insufficient. `--max-iterations` caps the training iterations; `--eval-start-iteration` defers periodic strict evaluations until that iteration; `--early-stop-evaluations 0` disables early stopping. Existing experiment directories are not overwritten; pass `-e` to use a new directory for standalone runs. -## Local checkpoint evaluation and inference +## Benchmark -The commands below use `model_best.pt` produced by local training. Evaluate the checkpoint before running inference. +Across a 10-seed `C10` benchmark (`seeds 1..10`, `-B 2048`, up to `1200` iterations, `v0.3.11`), **8/10** seeds passed strict blind evaluation (`seed = 18000 + s`, 64 episodes, ≥98% success rate, ≤1.0 mm max pressing) and single-environment `GLB` replay, achieving **`508/512 (99.22%)`** combined blind success across passing seeds with **`0.00`** IK rejects (four seeds at `64/64 = 100.0%`, four at `63/64 = 98.44%`). + +The pretrained checkpoint hosted on Hugging Face (`pick_place/xarm6-pick-place/seed-7/model_best.pt`, early-stopped at `650` iterations) was verified on both Colab L4 and a local **NVIDIA GeForce RTX 4060 Ti (8 GB)**: + +| Robot + Gripper | Obs / Act Dim | Checkpoint | Dual Holdout (`17000` / `17500`) | Blind Eval (`18007`, 64 eps) | Max Press (`18007`) | Mean / Median Target Err (`18007`) | GLB `B=1` Replay | +|---|---:|---|---|---|---|---|---| +| `xarm6` + `gripper_g2` | 70 / 4 | `seed-7/model_best.pt` | **100%** (64/64) / **100%** (128/128) | **100%** (64/64) | `0.477 mm` (≤1.0 mm) | `6.98` / `6.14 mm` (≤20 mm) | **PASS** | + +## Evaluation and inference + +If you do not need to train from scratch locally, download the pretrained checkpoint from Hugging Face ([`UFACTORY-Developer/ufactory_genesis_rl`](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl)) into `outputs/rl/pick_place/`: + +```bash +# Install the Hugging Face CLI if not already available: pip install huggingface_hub +hf download UFACTORY-Developer/ufactory_genesis_rl --include "pick_place/**" --local-dir outputs/rl +``` + +The examples below use the downloaded checkpoint `outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt` (for a locally trained run, replace `--checkpoint` with `outputs/rl/pick_place/pick_place_e2e_s1/model_best.pt` or pass `-e pick_place_e2e_s1`). Evaluate the checkpoint before running inference. ### Evaluation -The example below evaluates the best checkpoint of seed 1, requiring ≥98% success rate and ≤1 mm maximum pressing over 64 episodes: +The example below evaluates the hosted seed-7 checkpoint, requiring ≥98% success rate and ≤1 mm maximum pressing over 64 episodes: ```bash python -m examples.rl.pick_place.evaluate \ - --checkpoint outputs/rl/pick_place/pick_place_e2e_s1/model_best.pt \ - -B 32 --episodes 64 --seed 18001 \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ + -B 32 --episodes 64 --seed 18007 \ --min-success-rate 0.98 --max-press-mm 1.0 \ - --quiet-episodes --out outputs/rl/pick_place/pick_place_e2e_s1/test.json + --quiet-episodes --out outputs/rl/pick_place/xarm6-pick-place/seed-7/test.json ``` `--out` writes both a JSON summary and a per-episode CSV table; exits with code `1` if the thresholds are not met. @@ -70,14 +87,16 @@ python -m examples.rl.pick_place.evaluate \ ```bash # Open interactive viewer -python -m examples.rl.pick_place.visualize -e pick_place_e2e_s1 -B 1 +python -m examples.rl.pick_place.visualize \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt -B 1 # Record a single-episode headless video python -m examples.rl.pick_place.visualize \ - -e pick_place_e2e_s1 -B 1 --episodes 1 --headless \ - --record outputs/rl/pick_place/pick_place_e2e_s1/replay.mp4 + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ + -B 1 --episodes 1 --headless \ + --record outputs/rl/pick_place/xarm6-pick-place/seed-7/replay.mp4 ``` -`-e` specifies the experiment name and loads `model_best.pt` from that directory by default; use `--checkpoint` to specify a file explicitly. `--headless` runs without a desktop window, and `--record` specifies the MP4 output path. +`-e` specifies an experiment name under `outputs/rl/pick_place/` and loads `model_best.pt` from that directory by default; use `--checkpoint` to specify any checkpoint path explicitly. `--headless` runs without a desktop window, and `--record` specifies the MP4 output path. Keep `model_best.pt`, `config.yaml`, and `model_best.checkpoint_manifest.json` in the same directory. When running `train`, `evaluate`, or `visualize` directly, use `--recipe` and `--runtime-config` to specify custom training recipes and scene configurations. Checkpoints verify the configuration on load; retrain after modifying the task configuration. diff --git a/examples/rl/pick_place/README_zh.md b/examples/rl/pick_place/README_zh.md index 78daf3a..c773e66 100644 --- a/examples/rl/pick_place/README_zh.md +++ b/examples/rl/pick_place/README_zh.md @@ -29,7 +29,7 @@ python -m examples.rl.pick_place.run_seeds \ --seeds 1 2 3 -B 2048 --max-iterations 2000 ``` -对三个种子依次训练、独立评估 64 回合,并录制单环境回放。每 50 轮评估并更新 `model_best.pt`;连续两次达到成功率 ≥98%、最大下压 ≤1 mm 后提前停止。结果保存在各自的 `pick_place_e2e_s<种子>/` 目录,汇总见 `e2e_validation/summary.json`。验收未通过时命令返回非零退出码。 +对三个种子依次训练、独立评估 64 回合,并录制单环境回放。每 50 轮评估(采用 `seed=17000` 64 回合 + `seed=17500` 128 回合共 192 回合双验证集,要求合并成功率 ≥99.4%、最大下压 ≤0.8 mm 且近期训练曲线稳定)并更新 `model_best.pt`;连续两次达标后提前停止。结果保存在各自的 `pick_place_e2e_s<种子>/` 目录,汇总见 `e2e_validation/summary.json`。验收未通过时命令返回非零退出码。 ### 单独训练或续训 @@ -46,22 +46,39 @@ python -m examples.rl.pick_place.train \ -e pick_place_e2e_s1_resume --seed 1 -B 2048 --max-iterations 200 ``` -`-B` 是并行环境数,显存不足时可减小。`--max-iterations` 是训练轮数上限;`--early-stop-evaluations 0` 可关闭提前停止。已有实验目录不会被覆盖,单独训练可通过 `-e` 指定新目录。 +`-B` 是并行环境数,显存不足时可减小。`--max-iterations` 是训练轮数上限;`--eval-start-iteration` 可推迟周期性严格评估起始轮次;`--early-stop-evaluations 0` 可关闭提前停止。已有实验目录不会被覆盖,单独训练可通过 `-e` 指定新目录。 -## 本地检查点评估与推理 +## 基准与预训练结果 -以下命令使用本地训练生成的 `model_best.pt`。请先评估检查点,再用于推理。 +在 `v0.3.11` 的 10 种子 `C10` 基准(`seeds 1..10`,`-B 2048`,上限 `1200` 轮)中,**8/10** 个种子通过独立盲测(`seed = 18000 + s`,64 回合成功率 ≥98%、最大下压 ≤1.0 mm)与单环境 `GLB` 回放,通过种子合计盲测成功率 **`508/512 (99.22%)`**,全种子 `ik_rejects = 0.00`(其中 4 个种子 `64/64 = 100.0%`,4 个种子 `63/64 = 98.44%`)。 + +托管于 Hugging Face 的预训练检查点(`pick_place/xarm6-pick-place/seed-7/model_best.pt`,第 `650` 轮早停)已在 Colab L4 与本地 **NVIDIA GeForce RTX 4060 Ti (8 GB)** 上双重验证通过: + +| 机械臂 + 夹爪 | 观测 / 动作维 | 检查点 | 双验证集 (`17000` / `17500`) | 独立盲测 (`18007`, 64 回合) | 最大下压 (`18007`) | 落点误差均值 / 中位 (`18007`) | GLB `B=1` 回放 | +|---|---:|---|---|---|---|---|---| +| `xarm6` + `gripper_g2` | 70 / 4 | `seed-7/model_best.pt` | **100%** (64/64) / **100%** (128/128) | **100%** (64/64) | `0.477 mm` (≤1.0 mm) | `6.98` / `6.14 mm` (≤20 mm) | **PASS** | + +## 评估与推理 + +如果不需要在本地从零训练,可先从 Hugging Face([`UFACTORY-Developer/ufactory_genesis_rl`](https://huggingface.co/UFACTORY-Developer/ufactory_genesis_rl))下载预训练检查点到 `outputs/rl/pick_place/`: + +```bash +# 如未安装 Hugging Face CLI,先执行:pip install huggingface_hub +hf download UFACTORY-Developer/ufactory_genesis_rl --include "pick_place/**" --local-dir outputs/rl +``` + +以下命令以下载后的 `outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt` 为例(若使用本地训练结果,将 `--checkpoint` 替换为 `outputs/rl/pick_place/pick_place_e2e_s1/model_best.pt` 或传入 `-e pick_place_e2e_s1`)。请先评估检查点,再用于推理。 ### 评估 -以下示例评估种子 1 的最佳检查点,要求 64 回合成功率 ≥98%、最大下压 ≤1 mm: +以下示例评估预训练种子 7 的最佳检查点,要求 64 回合成功率 ≥98%、最大下压 ≤1 mm: ```bash python -m examples.rl.pick_place.evaluate \ - --checkpoint outputs/rl/pick_place/pick_place_e2e_s1/model_best.pt \ - -B 32 --episodes 64 --seed 18001 \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ + -B 32 --episodes 64 --seed 18007 \ --min-success-rate 0.98 --max-press-mm 1.0 \ - --quiet-episodes --out outputs/rl/pick_place/pick_place_e2e_s1/test.json + --quiet-episodes --out outputs/rl/pick_place/xarm6-pick-place/seed-7/test.json ``` `--out` 同时生成 JSON 汇总和 CSV 逐回合结果;未达到门限时命令返回退出码 `1`。 @@ -70,14 +87,16 @@ python -m examples.rl.pick_place.evaluate \ ```bash # 打开交互窗口 -python -m examples.rl.pick_place.visualize -e pick_place_e2e_s1 -B 1 +python -m examples.rl.pick_place.visualize \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt -B 1 # 无头录制单回合视频 python -m examples.rl.pick_place.visualize \ - -e pick_place_e2e_s1 -B 1 --episodes 1 --headless \ - --record outputs/rl/pick_place/pick_place_e2e_s1/replay.mp4 + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ + -B 1 --episodes 1 --headless \ + --record outputs/rl/pick_place/xarm6-pick-place/seed-7/replay.mp4 ``` -`-e` 指定实验名,默认加载对应目录中的 `model_best.pt`;也可使用 `--checkpoint` 指定文件。`--headless` 无需桌面窗口,`--record` 指定 MP4 输出路径。 +`-e` 指定 `outputs/rl/pick_place/` 下的实验名,默认加载对应目录中的 `model_best.pt`;也可使用 `--checkpoint` 显式指定检查点文件。`--headless` 无需桌面窗口,`--record` 指定 MP4 输出路径。检查点、`config.yaml` 与 `model_best.checkpoint_manifest.json` 需放在同一目录。 单独运行 `train`、`evaluate` 或 `visualize` 时,可用 `--recipe`、`--runtime-config` 指定训练配方和场景配置。检查点会校验配置;修改任务配置后需重新训练。 diff --git a/examples/rl/pick_place/env.py b/examples/rl/pick_place/env.py index f8fd5f3..b5b3ebf 100644 --- a/examples/rl/pick_place/env.py +++ b/examples/rl/pick_place/env.py @@ -26,18 +26,20 @@ from ufactory.simulation.g2_model import G2Model from ufactory.training.logic.common import action_penalty as _quadratic_penalty from ufactory.training.pick_place_config import ( - PICK_PLACE_ACTION_CONTRACT, HOME_EE_POS, - TABLE_SIZE, - TABLE_POS, - TARGET_PAD_SIZE, - TARGET_PAD_POS, - PICK_PLACE_ROBOT, - PICK_PLACE_URDF, + PICK_PLACE_ACTION_CONTRACT, PICK_PLACE_CONTROL, PICK_PLACE_ENV_VERSION, PICK_PLACE_NUM_ACTIONS, PICK_PLACE_NUM_OBS, + PICK_PLACE_ROBOT, + PICK_PLACE_URDF, + PRE_LIFT_PAD_FLOOR_Z, + TABLE_POS, + TABLE_SIZE, + TARGET_PAD_POS, + TARGET_PAD_SIZE, + TOUCHDOWN_REF_MARGIN_Z, ) from ufactory.visualization import start_deferred_viewer from ufactory.visualization.glb import glb_pbr_surfaces, glb_view_surface @@ -52,18 +54,18 @@ PRESS_LIMIT_M, RELEASE_MAX_HEIGHT_M, SAFE_LIFT_Z, - cube_clearance, - grasp_distance, - PickPlaceMetrics, SPAWN_X, - SPAWN_Y, SPAWN_XY_LOWER, SPAWN_XY_UPPER, + SPAWN_Y, SUCCESS_HOLD_STEPS, SUPPORT_FORCE_N, TARGET_X, TARGET_Y, TILT_LIMIT_DEG, + PickPlaceMetrics, + cube_clearance, + grasp_distance, ) ENV_VERSION = PICK_PLACE_ENV_VERSION @@ -310,7 +312,9 @@ def __init__( ) self.ep_return = torch.zeros(self.num_envs, device=self.device, dtype=gs.tc_float) self.contact_rewarded = torch.zeros(self.num_envs, device=self.device, dtype=torch.bool) + self.touchdown_rewarded = torch.zeros(self.num_envs, device=self.device, dtype=torch.bool) self.place_rewarded = torch.zeros(self.num_envs, device=self.device, dtype=torch.bool) + self.pre_lift_grip_steps = torch.zeros(self.num_envs, device=self.device, dtype=torch.long) self.ik_rejects = torch.zeros(self.num_envs, device=self.device, dtype=gs.tc_float) self.default_spawn_xy = torch.tensor([[SPAWN_X, SPAWN_Y]], device=self.device, dtype=gs.tc_float) @@ -319,9 +323,17 @@ def __init__( self.fixed_cursor = 0 self.extras: dict[str, Any] = {"observations": {}} self.reset() + self._derive_flange_height_limits() if show_viewer: start_deferred_viewer(self.scene) + def _derive_flange_height_limits(self) -> None: + """Derive flange-height limits directly from the loaded Gripper G2 pad geometry.""" + left, right = pad_centers(self.g2_model, self.left_finger_link, self.right_finger_link) + flange_to_pad_z = float((self.ee_link.get_pos()[:, 2] - (left[:, 2] + right[:, 2]) / 2).mean()) + self.pre_lift_flange_floor_z = PRE_LIFT_PAD_FLOOR_Z + flange_to_pad_z + self.touchdown_ref_ee_z = self.pre_lift_flange_floor_z + TOUCHDOWN_REF_MARGIN_Z + def training_state_dict(self) -> dict[str, Any]: return { "schema_version": 3, @@ -397,7 +409,9 @@ def reset_idx(self, idx: torch.Tensor) -> None: self.episode_length_buf, self.ep_return, self.contact_rewarded, + self.touchdown_rewarded, self.place_rewarded, + self.pre_lift_grip_steps, self.ik_rejects, ): buf[idx] = 0 @@ -466,10 +480,11 @@ def _apply_action(self, actions: torch.Tensor, current_measured_gap: torch.Tenso contact_steps = getattr(self.metrics, "contact_steps", torch.zeros_like(self.metrics.hold_steps)) ever_carried = getattr(self.metrics, "ever_carried", torch.zeros_like(self.metrics.ever_lifted_clear)) gripping_pre_lift = pre_lift & ((contact_steps >= 3) | ever_carried) + pre_lift_floor = getattr(self, "pre_lift_flange_floor_z", 0.1833) pre_lift_min_sp_z = torch.where( gripping_pre_lift, - torch.maximum(base_setpoint[:, 2], ee[:, 2] + 0.0036).clamp(min=0.1818), - torch.full_like(ee[:, 2], 0.1818), + torch.maximum(base_setpoint[:, 2], ee[:, 2] + 0.0036).clamp(min=pre_lift_floor), + torch.full_like(ee[:, 2], pre_lift_floor), ) base_setpoint = base_setpoint.clone() base_setpoint[:, 2] = torch.where( @@ -479,6 +494,8 @@ def _apply_action(self, actions: torch.Tensor, current_measured_gap: torch.Tenso ) actions = actions.clone() actions[:, 2] = torch.where(gripping_pre_lift, actions[:, 2].clamp(min=0.0), actions[:, 2]) + lift_off_xy_damp = gripping_pre_lift & (height < 0.015) + actions[:, :2] = torch.where(lift_off_xy_damp[:, None], actions[:, :2] * 0.35, actions[:, :2]) near_place = self.metrics.ever_lifted_clear & (height <= self.near_table_m) if near_place.any(): table_ee_z = torch.maximum(self.metrics.touchdown_ee_z, ee[:, 2] - height) @@ -504,9 +521,34 @@ def _apply_action(self, actions: torch.Tensor, current_measured_gap: torch.Tenso actions[:, 2] = torch.where(near_place, dz_cmd, actions[:, 2]) hold_xy = at_release_table & (~self.metrics.release_confirmed) actions[:, :2] = torch.where(hold_xy[:, None], actions[:, :2] * 0.25, actions[:, :2]) + if hasattr(self, "metrics") and hasattr(self, "obj"): + # Zero-penalty outer-margin linear spring keeps targets well inside the + # reachable IK envelope with full-rank action Jacobian (no clamp dead zones). + base_setpoint = base_setpoint.clone() + dx_lo = (0.275 - base_setpoint[:, 0]).clamp(min=0.0) + dx_hi = (base_setpoint[:, 0] - 0.515).clamp(min=0.0) + base_setpoint[:, 0] = base_setpoint[:, 0] + 0.16 * dx_lo - 0.16 * dx_hi + dy_lo = (-0.215 - base_setpoint[:, 1]).clamp(min=0.0) + dy_hi = (base_setpoint[:, 1] - 0.315).clamp(min=0.0) + base_setpoint[:, 1] = base_setpoint[:, 1] + 0.16 * dy_lo - 0.16 * dy_hi + r_sp = torch.linalg.vector_norm(base_setpoint[:, :2], dim=-1, keepdim=True).clamp(min=1e-9) + r_pull = (r_sp - 0.542).clamp(min=0.0) * 0.22 + base_setpoint[:, :2] = base_setpoint[:, :2] * ((r_sp - r_pull).clamp(min=0.0) / r_sp) + z_soft_ceil = torch.where(~self.metrics.ever_lifted_clear, 0.304, 0.262) + dz_hi = (base_setpoint[:, 2] - z_soft_ceil).clamp(min=0.0) + base_setpoint[:, 2] = base_setpoint[:, 2] - 0.16 * dz_hi target = base_setpoint + actions[:, :3] * self.action_scale if hasattr(self, "metrics") and hasattr(self, "obj"): - target[:, 2] = torch.where(~self.metrics.ever_lifted_clear, target[:, 2].clamp(min=0.1818), target[:, 2]) + pre_lift_floor = getattr(self, "pre_lift_flange_floor_z", 0.1833) + target[:, 0] = target[:, 0].clamp(min=0.225, max=0.550) + target[:, 1] = target[:, 1].clamp(min=-0.252, max=0.350) + r_xy = torch.linalg.vector_norm(target[:, :2], dim=-1, keepdim=True).clamp(min=1e-9) + target[:, :2] = target[:, :2] * (0.568 / r_xy).clamp(max=1.0) + target[:, 2] = torch.where( + ~self.metrics.ever_lifted_clear, + target[:, 2].clamp(min=pre_lift_floor, max=0.340), + target[:, 2].clamp(max=0.305), + ) if near_place is not None and table_sp_z is not None: target[:, 2] = torch.where(near_place, torch.maximum(target[:, 2], table_sp_z), target[:, 2]) target = torch.maximum(torch.minimum(target, self.workspace_upper), self.workspace_lower) @@ -522,12 +564,16 @@ def _apply_action(self, actions: torch.Tensor, current_measured_gap: torch.Tenso self.q_target = torch.where(accepted[:, None], q, self.q_target) self.robot.control_dofs_position(self.q_target, self.arm_dof_idx) base_gap = self.gap_cmd + gap_act = actions[:, 3] if at_release_table is not None: opening_at_table = at_release_table & (actions[:, 3] > 0) & (self.gap_cmd < current_measured_gap) base_gap = torch.where(opening_at_table, current_measured_gap, base_gap) - self.gap_cmd = (base_gap + actions[:, 3] * self.gap_action_scale).clamp( - self.close_floor_gap_m, GRIPPER_G2_OPEN_GAP_M - ) + unclamping_at_table = at_release_table & ( + (base_gap >= current_measured_gap - 5e-4) + | (self.metrics.release_confirmed & (~self.metrics.high_release)) + ) + gap_act = torch.where(unclamping_at_table, gap_act.clamp(min=0.0), gap_act) + self.gap_cmd = (base_gap + gap_act * self.gap_action_scale).clamp(self.close_floor_gap_m, GRIPPER_G2_OPEN_GAP_M) self.g2_controller.command(self.gap_cmd * 1000, self.g2_speed_percent, self.g2_force_percent) apply_batch_control( self.robot, @@ -599,7 +645,7 @@ def _potential(self) -> torch.Tensor: ) * floor_gate pregrasp_kernel = 1.125 * torch.exp(-distance / 0.040) * pregrasp_gap * floor_gate target_near = torch.exp(-target_error / 0.04) - place_approach = 0.75 * target_near + 0.25 * torch.exp(-target_error / 0.18) + place_approach = 0.70 * target_near + 0.30 * torch.exp(-target_error / 0.24) target_zone = torch.exp(-(target_error - 0.015).clamp(min=0) / 0.04) lifted = self.metrics.ever_lifted_clear.float() place_height_err = (height - self.metrics.place_clearance).clamp(min=0) @@ -608,7 +654,11 @@ def _potential(self) -> torch.Tensor: meas_open = ((current_gap - CUBE_SIZE) / (self.pre_grasp_gap_m - CUBE_SIZE)).clamp(0, 1) if hasattr(self, "ee_link"): ee_z = self.ee_link.get_pos()[:, 2] - ref_ee_z = torch.where(self.metrics.touchdown_ee_z > 0, self.metrics.touchdown_ee_z, 0.184) + ref_ee_z = torch.where( + self.metrics.touchdown_ee_z > 0, + self.metrics.touchdown_ee_z, + getattr(self, "touchdown_ref_ee_z", 0.1855), + ) has_td_ref = ((self.metrics.touchdown_ee_z > 0) | self.metrics.release_confirmed) & at_table ee_sink = torch.where( has_td_ref, @@ -624,7 +674,7 @@ def _potential(self) -> torch.Tensor: 0, 1 ) action_open = (0.5 * (self.last_actions[:, 3] + 1.0)).clamp(0, 1) - open_drive = 0.85 * cmd_open + 0.15 * action_open + open_drive = 0.65 * cmd_open + 0.35 * action_open release_zone = place_zone * torch.maximum(open_drive, meas_open) approach_term = torch.maximum( approach_kernel * torch.where(at_table, table_guard, 1.0), @@ -647,7 +697,12 @@ def _potential(self) -> torch.Tensor: max_lift = (self.metrics.max_held_z - CUBE_REST_Z).clamp(0, SAFE_LIFT_Z - CUBE_REST_Z) current_lift = torch.where((self.forces > 0.05).all(-1), height.clamp(0, SAFE_LIFT_Z - CUBE_REST_Z), 0.0) lift_progress = torch.where(self.metrics.ever_lifted_clear, max_lift, 0.75 * current_lift + 0.25 * max_lift) - transit_xy_progress = (init_target_dist - target_error).clamp(min=-0.05) + contact_steps = getattr(self.metrics, "contact_steps", torch.zeros_like(self.metrics.hold_steps)) + ever_carried = getattr(self.metrics, "ever_carried", torch.zeros_like(self.metrics.ever_lifted_clear)) + gripping_pre_lift = (~self.metrics.ever_lifted_clear) & ((contact_steps >= 3) | ever_carried) + lift_action_up = (0.5 * (self.last_actions[:, 2] + 1.0)).clamp(0, 1) + lift_drive = torch.where(self.metrics.ever_lifted_clear, 1.0, gripping_pre_lift.float() * lift_action_up) + transit_xy_progress = (init_target_dist - target_error).clamp(min=-0.50) excess_height = (height - (SAFE_LIFT_Z - CUBE_REST_Z)).clamp(min=0) s = self.reward_scales return ( @@ -655,12 +710,26 @@ def _potential(self) -> torch.Tensor: + float(s.get("pregrasp_potential", 4)) * pregrasp + float(s.get("grasp_potential", 4)) * grasp_or_place + float(s.get("lift_potential", 40)) * lift_progress - + float(s.get("transit_potential", 8)) * lifted * (transit_xy_progress - 0.8 * excess_height) - + float(s.get("place_potential", 6)) * lifted * place_approach / (1 + place_height_err / 0.10) + + float(s.get("lift_drive_potential", 1.2)) * lift_drive + + float(s.get("transit_potential", 8)) * lifted * (transit_xy_progress - 1.8 * excess_height) + + float(s.get("place_potential", 9)) + * lifted + * ( + place_approach / (1 + place_height_err / 0.08) + + 0.45 * target_zone * torch.exp(-place_height_err / 0.045) + ) + float(s.get("release_potential", 4)) * place_zone * open_drive + float(s.get("hold_potential", 6)) * (0.5 * place_zone * meas_open + 0.5 * hold_progress) ) + def _lift_only_potential(self) -> torch.Tensor: + """Lift-height potential alone; zero on the table so pre-lift timeout keeps partial lift credit only.""" + height = cube_clearance(self.obj.get_pos(), self.obj.get_quat()).clamp(min=0) + max_lift = (self.metrics.max_held_z - CUBE_REST_Z).clamp(0, SAFE_LIFT_Z - CUBE_REST_Z) + current_lift = torch.where((self.forces > 0.05).all(-1), height.clamp(0, SAFE_LIFT_Z - CUBE_REST_Z), 0.0) + lift_progress = torch.where(self.metrics.ever_lifted_clear, max_lift, 0.75 * current_lift + 0.25 * max_lift) + return float(self.reward_scales.get("lift_potential", 40)) * lift_progress + def _action_penalty(self, raw_actions: torch.Tensor) -> torch.Tensor: bounded = raw_actions.clamp(-self.action_clip, self.action_clip) excess = (raw_actions - bounded).clamp(-5.0, 5.0) @@ -737,13 +806,56 @@ def step(self, actions: torch.Tensor) -> tuple[TensorDict, torch.Tensor, torch.T status["first_release"] & status["in_target_xy"] & (~self.metrics.high_release) & (~self.place_rewarded) ) self.place_rewarded |= first_place - # Terminal potential is zero on failure or timeout so discounted shaping - # cannot pay for a loop or for deliberately ending an episode early. - potential = torch.where(done & (~success), 0, self._potential()) + raw_potential = self._potential() + lift_only_potential = self._lift_only_potential() + at_table_target_touchdown = ( + self.metrics.ever_lifted_clear + & (self.metrics.touchdown_seen | self.metrics.release_confirmed | self.place_rewarded) + & (self.metrics.target_error <= 0.060) + & (~status["collision_failed"]) + ) + post_lift_timeout = ( + timeout & self.metrics.ever_lifted_clear & (~failed) & (~success) & (~at_table_target_touchdown) + ) + post_lift_noncol_fail = ( + failed & self.metrics.ever_lifted_clear & (~status["collision_failed"]) & (~at_table_target_touchdown) + ) + pre_lift_timeout = timeout & (~failed) & (~success) & (~self.metrics.ever_lifted_clear) + potential = torch.where( + done & (~success), + torch.where( + at_table_target_touchdown, + torch.where( + self.metrics.release_confirmed | self.place_rewarded, + (raw_potential - 0.5).clamp(min=0.0), + (raw_potential - 3.5).clamp(min=0.0), + ), + torch.where( + post_lift_timeout, + (raw_potential - 1.5).clamp(min=0.0), + torch.where( + post_lift_noncol_fail, + torch.minimum(raw_potential, torch.full_like(raw_potential, 6.0)), + torch.where(pre_lift_timeout, lift_only_potential, 0.0), + ), + ), + ), + raw_potential, + ) reward = self.reward_gamma * potential - old_potential - float(s.get("step_penalty", 0.005)) reward += first_contact.float() * float(s.get("first_contact", 2)) reward += status["first_carry"].float() * float(s.get("first_carry", 3)) reward += status["first_lift_clear"].float() * float(s.get("first_lift", 6)) + first_target_touchdown = ( + status["first_touchdown"] + & (~self.touchdown_rewarded) + & (self.metrics.target_error <= 0.060) + & status["quality_ok"] + & (~status["collision_failed"]) + ) + self.touchdown_rewarded |= first_target_touchdown + td_xy_quality = torch.exp(-(self.metrics.target_error - 0.015).clamp(min=0) / 0.025) + reward += first_target_touchdown.float() * float(s.get("first_touchdown", 8)) * (0.25 + 0.75 * td_xy_quality) reward += first_place.float() * float(s.get("first_place", 10)) at_release_table = ( (self.metrics.clearance <= 0.0005) | self.metrics.touchdown_seen | self.metrics.release_confirmed @@ -762,16 +874,43 @@ def step(self, actions: torch.Tensor) -> tuple[TensorDict, torch.Tensor, torch.T 0.0, ) reward -= float(s.get("fast_descent_penalty", 10)) * torch.where(near_held, fast_descent + lateral_excess, 0) - reward -= float(s.get("press_penalty", 3000)) * status["press_increment"] + capped_press = self.metrics.max_press.clamp(max=0.0028) + prev_press = (self.metrics.max_press - status["press_increment"]).clamp(min=0.0, max=0.0028) + capped_inc = (capped_press - prev_press).clamp(min=0.0) + excess_press_inc = (capped_press - 0.0005).clamp(min=0.0) - (prev_press - 0.0005).clamp(min=0.0) + reward -= float(s.get("press_penalty", 3000)) * (0.25 * capped_inc + 0.75 * excess_press_inc) reward -= float(s.get("recontact_penalty", 0)) * status["recontact"].float() - overload = (self.table_force - self.object_mass_kg * 9.81 - self.table_overload_margin_n).clamp(min=0) - reward -= float(s.get("table_overload_penalty", 0.1)) * torch.where(near_held, overload, 0) * self.ctrl_dt + overload = (self.table_force - self.object_mass_kg * 9.81 - self.table_overload_margin_n).clamp( + min=0.0, max=40.0 + ) + reward -= float(s.get("table_overload_penalty", 0.1)) * torch.where(near_held, overload, 0.0) * self.ctrl_dt reward -= ( float(s.get("high_release_penalty", 10)) * (status["first_release"] & self.metrics.high_release).float() ) - reward -= float(s.get("robot_table_penalty", 1)) * self.robot_table_force * self.ctrl_dt + reward -= float(s.get("robot_table_penalty", 1)) * self.robot_table_force.clamp(max=150.0) * self.ctrl_dt reward -= action_penalty - reward += float(s.get("success", 40)) * success.float() - float(s.get("failure_penalty", 10)) * failed.float() + unreleased_timeout = timeout & (~success) & (~self.metrics.ever_lifted_clear) + stalled_pre_lift_grip = ( + (~self.metrics.ever_carried) & status["stable_contact"] & (self.metrics.clearance < 0.015) + ) + self.pre_lift_grip_steps = torch.where(stalled_pre_lift_grip, self.pre_lift_grip_steps + 1, 0) + stall_grace_steps = int(self.env_cfg.get("pre_lift_stall_grace_steps", 30)) + reward -= float(s.get("pre_lift_stall_penalty", 0.04)) * (self.pre_lift_grip_steps > stall_grace_steps).float() + pre_lift_clawback = ( + (failed | unreleased_timeout) & (~self.metrics.ever_carried) & self.contact_rewarded + ).float() * float(s.get("first_contact", 2)) + reward -= pre_lift_clawback + fail_pen = torch.where( + self.metrics.ever_lifted_clear, + torch.where( + status["collision_failed"], + float(s.get("failure_penalty", 10)), + float(s.get("post_lift_failure_penalty", 6.0)), + ), + float(s.get("pre_lift_failure_penalty", 4.0)), + ) + penalized_fail = failed | unreleased_timeout + reward += float(s.get("success", 40)) * success.float() - fail_pen * penalized_fail.float() self.ep_return += reward terminal = { "success": success.clone(), @@ -810,7 +949,9 @@ def step(self, actions: torch.Tensor) -> tuple[TensorDict, torch.Tensor, torch.T "scenario_id": self.scenario_id.clone(), "ik_rejects": self.ik_rejects.clone(), } - info: dict[str, Any] = {"episode": {}, "terminal": terminal, "time_outs": timeout & ~success & ~failed} + # Remaining time is explicitly observed (dim 69), so finite-horizon timeouts + # are true terminal states and must not be bootstrapped by RSL-RL. + info: dict[str, Any] = {"episode": {}, "terminal": terminal, "time_outs": torch.zeros_like(timeout)} if done.any(): idx = done.nonzero(as_tuple=False).squeeze(-1) info["episode"] = { diff --git a/examples/rl/pick_place/recipe.yaml b/examples/rl/pick_place/recipe.yaml index 378c02e..fef8780 100644 --- a/examples/rl/pick_place/recipe.yaml +++ b/examples/rl/pick_place/recipe.yaml @@ -1,4 +1,4 @@ -# End-to-end tabletop pick-and-place, pure PPO from the fixed home pose. +# End-to-end tabletop pick-and-place, pure PPO from the fixed home pose (C10 seed-stability recipe). schema_version: 1 environment: task_name: pick_place @@ -30,23 +30,27 @@ reward: pregrasp_potential: 4.0 grasp_potential: 4.0 lift_potential: 40.0 + lift_drive_potential: 1.2 transit_potential: 8.0 - place_potential: 6.0 - release_potential: 4.0 - hold_potential: 6.0 - first_contact: 2.0 + place_potential: 9.0 + release_potential: 8.0 + hold_potential: 8.0 + first_contact: 3.0 first_lift: 6.0 first_place: 10.0 success: 40.0 failure_penalty: 10.0 + pre_lift_failure_penalty: 4.0 + post_lift_failure_penalty: 6.0 + pre_lift_stall_penalty: 0.04 fast_descent_penalty: 10.0 press_penalty: 3000.0 recontact_penalty: 5.0 table_overload_penalty: 0.1 - high_release_penalty: 10.0 + high_release_penalty: 14.0 robot_table_penalty: 1.0 action_penalty: 0.001 - action_saturation_penalty: 0.0 + action_saturation_penalty: 0.05 step_penalty: 0.005 train: algorithm: @@ -74,6 +78,7 @@ train: class_name: GaussianDistribution init_std: 0.50 std_type: scalar + std_range: [0.16, 0.65] critic: class_name: MLPModel hidden_dims: [256, 256] diff --git a/examples/rl/pick_place/train.py b/examples/rl/pick_place/train.py index 3c09d1e..0926a67 100644 --- a/examples/rl/pick_place/train.py +++ b/examples/rl/pick_place/train.py @@ -6,6 +6,7 @@ from copy import deepcopy import json import math +import os from pathlib import Path from typing import Any @@ -58,6 +59,17 @@ def _install_fixed_learning_rate_guard(runner: Any, train_cfg: dict[str, Any]) - def guarded_update(*args: Any, **kwargs: Any) -> Any: result = original_update(*args, **kwargs) + if hasattr(runner.alg, "actor"): + dist = getattr(runner.alg.actor, "distribution", None) + with torch.no_grad(): + if dist is not None and hasattr(dist, "std_param"): + dist.std_param.clamp_(min=0.16, max=0.65) + elif dist is not None and hasattr(dist, "log_std_param"): + dist.log_std_param.clamp_(min=math.log(0.16), max=math.log(0.65)) + elif hasattr(runner.alg.actor, "std"): + runner.alg.actor.std.clamp_(min=0.16, max=0.65) + elif hasattr(runner.alg.actor, "log_std"): + runner.alg.actor.log_std.clamp_(min=math.log(0.16), max=math.log(0.65)) actual_lr = float(runner.alg.learning_rate) group_lrs = [float(group["lr"]) for group in runner.alg.optimizer.param_groups] if not math.isclose(actual_lr, expected_lr, rel_tol=1e-9, abs_tol=1e-12) or any( @@ -71,6 +83,22 @@ def guarded_update(*args: Any, **kwargs: Any) -> Any: runner.alg.update = guarded_update +def _recent_training_stable(log_dir: Path, window: int = 15) -> bool: + metrics_path = log_dir / "training_metrics.jsonl" + if not metrics_path.is_file(): + return True + rows = [json.loads(line) for line in metrics_path.read_text(encoding="utf-8").splitlines() if line.strip()] + valid = [r.get("episode", {}) for r in rows if int(r.get("completed_episodes", 0)) >= 32] + recent = valid[-window:] if valid else [r.get("episode", {}) for r in rows[-window:]] + if not recent: + return True + mean_sr = sum(float(ep.get("success_rate", 0.0)) for ep in recent) / len(recent) + mean_col_press = sum( + float(ep.get("collision_failed", 0.0)) + float(ep.get("press_failed", 0.0)) for ep in recent + ) / len(recent) + return mean_sr >= 0.88 and mean_col_press <= 0.035 + + def _provenance_sources(repo_root: Path) -> list[Path]: return [ Path(__file__).resolve(), @@ -111,6 +139,7 @@ def main() -> None: parser.add_argument("--backend", choices=("gpu", "cpu"), default="gpu") parser.add_argument("--eval-episodes", type=int, default=64) parser.add_argument("--eval-interval", type=int, default=50) + parser.add_argument("--eval-start-iteration", type=int, default=0) parser.add_argument( "--early-stop-evaluations", type=int, help="Consecutive passing evaluations before stopping; 0 disables" ) @@ -128,8 +157,12 @@ def main() -> None: if args.early_stop_evaluations is not None and args.early_stop_evaluations < 0: parser.error("--early-stop-evaluations must be non-negative") - torch.set_num_threads(4) + num_threads = max(1, int(os.environ.get("OMP_NUM_THREADS", "4"))) + torch.set_num_threads(num_threads) torch.set_float32_matmul_precision("high") + if torch.cuda.is_available(): + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True recipe = load_training_recipe(args.recipe) early_stop_evaluations = int( @@ -229,10 +262,11 @@ def main() -> None: if "ufactory_env_state" in infos: env.load_training_state_dict(infos["ufactory_env_state"]) - best_score = (-1.0, -1.0, -1.0, float("-inf"), float("-inf")) + best_score = (-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, float("-inf"), float("-inf")) + passing_evaluations = 0 def validate(tag: str) -> dict[str, Any]: - nonlocal best_score + nonlocal best_score, passing_evaluations actor = runner.get_inference_policy(device=gs.device) def _policy(obs: Any) -> torch.Tensor: @@ -240,9 +274,49 @@ def _policy(obs: Any) -> torch.Tensor: summary, rows = evaluate(env, _policy, episodes=args.eval_episodes, seed=17000) summary["passed"] = acceptance_passed(summary) + holdout_passed = False + combined_sr = float(summary["success_rate"]) + combined_press = float(summary["press_mm"]["max"]) + if summary["passed"] and tag != "initial": + holdout_eps = max(128, int(args.eval_episodes) * 2) + holdout_summary, _ = evaluate(env, _policy, episodes=holdout_eps, seed=17500) + holdout_passed = acceptance_passed(holdout_summary) + total_eps = float(args.eval_episodes + holdout_eps) + combined_sr = ( + float(summary["success_rate"]) * args.eval_episodes + + float(holdout_summary["success_rate"]) * holdout_eps + ) / total_eps + combined_press = max(combined_press, float(holdout_summary["press_mm"]["max"])) + summary["holdout_17500"] = { + "episodes": holdout_eps, + "success_rate": float(holdout_summary["success_rate"]), + "max_press_mm": float(holdout_summary["press_mm"]["max"]), + "passed": holdout_passed, + } + both_passed = bool(summary["passed"] and holdout_passed) + stable_pass = bool( + both_passed and combined_sr >= 0.994 and combined_press <= 0.8 and _recent_training_stable(log_dir) + ) + summary["both_passed"] = both_passed + summary["stable_pass"] = stable_pass + summary["combined_sr"] = combined_sr + summary["combined_press_mm"] = combined_press + if tag != "initial": + passing_evaluations = passing_evaluations + 1 if stable_pass else 0 save_results(log_dir / f"evaluation_{tag}.json", summary, rows) print(f"STRICT EVAL {tag}: {json.dumps(summary)}", flush=True) - score = checkpoint_score(summary) + streak_tier = min(passing_evaluations, early_stop_evaluations) if early_stop_evaluations else int(stable_pass) + base_cs = checkpoint_score(summary) + score = ( + float(both_passed), + float(stable_pass), + float(streak_tier), + combined_sr, + base_cs[1], + base_cs[2], + -combined_press, + base_cs[4], + ) if score > best_score: best_score = score runner.save(str(log_dir / "model_best.pt"), infos={"validation": summary, "stage": tag}) @@ -253,17 +327,17 @@ def _policy(obs: Any) -> torch.Tensor: runner.logger.cur_episode_length.zero_() return summary - validate("initial") + if args.eval_start_iteration <= 0: + validate("initial") remaining = max_iterations completed = 0 - passing_evaluations = 0 while remaining > 0: count = min(args.eval_interval, remaining) runner.learn(num_learning_iterations=count, init_at_random_ep_len=False) remaining -= count completed += count - summary = validate(f"ppo_{completed}") - passing_evaluations = passing_evaluations + 1 if summary["passed"] else 0 + if completed >= args.eval_start_iteration or remaining == 0: + validate(f"ppo_{completed}") if early_stop_evaluations and passing_evaluations >= early_stop_evaluations: break if remaining > 0: @@ -286,8 +360,8 @@ def _policy(obs: Any) -> torch.Tensor: "max_iterations": max_iterations, "early_stopped": remaining > 0, "passing_evaluations": passing_evaluations, - "best_success_rate": best_score[0], - "best_press_mm": -best_score[3], + "best_success_rate": best_score[-5], + "best_press_mm": -best_score[-2], "selected_checkpoint": selected.name, }, indent=2, @@ -297,7 +371,7 @@ def _policy(obs: Any) -> torch.Tensor: encoding="utf-8", ) gs.destroy() - print(f"Completed {completed} iterations: best strict success_rate={best_score[0]:.3f}; {selected}", flush=True) + print(f"Completed {completed} iterations: best strict success_rate={best_score[-5]:.3f}; {selected}", flush=True) if __name__ == "__main__": diff --git a/examples/simulation/pick_place/README.md b/examples/simulation/pick_place/README.md index 3cb0f4a..7f1a47d 100644 --- a/examples/simulation/pick_place/README.md +++ b/examples/simulation/pick_place/README.md @@ -11,11 +11,12 @@ Multi-robot pick-place in Genesis physics simulation or offline trajectory and c | Flag | Values / notes | |------|----------------| | `--robot` | Required: `xarm5` / `xarm6` / `xarm7` / `uf850` / `lite6` | -| `--gripper` | Optional: `default` / `g2` / `bio_gripper_g2` / `lite6` / `robotiq_2f_85` / `robotiq_2f_140` (`bio_gripper_g2` and `robotiq_2f_*` support `xarm5`, `xarm6`, `xarm7`, `uf850`; `bio_gripper_g2` runs the microplate task in `sim` mode only; `robotiq_2f_*` runs on a real controller (`sdk-sim` / `real`) only as `robotiq_2f_85` on `xarm6`, validated on hardware with the 11 mm flange adapter; every other Robotiq combination is `sim` / `dry-run` only) | +| `--gripper` | Optional: `default` / `g2` / `bio_gripper_g2` / `lite6` / `robotiq_2f_85` / `robotiq_2f_140` / `vacuum_gripper` (`bio_gripper_g2`, `robotiq_2f_*`, and `vacuum_gripper` support `xarm5`, `xarm6`, `xarm7`, `uf850`; `bio_gripper_g2` runs the microplate task in `sim`, and `dry-run` / `sdk-sim` / `real` with `--executor servo_j` or `servo_cartesian` (`sdk-sim` / `real` validated on `xarm6` only); `vacuum_gripper` supports `dry-run` / `sdk-sim` / `real` with `--executor servo_j` or `servo_cartesian` (optional `--visual` empty-grasp mirror; no suction physics `sim`), hardware-validated on `xarm5` (plug-in hardware version 1); `robotiq_2f_*` runs on a real controller (`sdk-sim` / `real`) only as `robotiq_2f_85` on `xarm6`, validated on hardware with the 11 mm flange adapter; every other Robotiq combination is `sim` / `dry-run` only) | +| `--vacuum-hardware-version` | Optional: `1` (plug-in `TGPIO 0/1`, default) or `2` (contact `TGPIO 3/4`) for `--gripper vacuum_gripper` | | `--mode` | Required for simulation: `sim` (Genesis physics), `dry-run` (offline trajectory and collision preflight) | -| `--executor` | `servo_j` or `servo_cartesian`; Bio G2 defaults to `servo_cartesian`, required for other grippers | +| `--executor` | `servo_j` or `servo_cartesian`; Bio G2 defaults to `servo_cartesian` in `sim`, required for non-`sim` modes and other grippers | | `--backend` | Optional: `cpu` / `gpu`; overrides `simulation.backend` (use `cpu` without a Genesis-supported GPU) | -| `--visual` | Optional: open the Genesis viewer in `sim` mode | +| `--visual` | Optional: open the Genesis viewer in `sim` mode, or an async kinematic mirror viewer in `real` mode (Bio G2 runs as empty grasp without carrying the cube) | | `--config` | Optional strict partial overlay YAML | | `--print-config` | Print resolved runtime YAML and exit | | `--report` | Optional report output path | @@ -39,6 +40,12 @@ python examples/simulation/pick_place/run.py \ python examples/simulation/pick_place/run.py \ --robot xarm6 --gripper bio_gripper_g2 --mode sim --visual +# xArm6 + Bio Gripper G2: offline preflight (servo_j or servo_cartesian) +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode dry-run --executor servo_j +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode dry-run --executor servo_cartesian + # xArm6 + Robotiq 2F-85 / 2F-140: pick-place physics simulation python examples/simulation/pick_place/run.py \ --robot xarm6 --gripper robotiq_2f_85 --mode sim --executor servo_j diff --git a/examples/simulation/pick_place/README_zh.md b/examples/simulation/pick_place/README_zh.md index a8f6a25..b37db02 100644 --- a/examples/simulation/pick_place/README_zh.md +++ b/examples/simulation/pick_place/README_zh.md @@ -11,11 +11,12 @@ | 参数 | 取值 / 说明 | | ---------------- | ---------------------------------------------------------------- | | `--robot` | 必选:`xarm5` / `xarm6` / `xarm7` / `uf850` / `lite6` | -| `--gripper` | 可选:`default` / `g2` / `bio_gripper_g2` / `lite6` / `robotiq_2f_85` / `robotiq_2f_140`(`bio_gripper_g2`、`robotiq_2f_*` 支持 `xarm5`、`xarm6`、`xarm7`、`uf850`;`bio_gripper_g2` 为微孔板任务,仅用于 `sim`;`robotiq_2f_*` 连接真实控制器(`sdk-sim` / `real`)目前只支持 `xarm6` + `robotiq_2f_85`,已在硬件上验证(含 11 mm 法兰转接件);其他 Robotiq 组合只支持 `sim` / `dry-run`) | +| `--gripper` | 可选:`default` / `g2` / `bio_gripper_g2` / `lite6` / `robotiq_2f_85` / `robotiq_2f_140` / `vacuum_gripper`(`bio_gripper_g2`、`robotiq_2f_*`、`vacuum_gripper` 支持 `xarm5`、`xarm6`、`xarm7`、`uf850`;`bio_gripper_g2` 在 `sim` 下运行微孔板任务,非 `sim` 模式(`dry-run` / `sdk-sim` / `real`)支持 `--executor servo_j` / `servo_cartesian` 且真机模式仅放行 `xarm6`;`vacuum_gripper` 支持 `dry-run` / `sdk-sim` / `real`(`servo_j` / `servo_cartesian`,可配 `--visual` 空吸镜像,不含物理负压 `sim`),已在 `xarm5`(1 代直插线)上完成真机验证;`robotiq_2f_*` 连接真实控制器(`sdk-sim` / `real`)目前只支持 `xarm6` + `robotiq_2f_85`,已在硬件上验证(含 11 mm 法兰转接件);其他 Robotiq 组合只支持 `sim` / `dry-run`) | +| `--vacuum-hardware-version` | 可选:`1`(1 代插线 `TGPIO 0/1`,默认)或 `2`(2 代触点 `TGPIO 3/4`),配合 `--gripper vacuum_gripper` 使用 | | `--mode` | 仿真必选:`sim`(Genesis 物理仿真)、`dry-run`(离线轨迹与碰撞预检) | -| `--executor` | `servo_j` 或 `servo_cartesian`;Bio G2 默认 `servo_cartesian`,其他夹爪必选 | +| `--executor` | `servo_j` 或 `servo_cartesian`;Bio G2 在 `sim` 下默认 `servo_cartesian`,非 `sim` 模式及其他夹爪必选 | | `--backend` | 可选:`cpu` / `gpu`;覆盖 `simulation.backend`(无 Genesis 支持显卡时用 `cpu`) | -| `--visual` | 可选:`sim` 模式下强制打开 Genesis 查看器视窗 | +| `--visual` | 可选:`sim` 模式下强制打开 Genesis 查看器视窗;`real` 模式下打开异步运动学镜像视窗(Bio G2 为空夹,不搬运方块) | | `--config` | 可选:严格的局部覆盖 YAML 路径 | | `--print-config` | 可选:打印解析后的运行时 YAML 后退出 | | `--report` | 可选:报告输出路径 | @@ -39,6 +40,12 @@ python examples/simulation/pick_place/run.py \ python examples/simulation/pick_place/run.py \ --robot xarm6 --gripper bio_gripper_g2 --mode sim --visual +# xArm6 + Bio Gripper G2:抓放离线轨迹与碰撞预检(支持 servo_j / servo_cartesian) +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode dry-run --executor servo_j +python examples/simulation/pick_place/run.py \ + --robot xarm6 --gripper bio_gripper_g2 --mode dry-run --executor servo_cartesian + # xArm6 + Robotiq 2F-85 / 2F-140:抓放物理仿真 python examples/simulation/pick_place/run.py \ --robot xarm6 --gripper robotiq_2f_85 --mode sim --executor servo_j diff --git a/examples/visualization/view_robot.py b/examples/visualization/view_robot.py index 6dbed51..694f073 100644 --- a/examples/visualization/view_robot.py +++ b/examples/visualization/view_robot.py @@ -4,7 +4,7 @@ import argparse -from ufactory.robots.assembly import accessories, mounting_plate_for +from ufactory.robots.assembly import accessories, ft_sensors, mounting_plate_for from ufactory.robots.paths import robot_visual_glb_urdf from ufactory.robots.registry import get_robot_profile, robot_cli_choices from ufactory.visualization.robot_viewer import run_glb_diagnose, run_glb_viewer @@ -55,6 +55,14 @@ def main() -> None: help="Mount the camera stand (camera_stand) or a camera on it between the flange and the end effector " "(all robots; bare arm or any end effector except --bio-gripper-g2)", ) + parser.add_argument( + "--ft-sensor", + nargs="?", + const="ft_sensor_ai1500", + default=None, + choices=tuple(ft_sensors()), + help="Mount a six-axis F/T sensor on the tool flange (default: ft_sensor_ai1500; xArm5/6/7 and UF850)", + ) parser.add_argument( "--mounting-plate", action="store_true", @@ -157,6 +165,8 @@ def main() -> None: ), None, ) + if args.ft_sensor and not profile.supports_ft_sensor(args.ft_sensor): + parser.error(f"--ft-sensor {args.ft_sensor} is not supported on {args.robot}") if args.camera and not profile.supports_accessory(args.camera, end_effector): parser.error(f"--camera {args.camera} does not fit {args.robot} with {end_effector or 'no end effector'}") @@ -182,6 +192,7 @@ def main() -> None: movable=args.movable, accessory=args.camera, mounting_plate=args.mounting_plate, + ft_sensor=args.ft_sensor, ) floor_z = -mounting_plate_for(profile.key).thickness_m if args.mounting_plate else 0.0 print(f"Loading: {urdf_path}") diff --git a/pyproject.toml b/pyproject.toml index cbafa19..3c42064 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "genesis-ufactory" -version = "0.3.10" +version = "0.3.11" description = "UFACTORY robot models and Genesis simulation utilities" requires-python = ">=3.12" license = {text = "MIT"} diff --git a/scripts/README.md b/scripts/README.md index 5523da0..9ffdf2b 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -6,7 +6,8 @@ | 脚本 | 模块 | 用途 | |------|------|------| -| `gen_kinematics_params.py` | `ufactory.kinematics` | 从机器人控制柜提取逐台运动学 YAML(严格 v0.2.5 校准 schema) | +| `gen_kinematics_params.py` | `ufactory.kinematics.controller_fk` | 从控制器 FK 辨识逐台运动学 YAML(严格 v0.2.5 校准 schema);只读查询,用 100 组未参与辨识的位姿校验,超过 1 mm / 0.5° 不写文件 | +| `ft_sensor_check.py` | `ufactory.hardware.ft_sensor` | 六维力矩传感器真机诊断与验证(`enable` / `disable` 开关采样,`status` 只读查配置/实时力,`zero` 静止置零,`identify-load` / `admittance-test` / `force-test` 需 `--confirm-real`) | 真机 hold 电流/力矩时间序列观察由 `observe-hold-current` 控制台入口(`ufactory.hardware.observe:cli_observe_hold_current`)提供,安装后可直接调用。 diff --git a/scripts/ft_sensor_check.py b/scripts/ft_sensor_check.py new file mode 100644 index 0000000..49eed56 --- /dev/null +++ b/scripts/ft_sensor_check.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Diagnostic and post-installation verification CLI for the xArm six-axis F/T sensor (AI1500). + +Enable / disable F/T sampling (no physical arm motion): + python scripts/ft_sensor_check.py enable --robot xarm6 --ip + python scripts/ft_sensor_check.py disable --robot xarm6 --ip + +Read-only status & wrench streaming: + python scripts/ft_sensor_check.py status --robot xarm6 --ip --duration 5 + +Stationary zeroing: + python scripts/ft_sensor_check.py zero --robot xarm6 --ip + +Load & zero-offset identification (moves the physical arm -> requires --confirm-real): + python scripts/ft_sensor_check.py identify-load --robot xarm6 --ip --confirm-real + +Conservative admittance / force-control verification (requires --confirm-real): + python scripts/ft_sensor_check.py admittance-test --robot xarm6 --ip --confirm-real + python scripts/ft_sensor_check.py force-test --robot xarm6 --ip --confirm-real +""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable, Sequence +from dataclasses import asdict +import json +from pathlib import Path +import time +from typing import Any + +from ufactory.hardware.ft_sensor import ( + FTAdmittanceParams, + FTForceControlParams, + FTSensorReading, + XArmFTSensor, +) +from ufactory.hardware.xarm import verify_controller_robot +from ufactory.robots.assembly import supported_ft_sensors +from ufactory.robots.registry import ROBOT_PROFILES, get_profile_key_for_robot_name + + +def _supported_robot_choices() -> list[str]: + choices: set[str] = set() + for key, profile in ROBOT_PROFILES.items(): + if supported_ft_sensors(key): + choices.add(key) + choices.add(profile.robot_name) + return sorted(choices) + + +def _default_arm_factory(ip: str) -> Any: + from xarm.wrapper import XArmAPI # type: ignore[import-untyped] + + arm = XArmAPI(ip, is_radian=True) + time.sleep(0.5) + if not getattr(arm, "connected", False): + raise ConnectionError(f"Failed to connect to controller at {ip}") + return arm + + +def _add_common_args(parser: argparse.ArgumentParser) -> None: + parser.add_argument("--robot", required=True, choices=_supported_robot_choices(), help="Supported robot model") + parser.add_argument("--ip", required=True, help="xArm controller IP address") + parser.add_argument("--json", action="store_true", help="Print structured JSON output") + + +def _sample_stream( + sensor: XArmFTSensor, + *, + duration_s: float, + rate_hz: float, + is_raw: bool, + from_report: bool, + as_json: bool, +) -> list[dict[str, Any]]: + if duration_s < 0.0: + raise ValueError("duration must be non-negative") + if rate_hz <= 0.0: + raise ValueError("rate_hz must be positive") + period_s = 1.0 / rate_hz + start = time.monotonic() + samples: list[dict[str, Any]] = [] + step = 0 + while True: + reading: FTSensorReading = sensor.read_wrench(is_raw=is_raw, from_report=from_report) + row = { + "t_s": round(time.monotonic() - start, 4), + "wrench": list(reading.wrench), + "overrange": list(reading.overrange), + "overload": list(reading.overload), + } + samples.append(row) + if not as_json: + flags = " OVERLOAD" if reading.any_overload else (" OVERRANGE" if reading.any_overrange else "") + vals = ", ".join(f"{v:8.3f}" for v in reading.wrench) + print(f"[{row['t_s']:6.2f}s] [{vals}]{flags}") + if duration_s <= 0.0 or (time.monotonic() - start) >= duration_s: + break + step += 1 + target = start + step * period_s + remaining = target - time.monotonic() + if remaining > 0.0: + time.sleep(remaining) + return samples + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="command", required=True) + + p_status = sub.add_parser("status", help="Read-only F/T status, config, and optional wrench stream") + _add_common_args(p_status) + p_status.add_argument("--duration", type=float, default=0.0, help="Stream duration in seconds (0 = single reading)") + p_status.add_argument("--rate-hz", type=float, default=20.0, help="Polling frequency in Hz") + p_status.add_argument("--raw", action="store_true", help="Read raw uncompensated wrench instead of external wrench") + p_status.add_argument("--from-report", action="store_true", help="Read cached socket report attributes") + p_status.add_argument("--include-identity", action="store_true", help="Query F/T sensor SN and firmware version") + + p_enable = sub.add_parser("enable", help="Enable F/T sensor data sampling (no physical arm motion)") + _add_common_args(p_enable) + + p_disable = sub.add_parser("disable", help="Exit force mode and disable F/T sensor sampling") + _add_common_args(p_disable) + + p_zero = sub.add_parser("zero", help="Enable sensor and zero current static offset (stationary)") + _add_common_args(p_zero) + + p_id = sub.add_parser("identify-load", help="Identify tool load and offset (drives robot motion)") + _add_common_args(p_id) + p_id.add_argument("--confirm-real", action="store_true", help="Required confirmation to move physical robot") + p_id.add_argument("--output", type=Path, default=None, help="Optional JSON output path") + p_id.add_argument("--apply", action="store_true", help="Write identified load offset back to controller") + p_id.add_argument("--update-tcp-load", action="store_true", help="Also update controller TCP load when applying") + + p_adm = sub.add_parser("admittance-test", help="Conservative admittance compliance check (requires --confirm-real)") + _add_common_args(p_adm) + p_adm.add_argument("--confirm-real", action="store_true", help="Required confirmation to enable F/T motion") + p_adm.add_argument("--coord", type=int, choices=(0, 1), default=1, help="0=base frame, 1=tool frame") + p_adm.add_argument("--c-axis", type=int, nargs=6, default=[1, 1, 1, 0, 0, 0]) + p_adm.add_argument("--mass", type=float, nargs=6, default=[0.1, 0.1, 0.1, 0.002, 0.002, 0.002]) + p_adm.add_argument("--stiffness", type=float, nargs=6, default=[300.0, 300.0, 300.0, 4.0, 4.0, 4.0]) + p_adm.add_argument("--damping", type=float, nargs=6, default=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + p_adm.add_argument("--duration", type=float, default=5.0, help="Hold duration in seconds") + p_adm.add_argument("--rate-hz", type=float, default=20.0, help="Logging rate in Hz") + p_adm.add_argument("--zero", action="store_true", help="Zero sensor before entering admittance mode") + p_adm.add_argument("--disable-on-exit", action="store_true", help="Disable sensor sampling after exiting mode") + + p_force = sub.add_parser("force-test", help="Conservative constant-force check (requires --confirm-real)") + _add_common_args(p_force) + p_force.add_argument("--confirm-real", action="store_true", help="Required confirmation to enable F/T motion") + p_force.add_argument("--coord", type=int, choices=(0, 1), default=1, help="0=base frame, 1=tool frame") + p_force.add_argument("--c-axis", type=int, nargs=6, default=[0, 0, 1, 0, 0, 0]) + p_force.add_argument("--f-ref", type=float, nargs=6, default=[0.0, 0.0, -2.0, 0.0, 0.0, 0.0]) + p_force.add_argument("--limits", type=float, nargs=6, default=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + p_force.add_argument("--kp", type=float, nargs=6, default=[0.001, 0.001, 0.001, 0.001, 0.001, 0.001]) + p_force.add_argument("--ki", type=float, nargs=6, default=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + p_force.add_argument("--kd", type=float, nargs=6, default=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + p_force.add_argument("--xe-limit", type=float, nargs=6, default=[10.0, 10.0, 10.0, 0.2, 0.2, 0.2]) + p_force.add_argument("--duration", type=float, default=2.0, help="Hold duration in seconds") + p_force.add_argument("--rate-hz", type=float, default=20.0, help="Logging rate in Hz") + p_force.add_argument("--zero", action="store_true", help="Zero sensor before entering force mode") + p_force.add_argument("--disable-on-exit", action="store_true", help="Disable sensor sampling after exiting mode") + + return parser + + +def main( + argv: Sequence[str] | None = None, + *, + arm_factory: Callable[[str], Any] | None = None, +) -> int: + parser = build_parser() + args = parser.parse_args(list(argv) if argv is not None else None) + robot_key = get_profile_key_for_robot_name(args.robot) + + if args.command in ("identify-load", "admittance-test", "force-test") and not args.confirm_real: + raise RuntimeError(f"Subcommand '{args.command}' requires --confirm-real before connecting to the controller") + + # Pre-validate force/admittance parameters before opening a hardware socket. + adm_params: FTAdmittanceParams | None = None + force_params: FTForceControlParams | None = None + if args.command == "admittance-test": + adm_params = FTAdmittanceParams( + coord=args.coord, + c_axis=tuple(args.c_axis), + M=tuple(args.mass), + K=tuple(args.stiffness), + B=tuple(args.damping), + ) + elif args.command == "force-test": + force_params = FTForceControlParams( + coord=args.coord, + c_axis=tuple(args.c_axis), + f_ref=tuple(args.f_ref), + limits=tuple(args.limits), + kp=tuple(args.kp), + ki=tuple(args.ki), + kd=tuple(args.kd), + xe_limit=tuple(args.xe_limit), + ) + + factory = _default_arm_factory if arm_factory is None else arm_factory + arm = factory(args.ip) + try: + verify_controller_robot(arm, robot_key) + sensor = XArmFTSensor(arm, robot_key=robot_key) + payload: dict[str, Any] = {"robot_key": robot_key, "ip": args.ip, "command": args.command} + + if args.command == "status": + status = sensor.read_status(include_identity=bool(args.include_identity)) + cfg = sensor.read_config() if callable(getattr(arm, "get_ft_sensor_config", None)) else None + payload["status"] = asdict(status) + if cfg is not None: + payload["config"] = asdict(cfg) + if not args.json: + print( + f"robot={robot_key} mode={status.mode} enabled={status.enabled} " + f"error={status.error_code} ({status.error_message})" + ) + if status.serial_number or status.firmware_version: + print(f"sn={status.serial_number} version={status.firmware_version}") + payload["samples"] = _sample_stream( + sensor, + duration_s=args.duration, + rate_hz=args.rate_hz, + is_raw=args.raw, + from_report=args.from_report, + as_json=args.json, + ) + + elif args.command == "enable": + sensor.set_enable(True) + time.sleep(0.2) + status = sensor.read_status() + reading = sensor.read_wrench() + payload["status"] = asdict(status) + payload["wrench"] = list(reading.wrench) + if not args.json: + print( + f"Enabled F/T sensor: robot={robot_key} mode={status.mode} enabled={status.enabled} " + f"error={status.error_code} ({status.error_message}) wrench={reading.wrench}" + ) + + elif args.command == "disable": + sensor.stop_force_mode(disable_sensor=True) + time.sleep(0.1) + status = sensor.read_status() + payload["status"] = asdict(status) + if not args.json: + print( + f"Disabled F/T sensor: robot={robot_key} mode={status.mode} enabled={status.enabled} " + f"error={status.error_code} ({status.error_message})" + ) + + elif args.command == "zero": + sensor.set_enable(True) + time.sleep(0.2) + before = sensor.read_wrench() + sensor.zero() + after = sensor.read_wrench() + payload["before"] = list(before.wrench) + payload["after"] = list(after.wrench) + if not args.json: + print(f"Zeroed F/T sensor: before={before.wrench} after={after.wrench}") + + elif args.command == "identify-load": + sensor.set_enable(True) + offset = sensor.identify_load_offset(confirm_real=True) + if args.apply: + sensor.set_load_offset(offset, update_tcp_load=bool(args.update_tcp_load)) + payload["load_offset"] = asdict(offset) + payload["applied"] = bool(args.apply) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + if not args.json: + print(f"Identified load offset: {offset}") + + elif args.command == "admittance-test": + assert adm_params is not None + with sensor.admittance_session( + adm_params, + confirm_real=True, + zero_on_enter=bool(args.zero), + disable_on_exit=bool(args.disable_on_exit), + ): + payload["samples"] = _sample_stream( + sensor, + duration_s=args.duration, + rate_hz=args.rate_hz, + is_raw=False, + from_report=False, + as_json=args.json, + ) + + elif args.command == "force-test": + assert force_params is not None + with sensor.force_control_session( + force_params, + confirm_real=True, + zero_on_enter=bool(args.zero), + disable_on_exit=bool(args.disable_on_exit), + ): + payload["samples"] = _sample_stream( + sensor, + duration_s=args.duration, + rate_hz=args.rate_hz, + is_raw=False, + from_report=False, + as_json=args.json, + ) + + if args.json: + print(json.dumps(payload, indent=2)) + return 0 + finally: + arm.disconnect() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/gen_kinematics_params.py b/scripts/gen_kinematics_params.py index 0f1798f..e578ab5 100644 --- a/scripts/gen_kinematics_params.py +++ b/scripts/gen_kinematics_params.py @@ -1,8 +1,13 @@ #!/usr/bin/env python3 -"""Extract per-robot kinematic calibration from xArm control box. +"""Export per-unit kinematic calibration from an xArm controller. -The output uses the strict calibration schema and is bound to the full -robot serial number: +The joint origins are identified from the controller's own forward kinematics +(read-only ``get_forward_kinematics`` queries: the zero pose and single-joint +sweeps, then 100 random configurations to verify the result). Nothing is +enabled or moved. The file is written only if it reproduces the controller FK +within the FK validation limits (1 mm, 0.5 deg). + +Output: the strict calibration schema, bound to the full robot serial number: joints.joint1..N: {x, y, z, roll, pitch, yaw} (meters, radians) SN eligibility (no compensation file expected): @@ -11,7 +16,7 @@ - UF850: all units have compensation Usage: - python scripts/gen_kinematics_params.py [suffix] + python scripts/gen_kinematics_params.py [suffix] [output_dir] python scripts/gen_kinematics_params.py [suffix] --force When suffix is omitted, defaults to the last 6 characters of the robot SN. @@ -21,11 +26,12 @@ import argparse import ipaddress -import socket -import struct +import math import sys +import time from pathlib import Path +import numpy as np from yaml import dump _REPO_ROOT = Path(__file__).resolve().parents[1] @@ -38,8 +44,15 @@ kinematics_suffix_from_sn, log_kinematics_sn_status, parse_sn_model_code, - robot_name_from_firmware, ) +from ufactory.kinematics.controller_fk import ( # noqa: E402 + CalibrationIdentificationError, + controller_flange_fk, + identify_from_controller_fk, + load_nominal_chain, +) +from ufactory.kinematics.tcp_offset import read_tcp_offset # noqa: E402 +from ufactory.robots.registry import get_robot_profile, joint_names, robot_name_for_controller # noqa: E402 def _parse_robot_ipv4(value: str) -> str: @@ -57,20 +70,103 @@ def _parse_robot_ipv4(value: str) -> str: def _output_dir_for_robot(robot_name: str) -> Path: - return _REPO_ROOT / "assets" / "urdf" / robot_name / "kinematics" / "user" + return _REPO_ROOT / "assets" / "urdf" / "robots" / robot_name / "kinematics" / "user" + + +def _read_world_offset(arm, timeout_s: float = 2.0, poll_s: float = 0.05) -> np.ndarray: + """``arm.world_offset`` once the rich report has delivered it (all-zero until then).""" + deadline = time.monotonic() + timeout_s + offset = np.zeros(6) + while time.monotonic() < deadline: + offset = np.asarray(arm.world_offset, dtype=np.float64).reshape(-1) + if np.any(np.abs(offset) > 1e-6): + return offset + time.sleep(poll_s) + return offset + + +def _export(arm, args: argparse.Namespace) -> int: + axis, device_type = int(arm.axis), int(arm.device_type) + robot_name = robot_name_for_controller(axis, device_type) + if robot_name is None: + print(f"[Failed] controller reports axis={axis}, device_type={device_type}: not a registered robot model") + return 1 + profile = get_robot_profile(robot_name) + sn = get_robot_sn(arm) + if not sn: + print("[Failed] controller did not report a serial number") + return 1 + if not args.kinematics_suffix: + args.kinematics_suffix = kinematics_suffix_from_sn(sn) + print(f"kinematics_suffix: {args.kinematics_suffix} (auto from SN {sn})") + print(f"robot_name : {robot_name}") + log_kinematics_sn_status( + sn, + robot_name, + kinematics_suffix=args.kinematics_suffix, + allow_sn_override=args.force, + ) + if not args.force and not has_per_unit_kinematics_calibration(sn, robot_name): + print( + "[Skipped] SN model code {} indicates no per-unit kinematics compensation. " + "Use nominal URDF without --kinematics-suffix. Pass --force to export anyway.".format( + parse_sn_model_code(sn) + ) + ) + return 2 -def _fetch_kinematics_bytes(robot_ip: str) -> bytes: - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: - sock.settimeout(10.0) - sock.connect((robot_ip, 502)) - send_data = [0x00, 0x01, 0x00, 0x02, 0x00, 0x01, 0x08] - sock.sendall(bytes(send_data)) - return sock.recv(179) + tcp_offset = read_tcp_offset(arm) + world_offset = _read_world_offset(arm) + if np.any(np.abs(world_offset) > 1e-6): + print( + f"[Failed] controller world_offset {world_offset.tolist()} is not zero; the export reads FK in the " + "robot base frame. Set the world offset to 0 in UFACTORY Studio, export, then restore it." + ) + return 1 + print(f"tcp_offset : {tcp_offset.tolist()} (removed from controller FK)") + + chain = load_nominal_chain(profile.assets_dir / profile.default_urdf, joint_names(profile)) + if chain.ee_link != profile.ee_link: + print(f"[Failed] URDF chain ends at {chain.ee_link}, expected {profile.ee_link}") + return 1 + try: + result = identify_from_controller_fk(controller_flange_fk(arm, tcp_offset), chain) + except (CalibrationIdentificationError, RuntimeError) as exc: + print(f"[Failed] {exc}; no file written") + return 1 + print( + f"controller FK : rigid chain to {result.rigid_chain_error_m * 1e6:.2f} um " + f"({result.identification_samples} identification + {result.verification_samples} held-out samples)" + ) + print( + f"calibration : held-out error mean {result.mean_position_error_m * 1e3:.4f} mm, " + f"max {result.max_position_error_m * 1e3:.4f} mm / {math.degrees(result.max_rotation_error_rad):.4f} deg" + ) + print( + f"flange : {result.flange_axis_offset_m * 1e6:.1f} um off and " + f"{math.degrees(result.flange_axis_tilt_rad) * 1e3:.2f} mdeg tilted from the last axis " + "(exact at last joint 0)" + ) + + output_dir = Path(args.output_dir).resolve() if args.output_dir else _output_dir_for_robot(robot_name) + output_dir.mkdir(parents=True, exist_ok=True) + output_file = output_dir / "{}_kinematics_{}.yaml".format(profile.kinematics_prefix, args.kinematics_suffix) + data = { + "schema_version": 1, + "robot_key": profile.key, + "serial_number": sn, + "units": {"position": "m", "angle": "rad"}, + "joints": result.joints(chain.joint_names), + } + with open(output_file, "w", encoding="utf-8") as f: + dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False) + print("[Success] save to {}".format(output_file)) + return 0 def main() -> int: - parser = argparse.ArgumentParser(description="Extract per-unit kinematics YAML from control box") + parser = argparse.ArgumentParser(description="Export per-unit kinematics YAML from the controller FK") parser.add_argument( "robot_ip", type=_parse_robot_ipv4, @@ -94,20 +190,21 @@ def main() -> int: arm = None try: - arm = XArmAPI(args.robot_ip, is_radian=True) + try: + arm = XArmAPI(args.robot_ip, is_radian=True) + except Exception as exc: + print( + f"[Failed] cannot connect to {args.robot_ip}: {exc}. " + "Check the IP, controller power, and host network settings." + ) + return 1 if not arm.connected: print( f"[Failed] cannot connect to {args.robot_ip}. " "Check the IP, controller power, and host network settings." ) return 1 - sn = get_robot_sn(arm) - except Exception as exc: - print( - f"[Failed] cannot connect to {args.robot_ip}: {exc}. " - "Check the IP, controller power, and host network settings." - ) - return 1 + return _export(arm, args) finally: if arm is not None: try: @@ -115,75 +212,6 @@ def main() -> int: except Exception: pass - if not args.kinematics_suffix: - args.kinematics_suffix = kinematics_suffix_from_sn(sn) - print(f"kinematics_suffix: {args.kinematics_suffix} (auto from SN {sn})") - - try: - recv_data = _fetch_kinematics_bytes(args.robot_ip) - except OSError as exc: - print( - f"[Failed] cannot read kinematics data from {args.robot_ip}:502: {exc}. " - "Check that the controller is reachable and TCP port 502 is available." - ) - return 1 - if not (len(recv_data) == 179 and recv_data[8]): - valid = 0 if len(recv_data) < 9 else recv_data[8] - print("[Failed] recv_len={}, valid={}".format(len(recv_data), valid)) - return 1 - - robot_dof = recv_data[9] - robot_type = recv_data[10] - robot_name = robot_name_from_firmware(robot_dof, robot_type) - - print(f"robot_name : {robot_name}") - log_kinematics_sn_status( - sn, - robot_name, - kinematics_suffix=args.kinematics_suffix, - allow_sn_override=args.force, - ) - - if not args.force and not has_per_unit_kinematics_calibration(sn, robot_name): - model_code = parse_sn_model_code(sn) - print( - "[Skipped] SN model code {} indicates no per-unit kinematics compensation. " - "Use nominal URDF without --kinematics-suffix. Pass --force to export anyway.".format(model_code) - ) - return 2 - - output_dir = Path(args.output_dir).resolve() if args.output_dir else _output_dir_for_robot(robot_name) - output_dir.mkdir(parents=True, exist_ok=True) - output_file = output_dir / "{}_kinematics_{}.yaml".format(robot_name, args.kinematics_suffix) - - params = struct.unpack("<42f", recv_data[11:]) - kinematics = {} - data = { - "schema_version": 1, - "robot_key": "{}_1305".format(robot_name) if robot_name.startswith("xarm") else robot_name, - "serial_number": sn, - "units": {"position": "m", "angle": "rad"}, - "joints": kinematics, - } - for i in range(robot_dof): - joint_param = {} - kinematics["joint{}".format(i + 1)] = joint_param - for axis_idx, axis in enumerate(("x", "y", "z", "roll", "pitch", "yaw")): - value = float(params[i * 6 + axis_idx]) - # xArm5 firmware may return mm-scale outliers on prismatic-like offsets. - if axis in ("x", "y", "z") and abs(value) > 1.0: - value /= 1000.0 - joint_param[axis] = value - - with open(output_file, "w", encoding="utf-8") as f: - try: - dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False) - except TypeError: - dump(data, f, default_flow_style=False, allow_unicode=True) - - print("[Success] save to {}".format(output_file)) - return 0 - if __name__ == "__main__": raise SystemExit(main()) diff --git a/tests/config/test_runtime_config.py b/tests/config/test_runtime_config.py index e99f407..335db39 100644 --- a/tests/config/test_runtime_config.py +++ b/tests/config/test_runtime_config.py @@ -231,3 +231,77 @@ def test_robotiq_gripper_overlay_resolution_and_validation(variant: str, open_m: def test_robotiq_2f_85_rejects_position_mm_above_85(): with pytest.raises(ConfigError, match="85"): load_runtime_config("xarm6", gripper="robotiq_2f_85", overrides={"simulation.robotiq.position_mm": 100.0}) + + +@pytest.mark.parametrize("robot", ["xarm5", "xarm6", "xarm7", "uf850"]) +@pytest.mark.parametrize("alias", ["bio_gripper_g2", "bio_g2"]) +def test_bio_g2_overlay_resolution_for_supported_arms(robot: str, alias: str): + cfg = load_runtime_config(robot, gripper=alias) + assert cfg.gripper is not None + assert cfg.gripper.adapter == "bio_g2" + assert cfg.gripper.closed_gap_m == pytest.approx(0.071) + assert cfg.gripper.open_gap_m == pytest.approx(0.150) + assert cfg.robot.urdf == "assembly:bio_gripper_g2" + assert list(cfg.task.parameters["fixed_object_position_m"]) == pytest.approx([0.38, -0.12, 0.015]) + assert list(cfg.task.parameters["fixed_target_position_m"]) == pytest.approx([0.38, 0.12, 0.015]) + assert list(cfg.task.parameters["default_ee_position_m"]) == pytest.approx([0.38, -0.12, 0.30]) + + +def test_bio_g2_overlay_rejects_lite6_and_reach(): + with pytest.raises(ConfigError, match="not supported"): + load_runtime_config("lite6", gripper="bio_gripper_g2") + with pytest.raises(ConfigError, match="reach"): + load_runtime_config("xarm6", task="reach", gripper="bio_gripper_g2") + + +def test_default_g2_and_robotiq_hashes_are_unchanged(): + g2_cfg = load_runtime_config("xarm6") + robotiq_cfg = load_runtime_config("xarm6", gripper="robotiq_2f_85") + bio_cfg = load_runtime_config("xarm6", gripper="bio_gripper_g2") + assert g2_cfg.gripper is not None and g2_cfg.gripper.tcp_offset == pytest.approx((0.0, 0.0, 178.6, 0.0, 0.0, 0.0)) + assert robotiq_cfg.gripper is not None and robotiq_cfg.gripper.tcp_offset == pytest.approx( + (0.0, 0.0, 173.8, 0.0, 0.0, 0.0) + ) + assert bio_cfg.gripper is not None and bio_cfg.gripper.tcp_offset == pytest.approx( + (157.64, 0.0, 59.5, 0.0, 0.0, 0.0) + ) + assert g2_cfg.sha256 == "f4ecfc73c965d1163e44c68a42867cfe8157e569912ec8d2ccc6efd5be95b88c" + assert robotiq_cfg.sha256 == "119a0c44439e3f6495f50209c05457b41eae78318ccb5105fe839d1b97bc20e0" + assert bio_cfg.sha256 == "154ddbc4baf6485c00da7cfc11612887953d97b7629a54e9c64de2594a458454" + + overridden = load_runtime_config("xarm6", overrides={"gripper.tcp_offset": [0.0, 0.0, 180.0, 0.0, 0.0, 0.0]}) + assert overridden.sha256 != g2_cfg.sha256 + with pytest.raises(ConfigError, match="gripper.tcp_offset"): + load_runtime_config("xarm6", overrides={"gripper.tcp_offset": [0.0, 0.0, 180.0]}) + + +@pytest.mark.parametrize("robot", ROBOTS) +def test_default_approx_motion_and_simulation_rate_defaults(robot: str) -> None: + cfg = load_runtime_config(robot) + assert cfg.motion.allow_approx_motion is False + assert cfg.motion.rate_hz == pytest.approx(50.0) + assert cfg.simulation.rate_hz == pytest.approx(50.0) + + +def test_allow_approx_motion_and_sim_rate_overrides_change_hash_and_validate(tmp_path: Path) -> None: + base = load_runtime_config("uf850") + approx_cfg = load_runtime_config("uf850", overrides={"motion.allow_approx_motion": True}) + rate_cfg = load_runtime_config("uf850", overrides={"simulation.rate_hz": 250.0}) + assert approx_cfg.motion.allow_approx_motion is True + assert rate_cfg.simulation.rate_hz == pytest.approx(250.0) + assert approx_cfg.sha256 != base.sha256 + assert rate_cfg.sha256 != base.sha256 + assert approx_cfg.sha256 != rate_cfg.sha256 + + for bad_approx in (1, "true", 0): + with pytest.raises(ConfigError, match=r"motion\.allow_approx_motion must be a boolean"): + load_runtime_config("uf850", overrides={"motion.allow_approx_motion": bad_approx}) + + for bad_rate in (0.0, -50.0, float("nan"), float("inf"), True): + with pytest.raises(ConfigError, match=r"simulation\.rate_hz must be finite"): + load_runtime_config("uf850", overrides={"simulation.rate_hz": bad_rate}) + + bad_yaml = tmp_path / "bad_approx.yaml" + bad_yaml.write_text("schema_version: 1\nmotion:\n allow_approx_motion: 1\n", encoding="utf-8") + with pytest.raises(ConfigError, match="boolean"): + load_runtime_config("uf850", config_path=bad_yaml) diff --git a/tests/control/test_arm_controller.py b/tests/control/test_arm_controller.py new file mode 100644 index 0000000..1e109b3 --- /dev/null +++ b/tests/control/test_arm_controller.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import math +from pathlib import Path + +import numpy as np +import pytest + +from ufactory.control import ( + DEFAULT_CONTROL_RATE_HZ, + DEFAULT_SERVO_RATE_HZ, + ERROR_INVALID_ARG, + ERROR_INVALID_MODE, + ERROR_NONE, + ERROR_OVERSPEED, + MODE_POSITION, + MODE_SERVO, + STATE_READY, + STATE_STOP, + ApproxMotionConfig, + ArmMotionController, +) + + +class _FakeXArm: + def __init__(self, initial_approx: int = 0) -> None: + self.approx = int(initial_approx) + self.calls: list[tuple[str, object]] = [] + + def get_allow_approx_motion(self) -> tuple[int, int]: + return (0, self.approx) + + def set_allow_approx_motion(self, on_off: bool) -> int: + self.approx = 1 if on_off else 0 + self.calls.append(("set_allow_approx_motion", bool(on_off))) + return 0 + + def set_mode(self, mode: int) -> int: + self.calls.append(("set_mode", mode)) + return 0 + + def set_state(self, state: int) -> int: + self.calls.append(("set_state", state)) + return 0 + + def clean_error(self) -> int: + self.calls.append(("clean_error", None)) + return 0 + + def set_tcp_offset(self, offset: list[float], *, is_radian: bool = True) -> int: + self.calls.append(("set_tcp_offset", (tuple(offset), is_radian))) + return 0 + + +def test_controller_defaults_rates_and_sdk_switch_parity() -> None: + ctrl = ArmMotionController.from_robot("uf850") + assert ctrl.control_rate_hz == DEFAULT_CONTROL_RATE_HZ == 250.0 + assert ctrl.servo_rate_hz == DEFAULT_SERVO_RATE_HZ == 50.0 + assert ctrl.is_approx_motion is False + assert ctrl.get_allow_approx_motion() == (0, 0) + + assert ctrl.set_allow_approx_motion(True) == 0 + assert ctrl.is_approx_motion is True + assert ctrl.get_allow_approx_motion() == (0, 1) + + with pytest.raises(TypeError): + ctrl.set_allow_approx_motion(1) # type: ignore[arg-type] + + # Servo rate allows 30-250 Hz, rejects out of range + ctrl.set_servo_rate(100.0) + assert ctrl.servo_rate_hz == 100.0 + ctrl.set_servo_rate(250.0) + with pytest.raises(ValueError, match="servo_rate_hz"): + ctrl.set_servo_rate(20.0) + with pytest.raises(ValueError, match="servo_rate_hz"): + ctrl.set_servo_rate(300.0) + + +def test_sync_hardware_switches_restores_on_normal_and_error() -> None: + fake = _FakeXArm(initial_approx=0) + ctrl = ArmMotionController.from_robot("lite6", allow_approx_motion=True) + + with ctrl.sync_hardware_switches(fake): + assert fake.approx == 1 + assert fake.approx == 0 + + with pytest.raises(RuntimeError, match="boom"): + with ctrl.sync_hardware_switches(fake): + assert fake.approx == 1 + raise RuntimeError("boom") + assert fake.approx == 0 + + +def test_mode0_250hz_movej_and_movel_and_tcp_offset() -> None: + ctrl = ArmMotionController.from_robot("uf850") + assert ctrl.set_tcp_offset([0.0, 0.0, 100.0, 0.0, 0.0, 0.0], is_radian=True) == ERROR_NONE + assert ctrl.set_mode(MODE_POSITION) == ERROR_NONE + assert ctrl.set_state(STATE_READY) == ERROR_NONE + + q_start = np.array([0.0, -0.3, -0.7, 0.0, 1.0, 0.0], dtype=np.float64) + assert ctrl.set_servo_angle(q_start, speed=1.0, mvacc=8.0, is_radian=True) == ERROR_NONE + assert ctrl.last_motion is not None + assert ctrl.last_motion.rate_hz == 250.0 + code_p, pos0 = ctrl.get_position(is_radian=True) + assert code_p == 0 + + # MoveL 60 mm in +X at 250 Hz + code_m = ctrl.set_position(x=pos0[0] + 60.0, speed=150.0, mvacc=800.0, is_radian=True) + assert code_m == ERROR_NONE + assert ctrl.last_motion is not None + assert ctrl.last_motion.kind == "movel" + assert ctrl.last_motion.rate_hz == 250.0 + assert len(ctrl.last_motion.q_samples) > 50 + _, pos1 = ctrl.get_position(is_radian=True) + assert pos1[0] == pytest.approx(pos0[0] + 60.0, abs=1e-3) + assert pos1[1] == pytest.approx(pos0[1], abs=1e-3) + assert pos1[2] == pytest.approx(pos0[2], abs=1e-3) + + # FK/IK SDK roundtrip (degree mode too) + code_a, ang_deg = ctrl.get_servo_angle(is_radian=False) + assert code_a == 0 + code_fk, fk_deg = ctrl.get_forward_kinematics(ang_deg, input_is_radian=False, return_is_radian=False) + assert code_fk == 0 + code_ik, ik_deg = ctrl.get_inverse_kinematics(fk_deg, input_is_radian=False, return_is_radian=False) + assert code_ik == 0 + assert np.allclose(ik_deg, ang_deg, atol=1e-2) + + +def test_mode0_and_mode1_singularity_c24_vs_approx_motion_with_calibrated_uf850() -> None: + cal = Path("assets/urdf/robots/uf850/kinematics/user/uf850_kinematics_F54B07.yaml") + if not cal.is_file(): + pytest.skip("local UF850 calibration YAML not present") + + pose_a = [300.0, 0.0, 288.6, math.pi, 0.0, 0.0] + pose_b = [300.0, 0.0, 188.6, math.pi, 0.0, 0.0] + + # Mode 0 (250 Hz): approx=False aborts with C24 overspeed, approx=True passes cleanly + ctrl = ArmMotionController.from_robot("uf850", calibration_path=cal, allow_approx_motion=False) + code_ik, q_a = ctrl.get_inverse_kinematics(pose_a, input_is_radian=True, return_is_radian=True) + assert code_ik == 0 + ctrl.reset_state(q_a) + + code_fail = ctrl.set_position(*pose_b, speed=150.0, mvacc=800.0, is_radian=True) + assert code_fail == ERROR_OVERSPEED + assert ctrl.state == STATE_STOP + assert ctrl.error_code == ERROR_OVERSPEED + + # Recover, enable allow_approx_motion, re-run Mode 0 (250 Hz) -> PASS with tiny orientation error + ctrl.clean_error() + ctrl.reset_state(q_a) + assert ctrl.set_allow_approx_motion(True) == 0 + code_ok = ctrl.set_position(*pose_b, speed=150.0, mvacc=800.0, is_radian=True) + assert code_ok == ERROR_NONE + assert ctrl.last_motion is not None + assert ctrl.last_motion.used_approx_steps > 0 + assert ctrl.last_motion.max_position_error_m < 1e-4 # < 0.1 mm + assert ctrl.last_motion.max_orientation_error_rad < math.radians(0.5) + _, end_pos = ctrl.get_position(is_radian=True) + assert end_pos[2] == pytest.approx(188.6, abs=0.05) + + # Mode 1 (50 Hz): set_servo_cartesian with approx=True passes smoothly + ctrl.reset_state(q_a) + assert ctrl.set_mode(MODE_SERVO) == 0 + assert ctrl.set_position(*pose_b) == ERROR_INVALID_MODE # Mode 0 API rejected in Mode 1 + zs = np.linspace(288.6, 188.6, 45) + for z in zs: + assert ctrl.set_servo_cartesian([300.0, 0.0, float(z), math.pi, 0.0, 0.0], is_radian=True) == 0 + _, end_pos_m1 = ctrl.get_position(is_radian=True) + assert end_pos_m1[2] == pytest.approx(188.6, abs=0.05) + + +def test_mode1_servo_angle_j_and_invalid_inputs() -> None: + ctrl = ArmMotionController.from_robot("lite6") + assert ctrl.set_servo_angle_j([0.0] * 6) == ERROR_INVALID_MODE # Still in Mode 0 + assert ctrl.set_mode(MODE_SERVO) == 0 + assert ctrl.set_servo_angle_j([0.1, 0.2, 0.5, 0.0, 0.2, 0.0]) == 0 + assert ctrl.set_servo_angle_j([0.1, 0.2]) == ERROR_INVALID_ARG + assert ctrl.set_servo_angle_j([0.0, 0.0, 99.0, 0.0, 0.0, 0.0]) == ERROR_INVALID_ARG + assert ctrl.state == STATE_STOP + ctrl.clean_error() + assert ctrl.set_servo_cartesian([200.0, 0.0, float("nan"), math.pi, 0.0, 0.0]) == ERROR_INVALID_ARG + assert ctrl.set_mode(99) == ERROR_INVALID_MODE + assert ctrl.set_state(99) == ERROR_INVALID_ARG + assert ctrl.set_tcp_offset([1.0, 2.0]) == ERROR_INVALID_ARG + assert ctrl.set_allow_approx_motion(False) == 0 + assert ctrl.approx_config == ApproxMotionConfig() diff --git a/tests/control/test_kinematics_chain.py b/tests/control/test_kinematics_chain.py new file mode 100644 index 0000000..ead014d --- /dev/null +++ b/tests/control/test_kinematics_chain.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import math +from pathlib import Path + +import numpy as np +import pytest +import yaml + +from ufactory.control import ( + CalibratedKinematicsChain, + pose_to_se3, + quat_xyzw_to_rotation, + rotation_to_quat_xyzw, + se3_to_pose_m_quat, + se3_to_pose_mm_rpy, + slerp_rotation, + so3_log, +) +from ufactory.kinematics.controller_fk import axis_angle_matrix + +ALL_ROBOTS = ("xarm5", "xarm6", "xarm7", "uf850", "lite6") + + +def test_so3_quaternion_and_slerp_roundtrip() -> None: + rng = np.random.default_rng(42) + for angle in (0.0, 1e-9, 0.35, 1.8, math.pi - 1e-6, math.pi - 1e-10): + axis = rng.normal(size=3) + axis /= np.linalg.norm(axis) + rot = axis_angle_matrix(axis, angle) + q = rotation_to_quat_xyzw(rot) + assert np.allclose(quat_xyzw_to_rotation(q), rot, atol=1e-10) + omega = so3_log(rot) + assert np.allclose(np.linalg.norm(omega), angle, atol=1e-6) + if angle > 1e-6: + rebuilt = axis_angle_matrix(omega / np.linalg.norm(omega), float(np.linalg.norm(omega))) + assert np.allclose(rebuilt, rot, atol=1e-6) + + # SLERP midpoint check + ra = axis_angle_matrix(np.array([0.0, 0.0, 1.0]), 0.0) + rb = axis_angle_matrix(np.array([0.0, 0.0, 1.0]), 1.2) + rmid = slerp_rotation(ra, rb, 0.5) + assert np.allclose(rmid, axis_angle_matrix(np.array([0.0, 0.0, 1.0]), 0.6), atol=1e-12) + assert np.allclose(slerp_rotation(ra, rb, 0.0), ra, atol=1e-12) + assert np.allclose(slerp_rotation(ra, rb, 1.0), rb, atol=1e-12) + + # Pose conversions + pose_mm = np.array([300.0, -50.0, 220.0, math.pi, 0.1, -0.3]) + t = pose_to_se3(pose_mm, position_in_mm=True) + assert np.allclose(se3_to_pose_mm_rpy(t)[:3], pose_mm[:3], atol=1e-9) + p7 = se3_to_pose_m_quat(t) + assert np.allclose(pose_to_se3(p7), t, atol=1e-12) + + +@pytest.mark.parametrize("robot", ALL_ROBOTS) +def test_analytical_jacobian_matches_finite_difference_all_5_robots(robot: str) -> None: + chain = CalibratedKinematicsChain.from_robot(robot, tcp_offset_mm_rpy=[12.0, -8.0, 45.0, 0.1, -0.2, 0.3]) + rng = np.random.default_rng(abs(hash(robot)) % (2**32)) + eps = 1e-6 + for _ in range(5): + lo = np.maximum(chain.lower + 0.1, -1.5) + hi = np.minimum(chain.upper - 0.1, 1.5) + q = rng.uniform(lo, hi) + t0, jac = chain.forward_and_jacobian(q, include_tcp=True) + jac_fd = np.zeros_like(jac) + for j in range(chain.dof): + qp = q.copy() + qm = q.copy() + qp[j] += eps + qm[j] -= eps + tp = chain.forward_matrix(qp, include_tcp=True) + tm = chain.forward_matrix(qm, include_tcp=True) + jac_fd[:3, j] = (tp[:3, 3] - tm[:3, 3]) / (2.0 * eps) + jac_fd[3:, j] = so3_log(tp[:3, :3] @ tm[:3, :3].T) / (2.0 * eps) + assert np.allclose(jac, jac_fd, atol=1e-6, rtol=1e-5) + assert np.allclose(chain.tcp_target_to_flange(t0), chain.forward_matrix(q, include_tcp=False), atol=1e-12) + + +@pytest.mark.parametrize("robot", ALL_ROBOTS) +def test_pure_numpy_fk_and_jacobian_match_pinocchio(robot: str) -> None: + pin = pytest.importorskip("pinocchio") + from ufactory.config import RepositoryAssetStore + from ufactory.robots.assembly import resolve_robot_urdf + from ufactory.robots.registry import PROJECT_ROOT, get_robot_profile + + profile = get_robot_profile(robot) + store = RepositoryAssetStore.discover() + assets_rel = profile.assets_dir.relative_to(PROJECT_ROOT).as_posix() + urdf = resolve_robot_urdf(profile.key, profile.default_urdf, assets_dir=assets_rel, store=store) + chain = CalibratedKinematicsChain.from_robot(robot, urdf_path=urdf) + + model = pin.buildModelFromUrdf(str(urdf)) + data = model.createData() + fid = model.getFrameId(chain.ee_link) + + rng = np.random.default_rng(1234 + chain.dof) + lo = np.maximum(chain.lower + 0.1, -1.5) + hi = np.minimum(chain.upper - 0.1, 1.5) + for _ in range(5): + q = rng.uniform(lo, hi) + t_np, j_np = chain.forward_and_jacobian(q, include_tcp=False) + pin.computeJointJacobians(model, data, q) + pin.updateFramePlacements(model, data) + oMf = data.oMf[fid] + j_pin = pin.getFrameJacobian(model, data, fid, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED) + assert np.allclose(t_np[:3, 3], oMf.translation, atol=1e-11) + assert np.allclose(t_np[:3, :3], oMf.rotation, atol=1e-11) + assert np.allclose(j_np, j_pin, atol=1e-11) + + +def test_parameter_compensation_yaml_updates_fk(tmp_path: Path) -> None: + nom = CalibratedKinematicsChain.from_robot("uf850") + joints_dict = {} + for idx, name in enumerate(nom.joint_names): + row = nom.nominal_origins[idx].copy() + if idx == 3: + row[0] += 0.0025 # +2.5 mm perturbation + row[4] += 0.004 # +4 mrad pitch tilt + joints_dict[name] = { + "x": float(row[0]), + "y": float(row[1]), + "z": float(row[2]), + "roll": float(row[3]), + "pitch": float(row[4]), + "yaw": float(row[5]), + } + cal_file = tmp_path / "uf850_kinematics_TEST1234.yaml" + cal_file.write_text( + yaml.safe_dump( + { + "schema_version": 1, + "robot_key": "uf850", + "serial_number": "FX851005TEST1234", + "units": {"position": "m", "angle": "rad"}, + "joints": joints_dict, + } + ), + encoding="utf-8", + ) + comp = CalibratedKinematicsChain.from_robot("uf850", calibration_path=cal_file) + assert comp.is_calibrated + assert comp.serial_number == "FX851005TEST1234" + q = np.array([0.1, -0.4, -0.5, 0.2, 0.3, -0.1]) + t_nom = nom.forward_matrix(q) + t_comp = comp.forward_matrix(q) + pos_diff, rot_diff = nom.pose_error(t_nom, t_comp) + assert pos_diff > 0.0015 + assert rot_diff > 0.002 diff --git a/tests/control/test_phase2_integration.py b/tests/control/test_phase2_integration.py new file mode 100644 index 0000000..7429274 --- /dev/null +++ b/tests/control/test_phase2_integration.py @@ -0,0 +1,218 @@ +"""Phase 2 integration unit tests (transport, sdk_sim switch sync, sim-rate stepping, CLIs, IK).""" + +from __future__ import annotations + +from types import SimpleNamespace + +import numpy as np +import pytest + +from ufactory.cli import packaging, pick_place +from ufactory.config import load_runtime_config +from ufactory.control import ArmMotionController +from ufactory.hardware.transport import XArmTransport +from ufactory.manipulation.commands import sdk_sim_feedback +from ufactory.trajectory.ik import compile_cartesian_program_to_joint_stream +from ufactory.trajectory.segments import JointLimits, Program, Segment, make_movel + + +class _ApproxFakeArm: + def __init__(self, q: np.ndarray, *, initial_approx: int = 0) -> None: + self.physical_q = np.asarray(q, dtype=np.float64).copy() + self.virtual_q = self.physical_q.copy() + self.axis = int(self.physical_q.size) + self.connected = True + self.state = 2 + self.mode = 0 + self.error_code = 0 + self.warn_code = 0 + self.is_simulation_robot = False + self.approx_state = int(initial_approx) + self.tcp_offset = [0.0] * 6 + self.calls: list[tuple] = [] + self.fail_on_servo = False + + def get_allow_approx_motion(self) -> tuple[int, int]: + return 0, self.approx_state + + def set_allow_approx_motion(self, on_off: bool) -> int: + self.approx_state = 1 if on_off else 0 + self.calls.append(("set_allow_approx_motion", bool(on_off))) + return 0 + + def motion_enable(self, enable: bool = True) -> int: + self.calls.append(("motion_enable", bool(enable))) + return 0 + + def set_mode(self, mode: int) -> int: + self.mode = int(mode) + return 0 + + def set_state(self, state: int) -> int: + self.state = 2 if int(state) == 0 else int(state) + return 0 + + def get_state(self) -> tuple[int, int]: + return 0, self.state + + def set_simulation_robot(self, on_off: bool) -> int: + self.is_simulation_robot = bool(on_off) + self.calls.append(("set_simulation_robot", bool(on_off))) + return 0 + + def set_servo_angle(self, angle, **_kwargs) -> int: + self.virtual_q = np.asarray(angle, dtype=np.float64).copy() + return 0 + + def set_servo_angle_j(self, angles, **_kwargs) -> int: + if self.fail_on_servo: + return 9 + self.virtual_q = np.asarray(angles, dtype=np.float64).copy() + return 0 + + def get_servo_angle(self, is_radian: bool = True): + del is_radian + return 0, (self.virtual_q if self.is_simulation_robot else self.physical_q).tolist() + + +def test_xarm_transport_approx_motion_methods() -> None: + arm = _ApproxFakeArm(np.zeros(6), initial_approx=0) + transport = XArmTransport(arm, robot_key="uf850", serial_number="FX851005XXXXXX") + assert transport.get_allow_approx_motion() == (0, 0) + assert transport.is_approx_motion is False + assert transport.set_allow_approx_motion(True) == 0 + assert transport.get_allow_approx_motion() == (0, 1) + assert transport.is_approx_motion is True + with pytest.raises(TypeError, match="bool"): + transport.set_allow_approx_motion(1) # type: ignore[arg-type] + + +def test_sdk_sim_feedback_syncs_and_restores_approx_motion_on_success_and_failure(monkeypatch) -> None: + monkeypatch.setattr("ufactory.manipulation.commands.time.sleep", lambda _s: None) + cfg = load_runtime_config("uf850", overrides={"motion.allow_approx_motion": True}) + q0 = np.asarray(cfg.arm.default_qpos_rad, dtype=np.float64) + seg = Segment( + kind="movej", + duration=0.02, + v_max=1.0, + a_max=12.0, + label="move", + q_start=q0, + q_end=q0, + q_samples=q0[None, :], + samples_count=1, + ) + prog = Program([seg], rate=50.0, robot_key=cfg.robot.key) + + arm = _ApproxFakeArm(q0, initial_approx=0) + sdk_sim_feedback(arm, prog, cfg, q0, tcp_offset=np.zeros(6)) + assert arm.approx_state == 0 + assert ("set_allow_approx_motion", True) in arm.calls + assert arm.calls[-2] == ("set_allow_approx_motion", False) + assert not arm.is_simulation_robot + + # Must also restore on failure + arm_fail = _ApproxFakeArm(q0, initial_approx=0) + arm_fail.fail_on_servo = True + with pytest.raises(RuntimeError, match="code 9"): + sdk_sim_feedback(arm_fail, prog, cfg, q0, tcp_offset=np.zeros(6)) + assert arm_fail.approx_state == 0 + assert not arm_fail.is_simulation_robot + + +def test_physics_steps_for_tick_rates() -> None: + pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.trajectory.sim_executor import physics_steps_for_tick + + assert physics_steps_for_tick(50.0, 50.0) == (1, 0.0) + assert physics_steps_for_tick(100.0, 50.0) == (2, 0.0) + assert physics_steps_for_tick(250.0, 50.0) == (5, 0.0) + # Non-integer ratio (60 Hz physics / 50 Hz control -> 6 steps every 5 control ticks) + acc = 0.0 + counts = [] + for _ in range(5): + n, acc = physics_steps_for_tick(60.0, 50.0, acc) + counts.append(n) + assert sum(counts) == 6 + assert abs(acc) < 1e-12 + with pytest.raises(ValueError, match="sim_rate_hz"): + physics_steps_for_tick(0.0, 50.0) + + +def test_cli_print_config_accepts_allow_approx_motion_and_sim_rate_hz(capsys) -> None: + rc1 = pick_place.main( + [ + "--robot", + "uf850", + "--mode", + "dry-run", + "--executor", + "servo_cartesian", + "--allow-approx-motion", + "--sim-rate-hz", + "250", + "--print-config", + ] + ) + out1 = capsys.readouterr().out + assert rc1 == 0 + assert "allow_approx_motion: true" in out1 + assert "rate_hz: 250.0" in out1 + + rc2 = packaging.main( + [ + "--robot", + "lite6", + "--mode", + "sim", + "--allow-approx-motion", + "--sim-rate-hz", + "100", + "--print-config", + ] + ) + out2 = capsys.readouterr().out + assert rc2 == 0 + assert "allow_approx_motion: true" in out2 + assert "rate_hz: 100.0" in out2 + + +def test_mirror_and_ik_compile_use_injected_arm_controller() -> None: + pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.trajectory.mirror_executor import resolve_segment_start_arm_q, resolve_tick_arm_q + + ctrl = ArmMotionController.from_robot("uf850", allow_approx_motion=True) + _, q_a_list = ctrl.get_inverse_kinematics( + [300.0, 0.0, 288.6, np.pi, 0.0, 0.0], input_is_radian=True, return_is_radian=True + ) + q_a = np.asarray(q_a_list, dtype=np.float64) + ctx = SimpleNamespace( + robot_key="uf850", + arm_controller=ctrl, + arm_dof_idx=list(range(6)), + home_qpos=q_a.copy(), + robot_urdf_path="", + kinematics_yaml_path=None, + kinematics_suffix=None, + ) + limits = JointLimits(1.0, 12.0, 0.15, 0.8) + seg = make_movel( + np.array([0.300, 0.0, 0.2886]), + np.array([0.300, 0.0, 0.1886]), + rate=50.0, + limits=limits, + label="descend", + ) + q_start = resolve_segment_start_arm_q(ctx, seg, init_qpos=q_a) + np.testing.assert_allclose(q_start, q_a, atol=1e-4) + + samples, _ = seg.samples(50.0) + q_tick0 = resolve_tick_arm_q(ctx, seg, samples, 0, init_qpos=q_a, dt_s=0.02) + assert q_tick0.shape == (6,) + + prog = Program([seg], rate=50.0, limits=limits, robot_key="uf850") + compiled = compile_cartesian_program_to_joint_stream(prog, ctx) + assert compiled.segments[0].kind == "movej" + assert compiled.segments[0].q_samples.shape[1] == 6 diff --git a/tests/control/test_solvers.py b/tests/control/test_solvers.py new file mode 100644 index 0000000..c41e8e1 --- /dev/null +++ b/tests/control/test_solvers.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +import math +from pathlib import Path + +import numpy as np +import pytest +import yaml + +from ufactory.control import ( + ApproxMotionConfig, + CalibratedKinematicsChain, + pose_to_se3, + solve_cartesian_step, + solve_exact_ik, + solve_spherical_wrist_analytical, +) + + +@pytest.mark.parametrize("robot", ("lite6", "uf850")) +def test_analytical_pieper_ik_recovers_all_branches_and_exact_pose(robot: str) -> None: + chain = CalibratedKinematicsChain.from_robot(robot) + rng = np.random.default_rng(77 if robot == "lite6" else 88) + tested = 0 + while tested < 25: + q_true = np.array( + [ + rng.uniform(-2.0, 2.0), + rng.uniform(-1.2, 1.2), + rng.uniform(0.3, 2.5) if robot == "lite6" else rng.uniform(-2.5, -0.3), + rng.uniform(-2.5, 2.5), + rng.uniform(-1.5, 1.5), + rng.uniform(-2.5, 2.5), + ], + dtype=np.float64, + ) + if abs(q_true[4]) < 0.08: + continue + target = chain.forward_matrix(q_true, include_tcp=False) + branches = solve_spherical_wrist_analytical(chain, target, seed_q_rad=q_true + rng.normal(0.0, 0.03, size=6)) + assert len(branches) >= 2 + for cand in branches: + pos_err, rot_err = chain.pose_error(target, chain.forward_matrix(cand, include_tcp=False)) + # Nominal URDF uses rounded 1.5708 for pi/2 (~3.7e-6 rad -> ~2 um residual before polish) + assert pos_err < 2e-5 + assert rot_err < 5e-5 + # Closest branch to slightly perturbed seed must recover q_true closely + # (URDF 1.5708 rounding introduces up to ~2e-4 rad before polish when r_xy is small) + assert float(np.max(np.abs(branches[0] - q_true))) < 5e-4 + + # Full exact solver (analytical + polish) reaches < 1e-7 m / 1e-5 rad + res = solve_exact_ik(chain, target, seed_q_rad=q_true + rng.normal(0.0, 0.05, size=6), include_tcp=False) + assert res.position_error_m < 1e-7 + assert res.orientation_error_rad < 1e-5 + assert float(np.max(np.abs(res.q_rad - q_true))) < 1e-4 + assert res.solver.startswith("analytical-pieper") + tested += 1 + + +@pytest.mark.parametrize("robot", ("lite6", "uf850")) +def test_analytical_ik_handles_wrist_singularity_and_calibrated_polish(robot: str, tmp_path: Path) -> None: + nom = CalibratedKinematicsChain.from_robot(robot) + # Exact wrist singularity q5 = 0 + q_sing = np.array([0.2, -0.3, 1.0 if robot == "lite6" else -1.0, 0.5, 0.0, -0.4], dtype=np.float64) + target_sing = nom.forward_matrix(q_sing, include_tcp=False) + branches = solve_spherical_wrist_analytical(nom, target_sing, seed_q_rad=q_sing) + assert len(branches) >= 1 + pos_err, rot_err = nom.pose_error(target_sing, nom.forward_matrix(branches[0], include_tcp=False)) + assert pos_err < 2e-5 and rot_err < 5e-5 + + # Synthetic calibration perturbation (breaks exact spherical wrist by ~1 mm & 3 mrad) + joints = {} + for idx, name in enumerate(nom.joint_names): + row = nom.nominal_origins[idx].copy() + if idx in (3, 4, 5): + row[0] += 0.0004 * (idx - 2) + row[1] -= 0.0003 + row[4] += 0.0012 + joints[name] = {k: float(v) for k, v in zip(("x", "y", "z", "roll", "pitch", "yaw"), row, strict=True)} + cal_path = tmp_path / f"{robot}_kinematics_CAL00001.yaml" + cal_path.write_text( + yaml.safe_dump( + { + "schema_version": 1, + "robot_key": nom.robot_key, + "serial_number": "TESTSERIAL0001", + "units": {"position": "m", "angle": "rad"}, + "joints": joints, + } + ), + encoding="utf-8", + ) + comp = CalibratedKinematicsChain.from_robot( + robot, + calibration_path=cal_path, + tcp_offset_mm_rpy=[0.0, 0.0, 80.0, 0.0, 0.0, 0.2], + ) + q_ref = np.array([0.1, -0.4, 0.9 if robot == "lite6" else -0.9, 0.2, 0.5, -0.3], dtype=np.float64) + target = comp.forward_matrix(q_ref, include_tcp=True) + res = solve_exact_ik(comp, target, seed_q_rad=q_ref + np.array([0.1, -0.1, 0.1, -0.1, 0.1, 0.1]), include_tcp=True) + assert res.position_error_m < 1e-7 + assert res.orientation_error_rad < 1e-5 + + +@pytest.mark.parametrize("robot", ("xarm6", "xarm7")) +def test_iterative_ik_xarm6_and_xarm7_converge_with_tcp_offset(robot: str) -> None: + chain = CalibratedKinematicsChain.from_robot(robot, tcp_offset_mm_rpy=[0.0, 0.0, 174.0, 0.0, 0.0, 0.0]) + q_true = ( + np.array([0.2, -0.4, -0.6, 0.3, 1.0, -0.2], dtype=np.float64) + if robot == "xarm6" + else np.array([0.2, -0.4, 0.1, 0.8, -0.1, 1.0, -0.2], dtype=np.float64) + ) + target = chain.forward_matrix(q_true, include_tcp=True) + seed = q_true + 0.08 * np.ones_like(q_true) + res = solve_exact_ik(chain, target, seed_q_rad=seed, include_tcp=True) + assert res.position_error_m < 1e-7 + assert res.orientation_error_rad < 1e-5 + if robot == "xarm7": + # Redundant arm stays close to seed (no wild elbow drift) + assert float(np.linalg.norm(res.q_rad - seed)) < 0.35 + + +def test_xarm7_cold_start_converges_without_nullspace_chord_stall() -> None: + chain = CalibratedKinematicsChain.from_robot("xarm7") + target = pose_to_se3([300.0, 0.0, 260.0, math.pi, 0.0, 0.0], position_in_mm=True) + seed = np.array([0.0, -0.5, 0.0, 0.0, 0.5, 0.0, 0.0], dtype=np.float64) + res = solve_exact_ik(chain, target, seed_q_rad=seed, include_tcp=False, cold_start_fallback=True) + assert res.solver == "iterative-7dof-redundant" + assert res.position_error_m < 1e-7 + assert res.orientation_error_rad < 1e-5 + + +def test_xarm5_position_priority_ik_tolerates_non_coplanar_calibration(tmp_path: Path) -> None: + nom = CalibratedKinematicsChain.from_robot("xarm5") + # Introduce realistic non-coplanar ~1.5 mrad roll tilt on joint 2/3 + joints = {} + for idx, name in enumerate(nom.joint_names): + row = nom.nominal_origins[idx].copy() + if idx == 1: + row[4] += 0.0015 + if idx == 4: + row[0] += 0.0005 + joints[name] = {k: float(v) for k, v in zip(("x", "y", "z", "roll", "pitch", "yaw"), row, strict=True)} + cal_path = tmp_path / "xarm5_kinematics_TEST0005.yaml" + cal_path.write_text( + yaml.safe_dump( + { + "schema_version": 1, + "robot_key": nom.robot_key, + "serial_number": "XF130505TEST05", + "units": {"position": "m", "angle": "rad"}, + "joints": joints, + } + ), + encoding="utf-8", + ) + comp = CalibratedKinematicsChain.from_robot("xarm5", calibration_path=cal_path) + target = pose_to_se3([300.0, 0.0, 200.0, math.pi, 0.0, 0.0], position_in_mm=True) + seed = np.array([0.0, -0.5, -0.8, 1.3, 0.0], dtype=np.float64) + res = solve_exact_ik(comp, target, seed_q_rad=seed, include_tcp=False) + assert res.solver == "iterative-5dof-pos-priority" + assert res.position_error_m < 1e-6 # Position priority achieves < 1 um + assert res.orientation_error_rad < 5e-3 # Accepts irreducible ~1.5 mrad roll + + +def test_approx_dls_step_passes_wrist_singularity_and_fails_closed_on_huge_error() -> None: + chain = CalibratedKinematicsChain.from_robot("uf850") + # Put arm right next to wrist singularity (q5 = 0.003 rad) + q_start = np.array([0.0, -0.4, -0.4, 0.02, 0.003, -0.02], dtype=np.float64) + t0 = chain.forward_matrix(q_start, include_tcp=False) + t_next = t0.copy() + t_next[2, 3] -= 0.003 # 3 mm vertical step (50 Hz at 150 mm/s) + + cfg = ApproxMotionConfig(damping=1.0, singular_value_threshold=0.08, trigger_joint_speed_rad_s=0.63) + res = solve_cartesian_step( + chain, + t_next, + q_start, + allow_approx_motion=True, + approx_config=cfg, + dt_s=0.02, + include_tcp=False, + ) + assert res.used_approx + assert res.position_error_m < 0.0005 + assert res.orientation_error_rad < math.radians(1.0) + # Wrist J4/J6 stay damped instead of jumping wildly + assert abs(res.q_rad[3] - q_start[3]) < 0.02 + assert abs(res.q_rad[5] - q_start[5]) < 0.02 + + # Unreachable giant orientation jump must fail closed even with allow_approx_motion=True + t_wild = t0.copy() + t_wild[:3, :3] = t0[:3, :3] @ axis_angle_matrix_y(0.6) + with pytest.raises(ValueError, match="exceeds safety ceiling"): + solve_cartesian_step( + chain, + t_wild, + q_start, + allow_approx_motion=True, + approx_config=cfg, + dt_s=0.02, + include_tcp=False, + ) + + +def axis_angle_matrix_y(theta: float) -> np.ndarray: + c, s = math.cos(theta), math.sin(theta) + return np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]], dtype=np.float64) + + +def test_nominal_uf850_continuous_tracking_across_q5_zero_avoids_urdf_rounding_spike() -> None: + from ufactory.control import ArmMotionController + from ufactory.kinematics.orientation import GRIPPER_DOWN_QUAT_XYZW + from ufactory.safety.statistics import compute_motion_statistics + from ufactory.trajectory.profile import linear_cartesian_samples + + ctrl = ArmMotionController.from_robot("uf850", allow_approx_motion=False) + _, q0_list = ctrl.get_inverse_kinematics( + [300.0, 0.0, 288.6, math.pi, 0.0, 0.0], input_is_radian=True, return_is_radian=True + ) + q = np.asarray(q0_list, dtype=np.float64) + pts, _, _ = linear_cartesian_samples( + np.array([0.300, 0.0, 0.2886]), + np.array([0.300, 0.0, 0.1886]), + rate=50.0, + v_max=0.15, + a_max=0.8, + ) + qs = [q.copy()] + xyzs = [ctrl.forward(q)[:3]] + for row in pts: + pose = np.concatenate((row, np.asarray(GRIPPER_DOWN_QUAT_XYZW))) + q = ctrl.solve_step(pose, q, dt_s=0.02, include_tcp=False).q_rad + qs.append(q.copy()) + xyzs.append(ctrl.forward(q)[:3]) + stats = compute_motion_statistics(np.stack(qs), np.stack(xyzs), rate_hz=50.0) + assert stats.max_joint_speed_rad_s < 1.0 + assert stats.max_joint_acceleration_rad_s2 < 12.0 diff --git a/tests/hardware/test_ft_sensor.py b/tests/hardware/test_ft_sensor.py new file mode 100644 index 0000000..9939064 --- /dev/null +++ b/tests/hardware/test_ft_sensor.py @@ -0,0 +1,462 @@ +"""Offline unit tests for ufactory.hardware.ft_sensor and scripts/ft_sensor_check.py.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +import sys +from types import SimpleNamespace +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from ufactory.hardware import ( + AI1500_MASS_KG, + AI1500_OVERLOAD, + AI1500_RANGE, + FT_COORD_BASE, + FT_COORD_TOOL, + FT_MODE_ADMITTANCE, + FT_MODE_FORCE, + FT_MODE_OFF, + FTAdmittanceParams, + FTCollisionConfig, + FTForceControlParams, + FTLoadOffset, + FTSensorConfigSnapshot, + FTSensorReading, + XArmFTSensor, + XArmTransport, + describe_ft_sensor_error, +) + +PROJECT_ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(PROJECT_ROOT)) +from scripts import ft_sensor_check # noqa: E402 + + +def _make_ft_arm( + *, state: int = 0, mode: int = 0, error_code: int = 0, warn_code: int = 0, axis: int = 6, device_type: int = 6 +) -> MagicMock: + arm = MagicMock() + arm.connected = True + arm.state = state + arm.mode = mode + arm.error_code = error_code + arm.warn_code = warn_code + arm.axis = axis + arm.device_type = device_type + arm.get_state.return_value = (0, state) + arm.motion_enable.return_value = 0 + arm.set_mode.return_value = 0 + arm.set_state.return_value = 0 + arm.set_ft_sensor_enable.return_value = 0 + arm.set_ft_sensor_mode.return_value = 0 + arm.get_ft_sensor_mode.return_value = (0, 0) + arm.set_ft_sensor_zero.return_value = 0 + arm.iden_ft_sensor_load_offset.return_value = (0, [0.8, 1.0, -2.0, 45.0, 0.1, -0.2, -7.8, 0.01, -0.02, 0.005]) + arm.set_ft_sensor_load_offset.return_value = 0 + arm.set_ft_sensor_admittance_parameters.return_value = 0 + arm.set_ft_sensor_force_parameters.return_value = 0 + arm.get_ft_sensor_data.return_value = (0, [0.5, -0.5, -9.8, 0.01, -0.02, 0.03]) + arm.ft_raw_force = [1.0, 2.0, 3.0, 0.1, 0.2, 0.3] + arm.ft_ext_force = [0.2, -0.1, -5.0, 0.01, 0.0, -0.02] + arm.get_ft_sensor_error.return_value = (0, 0) + arm.get_ft_sensor_sn.return_value = (0, "AI150000000001") + arm.get_ft_sensor_version.return_value = (0, "1.2.3") + arm.get_ft_sensor_config.return_value = ( + 0, + [ + 0, + 1, + 1, + 1, + 200, + 0.6, + 0.0, + [0.0, 0.0, 22.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + 1, + [1, 1, 1, 0, 0, 0], + [0.1, 0.1, 0.1, 0.002, 0.002, 0.002], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [20.0, 20.0, 20.0, 1.0, 1.0, 1.0], + 1, + [0, 0, 1, 0, 0, 0], + [0.0, 0.0, -5.0, 0.0, 0.0, 0.0], + [50.0, 50.0, 50.0, 10.0, 10.0, 10.0], + [0.001] * 6, + [0.0] * 6, + [0.0] * 6, + [50.0] * 6, + ], + ) + arm.set_ft_collision_detection.return_value = 0 + arm.get_ft_collision_detection.return_value = (0, 1) + arm.set_ft_collision_threshold.return_value = 0 + arm.get_ft_collision_threshold.return_value = (0, [50.0, 50.0, 50.0, 1.0, 1.0, 1.0]) + arm.set_ft_collision_rebound.return_value = 0 + arm.get_ft_collision_rebound.return_value = (0, 1) + arm.set_ft_collision_reb_distance.return_value = 0 + arm.get_ft_collision_reb_distance.return_value = (0, [10.0, 10.0, 10.0, 0.1, 0.1, 0.1]) + arm.set_ft_admittance_ctrl_threshold.return_value = 0 + arm.get_ft_admittance_ctrl_threshold.return_value = (0, [1.0, 1.0, 1.0, 0.1, 0.1, 0.1]) + return arm + + +def test_dataclass_validation_and_bounds() -> None: + reading = FTSensorReading.from_wrench([400.1, -10.0, 600.0, 20.0, 20.1, -30.0], is_raw=False, monotonic_ns=123) + assert reading.overrange == (True, False, True, False, True, True) + assert reading.overload == (False, False, True, False, False, True) + assert reading.any_overrange and reading.any_overload + assert reading.force_n == (400.1, -10.0, 600.0) + assert reading.torque_nm == (20.0, 20.1, -30.0) + np.testing.assert_allclose(reading.as_array(), [400.1, -10.0, 600.0, 20.0, 20.1, -30.0]) + assert AI1500_RANGE == (400.0, 400.0, 400.0, 20.0, 20.0, 20.0) + assert AI1500_OVERLOAD == (600.0, 600.0, 600.0, 30.0, 30.0, 30.0) + assert AI1500_MASS_KG == pytest.approx(0.6) + + with pytest.raises(ValueError, match="finite"): + FTSensorReading.from_wrench([0, 0, float("nan"), 0, 0, 0], is_raw=False) + with pytest.raises(ValueError, match="length 6"): + FTSensorReading.from_wrench([0, 0, 0], is_raw=True) + + load = FTLoadOffset.from_sdk_list([0.8, 1.0, 2.0, 3.0, 0.1, 0.2, 0.3, 0.01, 0.02, 0.03]) + assert load.to_sdk_list() == [0.8, 1.0, 2.0, 3.0, 0.1, 0.2, 0.3, 0.01, 0.02, 0.03] + with pytest.raises(ValueError, match="non-negative"): + FTLoadOffset(-0.1, (0.0, 0.0, 0.0), (0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) + + adm = FTAdmittanceParams( + coord=FT_COORD_TOOL, + c_axis=(1, 1, 1, 0, 0, 0), + M=(0.02, 0.5, 1.0, 0.0001, 0.005, 0.01), + K=(0.0, 500.0, 2000.0, 0.0, 5.0, 20.0), + B=(0.0, 10.0, 20.0, 0.1, 1.0, 2.0), + ) + assert adm.coord == 1 + with pytest.raises(ValueError, match="coord"): + FTAdmittanceParams(2, (1, 0, 0, 0, 0, 0), (0.1, 0.1, 0.1, 0.001, 0.001, 0.001), (0,) * 6, (1,) * 6) + with pytest.raises(ValueError, match="integer 0 or 1"): + FTAdmittanceParams(0, (True, 0, 0, 0, 0, 0), (0.1, 0.1, 0.1, 0.001, 0.001, 0.001), (0,) * 6, (1,) * 6) # type: ignore[arg-type] + with pytest.raises(ValueError, match=r"M\[0\]"): + FTAdmittanceParams(0, (1, 0, 0, 0, 0, 0), (0.01, 0.1, 0.1, 0.001, 0.001, 0.001), (0,) * 6, (1,) * 6) + with pytest.raises(ValueError, match=r"K\[3\]"): + FTAdmittanceParams(0, (1, 0, 0, 0, 0, 0), (0.1, 0.1, 0.1, 0.001, 0.001, 0.001), (0, 0, 0, 25.0, 0, 0), (1,) * 6) + with pytest.raises(ValueError, match=r"B\[0\]"): + FTAdmittanceParams(0, (1, 0, 0, 0, 0, 0), (0.1, 0.1, 0.1, 0.001, 0.001, 0.001), (0,) * 6, (-1,) * 6) + + fc = FTForceControlParams( + coord=FT_COORD_BASE, + c_axis=(0, 0, 1, 0, 0, 0), + f_ref=(0, 0, -20.0, 0, 0, 0), + limits=(50, 50, 50, 10, 10, 10), + kp=(0.05,) * 6, + ki=(0.0005,) * 6, + kd=(0.05,) * 6, + xe_limit=(200.0,) * 6, + ) + assert fc.coord == 0 + with pytest.raises(ValueError, match=r"f_ref\[2\]"): + FTForceControlParams( + 0, (0, 0, 1, 0, 0, 0), (0, 0, 201, 0, 0, 0), (10,) * 6, (0.01,) * 6, (0,) * 6, (0,) * 6, (10,) * 6 + ) + with pytest.raises(ValueError, match=r"ki\[0\]"): + FTForceControlParams( + 0, (0, 0, 1, 0, 0, 0), (0, 0, -5, 0, 0, 0), (10,) * 6, (0.01,) * 6, (0.001,) * 6, (0,) * 6, (10,) * 6 + ) + + +def test_robot_compatibility_and_error_descriptions() -> None: + arm = _make_ft_arm() + for robot in ("xarm5", "xarm6_1305", "xarm7", "uf850"): + assert XArmFTSensor(arm, robot_key=robot).robot_key is not None + with pytest.raises(ValueError, match="does not support F/T sensor"): + XArmFTSensor(arm, robot_key="lite6") + + assert describe_ft_sensor_error(0) == "Normal" + assert "Communication" in describe_ft_sensor_error(64) + assert "Fx" in describe_ft_sensor_error(66) + assert "code=99" in describe_ft_sensor_error(99) + + +def test_read_methods_and_fail_closed_errors() -> None: + arm = _make_ft_arm() + ft = XArmFTSensor(arm, robot_key="xarm6") + + snap = ft.read_config() + assert isinstance(snap, FTSensorConfigSnapshot) + assert snap.ft_freq == 200 + assert snap.ft_mass_kg == pytest.approx(0.6) + assert snap.ft_centroid == (0.0, 0.0, 22.0) + + status = ft.read_status(include_identity=True) + assert status.mode == 0 + assert status.error_code == 0 + assert status.enabled is True + assert status.serial_number == "AI150000000001" + assert status.firmware_version == "1.2.3" + + r_ext = ft.read_wrench() + assert not r_ext.is_raw + assert r_ext.wrench == (0.5, -0.5, -9.8, 0.01, -0.02, 0.03) + r_rep = ft.read_wrench(is_raw=True, from_report=True) + assert r_rep.is_raw + assert r_rep.wrench == (1.0, 2.0, 3.0, 0.1, 0.2, 0.3) + + col_cfg = ft.read_collision_config(is_radian=True) + assert isinstance(col_cfg, FTCollisionConfig) + assert col_cfg.enabled and col_cfg.rebound_enabled + assert ft.read_admittance_threshold() == (1.0, 1.0, 1.0, 0.1, 0.1, 0.1) + + # Unplugged / comm error fails closed cleanly. + arm.get_ft_sensor_data.return_value = (1, [0.0] * 6) + with pytest.raises(RuntimeError, match="get_ft_sensor_data failed"): + ft.read_wrench() + arm.get_ft_sensor_sn.return_value = (0, "**************") + with pytest.raises(RuntimeError, match="Invalid F/T sensor serial number"): + ft.read_serial_number() + + # Fallback to arm._arm for xarm-python-sdk 1.18.4 where XArmAPI omits SN/version wrappers. + inner = SimpleNamespace( + get_ft_sensor_sn=lambda: (0, "AI15000626001F"), + get_ft_sensor_version=lambda: (0, "1.1.1"), + ) + wrapper_like = SimpleNamespace(_arm=inner) + ft_wrapped = XArmFTSensor(wrapper_like, robot_key="xarm6") + assert ft_wrapped.read_serial_number() == "AI15000626001F" + assert ft_wrapped.read_firmware_version() == "1.1.1" + with pytest.raises(RuntimeError, match="does not expose get_ft_sensor_sn"): + XArmFTSensor(SimpleNamespace(), robot_key="xarm6").read_serial_number() + + +def test_safety_gates_never_clean_errors_and_always_stop_in_finally(monkeypatch: pytest.MonkeyPatch) -> None: + import ufactory.hardware.ft_sensor as ft_mod + + monkeypatch.setattr(ft_mod.time, "sleep", lambda _s: None) + arm = _make_ft_arm() + ft = XArmFTSensor(arm, robot_key="xarm6") + + # confirm_real gate blocks motion-capable operations. + with pytest.raises(RuntimeError, match="confirm_real=True"): + ft.identify_load_offset() + with pytest.raises(RuntimeError, match="confirm_real=True"): + ft.set_mode(FT_MODE_ADMITTANCE) + with pytest.raises(RuntimeError, match="confirm_real=True"): + ft.set_mode(FT_MODE_FORCE) + # Turning mode OFF never requires confirm_real and does not re-enter motion state. + arm.set_state.reset_mock() + ft.set_mode(FT_MODE_OFF) + arm.set_ft_sensor_mode.assert_called_with(0) + arm.set_state.assert_not_called() + + # Controller error / stop / warn / FT error refuse active ops without calling clean_error/clean_warn. + adm = FTAdmittanceParams(1, (1, 1, 1, 0, 0, 0), (0.1,) * 3 + (0.002,) * 3, (300.0,) * 3 + (4.0,) * 3, (0.0,) * 6) + arm.error_code = 10 + with pytest.raises(RuntimeError, match="active error"): + ft.set_mode(FT_MODE_ADMITTANCE, confirm_real=True) + arm.error_code = 0 + arm.warn_code = 3 + with pytest.raises(RuntimeError, match="active warning"): + ft.zero() + arm.warn_code = 0 + arm.get_ft_sensor_error.return_value = (0, 64) + with pytest.raises(RuntimeError, match="64"): + with ft.admittance_session(adm, confirm_real=True): + pass + arm.clean_error.assert_not_called() + arm.clean_warn.assert_not_called() + + # Context managers prepare motion state, call set_state(0) after mode activation, + # and guarantee mode=0 teardown on both normal exit and body exception. + arm.get_ft_sensor_error.return_value = (0, 0) + arm.set_ft_sensor_mode.reset_mock() + arm.set_state.reset_mock() + arm.motion_enable.reset_mock() + with pytest.raises(ValueError, match="boom"): + with ft.admittance_session( + adm, + confirm_real=True, + reaction_threshold=(1.0, 1.0, 1.0, 0.1, 0.1, 0.1), + zero_on_enter=True, + disable_on_exit=True, + ): + raise ValueError("boom") + mode_calls = [call.args[0] for call in arm.set_ft_sensor_mode.call_args_list] + assert mode_calls == [FT_MODE_ADMITTANCE, FT_MODE_OFF] + arm.motion_enable.assert_called_with(enable=True) + assert arm.set_state.call_count == 2 # prepare_arm_for_motion + post-mode activation + arm.set_ft_sensor_enable.assert_any_call(True) + arm.set_ft_sensor_enable.assert_any_call(False) + + fc = FTForceControlParams( + 1, + (0, 0, 1, 0, 0, 0), + (0, 0, -2, 0, 0, 0), + (0,) * 6, + (0.001,) * 6, + (0,) * 6, + (0,) * 6, + (10, 10, 10, 0.2, 0.2, 0.2), + ) + arm.set_ft_sensor_mode.reset_mock() + arm.set_state.reset_mock() + with ft.force_control_session(fc, confirm_real=True): + pass + assert [c.args[0] for c in arm.set_ft_sensor_mode.call_args_list] == [FT_MODE_FORCE, FT_MODE_OFF] + assert arm.set_state.call_count == 2 + + # RET_IS_INVALID (code=10) from identify_load_offset yields actionable hint. + arm.iden_ft_sensor_load_offset.return_value = (10, [0.5, -1898.0, 3085.0, -34954.0, 0, 0, 0, 0, 0, 0]) + with pytest.raises(RuntimeError, match="RET_IS_INVALID"): + ft.identify_load_offset(confirm_real=True) + + +def test_collision_and_load_configuration_calls() -> None: + arm = _make_ft_arm() + ft = XArmFTSensor(arm, robot_key="uf850") + offset = ft.identify_load_offset(confirm_real=True) + ft.set_load_offset(offset, update_tcp_load=True) + arm.set_ft_sensor_load_offset.assert_called_once_with(offset.to_sdk_list(), association_setting_tcp_load=True) + + ft.configure_collision_detection( + enabled=True, + thresholds=(20.0, 20.0, 20.0, 1.0, 1.0, 1.0), + rebound=True, + rebound_distance=(10.0, 10.0, 10.0, math.radians(5.0), math.radians(5.0), math.radians(5.0)), + is_radian=True, + ) + arm.set_ft_collision_threshold.assert_called_once() + arm.set_ft_collision_reb_distance.assert_called_once() + arm.set_ft_collision_rebound.assert_called_once_with(True) + arm.set_ft_collision_detection.assert_called_once_with(True) + + with pytest.raises(ValueError, match="collision_thresholds"): + ft.configure_collision_detection(thresholds=(1.0, 20.0, 20.0, 1.0, 1.0, 1.0)) + with pytest.raises(ValueError, match="rebound_distance"): + ft.configure_collision_detection(rebound_distance=(1.0, 10.0, 10.0, 5.0, 5.0, 5.0), is_radian=False) + + # XArmTransport.ft_sensor factory integrates cleanly. + transport = XArmTransport(arm, robot_key="xarm6_1305", serial_number="XI1305000001") + assert isinstance(transport.ft_sensor(), XArmFTSensor) + assert transport.ft_sensor().robot_key == "xarm6_1305" + + +def test_ft_sensor_check_cli_mock( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + import ufactory.hardware.ft_sensor as ft_mod + + arm = _make_ft_arm() + monkeypatch.setattr(ft_sensor_check.time, "sleep", lambda _s: None) + monkeypatch.setattr(ft_mod.time, "sleep", lambda _s: None) + + assert ( + ft_sensor_check.main( + ["status", "--robot", "xarm6", "--ip", "mock", "--include-identity", "--json"], arm_factory=lambda _ip: arm + ) + == 0 + ) + out = json.loads(capsys.readouterr().out) + assert out["status"]["serial_number"] == "AI150000000001" + arm.disconnect.assert_called() + + arm.disconnect.reset_mock() + arm.set_ft_sensor_enable.reset_mock() + arm.set_ft_sensor_mode.reset_mock() + assert ( + ft_sensor_check.main(["enable", "--robot", "xarm6", "--ip", "mock", "--json"], arm_factory=lambda _ip: arm) == 0 + ) + enable_out = json.loads(capsys.readouterr().out) + assert enable_out["command"] == "enable" + assert enable_out["status"]["enabled"] is True + arm.set_ft_sensor_enable.assert_called_once_with(True) + + arm.set_ft_sensor_enable.reset_mock() + arm.set_ft_sensor_mode.reset_mock() + assert ( + ft_sensor_check.main(["disable", "--robot", "xarm6", "--ip", "mock", "--json"], arm_factory=lambda _ip: arm) + == 0 + ) + disable_out = json.loads(capsys.readouterr().out) + assert disable_out["command"] == "disable" + arm.set_ft_sensor_mode.assert_called_once_with(FT_MODE_OFF) + arm.set_ft_sensor_enable.assert_called_once_with(False) + + arm.disconnect.reset_mock() + assert ( + ft_sensor_check.main(["zero", "--robot", "xarm6", "--ip", "mock", "--json"], arm_factory=lambda _ip: arm) == 0 + ) + arm.set_ft_sensor_zero.assert_called_once() + + # Motion commands refuse without --confirm-real BEFORE connecting. + called = False + + def fail_if_connected(_ip: str): + nonlocal called + called = True + return SimpleNamespace() + + with pytest.raises(RuntimeError, match="--confirm-real"): + ft_sensor_check.main(["identify-load", "--robot", "xarm6", "--ip", "mock"], arm_factory=fail_if_connected) + with pytest.raises(RuntimeError, match="--confirm-real"): + ft_sensor_check.main(["admittance-test", "--robot", "xarm6", "--ip", "mock"], arm_factory=fail_if_connected) + with pytest.raises(RuntimeError, match="--confirm-real"): + ft_sensor_check.main(["force-test", "--robot", "xarm6", "--ip", "mock"], arm_factory=fail_if_connected) + assert not called + + with pytest.raises(SystemExit): + ft_sensor_check.main(["status", "--robot", "lite6", "--ip", "mock"], arm_factory=lambda _ip: arm) + + out_json = tmp_path / "load.json" + assert ( + ft_sensor_check.main( + [ + "identify-load", + "--robot", + "xarm6", + "--ip", + "mock", + "--confirm-real", + "--apply", + "--output", + str(out_json), + "--json", + ], + arm_factory=lambda _ip: arm, + ) + == 0 + ) + assert out_json.is_file() + + arm.set_ft_sensor_mode.reset_mock() + assert ( + ft_sensor_check.main( + [ + "admittance-test", + "--robot", + "xarm6", + "--ip", + "mock", + "--confirm-real", + "--duration", + "0", + "--zero", + "--json", + ], + arm_factory=lambda _ip: arm, + ) + == 0 + ) + assert [c.args[0] for c in arm.set_ft_sensor_mode.call_args_list] == [FT_MODE_ADMITTANCE, FT_MODE_OFF] + + arm.set_ft_sensor_mode.reset_mock() + assert ( + ft_sensor_check.main( + ["force-test", "--robot", "xarm6", "--ip", "mock", "--confirm-real", "--duration", "0", "--json"], + arm_factory=lambda _ip: arm, + ) + == 0 + ) + assert [c.args[0] for c in arm.set_ft_sensor_mode.call_args_list] == [FT_MODE_FORCE, FT_MODE_OFF] diff --git a/tests/kinematics/test_controller_fk.py b/tests/kinematics/test_controller_fk.py new file mode 100644 index 0000000..cb21524 --- /dev/null +++ b/tests/kinematics/test_controller_fk.py @@ -0,0 +1,191 @@ +"""Calibration export: joint origins identified from (synthetic) controller FK.""" + +from __future__ import annotations + +import argparse +import importlib.util +import math +from pathlib import Path + +import numpy as np +import pytest + +from ufactory.kinematics import build_calibrated_urdf, load_kinematics_calibration +from ufactory.kinematics.controller_fk import ( + CalibrationIdentificationError, + chain_pose, + controller_flange_fk, + identify_from_controller_fk, + load_nominal_chain, + matrix_rpy, + rotation_angle, + sweep_angles, +) +from ufactory.kinematics.tcp_offset import matrix_to_pose, pose_to_matrix, rpy_matrix +from ufactory.robots.registry import ROBOT_PROFILES, get_robot_profile, joint_names + +ROOT = Path(__file__).resolve().parents[2] +ROBOTS = ("xarm5", "xarm6", "xarm7", "uf850", "lite6") + + +def _chain(robot: str): + profile = get_robot_profile(robot) + return load_nominal_chain(profile.assets_dir / profile.default_urdf, joint_names(profile)) + + +def _flange(offset_m: float, tilt_rad: float) -> np.ndarray: + flange = np.eye(4) + flange[:3, :3] = rpy_matrix(tilt_rad, 0.5 * tilt_rad, 0.25 * tilt_rad) + flange[:3, 3] = (0.6 * offset_m, -0.8 * offset_m, 0.0) + return flange + + +def _controller(chain, *, seed=1, offset_m=200e-6, tilt_rad=math.radians(0.02), perturb=True): + """Rigid controller chain: perturbed joint origins, flange off the last axis.""" + + rng = np.random.default_rng(seed) + origins = chain.origins.copy() + if perturb: + origins[:, :3] += rng.uniform(-1e-3, 1e-3, size=(len(origins), 3)) + origins[:, 3:] += rng.uniform(-math.radians(0.2), math.radians(0.2), size=(len(origins), 3)) + flange = _flange(offset_m, tilt_rad) + return lambda q: chain_pose(origins, chain.axes, q) @ flange + + +@pytest.mark.parametrize("robot", ROBOTS) +def test_identified_origins_reproduce_the_controller(robot): + chain = _chain(robot) + controller = _controller(chain) + result = identify_from_controller_fk(controller, chain, verification_samples=40) + + assert result.rigid_chain_error_m < 1e-9 + assert result.flange_axis_offset_m == pytest.approx(200e-6, abs=1e-9) + assert result.flange_axis_tilt_rad == pytest.approx(math.hypot(1.0, 0.5) * math.radians(0.02), rel=1e-3) + # Exact whenever the last joint is at 0; otherwise within twice the flange offset. + rng = np.random.default_rng(7) + for q in rng.uniform(-1.0, 1.0, size=(20, len(chain.joint_names))): + q[-1] = 0.0 + model, reference = chain_pose(result.origins, chain.axes, q), controller(q) + assert np.linalg.norm(model[:3, 3] - reference[:3, 3]) < 1e-9 + assert rotation_angle(model[:3, :3], reference[:3, :3]) < 1e-9 + assert result.max_position_error_m <= 2 * 200e-6 + 1e-9 + + +@pytest.mark.parametrize("robot", ROBOTS) +def test_nominal_controller_gives_the_nominal_urdf_origins(robot): + chain = _chain(robot) + result = identify_from_controller_fk( + _controller(chain, perturb=False, offset_m=0.0, tilt_rad=0.0), chain, verification_samples=10 + ) + + assert result.max_position_error_m < 1e-9 + np.testing.assert_allclose(result.origins[:, :3], chain.origins[:, :3], atol=1e-9) + for identified, nominal in zip(result.origins, chain.origins, strict=True): + assert rotation_angle(rpy_matrix(*identified[3:]), rpy_matrix(*nominal[3:])) < 1e-9 + + +def test_non_rigid_controller_wrong_model_and_large_flange_offset_are_refused(): + chain = _chain("xarm6") + rigid = _controller(chain) + + def sagging(q): + pose = rigid(q) + pose[2, 3] -= 1e-4 * q[1] * q[2] + return pose + + with pytest.raises(CalibrationIdentificationError, match="not a rigid chain"): + identify_from_controller_fk(sagging, chain, verification_samples=20) + with pytest.raises(CalibrationIdentificationError, match="nominal URDF"): + identify_from_controller_fk(_controller(_chain("uf850")), chain, verification_samples=20) + with pytest.raises(CalibrationIdentificationError, match="miss controller FK"): + identify_from_controller_fk(_controller(chain, offset_m=0.8e-3), chain, verification_samples=40) + + +def test_sweep_angles_cover_one_sided_joints_and_reject_tiny_ranges(): + lower, upper = _chain("xarm5").lower[2], _chain("xarm5").upper[2] + angles = sweep_angles(float(lower), float(upper)) + + assert len(angles) >= 4 and all(lower <= a <= upper and abs(a) > 0.04 for a in angles) + assert sweep_angles(-3.0, 3.0) == (-1.5, -1.0, -0.5, 0.5, 1.0, 1.5) + with pytest.raises(CalibrationIdentificationError): + sweep_angles(-0.01, 0.01) + + +@pytest.mark.parametrize("rpy", [(0.3, -0.2, 1.1), (1.2, math.pi / 2, 0.4), (-0.7, -math.pi / 2, 0.0)]) +def test_matrix_rpy_round_trips_including_gimbal_lock(rpy): + rotation = rpy_matrix(*rpy) + + assert rotation_angle(rpy_matrix(*matrix_rpy(rotation)), rotation) < 1e-12 + + +class FakeArm: + """Controller double: SDK FK returns the TCP pose (mm, rad) of a synthetic xArm6.""" + + axis, device_type = 6, 6 + + def __init__(self, *, world_offset=(0.0,) * 6, fail=False): + chain = _chain("xarm6") + self.flange = _controller(chain) + self.tcp_offset = [1.0, -2.0, 174.0, 0.0, 0.01, 0.0] + self.world_offset = list(world_offset) + self.fail = fail + self.calls = 0 + + def get_robot_sn(self): + return 0, "XI130505TEST01" + + def get_forward_kinematics(self, angles, input_is_radian=None, return_is_radian=None): + assert input_is_radian and return_is_radian + self.calls += 1 + if self.fail: + return 1, [] + flange = self.flange(np.asarray(angles)) + flange[:3, 3] *= 1000.0 + return 0, matrix_to_pose(flange @ pose_to_matrix(self.tcp_offset)).tolist() + + +def test_controller_flange_fk_removes_the_tcp_offset(): + arm = FakeArm() + q = np.asarray([0.1, -0.2, 0.3, 0.4, -0.5, 0.6]) + flange = controller_flange_fk(arm, arm.tcp_offset)(q) + + np.testing.assert_allclose(flange, arm.flange(q), atol=1e-12) + with pytest.raises(RuntimeError, match="controller FK failed"): + controller_flange_fk(FakeArm(fail=True), arm.tcp_offset)(q) + + +def _script(): + spec = importlib.util.spec_from_file_location( + "gen_kinematics_params", ROOT / "scripts" / "gen_kinematics_params.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_export_writes_a_loadable_calibration_that_reproduces_the_controller(tmp_path, monkeypatch): + script = _script() + monkeypatch.setattr(script, "_read_world_offset", lambda arm: np.asarray(arm.world_offset)) + arm = FakeArm() + args = argparse.Namespace(kinematics_suffix=None, output_dir=str(tmp_path), force=False) + + assert script._export(arm, args) == 0 + path = tmp_path / "xarm6_kinematics_TEST01.yaml" + calibration = load_kinematics_calibration(str(path), robot_key="xarm6", serial_number="XI130505TEST01") + profile = ROBOT_PROFILES["xarm6_1305"] + urdf = build_calibrated_urdf( + str(profile.assets_dir / profile.default_urdf), calibration, joint_count=6, output_dir=str(tmp_path) + ) + calibrated = load_nominal_chain(urdf, joint_names(profile)) + q = np.asarray([0.2, -0.4, 0.3, 1.0, -0.6, 0.0]) + np.testing.assert_allclose(chain_pose(calibrated.origins, calibrated.axes, q), arm.flange(q), atol=1e-9) + + +def test_export_refuses_a_world_offset_and_writes_nothing(tmp_path, capsys): + script = _script() + arm = FakeArm(world_offset=(10.0, 0.0, 0.0, 0.0, 0.0, 0.0)) + args = argparse.Namespace(kinematics_suffix=None, output_dir=str(tmp_path), force=False) + + assert script._export(arm, args) == 1 + assert "world_offset" in capsys.readouterr().out + assert arm.calls == 0 and not list(tmp_path.iterdir()) diff --git a/tests/manipulation/test_bio_g2_mode_gate.py b/tests/manipulation/test_bio_g2_mode_gate.py new file mode 100644 index 0000000..6be2a99 --- /dev/null +++ b/tests/manipulation/test_bio_g2_mode_gate.py @@ -0,0 +1,186 @@ +"""Mode gates, flange offset, and dry-run preflight for Bio Gripper G2 in pick_place.""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +import pytest + +from ufactory.config import load_runtime_config +from ufactory.grippers.bio_g2 import ( + BIO_G2_CONTROLLER_VALIDATED, + BIO_GRIPPER_G2_TCP_IN_FLANGE_M, + bio_g2_controller_mode_error, +) +from ufactory.manipulation.commands import build_arm_controller +from ufactory.robots.assembly import compose_robot_urdf + + +def _pick_place_module(): + pytest.importorskip("torch") + pytest.importorskip("genesis") + return importlib.import_module("ufactory.cli.pick_place") + + +def test_bio_g2_controller_validation_matrix() -> None: + assert BIO_G2_CONTROLLER_VALIDATED == frozenset({("pick_place", "xarm6")}) + for mode in ("sim", "dry-run"): + assert bio_g2_controller_mode_error("pick_place", "xarm5", "bio_gripper_g2", mode) is None + assert bio_g2_controller_mode_error("pick_place", "xarm6", "bio_gripper_g2", "sdk-sim") is None + assert bio_g2_controller_mode_error("pick_place", "xarm6", "bio_gripper_g2", "real") is None + assert bio_g2_controller_mode_error("pick_place", "xarm6", "g2", "real") is None + for robot in ("xarm5", "xarm7", "uf850"): + for mode in ("sdk-sim", "real"): + err = bio_g2_controller_mode_error("pick_place", robot, "bio_gripper_g2", mode) + assert err is not None and "pick_place on xarm6" in err + + +@pytest.mark.parametrize( + "argv", + [ + ["--robot", "xarm6", "--gripper", "bio_gripper_g2", "--mode", "dry-run"], + [ + "--robot", + "xarm6", + "--gripper", + "bio_gripper_g2", + "--mode", + "sdk-sim", + "--executor", + "servo_j", + "--visual", + ], + [ + "--robot", + "xarm5", + "--gripper", + "bio_gripper_g2", + "--mode", + "sdk-sim", + "--executor", + "servo_cartesian", + ], + [ + "--robot", + "xarm7", + "--gripper", + "bio_gripper_g2", + "--mode", + "real", + "--executor", + "servo_cartesian", + ], + ], +) +def test_bio_g2_non_sim_gates_reject_unsupported_combinations(argv: list[str]) -> None: + module = _pick_place_module() + with pytest.raises(SystemExit) as exc: + module.main(argv) + assert exc.value.code == 2 + + +@pytest.mark.parametrize("executor", ["servo_j", "servo_cartesian"]) +def test_bio_g2_real_visual_passes_gate_and_reaches_ip_check( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + executor: str, +) -> None: + module = _pick_place_module() + monkeypatch.delenv("XARM_IP", raising=False) + with pytest.raises(SystemExit) as exc: + module.main( + [ + "--robot", + "xarm6", + "--gripper", + "bio_gripper_g2", + "--mode", + "real", + "--executor", + executor, + "--visual", + ] + ) + assert exc.value.code == 2 + err = capsys.readouterr().err + error_line = err.splitlines()[-1] + assert "--ip or XARM_IP" in error_line + assert "servo_cartesian" not in error_line + assert "requires --executor servo_cartesian" not in err + + +@pytest.mark.gpu +def test_bio_g2_servo_j_compile_and_dry_run_pass(tmp_path: Path) -> None: + import numpy as np + + from ufactory.simulation import GenesisRuntimeManager + + module = _pick_place_module() + cfg = load_runtime_config("xarm6", gripper="bio_gripper_g2") + with GenesisRuntimeManager(cfg.simulation): + program, ctx, q_home = module._compile_servo_j_program(cfg, calibration=None) + home_pregrasp = next(seg for seg in program.segments if seg.label == "home->pregrasp") + assert home_pregrasp.q_start is not None + assert float(np.max(np.abs(np.asarray(home_pregrasp.q_start, dtype=np.float64) - q_home))) < 2e-3 + assert ctx.gripper_dof_multipliers == (1.0, -1.0) + + report = tmp_path / "bio_dry_run_servo_j.json" + rc = module.main( + [ + "--robot", + "xarm6", + "--gripper", + "bio_gripper_g2", + "--mode", + "dry-run", + "--executor", + "servo_j", + "--report", + str(report), + ] + ) + assert rc == 0 + assert report.is_file() + + +def test_bio_g2_build_program_applies_flange_xy_offset_and_closed_gap() -> None: + module = _pick_place_module() + cfg = load_runtime_config("xarm6", gripper="bio_gripper_g2") + urdf = Path(compose_robot_urdf("xarm6_1305", "bio_gripper_g2")) + kinematics = build_arm_controller(cfg, urdf) + program = module._build_program(cfg, kinematics) + + expected_obj_x = 0.38 - BIO_GRIPPER_G2_TCP_IN_FLANGE_M[0] + descend = next(seg for seg in program.segments if seg.label == "descend") + samples, _ = descend.samples(program.rate) + assert samples[-1, 0] == pytest.approx(expected_obj_x, abs=1e-6) + assert samples[-1, 1] == pytest.approx(-0.12, abs=1e-6) + assert samples[-1, 2] == pytest.approx(0.1595, abs=1e-6) + + grip = next(seg for seg in program.segments if seg.label == "grip") + grip_samples, _ = grip.samples(program.rate) + assert grip.gap_start == pytest.approx(0.150, abs=1e-6) + assert 0.149 < float(grip_samples[0, 0]) <= 0.150 + assert grip_samples[-1, 0] == pytest.approx(0.071, abs=1e-6) + + +def test_bio_g2_xarm6_dry_run_servo_cartesian_passes(tmp_path: Path) -> None: + module = _pick_place_module() + report = tmp_path / "bio_dry_run.json" + rc = module.main( + [ + "--robot", + "xarm6", + "--gripper", + "bio_gripper_g2", + "--mode", + "dry-run", + "--executor", + "servo_cartesian", + "--report", + str(report), + ] + ) + assert rc == 0 + assert report.is_file() diff --git a/tests/manipulation/test_tool_tcp.py b/tests/manipulation/test_tool_tcp.py new file mode 100644 index 0000000..d3152d0 --- /dev/null +++ b/tests/manipulation/test_tool_tcp.py @@ -0,0 +1,98 @@ +"""Unit tests for unified ToolTcpSpec transforms and real-controller TCP consistency checks.""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest + +from ufactory.config import load_runtime_config +from ufactory.manipulation.tcp import ( + DEFAULT_REAL_TCP_POS_TOL_MM, + DEFAULT_REAL_TCP_ROT_TOL_DEG, + ToolTcpSpec, + check_controller_tcp_offset, + resolve_tool_tcp_spec, + tcp_offset_mm_deg_to_mm_rad, + tcp_offset_mm_rad_to_mm_deg, +) +from ufactory.robots.runtime import LITE6_VACUUM_GRIPPER_PARAMS, VACUUM_GRIPPER_PARAMS + + +@pytest.mark.parametrize( + ("robot", "gripper", "expected_grasp_flange_xyz"), + [ + ("xarm6", None, (0.30, 0.00, 0.1886)), + ("xarm5", None, (0.30, 0.00, 0.1886)), + ("xarm7", None, (0.30, 0.00, 0.1886)), + ("uf850", None, (0.30, 0.00, 0.1886)), + ("lite6", None, (0.20, 0.00, 0.0963)), + ("xarm6", "robotiq_2f_85", (0.30, 0.00, 0.1838)), + ("xarm6", "robotiq_2f_140", (0.30, 0.00, 0.2561)), + ("xarm6", "bio_gripper_g2", (0.38 - 0.15764, -0.12, 0.1595)), + ], +) +def test_resolve_tool_tcp_spec_matches_expected_grasp_flange_waypoints( + robot: str, + gripper: str | None, + expected_grasp_flange_xyz: tuple[float, float, float], +) -> None: + cfg = load_runtime_config(robot, gripper=gripper) + spec = resolve_tool_tcp_spec(cfg) + obj = cfg.task.parameters["fixed_object_position_m"] + flange = spec.tcp_to_flange_xyz([float(obj[0]), float(obj[1]), spec.grasp_tcp_z_m]) + np.testing.assert_allclose(flange, expected_grasp_flange_xyz, atol=1e-9) + roundtrip = spec.flange_to_tcp_xyz(flange) + np.testing.assert_allclose(roundtrip, [float(obj[0]), float(obj[1]), spec.grasp_tcp_z_m], atol=1e-9) + + +def test_tool_tcp_spec_zero_dof_and_deg_rad_conversion() -> None: + vac = resolve_tool_tcp_spec(VACUUM_GRIPPER_PARAMS) + assert vac.tcp_offset_mm_deg == (0.0, 0.0, 126.0, 0.0, 0.0, 0.0) + assert vac.tool_tip_link == "vacuum_tcp" + assert vac.tcp_offset_flange_m == pytest.approx((0.0, 0.0, 0.126)) + + lite_vac = resolve_tool_tcp_spec(LITE6_VACUUM_GRIPPER_PARAMS) + assert lite_vac.tcp_offset_mm_deg == (0.0, 0.0, 61.0, 0.0, 0.0, 0.0) + assert lite_vac.tool_tip_link == "link_tcp" + + bare = resolve_tool_tcp_spec(None) + assert bare == ToolTcpSpec() + np.testing.assert_allclose(bare.tcp_to_flange_xyz([0.3, 0.1, 0.2]), [0.3, 0.1, 0.2], atol=1e-12) + + mm_deg = (157.64, 0.0, 59.5, 10.0, -20.0, 45.0) + mm_rad = tcp_offset_mm_deg_to_mm_rad(mm_deg) + np.testing.assert_allclose(mm_rad[:3], [157.64, 0.0, 59.5]) + np.testing.assert_allclose(mm_rad[3:], [math.radians(10.0), math.radians(-20.0), math.radians(45.0)]) + np.testing.assert_allclose(tcp_offset_mm_rad_to_mm_deg(mm_rad), mm_deg, atol=1e-9) + + +def test_check_controller_tcp_offset_tolerates_minor_diff_and_fails_closed_on_real(capsys) -> None: + bio_yaml = (157.64, 0.0, 59.5, 0.0, 0.0, 0.0) + bio_ctrl = (159.5, 0.0, 59.5, 0.0, 0.0, 0.0) + pos_mm, rot_deg = check_controller_tcp_offset(bio_ctrl, bio_yaml, mode="real") + assert pos_mm == pytest.approx(1.86, abs=1e-6) + assert rot_deg == pytest.approx(0.0, abs=1e-6) + assert "tcp_offset check PASS" in capsys.readouterr().out + + # Major position mismatch: YAML bare flange vs controller G2 (172 mm). + g2_ctrl = (0.0, 0.0, 172.0, 0.0, 0.0, 0.0) + bare_yaml = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + with pytest.raises(RuntimeError, match="real motion refused"): + check_controller_tcp_offset(g2_ctrl, bare_yaml, mode="real") + + # sdk-sim warns instead of raising. + pos_mm, rot_deg = check_controller_tcp_offset(g2_ctrl, bare_yaml, mode="sdk-sim") + assert pos_mm == pytest.approx(172.0, abs=1e-6) + assert "WARNING" in capsys.readouterr().out + + # Rotation mismatch > 2 deg fails closed in real mode. + rot_ctrl = (157.64, 0.0, 59.5, 0.0, 0.0, math.radians(DEFAULT_REAL_TCP_ROT_TOL_DEG + 1.0)) + with pytest.raises(RuntimeError, match="real motion refused"): + check_controller_tcp_offset(rot_ctrl, bio_yaml, mode="real") + + # Position mismatch just above 10 mm fails closed in real mode. + edge_ctrl = (157.64, 0.0, 59.5 + DEFAULT_REAL_TCP_POS_TOL_MM + 0.1, 0.0, 0.0, 0.0) + with pytest.raises(RuntimeError, match="real motion refused"): + check_controller_tcp_offset(edge_ctrl, bio_yaml, mode="real") diff --git a/tests/manipulation/test_vacuum_pick_place.py b/tests/manipulation/test_vacuum_pick_place.py new file mode 100644 index 0000000..a091ce1 --- /dev/null +++ b/tests/manipulation/test_vacuum_pick_place.py @@ -0,0 +1,123 @@ +"""Config overlay, mode gates, and offline dry-run preflight for vacuum_gripper in pick_place.""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +import pytest + +from ufactory.config import ConfigError, load_runtime_config +from ufactory.manipulation.commands import build_arm_controller +from ufactory.robots.assembly import compose_robot_urdf + + +def _pick_place_module(): + return importlib.import_module("ufactory.cli.pick_place") + + +@pytest.mark.parametrize("robot", ["xarm5", "xarm6", "xarm7", "uf850"]) +def test_vacuum_gripper_runtime_config_overlay(robot: str) -> None: + cfg = load_runtime_config(robot, gripper="vacuum_gripper") + assert cfg.robot.urdf == "assembly:vacuum_gripper" + assert cfg.gripper is not None + assert cfg.gripper.adapter == "vacuum_gripper" + assert cfg.gripper.has_actuated_joints is False + assert cfg.gripper.real_command is True + assert cfg.gripper.tcp_offset == pytest.approx((0.0, 0.0, 126.0, 0.0, 0.0, 0.0)) + assert cfg.gripper.open_gap_m == pytest.approx(1.0) + assert cfg.gripper.closed_gap_m == pytest.approx(0.0) + + +def test_vacuum_gripper_overlay_rejects_lite6_and_reach() -> None: + with pytest.raises(ConfigError): + load_runtime_config("lite6", gripper="vacuum_gripper") + with pytest.raises(ConfigError): + load_runtime_config("xarm5", task="reach", gripper="vacuum_gripper") + + +@pytest.mark.parametrize( + "argv", + [ + ["--robot", "xarm5", "--gripper", "vacuum_gripper", "--mode", "sim", "--executor", "servo_j"], + ["--robot", "lite6", "--gripper", "vacuum_gripper", "--mode", "dry-run", "--executor", "servo_j"], + ["--robot", "xarm5", "--gripper", "vacuum_gripper", "--mode", "dry-run"], + ], +) +def test_vacuum_pick_place_cli_rejects_invalid_combinations(argv: list[str]) -> None: + module = _pick_place_module() + with pytest.raises(SystemExit) as exc: + module.main(argv) + assert exc.value.code == 2 + + +@pytest.mark.parametrize("executor", ["servo_j", "servo_cartesian"]) +def test_vacuum_real_visual_passes_gate_to_ip_check( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + executor: str, +) -> None: + module = _pick_place_module() + monkeypatch.delenv("XARM_IP", raising=False) + monkeypatch.setattr(module, "require_genesis_capabilities", lambda **_kw: None) + with pytest.raises(SystemExit) as exc: + module.main( + [ + "--robot", + "xarm5", + "--gripper", + "vacuum_gripper", + "--mode", + "real", + "--executor", + executor, + "--visual", + ] + ) + assert exc.value.code == 2 + err = capsys.readouterr().err + assert "--ip or XARM_IP" in err.splitlines()[-1] + + +def test_vacuum_xarm5_program_applies_126mm_tcp_offset() -> None: + module = _pick_place_module() + cfg = load_runtime_config("xarm5", gripper="vacuum_gripper") + urdf = Path(compose_robot_urdf("xarm5_1305", "vacuum_gripper")) + kinematics = build_arm_controller(cfg, urdf) + program = module._build_program(cfg, kinematics) + + descend = next(seg for seg in program.segments if seg.label == "descend") + samples, _ = descend.samples(program.rate) + # grasp_table_clearance_m (0.050) + vacuum TCP Z (0.126) = 0.176 m flange Z + assert samples[-1, 0] == pytest.approx(0.30, abs=1e-6) + assert samples[-1, 1] == pytest.approx(0.00, abs=1e-6) + assert samples[-1, 2] == pytest.approx(0.176, abs=1e-6) + + grip = next(seg for seg in program.segments if seg.label == "grip") + grip_samples, _ = grip.samples(program.rate) + assert grip.gap_start == pytest.approx(1.0, abs=1e-6) + assert grip_samples[-1, 0] == pytest.approx(0.0, abs=1e-6) + + +@pytest.mark.parametrize("executor", ["servo_j", "servo_cartesian"]) +def test_vacuum_xarm5_dry_run_passes(tmp_path: Path, executor: str) -> None: + pytest.importorskip("pinocchio") + pytest.importorskip("coal") + module = _pick_place_module() + report = tmp_path / f"xarm5_vacuum_{executor}.json" + rc = module.main( + [ + "--robot", + "xarm5", + "--gripper", + "vacuum_gripper", + "--mode", + "dry-run", + "--executor", + executor, + "--report", + str(report), + ] + ) + assert rc == 0 + assert report.is_file() diff --git a/tests/robots/test_assembly.py b/tests/robots/test_assembly.py index 27b5835..bb28f1f 100644 --- a/tests/robots/test_assembly.py +++ b/tests/robots/test_assembly.py @@ -149,7 +149,7 @@ def test_stl_visual_override_keeps_the_stl_material(tmp_path: Path) -> None: the fingers still show their collision meshes.""" path = Path(compose_robot_urdf("xarm6", "gripper_g2", visual="stl", out_dir=tmp_path)) root = ET.parse(path).getroot() - meshes = PROJECT_ROOT.resolve() / "assets/urdf/gripper_g2/meshes" + meshes = PROJECT_ROOT.resolve() / "assets/urdf/end_effectors/gripper_g2/meshes" def shown(visual: ET.Element) -> tuple[Path, str]: mesh = (path.parent / visual.find("geometry/mesh").get("filename")).resolve() @@ -280,7 +280,7 @@ def test_bio_gripper_g2_adapter_sits_on_the_xarm_flange() -> None: # Flat faces cannot tilt; a tilted mount also breaks TCP-down IK on xArm5 (5-DOF) and xArm6 (wrist). assert rpy[:2] == (0.0, 0.0) mount = _pose(xyz, rpy) - base = PROJECT_ROOT / "assets/urdf/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_base.glb" + base = PROJECT_ROOT / "assets/urdf/end_effectors/bio_gripper_g2/meshes/visual/visual_glb/bio_gripper_g2_base.glb" mesh = trimesh.load(base, force="mesh") normals = mesh.face_normals @ mount[:3, :3].T centres = mesh.triangles_center @ mount[:3, :3].T + mount[:3, 3] @@ -343,10 +343,10 @@ def _fail(*args: object, **kwargs: object) -> str: raise AssertionError("validation must not compose") monkeypatch.setattr(assembly, "compose_robot_urdf", _fail) - validate_robot_urdf("xarm6", "assembly:gripper_g2", assets_dir="assets/urdf/xarm6", store=store) - validate_robot_urdf("xarm6", "xarm6_1305.urdf", assets_dir="assets/urdf/xarm6", store=store) + validate_robot_urdf("xarm6", "assembly:gripper_g2", assets_dir="assets/urdf/robots/xarm6", store=store) + validate_robot_urdf("xarm6", "xarm6_1305.urdf", assets_dir="assets/urdf/robots/xarm6", store=store) with pytest.raises(AssemblyError): - validate_robot_urdf("lite6", "assembly:gripper_g2", assets_dir="assets/urdf/lite6", store=store) + validate_robot_urdf("lite6", "assembly:gripper_g2", assets_dir="assets/urdf/robots/lite6", store=store) def test_visual_glb_wrapper_maps_flags_to_assemblies() -> None: diff --git a/tests/robots/test_asset_integrity.py b/tests/robots/test_asset_integrity.py index 1335233..52bd56d 100644 --- a/tests/robots/test_asset_integrity.py +++ b/tests/robots/test_asset_integrity.py @@ -65,9 +65,9 @@ def test_public_urdf_mesh_references_exist() -> None: for accessory in accessories() for visual in ("glb", "stl") ] - urdfs += [_URDF_ROOT / "robotiq_mounting" / "robotiq_mounting.urdf"] + urdfs += [_URDF_ROOT / "mounts" / "robotiq_mounting" / "robotiq_mounting.urdf"] urdfs += [ - _URDF_ROOT / f"{plate}/{plate}.urdf" + _URDF_ROOT / f"mounts/{plate}/{plate}.urdf" for plate in ("xarm_mounting_plate", "uf850_mounting_plate", "lite6_mounting_plate") ] urdfs += [ @@ -179,7 +179,7 @@ def test_standard_g2_urdf_joint_origins_and_mesh_alignment() -> None: assert _rounded_xyz(orig.get("xyz")) == (0.0, 0.0, 0.0), (path, lname, tag) assert _rounded_xyz(orig.get("rpy")) == (0.0, 0.0, 0.0), (path, lname, tag) - pkg = PROJECT_ROOT / "assets" / "urdf" / "gripper_g2" / "meshes" + pkg = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "gripper_g2" / "meshes" base_stl = _mesh_vertices(pkg / "visual" / "base_link.stl", trimesh) base_glb = _mesh_vertices(pkg / "visual" / "visual_glb" / "base.glb", trimesh) lf_glb = _mesh_vertices(pkg / "visual" / "visual_glb" / "left_finger.glb", trimesh) @@ -208,7 +208,7 @@ def test_standard_g2_urdf_joint_origins_and_mesh_alignment() -> None: assert actual_axial_mm == pytest.approx(expected_axial_mm, abs=0.01) -_G2_PART = _URDF_ROOT / "gripper_g2" / "gripper_g2_movable_visual.urdf" +_G2_PART = _URDF_ROOT / "end_effectors" / "gripper_g2" / "gripper_g2_movable_visual.urdf" _G2_BASE_GEOMETRY = ("visual/visual_glb/base.glb", "visual/base_link.stl", "collision hulls") @@ -235,7 +235,7 @@ def _g2_base_triangles(geometry: str) -> np.ndarray: if geometry == "collision hulls": names = _collision_meshes_by_link(_G2_PART)["xarm_gripper_base_link"] return np.concatenate([_triangles((_G2_PART.parent / name).resolve()) for name in names]) - return _triangles(_URDF_ROOT / "gripper_g2" / "meshes" / geometry) + return _triangles(_URDF_ROOT / "end_effectors" / "gripper_g2" / "meshes" / geometry) def _section_mm(triangles_mm: np.ndarray, z_mm: float) -> np.ndarray: @@ -282,7 +282,9 @@ def test_gripper_g2_base_collides_as_ten_convex_hulls() -> None: for name, mesh in zip(names, hulls): assert mesh.is_watertight and 1.0 - mesh.volume / mesh.convex_hull.volume <= 1e-5, name assert sum(mesh.volume for mesh in hulls) * 1e6 == pytest.approx(353.2, abs=0.1) - visual = _triangles(_URDF_ROOT / "gripper_g2" / "meshes" / "visual" / "base_link.stl").reshape(-1, 3) + visual = _triangles(_URDF_ROOT / "end_effectors" / "gripper_g2" / "meshes" / "visual" / "base_link.stl").reshape( + -1, 3 + ) np.testing.assert_allclose(np.min([m.bounds[0] for m in hulls], axis=0), visual.min(axis=0), atol=1e-5) np.testing.assert_allclose(np.max([m.bounds[1] for m in hulls], axis=0), visual.max(axis=0), atol=1e-5) @@ -308,8 +310,10 @@ def test_gripper_g2_base_flange_uses_the_arm_flange_material() -> None: """The G2 base GLB shows the flange, centring boss and locating pin in the xArm / UF850 flange material, the +Y connector cover in the fingers' black, and the bearing cover between the fingers (plus its four M3x8 screws) in matte black anodized aluminium; only the outer housing stays white.""" - parts = _glb_material_triangles(_URDF_ROOT / "gripper_g2/meshes/visual/visual_glb/base.glb") - finger = _glb_material_triangles(_URDF_ROOT / "gripper_g2/meshes/visual/visual_glb/left_finger.glb")[0][0] + parts = _glb_material_triangles(_URDF_ROOT / "end_effectors/gripper_g2/meshes/visual/visual_glb/base.glb") + finger = _glb_material_triangles(_URDF_ROOT / "end_effectors/gripper_g2/meshes/visual/visual_glb/left_finger.glb")[ + 0 + ][0] assert len(parts) == 4 [(flange_pbr, flange)] = [(m, t) for m, t in parts if m.metallicFactor > 0.5 and m.baseColorFactor[0] > 0.5] [(bearing_pbr, bearing)] = [(m, t) for m, t in parts if m.metallicFactor > 0.5 and m.baseColorFactor[0] < 0.25] @@ -325,7 +329,10 @@ def test_gripper_g2_base_flange_uses_the_arm_flange_material() -> None: assert bearing[..., 2].min() == pytest.approx(92.94, abs=0.05) assert bearing[..., 2].max() == pytest.approx(101.94, abs=0.05) - for arm_glb in ("xarm6/meshes/xarm6_1305/visual_glb/link6.glb", "uf850/meshes/uf850/visual_glb/link6.glb"): + for arm_glb in ( + "robots/xarm6/meshes/xarm6_1305/visual_glb/link6.glb", + "robots/uf850/meshes/uf850/visual_glb/link6.glb", + ): (arm_pbr,) = [m for m, _ in _glb_material_triangles(_URDF_ROOT / arm_glb) if m.metallicFactor > 0.5] np.testing.assert_allclose(flange_pbr.baseColorFactor, arm_pbr.baseColorFactor, atol=1e-6) assert flange_pbr.metallicFactor == pytest.approx(arm_pbr.metallicFactor, abs=1e-6) @@ -365,12 +372,12 @@ def test_gripper_g2_finger_pads_use_white_translucent_silicone() -> None: pygltflib = pytest.importorskip("pygltflib") cover_black = [ m.baseColorFactor - for m, _ in _glb_material_triangles(_URDF_ROOT / "gripper_g2/meshes/visual/visual_glb/base.glb") + for m, _ in _glb_material_triangles(_URDF_ROOT / "end_effectors/gripper_g2/meshes/visual/visual_glb/base.glb") if m.metallicFactor == 0.0 and m.baseColorFactor != [1.0, 1.0, 1.0, 1.0] ][0] for side in ("left", "right"): - glb_path = _URDF_ROOT / f"gripper_g2/meshes/visual/visual_glb/{side}_finger.glb" + glb_path = _URDF_ROOT / f"end_effectors/gripper_g2/meshes/visual/visual_glb/{side}_finger.glb" glb = pygltflib.GLTF2().load(str(glb_path)) assert glb.materials[glb.meshes[0].primitives[0].material].alphaMode in (None, "OPAQUE") assert glb.materials[glb.meshes[1].primitives[0].material].alphaMode == "BLEND" @@ -398,7 +405,7 @@ def test_gripper_g2_finger_pads_use_white_translucent_silicone() -> None: def test_gripper_g2_locating_pin_is_round_and_slotted(geometry: str) -> None: """The locating pin at (0, -25) mm is a round dome-tipped cylinder (r = 2.98 mm, tip z = -4.50 mm) with a 1.00 mm wide x 2.00 mm deep slot at the STEP yaw (-0.12283004 rad).""" - tri_mm = _triangles(_URDF_ROOT / "gripper_g2" / "meshes" / geometry) * 1000.0 + tri_mm = _triangles(_URDF_ROOT / "end_effectors" / "gripper_g2" / "meshes" / geometry) * 1000.0 pin_axis = np.array([0.0, -25.0]) tri_r = np.hypot(tri_mm[:, :, 0] - pin_axis[0], tri_mm[:, :, 1] - pin_axis[1]) pin_tri = tri_mm[(tri_r.max(axis=1) <= 3.1) & (tri_mm[:, :, 2].min(axis=1) < -0.05)] @@ -447,7 +454,7 @@ def test_gripper_g2_locating_pin_is_round_and_slotted(geometry: str) -> None: @pytest.mark.parametrize("geometry", ("visual/visual_glb/base.glb", "visual/base_link.stl")) def test_gripper_g2_flange_and_boss_circles_are_round(geometry: str) -> None: """The centring boss, mounting flange, pin hole, and +Y connector cover have smooth analytic circular surfaces.""" - tri_mm = _triangles(_URDF_ROOT / "gripper_g2" / "meshes" / geometry) * 1000.0 + tri_mm = _triangles(_URDF_ROOT / "end_effectors" / "gripper_g2" / "meshes" / geometry) * 1000.0 fn = np.cross(tri_mm[:, 1] - tri_mm[:, 0], tri_mm[:, 2] - tri_mm[:, 0]) fn_norm = np.linalg.norm(fn, axis=1) valid = fn_norm > 1e-10 @@ -487,7 +494,7 @@ def test_gripper_g2_flange_and_boss_circles_are_round(geometry: str) -> None: if geometry.endswith(".glb"): DracoPy = pytest.importorskip("DracoPy") pygltflib = pytest.importorskip("pygltflib") - glb = pygltflib.GLTF2().load(str(_URDF_ROOT / "gripper_g2" / "meshes" / geometry)) + glb = pygltflib.GLTF2().load(str(_URDF_ROOT / "end_effectors" / "gripper_g2" / "meshes" / geometry)) blob = glb.binary_blob() pts_chunks, nrm_chunks = [], [] for mesh in glb.meshes: @@ -561,7 +568,7 @@ def test_intermediate_assets_and_dev_scripts_are_not_public_files() -> None: def _registered_arm_urdfs(robot_dir: str) -> list[Path]: """Tracked arm URDFs (dynamics + GLB visual) and every composed assembly of that arm.""" _, mesh_prefix, key = _REGISTERED_ARMS[robot_dir] - urdf_dir = _URDF_ROOT / robot_dir + urdf_dir = _URDF_ROOT / "robots" / robot_dir tracked = [urdf_dir / f"{mesh_prefix}.urdf", urdf_dir / f"{mesh_prefix}_visual.glb.urdf"] assert sorted(p.name for p in urdf_dir.glob("*.urdf")) == sorted(p.name for p in tracked), robot_dir return tracked + _assembly_urdfs(robot=key) @@ -581,8 +588,8 @@ def _registered_arm_urdfs(robot_dir: str) -> list[Path]: } _BIO_GRIPPER_G2_PARTS = ( - _URDF_ROOT / "bio_gripper_g2" / "bio_gripper_g2.urdf", - _URDF_ROOT / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf", + _URDF_ROOT / "end_effectors" / "bio_gripper_g2" / "bio_gripper_g2.urdf", + _URDF_ROOT / "end_effectors" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf", ) @@ -793,7 +800,7 @@ def _part_sources(robot_dir: str, link_name: str) -> tuple[tuple[str, str], ...] "link3": 2, "link4": 4, "link5": 1, - "link6": 1, + "link6": 3, }, "uf850": { "link_base": 3, @@ -839,6 +846,7 @@ def test_registered_arm_collision_meshes_use_visual_stl() -> None: expected = [ str( _URDF_ROOT + / "robots" / src_dir / f"meshes/{_REGISTERED_ARMS[src_dir][1]}/collision/{src_dir}_{src_link}_col_{idx:02d}.stl" ) @@ -925,8 +933,8 @@ def _placed_meshes(urdf: Path, link_name: str, tag: str) -> list[tuple[np.ndarra @pytest.mark.parametrize("variant", _XARM_URDF_VARIANTS) def test_xarm5_is_xarm6_with_j4_locked(variant: str) -> None: """xArm5 link frames and placed meshes equal xArm6's at J4 = 0 (xArm5 J4/J5 are xArm6 J5/J6).""" - xarm5 = _URDF_ROOT / "xarm5" / variant.format("xarm5") - xarm6 = _URDF_ROOT / "xarm6" / variant.format("xarm6") + xarm5 = _URDF_ROOT / "robots" / "xarm5" / variant.format("xarm5") + xarm6 = _URDF_ROOT / "robots" / "xarm6" / variant.format("xarm6") frames = {link: _part_sources("xarm5", link)[0][1] for link in _arm_link_names(5)} for q in np.random.default_rng(0).uniform(-np.pi, np.pi, size=(8, 5)): poses5 = _link_poses(xarm5, {f"joint{i}": float(v) for i, v in zip((1, 2, 3, 4, 5), q)}) @@ -949,12 +957,12 @@ def test_xarm5_is_xarm6_with_j4_locked(variant: str) -> None: def test_shared_arm_links_reuse_the_source_link_meshes(variant: str) -> None: """A shared link with a single source carries exactly the source link's visuals and collisions.""" for robot_dir, links in _ARM_PART_SOURCES.items(): - urdf = _URDF_ROOT / robot_dir / variant.format(robot_dir) + urdf = _URDF_ROOT / "robots" / robot_dir / variant.format(robot_dir) for link, sources in links.items(): if len(sources) != 1: continue ((src_dir, src_link),) = sources - source = _URDF_ROOT / src_dir / variant.format(src_dir) + source = _URDF_ROOT / "robots" / src_dir / variant.format(src_dir) for tag in ("visual", "collision"): got, want = _placed_meshes(urdf, link, tag), _placed_meshes(source, src_link, tag) assert [path for _, path in got] == [path for _, path in want], (robot_dir, link, tag) @@ -967,13 +975,16 @@ def test_xarm_bases_use_the_production_base() -> None: trimesh = pytest.importorskip("trimesh") pytest.importorskip("DracoPy") pytest.importorskip("pygltflib") - meshes = _URDF_ROOT / "xarm6" / "meshes" / "xarm6_1305" + meshes = _URDF_ROOT / "robots" / "xarm6" / "meshes" / "xarm6_1305" stl, glb = meshes / "visual" / "link_base.stl", meshes / "visual_glb" / "link_base.glb" for robot_dir in ("xarm5", "xarm6", "xarm7"): for variant, visual in zip(_XARM_URDF_VARIANTS, (stl, glb)): - urdf = _URDF_ROOT / robot_dir / variant.format(robot_dir) + urdf = _URDF_ROOT / "robots" / robot_dir / variant.format(robot_dir) assert [path for _, path in _placed_meshes(urdf, "link_base", "visual")] == [visual], _rel(urdf) - hulls = [path for _, path in _placed_meshes(_URDF_ROOT / "xarm6" / "xarm6_1305.urdf", "link_base", "collision")] + hulls = [ + path + for _, path in _placed_meshes(_URDF_ROOT / "robots" / "xarm6" / "xarm6_1305.urdf", "link_base", "collision") + ] stl_top = _mesh_vertices(stl, trimesh)[:, 2].max() assert stl_top == pytest.approx(0.15035, abs=5e-5) assert _mesh_vertices(glb, trimesh)[:, 2].max() == pytest.approx(stl_top, abs=1e-4) @@ -998,7 +1009,7 @@ def test_xarm_bases_share_unified_inertial_parameters() -> None: serialized: list[str] = [] for robot_dir in ("xarm5", "xarm6", "xarm7"): for variant in _XARM_URDF_VARIANTS: - urdf = _URDF_ROOT / robot_dir / variant.format(robot_dir) + urdf = _URDF_ROOT / "robots" / robot_dir / variant.format(robot_dir) inertial = ET.parse(urdf).getroot().find("./link[@name='link_base']/inertial") assert inertial is not None, _rel(urdf) @@ -1033,6 +1044,58 @@ def test_xarm_bases_share_unified_inertial_parameters() -> None: np.testing.assert_allclose(eig, expected_principal, rtol=0.0, atol=1e-11) +def test_uf850_base_uses_solidworks_inertial_parameters() -> None: + """UF850 STL and GLB URDFs share the SolidWorks Arm850_P01 link_base inertials (URDF negative off-diagonals).""" + expected_mass = 5.869631 + expected_com = (-0.000762, -4.4e-05, 0.11761) + expected_rpy = (0.0, 0.0, 0.0) + expected_inertia = { + "ixx": 0.032711870245, + "ixy": 8.0733473e-05, + "ixz": -0.000343329636, + "iyy": 0.03295126767, + "iyz": -1.0328638e-05, + "izz": 0.013458380527, + } + expected_principal = np.array([13452256.142, 32692678.345, 32976583.954], dtype=np.float64) * 1e-9 + + serialized: list[str] = [] + for filename in ("uf850.urdf", "uf850_visual.glb.urdf"): + urdf = _URDF_ROOT / "robots" / "uf850" / filename + inertial = ET.parse(urdf).getroot().find("./link[@name='link_base']/inertial") + assert inertial is not None, _rel(urdf) + + mass = float(inertial.find("mass").attrib["value"]) + assert mass == pytest.approx(expected_mass, rel=0.0, abs=1e-12), _rel(urdf) + + origin = inertial.find("origin") + xyz = tuple(float(v) for v in origin.attrib["xyz"].split()) + rpy = tuple(float(v) for v in origin.attrib.get("rpy", "0 0 0").split()) + assert xyz == pytest.approx(expected_com, rel=0.0, abs=1e-12), _rel(urdf) + assert rpy == pytest.approx(expected_rpy, rel=0.0, abs=1e-12), _rel(urdf) + + inertia = {k: float(v) for k, v in inertial.find("inertia").attrib.items()} + for key, expected_val in expected_inertia.items(): + assert inertia[key] == pytest.approx(expected_val, rel=0.0, abs=1e-12), (_rel(urdf), key) + + serialized.append(ET.tostring(inertial, encoding="unicode").strip()) + + assert len(set(serialized)) == 1 + + tensor = np.array( + [ + [expected_inertia["ixx"], expected_inertia["ixy"], expected_inertia["ixz"]], + [expected_inertia["ixy"], expected_inertia["iyy"], expected_inertia["iyz"]], + [expected_inertia["ixz"], expected_inertia["iyz"], expected_inertia["izz"]], + ], + dtype=np.float64, + ) + eig = np.linalg.eigvalsh(tensor) + assert eig.min() > 0.0 + assert eig[0] + eig[1] > eig[2] + np.testing.assert_allclose(eig, expected_principal, rtol=0.0, atol=1e-11) + + def test_xarm_flange_visual_is_centred_on_the_flange_frame() -> None: """xArm5/6/7 share one flange link; its GLB stays centred on the flange axis like the STL. @@ -1041,11 +1104,11 @@ def test_xarm_flange_visual_is_centred_on_the_flange_frame() -> None: trimesh = pytest.importorskip("trimesh") pytest.importorskip("DracoPy") pytest.importorskip("pygltflib") - meshes = _URDF_ROOT / "xarm6" / "meshes" / "xarm6_1305" + meshes = _URDF_ROOT / "robots" / "xarm6" / "meshes" / "xarm6_1305" stl, glb = meshes / "visual" / "link6.stl", meshes / "visual_glb" / "link6.glb" for robot_dir, flange in (("xarm5", "link5"), ("xarm6", "link6"), ("xarm7", "link7")): for variant, visual in zip(_XARM_URDF_VARIANTS, (stl, glb)): - urdf = _URDF_ROOT / robot_dir / variant.format(robot_dir) + urdf = _URDF_ROOT / "robots" / robot_dir / variant.format(robot_dir) assert [path for _, path in _placed_meshes(urdf, flange, "visual")] == [visual], _rel(urdf) def bbox_centre(path: Path) -> np.ndarray: @@ -1060,7 +1123,7 @@ def test_lite6_base_glb_is_aligned_with_stl_at_z0() -> None: trimesh = pytest.importorskip("trimesh") pytest.importorskip("DracoPy") pytest.importorskip("pygltflib") - meshes = _URDF_ROOT / "lite6" / "meshes" / "lite6" + meshes = _URDF_ROOT / "robots" / "lite6" / "meshes" / "lite6" stl = _mesh_vertices(meshes / "visual" / "link_base.stl", trimesh) glb = _mesh_vertices(meshes / "visual_glb" / "link_base.glb", trimesh) assert float(glb[:, 2].min()) == pytest.approx(float(stl[:, 2].min()), abs=2e-5) @@ -1070,7 +1133,9 @@ def test_lite6_base_glb_is_aligned_with_stl_at_z0() -> None: def test_arm_and_bio_g2_collision_meshes_are_convex_hulls() -> None: """Genesis keeps its pure-convex path, and the Bio G2 collision audit checks these meshes as convex shapes.""" trimesh = pytest.importorskip("trimesh") - urdfs = [_URDF_ROOT / robot_dir / f"{prefix}.urdf" for robot_dir, (_, prefix, _) in _REGISTERED_ARMS.items()] + urdfs = [ + _URDF_ROOT / "robots" / robot_dir / f"{prefix}.urdf" for robot_dir, (_, prefix, _) in _REGISTERED_ARMS.items() + ] meshes = sorted( { (urdf.parent / name).resolve() @@ -1099,7 +1164,7 @@ def test_bio_gripper_g2_collision_mesh_basenames_are_unique_in_combos() -> None: def test_bio_gripper_g2_urdfs_do_not_reference_legacy_short_stl_names() -> None: legacy = { - (_URDF_ROOT / "bio_gripper_g2" / "meshes" / "visual" / name).resolve() + (_URDF_ROOT / "end_effectors" / "bio_gripper_g2" / "meshes" / "visual" / name).resolve() for name in ("link_base.stl", "left_finger.stl", "right_finger.stl") } bad: list[str] = [] @@ -1181,7 +1246,7 @@ def test_bio_gripper_g2_movable_collision_bbox_centers_match_visual_glb() -> Non def test_bio_gripper_g2_visual_glb_budget() -> None: """High-poly + native Draco should keep Bio G2 visual GLBs under 1 MiB.""" - package_dir = PROJECT_ROOT / "assets" / "urdf" / "bio_gripper_g2" + package_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "bio_gripper_g2" visual_dir = package_dir / "meshes" / "visual" glbs = sorted( path @@ -1245,7 +1310,7 @@ def _bio_g2_adapter_metal(name: str) -> tuple[np.ndarray, np.ndarray, np.ndarray pygltflib = pytest.importorskip("pygltflib") from scipy.spatial.transform import Rotation - glb = pygltflib.GLTF2().load(str(_URDF_ROOT / "bio_gripper_g2" / "meshes" / "visual" / name)) + glb = pygltflib.GLTF2().load(str(_URDF_ROOT / "end_effectors" / "bio_gripper_g2" / "meshes" / "visual" / name)) blob = glb.binary_blob() metal = [i for i, m in enumerate(glb.materials) if m.pbrMetallicRoughness.metallicFactor > 0.5] prim = next(p for m in glb.meshes for p in m.primitives if p.material in metal) @@ -1343,7 +1408,7 @@ def test_bio_gripper_g2_adapter_faces_stop_at_hole_rims(name: str) -> None: def test_gripper_g2_visual_glb_budget() -> None: """Canonical Gripper G2 visual GLBs (native Draco) must stay under 1 MiB.""" - package_dir = PROJECT_ROOT / "assets" / "urdf" / "gripper_g2" + package_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "gripper_g2" visual_dir = package_dir / "meshes" / "visual" glbs = sorted( path @@ -1369,7 +1434,7 @@ def test_gripper_g2_visual_glb_budget() -> None: def test_lite6_gripper_visual_glb_budget() -> None: """Lite6 gripper visual GLBs (native Draco) must stay under 1 MiB.""" - package_dir = PROJECT_ROOT / "assets" / "urdf" / "lite6_gripper" + package_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "lite6_gripper" visual_dir = package_dir / "meshes" / "visual" glbs = sorted(visual_dir.rglob("*.glb")) assert glbs, "expected Lite6 gripper visual GLBs" @@ -1382,7 +1447,7 @@ def test_lite6_gripper_visual_glb_budget() -> None: def test_lite6_vacuum_gripper_visual_glb_budget() -> None: """Lite6 vacuum gripper visual GLB (native Draco) must stay under 1 MiB.""" - package_dir = PROJECT_ROOT / "assets" / "urdf" / "lite6_vacuum_gripper" + package_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "lite6_vacuum_gripper" visual_dir = package_dir / "meshes" / "visual" glbs = sorted(visual_dir.rglob("*.glb")) assert glbs, "expected Lite6 vacuum gripper visual GLBs" @@ -1394,7 +1459,7 @@ def test_lite6_vacuum_gripper_visual_glb_budget() -> None: def test_vacuum_gripper_visual_glb_budget() -> None: """xArm/UF850 vacuum gripper visual GLB (native Draco) must stay under 1 MiB.""" - package_dir = PROJECT_ROOT / "assets" / "urdf" / "vacuum_gripper" + package_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "vacuum_gripper" visual_dir = package_dir / "meshes" / "visual" glbs = sorted(visual_dir.rglob("*.glb")) assert glbs, "expected xArm/UF850 vacuum gripper visual GLBs" @@ -1409,7 +1474,7 @@ def test_vacuum_gripper_visual_glb_budget() -> None: [ ( "xarm6", - "assets/urdf/xarm6/meshes/xarm6_1305/visual_glb", + "assets/urdf/robots/xarm6/meshes/xarm6_1305/visual_glb", 1_500_000, { "link_base.glb", @@ -1423,13 +1488,13 @@ def test_vacuum_gripper_visual_glb_budget() -> None: ), ( "xarm7", - "assets/urdf/xarm7/meshes/xarm7_1305/visual_glb", + "assets/urdf/robots/xarm7/meshes/xarm7_1305/visual_glb", 1_000_000, {"link1.glb", "link2.glb", "link3.glb", "link4.glb", "link5.glb", "link6.glb"}, ), ( "uf850", - "assets/urdf/uf850/meshes/uf850/visual_glb", + "assets/urdf/robots/uf850/meshes/uf850/visual_glb", 1_000_000, { "link_base.glb", @@ -1443,7 +1508,7 @@ def test_vacuum_gripper_visual_glb_budget() -> None: ), ( "lite6", - "assets/urdf/lite6/meshes/lite6/visual_glb", + "assets/urdf/robots/lite6/meshes/lite6/visual_glb", 1_000_000, { "link_base.glb", @@ -1475,14 +1540,14 @@ def test_arm_body_visual_glb_budget( def test_accessory_collision_meshes_are_stl_files() -> None: urdfs = ( - _URDF_ROOT / "gripper_g2" / "gripper_g2_movable_visual.urdf", + _URDF_ROOT / "end_effectors" / "gripper_g2" / "gripper_g2_movable_visual.urdf", *_BIO_GRIPPER_G2_PARTS, - _URDF_ROOT / "lite6_gripper" / "lite6_gripper_movable_visual.urdf", - _URDF_ROOT / "lite6_vacuum_gripper" / "lite6_vacuum_gripper.urdf", - _URDF_ROOT / "vacuum_gripper" / "vacuum_gripper.urdf", - _URDF_ROOT / "xarm_mounting_plate" / "xarm_mounting_plate.urdf", - _URDF_ROOT / "uf850_mounting_plate" / "uf850_mounting_plate.urdf", - _URDF_ROOT / "lite6_mounting_plate" / "lite6_mounting_plate.urdf", + _URDF_ROOT / "end_effectors" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf", + _URDF_ROOT / "end_effectors" / "lite6_vacuum_gripper" / "lite6_vacuum_gripper.urdf", + _URDF_ROOT / "end_effectors" / "vacuum_gripper" / "vacuum_gripper.urdf", + _URDF_ROOT / "mounts" / "xarm_mounting_plate" / "xarm_mounting_plate.urdf", + _URDF_ROOT / "mounts" / "uf850_mounting_plate" / "uf850_mounting_plate.urdf", + _URDF_ROOT / "mounts" / "lite6_mounting_plate" / "lite6_mounting_plate.urdf", *_assembly_urdfs(), ) bad: list[str] = [] @@ -1499,7 +1564,7 @@ def test_accessory_collision_meshes_are_stl_files() -> None: def test_standalone_movable_accessory_collision_links_are_movable() -> None: expected = { - PROJECT_ROOT / "assets" / "urdf" / "gripper_g2" / "gripper_g2_movable_visual.urdf": { + PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "gripper_g2" / "gripper_g2_movable_visual.urdf": { "left_outer_knuckle", "left_finger", "left_inner_knuckle", @@ -1507,11 +1572,11 @@ def test_standalone_movable_accessory_collision_links_are_movable() -> None: "right_finger", "right_inner_knuckle", }, - PROJECT_ROOT / "assets" / "urdf" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf": { + PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf": { "bio_gripper_g2_left_finger", "bio_gripper_g2_right_finger", }, - PROJECT_ROOT / "assets" / "urdf" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf": { + PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf": { "uflite_finger1", "uflite_finger2", }, @@ -1533,7 +1598,7 @@ def test_standalone_movable_accessory_collision_links_are_movable() -> None: def test_lite6_vacuum_standalone_collision_is_static_only() -> None: - urdfs = (_URDF_ROOT / "lite6_vacuum_gripper" / "lite6_vacuum_gripper.urdf",) + urdfs = (_URDF_ROOT / "end_effectors" / "lite6_vacuum_gripper" / "lite6_vacuum_gripper.urdf",) bad: list[str] = [] for urdf in urdfs: movable_joints = sorted(_non_fixed_joint_names(urdf)) @@ -1545,7 +1610,7 @@ def test_lite6_vacuum_standalone_collision_is_static_only() -> None: def test_arm_movable_accessory_collision_links_match_standalone_models() -> None: cases = ( ( - PROJECT_ROOT / "assets" / "urdf" / "gripper_g2" / "gripper_g2_movable_visual.urdf", + PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "gripper_g2" / "gripper_g2_movable_visual.urdf", { "left_outer_knuckle", "left_finger", @@ -1557,7 +1622,12 @@ def test_arm_movable_accessory_collision_links_match_standalone_models() -> None tuple(_assembly_urdfs("gripper_g2")), ), ( - PROJECT_ROOT / "assets" / "urdf" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf", + PROJECT_ROOT + / "assets" + / "urdf" + / "end_effectors" + / "bio_gripper_g2" + / "bio_gripper_g2_movable_visual.urdf", { "bio_gripper_g2_left_finger", "bio_gripper_g2_right_finger", @@ -1565,7 +1635,7 @@ def test_arm_movable_accessory_collision_links_match_standalone_models() -> None tuple(_assembly_urdfs("bio_gripper_g2")), ), ( - PROJECT_ROOT / "assets" / "urdf" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf", + PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf", { "uflite_finger1", "uflite_finger2", @@ -1604,7 +1674,7 @@ def test_arm_movable_accessory_collision_links_match_standalone_models() -> None def _lite6_gripper_finger_urdfs() -> list[Path]: """Lite6 gripper part and composed assemblies that keep per-finger visuals (GLB and STL arm visuals).""" return [ - _URDF_ROOT / "lite6_gripper" / "lite6_gripper_movable_visual.urdf", + _URDF_ROOT / "end_effectors" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf", *_assembly_urdfs("lite6_gripper", modes=("glb", "stl")), ] @@ -1693,7 +1763,7 @@ def _lite6_gripper_finger_center_separation_mm( def test_lite6_gripper_finger_collision_gap_at_keyframes() -> None: trimesh = pytest.importorskip("trimesh") - mesh_dir = PROJECT_ROOT / "assets" / "urdf" / "lite6_gripper" / "meshes" / "collision" + mesh_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "lite6_gripper" / "meshes" / "collision" finger1_vertices = _mesh_vertices(mesh_dir / "finger1.stl", trimesh) finger2_vertices = _mesh_vertices(mesh_dir / "finger2.stl", trimesh) @@ -1800,9 +1870,13 @@ def test_lite6_gripper_finger_collision_gap_at_keyframes() -> None: def test_lite6_vacuum_collision_uses_visual_stl() -> None: - expected = {(_URDF_ROOT / "lite6_vacuum_gripper" / "meshes" / "visual" / "vacuum_gripper_lite.stl").resolve()} + expected = { + ( + _URDF_ROOT / "end_effectors" / "lite6_vacuum_gripper" / "meshes" / "visual" / "vacuum_gripper_lite.stl" + ).resolve() + } urdfs = ( - _URDF_ROOT / "lite6_vacuum_gripper" / "lite6_vacuum_gripper.urdf", + _URDF_ROOT / "end_effectors" / "lite6_vacuum_gripper" / "lite6_vacuum_gripper.urdf", *_assembly_urdfs("lite6_vacuum_gripper"), ) bad: list[str] = [] @@ -1835,7 +1909,7 @@ def test_vacuum_gripper_static_urdfs_and_parameters() -> None: } from ufactory.robots.registry import get_robot_profile - cases = [(_URDF_ROOT / "vacuum_gripper" / "vacuum_gripper.urdf", "vacuum_mount", 0)] + cases = [(_URDF_ROOT / "end_effectors" / "vacuum_gripper" / "vacuum_gripper.urdf", "vacuum_mount", 0)] for key in end_effectors()["vacuum_gripper"].robots: profile = get_robot_profile(key) cases += [(urdf, profile.ee_link, profile.dof) for urdf in _assembly_urdfs("vacuum_gripper", robot=key)] @@ -1877,11 +1951,11 @@ def test_robotiq_urdfs_share_joint_limits_mimic_and_glb_budget(variant: str) -> from ufactory.grippers.robotiq import get_robotiq_spec spec = get_robotiq_spec(variant) - glb_dir = _URDF_ROOT / variant / "meshes" / "visual" / "visual_glb" + glb_dir = _URDF_ROOT / "end_effectors" / variant / "meshes" / "visual" / "visual_glb" glb_total = sum(p.stat().st_size for p in glb_dir.glob("*.glb")) assert 0 < glb_total < 1_000_000, f"{variant} GLB total {glb_total} bytes exceeds 1 MB" - part = _URDF_ROOT / variant / f"{variant}_movable_visual.urdf" + part = _URDF_ROOT / "end_effectors" / variant / f"{variant}_movable_visual.urdf" models = [part, *_assembly_urdfs(variant)] assert len(models) == 9 for path in models: @@ -1899,3 +1973,57 @@ def test_robotiq_urdfs_share_joint_limits_mimic_and_glb_budget(variant: str) -> assert mimic.get("joint") == spec.drive_joint_name, (path, name) assert float(mimic.get("multiplier", "1")) == 1.0, (path, name) assert float(mimic.get("offset", "0")) == 0.0, (path, name) + + +def test_lite6_link6_three_hull_enclosure_and_wrist_clearance() -> None: + """Lite6 link6's three convex hulls enclose link6.stl tightly without hiding near-limit link4/link6 contact.""" + trimesh = pytest.importorskip("trimesh") + pytest.importorskip("pinocchio") + pytest.importorskip("coal") + from ufactory.safety.adapters.pinocchio import PinocchioCollisionBackend + + meshes_dir = _URDF_ROOT / "robots" / "lite6" / "meshes" / "lite6" + visual = trimesh.load(meshes_dir / "visual" / "link6.stl", force="mesh") + hulls = [ + trimesh.load(meshes_dir / "collision" / f"lite6_link6_col_{idx:02d}.stl", force="mesh") for idx in range(3) + ] + + for hull in hulls: + _, dists, _ = trimesh.proximity.closest_point(visual, hull.vertices) + assert float(np.max(dists)) < 5e-5 + + pts = np.asarray(visual.vertices, dtype=np.float64) + min_outside = np.full(len(pts), np.inf, dtype=np.float64) + for hull in hulls: + normals = np.asarray(hull.face_normals, dtype=np.float64) + v0 = np.asarray(hull.vertices[hull.faces[:, 0]], dtype=np.float64) + outside = np.max(pts @ normals.T - np.sum(v0 * normals, axis=1)[None, :], axis=1) + min_outside = np.minimum(min_outside, outside) + assert float(np.max(min_outside)) < 1e-6 + + backend = PinocchioCollisionBackend( + _URDF_ROOT / "robots" / "lite6" / "lite6.urdf", + joint_names=("joint1", "joint2", "joint3", "joint4", "joint5", "joint6"), + ee_link="link6", + tool_root_link="link6", + ) + + def link4_link6_min_mm(q5: float, q6: float) -> float: + q = np.array([0.0, 0.0, 0.0, 0.0, q5, q6], dtype=np.float64) + return min( + res.min_distance_m * 1000.0 + for res in backend.check_all(q, stage="start") + if {res.link_a, res.link_b} == {"link4", "link6"} + ) + + # Normal working range stays comfortably above the 5 mm preflight margin across all q6. + normal_min_mm = min( + link4_link6_min_mm(q5, q6) + for q5 in (-1.8, -1.0, 0.0, 0.2742, 1.0, 1.8) + for q6 in np.linspace(-np.pi, np.pi, 13) + ) + assert normal_min_mm > 5.8 + + # Near the J5 mechanical limit, real link4/link6 contact is still detected. + limit_min_mm = min(link4_link6_min_mm(2.1642, q6) for q6 in np.linspace(-np.pi, np.pi, 13)) + assert limit_min_mm < 0.5 diff --git a/tests/robots/test_camera_assembly.py b/tests/robots/test_camera_assembly.py index 67954c7..943e42c 100644 --- a/tests/robots/test_camera_assembly.py +++ b/tests/robots/test_camera_assembly.py @@ -305,7 +305,7 @@ def test_camera_sits_on_the_stand_holes_and_looks_along_flange_z(arm: str, camer def test_stand_frames_match_the_drawing() -> None: - model, data = _placements(URDF_ROOT / "camera_stand" / "camera_stand.urdf") + model, data = _placements(URDF_ROOT / "mounts" / "camera_stand" / "camera_stand.urdf") expected_mm = { "stand_camera_mount": (67.5, 3.0, 0.0), "stand_hole_20_0": (67.5, 3.0, -10.0), @@ -409,7 +409,8 @@ def _glb_json(path: Path) -> dict[str, object]: @pytest.mark.parametrize("part", ACCESSORIES) def test_part_assets_budget_inertia_and_license(part: str) -> None: - glb = URDF_ROOT / part / "meshes" / "visual" / f"{part}.glb" + part_dir = URDF_ROOT / ("mounts" if part == "camera_stand" else "cameras") / part + glb = part_dir / "meshes" / "visual" / f"{part}.glb" assert glb.stat().st_size < 1_000_000 meta = _glb_json(glb) assert meta["extensionsRequired"] == ["KHR_draco_mesh_compression"] @@ -419,7 +420,10 @@ def test_part_assets_budget_inertia_and_license(part: str) -> None: ) if part in ("camera_stand", "d405", "d435", "gemini_305"): housing_pbr = meta["materials"][0]["pbrMetallicRoughness"] # type: ignore[index] - for arm_glb in ("xarm6/meshes/xarm6_1305/visual_glb/link6.glb", "uf850/meshes/uf850/visual_glb/link6.glb"): + for arm_glb in ( + "robots/xarm6/meshes/xarm6_1305/visual_glb/link6.glb", + "robots/uf850/meshes/uf850/visual_glb/link6.glb", + ): arm_meta = _glb_json(URDF_ROOT / arm_glb) arm_metals = [ m["pbrMetallicRoughness"] @@ -437,7 +441,7 @@ def test_part_assets_budget_inertia_and_license(part: str) -> None: glass_pbr = meta["materials"][1]["pbrMetallicRoughness"] # type: ignore[index] np.testing.assert_allclose(glass_pbr["baseColorFactor"], [0.025, 0.03, 0.035, 1.0], atol=1e-4) - root = ET.parse(URDF_ROOT / part / f"{part}.urdf").getroot() + root = ET.parse(part_dir / f"{part}.urdf").getroot() base = "camera_stand" if part == "camera_stand" else f"{part}_body" inertial = root.find(f"./link[@name='{base}']/inertial") assert inertial is not None @@ -447,15 +451,16 @@ def test_part_assets_budget_inertia_and_license(part: str) -> None: tensor = np.array([[i["ixx"], i["ixy"], i["ixz"]], [i["ixy"], i["iyy"], i["iyz"]], [i["ixz"], i["iyz"], i["izz"]]]) eig = np.linalg.eigvalsh(tensor) assert eig.min() > 0.0 and eig[0] + eig[1] > eig[2] - assert (URDF_ROOT / part / "README.md").is_file() - assert (URDF_ROOT / part / "LICENSE").is_file() == (part in ("d405", "d435")) + assert (part_dir / "README.md").is_file() + assert (part_dir / "LICENSE").is_file() == (part in ("d405", "d435")) def test_stand_collision_is_45_prisms() -> None: - root = ET.parse(URDF_ROOT / "camera_stand" / "camera_stand.urdf").getroot() + stand_dir = URDF_ROOT / "mounts" / "camera_stand" + root = ET.parse(stand_dir / "camera_stand.urdf").getroot() meshes = [m.get("filename") for m in root.findall("./link[@name='camera_stand']/collision/geometry/mesh")] assert meshes == [f"meshes/collision/piece_{i:03d}.stl" for i in range(45)] - files = sorted(p.name for p in (URDF_ROOT / "camera_stand" / "meshes" / "collision").iterdir()) + files = sorted(p.name for p in (stand_dir / "meshes" / "collision").iterdir()) assert files == [f"piece_{i:03d}.stl" for i in range(45)] diff --git a/tests/robots/test_ft_sensor_assembly.py b/tests/robots/test_ft_sensor_assembly.py new file mode 100644 index 0000000..0450951 --- /dev/null +++ b/tests/robots/test_ft_sensor_assembly.py @@ -0,0 +1,349 @@ +"""AI1500 six-axis F/T sensor asset, assembly, Pinocchio FK/collision, and Genesis smoke tests.""" + +from __future__ import annotations + +import itertools +from pathlib import Path +import xml.etree.ElementTree as ET + +import numpy as np +import pytest + +from ufactory.robots import assembly +from ufactory.robots.assembly import ( + AssemblyError, + AssemblyRef, + compose_robot_urdf, + compose_standalone_ft_sensor_urdf, + ft_sensors, + get_ft_sensor, + parse_assembly_ref, + resolve_robot_urdf, + supported_ft_sensors, + supports_ft_sensor, + validate_robot_urdf, +) +from ufactory.robots.paths import ft_sensor_ai1500_urdf, robot_urdf, robot_visual_glb_urdf +from ufactory.robots.registry import PROJECT_ROOT, get_robot_profile +from ufactory.config import RepositoryAssetStore + +URDF_ROOT = PROJECT_ROOT / "assets" / "urdf" +SENSOR_DIR = URDF_ROOT / "accessories" / "ft_sensor_ai1500" +XARM_ARMS = ("xarm5_1305", "xarm6_1305", "xarm7_1305", "uf850") +SENSOR_LIFT_M = 0.0586 +STAND_LIFT_M = 0.003 +ADAPTER_LIFT_M = 0.011 +SENSOR_MASS_KG = 0.6 +SENSOR_COM_M = np.array([0.0, 0.0, 0.022], dtype=np.float64) +SENSOR_INERTIA_DIAG = (0.000428064, 0.000428064, 0.000451632) + + +def test_catalog_registers_ft_sensor_ai1500_for_xarm_and_uf850_only() -> None: + sensors = ft_sensors() + assert tuple(sensors) == ("ft_sensor_ai1500",) + ft = get_ft_sensor("ft_sensor_ai1500") + assert ft == sensors["ft_sensor_ai1500"] + assert ft.flange == "xarm" + assert ft.robots == XARM_ARMS + assert ft.output_link == "ft_sensor_ai1500_output" + assert ft.tool_lift_m == pytest.approx(SENSOR_LIFT_M) + + for arm in XARM_ARMS: + assert supported_ft_sensors(arm) == ("ft_sensor_ai1500",) + assert supports_ft_sensor(arm, "ft_sensor_ai1500") + assert get_robot_profile(arm).supports_ft_sensor_ai1500 + + assert supported_ft_sensors("lite6") == () + assert not supports_ft_sensor("lite6", "ft_sensor_ai1500") + assert not get_robot_profile("lite6").supports_ft_sensor_ai1500 + + with pytest.raises(AssemblyError, match="unknown F/T sensor"): + get_ft_sensor("ft_sensor_missing") + + +def test_ft_sensor_schema_validation_rejects_invalid_configs(tmp_path: Path) -> None: + def write_schema(body: str) -> Path: + p = tmp_path / "assembly.yaml" + p.write_text(f"schema_version: 6\nflanges:\n xarm:\n robots: [xarm6]\n{body}", encoding="utf-8") + return p + + bad_prefix = "ft_sensors:\n ai1500:\n source: s.urdf\n base_link: b\n output_link: o\n mount_joint: j\n flange: xarm\n" + with pytest.raises(AssemblyError, match="must start with 'ft_sensor_'"): + assembly._load_catalog(write_schema(bad_prefix), 1) + + bad_lift = ( + "ft_sensors:\n" + " ft_sensor_x:\n source: s.urdf\n base_link: b\n output_link: o\n" + " mount_joint: j\n flange: xarm\n tool_lift_m: -0.01\n" + ) + with pytest.raises(AssemblyError, match="tool_lift_m must be non-negative"): + assembly._load_catalog(write_schema(bad_lift), 2) + + missing_out = ( + "ft_sensors:\n" + " ft_sensor_x:\n source: s.urdf\n base_link: b\n output_link: ''\n" + " mount_joint: j\n flange: xarm\n" + ) + with pytest.raises(AssemblyError, match="output_link is required"): + assembly._load_catalog(write_schema(missing_out), 3) + + +def test_ft_sensor_ai1500_assets_and_urdf_integrity() -> None: + trimesh = pytest.importorskip("trimesh") + pygltflib = pytest.importorskip("pygltflib") + DracoPy = pytest.importorskip("DracoPy") + + urdf_path = SENSOR_DIR / "ft_sensor_ai1500.urdf" + glb_path = SENSOR_DIR / "meshes" / "visual" / "ft_sensor_ai1500.glb" + stl_path = SENSOR_DIR / "meshes" / "visual" / "ft_sensor_ai1500.stl" + col_path = SENSOR_DIR / "meshes" / "collision" / "ft_sensor_ai1500_col_00.stl" + + for path in (urdf_path, glb_path, stl_path, col_path): + assert path.is_file(), path + + assert glb_path.stat().st_size < 1_000_000 + assert glb_path.read_bytes()[:4] == b"glTF" + glb = pygltflib.GLTF2().load(str(glb_path)) + assert "KHR_draco_mesh_compression" in (glb.extensionsUsed or []) + assert len(glb.materials) == 5 + blob = glb.binary_blob() or b"" + decoded_chunks = [] + for mesh in glb.meshes: + for prim in mesh.primitives: + view = glb.bufferViews[prim.extensions["KHR_draco_mesh_compression"]["bufferView"]] + dec = DracoPy.decode(blob[view.byteOffset : view.byteOffset + view.byteLength]) + decoded_chunks.append(np.asarray(dec.points, dtype=np.float64)) + glb_pts = np.vstack(decoded_chunks) + assert float(glb_pts[:, 2].min() * 1000.0) == pytest.approx(-5.0, abs=0.05) + assert float(glb_pts[:, 2].max() * 1000.0) == pytest.approx(58.6, abs=0.05) + + col_mesh = trimesh.load(col_path, force="mesh") + assert col_mesh.is_watertight and col_mesh.is_convex + assert len(col_mesh.vertices) == 48 + assert len(col_mesh.faces) == 92 + + root = ET.parse(urdf_path).getroot() + inertial = root.find("./link[@name='ft_sensor_ai1500']/inertial") + assert inertial is not None + assert float(inertial.find("mass").attrib["value"]) == pytest.approx(SENSOR_MASS_KG) + com = np.array([float(x) for x in inertial.find("origin").attrib["xyz"].split()]) + np.testing.assert_allclose(com, SENSOR_COM_M, atol=1e-9) + inert = inertial.find("inertia").attrib + assert float(inert["ixx"]) == pytest.approx(SENSOR_INERTIA_DIAG[0], abs=1e-12) + assert float(inert["iyy"]) == pytest.approx(SENSOR_INERTIA_DIAG[1], abs=1e-12) + assert float(inert["izz"]) == pytest.approx(SENSOR_INERTIA_DIAG[2], abs=1e-12) + + for frame_name in ("ft_sensor_ai1500_output", "ft_sensor_ai1500_measurement"): + j = root.find(f"./joint[@name='{frame_name}_joint']") + assert j is not None + xyz = np.array([float(x) for x in j.find("origin").attrib["xyz"].split()]) + np.testing.assert_allclose(xyz, [0.0, 0.0, SENSOR_LIFT_M], atol=1e-9) + + standalone = Path(ft_sensor_ai1500_urdf()) + assert standalone == Path(compose_standalone_ft_sensor_urdf("ft_sensor_ai1500", visual="glb")) + assert standalone.is_file() + + +def test_assembly_ref_round_trip_and_validation() -> None: + cases = [ + ("assembly:bare+ft_sensor_ai1500", AssemblyRef(None, "glb", None, False, "ft_sensor_ai1500")), + ("assembly:gripper_g2+ft_sensor_ai1500", AssemblyRef("gripper_g2", "glb", None, False, "ft_sensor_ai1500")), + ( + "assembly:gripper_g2+ft_sensor_ai1500+d435+mounting_plate:stl", + AssemblyRef("gripper_g2", "stl", "d435", True, "ft_sensor_ai1500"), + ), + ( + "assembly:bare+ft_sensor_ai1500+camera_stand+mounting_plate", + AssemblyRef(None, "glb", "camera_stand", True, "ft_sensor_ai1500"), + ), + ] + for text, expected in cases: + parsed = parse_assembly_ref(text) + assert parsed == expected + assert str(parsed) == text + + for bad in ( + "assembly:ft_sensor_ai1500", + "assembly:bare+ft_sensor_ai1500+ft_sensor_other", + "assembly:bare+d435+camera_stand+ft_sensor_ai1500", + ): + with pytest.raises(AssemblyError): + parse_assembly_ref(bad) + + with pytest.raises(AssemblyError, match="not supported on lite6"): + compose_robot_urdf("lite6", None, ft_sensor="ft_sensor_ai1500") + with pytest.raises(ValueError, match="does not support F/T sensor"): + robot_visual_glb_urdf("lite6", ft_sensor="ft_sensor_ai1500") + with pytest.raises(AssemblyError, match="camera_stand does not fit with bio_gripper_g2"): + compose_robot_urdf("xarm6_1305", "bio_gripper_g2", accessory="camera_stand", ft_sensor="ft_sensor_ai1500") + + # Resolving via paths & assembly store works without error. + store = RepositoryAssetStore.discover(PROJECT_ROOT) + validate_robot_urdf( + "xarm6_1305", + "assembly:gripper_g2+ft_sensor_ai1500+d435", + assets_dir=URDF_ROOT / "robots" / "xarm6", + store=store, + ) + resolved = resolve_robot_urdf("xarm6_1305", "assembly:bare+ft_sensor_ai1500") + assert resolved.is_file() + assert Path(robot_urdf("xarm6_1305", "assembly:gripper_g2+ft_sensor_ai1500")).is_file() + + +def test_backward_compatibility_without_ft_sensor() -> None: + baseline = Path(compose_robot_urdf("xarm6_1305", "gripper_g2", accessory="d435", mounting_plate=True)) + assert "ft_sensor" not in baseline.name + root = ET.parse(baseline).getroot() + assert root.find("./link[@name='ft_sensor_ai1500']") is None + + +def test_pinocchio_cumulative_lift_mass_and_internal_clearance() -> None: + pin = pytest.importorskip("pinocchio") + pytest.importorskip("coal") + from ufactory.safety.adapters.pinocchio import PinocchioCollisionBackend, urdf_subtree_links + + def _build_pin_model(urdf_path: str): + try: + return pin.buildModelFromUrdf(urdf_path, mimic=True) + except ValueError as exc: + if "mimic" not in str(exc).lower(): + raise + return pin.buildModelFromUrdf(urdf_path) + + def link_in_flange_z(urdf_path: str, flange_link: str, target_link: str) -> tuple[float, float]: + model = _build_pin_model(urdf_path) + data = model.createData() + pin.framesForwardKinematics(model, data, pin.neutral(model)) + flange_id = model.getFrameId(flange_link) + target_id = model.getFrameId(target_link) + rel = data.oMf[flange_id].actInv(data.oMf[target_id]) + total_mass = sum(float(inertia.mass) for inertia in model.inertias) + return float(rel.translation[2]), total_mass + + for robot_key in XARM_ARMS: + profile = get_robot_profile(robot_key) + bare_urdf = str(profile.assets_dir / profile.default_urdf) + bare_model = pin.buildModelFromUrdf(bare_urdf, mimic=True) + m_bare = sum(float(inertia.mass) for inertia in bare_model.inertias) + + # 1. Bare + FT sensor -> output frame at +58.6 mm in flange +Z, mass +0.6 kg. + ft_bare = compose_robot_urdf(robot_key, None, ft_sensor="ft_sensor_ai1500", visual="stl") + z_out, m_ft_bare = link_in_flange_z(ft_bare, profile.ee_link, "ft_sensor_ai1500_output") + assert z_out == pytest.approx(SENSOR_LIFT_M, abs=1e-6) + assert m_ft_bare - m_bare == pytest.approx(SENSOR_MASS_KG, abs=1e-6) + + # 2. If the arm defines link_eef (e.g. xarm6_1305), link_eef lifts +58.6 mm / +61.6 mm. + if bare_model.existFrame("link_eef"): + z_bare, _ = link_in_flange_z(bare_urdf, profile.ee_link, "link_eef") + z_ft_eef, _ = link_in_flange_z(ft_bare, profile.ee_link, "link_eef") + assert z_ft_eef - z_bare == pytest.approx(SENSOR_LIFT_M, abs=1e-6) + + ft_cam_bare = compose_robot_urdf( + robot_key, None, accessory="camera_stand", ft_sensor="ft_sensor_ai1500", visual="stl" + ) + z_ft_cam_eef, _ = link_in_flange_z(ft_cam_bare, profile.ee_link, "link_eef") + assert z_ft_cam_eef - z_bare == pytest.approx(SENSOR_LIFT_M + STAND_LIFT_M, abs=1e-6) + + # 3. Downstream end effectors stack onto ft_sensor_ai1500_output cleanly. + combos: list[tuple[str, str | None, str, float, float | None]] = [ + ("gripper_g2", None, "xarm_gripper_base_link", SENSOR_LIFT_M, SENSOR_LIFT_M), + ("gripper_g2", "d435", "xarm_gripper_base_link", SENSOR_LIFT_M + STAND_LIFT_M, SENSOR_LIFT_M + STAND_LIFT_M), + ("bio_gripper_g2", None, "bio_gripper_g2_base_link", SENSOR_LIFT_M, None), + ( + "vacuum_gripper", + "d405", + "xarm_vacuum_gripper_link", + SENSOR_LIFT_M + STAND_LIFT_M, + SENSOR_LIFT_M + STAND_LIFT_M, + ), + ("robotiq_2f_85", None, "robotiq_2f_85_base_link", SENSOR_LIFT_M, SENSOR_LIFT_M + ADAPTER_LIFT_M), + ( + "robotiq_2f_140", + "zed_x_nano", + "robotiq_2f_140_base_link", + SENSOR_LIFT_M + STAND_LIFT_M, + SENSOR_LIFT_M + STAND_LIFT_M + ADAPTER_LIFT_M, + ), + ] + for ee, acc, link_name, expected_delta, expected_abs_z in combos: + base_urdf = compose_robot_urdf("xarm6_1305", ee, visual="stl") + ft_urdf = compose_robot_urdf("xarm6_1305", ee, accessory=acc, ft_sensor="ft_sensor_ai1500", visual="stl") + z_no_ft, _ = link_in_flange_z(base_urdf, "link6", link_name) + z_with_ft, _ = link_in_flange_z(ft_urdf, "link6", link_name) + assert z_with_ft - z_no_ft == pytest.approx(expected_delta, abs=1e-6) + if expected_abs_z is not None: + assert z_with_ft == pytest.approx(expected_abs_z, abs=1e-6) + + # 4. Flange-subtree internal clearance sweep with ft_sensor_ai1500 (+ optional d435). + for ee, acc in itertools.product( + ("gripper_g2", "vacuum_gripper", "robotiq_2f_85", "robotiq_2f_140"), (None, "d435") + ): + urdf = Path(compose_robot_urdf("xarm6_1305", ee, accessory=acc, ft_sensor="ft_sensor_ai1500", visual="stl")) + root_xml = ET.parse(urdf).getroot() + arm_joints = tuple(f"joint{i}" for i in range(1, 7)) + drives = [ + j + for j in root_xml.findall("joint") + if j.get("type") in {"revolute", "prismatic"} + and j.find("mimic") is None + and j.get("name") not in arm_joints + ] + passive = {} + values: list[float | None] = [None] + if drives: + lim = drives[0].find("limit") + assert lim is not None + lo, hi = float(lim.attrib["lower"]), float(lim.attrib["upper"]) + passive = {str(drives[0].attrib["name"]): lo} + values = list(np.linspace(lo, hi, 11)) + backend = PinocchioCollisionBackend( + urdf, joint_names=arm_joints, ee_link="link6", passive_joint_positions=passive + ) + tool = urdf_subtree_links(root_xml, "link6") + for pair in list(backend.geometry_model.collisionPairs): + names = {backend._link_name(pair.first), backend._link_name(pair.second)} + if not names <= tool: + backend.geometry_model.removeCollisionPair(pin.CollisionPair(int(pair.first), int(pair.second))) + backend.geometry_data = backend.geometry_model.createData() + q_arm = np.zeros(6) + for val in values: + for res in backend.check_all(q_arm, stage="sweep", gripper_drive=val): + if res.colliding: + # Only expected four-bar pin / closed-finger pairs inside the gripper; never ft_sensor_ai1500. + assert "ft_sensor_ai1500" not in (res.link_a, res.link_b) + + +@pytest.mark.gpu +def test_genesis_loads_ft_sensor_standalone_and_assembled() -> None: + gs = pytest.importorskip("genesis") + from ufactory.config import load_runtime_config + from ufactory.simulation import GenesisRuntimeManager, make_rigid_options + from ufactory.visualization.glb import glb_pbr_surfaces, glb_view_surface + + config = load_runtime_config("xarm6_1305") + with GenesisRuntimeManager(config.simulation): + scene = gs.Scene( + show_viewer=False, + sim_options=gs.options.SimOptions(dt=0.02, substeps=8), + rigid_options=make_rigid_options(gs), + ) + with glb_pbr_surfaces(): + sensor_ent = scene.add_entity( + gs.morphs.URDF(file=ft_sensor_ai1500_urdf(), fixed=True, pos=(0.5, 0.0, 0.1)), + surface=glb_view_surface(), + ) + arm_urdf = robot_visual_glb_urdf( + "xarm6_1305", + with_gripper_g2=True, + accessory="d435", + ft_sensor="ft_sensor_ai1500", + ) + arm_ent = scene.add_entity( + gs.morphs.URDF(file=arm_urdf, fixed=True), + surface=glb_view_surface(), + ) + scene.build() + for _ in range(5): + scene.step() + assert sensor_ent.n_links >= 1 + assert arm_ent.n_links >= 7 diff --git a/tests/robots/test_gripper_adapters.py b/tests/robots/test_gripper_adapters.py index 0333ed3..0b9d60d 100644 --- a/tests/robots/test_gripper_adapters.py +++ b/tests/robots/test_gripper_adapters.py @@ -157,17 +157,16 @@ def test_lite6_runtime_config_and_drive_setup_match_calibrated_pneumatic_dynamic assert list(robot.control_dofs_force.call_args.args[1]) == [7] -def test_bio_g2_adapter_mapping_and_sdk_contract(): +def _bio_g2_test_profile(): from ufactory.config.models import GripperProfile from ufactory.grippers.bio_g2 import ( BIO_GRIPPER_G2_CLOSED_GAP_M, BIO_GRIPPER_G2_OPEN_GAP_M, BIO_GRIPPER_G2_SIM_CLOSED_DRIVE, BIO_GRIPPER_G2_SIM_OPEN_DRIVE, - bio_gripper_g2_gap_m_to_sim_drive, ) - profile = GripperProfile( + return GripperProfile( adapter="bio_g2", drive_joint="bio_gripper_g2_right_finger_joint", all_joint_names=("bio_gripper_g2_right_finger_joint", "bio_gripper_g2_left_finger_joint"), @@ -184,32 +183,107 @@ def test_bio_g2_adapter_mapping_and_sdk_contract(): frictionloss=0.0, real_command=True, feedback=True, - closed_loop=True, + closed_loop=False, allowed_contact_links=frozenset({"bio_gripper_g2_left_finger", "bio_gripper_g2_right_finger"}), - tool_tip_offset_z_m=0.128, + tool_tip_offset_z_m=0.0595, finger_pad_below_center_m=0.0, finger_close_descent_m=0.0, - grasp_table_clearance_m=0.01, + grasp_table_clearance_m=0.05, grasp_height_extra_m=0.0, ) + + +def test_bio_g2_adapter_mapping_and_sdk_contract(): + from ufactory.grippers.adapters import BioG2Adapter + from ufactory.grippers.bio_g2 import bio_gripper_g2_gap_m_to_sim_drive + + profile = _bio_g2_test_profile() adapter = create_gripper_adapter(profile) + assert isinstance(adapter, BioG2Adapter) arm = MagicMock() arm.get_bio_gripper_error.return_value = (0, 0) arm.set_bio_gripper_enable.return_value = 0 + arm.get_bio_gripper_g2_position.return_value = (0, 150) arm.set_bio_gripper_g2_position.return_value = 0 assert adapter.prepare_real(arm) == 0 + arm.get_bio_gripper_g2_position.assert_called_once_with() + for gap in (0.071, 0.08548, 0.110, 0.150): q = adapter.gap_to_drive(gap) assert q == pytest.approx(bio_gripper_g2_gap_m_to_sim_drive(gap), abs=1e-14) assert adapter.drive_to_gap(q) == pytest.approx(gap, abs=1e-12) assert adapter.send_real_gap(arm, gap) == 0 - arm.set_bio_gripper_g2_position.assert_called_with(pos=gap * 1000.0, wait=False) + arm.set_bio_gripper_g2_position.assert_called_with( + pos=gap * 1000.0, + speed=2000, + force=50, + wait=False, + wait_motion=False, + ) + + # Deduplication skips sub-0.05 mm repeats; prepare_real resets deduplication state. + calls_before = arm.set_bio_gripper_g2_position.call_count + assert adapter.send_real_gap(arm, 0.15004) == 0 + assert arm.set_bio_gripper_g2_position.call_count == calls_before + assert adapter.prepare_real(arm) == 0 + assert adapter.send_real_gap(arm, 0.150) == 0 + assert arm.set_bio_gripper_g2_position.call_count == calls_before + 1 + + # Non-zero error / enable / pre-read codes propagate cleanly. + arm.get_bio_gripper_error.return_value = (11, 0) + assert adapter.prepare_real(arm) == 11 + arm.get_bio_gripper_error.return_value = (0, 0) + arm.set_bio_gripper_enable.return_value = 12 + assert adapter.prepare_real(arm) == 12 + arm.set_bio_gripper_enable.return_value = 0 + arm.get_bio_gripper_g2_position.return_value = (13, 0) + assert adapter.prepare_real(arm) == 13 arm.get_bio_gripper_error.return_value = (0, 3) with pytest.raises(RuntimeError, match="recover manually"): adapter.prepare_real(arm) +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"speed_rpm": 499}, "speed_rpm"), + ({"speed_rpm": 4001}, "speed_rpm"), + ({"speed_rpm": float("nan")}, "speed_rpm"), + ({"speed_rpm": True}, "speed_rpm"), + ({"force_percent": 0}, "force_percent"), + ({"force_percent": 101}, "force_percent"), + ({"force_percent": float("inf")}, "force_percent"), + ({"force_percent": False}, "force_percent"), + ], +) +def test_bio_g2_adapter_rejects_out_of_range_parameters(kwargs, match): + from ufactory.grippers.adapters import BioG2Adapter + + with pytest.raises(ValueError, match=match): + BioG2Adapter(_bio_g2_test_profile(), **kwargs) + + +def test_bio_g2_tcp_in_flange_constant_matches_composed_urdf_fk(): + pin = pytest.importorskip("pinocchio") + import numpy as np + + from ufactory.grippers.bio_g2 import BIO_GRIPPER_G2_TCP_IN_FLANGE_M + from ufactory.robots.assembly import compose_robot_urdf + + urdf = compose_robot_urdf("xarm6_1305", "bio_gripper_g2") + model = pin.buildModelFromUrdf(str(urdf)) + data = model.createData() + q = pin.neutral(model) + pin.forwardKinematics(model, data, q) + pin.updateFramePlacements(model, data) + flange = data.oMf[model.getFrameId("link6")] + tcp = data.oMf[model.getFrameId("bio_gripper_g2_tcp_link")] + measured = flange.actInv(tcp).translation + err_mm = float(np.linalg.norm(measured - np.asarray(BIO_GRIPPER_G2_TCP_IN_FLANGE_M)) * 1000.0) + assert err_mm <= 0.05 + + @pytest.mark.parametrize(("variant", "open_m"), [("robotiq_2f_85", 0.085), ("robotiq_2f_140", 0.140)]) def test_robotiq_adapter_mapping_and_sdk_safety_contract(variant: str, open_m: float) -> None: config = load_runtime_config("xarm6", gripper=variant) diff --git a/tests/robots/test_mounting_plate_assembly.py b/tests/robots/test_mounting_plate_assembly.py index a250c68..c9f9f40 100644 --- a/tests/robots/test_mounting_plate_assembly.py +++ b/tests/robots/test_mounting_plate_assembly.py @@ -57,7 +57,7 @@ "x_bounds_mm": (-95.0, 95.0), "y_bounds_mm": (-130.0, 130.0), "collision_count": 1, - "mass_kg": 0.9141612212, + "mass_kg": 1.056, "mount_xyz": (0.0, 0.0, 0.0), "solid_xy_mm": (0.0, 105.0), }, @@ -163,7 +163,9 @@ def test_path_helpers_and_asset_store_support_mounting_plates(tmp_path: Path) -> from ufactory.config import RepositoryAssetStore store = RepositoryAssetStore(PROJECT_ROOT) - validate_robot_urdf("xarm6_1305", "assembly:gripper_g2+mounting_plate", assets_dir="assets/urdf/xarm6", store=store) + validate_robot_urdf( + "xarm6_1305", "assembly:gripper_g2+mounting_plate", assets_dir="assets/urdf/robots/xarm6", store=store + ) resolved = resolve_robot_urdf("lite6", "assembly:bare+mounting_plate", store=store) assert resolved == Path(compose_robot_urdf("lite6", None, mounting_plate=True)) @@ -282,6 +284,78 @@ def _is_convex(mesh, tol_m: float = 1e-6) -> bool: return bool((vertices @ normals.T - offsets).max() <= tol_m) +def test_mounting_plate_urdf_inertials() -> None: + """Validate plate URDF masses and inertia tensors without optional mesh dependencies.""" + uf850_expected_inertia = { + "ixx": 0.007494367693, + "ixy": 2.827268798e-09, + "ixz": 8.907087421e-11, + "iyy": 0.003785981885, + "iyz": -2.155216145e-11, + "izz": 0.0112627498, + } + for plate, cfg in PLATES.items(): + root = ET.parse(URDF_ROOT / "mounts" / plate / f"{plate}.urdf").getroot() + inertial = root.find(f"./link[@name='{plate}']/inertial") + assert inertial is not None + mass = float(inertial.find("mass").attrib["value"]) # type: ignore[union-attr] + assert mass == pytest.approx(float(cfg["mass_kg"]), rel=0.0, abs=1e-10) + xyz = tuple(float(v) for v in inertial.find("origin").attrib["xyz"].split()) # type: ignore[union-attr] + i = {k: float(v) for k, v in inertial.find("inertia").attrib.items()} # type: ignore[union-attr] + tensor = np.array( + [[i["ixx"], i["ixy"], i["ixz"]], [i["ixy"], i["iyy"], i["iyz"]], [i["ixz"], i["iyz"], i["izz"]]] + ) + eig = np.linalg.eigvalsh(tensor) + assert eig.min() > 0.0 and eig[0] + eig[1] > eig[2] + if plate == "uf850_mounting_plate": + assert mass == pytest.approx(1.056, rel=0.0, abs=1e-12) + assert xyz == pytest.approx((-5.112679085e-08, -1.296273053e-07, -0.005000003168), rel=0.0, abs=1e-12) + for key, expected_val in uf850_expected_inertia.items(): + assert i[key] == pytest.approx(expected_val, rel=0.0, abs=1e-12), key + + +def test_mounting_plate_materials_match_arm_flanges() -> None: + """Validate plate GLB PBR and URDF materials match the arm flange metal without optional mesh deps.""" + flange_glbs = ( + "robots/xarm6/meshes/xarm6_1305/visual_glb/link6.glb", + "robots/uf850/meshes/uf850/visual_glb/link6.glb", + "robots/lite6/meshes/lite6/visual_glb/link6.glb", + ) + for plate in PLATES: + plate_dir = URDF_ROOT / "mounts" / plate + meta = _glb_json(plate_dir / "meshes" / "visual" / f"{plate}.glb") + assert meta["extensionsRequired"] == ["KHR_draco_mesh_compression"] + mats = meta["materials"] + assert isinstance(mats, list) and len(mats) == 1 + assert mats[0]["name"] == "plate_anodized_aluminum" + pbr = mats[0]["pbrMetallicRoughness"] + np.testing.assert_allclose( + pbr["baseColorFactor"], + [0.9529411764705883, 0.9529411764705883, 0.9490196078431372, 1.0], + atol=1e-5, + ) + assert pbr["metallicFactor"] == pytest.approx(0.8, abs=1e-5) + assert pbr["roughnessFactor"] == pytest.approx(0.640130877494812, abs=1e-5) + + for arm_glb in flange_glbs: + arm_meta = _glb_json(URDF_ROOT / arm_glb) + arm_metals = [ + m["pbrMetallicRoughness"] + for m in arm_meta["materials"] # type: ignore[index] + if m.get("pbrMetallicRoughness", {}).get("metallicFactor", 0.0) > 0.5 + ] + assert len(arm_metals) == 1, arm_glb + np.testing.assert_allclose(pbr["baseColorFactor"], arm_metals[0]["baseColorFactor"], atol=1e-5) + assert pbr["metallicFactor"] == pytest.approx(arm_metals[0]["metallicFactor"], abs=1e-5) + assert pbr["roughnessFactor"] == pytest.approx(arm_metals[0]["roughnessFactor"], abs=0.01) + + root = ET.parse(plate_dir / f"{plate}.urdf").getroot() + color = root.find("./material[@name='PlateAluminum']/color") + assert color is not None + rgba = [float(v) for v in color.attrib["rgba"].split()] + np.testing.assert_allclose(rgba, [0.952941, 0.952941, 0.94902, 1.0], atol=1e-5) + + @pytest.mark.parametrize("plate", tuple(PLATES)) def test_plate_assets_geometry_openings_and_inertials(plate: str) -> None: trimesh = pytest.importorskip("trimesh") @@ -289,7 +363,7 @@ def test_plate_assets_geometry_openings_and_inertials(plate: str) -> None: pytest.importorskip("pygltflib") cfg = PLATES[plate] - plate_dir = URDF_ROOT / plate + plate_dir = URDF_ROOT / "mounts" / plate glb = plate_dir / "meshes" / "visual" / f"{plate}.glb" assert glb.stat().st_size < 1_000_000 meta = _glb_json(glb) diff --git a/tests/robots/test_robot_registry.py b/tests/robots/test_robot_registry.py index 294c9de..70f2d14 100644 --- a/tests/robots/test_robot_registry.py +++ b/tests/robots/test_robot_registry.py @@ -91,7 +91,7 @@ def test_lite6_movable_gripper_assembly_matches_standalone_part() -> None: standalone_path = Path(lite6_gripper_movable_visual_urdf()) assert combo_path.name.startswith("lite6__lite6_gripper__glb.") - finger_mesh_dir = PROJECT_ROOT / "assets" / "urdf" / "lite6_gripper" / "meshes" / "collision" + finger_mesh_dir = PROJECT_ROOT / "assets" / "urdf" / "end_effectors" / "lite6_gripper" / "meshes" / "collision" for path in (combo_path, standalone_path): root = ET.parse(path).getroot() diff --git a/tests/robots/test_robotiq_mounting_assembly.py b/tests/robots/test_robotiq_mounting_assembly.py index ff78d21..993b31e 100644 --- a/tests/robots/test_robotiq_mounting_assembly.py +++ b/tests/robots/test_robotiq_mounting_assembly.py @@ -28,14 +28,14 @@ PROJECT_ROOT = Path(__file__).resolve().parents[2] URDF_ROOT = PROJECT_ROOT / "assets" / "urdf" -ADAPTER_DIR = URDF_ROOT / "robotiq_mounting" +ADAPTER_DIR = URDF_ROOT / "mounts" / "robotiq_mounting" XARM_ARMS = ("xarm5_1305", "xarm6_1305", "xarm7_1305", "uf850") ROBOTIQ_EES = ("robotiq_2f_85", "robotiq_2f_140") CAMERAS = ("d405", "d435", "gemini_305", "zed_x_nano") ADAPTER_LIFT_M = 0.011 STAND_LIFT_M = 0.003 -ADAPTER_MASS_KG = 0.1097214329 +ADAPTER_MASS_KG = 0.118 ROBOTIQ_BASE_TCP_Z_M = {"robotiq_2f_85": 0.162253, "robotiq_2f_140": 0.234466} ROBOTIQ_TOOL_TIP_Z_M = {"robotiq_2f_85": 0.1093, "robotiq_2f_140": 0.1403} @@ -159,7 +159,10 @@ def test_adapter_assets_budget_material_hulls_and_inertial() -> None: ) assert pbr["metallicFactor"] == pytest.approx(0.8, abs=1e-5) assert pbr["roughnessFactor"] == pytest.approx(0.640130877494812, abs=1e-5) - for arm_glb in ("xarm6/meshes/xarm6_1305/visual_glb/link6.glb", "uf850/meshes/uf850/visual_glb/link6.glb"): + for arm_glb in ( + "robots/xarm6/meshes/xarm6_1305/visual_glb/link6.glb", + "robots/uf850/meshes/uf850/visual_glb/link6.glb", + ): arm_meta = _glb_json(URDF_ROOT / arm_glb) arm_metals = [ m["pbrMetallicRoughness"] @@ -182,6 +185,16 @@ def test_adapter_assets_budget_material_hulls_and_inertial() -> None: tensor = np.array([[i["ixx"], i["ixy"], i["ixz"]], [i["ixy"], i["iyy"], i["iyz"]], [i["ixz"], i["iyz"], i["izz"]]]) eig = np.linalg.eigvalsh(tensor) assert eig.min() > 0.0 and eig[0] + eig[1] > eig[2] + expected_inertia = { + "ixx": 4.427070717e-05, + "ixy": 0.0, + "ixz": 0.0, + "iyy": 4.997953153e-05, + "iyz": 7.208106518e-08, + "izz": 9.018403314e-05, + } + for key, expected_val in expected_inertia.items(): + assert i[key] == pytest.approx(expected_val, rel=0.0, abs=1e-12), key cols = [m.get("filename") for m in root.findall("./link[@name='robotiq_mounting']/collision/geometry/mesh")] assert cols == ["meshes/collision/robotiq_mounting_col_00.stl", "meshes/collision/robotiq_mounting_col_01.stl"] @@ -213,7 +226,7 @@ def test_robotiq_base_collar_is_smooth_coated_metal(ee: str) -> None: pygltflib = pytest.importorskip("pygltflib") DracoPy = pytest.importorskip("DracoPy") - glb_path = URDF_ROOT / ee / "meshes" / "visual" / "visual_glb" / "base.glb" + glb_path = URDF_ROOT / "end_effectors" / ee / "meshes" / "visual" / "visual_glb" / "base.glb" glb = pygltflib.GLTF2().load(str(glb_path)) blob = glb.binary_blob() assert len(glb.meshes) == 2 @@ -362,7 +375,9 @@ def frame_mm(name: str) -> np.ndarray: flange = get_robot_profile(arm).ee_link for ee in ROBOTIQ_EES: - rq_part = pin.buildModelFromUrdf(str(URDF_ROOT / ee / f"{ee}_movable_visual.urdf"), mimic=True) + rq_part = pin.buildModelFromUrdf( + str(URDF_ROOT / "end_effectors" / ee / f"{ee}_movable_visual.urdf"), mimic=True + ) rq_mass = sum(i.mass for i in rq_part.inertias) m = pin.buildModelFromUrdf(compose_robot_urdf(arm, ee), mimic=True) diff --git a/tests/robots/test_vacuum_adapter.py b/tests/robots/test_vacuum_adapter.py new file mode 100644 index 0000000..73d1e5b --- /dev/null +++ b/tests/robots/test_vacuum_adapter.py @@ -0,0 +1,150 @@ +"""Mock contract tests for VacuumGripperAdapter and TGPIO pin mapping.""" + +from __future__ import annotations + +from unittest.mock import MagicMock + +import pytest + +from ufactory.config import load_runtime_config +from ufactory.grippers import ( + VacuumGripperAdapter, + VacuumProfileAdapter, + create_gripper_adapter, + vacuum_controller_mode_error, + vacuum_io_pins, +) + + +@pytest.mark.parametrize(("version", "expected"), [(1, (0, 1)), (2, (3, 4))]) +def test_vacuum_io_pins_mapping(version: int, expected: tuple[int, int]) -> None: + assert vacuum_io_pins(version) == expected + + +@pytest.mark.parametrize("bad_version", [0, 3, -1, True, False, 1.5, "1"]) +def test_vacuum_io_pins_rejects_invalid_version(bad_version) -> None: + with pytest.raises(ValueError): + vacuum_io_pins(bad_version) + with pytest.raises(ValueError): + VacuumGripperAdapter(hardware_version=bad_version) + + +@pytest.mark.parametrize("version", [1, 2]) +def test_vacuum_adapter_sdk_contract(version: int) -> None: + adapter = VacuumGripperAdapter(hardware_version=version) + arm = MagicMock() + arm.get_vacuum_gripper.return_value = (0, 0) + arm.set_vacuum_gripper.return_value = 0 + + assert adapter.prepare_real(arm) == 0 + arm.get_vacuum_gripper.assert_called_with(hardware_version=version) + + assert adapter.send_real_suction(arm, True) == 0 + arm.set_vacuum_gripper.assert_called_with(True, wait=False, hardware_version=version) + + assert adapter.send_real_suction(arm, False) == 0 + arm.set_vacuum_gripper.assert_called_with(False, wait=False, hardware_version=version) + + arm.get_vacuum_gripper.return_value = (0, 1) + assert adapter.read_real(arm) == (0, 1) + + +def test_vacuum_adapter_prepare_real_requires_sdk_methods() -> None: + adapter = VacuumGripperAdapter() + + class IncompleteArm: + def get_vacuum_gripper(self, **_kwargs): + return (0, 0) + + with pytest.raises(RuntimeError, match="set_vacuum_gripper"): + adapter.prepare_real(IncompleteArm()) + + +def test_vacuum_adapter_rejects_non_boolean_suction_argument() -> None: + adapter = VacuumGripperAdapter() + arm = MagicMock() + with pytest.raises(ValueError, match="boolean"): + adapter.send_real_suction(arm, "on") # type: ignore[arg-type] + arm.set_vacuum_gripper.assert_not_called() + + +@pytest.mark.parametrize(("version", "pins"), [(1, (0, 1)), (2, (3, 4))]) +def test_vacuum_adapter_sync_false_and_read_real_output(version: int, pins: tuple[int, int]) -> None: + adapter = VacuumGripperAdapter(hardware_version=version) + arm = MagicMock() + arm.set_vacuum_gripper.return_value = 0 + outputs = [0, 0, 0, 0, 0] + outputs[pins[0]] = 1 + arm.get_tgpio_output_digital.return_value = (0, outputs) + + assert adapter.send_real_suction(arm, True, sync=False) == 0 + arm.set_vacuum_gripper.assert_called_with(True, wait=False, sync=False, hardware_version=version) + assert adapter.read_real_output(arm) == (0, (1, 0)) + + +@pytest.mark.parametrize("version", [1, 2]) +def test_vacuum_profile_adapter_deduplicates_and_shuts_down(version: int) -> None: + cfg = load_runtime_config("xarm5", gripper="vacuum_gripper") + assert cfg.gripper is not None + adapter = create_gripper_adapter(cfg.gripper, hardware_version=version) + assert isinstance(adapter, VacuumProfileAdapter) + assert adapter.gap_to_drive(1.0) == 0.0 + assert adapter.gap_to_drive(0.0) == 0.0 + assert adapter.drive_to_gap(0.0) == 1.0 + + arm = MagicMock() + arm.set_vacuum_gripper.return_value = 0 + outputs_off = [0, 0, 0, 0, 0] + outputs_off[adapter._vacuum.off_pin] = 1 + arm.get_tgpio_output_digital.return_value = (0, outputs_off) + + # prepare_real releases suction without calling check_on=True get_vacuum_gripper. + assert adapter.prepare_real(arm) == 0 + arm.get_vacuum_gripper.assert_not_called() + arm.set_vacuum_gripper.assert_called_once_with(False, wait=False, hardware_version=version) + + # Repeated open/off ticks deduplicate; crossing midpoint switches suction ON once. + assert adapter.send_real_gap(arm, 1.0) == 0 + assert adapter.send_real_gap(arm, 0.8) == 0 + assert arm.set_vacuum_gripper.call_count == 1 + + assert adapter.send_real_gap(arm, 0.2) == 0 + assert adapter.send_real_gap(arm, 0.0) == 0 + assert arm.set_vacuum_gripper.call_count == 2 + arm.set_vacuum_gripper.assert_called_with(True, wait=False, hardware_version=version) + + # Crossing back above midpoint switches suction OFF once. + assert adapter.send_real_gap(arm, 0.6) == 0 + assert adapter.send_real_gap(arm, 1.0) == 0 + assert arm.set_vacuum_gripper.call_count == 3 + arm.set_vacuum_gripper.assert_called_with(False, wait=False, hardware_version=version) + + # shutdown_real skips blocking SDK call when TGPIO output is already OFF (0, 1). + assert adapter.shutdown_real(arm) == 0 + assert arm.set_vacuum_gripper.call_count == 3 + + # When suction is still ON and arm is not paused, shutdown_real turns it OFF via SDK. + outputs_on = [0, 0, 0, 0, 0] + outputs_on[adapter._vacuum.on_pin] = 1 + arm.get_tgpio_output_digital.return_value = (0, outputs_on) + arm.state = 2 + assert adapter.shutdown_real(arm) == 0 + assert arm.set_vacuum_gripper.call_count == 4 + + # When suction is still ON while paused (state=3), shutdown_real never calls blocking set_vacuum_gripper. + arm.state = 3 + arm._arm.arm_cmd.tgpio_set_digital.return_value = [0] + assert adapter.shutdown_real(arm) == 0 + assert arm.set_vacuum_gripper.call_count == 4 + assert arm._arm.arm_cmd.tgpio_set_digital.call_count == 2 + + +def test_vacuum_controller_mode_error_matrix() -> None: + for robot in ("xarm5", "xarm6", "xarm7", "uf850"): + for mode in ("dry-run", "sdk-sim", "real"): + assert vacuum_controller_mode_error("pick_place", robot, "vacuum_gripper", mode) is None + sim_err = vacuum_controller_mode_error("pick_place", robot, "vacuum_gripper", "sim") + assert sim_err is not None and "--mode sim" in sim_err + lite_err = vacuum_controller_mode_error("pick_place", "lite6", "vacuum_gripper", "dry-run") + assert lite_err is not None and "xarm5" in lite_err + assert vacuum_controller_mode_error("pick_place", "lite6", "default", "sim") is None diff --git a/tests/safety/test_pinocchio_mimic_fallback.py b/tests/safety/test_pinocchio_mimic_fallback.py new file mode 100644 index 0000000..4d04a2b --- /dev/null +++ b/tests/safety/test_pinocchio_mimic_fallback.py @@ -0,0 +1,60 @@ +"""Pinocchio mimic fallback for URDFs where precedes its parent joint.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from ufactory.robots.assembly import compose_robot_urdf +from ufactory.safety.adapters.pinocchio import PinocchioCollisionBackend + + +def test_bio_g2_mimic_fallback_and_symmetric_fingers() -> None: + pytest.importorskip("pinocchio") + + bio_urdf = compose_robot_urdf("xarm6_1305", "bio_gripper_g2") + backend = PinocchioCollisionBackend( + bio_urdf, + joint_names=("joint1", "joint2", "joint3", "joint4", "joint5", "joint6"), + ee_link="link6", + passive_joint_positions={"bio_gripper_g2_right_finger_joint": 0.0395}, + ) + assert backend._mimic_fallback is True + left_id = int(backend.model.getJointId("bio_gripper_g2_left_finger_joint")) + right_id = int(backend.model.getJointId("bio_gripper_g2_right_finger_joint")) + left_idx = int(backend.model.joints[left_id].idx_q) + right_idx = int(backend.model.joints[right_id].idx_q) + + q0 = np.zeros(6, dtype=np.float64) + q_open = backend.full_q(q0) + assert q_open[right_idx] == pytest.approx(0.0395, abs=1e-9) + assert q_open[left_idx] == pytest.approx(-0.0395, abs=1e-9) + + q_closed = backend.full_q(q0, gripper_drive=0.0) + assert q_closed[right_idx] == pytest.approx(0.0, abs=1e-9) + assert q_closed[left_idx] == pytest.approx(0.0, abs=1e-9) + + # Verify the two finger frames are symmetric across the bio_gripper_g2_base_link Y midplane. + base_id = backend.model.getFrameId("bio_gripper_g2_base_link") + for drive, expected_half_y in ((0.0395, 0.0395), (0.0, 0.0)): + q_full = backend.full_q(q0, gripper_drive=drive) + backend.pin.forwardKinematics(backend.model, backend.data, q_full) + backend.pin.updateFramePlacements(backend.model, backend.data) + base = backend.data.oMf[base_id] + left_pos = base.actInv(backend.data.oMf[backend.model.getFrameId("bio_gripper_g2_left_finger")]).translation + right_pos = base.actInv(backend.data.oMf[backend.model.getFrameId("bio_gripper_g2_right_finger")]).translation + assert left_pos[1] == pytest.approx(-expected_half_y, abs=1e-6) + assert right_pos[1] == pytest.approx(expected_half_y, abs=1e-6) + + +def test_default_g2_keeps_native_pinocchio_mimic_path() -> None: + pytest.importorskip("pinocchio") + + g2_urdf = compose_robot_urdf("xarm6_1305", "gripper_g2") + backend = PinocchioCollisionBackend( + g2_urdf, + joint_names=("joint1", "joint2", "joint3", "joint4", "joint5", "joint6"), + ee_link="link6", + passive_joint_positions={"drive_joint": 0.057210812728026743}, + ) + assert backend._mimic_fallback is False diff --git a/tests/safety/test_safety_gate_approx_motion.py b/tests/safety/test_safety_gate_approx_motion.py new file mode 100644 index 0000000..ae27808 --- /dev/null +++ b/tests/safety/test_safety_gate_approx_motion.py @@ -0,0 +1,226 @@ +"""Phase 2 SafetyGate integration tests for ArmMotionController and allow_approx_motion.""" + +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path + +import numpy as np +import yaml + +from ufactory.cli.pick_place import _build_program +from ufactory.config import load_runtime_config +from ufactory.control import ArmMotionController +from ufactory.kinematics.controller_fk import CALIBRATION_FIELDS, load_nominal_chain +from ufactory.manipulation.commands import build_arm_controller, model_and_hashes +from ufactory.safety import ( + CartesianStepController, + CollisionResult, + JacobianKinematicsBackend, + ViolationType, +) +from ufactory.trajectory.preflight import create_safety_gate +from ufactory.trajectory.segments import JointLimits, Program, make_movel, make_movej + + +class _PassCollision: + def check(self, q, *, stage, gripper_drive=None): + return CollisionResult(False, 1.0, "link1", "link3") + + def check_all(self, q, *, stage, gripper_drive=None): + return (CollisionResult(False, 1.0, "link1", "link3"),) + + +class _PlainKinematics: + def forward(self, q): + return np.asarray((0.3, 0.0, 0.3, 1.0, 0.0, 0.0, 0.0), dtype=np.float64) + + def inverse(self, pose, seed): + return np.asarray(seed, dtype=np.float64) + + +def _write_synthetic_calibration( + tmp_path: Path, + robot_type: str, + serial_number: str, + deltas: dict[str, dict[str, float]], +) -> Path: + """Write a deterministic synthetic schema-v1 calibration YAML for CI-safe testing.""" + cfg = load_runtime_config(robot_type) + nominal_urdf, _, _ = model_and_hashes(cfg, None, None) + chain = load_nominal_chain(nominal_urdf, cfg.robot.joint_names) + joints = { + name: { + field: float(value) + float(deltas.get(name, {}).get(field, 0.0)) + for field, value in zip(CALIBRATION_FIELDS, row, strict=True) + } + for name, row in zip(chain.joint_names, chain.origins, strict=True) + } + payload = { + "schema_version": 1, + "robot_key": cfg.robot.key, + "serial_number": serial_number, + "units": {"position": "m", "angle": "rad"}, + "joints": joints, + } + path = tmp_path / f"{cfg.robot.key}_synthetic_calibration.yaml" + path.write_text(yaml.safe_dump(payload, sort_keys=False), encoding="utf-8") + return path + + +def test_arm_motion_controller_satisfies_safety_protocols() -> None: + ctrl = ArmMotionController.from_robot("uf850") + assert isinstance(ctrl, JacobianKinematicsBackend) + assert isinstance(ctrl, CartesianStepController) + assert ctrl.is_approx_motion is False + + +def test_safety_gate_uf850_wrist_singularity_fails_off_and_passes_on(tmp_path: Path) -> None: + cal = _write_synthetic_calibration( + tmp_path, + "uf850", + "FX851000TEST01", + {"joint4": {"y": 0.002, "roll": 0.004}}, + ) + cfg_off = load_runtime_config("uf850") + urdf, _, cal_hash = model_and_hashes(cfg_off, cal, None) + ctrl_off = build_arm_controller(cfg_off, urdf) + + # Start right above the UF850 wrist singularity and descend through z=208.6 mm + p_a = np.array([0.300, 0.0, 0.2886], dtype=np.float64) + p_b = np.array([0.300, 0.0, 0.1886], dtype=np.float64) + _, q_a_list = ctrl_off.get_inverse_kinematics( + [300.0, 0.0, 288.6, np.pi, 0.0, 0.0], input_is_radian=True, return_is_radian=True + ) + q_a = np.asarray(q_a_list, dtype=np.float64) + limits = JointLimits( + cfg_off.motion.joint_speed_rad_s, + cfg_off.motion.joint_acceleration_rad_s2, + cfg_off.motion.cartesian_speed_m_s, + cfg_off.motion.cartesian_acceleration_m_s2, + ) + prog = Program( + segments=[ + make_movej(q_a, q_a, rate=50.0, limits=limits, label="start"), + make_movel(p_a, p_b, rate=50.0, limits=limits, label="descend"), + ], + rate=50.0, + robot_key=cfg_off.robot.key, + ) + + gate_off = create_safety_gate( + cfg_off, + kinematics=ctrl_off, + collision=_PassCollision(), + calibration_sha256=cal_hash, + scene_sha256="0" * 64, + urdf_path=urdf, + ) + rep_off = gate_off.preflight(prog, executor="servo_cartesian") + assert not rep_off.passed + violation_types = {v.type for v in rep_off.violations} + assert ViolationType.VELOCITY in violation_types + assert ViolationType.ACCELERATION in violation_types + tl_off = next(c for c in rep_off.checks if c.name == "timeline") + assert tl_off.details["allow_approx_motion"] is False + assert tl_off.details["approx_steps"] == 0 + assert rep_off.warnings == () + + cfg_on = load_runtime_config("uf850", overrides={"motion.allow_approx_motion": True}) + assert cfg_on.sha256 != cfg_off.sha256 + ctrl_on = build_arm_controller(cfg_on, urdf) + gate_on = create_safety_gate( + cfg_on, + kinematics=ctrl_on, + collision=_PassCollision(), + calibration_sha256=cal_hash, + scene_sha256="0" * 64, + urdf_path=urdf, + ) + rep_on = gate_on.preflight(prog, executor="servo_cartesian") + assert rep_on.passed, rep_on.violations + tl_on = next(c for c in rep_on.checks if c.name == "timeline") + assert tl_on.details["allow_approx_motion"] is True + assert tl_on.details["approx_steps"] > 0 + assert 0.0 <= tl_on.details["max_approx_position_error_m"] < 0.002 + assert 0.0 < tl_on.details["max_approx_orientation_error_rad"] < 0.05 + assert any("allow_approx_motion activated" in w for w in rep_on.warnings) + + +def test_safety_gate_fails_closed_on_approx_motion_mismatch() -> None: + cfg_on = load_runtime_config("uf850", overrides={"motion.allow_approx_motion": True}) + cfg_off = load_runtime_config("uf850") + q0 = np.asarray(cfg_off.arm.default_qpos_rad, dtype=np.float64) + limits = JointLimits(1.0, 12.0, 0.15, 0.8) + prog = Program( + [make_movej(q0, q0, rate=50.0, limits=limits, label="start")], rate=50.0, robot_key=cfg_off.robot.key + ) + + # 1. allow_approx_motion=True but kinematics is not a CartesianStepController + gate_plain = create_safety_gate( + cfg_on, + kinematics=_PlainKinematics(), + collision=_PassCollision(), + calibration_sha256="0" * 64, + scene_sha256="0" * 64, + ) + rep_plain = gate_plain.preflight(prog, executor="servo_cartesian") + assert not rep_plain.passed + assert ViolationType.BACKEND_UNAVAILABLE in {v.type for v in rep_plain.violations} + + # 2. config enables approx motion, controller disables it + ctrl_off = ArmMotionController.from_robot("uf850", allow_approx_motion=False) + gate_mismatch_1 = create_safety_gate( + cfg_on, + kinematics=ctrl_off, + collision=_PassCollision(), + calibration_sha256="0" * 64, + scene_sha256="0" * 64, + ) + rep_m1 = gate_mismatch_1.preflight(prog, executor="servo_cartesian") + assert not rep_m1.passed + assert ViolationType.INVALID_INPUT in {v.type for v in rep_m1.violations} + + # 3. config disables approx motion, controller enables it + ctrl_on = ArmMotionController.from_robot("uf850", allow_approx_motion=True) + gate_mismatch_2 = create_safety_gate( + cfg_off, + kinematics=ctrl_on, + collision=_PassCollision(), + calibration_sha256="0" * 64, + scene_sha256="0" * 64, + ) + rep_m2 = gate_mismatch_2.preflight(prog, executor="servo_cartesian") + assert not rep_m2.passed + assert ViolationType.INVALID_INPUT in {v.type for v in rep_m2.violations} + + +def test_safety_gate_calibrated_xarm5_pick_place_passes_with_position_priority_ik( + tmp_path: Path, +) -> None: + cal = _write_synthetic_calibration( + tmp_path, + "xarm5", + "XF130500TEST01", + { + "joint2": {"roll": 0.004, "pitch": -0.003}, + "joint4": {"y": 0.0015, "roll": -0.003, "pitch": 0.002}, + }, + ) + cfg = load_runtime_config("xarm5") + urdf, _, cal_hash = model_and_hashes(cfg, cal, None) + ctrl = build_arm_controller(cfg, urdf) + prog = _build_program(cfg, kinematics=ctrl) + gate = create_safety_gate( + cfg, + kinematics=ctrl, + collision=_PassCollision(), + calibration_sha256=cal_hash, + scene_sha256="0" * 64, + urdf_path=urdf, + ) + rep = gate.preflight(prog, executor="servo_cartesian") + assert rep.passed, rep.violations + # Verify default config uses allow_approx_motion=False + cfg_no_req = replace(cfg, safety=replace(cfg.safety, require_collision=False)) + assert cfg_no_req.motion.allow_approx_motion is False diff --git a/tests/safety/test_sdk_sim_self_motion.py b/tests/safety/test_sdk_sim_self_motion.py new file mode 100644 index 0000000..97bb09b --- /dev/null +++ b/tests/safety/test_sdk_sim_self_motion.py @@ -0,0 +1,118 @@ +"""SDK-simulation comparison of redundant arms: self-motion is accepted, end-effector disagreement is not.""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest + +from ufactory.config import load_runtime_config +from ufactory.safety import CollisionResult +from ufactory.safety.sdk_sim import _quaternion_angle, validate_sdk_simulation + + +class SelfMotionKin: + """FK double: only q1 + q2 moves the end effector (q1 - q2 is self-motion); q7 turns the flange about z.""" + + def __init__(self, *, with_orientation: bool = True): + self.with_orientation = with_orientation + + def forward(self, q): + q = np.asarray(q, dtype=np.float64) + xyz = (0.3 + 0.1 * (q[0] + q[1]), 0.0, 0.3 + 0.1 * q[2]) + if not self.with_orientation: + return np.asarray(xyz) + half = 0.5 * q[-1] + return np.asarray((*xyz, 0.0, 0.0, math.sin(half), math.cos(half))) + + def inverse(self, pose, seed): + return np.asarray(seed, dtype=np.float64) + + +class Clear: + def check(self, q, *, stage, gripper_drive=None): + return CollisionResult(False, 1.0, "link1", "table", environment=True) + + def check_all(self, q, *, stage, gripper_drive=None): + return (self.check(q, stage=stage),) + + +def _validate(firmware_offset, *, dof=7, kinematics=None, limits=(-3.0, 3.0)): + config = load_runtime_config("xarm7" if dof == 7 else "xarm6") + shadow = np.zeros((3, dof)) + firmware = shadow + np.asarray(firmware_offset, dtype=np.float64) + return validate_sdk_simulation( + robot_key=config.robot.key, + serial_number="XS130502XXXXXX", + program_sha256="p" * 64, + config_sha256=config.sha256, + shadow_joint_stream_rad=shadow, + firmware_joint_stream_rad=firmware, + stages=("a", "b", "c"), + policy=config.safety, + kinematics=kinematics or SelfMotionKin(), + collision=Clear(), + joint_lower_rad=None if limits is None else np.full(dof, limits[0]), + joint_upper_rad=None if limits is None else np.full(dof, limits[1]), + ) + + +ELBOW = [0.17, -0.17, 0.0, 0.0, 0.0, 0.0, 0.0] # 10 deg apart, same end effector + + +def test_redundant_arm_accepts_a_different_elbow_when_the_end_effector_matches(): + evidence = _validate(ELBOW) + + assert evidence.passed, evidence.failures + assert evidence.self_motion_allowed + assert evidence.max_joint_error_rad == pytest.approx(0.17) + assert evidence.max_ee_error_m == pytest.approx(0.0, abs=1e-12) + assert evidence.max_ee_rotation_error_rad == pytest.approx(0.0, abs=1e-12) + + +def test_redundant_arm_rejects_end_effector_position_or_rotation_mismatch(): + moved = _validate([0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) # 10 mm along x + turned = _validate([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.06]) # flange only: position unchanged + + assert not moved.passed + assert any("FK error" in failure for failure in moved.failures) + assert not turned.passed + assert turned.max_ee_error_m == pytest.approx(0.0, abs=1e-12) + assert turned.max_ee_rotation_error_rad == pytest.approx(0.06) + assert any("rotation error" in failure for failure in turned.failures) + + +def test_redundant_arm_self_motion_needs_joint_limits_and_stays_inside_them(): + without_limits = _validate(ELBOW, limits=None) + near_limit = _validate(ELBOW, limits=(-0.18, 0.18)) # 0.17 is inside 0.18 but not inside the 0.02 margin + + assert not without_limits.passed + assert any("joint limits are required" in failure for failure in without_limits.failures) + assert not near_limit.passed + assert any("exceeds joint 1 limit" in failure for failure in near_limit.failures) + + +def test_redundant_arm_self_motion_needs_fk_orientation(): + evidence = _validate(ELBOW, kinematics=SelfMotionKin(with_orientation=False)) + + assert not evidence.passed + assert any("xyz+quaternion" in failure for failure in evidence.failures) + + +def test_non_redundant_arm_still_compares_joint_by_joint(): + evidence = _validate(ELBOW[:6], dof=6) + + assert not evidence.self_motion_allowed + assert not evidence.passed + assert any("joint error" in failure for failure in evidence.failures) + + +def test_quaternion_angle_is_the_rotation_angle(): + angle = 0.1 + q = np.asarray((0.0, 0.0, math.sin(angle / 2), math.cos(angle / 2))) + identity = np.asarray((0.0, 0.0, 0.0, 1.0)) + + assert _quaternion_angle(identity, q) == pytest.approx(angle) + assert _quaternion_angle(identity, -q) == pytest.approx(angle) + assert _quaternion_angle(q, q) == pytest.approx(0.0, abs=1e-15) diff --git a/tests/training/test_pick_place_e2e.py b/tests/training/test_pick_place_e2e.py index 802b007..a0d55d6 100644 --- a/tests/training/test_pick_place_e2e.py +++ b/tests/training/test_pick_place_e2e.py @@ -502,3 +502,216 @@ def run(command, log): assert not report["passed"] assert report["seeds"]["1"]["passed"] and report["seeds"]["3"]["passed"] assert "glb" in report["seeds"]["2"] + + +def test_outer_margin_linear_spring_relaxes_without_dead_zone(monkeypatch): + env = controller(monkeypatch) + env.obj = SimpleNamespace( + get_pos=lambda: torch.tensor([[0.30, 0.00, 0.080], [0.30, 0.00, 0.080]]), + get_quat=lambda: torch.tensor([[1.0, 0.0, 0.0, 0.0]]).repeat(2, 1), + ) + env.target_xy = torch.tensor([[0.3, 0.3]]) + env.near_table_m = 0.020 + env.metrics = SimpleNamespace( + ever_lifted_clear=torch.tensor([True, True]), + release_confirmed=torch.tensor([False, False]), + high_release=torch.tensor([False, False]), + touchdown_seen=torch.tensor([False, False]), + touchdown_ee_z=torch.zeros(2), + hold_steps=torch.zeros(2, dtype=torch.long), + contact_steps=torch.zeros(2, dtype=torch.long), + ever_carried=torch.tensor([True, True]), + target_tol=0.020, + place_clearance=0.002, + release_max_height=0.003, + ) + # Env 0 inside inner box -> zero spring drift; Env 1 above soft ceiling z=0.262 -> spring pulls back smoothly. + env.ee_setpoint = torch.tensor([[0.35, 0.10, 0.24], [0.35, 0.10, 0.29]]) + env.ee_link = SimpleNamespace(get_pos=lambda: env.ee_setpoint.clone()) + env._apply_action(torch.zeros(2, 4), torch.tensor([0.03, 0.03])) + torch.testing.assert_close(env.ee_setpoint[0], torch.tensor([0.35, 0.10, 0.24])) + assert env.ee_setpoint[1, 2].item() == pytest.approx(0.29 - 0.16 * (0.29 - 0.262), abs=1e-6) + + +def test_unclamping_ratchet_blocks_negative_jitter_only_after_unclamp_starts(monkeypatch): + env = controller(monkeypatch) + env.obj = SimpleNamespace( + get_pos=lambda: torch.tensor([[0.30, 0.30, 0.016], [0.30, 0.30, 0.016]]), + get_quat=lambda: torch.tensor([[1.0, 0.0, 0.0, 0.0]]).repeat(2, 1), + ) + env.target_xy = torch.tensor([[0.3, 0.3]]) + env.near_table_m = 0.020 + env.metrics = SimpleNamespace( + ever_lifted_clear=torch.tensor([True, True]), + release_confirmed=torch.tensor([False, False]), + high_release=torch.tensor([False, False]), + touchdown_seen=torch.tensor([True, True]), + touchdown_ee_z=torch.tensor([0.185, 0.185]), + hold_steps=torch.zeros(2, dtype=torch.long), + contact_steps=torch.zeros(2, dtype=torch.long), + ever_carried=torch.tensor([True, True]), + target_tol=0.020, + place_clearance=0.002, + release_max_height=0.003, + ) + # Env 0 is still clamped (gap_cmd=0.015 < measured 0.030); Env 1 has started unclamping (gap_cmd=0.031 >= measured 0.030). + env.gap_cmd = torch.tensor([0.015, 0.031]) + env._apply_action(torch.tensor([[0.0, 0.0, 0.0, -1.0], [0.0, 0.0, 0.0, -1.0]]), torch.tensor([0.030, 0.030])) + assert env.gap_cmd[0].item() == pytest.approx(0.012, abs=1e-6) + assert env.gap_cmd[1].item() == pytest.approx(0.031, abs=1e-6) + + +def test_c10_lift_drive_gives_positive_gradient_at_negative_az_and_no_drop_at_lift(monkeypatch): + env = controller(monkeypatch) + from examples.rl.pick_place import env as module + + obj = torch.tensor([[0.35, 0.0, 0.019], [0.35, 0.0, 0.019]]) + pads = obj.clone() + env.obj = SimpleNamespace(get_pos=lambda: obj, get_quat=lambda: torch.tensor([[1.0, 0.0, 0.0, 0.0]]).repeat(2, 1)) + monkeypatch.setattr(module, "pad_centers", lambda *args: (pads, pads)) + env.g2_model, env.left_finger_link, env.right_finger_link = None, None, None + env.pre_grasp_gap_m, env.reward_scales = 0.05, {"lift_drive_potential": 1.2} + env.target_xy = torch.tensor([[0.3, 0.3]]) + env.forces = torch.full((2, 2), 4.0) + env.place_rewarded = torch.zeros(2, dtype=torch.bool) + env.gap_cmd = torch.full((2,), 0.015) + env.measured_gap = lambda: torch.full((2,), 0.030) + env.metrics = SimpleNamespace( + spawn_xy=obj[:, :2].clone(), + max_held_z=torch.full((2,), 0.019), + ever_lifted_clear=torch.zeros(2, dtype=torch.bool), + ever_carried=torch.zeros(2, dtype=torch.bool), + contact_steps=torch.tensor([5, 5], dtype=torch.long), + release_confirmed=torch.zeros(2, dtype=torch.bool), + touchdown_seen=torch.zeros(2, dtype=torch.bool), + touchdown_ee_z=torch.zeros(2), + hold_steps=torch.zeros(2, dtype=torch.long), + required_hold_steps=10, + place_clearance=0.002, + release_max_height=0.003, + ) + # Even when both sampled a_z < 0 (clamped physically to 0), less-negative a_z must raise potential. + env.last_actions = torch.tensor([[0.0, 0.0, -1.0, 0.0], [0.0, 0.0, -0.2, 0.0]]) + pot_neg = env._potential() + assert pot_neg[1] > pot_neg[0] + 0.4 + + # Crossing ever_lifted_clear must never cause a negative jump in lift_drive. + obj[:, 2] = 0.080 + pads[:] = obj + env.metrics.max_held_z[:] = 0.080 + before = env._potential() + env.metrics.ever_lifted_clear[:] = True + after = env._potential() + assert torch.all(after >= before) + + +def test_c10_lift_off_xy_damping_active_only_below_15mm(monkeypatch): + env = controller(monkeypatch) + # Env 0 cube at 4 mm clearance (< 15 mm) -> damped by 0.35; Env 1 at 25 mm (>= 15 mm) -> full 1.0 XY control. + env.obj = SimpleNamespace( + get_pos=lambda: torch.tensor([[0.35, 0.00, 0.019], [0.35, 0.00, 0.040]]), + get_quat=lambda: torch.tensor([[1.0, 0.0, 0.0, 0.0]]).repeat(2, 1), + ) + env.target_xy = torch.tensor([[0.3, 0.3]]) + env.near_table_m = 0.020 + env.metrics = SimpleNamespace( + ever_lifted_clear=torch.tensor([False, False]), + release_confirmed=torch.tensor([False, False]), + high_release=torch.tensor([False, False]), + touchdown_seen=torch.tensor([False, False]), + touchdown_ee_z=torch.zeros(2), + hold_steps=torch.zeros(2, dtype=torch.long), + contact_steps=torch.tensor([5, 5], dtype=torch.long), + ever_carried=torch.tensor([False, True]), + target_tol=0.020, + place_clearance=0.002, + release_max_height=0.003, + ) + env.ee_setpoint = torch.tensor([[0.35, 0.00, 0.20], [0.35, 0.00, 0.22]]) + env.ee_link = SimpleNamespace(get_pos=lambda: env.ee_setpoint.clone()) + env._apply_action(torch.tensor([[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]]), torch.tensor([0.03, 0.03])) + assert env.ee_setpoint[0, 0].item() == pytest.approx(0.35 + 0.35 * 0.005, abs=1e-6) + assert env.ee_setpoint[1, 0].item() == pytest.approx(0.35 + 1.00 * 0.005, abs=1e-6) + + +def test_c10_lift_only_potential_zero_at_rest_and_positive_when_lifted(monkeypatch): + env = controller(monkeypatch) + # Env 0 rests on table (0 mm), Env 1 lifted cleanly to 25 mm. + env.obj = SimpleNamespace( + get_pos=lambda: torch.tensor([[0.35, 0.00, 0.015], [0.35, 0.00, 0.040]]), + get_quat=lambda: torch.tensor([[1.0, 0.0, 0.0, 0.0]]).repeat(2, 1), + ) + env.forces = torch.tensor([[4.0, 4.0], [4.0, 4.0]]) + env.reward_scales = {"lift_potential": 40.0} + env.metrics = SimpleNamespace( + max_held_z=torch.tensor([0.015, 0.040]), + ever_lifted_clear=torch.tensor([False, False]), + ) + lift_pot = env._lift_only_potential() + assert lift_pot[0].item() == pytest.approx(0.0, abs=1e-7) + assert lift_pot[1].item() == pytest.approx(40.0 * 0.025, abs=1e-6) + + +@pytest.mark.gpu +def test_c10_gpu_flange_limits_and_finite_horizon_timeout() -> None: + import json + import subprocess + import sys + import textwrap + + pytest.importorskip("genesis") + from ufactory.training.pick_place_config import PRE_LIFT_PAD_FLOOR_Z, TOUCHDOWN_REF_MARGIN_Z + + project_root = Path(__file__).resolve().parents[2] + script = textwrap.dedent( + """ + import json + from pathlib import Path + import genesis as gs + import torch + + from examples.rl.pick_place.env import XArm6PickPlaceEnv + from examples.rl.pick_place.runtime import DEFAULT_RECIPE, configure_runtime + from ufactory.simulation.compat import require_genesis_runtime + from ufactory.simulation.g2_adapter import pad_centers + from ufactory.training import build_pick_place_task_configs + + configure_runtime() + env_cfg, reward_cfg, robot_cfg = build_pick_place_task_configs("xarm6", recipe_path=DEFAULT_RECIPE) + env_cfg["num_envs"] = 4 + require_genesis_runtime(gs) + gs.init(backend=gs.gpu, precision="32", logging_level="warning", seed=1) + env = XArm6PickPlaceEnv(env_cfg=env_cfg, reward_cfg=reward_cfg, robot_cfg=robot_cfg, show_viewer=False) + left, right = pad_centers(env.g2_model, env.left_finger_link, env.right_finger_link) + flange_to_pad_z = float((env.ee_link.get_pos()[:, 2] - (left[:, 2] + right[:, 2]) / 2).mean()) + env.episode_length_buf[:] = env.max_episode_length - 1 + _, _, timeout_dones, timeout_info = env.step(torch.zeros(4, 4, device=gs.device)) + print( + json.dumps( + { + "pre_lift_flange_floor_z": env.pre_lift_flange_floor_z, + "touchdown_ref_ee_z": env.touchdown_ref_ee_z, + "flange_to_pad_z": flange_to_pad_z, + "timeout_dones": timeout_dones.bool().tolist(), + "time_outs": timeout_info["time_outs"].bool().tolist(), + } + ) + ) + gs.destroy() + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + cwd=project_root, + capture_output=True, + text=True, + timeout=180, + ) + assert result.returncode == 0, f"stderr:\n{result.stderr}\nstdout:\n{result.stdout}" + data = json.loads(result.stdout.strip().splitlines()[-1]) + assert data["pre_lift_flange_floor_z"] == pytest.approx(PRE_LIFT_PAD_FLOOR_Z + data["flange_to_pad_z"], abs=1e-5) + assert data["touchdown_ref_ee_z"] == pytest.approx( + data["pre_lift_flange_floor_z"] + TOUCHDOWN_REF_MARGIN_Z, abs=1e-9 + ) + assert data["timeout_dones"] == [True, True, True, True] + assert data["time_outs"] == [False, False, False, False] diff --git a/tests/training/test_public_rl_example.py b/tests/training/test_public_rl_example.py index 9887915..1206227 100644 --- a/tests/training/test_public_rl_example.py +++ b/tests/training/test_public_rl_example.py @@ -34,13 +34,18 @@ (("environment", "success_hold_steps"), 10), (("reward", "approach_potential"), 8.0), (("reward", "grasp_potential"), 4.0), - (("reward", "release_potential"), 4.0), + (("reward", "lift_drive_potential"), 1.2), + (("reward", "place_potential"), 9.0), + (("reward", "release_potential"), 8.0), + (("reward", "hold_potential"), 8.0), + (("reward", "pre_lift_stall_penalty"), 0.04), (("reward", "lift_potential"), 40.0), (("reward", "transit_potential"), 8.0), (("reward", "success"), 40.0), (("train", "algorithm", "class_name"), "PPO"), (("train", "algorithm", "learning_rate"), 3e-4), (("train", "actor", "class_name"), "MLPModel"), + (("train", "actor", "distribution_cfg", "std_range"), [0.16, 0.65]), (("train", "critic", "class_name"), "MLPModel"), (("train", "runner", "max_iterations"), 2000), (("train", "runner", "early_stop_evaluations"), 2), @@ -77,7 +82,7 @@ def test_pick_place_task_configs_bind_current_runtime_hash() -> None: assert env_cfg["runtime_config_sha256"] == rl_config.sha256 assert env_cfg["num_obs"] == 70 assert env_cfg["num_actions"] == 4 - assert reward_cfg["release_potential"] == pytest.approx(4.0) + assert reward_cfg["release_potential"] == pytest.approx(8.0) assert set(robot_cfg) == {"gripper_damping", "gripper_frictionloss"} diff --git a/tests/training/test_reach.py b/tests/training/test_reach.py index fc052b5..98f1fc4 100644 --- a/tests/training/test_reach.py +++ b/tests/training/test_reach.py @@ -126,11 +126,11 @@ def test_reach_runtime_config_uses_the_bare_arm_and_target_box( @pytest.mark.parametrize( ("robot", "dof", "num_obs", "urdf_suffix"), ( - ("xarm5", 5, 21, "assets/urdf/xarm5/xarm5_1305.urdf"), - ("xarm6", 6, 24, "assets/urdf/xarm6/xarm6_1305.urdf"), - ("xarm7", 7, 27, "assets/urdf/xarm7/xarm7_1305.urdf"), - ("uf850", 6, 24, "assets/urdf/uf850/uf850.urdf"), - ("lite6", 6, 24, "assets/urdf/lite6/lite6.urdf"), + ("xarm5", 5, 21, "assets/urdf/robots/xarm5/xarm5_1305.urdf"), + ("xarm6", 6, 24, "assets/urdf/robots/xarm6/xarm6_1305.urdf"), + ("xarm7", 7, 27, "assets/urdf/robots/xarm7/xarm7_1305.urdf"), + ("uf850", 6, 24, "assets/urdf/robots/uf850/uf850.urdf"), + ("lite6", 6, 24, "assets/urdf/robots/lite6/lite6.urdf"), ), ) def test_reach_task_config_supports_all_robots_and_round_trips( diff --git a/tests/trajectory/test_bio_g2_mirror_scene.py b/tests/trajectory/test_bio_g2_mirror_scene.py new file mode 100644 index 0000000..81bc2f4 --- /dev/null +++ b/tests/trajectory/test_bio_g2_mirror_scene.py @@ -0,0 +1,128 @@ +"""Scene builder and kinematic mirror helpers for Bio Gripper G2.""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +import pytest + +torch = pytest.importorskip("torch") +pytest.importorskip("genesis") + +from ufactory.config import load_runtime_config +from ufactory.robots.assembly import compose_robot_urdf +from ufactory.robots.runtime import BIO_GRIPPER_G2_GRIPPER_PARAMS, G2_GRIPPER_PARAMS, get_robot_runtime_profile +from ufactory.simulation import GenesisRuntimeManager +from ufactory.trajectory.mirror_executor import ( + KinematicCarryTracker, + TrajKinematicMirror, + _set_kinematic_pose, + gap_m_from_drive, +) +from ufactory.trajectory.scene import _robot_urdf_for_visual_model, drive_for_gap_m, gripper_dof_multipliers + + +class _RecordingRobot: + def __init__(self) -> None: + self.calls: list[tuple[list[float], list[int], bool]] = [] + + def set_dofs_position(self, values, dof_idx, *, zero_velocity: bool = False) -> None: + self.calls.append(([float(v) for v in values], list(dof_idx), bool(zero_velocity))) + + +def test_gripper_dof_multipliers_bio_and_g2() -> None: + assert gripper_dof_multipliers(BIO_GRIPPER_G2_GRIPPER_PARAMS) == (1.0, -1.0) + assert gripper_dof_multipliers(G2_GRIPPER_PARAMS) == (1.0,) * len(G2_GRIPPER_PARAMS.all_joint_names) + assert gripper_dof_multipliers(None) == () + + +def test_robot_urdf_for_visual_model_supports_bio_gripper_g2() -> None: + runtime = get_robot_runtime_profile("xarm6", gripper="bio_gripper_g2") + urdf_path, use_glb = _robot_urdf_for_visual_model(runtime, "glb") + assert use_glb is True + assert urdf_path == compose_robot_urdf("xarm6_1305", "bio_gripper_g2") + assert Path(urdf_path).is_file() + + +def test_set_kinematic_pose_applies_grip_multipliers() -> None: + q_arm = [0.1, -0.2, 0.3, 0.0, 0.4, 0.5] + arm_idx = [0, 1, 2, 3, 4, 5] + grip_idx = [6, 7] + drive = 0.02 + + robot_with_mult = _RecordingRobot() + _set_kinematic_pose(robot_with_mult, q_arm, arm_idx, drive, grip_idx, grip_multipliers=(1.0, -1.0)) + assert len(robot_with_mult.calls) == 2 + assert robot_with_mult.calls[0] == (pytest.approx(q_arm), arm_idx, True) + assert robot_with_mult.calls[1] == (pytest.approx([drive, -drive]), grip_idx, True) + + robot_without_mult = _RecordingRobot() + _set_kinematic_pose(robot_without_mult, q_arm, arm_idx, drive, grip_idx, grip_multipliers=None) + assert len(robot_without_mult.calls) == 2 + assert robot_without_mult.calls[1] == (pytest.approx([drive, drive]), grip_idx, True) + + +@pytest.mark.parametrize( + ("gap_m", "expected_drive"), + [ + (0.071, 0.0), + (0.150, 0.0395), + (0.1105, 0.01975), + ], +) +def test_bio_g2_drive_gap_roundtrip(gap_m: float, expected_drive: float) -> None: + drive = drive_for_gap_m(gap_m, BIO_GRIPPER_G2_GRIPPER_PARAMS) + assert drive == pytest.approx(expected_drive, abs=1e-9) + assert gap_m_from_drive(drive, BIO_GRIPPER_G2_GRIPPER_PARAMS) == pytest.approx(gap_m, abs=1e-9) + + +@pytest.mark.gpu +def test_bio_g2_headless_kinematic_mirror_symmetry_and_empty_grasp() -> None: + cfg = load_runtime_config("xarm6", gripper="bio_gripper_g2") + module = importlib.import_module("ufactory.cli.pick_place") + + with GenesisRuntimeManager(cfg.simulation): + program, ctx, _q_home = module._compile_servo_j_program(cfg, calibration=None) + mirror = TrajKinematicMirror(ctx, program) + mirror.prime_to_home() + tracker = KinematicCarryTracker( + mirror, + grasp_gap_m=module._close_gap_m(cfg), + attach_dist_m=module._mirror_attach_dist_m(cfg), + grasp_segment_label="grip", + release_segment_label="release", + approach_freeze_labels=("descend",), + ) + + obj0 = ctx.obj.get_pos()[0].clone() + saw_grip_mid = False + saw_grip_end = False + saw_release_end = False + + for seg in program.segments: + _, n = seg.samples(program.rate) + for i in range(n): + tracker.on_tick(seg, i) + if seg.label == "grip" and i == n // 2: + mid_q = ctx.robot.get_dofs_position(ctx.all_gripper_dof_idx).detach().cpu().numpy().reshape(-1) + assert mid_q[0] > 0.005 + assert mid_q[1] == pytest.approx(-mid_q[0], abs=1e-6) + saw_grip_mid = True + if seg.label == "grip" and i == n - 1: + grip_q = ctx.robot.get_dofs_position(ctx.all_gripper_dof_idx).detach().cpu().numpy().reshape(-1) + assert grip_q[0] == pytest.approx(0.0, abs=1e-6) + assert grip_q[1] == pytest.approx(-grip_q[0], abs=1e-6) + assert gap_m_from_drive(mirror.grip_drive, ctx.gripper) == pytest.approx(0.071, abs=1e-6) + assert tracker.attached is False + saw_grip_end = True + if seg.label == "release" and i == n - 1: + release_q = ctx.robot.get_dofs_position(ctx.all_gripper_dof_idx).detach().cpu().numpy().reshape(-1) + assert release_q[0] == pytest.approx(0.0395, abs=1e-6) + assert release_q[1] == pytest.approx(-0.0395, abs=1e-6) + assert tracker.attached is False + saw_release_end = True + + assert saw_grip_mid and saw_grip_end and saw_release_end + obj_end = ctx.obj.get_pos()[0] + assert float(torch.linalg.norm(obj_end - obj0)) < 1e-3 diff --git a/tests/trajectory/test_pick_place_visual_cli.py b/tests/trajectory/test_pick_place_visual_cli.py index 0d53b43..10d1e44 100644 --- a/tests/trajectory/test_pick_place_visual_cli.py +++ b/tests/trajectory/test_pick_place_visual_cli.py @@ -10,11 +10,10 @@ from ufactory.cli import pick_place from ufactory.safety import PreflightCheck, SafetyViolation, ViolationType -from ufactory.trajectory.mirror_executor import update_scene_visualizer from ufactory.visualization.viewer import start_deferred_viewer -def test_servo_j_compatibility_fails_before_hardware_connection(monkeypatch): +def test_visual_compatibility_fails_before_hardware_connection(monkeypatch): connected = False def _reject_capabilities(**_kwargs): @@ -37,6 +36,7 @@ def _unexpected_connect(_ip): "real", "--executor", "servo_j", + "--visual", "--ip", "192.0.2.1", "--calibration", @@ -47,6 +47,37 @@ def _unexpected_connect(_ip): assert connected is False +@pytest.mark.parametrize( + ("cli_name", "argv"), + [ + ("pick_place", ["--robot", "xarm6", "--mode", "dry-run", "--executor", "servo_j"]), + ( + "pick_place", + ["--robot", "xarm6", "--gripper", "bio_gripper_g2", "--mode", "dry-run", "--executor", "servo_j"], + ), + ("packaging", ["--robot", "xarm6", "--mode", "dry-run", "--executor", "servo_j"]), + ], +) +def test_headless_servo_j_skips_genesis_for_pick_place_and_packaging(monkeypatch, tmp_path, cli_name, argv): + pytest.importorskip("pinocchio") + from ufactory.cli import packaging + import ufactory.simulation as simulation_pkg + + def _forbid_genesis(*_args, **_kwargs): + raise AssertionError("Genesis must not be checked or initialized for headless servo_j") + + monkeypatch.setattr(pick_place, "require_genesis_capabilities", _forbid_genesis) + monkeypatch.setattr(pick_place, "GenesisRuntimeManager", _forbid_genesis) + monkeypatch.setattr(packaging, "require_genesis_capabilities", _forbid_genesis) + monkeypatch.setattr(simulation_pkg, "GenesisRuntimeManager", _forbid_genesis) + + report = tmp_path / f"{cli_name}_servo_j.json" + module = pick_place if cli_name == "pick_place" else packaging + rc = module.main([*argv, "--report", str(report)]) + assert rc == 0 + assert report.is_file() + + def test_visual_rejected_for_dry_run(capsys): with pytest.raises(SystemExit) as excinfo: pick_place.main( @@ -341,6 +372,10 @@ def on_step() -> None: def test_mirror_visual_update_drops_frame_when_render_lock_is_busy(): + pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.trajectory.mirror_executor import update_scene_visualizer + class BusyLock: def acquire(self, *, blocking: bool) -> bool: assert blocking is False @@ -356,3 +391,104 @@ def acquire(self, *, blocking: bool) -> bool: assert update_scene_visualizer(scene) is False assert context_updates == [] + + +def test_mirror_visual_update_supports_genesis_1_4_7_rigid_geoms_t(): + pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.trajectory.mirror_executor import update_scene_visualizer + import numpy as np + + class FreeLock: + def acquire(self, *, blocking: bool) -> bool: + assert blocking is False + return True + + def release(self) -> None: + pass + + geom_0 = SimpleNamespace(uid="g0", idx=0) + geom_1 = SimpleNamespace(uid="g1", idx=1) + solver = SimpleNamespace() # No _vgeoms_render_T (Genesis 1.4.7+). + entity_a = SimpleNamespace( + _morph=SimpleNamespace(enable_custom_vverts=False), + _solver=solver, + surface=SimpleNamespace(vis_mode="visual"), + vgeoms=[geom_0], + geoms=[], + ) + entity_b = SimpleNamespace( + _morph=SimpleNamespace(enable_custom_vverts=False), + _solver=solver, + surface=SimpleNamespace(vis_mode="visual"), + vgeoms=[geom_1], + geoms=[], + ) + t0 = np.eye(4, dtype=np.float32) + t0[0, 3] = 0.25 + t1 = np.eye(4, dtype=np.float32) + t1[1, 3] = -0.15 + # Genesis 1.4.7 rigid_geoms_T layout: (n_rendered_envs, n_geoms, 4, 4). + geoms_t = np.stack([t0, t1], axis=0)[None, ...] + rigid_calls: list[tuple[object, bool]] = [] + + def rigid_geoms_t(s, is_visual: bool): + rigid_calls.append((s, is_visual)) + return geoms_t + + node_0 = SimpleNamespace(mesh=SimpleNamespace(_bounds="old", primitives=[SimpleNamespace(poses=None)])) + node_1 = SimpleNamespace(mesh=SimpleNamespace(_bounds="old", primitives=[SimpleNamespace(poses=None)])) + uploaded: list[tuple[object, str, np.ndarray]] = [] + context = SimpleNamespace( + visualizer=SimpleNamespace(update_visual_states=lambda **kwargs: None), + _scene=SimpleNamespace(_bounds="old"), + rigid_nodes={"g0": node_0, "g1": node_1}, + rendered_envs_idx=[0], + rigid_geoms_T=rigid_geoms_t, + _get_geom_active_envs_idx=lambda geom, rendered: list(rendered), + jit=SimpleNamespace(update_buffer=lambda node, name, arr: uploaded.append((node, name, arr))), + update=lambda **kwargs: (_ for _ in ()).throw(AssertionError("should not fall back to full update")), + ) + viewer = SimpleNamespace( + _pyrender_viewer=SimpleNamespace(render_lock=FreeLock(), update_on_sim_step=lambda: None), + context=context, + is_alive=lambda: True, + ) + scene = SimpleNamespace(visualizer=SimpleNamespace(viewer=viewer)) + + assert update_scene_visualizer(scene, entities=(entity_a, entity_b)) is True + assert rigid_calls == [(solver, True)] + assert len(uploaded) == 2 + np.testing.assert_allclose(node_0.mesh.primitives[0].poses[0], t0) + np.testing.assert_allclose(node_1.mesh.primitives[0].poses[0], t1) + np.testing.assert_allclose(uploaded[0][2][0], t0.T) + np.testing.assert_allclose(uploaded[1][2][0], t1.T) + + +def test_mirror_visual_update_falls_back_to_context_update_for_genesis_1_5(): + pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.trajectory.mirror_executor import update_scene_visualizer + + class FreeLock: + def acquire(self, *, blocking: bool) -> bool: + return True + + def release(self) -> None: + pass + + fallback_calls: list[bool] = [] + # Genesis 1.5+ removes context.rigid_nodes and visualizer.update_visual_states. + context = SimpleNamespace( + visualizer=SimpleNamespace(), + update=lambda **kwargs: fallback_calls.append(kwargs["force_render"]), + ) + viewer = SimpleNamespace( + _pyrender_viewer=SimpleNamespace(render_lock=FreeLock(), update_on_sim_step=lambda: None), + context=context, + is_alive=lambda: True, + ) + scene = SimpleNamespace(visualizer=SimpleNamespace(viewer=viewer)) + + assert update_scene_visualizer(scene, entities=(SimpleNamespace(),)) is True + assert fallback_calls == [True] diff --git a/tests/trajectory/test_trajectory_ik.py b/tests/trajectory/test_trajectory_ik.py index 2726a03..988612a 100644 --- a/tests/trajectory/test_trajectory_ik.py +++ b/tests/trajectory/test_trajectory_ik.py @@ -206,3 +206,38 @@ def test_retime_ik_joint_stream_and_compile_handle_unconstrained_limits_without_ v_max=0.0, a_max=0.0, ) + + +def test_arm_ik_context_and_solve_arm_home_q_pure_numpy(): + from ufactory.control import ArmMotionController + from ufactory.trajectory.ik import ArmIKContext, solve_arm_home_q + + controller = ArmMotionController.from_robot( + "xarm6", + tcp_offset_mm_rpy=(157.64, 0.0, 59.5, 0.0, 0.0, 0.0), + ) + q_flange = solve_arm_home_q(controller, [0.22236, -0.12, 0.30], include_tcp=False) + q_tcp = solve_arm_home_q(controller, [0.38, -0.12, 0.30 - 0.0595], include_tcp=True) + np.testing.assert_allclose(q_flange, q_tcp, atol=1e-5) + + limits = JointLimits(0.35, 2.0, 0.14, 0.8) + move_seg = make_movel( + np.array([0.22236, -0.12, 0.30]), + np.array([0.22236, -0.12, 0.20]), + rate=50.0, + limits=limits, + label="descend", + ) + source = Program(rate=50.0, robot_key="xarm6_1305", limits=limits, segments=[move_seg]) + ctx = ArmIKContext( + arm_controller=controller, + robot_key="xarm6_1305", + robot_urdf_path="/tmp/xarm6.urdf", + kinematics_yaml_path="/tmp/cal.yaml", + kinematics_suffix="L56A01", + include_tcp=False, + ) + compiled = compile_cartesian_program_to_joint_stream(source, ctx) + assert compiled.segments[0].kind == "movej" + assert compiled.metadata["ik_kinematics_suffix"] == "L56A01" + np.testing.assert_allclose(compiled.segments[0].q_start, q_flange, atol=1e-4) diff --git a/tests/trajectory/test_zero_dof_scene_mirror.py b/tests/trajectory/test_zero_dof_scene_mirror.py new file mode 100644 index 0000000..424ced2 --- /dev/null +++ b/tests/trajectory/test_zero_dof_scene_mirror.py @@ -0,0 +1,153 @@ +"""Tests for 0-DOF end-effector (vacuum gripper / bare arm) support in scene and mirror.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import numpy as np +import pytest + +from ufactory.config.models import GripperProfile +from ufactory.robots.runtime import ( + LITE6_VACUUM_GRIPPER_PARAMS, + VACUUM_GRIPPER_PARAMS, + get_robot_runtime_profile, +) + + +def test_zero_dof_gripper_profile_and_runtime_params() -> None: + profile = GripperProfile( + adapter="vacuum_gripper", + drive_joint="", + all_joint_names=(), + finger_link_names=(), + open_drive=0.0, + closed_drive=0.0, + open_gap_m=0.0, + closed_gap_m=0.0, + kp=0.0, + kv=0.0, + force_lower_n=0.0, + force_upper_n=0.0, + damping=0.0, + frictionloss=0.0, + real_command=True, + feedback=True, + closed_loop=False, + allowed_contact_links=frozenset({"xarm_vacuum_gripper_link"}), + tool_tip_offset_z_m=0.126, + finger_pad_below_center_m=0.0, + finger_close_descent_m=0.0, + grasp_table_clearance_m=0.010, + grasp_height_extra_m=0.0, + tcp_offset=(0.0, 0.0, 126.0, 0.0, 0.0, 0.0), + ) + assert profile.has_actuated_joints is False + assert profile.tcp_offset == (0.0, 0.0, 126.0, 0.0, 0.0, 0.0) + + assert VACUUM_GRIPPER_PARAMS.has_actuated_joints is False + assert VACUUM_GRIPPER_PARAMS.has_finger_links is False + assert LITE6_VACUUM_GRIPPER_PARAMS.has_actuated_joints is False + assert LITE6_VACUUM_GRIPPER_PARAMS.has_finger_links is False + + rt_vac = get_robot_runtime_profile("xarm6", gripper="vacuum_gripper") + assert rt_vac.gripper == VACUUM_GRIPPER_PARAMS + rt_bare = get_robot_runtime_profile("xarm6", gripper="bare") + assert rt_bare.gripper is None + + +def test_zero_dof_drive_gap_and_tool_center_fallbacks() -> None: + torch = pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.trajectory.mirror_executor import KinematicCarryTracker, gap_m_from_drive + from ufactory.trajectory.scene import drive_for_gap_m, gripper_dof_multipliers + + assert drive_for_gap_m(0.05, VACUUM_GRIPPER_PARAMS) == 0.0 + assert drive_for_gap_m(0.05, None) == 0.0 + assert gap_m_from_drive(0.0, VACUUM_GRIPPER_PARAMS) == 0.0 + assert gap_m_from_drive(0.0, None) == 0.0 + assert gripper_dof_multipliers(VACUUM_GRIPPER_PARAMS) == () + assert gripper_dof_multipliers(None) == () + + # Test _tool_center fallback to tool_tip_link, then ik_link + rotated tcp_offset_flange_m. + obj = SimpleNamespace( + get_pos=lambda: torch.tensor([[0.3, 0.0, 0.415]], dtype=torch.float32), + get_quat=lambda: torch.tensor([[1.0, 0.0, 0.0, 0.0]], dtype=torch.float32), + ) + tip = SimpleNamespace(get_pos=lambda: torch.tensor([[0.3, 0.0, 0.50]], dtype=torch.float32)) + ik = SimpleNamespace( + get_pos=lambda: torch.tensor([[0.3, 0.0, 0.626]], dtype=torch.float32), + get_quat=lambda: torch.tensor([[0.0, 1.0, 0.0, 0.0]], dtype=torch.float32), # Rx(pi) gripper-down WXYZ + ) + + mirror_tip = SimpleNamespace( + ctx=SimpleNamespace(left_finger=None, right_finger=None, tool_tip_link=tip, ik_link=ik, obj=obj), + rate=50.0, + ) + tracker_tip = KinematicCarryTracker(mirror_tip, grasp_gap_m=0.0) + np.testing.assert_allclose(tracker_tip._tool_center().numpy(), [0.3, 0.0, 0.50], atol=1e-6) + + mirror_offset = SimpleNamespace( + ctx=SimpleNamespace( + left_finger=None, + right_finger=None, + tool_tip_link=None, + ik_link=ik, + tcp_offset_flange_m=(0.0, 0.0, 0.126), + obj=obj, + ), + rate=50.0, + ) + tracker_offset = KinematicCarryTracker(mirror_offset, grasp_gap_m=0.0) + np.testing.assert_allclose(tracker_offset._tool_center().numpy(), [0.3, 0.0, 0.50], atol=1e-6) + + +@pytest.mark.gpu +@pytest.mark.parametrize("gripper", ["vacuum_gripper", "bare"]) +def test_build_scene_and_mirror_support_zero_dof_end_effectors(gripper: str) -> None: + pytest.importorskip("torch") + pytest.importorskip("genesis") + from ufactory.config import load_runtime_config + from ufactory.simulation import GenesisRuntimeManager + from ufactory.trajectory.mirror_executor import KinematicCarryTracker, TrajKinematicMirror + from ufactory.trajectory.scene import build_scene + from ufactory.trajectory.segments import JointLimits, Program, make_gripper, make_movel + + cfg = load_runtime_config("xarm6") + with GenesisRuntimeManager(cfg.simulation): + ctx = build_scene(robot_key="xarm6", gripper=gripper, show_viewer=False, calibrated_g2=False) + assert ctx.left_finger is None + assert ctx.right_finger is None + assert ctx.gripper_dof_idx == [] + assert ctx.all_gripper_dof_idx == [] + if gripper == "vacuum_gripper": + assert ctx.tcp_offset_flange_m == pytest.approx((0.0, 0.0, 0.126), abs=1e-6) + assert ctx.finger_z_offset == pytest.approx(0.126, abs=2e-3) + else: + assert ctx.gripper is None + assert ctx.tcp_offset_flange_m == pytest.approx((0.0, 0.0, 0.0), abs=1e-6) + assert ctx.finger_z_offset == pytest.approx(0.0, abs=1e-6) + + limits = JointLimits(0.35, 2.0, 0.14, 0.8) + seg_move = make_movel( + np.array(ctx.home_pos_base, dtype=np.float64), + np.array([ctx.home_pos_base[0], ctx.home_pos_base[1], ctx.home_pos_base[2] - 0.03], dtype=np.float64), + rate=50.0, + limits=limits, + label="descend", + ) + seg_grip = make_gripper(0.0, 0.0, rate=50.0, duration_s=0.04, label="grip") + program = Program(rate=50.0, robot_key="xarm6_1305", limits=limits, segments=[seg_move, seg_grip]) + + mirror = TrajKinematicMirror(ctx, program) + mirror.prime_to_home() + tracker = KinematicCarryTracker(mirror, grasp_gap_m=0.0, attach_dist_m=0.0) + for seg in program.segments: + _, n = seg.samples(program.rate) + for i in range(n): + tracker.on_tick(seg, i) + assert tracker.attached is False + flange_z = float(ctx.ik_link.get_pos()[0][2]) + tool_z = float(tracker._tool_center()[2]) + expected_dz = 0.126 if gripper == "vacuum_gripper" else 0.0 + assert (flange_z - tool_z) == pytest.approx(expected_dz, abs=2e-3) diff --git a/ufactory/__init__.py b/ufactory/__init__.py index a61ed77..495fc88 100644 --- a/ufactory/__init__.py +++ b/ufactory/__init__.py @@ -1,6 +1,7 @@ """Minimal robot catalog and source-asset access API.""" from ufactory.config.assets import AssetLayoutError, RepositoryAssetStore +from ufactory.control import ArmMotionController from ufactory.robots.registry import ( PROJECT_ROOT, ROBOT_PROFILES, @@ -15,6 +16,7 @@ "PROJECT_ROOT", "ROBOT_PROFILES", "RobotModelSpec", + "ArmMotionController", "AssetLayoutError", "compose_robot_urdf", "RepositoryAssetStore", diff --git a/ufactory/cli/packaging.py b/ufactory/cli/packaging.py index 3fa46f2..b4d140a 100644 --- a/ufactory/cli/packaging.py +++ b/ufactory/cli/packaging.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +from contextlib import nullcontext from dataclasses import asdict import os from pathlib import Path @@ -40,10 +41,11 @@ packaging_layout, packaging_scene_sha256, ) +from ufactory.manipulation.tcp import check_controller_tcp_offset, resolve_tool_tcp_spec from ufactory.robots.registry import robot_cli_choices from ufactory.safety import validate_sdk_simulation from ufactory.safety.gate import program_sha256 -from ufactory.simulation import GenesisRuntimeManager, override_simulation_backend +from ufactory.simulation import override_simulation_backend from ufactory.simulation.compat import require_genesis_capabilities from ufactory.trajectory.execution import ExecutionBindings, execute_real from ufactory.trajectory.preflight import create_safety_gate @@ -57,7 +59,7 @@ def _build_packaging_context(config: Any, urdf: Path, *, show_viewer: bool = Fal ) scene, robot, block, display_layout = build_packaging_scene( - sim_dt=1.0 / float(config.motion.rate_hz), + sim_dt=1.0 / float(config.simulation.rate_hz), show_viewer=show_viewer, robot_urdf_path=str(urdf), runtime_config=config, @@ -141,6 +143,17 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("--position-mm", type=float) parser.add_argument("--speed-percent", type=float) parser.add_argument("--force-percent", type=float) + parser.add_argument( + "--allow-approx-motion", + action="store_true", + help="Enable firmware-aligned DLS singularity avoidance (mirrors set_allow_approx_motion(True))", + ) + parser.add_argument( + "--sim-rate-hz", + type=float, + default=None, + help="Override Genesis physics simulation step rate in Hz (default: 50.0)", + ) parser.add_argument("--visual", action="store_true") parser.add_argument("--speed", type=float, default=1.0, help="Simulation-only playback multiplier") parser.add_argument("--cycles", type=_positive_cycles, default=None, help="Simulation cycle count (default: 1)") @@ -167,13 +180,18 @@ def main(argv: Sequence[str] | None = None) -> int: if args.visual and args.mode in {"dry-run", "sdk-sim"}: parser.error("--visual is only supported with --mode sim or --mode real") selected_gripper = None if args.gripper == "default" else args.gripper + cli_overrides: dict[str, Any] = dict(gripper_overrides) + if args.allow_approx_motion: + cli_overrides["motion.allow_approx_motion"] = True + if args.sim_rate_hz is not None: + cli_overrides["simulation.rate_hz"] = args.sim_rate_hz try: config = load_runtime_config( args.robot, task="packaging_showcase", gripper=selected_gripper, config_path=args.config, - overrides=gripper_overrides, + overrides=cli_overrides, ) except ValueError as exc: parser.error(str(exc)) @@ -186,10 +204,10 @@ def main(argv: Sequence[str] | None = None) -> int: parser.error( f"{config.robot.key} has no enabled real gripper; full real packaging is unsupported for this profile" ) - if args.mode != "sim" and (args.executor == "servo_j" or args.visual): + if args.mode != "sim" and args.visual: require_genesis_capabilities( pbr=True, - deferred_viewer=bool(args.visual), + deferred_viewer=True, ) if args.mode == "sim": if config.gripper is not None and config.gripper.adapter == "g2" and config.simulation.g2.speed_percent <= 0: @@ -219,25 +237,36 @@ def main(argv: Sequence[str] | None = None) -> int: flush=True, ) - genesis = None bridge = None try: urdf, urdf_hash, calibration_hash = _model_and_hashes(config, args.calibration, serial) kinematics, collision = _backends(config, urdf) - ik_ctx = None q_home: np.ndarray | None = None if args.executor == "servo_j": - from ufactory.trajectory.ik import compile_cartesian_program_to_joint_stream + from ufactory.trajectory.ik import ( + ArmIKContext, + compile_cartesian_program_to_joint_stream, + solve_arm_home_q, + ) print( - "[ik-compile] building Genesis scene and compiling servo_j trajectory...", + "[ik-compile] compiling servo_j trajectory with ArmMotionController...", flush=True, ) ik_started = time.perf_counter() - genesis = GenesisRuntimeManager(config.simulation) - genesis.__enter__() - ik_ctx = _build_packaging_context(config, urdf, show_viewer=False) - q_home = np.asarray(ik_ctx.home_qpos, dtype=np.float64)[ik_ctx.arm_dof_idx] + layout = packaging_layout(config) + q_home = solve_arm_home_q( + kinematics, + layout.home_position_m, + default_qpos_rad=config.arm.default_qpos_rad, + ) + ik_ctx = ArmIKContext( + arm_controller=kinematics, + robot_key=config.robot.key, + robot_urdf_path=str(urdf), + kinematics_yaml_path=str(args.calibration) if args.calibration is not None else None, + kinematics_suffix=serial, + ) program = compile_cartesian_program_to_joint_stream( build_packaging_program(config, q_home=q_home), ik_ctx, @@ -272,6 +301,11 @@ def main(argv: Sequence[str] | None = None) -> int: # Read once so SDK simulation and real execution share the same TCP conversion. tcp_offset = read_tcp_offset(arm) print(f"[hardware] controller tcp_offset={tcp_offset.tolist()} (xyz mm, rpy rad)", flush=True) + check_controller_tcp_offset( + tcp_offset, + resolve_tool_tcp_spec(config).tcp_offset_mm_deg, + mode=args.mode, + ) transport = XArmTransport(arm, robot_key=config.robot.key, serial_number=serial, tcp_offset=tcp_offset) shadow = None stages = None @@ -298,7 +332,14 @@ def main(argv: Sequence[str] | None = None) -> int: if args.executor == "servo_cartesian" or args.mode == "sdk-sim": if shadow is None or stages is None: shadow, stages = gate.shadow_joint_stream(program) - firmware = _sdk_sim_feedback(arm, program, config, start_q, tcp_offset=tcp_offset) + firmware = _sdk_sim_feedback( + arm, + program, + config, + start_q, + tcp_offset=tcp_offset, + allow_approx_motion=config.motion.allow_approx_motion, + ) evidence = validate_sdk_simulation( robot_key=config.robot.key, serial_number=serial, @@ -311,6 +352,8 @@ def main(argv: Sequence[str] | None = None) -> int: kinematics=kinematics, collision=collision, allowed_collision=gate.collision_allowed, + joint_lower_rad=gate.joint_lower_rad, + joint_upper_rad=gate.joint_upper_rad, ) evidence_path = _sdk_evidence_path(args.report, config.robot.key) _write_json(evidence_path, asdict(evidence)) @@ -334,13 +377,6 @@ def main(argv: Sequence[str] | None = None) -> int: if args.visual: from ufactory.trajectory.mirror_process import PackagingMirrorProcess - # The servo_j compiler no longer needs its Genesis scene. Destroy - # it before the isolated viewer starts so GPU memory is not held by - # two Genesis runtimes at once. - if genesis is not None: - genesis.__exit__(None, None, None) - genesis = None - ik_ctx = None bridge = PackagingMirrorProcess( approved.program, robot_key=config.robot.key, @@ -359,28 +395,36 @@ def main(argv: Sequence[str] | None = None) -> int: ) current_drive, gripper_sender = prepare_real_gripper_sender(arm, transport, config.gripper) - execution = execute_real( - approved, - transport=transport, - bindings=ExecutionBindings( - robot_key=config.robot.key, - serial_number=serial, - config_sha256=config.sha256, - urdf_sha256=urdf_hash, - calibration_sha256=calibration_hash, - scene_sha256=scene_hash, - ), - confirm_real=True, - runtime_monitor=lambda q, stage: gate.runtime_monitor( - q, - stage, - gripper_drive=current_drive[0], - include_collision=False, - ), - gripper_sender=gripper_sender, - on_tick=bridge.on_tick if bridge is not None else None, - not_ready_codes=frozenset((9,)), + switch_ctx = ( + kinematics.sync_hardware_switches(arm) + if args.executor == "servo_cartesian" + and callable(getattr(kinematics, "sync_hardware_switches", None)) + and callable(getattr(arm, "set_allow_approx_motion", None)) + else nullcontext() ) + with switch_ctx: + execution = execute_real( + approved, + transport=transport, + bindings=ExecutionBindings( + robot_key=config.robot.key, + serial_number=serial, + config_sha256=config.sha256, + urdf_sha256=urdf_hash, + calibration_sha256=calibration_hash, + scene_sha256=scene_hash, + ), + confirm_real=True, + runtime_monitor=lambda q, stage: gate.runtime_monitor( + q, + stage, + gripper_drive=current_drive[0], + include_collision=False, + ), + gripper_sender=gripper_sender, + on_tick=bridge.on_tick if bridge is not None else None, + not_ready_codes=frozenset((9,)), + ) print_real_execution_summary(execution) if bridge is not None: bridge.hold_until_closed() @@ -388,8 +432,6 @@ def main(argv: Sequence[str] | None = None) -> int: finally: if bridge is not None: bridge.close() - if genesis is not None: - genesis.__exit__(None, None, None) if arm is not None and getattr(arm, "connected", False): arm.disconnect() diff --git a/ufactory/cli/pick_place.py b/ufactory/cli/pick_place.py index 8c08b1e..e9586a6 100644 --- a/ufactory/cli/pick_place.py +++ b/ufactory/cli/pick_place.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +from contextlib import nullcontext from dataclasses import asdict import hashlib import json @@ -19,6 +20,7 @@ resolve_pick_place_object_spec, ) from ufactory.manipulation.commands import ( + build_arm_controller, build_manipulation_backends, model_and_hashes as _model_and_hashes, paced_start_hold as _paced_start_hold, @@ -26,6 +28,7 @@ prime_first_movej_sample, print_real_execution_summary, print_sdk_sim_failures, + shutdown_real_gripper, write_json as _write_json, connect as _connect, read_q as _read_q, @@ -39,7 +42,10 @@ print_preflight_complete as _print_preflight_complete, print_preflight_violation_summary as _print_preflight_violation_summary, ) +from ufactory.grippers.bio_g2 import bio_g2_controller_mode_error from ufactory.grippers.robotiq import robotiq_controller_mode_error +from ufactory.grippers.vacuum import vacuum_controller_mode_error +from ufactory.manipulation.tcp import check_controller_tcp_offset, resolve_tool_tcp_spec from ufactory.hardware import XArmTransport from ufactory.kinematics import get_robot_sn, read_tcp_offset from ufactory.kinematics.orientation import GRIPPER_DOWN_QUAT_XYZW @@ -49,7 +55,11 @@ from ufactory.simulation import GenesisRuntimeManager, override_simulation_backend from ufactory.simulation.compat import require_genesis_capabilities from ufactory.trajectory.execution import ExecutionBindings, execute_real, execute_sim -from ufactory.trajectory.ik import compile_cartesian_program_to_joint_stream +from ufactory.trajectory.ik import ( + ArmIKContext, + compile_cartesian_program_to_joint_stream, + solve_arm_home_q, +) from ufactory.trajectory.planner import ( CartesianWaypoint, JointWaypoint, @@ -102,29 +112,32 @@ def _backends(config: Any, urdf: Path, *, calibrated_g2: bool = False) -> tuple[ def _build_program(config: Any, kinematics: Any | None = None, *, q_home: np.ndarray | None = None) -> Any: """Build the v0.2.4-style pick-place program starting at Cartesian home. - ``start_xyz`` is always ``[obj_x, obj_y, home_z]`` (not FK of default_qpos). - When ``q_home`` is provided (Genesis home IK), a zero-length MoveJ seed is - prepended for ``servo_j`` compilation/preposition. Otherwise, if - ``kinematics`` is provided, Pinocchio IK seeds a MoveJ at home for - ``servo_cartesian`` preflight. + ``start_xyz`` is always the flange position above the pick point at ``home_z`` + (not FK of ``default_qpos``). Task pick/place coordinates are expressed in + TCP space and converted to flange (``link6``) waypoints via + :func:`~ufactory.manipulation.tcp.resolve_tool_tcp_spec`. + When ``q_home`` is provided, a zero-length MoveJ seed is prepended for + ``servo_j`` compilation/preposition. Otherwise, if ``kinematics`` is + provided, exact IK seeds a MoveJ at home for ``servo_cartesian`` preflight. """ params = config.task.parameters object_pos = np.asarray(params["fixed_object_position_m"], dtype=np.float64) target_pos = np.asarray(params["fixed_target_position_m"], dtype=np.float64) - from ufactory.trajectory.scene import dry_heights - - gripper_name = config.gripper.adapter if config.gripper is not None else None - heights = dry_heights(config.robot.key, gripper=gripper_name) + tool_tcp = resolve_tool_tcp_spec(config) + grasp_tcp_z = tool_tcp.grasp_tcp_z_m + grasp_flange = tool_tcp.tcp_to_flange_xyz([float(object_pos[0]), float(object_pos[1]), grasp_tcp_z]) + place_flange = tool_tcp.tcp_to_flange_xyz([float(target_pos[0]), float(target_pos[1]), grasp_tcp_z]) is_lite6 = str(getattr(config.gripper, "adapter", "")) == "lite6" - obj_x, obj_y = float(object_pos[0]), float(object_pos[1]) - place_x, place_y = float(target_pos[0]), float(target_pos[1]) - grasp_z = float(heights.grasp_link6_z) - pre_grasp_z = float(heights.pre_grasp_link6_z) - lift_z = float(heights.lift_link6_z) - home_z = float(heights.home_pos_base[2]) + obj_x, obj_y = float(grasp_flange[0]), float(grasp_flange[1]) + place_x, place_y = float(place_flange[0]), float(place_flange[1]) + grasp_z = float(grasp_flange[2]) + pre_grasp_z = grasp_z + 0.10 + default_ee_z = float(params["default_ee_position_m"][2]) + lift_z = default_ee_z + home_z = default_ee_z open_gap = float(config.gripper.open_gap_m) - close_gap = LITE6_DEFAULT_GRIPPER_GRASP_GAP_M if is_lite6 else DEFAULT_GRIPPER_GRASP_GAP_M + close_gap = _close_gap_m(config) gripper_duration_s = LITE6_GRIPPER_DURATION_S if is_lite6 else float(config.motion.gripper_duration_s) pre_grasp = [obj_x, obj_y, pre_grasp_z] @@ -222,16 +235,12 @@ def _build_program(config: Any, kinematics: Any | None = None, *, q_home: np.nda def _home_xyz_m(config: Any) -> np.ndarray: - from ufactory.trajectory.scene import dry_heights - params = config.task.parameters object_pos = np.asarray(params["fixed_object_position_m"], dtype=np.float64) - gripper_name = config.gripper.adapter if config.gripper is not None else None - heights = dry_heights(config.robot.key, gripper=gripper_name) - return np.asarray( - [float(object_pos[0]), float(object_pos[1]), float(heights.home_pos_base[2])], - dtype=np.float64, - ) + tool_tcp = resolve_tool_tcp_spec(config) + flange_xy = tool_tcp.tcp_to_flange_xyz([float(object_pos[0]), float(object_pos[1]), 0.0])[:2] + home_z = float(params["default_ee_position_m"][2]) + return np.asarray([float(flange_xy[0]), float(flange_xy[1]), home_z], dtype=np.float64) def _arm_q_from_scene(ctx: Any) -> np.ndarray: @@ -241,14 +250,22 @@ def _arm_q_from_scene(ctx: Any) -> np.ndarray: def _build_ik_scene( - config: Any, *, calibration: Path | None, show_viewer: bool = False, calibrated_g2: bool = False + config: Any, + *, + calibration: Path | None, + show_viewer: bool = False, + calibrated_g2: bool = False, + arm_controller: Any | None = None, ) -> Any: from ufactory.trajectory.scene import build_scene gripper_name = config.gripper.adapter if config.gripper is not None else None + tool_tcp = resolve_tool_tcp_spec(config) + has_xy_offset = any(abs(v) > 1e-9 for v in tool_tcp.tcp_offset_flange_m[:2]) + home_xy_base = tuple(float(v) for v in _home_xyz_m(config)[:2]) if has_xy_offset else None return build_scene( robot_key=config.robot.key, - rate=config.motion.rate_hz, + rate=config.simulation.rate_hz, show_viewer=show_viewer, substeps=config.simulation.substeps, constraint_solver=config.simulation.constraint_solver, @@ -264,10 +281,19 @@ def _build_ik_scene( robotiq_settings=config.simulation.robotiq, gripper=gripper_name, excluded_geometry_pairs=config.gripper.excluded_geometry_pairs if config.gripper is not None else (), + arm_controller=arm_controller, + home_xy_base=home_xy_base, **_scene_layout_kwargs(config), ) +def _mirror_attach_dist_m(config: Any) -> float | None: + """Return mirror carry latch distance override, disabling carry for empty Bio G2 / vacuum runs.""" + if str(getattr(config.gripper, "adapter", "")) in {"bio_g2", "vacuum_gripper"}: + return 0.0 + return None + + def _open_sim_viewer(ctx: Any, *, warmup_steps: int = 3) -> None: """Settle the scene, then open the interactive viewer at the home pose.""" @@ -279,15 +305,48 @@ def _open_sim_viewer(ctx: Any, *, warmup_steps: int = 3) -> None: start_deferred_viewer(scene) +def _compile_servo_j_offline( + config: Any, + *, + kinematics: Any, + urdf: Path, + calibration: Path | None = None, + serial: str | None = None, +) -> tuple[Any, np.ndarray]: + """Compile the Cartesian pick-place program to a joint stream without starting Genesis.""" + + q_home = solve_arm_home_q( + kinematics, + _home_xyz_m(config), + default_qpos_rad=config.arm.default_qpos_rad, + ) + seeded = _build_program(config, q_home=q_home) + ik_ctx = ArmIKContext( + arm_controller=kinematics, + robot_key=config.robot.key, + robot_urdf_path=str(urdf), + kinematics_yaml_path=str(calibration) if calibration is not None else None, + kinematics_suffix=serial, + ) + compiled = compile_cartesian_program_to_joint_stream(seeded, ik_ctx) + return compiled, q_home + + def _compile_servo_j_program( config: Any, *, calibration: Path | None, show_viewer: bool = False, + arm_controller: Any | None = None, ) -> tuple[Any, Any, np.ndarray]: - """Build Cartesian program, Genesis-compile with down_quat, return (program, ctx, q_home).""" + """Build Cartesian program, compile with down_quat, return (program, ctx, q_home).""" - ctx = _build_ik_scene(config, calibration=calibration, show_viewer=show_viewer) + ctx = _build_ik_scene( + config, + calibration=calibration, + show_viewer=show_viewer, + arm_controller=arm_controller, + ) q_home = _arm_q_from_scene(ctx) seeded = _build_program(config, q_home=q_home) compiled = compile_cartesian_program_to_joint_stream(seeded, ctx) @@ -296,7 +355,12 @@ def _compile_servo_j_program( def _close_gap_m(config: Any) -> float: adapter = str(getattr(config.gripper, "adapter", "")) - return LITE6_DEFAULT_GRIPPER_GRASP_GAP_M if adapter == "lite6" else DEFAULT_GRIPPER_GRASP_GAP_M + if adapter == "lite6": + return LITE6_DEFAULT_GRIPPER_GRASP_GAP_M + if adapter == "vacuum_gripper": + return float(getattr(config.gripper, "closed_gap_m", 0.0)) + closed_gap = float(getattr(config.gripper, "closed_gap_m", 0.0)) + return max(DEFAULT_GRIPPER_GRASP_GAP_M, closed_gap) def _scene_layout_kwargs(config: Any) -> dict[str, Any]: @@ -364,9 +428,16 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("--robot", required=True, choices=("xarm5", "xarm6", "xarm7", "uf850", "lite6")) parser.add_argument( "--gripper", - choices=("default", "g2", "bio_gripper_g2", "lite6", "robotiq_2f_85", "robotiq_2f_140"), + choices=("default", "g2", "bio_gripper_g2", "lite6", "robotiq_2f_85", "robotiq_2f_140", "vacuum_gripper"), default="default", - help="Select end-effector variant (bio_gripper_g2, robotiq_2f_85, robotiq_2f_140 support xarm5/6/7 and uf850)", + help="Select end-effector variant (bio_gripper_g2, robotiq_2f_85, robotiq_2f_140, vacuum_gripper support xarm5/6/7 and uf850)", + ) + parser.add_argument( + "--vacuum-hardware-version", + type=int, + choices=(1, 2), + default=1, + help="Vacuum gripper hardware version (1: plug-in TGPIO 0/1, 2: contact TGPIO 3/4)", ) parser.add_argument("--mode", required=True, choices=("sim", "dry-run", "sdk-sim", "real")) parser.add_argument("--executor", choices=("servo_j", "servo_cartesian")) @@ -390,6 +461,17 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("--transport-speed-mm-s", type=float) parser.add_argument("--substeps", type=int, choices=(8, 32)) parser.add_argument("--force-percent", type=float) + parser.add_argument( + "--allow-approx-motion", + action="store_true", + help="Enable firmware-aligned DLS singularity avoidance (mirrors set_allow_approx_motion(True))", + ) + parser.add_argument( + "--sim-rate-hz", + type=float, + default=None, + help="Override Genesis physics simulation step rate in Hz (default: 50.0)", + ) parser.add_argument( "--visual", action="store_true", @@ -411,66 +493,91 @@ def main(argv: Sequence[str] | None = None) -> int: if robotiq_error is not None: parser.error(robotiq_error) + bio_error = bio_g2_controller_mode_error("pick_place", args.robot, args.gripper, args.mode) + if bio_error is not None: + parser.error(bio_error) + + vacuum_error = vacuum_controller_mode_error("pick_place", args.robot, args.gripper, args.mode) + if vacuum_error is not None: + parser.error(vacuum_error) + if args.gripper == "bio_gripper_g2": if args.robot not in {"xarm5", "xarm6", "xarm7", "uf850"}: parser.error("--gripper bio_gripper_g2 requires --robot xarm5, xarm6, xarm7 or uf850") - if args.mode != "sim": - parser.error("--gripper bio_gripper_g2 currently requires --mode sim") - if args.speed_mm_s is not None and args.speed_percent is not None: - parser.error("Provide at most one of --speed-mm-s or --speed-percent") - from ufactory.simulation.bio_g2_model import ( - MAX_SPEED_MM_S, - MIN_SPEED_MM_S, - bio_g2_speed_mm_s_from_percent, - bounded, - finger_force_n, - ) - from ufactory.trajectory.bio_g2_replay import ( - DEFAULT_PICK_PLACE_SPEED_MM_S, - DEFAULT_SUBSTEPS, - DEFAULT_TRANSPORT_SPEED_MM_S, - run_bio_g2_pick_place, - ) + if args.mode == "sim": + if args.speed_mm_s is not None and args.speed_percent is not None: + parser.error("Provide at most one of --speed-mm-s or --speed-percent") + from ufactory.simulation.bio_g2_model import ( + MAX_SPEED_MM_S, + MIN_SPEED_MM_S, + bio_g2_speed_mm_s_from_percent, + bounded, + finger_force_n, + ) + from ufactory.trajectory.bio_g2_replay import ( + DEFAULT_PICK_PLACE_SPEED_MM_S, + DEFAULT_SUBSTEPS, + DEFAULT_TRANSPORT_SPEED_MM_S, + run_bio_g2_pick_place, + ) - try: - if args.speed_mm_s is not None: - speed_mm_s = bounded(args.speed_mm_s, MIN_SPEED_MM_S, MAX_SPEED_MM_S, "speed_mm_s") - elif args.speed_percent is not None: - if args.speed_percent <= 0: - raise ValueError("automatic Bio Gripper G2 manipulation requires --speed-percent > 0") - speed_mm_s = bio_g2_speed_mm_s_from_percent(args.speed_percent) - else: - speed_mm_s = DEFAULT_PICK_PLACE_SPEED_MM_S - force_percent = 50.0 if args.force_percent is None else float(args.force_percent) - finger_force_n(force_percent) - transport_speed_mm_s = ( - DEFAULT_TRANSPORT_SPEED_MM_S if args.transport_speed_mm_s is None else float(args.transport_speed_mm_s) + try: + if args.speed_mm_s is not None: + speed_mm_s = bounded(args.speed_mm_s, MIN_SPEED_MM_S, MAX_SPEED_MM_S, "speed_mm_s") + elif args.speed_percent is not None: + if args.speed_percent <= 0: + raise ValueError("automatic Bio Gripper G2 manipulation requires --speed-percent > 0") + speed_mm_s = bio_g2_speed_mm_s_from_percent(args.speed_percent) + else: + speed_mm_s = DEFAULT_PICK_PLACE_SPEED_MM_S + force_percent = 50.0 if args.force_percent is None else float(args.force_percent) + finger_force_n(force_percent) + transport_speed_mm_s = ( + DEFAULT_TRANSPORT_SPEED_MM_S + if args.transport_speed_mm_s is None + else float(args.transport_speed_mm_s) + ) + if not np.isfinite(transport_speed_mm_s) or transport_speed_mm_s <= 0: + raise ValueError("transport_speed_mm_s must be finite and positive") + except ValueError as exc: + parser.error(str(exc)) + + summary = run_bio_g2_pick_place( + robot=args.robot, + backend=args.backend or "gpu", + headless=not bool(args.visual), + executor=args.executor or "servo_cartesian", + speed_mm_s=speed_mm_s, + transport_speed_mm_s=transport_speed_mm_s, + substeps=DEFAULT_SUBSTEPS if args.substeps is None else int(args.substeps), + force_percent=force_percent, + csv_path=args.csv, + summary_path=args.sim_report or args.report, ) - if not np.isfinite(transport_speed_mm_s) or transport_speed_mm_s <= 0: - raise ValueError("transport_speed_mm_s must be finite and positive") - except ValueError as exc: - parser.error(str(exc)) - - summary = run_bio_g2_pick_place( - robot=args.robot, - backend=args.backend or "gpu", - headless=not bool(args.visual), - executor=args.executor or "servo_cartesian", - speed_mm_s=speed_mm_s, - transport_speed_mm_s=transport_speed_mm_s, - substeps=DEFAULT_SUBSTEPS if args.substeps is None else int(args.substeps), - force_percent=force_percent, - csv_path=args.csv, - summary_path=args.sim_report or args.report, - ) - metrics = summary["metrics"] - if "place_xy_error_mm" in metrics and "home_return_error_mm" in metrics: - print( - f"place_error_mm={metrics['place_xy_error_mm']:.3f} " - f"home_drift_mm={metrics['home_return_error_mm']:.3f} " - f"completed={summary['passed']}" + metrics = summary["metrics"] + if "place_xy_error_mm" in metrics and "home_return_error_mm" in metrics: + print( + f"place_error_mm={metrics['place_xy_error_mm']:.3f} " + f"home_drift_mm={metrics['home_return_error_mm']:.3f} " + f"completed={summary['passed']}" + ) + return 0 if summary["passed"] else 1 + if ( + any( + getattr(args, name) is not None + for name in ( + "position_mm", + "speed_percent", + "force_percent", + "speed_mm_s", + "transport_speed_mm_s", + "substeps", + ) ) - return 0 if summary["passed"] else 1 + or args.csv + or args.sim_report + ): + parser.error("Bio Gripper G2 simulation speed/force/record flags require --mode sim") if args.executor is None: parser.error("--executor is required for this gripper") @@ -482,13 +589,18 @@ def main(argv: Sequence[str] | None = None) -> int: } if args.mode != "sim" and (gripper_overrides or args.csv or args.sim_report): parser.error("percentage commands and execution records require --mode sim") + cli_overrides: dict[str, Any] = dict(gripper_overrides) + if args.allow_approx_motion: + cli_overrides["motion.allow_approx_motion"] = True + if args.sim_rate_hz is not None: + cli_overrides["simulation.rate_hz"] = args.sim_rate_hz selected_gripper = None if args.gripper == "default" else args.gripper try: config = load_runtime_config( args.robot, gripper=selected_gripper, config_path=args.config, - overrides=gripper_overrides, + overrides=cli_overrides, ) except ValueError as exc: parser.error(str(exc)) @@ -505,7 +617,7 @@ def main(argv: Sequence[str] | None = None) -> int: if args.print_config: print(dump_runtime_config(config), end="") return 0 - if args.executor == "servo_j" or args.mode == "sim" or args.visual: + if args.mode == "sim" or args.visual: require_genesis_capabilities( pbr=True, deferred_viewer=bool(args.visual) or bool(config.simulation.show_viewer), @@ -528,6 +640,7 @@ def main(argv: Sequence[str] | None = None) -> int: ) try: urdf, urdf_hash, calibration_hash = _model_and_hashes(config, args.calibration, serial) + arm_controller = build_arm_controller(config, urdf) if urdf.is_file() else None ik_ctx = None q_home: np.ndarray | None = None genesis_for_ik = None @@ -537,10 +650,16 @@ def main(argv: Sequence[str] | None = None) -> int: genesis_for_ik = GenesisRuntimeManager(config.simulation) genesis_for_ik.__enter__() - ik_ctx = _build_ik_scene(config, calibration=args.calibration, calibrated_g2=True) + ik_ctx = _build_ik_scene( + config, + calibration=args.calibration, + calibrated_g2=True, + arm_controller=arm_controller, + ) urdf = Path(ik_ctx.robot_urdf_path) urdf_hash = sha256_file(urdf) kinematics, collision = _backends(config, urdf, calibrated_g2=True) + ik_ctx.arm_controller = kinematics q_home = _arm_q_from_scene(ik_ctx) program = _build_program(config, q_home=q_home) if config.gripper.adapter == "g2": @@ -552,16 +671,16 @@ def main(argv: Sequence[str] | None = None) -> int: elif args.executor == "servo_j": kinematics, collision = _backends(config, urdf) print( - "[ik-compile] building Genesis scene and compiling servo_j trajectory...", + "[ik-compile] compiling servo_j trajectory with ArmMotionController...", flush=True, ) ik_started = time.perf_counter() - genesis_for_ik = GenesisRuntimeManager(config.simulation) - genesis_for_ik.__enter__() - program, ik_ctx, q_home = _compile_servo_j_program( + program, q_home = _compile_servo_j_offline( config, + kinematics=kinematics, + urdf=urdf, calibration=args.calibration, - show_viewer=False, + serial=serial, ) _print_ik_compile_complete(program, elapsed_s=time.perf_counter() - ik_started) else: @@ -631,6 +750,11 @@ def main(argv: Sequence[str] | None = None) -> int: # Read once so SDK simulation and real execution share the same TCP conversion. tcp_offset = read_tcp_offset(arm) print(f"[hardware] controller tcp_offset={tcp_offset.tolist()} (xyz mm, rpy rad)", flush=True) + check_controller_tcp_offset( + tcp_offset, + resolve_tool_tcp_spec(config).tcp_offset_mm_deg, + mode=args.mode, + ) transport = XArmTransport(arm, robot_key=config.robot.key, serial_number=serial, tcp_offset=tcp_offset) shadow = None stages = None @@ -661,7 +785,14 @@ def main(argv: Sequence[str] | None = None) -> int: if args.executor == "servo_cartesian" or args.mode == "sdk-sim": if shadow is None or stages is None: shadow, stages = gate.shadow_joint_stream(program) - firmware = _sdk_sim_feedback(arm, program, config, start_q, tcp_offset=tcp_offset) + firmware = _sdk_sim_feedback( + arm, + program, + config, + start_q, + tcp_offset=tcp_offset, + allow_approx_motion=config.motion.allow_approx_motion, + ) evidence = validate_sdk_simulation( robot_key=config.robot.key, serial_number=serial, @@ -674,6 +805,8 @@ def main(argv: Sequence[str] | None = None) -> int: kinematics=kinematics, collision=collision, allowed_collision=gate.collision_allowed, + joint_lower_rad=gate.joint_lower_rad, + joint_upper_rad=gate.joint_upper_rad, ) evidence_path = args.report or Path("reports") / f"sdk_sim_{config.robot.key}.json" _write_json(evidence_path, asdict(evidence)) @@ -716,26 +849,39 @@ def main(argv: Sequence[str] | None = None) -> int: if genesis_for_ik is None: genesis_for_ik = GenesisRuntimeManager(config.simulation) genesis_for_ik.__enter__() - mirror_ctx = _build_ik_scene(config, calibration=args.calibration, show_viewer=False) + mirror_ctx = _build_ik_scene( + config, + calibration=args.calibration, + show_viewer=False, + arm_controller=kinematics, + ) + attach_dist_m = _mirror_attach_dist_m(config) + carry_note = ( + "empty grasp; cube not carried" + if attach_dist_m == 0.0 + else "cube kinematically carried while gripped" + ) base_mm = [v * 1000.0 for v in mirror_ctx.base_pos_world] print( f"\n[mirror] robot={mirror_ctx.robot_key} gripper={mirror_ctx.gripper.family} " f"rate={config.motion.rate_hz}Hz visual_model={mirror_ctx.visual_model} " f"base=[{base_mm[0]:.0f},{base_mm[1]:.0f},{base_mm[2]:.0f}]mm " - f"kinematic open-loop; cube kinematically carried while gripped " + f"kinematic open-loop; {carry_note} " f"(no contact physics; async mirror off servo critical path)" ) mirror = TrajKinematicMirror(mirror_ctx, approved.program) mirror.prime_to_home() start_deferred_viewer(mirror_ctx.scene, kinematic_mirror=True) _hold_mirror_at_program_start(mirror, hold_s=args.visual_start_hold_s) - tracker = KinematicCarryTracker( - mirror, - grasp_gap_m=_close_gap_m(config), - grasp_segment_label="grip", - release_segment_label="release", - approach_freeze_labels=("descend",), - ) + tracker_kwargs: dict[str, Any] = { + "grasp_gap_m": _close_gap_m(config), + "grasp_segment_label": "grip", + "release_segment_label": "release", + "approach_freeze_labels": ("descend",), + } + if attach_dist_m is not None: + tracker_kwargs["attach_dist_m"] = attach_dist_m + tracker = KinematicCarryTracker(mirror, **tracker_kwargs) _warm_real_visual_tracker(tracker) bridge = AsyncMirrorBridge(tracker) @@ -743,29 +889,49 @@ def main(argv: Sequence[str] | None = None) -> int: prime_first_movej_sample(transport, approved.program, executor=args.executor) if mirror is not None: mirror.prime_to_first_arm_segment_start(approved.program) - current_drive, gripper_sender = prepare_real_gripper_sender(arm, transport, config.gripper) - execution = execute_real( - approved, - transport=transport, - bindings=ExecutionBindings( - robot_key=config.robot.key, - serial_number=serial, - config_sha256=config.sha256, - urdf_sha256=urdf_hash, - calibration_sha256=calibration_hash, - scene_sha256=scene_hash, - ), - confirm_real=True, - runtime_monitor=lambda q, stage: gate.runtime_monitor( - q, - stage, - gripper_drive=current_drive[0], - include_collision=False, - ), - gripper_sender=gripper_sender, - on_tick=bridge.on_tick if bridge is not None else None, - not_ready_codes=frozenset((9,)), + current_drive, gripper_sender = prepare_real_gripper_sender( + arm, + transport, + config.gripper, + hardware_version=int(args.vacuum_hardware_version), + ) + switch_ctx = ( + kinematics.sync_hardware_switches(arm) + if args.executor == "servo_cartesian" + and callable(getattr(kinematics, "sync_hardware_switches", None)) + and callable(getattr(arm, "set_allow_approx_motion", None)) + else nullcontext() ) + try: + with switch_ctx: + execution = execute_real( + approved, + transport=transport, + bindings=ExecutionBindings( + robot_key=config.robot.key, + serial_number=serial, + config_sha256=config.sha256, + urdf_sha256=urdf_hash, + calibration_sha256=calibration_hash, + scene_sha256=scene_hash, + ), + confirm_real=True, + runtime_monitor=lambda q, stage: gate.runtime_monitor( + q, + stage, + gripper_drive=current_drive[0], + include_collision=False, + ), + gripper_sender=gripper_sender, + on_tick=bridge.on_tick if bridge is not None else None, + not_ready_codes=frozenset((9,)), + ) + finally: + shutdown_real_gripper( + arm, + config.gripper, + hardware_version=int(args.vacuum_hardware_version), + ) print_real_execution_summary(execution) if args.visual and mirror_ctx is not None and tracker is not None: _hold_viewer(mirror_ctx, on_step=tracker.hold_step) diff --git a/ufactory/config/loader.py b/ufactory/config/loader.py index 706ae1f..7495d13 100644 --- a/ufactory/config/loader.py +++ b/ufactory/config/loader.py @@ -162,6 +162,7 @@ def _build_resolved(data: dict[str, Any], sources: tuple[str, ...]) -> ResolvedR geometry_pairs = gripper_data.get("excluded_geometry_pairs", []) if not isinstance(geometry_pairs, list) or any(not isinstance(pair, list | tuple) for pair in geometry_pairs): raise ConfigError("gripper.excluded_geometry_pairs must be a list of geometry pairs") + tcp_offset_raw = _tuple_floats(gripper_data["tcp_offset"], field="gripper.tcp_offset", size=6) gripper = GripperProfile( adapter=str(gripper_data["adapter"]), drive_joint=str(gripper_data["drive_joint"]), @@ -187,6 +188,14 @@ def _build_resolved(data: dict[str, Any], sources: tuple[str, ...]) -> ResolvedR grasp_table_clearance_m=float(gripper_data["grasp_table_clearance_m"]), grasp_height_extra_m=float(gripper_data["grasp_height_extra_m"]), excluded_geometry_pairs=tuple(tuple(pair) for pair in geometry_pairs), + tcp_offset=( + tcp_offset_raw[0], + tcp_offset_raw[1], + tcp_offset_raw[2], + tcp_offset_raw[3], + tcp_offset_raw[4], + tcp_offset_raw[5], + ), ) task_parameters = task_data["parameters"] if not isinstance(task_parameters, Mapping): @@ -343,6 +352,9 @@ def require_on_table(name: str, center_x: float, center_y: float, size_x: float, allowed_contacts=task_data["allowed_contacts"], ) motion_data = data["motion"] + raw_allow_approx = motion_data.get("allow_approx_motion", False) + if not isinstance(raw_allow_approx, bool): + raise ConfigError("motion.allow_approx_motion must be a boolean") motion = MotionConfig( rate_hz=_positive(motion_data["rate_hz"], field="motion.rate_hz"), joint_speed_rad_s=_positive(motion_data["joint_speed_rad_s"], field="motion.joint_speed_rad_s"), @@ -354,8 +366,13 @@ def require_on_table(name: str, center_x: float, center_y: float, size_x: float, motion_data["cartesian_acceleration_m_s2"], field="motion.cartesian_acceleration_m_s2" ), gripper_duration_s=_positive(motion_data["gripper_duration_s"], field="motion.gripper_duration_s"), + allow_approx_motion=raw_allow_approx, ) simulation_data = data["simulation"] + raw_sim_rate = simulation_data.get("rate_hz", 50.0) + if isinstance(raw_sim_rate, bool): + raise ConfigError("simulation.rate_hz must be finite and positive") + simulation_rate_hz = _positive(raw_sim_rate, field="simulation.rate_hz") raw_simulation_substeps = simulation_data["substeps"] if isinstance(raw_simulation_substeps, bool) or not isinstance(raw_simulation_substeps, int): raise ConfigError("simulation.substeps must be a positive integer") @@ -382,6 +399,7 @@ def require_on_table(name: str, center_x: float, center_y: float, size_x: float, show_viewer=bool(simulation_data.get("show_viewer", False)), g2=G2SimulationConfig(**simulation_data["g2"]), robotiq=RobotiqSimulationConfig(**simulation_data["robotiq"]), + rate_hz=simulation_rate_hz, ) if gripper is not None and gripper.adapter in {"robotiq_2f_85", "robotiq_2f_140"}: max_gap_mm = gripper.open_gap_m * 1000.0 @@ -487,6 +505,22 @@ def load_runtime_config( elif normalized_gripper == "lite6": if default_adapter != "lite6": raise ConfigError(f"robot {canonical} does not support gripper {normalized_gripper}") + elif normalized_gripper in {"bio_gripper_g2", "bio_g2"}: + try: + validate_assembly(canonical, "bio_gripper_g2", root=store.root) + except AssemblyError as exc: + raise ConfigError(str(exc)) from exc + overlay_rel = "assets/configs/runtime/grippers/bio_gripper_g2.yaml" + _merge_strict(data, _read_yaml(store.require(overlay_rel))) + sources.append(overlay_rel) + elif normalized_gripper == "vacuum_gripper": + try: + validate_assembly(canonical, "vacuum_gripper", root=store.root) + except AssemblyError as exc: + raise ConfigError(str(exc)) from exc + overlay_rel = "assets/configs/runtime/grippers/vacuum_gripper.yaml" + _merge_strict(data, _read_yaml(store.require(overlay_rel))) + sources.append(overlay_rel) elif normalized_gripper in {"robotiq_2f_85", "robotiq_2f_140"}: try: validate_assembly(canonical, normalized_gripper, root=store.root) diff --git a/ufactory/config/models.py b/ufactory/config/models.py index 116ba14..c712934 100644 --- a/ufactory/config/models.py +++ b/ufactory/config/models.py @@ -11,6 +11,7 @@ FloatTuple = tuple[float, ...] +TcpOffsetTuple = tuple[float, float, float, float, float, float] G2_PHYSICS_PROFILE = "g2_calibrated_v1" ROBOTIQ_2F_85_PHYSICS_PROFILE = "robotiq_2f_85_calibrated_v1" ROBOTIQ_2F_140_PHYSICS_PROFILE = "robotiq_2f_140_calibrated_v1" @@ -111,10 +112,24 @@ class GripperProfile: grasp_height_extra_m: float # URDF collision geometries (``_``) whose mutual contact Genesis physics ignores. excluded_geometry_pairs: tuple[tuple[str, str], ...] = () + # Flange-to-TCP 6D offset [x_mm, y_mm, z_mm, roll_deg, pitch_deg, yaw_deg] + # matching xarm-python-sdk default (is_radian=False) and UFACTORY Studio. + tcp_offset: TcpOffsetTuple = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + @property + def has_actuated_joints(self) -> bool: + return bool(self.drive_joint and self.all_joint_names) def __post_init__(self) -> None: - if not self.adapter or not self.drive_joint: + if not self.adapter: + raise ValueError("gripper adapter is required") + is_zero_dof = not self.drive_joint and not self.all_joint_names + if not is_zero_dof and not self.drive_joint: raise ValueError("gripper adapter and drive joint are required") + tcp = tuple(float(value) for value in self.tcp_offset) + if len(tcp) != 6 or not all(math.isfinite(value) for value in tcp): + raise ValueError("gripper tcp_offset must contain 6 finite values [x_mm, y_mm, z_mm, r_deg, p_deg, y_deg]") + object.__setattr__(self, "tcp_offset", (tcp[0], tcp[1], tcp[2], tcp[3], tcp[4], tcp[5])) pairs = self.excluded_geometry_pairs if any( len(pair) != 2 or any(not isinstance(name, str) or not name.strip() for name in pair) or pair[0] == pair[1] @@ -124,14 +139,22 @@ def __post_init__(self) -> None: if len({frozenset(pair) for pair in pairs}) != len(pairs): raise ValueError("excluded_geometry_pairs cannot contain duplicate pairs") object.__setattr__(self, "excluded_geometry_pairs", tuple(tuple(pair) for pair in pairs)) - if self.open_gap_m <= self.closed_gap_m: - raise ValueError("gripper open_gap_m must be greater than closed_gap_m") if not self.closed_gap_m >= 0.0: raise ValueError("gripper gaps cannot be negative") - if self.force_lower_n >= self.force_upper_n: - raise ValueError("gripper force_lower_n must be below force_upper_n") - if self.tool_tip_offset_z_m <= 0.0: - raise ValueError("gripper tool_tip_offset_z_m must be positive") + if is_zero_dof: + if self.open_gap_m < self.closed_gap_m: + raise ValueError("gripper open_gap_m cannot be below closed_gap_m") + if self.force_lower_n > self.force_upper_n: + raise ValueError("gripper force_lower_n cannot exceed force_upper_n") + if not math.isfinite(float(self.tool_tip_offset_z_m)) or self.tool_tip_offset_z_m < 0.0: + raise ValueError("gripper tool_tip_offset_z_m must be finite and non-negative") + else: + if self.open_gap_m <= self.closed_gap_m: + raise ValueError("gripper open_gap_m must be greater than closed_gap_m") + if self.force_lower_n >= self.force_upper_n: + raise ValueError("gripper force_lower_n must be below force_upper_n") + if self.tool_tip_offset_z_m <= 0.0: + raise ValueError("gripper tool_tip_offset_z_m must be positive") for name in ( "finger_pad_below_center_m", "finger_close_descent_m", @@ -214,6 +237,11 @@ class MotionConfig: cartesian_speed_m_s: float cartesian_acceleration_m_s2: float gripper_duration_s: float + allow_approx_motion: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.allow_approx_motion, bool): + raise ValueError("motion.allow_approx_motion must be a boolean") @dataclass(frozen=True) @@ -294,12 +322,15 @@ class SimulationConfig: show_viewer: bool g2: G2SimulationConfig = G2SimulationConfig() robotiq: RobotiqSimulationConfig = RobotiqSimulationConfig() + rate_hz: float = 50.0 def __post_init__(self) -> None: if self.backend not in {"cpu", "gpu"}: raise ValueError("simulation backend must be cpu or gpu") if self.precision not in {"32", "64"}: raise ValueError("simulation precision must be 32 or 64") + if isinstance(self.rate_hz, bool) or not math.isfinite(float(self.rate_hz)) or float(self.rate_hz) <= 0.0: + raise ValueError("simulation rate_hz must be finite and positive") if self.substeps < 1 or self.solver_iterations < 1 or self.noslip_iterations < 0: raise ValueError("simulation iteration counts are invalid") if self.constraint_time_constant_s <= 0.0: diff --git a/ufactory/control/__init__.py b/ufactory/control/__init__.py new file mode 100644 index 0000000..4f9a352 --- /dev/null +++ b/ufactory/control/__init__.py @@ -0,0 +1,71 @@ +"""Pure-NumPy unified motion controller for all 5 UFACTORY robotic arms.""" + +from ufactory.control.arm_controller import ( + DEFAULT_CONTROL_RATE_HZ, + DEFAULT_SERVO_RATE_HZ, + ERROR_IK_FAILED, + ERROR_INVALID_ARG, + ERROR_INVALID_MODE, + ERROR_NONE, + ERROR_OVERSPEED, + MAX_SERVO_RATE_HZ, + MIN_SERVO_RATE_HZ, + MODE_POSITION, + MODE_SERVO, + STATE_PAUSE, + STATE_READY, + STATE_STOP, + ArmMotionController, + PlannedMotion, +) +from ufactory.control.kinematics_chain import ( + CalibratedKinematicsChain, + pose_to_se3, + quat_xyzw_to_rotation, + rotation_to_quat_xyzw, + se3_to_pose_m_quat, + se3_to_pose_mm_rpy, + slerp_rotation, + so3_log, +) +from ufactory.control.solvers import ( + SPHERICAL_WRIST_ROBOTS, + ApproxMotionConfig, + IKStepResult, + solve_cartesian_step, + solve_exact_ik, + solve_spherical_wrist_analytical, +) + +__all__ = [ + "ArmMotionController", + "ApproxMotionConfig", + "CalibratedKinematicsChain", + "IKStepResult", + "PlannedMotion", + "DEFAULT_CONTROL_RATE_HZ", + "DEFAULT_SERVO_RATE_HZ", + "MIN_SERVO_RATE_HZ", + "MAX_SERVO_RATE_HZ", + "MODE_POSITION", + "MODE_SERVO", + "STATE_READY", + "STATE_PAUSE", + "STATE_STOP", + "ERROR_NONE", + "ERROR_IK_FAILED", + "ERROR_OVERSPEED", + "ERROR_INVALID_MODE", + "ERROR_INVALID_ARG", + "SPHERICAL_WRIST_ROBOTS", + "pose_to_se3", + "quat_xyzw_to_rotation", + "rotation_to_quat_xyzw", + "se3_to_pose_m_quat", + "se3_to_pose_mm_rpy", + "slerp_rotation", + "so3_log", + "solve_cartesian_step", + "solve_exact_ik", + "solve_spherical_wrist_analytical", +] diff --git a/ufactory/control/arm_controller.py b/ufactory/control/arm_controller.py new file mode 100644 index 0000000..d5132f7 --- /dev/null +++ b/ufactory/control/arm_controller.py @@ -0,0 +1,835 @@ +"""Unified hardware-parity virtual ArmMotionController (pure NumPy). + +Supports all 5 UFACTORY arms (xArm5 / xArm6 / xArm7 / UF850 / Lite6), per-unit +kinematics calibration, TCP offset, Mode 0 (default 250 Hz MoveJ/MoveL planning +via ``set_servo_angle`` / ``set_position``), Mode 1 (default 50 Hz, 30-250 Hz +configurable servo streaming via ``set_servo_angle_j`` / ``set_servo_cartesian``), +and xArm-SDK-compatible ``set_allow_approx_motion`` singularity avoidance. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from ufactory.config.assets import RepositoryAssetStore +from ufactory.control.kinematics_chain import ( + CalibratedKinematicsChain, + pose_to_se3, + slerp_rotation, + so3_log, +) +from ufactory.control.solvers import ( + ApproxMotionConfig, + IKStepResult, + solve_cartesian_step, + solve_exact_ik, +) +from ufactory.trajectory.profile import ( + _EPS, + _lspb_alpha_for_duration, + _lspb_displacement, + _sample_grid, + joint_lspb_samples, + lspb_duration, +) +from ufactory.types import FloatArray + +MODE_POSITION = 0 +MODE_SERVO = 1 + +STATE_READY = 0 +STATE_PAUSE = 3 +STATE_STOP = 4 + +# Controller error codes matching xArm firmware conventions +ERROR_NONE = 0 +ERROR_IK_FAILED = 21 +ERROR_OVERSPEED = 24 +ERROR_INVALID_MODE = -1 +ERROR_INVALID_ARG = -2 + +DEFAULT_CONTROL_RATE_HZ = 250.0 # Firmware Mode 0 internal interpolation rate (4 ms) +DEFAULT_SERVO_RATE_HZ = 50.0 # Default Mode 1 streaming rate (20 ms) +MIN_SERVO_RATE_HZ = 30.0 +MAX_SERVO_RATE_HZ = 250.0 + +# Official UFACTORY hardware joint velocity cap (~180 deg/s) +DEFAULT_HARDWARE_JOINT_SPEED_LIMIT_RAD_S = math.pi +DEFAULT_MOVEJ_SPEED_RAD_S = 1.0 +DEFAULT_MOVEJ_ACC_RAD_S2 = 10.0 +DEFAULT_MOVEL_SPEED_MM_S = 150.0 +DEFAULT_MOVEL_ACC_MM_S2 = 800.0 +DEFAULT_ROT_SPEED_RAD_S = 1.0 +DEFAULT_ROT_ACC_RAD_S2 = 5.0 + + +@dataclass(frozen=True) +class PlannedMotion: + """Deterministic trajectory generated by Mode 0 ``set_servo_angle`` / ``set_position``.""" + + kind: str # "movej" | "movel" + rate_hz: float + duration_s: float + q_samples: FloatArray # (N, dof) rad + timestamps_s: FloatArray # (N,) s + error_code: int = ERROR_NONE + used_approx_steps: int = 0 + max_position_error_m: float = 0.0 + max_orientation_error_rad: float = 0.0 + max_joint_speed_rad_s: float = 0.0 + message: str = "" + + +class ArmMotionController: + """Pure-NumPy motion controller mirroring UFACTORY firmware behavior across all 5 arms.""" + + def __init__( + self, + chain: CalibratedKinematicsChain, + *, + control_rate_hz: float = DEFAULT_CONTROL_RATE_HZ, + servo_rate_hz: float = DEFAULT_SERVO_RATE_HZ, + allow_approx_motion: bool = False, + approx_config: ApproxMotionConfig | None = None, + joint_speed_limit_rad_s: float = DEFAULT_HARDWARE_JOINT_SPEED_LIMIT_RAD_S, + initial_q_rad: Sequence[float] | FloatArray | None = None, + hardware_arm: Any | None = None, + ) -> None: + if not math.isfinite(control_rate_hz) or control_rate_hz <= 0.0: + raise ValueError("control_rate_hz must be finite and positive") + if not math.isfinite(servo_rate_hz) or not (MIN_SERVO_RATE_HZ <= servo_rate_hz <= MAX_SERVO_RATE_HZ): + raise ValueError(f"servo_rate_hz must lie in [{MIN_SERVO_RATE_HZ}, {MAX_SERVO_RATE_HZ}] Hz") + if not isinstance(allow_approx_motion, bool): + raise TypeError("allow_approx_motion must be a bool") + if not math.isfinite(joint_speed_limit_rad_s) or joint_speed_limit_rad_s <= 0.0: + raise ValueError("joint_speed_limit_rad_s must be finite and positive") + + self._chain = chain + self._control_rate_hz = float(control_rate_hz) + self._servo_rate_hz = float(servo_rate_hz) + self._allow_approx_motion = bool(allow_approx_motion) + self._approx_config = approx_config or ApproxMotionConfig() + self._joint_speed_limit_rad_s = float(joint_speed_limit_rad_s) + self._hardware_arm = hardware_arm + + self._mode: int = MODE_POSITION + self._state: int = STATE_READY + self._error_code: int = ERROR_NONE + self._q_rad: FloatArray = ( + np.zeros(chain.dof, dtype=np.float64) if initial_q_rad is None else chain.validate_q(initial_q_rad).copy() + ) + self._last_motion: PlannedMotion | None = None + self._last_step: IKStepResult | None = None + + @classmethod + def from_robot( + cls, + robot_key: str, + *, + urdf_path: str | Path | None = None, + calibration_path: str | Path | None = None, + serial_number: str | None = None, + tcp_offset_mm_rpy: Sequence[float] | FloatArray | None = None, + control_rate_hz: float = DEFAULT_CONTROL_RATE_HZ, + servo_rate_hz: float = DEFAULT_SERVO_RATE_HZ, + allow_approx_motion: bool = False, + approx_config: ApproxMotionConfig | None = None, + joint_speed_limit_rad_s: float = DEFAULT_HARDWARE_JOINT_SPEED_LIMIT_RAD_S, + initial_q_rad: Sequence[float] | FloatArray | None = None, + hardware_arm: Any | None = None, + asset_store: RepositoryAssetStore | None = None, + ) -> ArmMotionController: + """Instantiate a controller for any of the 5 UFACTORY arms with optional calibration.""" + + chain = CalibratedKinematicsChain.from_robot( + robot_key, + urdf_path=urdf_path, + calibration_path=calibration_path, + serial_number=serial_number, + tcp_offset_mm_rpy=tcp_offset_mm_rpy, + asset_store=asset_store, + ) + return cls( + chain, + control_rate_hz=control_rate_hz, + servo_rate_hz=servo_rate_hz, + allow_approx_motion=allow_approx_motion, + approx_config=approx_config, + joint_speed_limit_rad_s=joint_speed_limit_rad_s, + initial_q_rad=initial_q_rad, + hardware_arm=hardware_arm, + ) + + # ------------------------------------------------------------------ properties + + @property + def chain(self) -> CalibratedKinematicsChain: + return self._chain + + @property + def robot_key(self) -> str: + return self._chain.robot_key + + @property + def dof(self) -> int: + return self._chain.dof + + @property + def control_rate_hz(self) -> float: + return self._control_rate_hz + + @property + def servo_rate_hz(self) -> float: + return self._servo_rate_hz + + @property + def mode(self) -> int: + return self._mode + + @property + def state(self) -> int: + return self._state + + @property + def error_code(self) -> int: + return self._error_code + + @property + def is_approx_motion(self) -> bool: + """Mirror ``XArmAPI.is_approx_motion``.""" + + return self._allow_approx_motion + + @property + def tcp_offset(self) -> FloatArray: + return self._chain.tcp_offset_mm_rpy.copy() + + @property + def last_motion(self) -> PlannedMotion | None: + return self._last_motion + + @property + def last_step(self) -> IKStepResult | None: + return self._last_step + + @property + def approx_config(self) -> ApproxMotionConfig: + return self._approx_config + + # ------------------------------------------------------------------ xArm-SDK-compatible configuration & state + + def set_mode(self, mode: int) -> int: + if isinstance(mode, bool) or int(mode) not in (MODE_POSITION, MODE_SERVO): + return ERROR_INVALID_MODE + self._mode = int(mode) + if self._hardware_arm is not None: + return int(self._hardware_arm.set_mode(self._mode)) + return ERROR_NONE + + def set_state(self, state: int) -> int: + if isinstance(state, bool) or int(state) not in (STATE_READY, STATE_PAUSE, STATE_STOP): + return ERROR_INVALID_ARG + self._state = int(state) + if self._hardware_arm is not None: + return int(self._hardware_arm.set_state(self._state)) + return ERROR_NONE + + def clean_error(self) -> int: + self._error_code = ERROR_NONE + if self._state == STATE_STOP: + self._state = STATE_READY + if self._hardware_arm is not None: + return int(self._hardware_arm.clean_error()) + return ERROR_NONE + + def set_allow_approx_motion(self, on_off: bool) -> int: + """Enable/disable singularity approximate DLS motion (mirrors ``XArmAPI.set_allow_approx_motion``).""" + + if not isinstance(on_off, bool): + raise TypeError("on_off must be a bool") + self._allow_approx_motion = bool(on_off) + if self._hardware_arm is not None: + return int(self._hardware_arm.set_allow_approx_motion(self._allow_approx_motion)) + return ERROR_NONE + + def get_allow_approx_motion(self) -> tuple[int, int]: + """Return ``(0, 1 if enabled else 0)`` matching ``XArmAPI.get_allow_approx_motion``.""" + + return (ERROR_NONE, 1 if self._allow_approx_motion else 0) + + def set_tcp_offset(self, offset: Sequence[float] | FloatArray, *, is_radian: bool = True) -> int: + """Set tool-center-point offset ``[x_mm, y_mm, z_mm, roll, pitch, yaw]``.""" + + arr: FloatArray = np.asarray(offset, dtype=np.float64).reshape(-1) + if arr.shape != (6,) or not np.all(np.isfinite(arr)): + return ERROR_INVALID_ARG + offset_rad = arr.copy() + if not is_radian: + offset_rad[3:] = np.deg2rad(offset_rad[3:]) + self._chain = self._chain.with_tcp_offset(offset_rad) + if self._hardware_arm is not None: + return int(self._hardware_arm.set_tcp_offset(offset_rad.tolist(), is_radian=True)) + return ERROR_NONE + + def set_control_rate(self, rate_hz: float) -> None: + if not math.isfinite(rate_hz) or rate_hz <= 0.0: + raise ValueError("control_rate_hz must be finite and positive") + self._control_rate_hz = float(rate_hz) + + def set_servo_rate(self, rate_hz: float) -> None: + if not math.isfinite(rate_hz) or not (MIN_SERVO_RATE_HZ <= rate_hz <= MAX_SERVO_RATE_HZ): + raise ValueError(f"servo_rate_hz must lie in [{MIN_SERVO_RATE_HZ}, {MAX_SERVO_RATE_HZ}] Hz") + self._servo_rate_hz = float(rate_hz) + + def reset_state(self, q_rad: Sequence[float] | FloatArray) -> None: + """Set virtual joint state without moving hardware.""" + + self._q_rad = self._chain.validate_q(q_rad).copy() + self._error_code = ERROR_NONE + self._state = STATE_READY + + def get_servo_angle(self, *, is_radian: bool = True) -> tuple[int, list[float]]: + """Return ``(0, angles)`` matching ``XArmAPI.get_servo_angle``.""" + + angles = self._q_rad if is_radian else np.rad2deg(self._q_rad) + return (ERROR_NONE, [float(v) for v in angles]) + + def get_position(self, *, is_radian: bool = True) -> tuple[int, list[float]]: + """Return ``(0, [x_mm, y_mm, z_mm, roll, pitch, yaw])`` matching ``XArmAPI.get_position``.""" + + pose = self._chain.forward_pose_mm_rpy(self._q_rad, include_tcp=True) + if not is_radian: + pose[3:] = np.rad2deg(pose[3:]) + return (ERROR_NONE, [float(v) for v in pose]) + + # ------------------------------------------------------------------ FK / IK queries (SDK-compatible) + + def get_forward_kinematics( + self, + angles: Sequence[float] | FloatArray, + *, + input_is_radian: bool = True, + return_is_radian: bool = True, + ) -> tuple[int, list[float]]: + """Compute TCP pose ``[x_mm, y_mm, z_mm, roll, pitch, yaw]`` from joint angles.""" + + try: + q: FloatArray = np.asarray(angles, dtype=np.float64).reshape(-1)[: self.dof] + if not input_is_radian: + q = np.deg2rad(q) + pose = self._chain.forward_pose_mm_rpy(q, include_tcp=True) + if not return_is_radian: + pose[3:] = np.rad2deg(pose[3:]) + return (ERROR_NONE, [float(v) for v in pose]) + except ValueError: + return (ERROR_INVALID_ARG, []) + + def get_inverse_kinematics( + self, + pose: Sequence[float] | FloatArray, + *, + input_is_radian: bool = True, + return_is_radian: bool = True, + seed_q: Sequence[float] | FloatArray | None = None, + ) -> tuple[int, list[float]]: + """Solve exact IK for TCP pose ``[x_mm, y_mm, z_mm, roll, pitch, yaw]``.""" + + try: + pose_arr: FloatArray = np.asarray(pose, dtype=np.float64).reshape(-1) + if pose_arr.shape != (6,) or not np.all(np.isfinite(pose_arr)): + return (ERROR_INVALID_ARG, []) + pose_rad = pose_arr.copy() + if not input_is_radian: + pose_rad[3:] = np.deg2rad(pose_rad[3:]) + target_se3 = pose_to_se3(pose_rad, position_in_mm=True) + seed = self._q_rad if seed_q is None else self._chain.validate_q(seed_q) + res = solve_exact_ik( + self._chain, + target_se3, + seed, + include_tcp=True, + cold_start_fallback=True, + ) + out = res.q_rad if return_is_radian else np.rad2deg(res.q_rad) + return (ERROR_NONE, [float(v) for v in out]) + except ValueError: + return (ERROR_IK_FAILED, []) + + # ------------------------------------------------------------------ Mode 0 planning & execution (default 250 Hz) + + def plan_move_j( + self, + target_q_rad: Sequence[float] | FloatArray, + *, + start_q_rad: Sequence[float] | FloatArray | None = None, + speed_rad_s: float = DEFAULT_MOVEJ_SPEED_RAD_S, + acc_rad_s2: float = DEFAULT_MOVEJ_ACC_RAD_S2, + rate_hz: float | None = None, + ) -> PlannedMotion: + """Plan a 250 Hz (default) synchronized LSPB MoveJ trajectory.""" + + q0 = self._q_rad.copy() if start_q_rad is None else self._chain.validate_q(start_q_rad) + q1 = self._chain.validate_q(target_q_rad) + if np.any(q1 < self._chain.lower - 1e-7) or np.any(q1 > self._chain.upper + 1e-7): + return PlannedMotion( + kind="movej", + rate_hz=float(self._control_rate_hz if rate_hz is None else rate_hz), + duration_s=0.0, + q_samples=q0.reshape(1, -1), + timestamps_s=np.zeros(1, dtype=np.float64), + error_code=ERROR_INVALID_ARG, + message="MoveJ target exceeds joint limits", + ) + rate = self._control_rate_hz if rate_hz is None else float(rate_hz) + samples, n, dur = joint_lspb_samples(q0, q1, rate=rate, v_max=float(speed_rad_s), a_max=float(acc_rad_s2)) + ts = np.arange(1, n + 1, dtype=np.float64) / rate + full = np.vstack((q0[None, :], samples)) + max_vj = float(np.max(np.abs(np.diff(full, axis=0)) * rate, initial=0.0)) + return PlannedMotion( + kind="movej", + rate_hz=rate, + duration_s=dur, + q_samples=samples, + timestamps_s=ts, + error_code=ERROR_NONE, + max_joint_speed_rad_s=max_vj, + ) + + def set_servo_angle( + self, + angle: Sequence[float] | FloatArray, + *, + speed: float | None = None, + mvacc: float | None = None, + is_radian: bool = True, + wait: bool = False, + ) -> int: + """Mode 0 joint move (mirrors ``XArmAPI.set_servo_angle``) using ``control_rate_hz`` (250 Hz default).""" + + if self._mode != MODE_POSITION or self._state != STATE_READY or self._error_code != ERROR_NONE: + return ERROR_INVALID_MODE + raw: FloatArray = np.asarray(angle, dtype=np.float64).reshape(-1) + if raw.shape != (self.dof,) or not np.all(np.isfinite(raw)): + return ERROR_INVALID_ARG + target_rad = raw if is_radian else np.deg2rad(raw) + spd = ( + DEFAULT_MOVEJ_SPEED_RAD_S if speed is None else (float(speed) if is_radian else math.radians(float(speed))) + ) + acc = DEFAULT_MOVEJ_ACC_RAD_S2 if mvacc is None else (float(mvacc) if is_radian else math.radians(float(mvacc))) + motion = self.plan_move_j(target_rad, speed_rad_s=spd, acc_rad_s2=acc) + self._last_motion = motion + if motion.error_code != ERROR_NONE: + self._error_code = motion.error_code + self._state = STATE_STOP + return motion.error_code + if self._hardware_arm is not None: + code = int( + self._hardware_arm.set_servo_angle( + angle=target_rad.tolist(), + speed=spd, + mvacc=acc, + is_radian=True, + wait=wait, + ) + ) + if code != 0: + return code + self._q_rad = motion.q_samples[-1].copy() + return ERROR_NONE + + def plan_move_l( + self, + target_pose_se3: FloatArray, + *, + start_q_rad: Sequence[float] | FloatArray | None = None, + speed_m_s: float = DEFAULT_MOVEL_SPEED_MM_S * 1e-3, + acc_m_s2: float = DEFAULT_MOVEL_ACC_MM_S2 * 1e-3, + rot_speed_rad_s: float = DEFAULT_ROT_SPEED_RAD_S, + rot_acc_rad_s2: float = DEFAULT_ROT_ACC_RAD_S2, + rate_hz: float | None = None, + motion_type: int = 0, + include_tcp: bool = True, + ) -> PlannedMotion: + """Plan a 250 Hz (default) Cartesian MoveL trajectory (LSPB xyz + SLERP rot + IK/DLS).""" + + q0 = self._q_rad.copy() if start_q_rad is None else self._chain.validate_q(start_q_rad) + rate = self._control_rate_hz if rate_hz is None else float(rate_hz) + dt = 1.0 / rate + target = np.asarray(target_pose_se3, dtype=np.float64).reshape(4, 4) + + if motion_type == 2: + # Direct transfer to IK using joint planning + try: + ik_end = solve_exact_ik(self._chain, target, q0, include_tcp=include_tcp, cold_start_fallback=True) + except ValueError as exc: + return PlannedMotion( + kind="movej", + rate_hz=rate, + duration_s=0.0, + q_samples=q0.reshape(1, -1), + timestamps_s=np.zeros(1, dtype=np.float64), + error_code=ERROR_IK_FAILED, + message=str(exc), + ) + return self.plan_move_j(ik_end.q_rad, start_q_rad=q0, rate_hz=rate) + + start_se3 = self._chain.forward_matrix(q0, include_tcp=include_tcp) + p0 = start_se3[:3, 3] + p1 = target[:3, 3] + r0 = start_se3[:3, :3] + r1 = target[:3, :3] + + lin_dist = float(np.linalg.norm(p1 - p0)) + rot_dist = float(np.linalg.norm(so3_log(r0.T @ r1))) + if lin_dist < _EPS and rot_dist < _EPS: + return PlannedMotion( + kind="movel", + rate_hz=rate, + duration_s=0.0, + q_samples=q0.reshape(1, -1), + timestamps_s=np.zeros(1, dtype=np.float64), + error_code=ERROR_NONE, + ) + + dur_lin = lspb_duration(lin_dist, speed_m_s, acc_m_s2) if lin_dist >= _EPS else 0.0 + dur_rot = lspb_duration(rot_dist, rot_speed_rad_s, rot_acc_rad_s2) if rot_dist >= _EPS else 0.0 + duration = max(dur_lin, dur_rot) + if duration <= _EPS: + duration = max(_EPS, lin_dist / max(speed_m_s, _EPS), rot_dist / max(rot_speed_rad_s, _EPS)) + n = max(1, int(math.ceil(duration * rate - _EPS))) + duration = float(n) / rate + u = _sample_grid(n) + + if lin_dist >= _EPS: + alpha_lin = _lspb_alpha_for_duration(lin_dist, speed_m_s, acc_m_s2, duration) + s_lin = _lspb_displacement(u, lin_dist, alpha_lin) / lin_dist + else: + s_lin = u + if rot_dist >= _EPS: + alpha_rot = _lspb_alpha_for_duration(rot_dist, rot_speed_rad_s, rot_acc_rad_s2, duration) + s_rot = _lspb_displacement(u, rot_dist, alpha_rot) / rot_dist + else: + s_rot = u + + # Mode 0 approximate-motion trigger mirrors firmware: once joint speed + # would exceed joint_speed_limit_rad_s (C24), switch to 250 Hz native + # [mm, rad] DLS for the remainder of the segment (or Chiaverini smooth + # ramp if configured). + mode0_approx_cfg = ApproxMotionConfig( + damping=self._approx_config.damping, + singular_value_threshold=self._approx_config.singular_value_threshold, + trigger_joint_speed_rad_s=( + self._approx_config.trigger_joint_speed_rad_s + if self._approx_config.trigger_joint_speed_rad_s is not None + else self._joint_speed_limit_rad_s + ), + max_position_error_m=self._approx_config.max_position_error_m, + max_orientation_error_rad=self._approx_config.max_orientation_error_rad, + position_unit_scale=self._approx_config.position_unit_scale, + ) + + q_rows: list[FloatArray] = [] + cur_q = q0.copy() + approx_steps = 0 + max_pos_err = 0.0 + max_rot_err = 0.0 + max_vj = 0.0 + segment_in_approx = False + err_code = ERROR_NONE + err_msg = "" + + for k in range(n): + pose_k: FloatArray = np.eye(4, dtype=np.float64) + pose_k[:3, 3] = p0 + float(s_lin[k]) * (p1 - p0) + pose_k[:3, :3] = slerp_rotation(r0, r1, float(s_rot[k])) + try: + step_res = solve_cartesian_step( + self._chain, + pose_k, + cur_q, + allow_approx_motion=self._allow_approx_motion, + approx_config=mode0_approx_cfg, + dt_s=dt, + include_tcp=include_tcp, + force_approx=segment_in_approx, + ) + except ValueError as exc: + err_code = ERROR_IK_FAILED + err_msg = str(exc) + break + + step_speed = float(np.max(np.abs(step_res.q_rad - cur_q))) / dt + if not self._allow_approx_motion and step_speed > self._joint_speed_limit_rad_s: + err_code = ERROR_OVERSPEED + err_msg = ( + f"joint speed {step_speed:.3f} rad/s exceeds limit {self._joint_speed_limit_rad_s:.3f} rad/s " + f"at MoveL tick {k} (C24 overspeed)" + ) + break + + if step_res.used_approx: + approx_steps += 1 + if mode0_approx_cfg.singular_value_threshold == 0.0: + segment_in_approx = True + max_vj = max(max_vj, step_speed) + max_pos_err = max(max_pos_err, step_res.position_error_m) + max_rot_err = max(max_rot_err, step_res.orientation_error_rad) + cur_q = step_res.q_rad + q_rows.append(cur_q.copy()) + + if err_code != ERROR_NONE and motion_type == 1: + return self.plan_move_l( + target, + start_q_rad=q0, + rate_hz=rate, + motion_type=2, + include_tcp=include_tcp, + ) + + samples = np.stack(q_rows, axis=0) if q_rows else q0.reshape(1, -1) + ts = np.arange(1, len(samples) + 1, dtype=np.float64) / rate + return PlannedMotion( + kind="movel", + rate_hz=rate, + duration_s=float(len(samples)) / rate, + q_samples=samples, + timestamps_s=ts, + error_code=err_code, + used_approx_steps=approx_steps, + max_position_error_m=max_pos_err, + max_orientation_error_rad=max_rot_err, + max_joint_speed_rad_s=max_vj, + message=err_msg, + ) + + def set_position( + self, + x: float | None = None, + y: float | None = None, + z: float | None = None, + roll: float | None = None, + pitch: float | None = None, + yaw: float | None = None, + *, + speed: float | None = None, + mvacc: float | None = None, + is_radian: bool = True, + wait: bool = False, + motion_type: int = 0, + ) -> int: + """Mode 0 Cartesian MoveL (mirrors ``XArmAPI.set_position``) at ``control_rate_hz`` (250 Hz default).""" + + if self._mode != MODE_POSITION or self._state != STATE_READY or self._error_code != ERROR_NONE: + return ERROR_INVALID_MODE + if motion_type not in (0, 1, 2): + return ERROR_INVALID_ARG + + cur_pose = self._chain.forward_pose_mm_rpy(self._q_rad, include_tcp=True) + vals = [ + cur_pose[0] if x is None else float(x), + cur_pose[1] if y is None else float(y), + cur_pose[2] if z is None else float(z), + cur_pose[3] if roll is None else (float(roll) if is_radian else math.radians(float(roll))), + cur_pose[4] if pitch is None else (float(pitch) if is_radian else math.radians(float(pitch))), + cur_pose[5] if yaw is None else (float(yaw) if is_radian else math.radians(float(yaw))), + ] + if not all(math.isfinite(v) for v in vals): + return ERROR_INVALID_ARG + + spd_mm_s = DEFAULT_MOVEL_SPEED_MM_S if speed is None else float(speed) + acc_mm_s2 = DEFAULT_MOVEL_ACC_MM_S2 if mvacc is None else float(mvacc) + if spd_mm_s <= 0.0 or acc_mm_s2 <= 0.0: + return ERROR_INVALID_ARG + + target_se3 = pose_to_se3(vals, position_in_mm=True) + motion = self.plan_move_l( + target_se3, + speed_m_s=spd_mm_s * 1e-3, + acc_m_s2=acc_mm_s2 * 1e-3, + motion_type=motion_type, + include_tcp=True, + ) + self._last_motion = motion + if motion.error_code != ERROR_NONE: + self._q_rad = motion.q_samples[-1].copy() + self._error_code = motion.error_code + self._state = STATE_STOP + return motion.error_code + + if self._hardware_arm is not None: + code = int( + self._hardware_arm.set_position( + x=vals[0], + y=vals[1], + z=vals[2], + roll=vals[3], + pitch=vals[4], + yaw=vals[5], + speed=spd_mm_s, + mvacc=acc_mm_s2, + is_radian=True, + wait=wait, + motion_type=motion_type, + ) + ) + if code != 0: + return code + + self._q_rad = motion.q_samples[-1].copy() + return ERROR_NONE + + # ------------------------------------------------------------------ Mode 1 servo streaming (30-250 Hz, default 50 Hz) + + def set_servo_angle_j(self, angles: Sequence[float] | FloatArray, *, is_radian: bool = True) -> int: + """Mode 1 single-tick joint servo command (mirrors ``XArmAPI.set_servo_angle_j``).""" + + if self._mode != MODE_SERVO or self._state != STATE_READY or self._error_code != ERROR_NONE: + return ERROR_INVALID_MODE + raw: FloatArray = np.asarray(angles, dtype=np.float64).reshape(-1) + if raw.shape != (self.dof,) or not np.all(np.isfinite(raw)): + return ERROR_INVALID_ARG + q_target = raw if is_radian else np.deg2rad(raw) + if np.any(q_target < self._chain.lower - 1e-7) or np.any(q_target > self._chain.upper + 1e-7): + self._error_code = ERROR_INVALID_ARG + self._state = STATE_STOP + return ERROR_INVALID_ARG + if self._hardware_arm is not None: + code = int(self._hardware_arm.set_servo_angle_j(angles=q_target.tolist(), is_radian=True)) + if code != 0: + return code + self._q_rad = q_target.copy() + return ERROR_NONE + + def set_servo_cartesian( + self, + mvpose: Sequence[float] | FloatArray, + *, + is_radian: bool = True, + dt_s: float | None = None, + ) -> int: + """Mode 1 single-tick Cartesian servo command (mirrors ``XArmAPI.set_servo_cartesian``).""" + + if self._mode != MODE_SERVO or self._state != STATE_READY or self._error_code != ERROR_NONE: + return ERROR_INVALID_MODE + raw: FloatArray = np.asarray(mvpose, dtype=np.float64).reshape(-1) + if raw.shape != (6,) or not np.all(np.isfinite(raw)): + return ERROR_INVALID_ARG + pose_rad = raw.copy() + if not is_radian: + pose_rad[3:] = np.deg2rad(pose_rad[3:]) + target_se3 = pose_to_se3(pose_rad, position_in_mm=True) + step_dt = (1.0 / self._servo_rate_hz) if dt_s is None else float(dt_s) + try: + res = solve_cartesian_step( + self._chain, + target_se3, + self._q_rad, + allow_approx_motion=self._allow_approx_motion, + approx_config=self._approx_config, + dt_s=step_dt, + include_tcp=True, + ) + except ValueError: + self._error_code = ERROR_IK_FAILED + self._state = STATE_STOP + return ERROR_IK_FAILED + self._last_step = res + if self._hardware_arm is not None: + code = int(self._hardware_arm.set_servo_cartesian(mvpose=pose_rad.tolist(), is_radian=True)) + if code != 0: + return code + self._q_rad = res.q_rad.copy() + return ERROR_NONE + + # ------------------------------------------------------------------ Domain / SafetyGate protocol methods (metres, flange) + + def forward(self, q_rad: FloatArray) -> FloatArray: + """``KinematicsBackend.forward``: base-frame flange pose ``[x, y, z, qx, qy, qz, qw]`` (m).""" + + return self._chain.forward_pose_m_quat(q_rad, include_tcp=False) + + def jacobian(self, q_rad: FloatArray) -> FloatArray: + """``JacobianKinematicsBackend.jacobian``: 6xN spatial Jacobian ``[v_m; w_rad]`` at flange.""" + + return self._chain.jacobian(q_rad, include_tcp=False) + + def solve_step( + self, + target_pose: FloatArray, + seed_q_rad: FloatArray, + *, + dt_s: float | None = None, + include_tcp: bool = False, + ) -> IKStepResult: + """Solve one flange/TCP Cartesian step (accepts ``xyz+rpy`` len 6 or ``xyz+quat_xyzw`` len 7 in m).""" + + target_se3 = pose_to_se3(target_pose, position_in_mm=False) + step_dt = (1.0 / self._servo_rate_hz) if dt_s is None else float(dt_s) + res = solve_cartesian_step( + self._chain, + target_se3, + seed_q_rad, + allow_approx_motion=self._allow_approx_motion, + approx_config=self._approx_config, + dt_s=step_dt, + include_tcp=include_tcp, + ) + self._last_step = res + return res + + def inverse(self, pose: FloatArray, seed_q_rad: FloatArray) -> FloatArray: + """``KinematicsBackend.inverse``: solve flange ``xyz+quat_xyzw`` (or ``xyz+rpy``) in metres.""" + + return self.solve_step(pose, seed_q_rad, include_tcp=False).q_rad + + def solve_cartesian_segment( + self, + poses: FloatArray, + seed_q_rad: FloatArray, + *, + rate_hz: float | None = None, + include_tcp: bool = False, + ) -> tuple[FloatArray, tuple[IKStepResult, ...]]: + """Sequentially solve a stream of Cartesian poses (metres, len 6 or 7) preserving seed continuity.""" + + arr = np.asarray(poses, dtype=np.float64) + if arr.ndim != 2 or arr.shape[0] < 1 or arr.shape[1] not in (6, 7): + raise ValueError(f"poses must have shape (N, 6) or (N, 7), got {arr.shape}") + step_dt = 1.0 / (self._servo_rate_hz if rate_hz is None else float(rate_hz)) + cur_q = self._chain.validate_q(seed_q_rad).copy() + q_rows: list[FloatArray] = [] + results: list[IKStepResult] = [] + for row in arr: + res = self.solve_step(row, cur_q, dt_s=step_dt, include_tcp=include_tcp) + cur_q = res.q_rad + q_rows.append(cur_q.copy()) + results.append(res) + return np.stack(q_rows, axis=0), tuple(results) + + # ------------------------------------------------------------------ Hardware switch sync context manager + + @contextmanager + def sync_hardware_switches(self, arm: Any) -> Iterator[None]: + """Apply controller ``allow_approx_motion`` to an ``XArmAPI`` instance and restore it unconditionally.""" + + read_code, prev_approx = arm.get_allow_approx_motion() + if int(read_code) != 0: + raise RuntimeError(f"get_allow_approx_motion failed with SDK code {read_code}") + set_code = int(arm.set_allow_approx_motion(self._allow_approx_motion)) + if set_code != 0: + raise RuntimeError(f"set_allow_approx_motion({self._allow_approx_motion}) failed with SDK code {set_code}") + try: + yield + finally: + restore_code = int(arm.set_allow_approx_motion(bool(prev_approx))) + if restore_code != 0: + raise RuntimeError( + f"failed to restore controller allow_approx_motion={bool(prev_approx)} (SDK code={restore_code})" + ) diff --git a/ufactory/control/kinematics_chain.py b/ufactory/control/kinematics_chain.py new file mode 100644 index 0000000..236a28c --- /dev/null +++ b/ufactory/control/kinematics_chain.py @@ -0,0 +1,407 @@ +"""Pure-NumPy rigid kinematics chain with per-unit parameter compensation and TCP offset. + +Reuses the repository's nominal URDF parser (:func:`load_nominal_chain`), +schema-v1 calibration loader (:func:`load_kinematics_calibration`), and SDK TCP +offset conventions (:mod:`ufactory.kinematics.tcp_offset`). No dependency on +Pinocchio, Genesis, Torch, or xArm SDK. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math +from pathlib import Path + +import numpy as np + +from ufactory.config.assets import RepositoryAssetStore +from ufactory.kinematics.calibration import KinematicsCalibration, load_kinematics_calibration +from ufactory.kinematics.controller_fk import ( + CALIBRATION_FIELDS, + NominalChain, + axis_angle_matrix, + load_nominal_chain, + matrix_rpy, + rotation_angle, +) +from ufactory.kinematics.tcp_offset import pose_to_matrix, rpy_matrix +from ufactory.robots.assembly import resolve_robot_urdf +from ufactory.robots.registry import PROJECT_ROOT, get_robot_profile +from ufactory.types import FloatArray + + +def rotation_to_quat_xyzw(rotation: FloatArray) -> FloatArray: + """Convert a 3x3 proper rotation matrix to a unit quaternion ``[x, y, z, w]``.""" + + r = np.asarray(rotation, dtype=np.float64).reshape(3, 3) + trace = float(r[0, 0] + r[1, 1] + r[2, 2]) + if trace > 0.0: + s = math.sqrt(trace + 1.0) * 2.0 + w = 0.25 * s + x = (r[2, 1] - r[1, 2]) / s + y = (r[0, 2] - r[2, 0]) / s + z = (r[1, 0] - r[0, 1]) / s + elif r[0, 0] > r[1, 1] and r[0, 0] > r[2, 2]: + s = math.sqrt(max(1.0 + float(r[0, 0] - r[1, 1] - r[2, 2]), 0.0)) * 2.0 + w = (r[2, 1] - r[1, 2]) / s + x = 0.25 * s + y = (r[0, 1] + r[1, 0]) / s + z = (r[0, 2] + r[2, 0]) / s + elif r[1, 1] > r[2, 2]: + s = math.sqrt(max(1.0 + float(r[1, 1] - r[0, 0] - r[2, 2]), 0.0)) * 2.0 + w = (r[0, 2] - r[2, 0]) / s + x = (r[0, 1] + r[1, 0]) / s + y = 0.25 * s + z = (r[1, 2] + r[2, 1]) / s + else: + s = math.sqrt(max(1.0 + float(r[2, 2] - r[0, 0] - r[1, 1]), 0.0)) * 2.0 + w = (r[1, 0] - r[0, 1]) / s + x = (r[0, 2] + r[2, 0]) / s + y = (r[1, 2] + r[2, 1]) / s + z = 0.25 * s + q = np.array([x, y, z, w], dtype=np.float64) + norm = float(np.linalg.norm(q)) + if norm < 1e-15: + return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64) + q /= norm + if q[3] < 0.0: + q = -q + return q + + +def quat_xyzw_to_rotation(quat_xyzw: Sequence[float] | FloatArray) -> FloatArray: + """Convert quaternion ``[x, y, z, w]`` to a 3x3 rotation matrix.""" + + q: FloatArray = np.asarray(quat_xyzw, dtype=np.float64).reshape(-1) + if q.shape != (4,) or not np.all(np.isfinite(q)): + raise ValueError("quaternion must contain 4 finite values [x, y, z, w]") + norm = float(np.linalg.norm(q)) + if norm < 1e-12: + raise ValueError("quaternion must have non-zero norm") + x, y, z, w = (float(v) / norm for v in q) + return np.array( + [ + [1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - z * w), 2.0 * (x * z + y * w)], + [2.0 * (x * y + z * w), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - x * w)], + [2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y)], + ], + dtype=np.float64, + ) + + +def so3_log(rotation: FloatArray) -> FloatArray: + """Robust SO(3) logarithm returning the rotation vector ``omega`` (rad), valid up to pi.""" + + r = np.asarray(rotation, dtype=np.float64).reshape(3, 3) + cos_theta = float(np.clip((float(np.trace(r)) - 1.0) * 0.5, -1.0, 1.0)) + theta = math.acos(cos_theta) + if theta < 1e-12: + return 0.5 * np.array([r[2, 1] - r[1, 2], r[0, 2] - r[2, 0], r[1, 0] - r[0, 1]], dtype=np.float64) + if math.pi - theta < 1e-5: + # Near pi: extract unit axis from the largest diagonal element of (R + I)/2. + diag = np.maximum(0.5 * (np.diag(r) + 1.0), 0.0) + idx = int(np.argmax(diag)) + axis: FloatArray = np.zeros(3, dtype=np.float64) + axis[idx] = math.sqrt(float(diag[idx])) + if axis[idx] > 1e-12: + for j in range(3): + if j != idx: + axis[j] = 0.5 * float(r[idx, j] + r[j, idx]) / (2.0 * axis[idx]) + axis_norm = float(np.linalg.norm(axis)) + if axis_norm < 1e-12: + axis = np.array([1.0, 0.0, 0.0], dtype=np.float64) + else: + axis /= axis_norm + # Fix sign using skew part when non-zero. + vee = np.array([r[2, 1] - r[1, 2], r[0, 2] - r[2, 0], r[1, 0] - r[0, 1]], dtype=np.float64) + if float(np.dot(axis, vee)) < 0.0: + axis = -axis + return axis * theta + sin_theta = math.sin(theta) + vee = 0.5 * np.array([r[2, 1] - r[1, 2], r[0, 2] - r[2, 0], r[1, 0] - r[0, 1]], dtype=np.float64) + return vee * (theta / sin_theta) + + +def slerp_rotation(rot_a: FloatArray, rot_b: FloatArray, alpha: float) -> FloatArray: + """Geodesic SLERP on SO(3) between ``rot_a`` (alpha=0) and ``rot_b`` (alpha=1).""" + + a = float(np.clip(alpha, 0.0, 1.0)) + ra = np.asarray(rot_a, dtype=np.float64).reshape(3, 3) + rb = np.asarray(rot_b, dtype=np.float64).reshape(3, 3) + if a <= 0.0: + return ra.copy() + if a >= 1.0: + return rb.copy() + omega = so3_log(ra.T @ rb) + theta = float(np.linalg.norm(omega)) + if theta < 1e-15: + return ra.copy() + return np.asarray(ra @ axis_angle_matrix(omega / theta, theta * a), dtype=np.float64) + + +def pose_to_se3(pose: Sequence[float] | FloatArray, *, position_in_mm: bool = False) -> FloatArray: + """Convert ``xyz+rpy`` (len 6) or ``xyz+quat_xyzw`` (len 7) to a 4x4 SE(3) matrix in metres.""" + + arr: FloatArray = np.asarray(pose, dtype=np.float64).reshape(-1) + if not np.all(np.isfinite(arr)): + raise ValueError("pose must contain only finite values") + scale = 1e-3 if position_in_mm else 1.0 + mat: FloatArray = np.eye(4, dtype=np.float64) + if arr.size == 6: + mat[:3, 3] = arr[:3] * scale + mat[:3, :3] = rpy_matrix(float(arr[3]), float(arr[4]), float(arr[5])) + return mat + if arr.size == 7: + mat[:3, 3] = arr[:3] * scale + mat[:3, :3] = quat_xyzw_to_rotation(arr[3:7]) + return mat + raise ValueError(f"pose must have length 6 (xyz+rpy) or 7 (xyz+quat_xyzw), got {arr.size}") + + +def se3_to_pose_m_quat(transform: FloatArray) -> FloatArray: + """Convert a 4x4 SE(3) matrix (metres) to ``[x, y, z, qx, qy, qz, qw]``.""" + + t = np.asarray(transform, dtype=np.float64).reshape(4, 4) + quat = rotation_to_quat_xyzw(t[:3, :3]) + return np.concatenate((t[:3, 3], quat)) + + +def se3_to_pose_mm_rpy(transform: FloatArray) -> FloatArray: + """Convert a 4x4 SE(3) matrix (metres) to SDK ``[x_mm, y_mm, z_mm, roll, pitch, yaw]``.""" + + t = np.asarray(transform, dtype=np.float64).reshape(4, 4) + roll, pitch, yaw = matrix_rpy(t[:3, :3]) + return np.array( + [t[0, 3] * 1000.0, t[1, 3] * 1000.0, t[2, 3] * 1000.0, roll, pitch, yaw], + dtype=np.float64, + ) + + +def _origin_matrix(row: FloatArray) -> FloatArray: + mat: FloatArray = np.eye(4, dtype=np.float64) + mat[:3, :3] = rpy_matrix(float(row[3]), float(row[4]), float(row[5])) + mat[:3, 3] = row[:3] + return mat + + +def _tcp_offset_matrix_m(tcp_offset_mm_rpy: Sequence[float] | FloatArray) -> tuple[FloatArray, FloatArray]: + arr: FloatArray = np.asarray(tcp_offset_mm_rpy, dtype=np.float64).reshape(-1) + if arr.shape != (6,) or not np.all(np.isfinite(arr)): + raise ValueError("tcp_offset must contain 6 finite values [x_mm, y_mm, z_mm, roll, pitch, yaw]") + mat_mm = pose_to_matrix(arr) + mat_m = mat_mm.copy() + mat_m[:3, 3] *= 1e-3 + return arr.copy(), mat_m + + +@dataclass(frozen=True) +class CalibratedKinematicsChain: + """Pure-NumPy revolute kinematic chain supporting nominal URDF + per-unit calibration + TCP offset.""" + + robot_key: str + joint_names: tuple[str, ...] + nominal_origins: FloatArray # (N, 6) [x, y, z, r, p, y] in m/rad from nominal URDF + origins: FloatArray # (N, 6) active origins (nominal or compensated) + origin_transforms: FloatArray # (N, 4, 4) precomputed T_origin per joint + axes: FloatArray # (N, 3) unit axis in local joint frame + lower: FloatArray # (N,) rad + upper: FloatArray # (N,) rad + ee_link: str + is_calibrated: bool + calibration_sha256: str | None + serial_number: str | None + tcp_offset_mm_rpy: FloatArray # (6,) [mm, mm, mm, rad, rad, rad] + tcp_transform_m: FloatArray # (4, 4) T_flange_to_tcp in metres + + @property + def dof(self) -> int: + return len(self.joint_names) + + @classmethod + def from_nominal_chain( + cls, + robot_key: str, + nominal: NominalChain, + *, + calibration: KinematicsCalibration | None = None, + tcp_offset_mm_rpy: Sequence[float] | FloatArray | None = None, + ) -> CalibratedKinematicsChain: + nominal_origins = np.asarray(nominal.origins, dtype=np.float64).copy() + if calibration is not None: + active_origins = np.asarray( + [[calibration.joints[name][field] for field in CALIBRATION_FIELDS] for name in nominal.joint_names], + dtype=np.float64, + ) + is_calibrated = True + cal_sha = calibration.sha256 + serial = calibration.serial_number + else: + active_origins = nominal_origins.copy() + is_calibrated = False + cal_sha = None + serial = None + + origin_transforms = np.stack([_origin_matrix(row) for row in active_origins], axis=0) + resolved_tcp = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) if tcp_offset_mm_rpy is None else tcp_offset_mm_rpy + tcp_arr, tcp_mat = _tcp_offset_matrix_m(resolved_tcp) + return cls( + robot_key=robot_key, + joint_names=tuple(nominal.joint_names), + nominal_origins=nominal_origins, + origins=active_origins, + origin_transforms=origin_transforms, + axes=np.asarray(nominal.axes, dtype=np.float64).copy(), + lower=np.asarray(nominal.lower, dtype=np.float64).copy(), + upper=np.asarray(nominal.upper, dtype=np.float64).copy(), + ee_link=nominal.ee_link, + is_calibrated=is_calibrated, + calibration_sha256=cal_sha, + serial_number=serial, + tcp_offset_mm_rpy=tcp_arr, + tcp_transform_m=tcp_mat, + ) + + @classmethod + def from_robot( + cls, + robot_key: str, + *, + urdf_path: str | Path | None = None, + calibration_path: str | Path | None = None, + serial_number: str | None = None, + tcp_offset_mm_rpy: Sequence[float] | FloatArray | None = None, + asset_store: RepositoryAssetStore | None = None, + ) -> CalibratedKinematicsChain: + """Build a pure-NumPy kinematic chain for one of the 5 UFACTORY arms.""" + + profile = get_robot_profile(robot_key) + joint_names = tuple(f"joint{i}" for i in range(1, profile.dof + 1)) + if urdf_path is None: + store = asset_store or RepositoryAssetStore.discover() + assets_rel = profile.assets_dir.relative_to(PROJECT_ROOT).as_posix() + resolved_urdf = resolve_robot_urdf( + profile.key, + profile.default_urdf, + assets_dir=assets_rel, + store=store, + ) + else: + resolved_urdf = Path(urdf_path).expanduser().resolve() + nominal = load_nominal_chain(resolved_urdf, joint_names) + calibration: KinematicsCalibration | None = None + if calibration_path is not None: + calibration = load_kinematics_calibration( + str(calibration_path), + robot_key=profile.key, + serial_number=serial_number, + joint_names=joint_names, + ) + return cls.from_nominal_chain( + profile.key, + nominal, + calibration=calibration, + tcp_offset_mm_rpy=tcp_offset_mm_rpy, + ) + + def with_tcp_offset(self, tcp_offset_mm_rpy: Sequence[float] | FloatArray) -> CalibratedKinematicsChain: + """Return a new chain with updated TCP offset (mm + rad).""" + + tcp_arr, tcp_mat = _tcp_offset_matrix_m(tcp_offset_mm_rpy) + return CalibratedKinematicsChain( + robot_key=self.robot_key, + joint_names=self.joint_names, + nominal_origins=self.nominal_origins, + origins=self.origins, + origin_transforms=self.origin_transforms, + axes=self.axes, + lower=self.lower, + upper=self.upper, + ee_link=self.ee_link, + is_calibrated=self.is_calibrated, + calibration_sha256=self.calibration_sha256, + serial_number=self.serial_number, + tcp_offset_mm_rpy=tcp_arr, + tcp_transform_m=tcp_mat, + ) + + def validate_q(self, q_rad: Sequence[float] | FloatArray) -> FloatArray: + q: FloatArray = np.asarray(q_rad, dtype=np.float64).reshape(-1) + if q.shape != (self.dof,) or not np.all(np.isfinite(q)): + raise ValueError(f"joint vector must contain {self.dof} finite values, got shape {q.shape}") + return q + + def forward_matrix(self, q_rad: Sequence[float] | FloatArray, *, include_tcp: bool = True) -> FloatArray: + """Return 4x4 SE(3) end-effector transform in robot base frame (metres).""" + + q = self.validate_q(q_rad) + pose: FloatArray = np.eye(4, dtype=np.float64) + for i in range(self.dof): + pose = pose @ self.origin_transforms[i] + rot = axis_angle_matrix(self.axes[i], float(q[i])) + pose[:3, :3] = pose[:3, :3] @ rot + if include_tcp: + pose = pose @ self.tcp_transform_m + return pose + + def forward_pose_m_quat(self, q_rad: Sequence[float] | FloatArray, *, include_tcp: bool = True) -> FloatArray: + """Return ``[x, y, z, qx, qy, qz, qw]`` in base frame (metres).""" + + return se3_to_pose_m_quat(self.forward_matrix(q_rad, include_tcp=include_tcp)) + + def forward_pose_mm_rpy(self, q_rad: Sequence[float] | FloatArray, *, include_tcp: bool = True) -> FloatArray: + """Return ``[x_mm, y_mm, z_mm, roll, pitch, yaw]`` in base frame (SDK units).""" + + return se3_to_pose_mm_rpy(self.forward_matrix(q_rad, include_tcp=include_tcp)) + + def forward_and_jacobian( + self, + q_rad: Sequence[float] | FloatArray, + *, + include_tcp: bool = True, + ) -> tuple[FloatArray, FloatArray]: + """Compute 4x4 FK transform and 6xN base-aligned geometric Jacobian ``[v_m; w_rad]``.""" + + q = self.validate_q(q_rad) + n = self.dof + joint_positions: FloatArray = np.empty((n, 3), dtype=np.float64) + joint_axes: FloatArray = np.empty((n, 3), dtype=np.float64) + pose: FloatArray = np.eye(4, dtype=np.float64) + for i in range(n): + pose = pose @ self.origin_transforms[i] + joint_positions[i] = pose[:3, 3] + joint_axes[i] = pose[:3, :3] @ self.axes[i] + rot = axis_angle_matrix(self.axes[i], float(q[i])) + pose[:3, :3] = pose[:3, :3] @ rot + if include_tcp: + pose = pose @ self.tcp_transform_m + p_ee = pose[:3, 3] + jac: FloatArray = np.empty((6, n), dtype=np.float64) + for i in range(n): + z_i = joint_axes[i] + jac[:3, i] = np.cross(z_i, p_ee - joint_positions[i]) + jac[3:, i] = z_i + return pose, jac + + def jacobian(self, q_rad: Sequence[float] | FloatArray, *, include_tcp: bool = True) -> FloatArray: + """Return 6xN spatial geometric Jacobian ``[v_m; w_rad]`` in base (LOCAL_WORLD_ALIGNED) frame.""" + + _, jac = self.forward_and_jacobian(q_rad, include_tcp=include_tcp) + return jac + + def tcp_target_to_flange(self, target_tcp_se3: FloatArray) -> FloatArray: + """Strip ``tcp_offset`` from a 4x4 TCP target matrix to obtain the flange target matrix.""" + + t = np.asarray(target_tcp_se3, dtype=np.float64).reshape(4, 4) + rot_t = self.tcp_transform_m[:3, :3].T + inv_tcp: FloatArray = np.eye(4, dtype=np.float64) + inv_tcp[:3, :3] = rot_t + inv_tcp[:3, 3] = -rot_t @ self.tcp_transform_m[:3, 3] + return np.asarray(t @ inv_tcp, dtype=np.float64) + + def pose_error(self, target_se3: FloatArray, current_se3: FloatArray) -> tuple[float, float]: + """Return ``(position_error_m, orientation_error_rad)`` between two 4x4 transforms.""" + + pos_err = float(np.linalg.norm(target_se3[:3, 3] - current_se3[:3, 3])) + rot_err = float(rotation_angle(current_se3[:3, :3], target_se3[:3, :3])) + return pos_err, rot_err diff --git a/ufactory/control/solvers.py b/ufactory/control/solvers.py new file mode 100644 index 0000000..85b5b58 --- /dev/null +++ b/ufactory/control/solvers.py @@ -0,0 +1,622 @@ +"""Pure-NumPy inverse kinematics solvers for all 5 UFACTORY arms + firmware-aligned DLS. + +* **Lite6 / UF850**: Closed-form Pieper spherical-wrist analytical IK on the + nominal geometry (enumerating all <= 8 branches, wrapping multi-turn joints to + ``seed_q``, filtering by joint limits), followed by a 2-6 step damped + Newton-Raphson polish on the compensated chain whenever per-unit calibration + is active (or to absorb tiny URDF ``1.5708`` rounding). +* **xArm6**: 6-DOF damped SE(3) Levenberg-Marquardt / Newton-Raphson IK. +* **xArm7**: 7-DOF redundant minimum-norm damped IK with nullspace seed attraction. +* **xArm5**: 5-DOF position-priority hierarchical IK (hard position convergence + < 1 um; secondary orientation projection inside the 2-DOF position nullspace, + tolerating irreducible roll residuals caused by non-coplanar calibration). +* **Singularity-robust approximate step (``set_allow_approx_motion(True)``)**: + Native ``[mm, rad]`` single-step Damped Least Squares (DLS, ``lambda_max = 1.0``) + reverse-engineered from UF850 v2.8.100 and Lite6 v2.8.2 controllers, paired + with Chiaverini C1 smooth damping ramp and fail-closed pose error ceilings. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math + +import numpy as np + +from ufactory.control.kinematics_chain import ( + CalibratedKinematicsChain, + so3_log, +) +from ufactory.kinematics.controller_fk import axis_angle_matrix +from ufactory.kinematics.tcp_offset import rpy_matrix +from ufactory.types import FloatArray + +SPHERICAL_WRIST_ROBOTS = frozenset({"lite6", "uf850"}) +DEFAULT_POS_TOL_M = 1e-7 +DEFAULT_ROT_TOL_RAD = 1e-5 +DEFAULT_XARM5_ROT_TOL_RAD = 5e-3 + + +@dataclass(frozen=True) +class ApproxMotionConfig: + """Tuning and fail-closed bounds for ``allow_approx_motion=True``.""" + + damping: float = 1.0 + singular_value_threshold: float = 0.08 + trigger_joint_speed_rad_s: float | None = None + max_position_error_m: float = 0.002 + max_orientation_error_rad: float = 0.05 + position_unit_scale: float = 1000.0 + + def __post_init__(self) -> None: + for name in ( + "damping", + "singular_value_threshold", + "max_position_error_m", + "max_orientation_error_rad", + "position_unit_scale", + ): + value = float(getattr(self, name)) + if not math.isfinite(value): + raise ValueError(f"ApproxMotionConfig.{name} must be finite") + if self.damping <= 0.0: + raise ValueError("ApproxMotionConfig.damping must be positive") + if self.singular_value_threshold < 0.0: + raise ValueError("ApproxMotionConfig.singular_value_threshold must be non-negative") + if self.trigger_joint_speed_rad_s is not None and ( + not math.isfinite(self.trigger_joint_speed_rad_s) or self.trigger_joint_speed_rad_s <= 0.0 + ): + raise ValueError("ApproxMotionConfig.trigger_joint_speed_rad_s must be finite and positive") + if self.max_position_error_m <= 0.0 or self.max_orientation_error_rad <= 0.0: + raise ValueError("ApproxMotionConfig error ceilings must be positive") + if self.position_unit_scale <= 0.0: + raise ValueError("ApproxMotionConfig.position_unit_scale must be positive") + + +@dataclass(frozen=True) +class IKStepResult: + """Result and diagnostics of one inverse-kinematics step.""" + + q_rad: FloatArray + used_approx: bool + effective_damping: float + min_singular_value: float + position_error_m: float + orientation_error_rad: float + solver: str + + +def _wrap_to_pi(angle: float) -> float: + return math.atan2(math.sin(angle), math.cos(angle)) + + +def _wrap_near(angle: float, reference: float, lower: float, upper: float) -> float | None: + """Choose ``angle + 2*pi*k`` inside ``[lower, upper]`` closest to ``reference``.""" + + k_center = round((reference - angle) / (2.0 * math.pi)) + best: float | None = None + best_dist = math.inf + for dk in (-2, -1, 0, 1, 2): + cand = angle + 2.0 * math.pi * (k_center + dk) + if lower - 1e-9 <= cand <= upper + 1e-9: + cand = float(np.clip(cand, lower, upper)) + dist = abs(cand - reference) + if dist < best_dist: + best_dist = dist + best = cand + return best + + +def _within_limits(q: FloatArray, lower: FloatArray, upper: FloatArray, tol: float = 1e-7) -> bool: + return bool(np.all(q >= lower - tol) and np.all(q <= upper + tol)) + + +def _clip_to_limits(q: FloatArray, lower: FloatArray, upper: FloatArray) -> FloatArray: + return np.asarray(np.clip(q, lower, upper), dtype=np.float64) + + +# ------------------------------------------------------------------ Lite6 / UF850 closed-form analytical Pieper IK + + +def solve_spherical_wrist_analytical( + chain: CalibratedKinematicsChain, + target_flange_se3: FloatArray, + *, + seed_q_rad: Sequence[float] | FloatArray | None = None, +) -> list[FloatArray]: + """Enumerate all valid closed-form Pieper IK solutions (up to 8 branches) for nominal Lite6 / UF850. + + Returns solutions sorted by weighted joint distance to ``seed_q_rad`` (closest first). + """ + + if chain.robot_key not in SPHERICAL_WRIST_ROBOTS or chain.dof != 6: + raise ValueError(f"analytical spherical-wrist IK only supports Lite6 and UF850, got {chain.robot_key!r}") + + seed = np.zeros(6, dtype=np.float64) if seed_q_rad is None else chain.validate_q(seed_q_rad) + nom = chain.nominal_origins # (6, 6): [x, y, z, r, p, y] + d1 = float(nom[0, 2]) + l2 = float(nom[2, 0]) + a4 = float(nom[3, 0]) + b4 = abs(float(nom[3, 1])) + d6 = abs(float(nom[5, 1])) + l3 = math.hypot(a4, b4) + phi = math.atan2(a4, b4) + + # Lite6 vs UF850 planar sign convention: + # Lite6: r = L2*sin(q2) + a4*cos(q2-q3) - b4*sin(q2-q3); wrist Rz(q4)*Ry(-q5)*Rz(q6) + # UF850: r = -L2*sin(q2) + a4*cos(q3-q2) - b4*sin(q3-q2) => identical with (u2, u3) = (-q2, -q3); + # wrist Rz(q4)*Ry(+q5)*Rz(q6). + is_uf850 = chain.robot_key == "uf850" + planar_sign = -1.0 if is_uf850 else 1.0 + wrist_q5_sign = 1.0 if is_uf850 else -1.0 + + r_flange = np.asarray(target_flange_se3[:3, :3], dtype=np.float64) + p_flange = np.asarray(target_flange_se3[:3, 3], dtype=np.float64) + # Wrist center W = p_flange - d6 * z_flange + w_pos = p_flange - d6 * r_flange[:, 2] + wx, wy, wz = float(w_pos[0]), float(w_pos[1]), float(w_pos[2]) + r_xy = math.hypot(wx, wy) + dz = wz - d1 + + # Step 1: q1 candidates (2 shoulder branches) + if r_xy < 1e-9: + q1_branches: list[tuple[float, float]] = [(_wrap_to_pi(float(seed[0])), 0.0)] + else: + q1_fwd = math.atan2(wy, wx) + q1_branches = [(q1_fwd, r_xy), (_wrap_to_pi(q1_fwd + math.pi), -r_xy)] + + # Precompute nominal origin rotations for exact R_04(q1, q2, q3) + r_orig = [rpy_matrix(float(nom[i, 3]), float(nom[i, 4]), float(nom[i, 5])) for i in range(6)] + z_axis = np.array([0.0, 0.0, 1.0], dtype=np.float64) + + solutions: list[FloatArray] = [] + for q1_raw, r_planar in q1_branches: + q1 = _wrap_near(q1_raw, float(seed[0]), float(chain.lower[0]), float(chain.upper[0])) + if q1 is None: + continue + + # Step 2: u3, u2 in canonical Lite6 planar coordinates + dist_sq = r_planar * r_planar + dz * dz + cos_u3_plus_phi = (l2 * l2 + l3 * l3 - dist_sq) / (2.0 * l2 * l3) + if abs(cos_u3_plus_phi) > 1.0 + 1e-7: + continue + cos_clamped = float(np.clip(cos_u3_plus_phi, -1.0, 1.0)) + acos_val = math.acos(cos_clamped) + u3_candidates = [acos_val - phi] if abs(acos_val) < 1e-10 else [acos_val - phi, -acos_val - phi] + + for u3 in u3_candidates: + q3_raw = planar_sign * u3 + q3 = _wrap_near(q3_raw, float(seed[2]), float(chain.lower[2]), float(chain.upper[2])) + if q3 is None: + continue + u3_eff = planar_sign * q3 + a_coeff = a4 * math.cos(u3_eff) + b4 * math.sin(u3_eff) + b_coeff = l2 + a4 * math.sin(u3_eff) - b4 * math.cos(u3_eff) + u2 = math.atan2(r_planar, dz) - math.atan2(a_coeff, b_coeff) + q2_raw = planar_sign * u2 + q2 = _wrap_near(q2_raw, float(seed[1]), float(chain.lower[1]), float(chain.upper[1])) + if q2 is None: + continue + + # Step 3: Exact nominal R_04(q1, q2, q3, q4=0) -> R_wrist = R_04^T @ R_flange + r01 = r_orig[0] @ axis_angle_matrix(z_axis, q1) + r02 = r01 @ r_orig[1] @ axis_angle_matrix(z_axis, q2) + r03 = r02 @ r_orig[2] @ axis_angle_matrix(z_axis, q3) + r04_zero = r03 @ r_orig[3] + r_wrist = r04_zero.T @ r_flange + + # Decompose R_wrist = Rz(q4) @ Ry(wrist_q5_sign * q5) @ Rz(q6) + m22 = float(np.clip(r_wrist[2, 2], -1.0, 1.0)) + beta_mag = math.acos(m22) + wrist_pairs: list[tuple[float, float, float]] = [] + if math.sin(beta_mag) < 1e-7: + # Wrist singularity: only q4 +/- q6 is determined; keep q4 = seed[3]. + alpha = float(seed[3]) + if m22 >= 0.0: + gamma = math.atan2(float(r_wrist[1, 0]), float(r_wrist[0, 0])) - alpha + wrist_pairs.append((alpha, 0.0, gamma)) + else: + gamma = alpha - math.atan2(float(r_wrist[1, 0]), -float(r_wrist[0, 0])) + wrist_pairs.append((alpha, wrist_q5_sign * math.pi, gamma)) + else: + for beta in (beta_mag, -beta_mag): + sb = math.sin(beta) + alpha = math.atan2(float(r_wrist[1, 2]) / sb, float(r_wrist[0, 2]) / sb) + gamma = math.atan2(float(r_wrist[2, 1]) / sb, -float(r_wrist[2, 0]) / sb) + wrist_pairs.append((alpha, wrist_q5_sign * beta, gamma)) + + for q4_raw, q5_raw, q6_raw in wrist_pairs: + q4 = _wrap_near(q4_raw, float(seed[3]), float(chain.lower[3]), float(chain.upper[3])) + q5 = _wrap_near(q5_raw, float(seed[4]), float(chain.lower[4]), float(chain.upper[4])) + q6 = _wrap_near(q6_raw, float(seed[5]), float(chain.lower[5]), float(chain.upper[5])) + if q4 is None or q5 is None or q6 is None: + continue + cand = np.array([q1, q2, q3, q4, q5, q6], dtype=np.float64) + if not any(float(np.max(np.abs(cand - prev))) < 1e-6 for prev in solutions): + solutions.append(cand) + + # Sort closest to seed_q (prioritize avoiding large shoulder/elbow flips) + weights = np.array([2.0, 2.0, 2.0, 1.0, 1.0, 1.0], dtype=np.float64) + solutions.sort(key=lambda q: float(np.sum(weights * np.square(q - seed)))) + return solutions + + +# ------------------------------------------------------------------ Iterative IK solvers (all 5 robots) + + +def _pose_residual_vec(target_se3: FloatArray, current_se3: FloatArray) -> FloatArray: + dp = target_se3[:3, 3] - current_se3[:3, 3] + dw = so3_log(target_se3[:3, :3] @ current_se3[:3, :3].T) + return np.concatenate((dp, dw)) + + +def solve_iterative_6dof_or_7dof( + chain: CalibratedKinematicsChain, + target_se3: FloatArray, + seed_q_rad: FloatArray, + *, + include_tcp: bool = True, + max_iterations: int = 120, + pos_tol_m: float = DEFAULT_POS_TOL_M, + rot_tol_rad: float = DEFAULT_ROT_TOL_RAD, + damping: float = 1e-6, + max_step_rad: float = 0.15, + nullspace_gain: float = 0.05, +) -> tuple[FloatArray, float, float]: + """Damped SE(3) Newton-Raphson IK for 6-DOF (xArm6, calibrated Lite6/UF850 polish) and 7-DOF (xArm7).""" + + q = _clip_to_limits(chain.validate_q(seed_q_rad).copy(), chain.lower, chain.upper) + seed_ref = q.copy() + n = chain.dof + is_redundant = n > 6 + pos_err = math.inf + rot_err = math.inf + + for _ in range(max_iterations): + cur_se3, jac = chain.forward_and_jacobian(q, include_tcp=include_tcp) + e = _pose_residual_vec(target_se3, cur_se3) + pos_err = float(np.linalg.norm(e[:3])) + rot_err = float(np.linalg.norm(e[3:])) + if pos_err <= pos_tol_m and rot_err <= rot_tol_rad: + return q, pos_err, rot_err + + # Scale position to mm internally only for well-conditioned SVD check, keep SI solve with adaptive damping + s_min = float(np.min(np.linalg.svd(jac, compute_uv=False))) + scale = min(10.0, max(1.0, 1e-2 / max(s_min, 1e-12))) + reg = (damping * (scale**2)) * np.eye(6, dtype=np.float64) + jjt = jac @ jac.T + reg + dq_task = jac.T @ np.linalg.solve(jjt, e) + + if is_redundant and nullspace_gain > 0.0 and (pos_err > 1e-4 or rot_err > 1e-3): + # Soft attraction toward seed_ref in the nullspace during coarse approach; + # disable inside the fine <0.1 mm / 1 mrad polish basin so second-order + # nonlinear chord error cannot stall final Newton convergence. + j_pinv = jac.T @ np.linalg.inv(jjt) + null_proj = np.eye(n, dtype=np.float64) - j_pinv @ jac + dq = dq_task + nullspace_gain * (null_proj @ (seed_ref - q)) + else: + dq = dq_task + + max_step = float(np.max(np.abs(dq), initial=0.0)) + if max_step > max_step_rad: + dq *= max_step_rad / max_step + q = _clip_to_limits(q + dq, chain.lower, chain.upper) + + raise ValueError( + f"{chain.robot_key} iterative IK did not converge after {max_iterations} iterations " + f"(pos_err={pos_err * 1e3:.4f} mm, rot_err={rot_err * 1e3:.4f} mrad)" + ) + + +def solve_iterative_5dof_position_priority( + chain: CalibratedKinematicsChain, + target_se3: FloatArray, + seed_q_rad: FloatArray, + *, + include_tcp: bool = True, + max_iterations: int = 120, + pos_tol_m: float = DEFAULT_POS_TOL_M, + rot_tol_rad: float = DEFAULT_XARM5_ROT_TOL_RAD, + max_step_rad: float = 0.15, +) -> tuple[FloatArray, float, float]: + """Hierarchical 5-DOF IK for xArm5: exact position priority + nullspace orientation projection. + + A calibrated 5-DOF arm has non-coplanar link offsets, so full 6-DOF pose is + over-constrained by ~0.3-2 mrad of irreducible roll residual. Solving 3-DOF + position first and projecting orientation into the 2-DOF position nullspace + achieves < 1 um position error while minimizing total rotation error. + """ + + if chain.dof != 5: + raise ValueError(f"5-DOF position-priority IK requires dof=5, got {chain.dof}") + + q = _clip_to_limits(chain.validate_q(seed_q_rad).copy(), chain.lower, chain.upper) + pos_err = math.inf + rot_err = math.inf + prev_rot_err = math.inf + stalled = 0 + + for _ in range(max_iterations): + cur_se3, jac = chain.forward_and_jacobian(q, include_tcp=include_tcp) + dp = target_se3[:3, 3] - cur_se3[:3, 3] + dw = so3_log(target_se3[:3, :3] @ cur_se3[:3, :3].T) + pos_err = float(np.linalg.norm(dp)) + rot_err = float(np.linalg.norm(dw)) + + jp = jac[:3, :] # (3, 5) + jr = jac[3:, :] # (3, 5) + jp_jjt = jp @ jp.T + 1e-10 * np.eye(3, dtype=np.float64) + jp_pinv = jp.T @ np.linalg.inv(jp_jjt) + dq_pos = jp_pinv @ dp + + null_p = np.eye(5, dtype=np.float64) - jp_pinv @ jp + jr_null = jr @ null_p # (3, 5), rank <= 2 + # Damped least-squares projection of remaining orientation error in position nullspace + gram = jr_null.T @ jr_null + 1e-6 * np.eye(5, dtype=np.float64) + rhs = jr_null.T @ (dw - jr @ dq_pos) + dq_ori = null_p @ np.linalg.solve(gram, rhs) + + dq = dq_pos + dq_ori + if pos_err <= pos_tol_m and float(np.linalg.norm(dq_ori)) < 1e-7: + if rot_err <= rot_tol_rad: + return q, pos_err, rot_err + break + if pos_err <= pos_tol_m and abs(prev_rot_err - rot_err) < 1e-9: + stalled += 1 + if stalled >= 4 and rot_err <= rot_tol_rad: + return q, pos_err, rot_err + else: + stalled = 0 + prev_rot_err = rot_err + + max_step = float(np.max(np.abs(dq), initial=0.0)) + if max_step > max_step_rad: + dq *= max_step_rad / max_step + q = _clip_to_limits(q + dq, chain.lower, chain.upper) + + if pos_err <= pos_tol_m and rot_err <= rot_tol_rad: + return q, pos_err, rot_err + raise ValueError( + f"{chain.robot_key} 5-DOF position-priority IK did not converge after {max_iterations} iterations " + f"(pos_err={pos_err * 1e3:.4f} mm, rot_err={rot_err * 1e3:.4f} mrad, rot_tol={rot_tol_rad * 1e3:.3f} mrad)" + ) + + +# ------------------------------------------------------------------ Unified exact IK dispatcher (all 5 robots) + + +def solve_exact_ik( + chain: CalibratedKinematicsChain, + target_se3: FloatArray, + seed_q_rad: Sequence[float] | FloatArray | None = None, + *, + include_tcp: bool = True, + pos_tol_m: float = DEFAULT_POS_TOL_M, + rot_tol_rad: float | None = None, + cold_start_fallback: bool = False, +) -> IKStepResult: + """Solve exact IK for any of the 5 UFACTORY arms (analytical + polish for Lite6/UF850, iterative for xArm5/6/7).""" + + seed = np.zeros(chain.dof, dtype=np.float64) if seed_q_rad is None else chain.validate_q(seed_q_rad) + target = np.asarray(target_se3, dtype=np.float64).reshape(4, 4) + + if chain.dof == 5: + r_tol = DEFAULT_XARM5_ROT_TOL_RAD if rot_tol_rad is None else float(rot_tol_rad) + seeds_5 = [seed] + if cold_start_fallback: + mid5 = 0.5 * (chain.lower + chain.upper) + seeds_5.extend( + [ + np.array([0.0, -0.5, -0.8, 1.3, 0.0], dtype=np.float64), + np.array([0.0, 0.2, -1.2, 1.0, 0.0], dtype=np.float64), + mid5, + ] + ) + last_exc_5: Exception | None = None + for cand_seed in seeds_5: + try: + q_sol, pos_err, rot_err = solve_iterative_5dof_position_priority( + chain, + target, + cand_seed, + include_tcp=include_tcp, + pos_tol_m=pos_tol_m, + rot_tol_rad=r_tol, + ) + jac = chain.jacobian(q_sol, include_tcp=include_tcp) + jac_mm = jac.copy() + jac_mm[:3, :] *= 1000.0 + s_min = float(np.min(np.linalg.svd(jac_mm, compute_uv=False))) + return IKStepResult(q_sol, False, 0.0, s_min, pos_err, rot_err, "iterative-5dof-pos-priority") + except ValueError as exc: + last_exc_5 = exc + raise ValueError(f"{chain.robot_key} 5-DOF iterative IK failed: {last_exc_5}") + + r_tol = DEFAULT_ROT_TOL_RAD if rot_tol_rad is None else float(rot_tol_rad) + + if chain.robot_key in SPHERICAL_WRIST_ROBOTS: + flange_target = chain.tcp_target_to_flange(target) if include_tcp else target + analytical_branches = solve_spherical_wrist_analytical(chain, flange_target, seed_q_rad=seed) + # Near wrist singularity (|q5| < 0.05 rad) during tight continuous tracking, + # URDF 4-decimal 1.5708 rounding (~3.7e-6 rad) gets amplified by 1/sin(q5) in + # closed-form atan2; prefer local damped Newton polish from seed first there, + # while using global Pieper analytical branches everywhere else. + seed_pos_err, seed_rot_err = chain.pose_error(target, chain.forward_matrix(seed, include_tcp=include_tcp)) + near_wrist_tracking = ( + not cold_start_fallback and seed_pos_err < 0.015 and seed_rot_err < 0.1 and abs(float(seed[4])) < 0.05 + ) + last_exc: Exception | None = None + candidates: list[tuple[FloatArray, str]] = [] + if near_wrist_tracking: + candidates.append((seed, "iterative-6dof")) + candidates.extend((b, "analytical-pieper+polish") for b in analytical_branches) + else: + candidates.extend((b, "analytical-pieper+polish") for b in analytical_branches) + candidates.append((seed, "iterative-6dof")) + for cand_seed, polish_label in candidates: + cur_se3 = chain.forward_matrix(cand_seed, include_tcp=include_tcp) + pos_err, rot_err = chain.pose_error(target, cur_se3) + if pos_err <= pos_tol_m and rot_err <= r_tol and _within_limits(cand_seed, chain.lower, chain.upper): + jac = chain.jacobian(cand_seed, include_tcp=include_tcp) + jac_mm = jac.copy() + jac_mm[:3, :] *= 1000.0 + s_min = float(np.min(np.linalg.svd(jac_mm, compute_uv=False))) + exact_label = "analytical-pieper" if polish_label.startswith("analytical") else "iterative-6dof" + return IKStepResult(cand_seed, False, 0.0, s_min, pos_err, rot_err, exact_label) + try: + q_sol, pos_err, rot_err = solve_iterative_6dof_or_7dof( + chain, + target, + cand_seed, + include_tcp=include_tcp, + max_iterations=60 if polish_label.startswith("analytical") else 120, + pos_tol_m=pos_tol_m, + rot_tol_rad=r_tol, + ) + jac = chain.jacobian(q_sol, include_tcp=include_tcp) + jac_mm = jac.copy() + jac_mm[:3, :] *= 1000.0 + s_min = float(np.min(np.linalg.svd(jac_mm, compute_uv=False))) + return IKStepResult(q_sol, False, 0.0, s_min, pos_err, rot_err, polish_label) + except ValueError as exc: + last_exc = exc + raise ValueError(f"{chain.robot_key} analytical+polish IK failed: {last_exc}") + + # xArm6 / xArm7 iterative IK (with optional multi-seed fallback for cold-start queries) + seeds_to_try = [seed] + if cold_start_fallback: + mid = 0.5 * (chain.lower + chain.upper) + if chain.dof == 6: + seeds_to_try.extend( + [ + np.array([0.0, -0.5, -0.8, 0.0, 1.3, 0.0], dtype=np.float64), + np.array([0.0, 0.2, -1.2, 0.0, 1.0, 0.0], dtype=np.float64), + mid, + ] + ) + elif chain.dof == 7: + seeds_to_try.extend( + [ + np.array([0.0, -0.5, 0.0, 0.0, 0.5, 0.0, 0.0], dtype=np.float64), + np.array([0.0, -0.4, 0.0, 0.8, 0.0, 1.2, 0.0], dtype=np.float64), + np.array([0.0, 0.2, 0.0, 1.2, 0.0, 1.0, 0.0], dtype=np.float64), + mid, + ] + ) + last_exc = None + for cand_seed in seeds_to_try: + try: + q_sol, pos_err, rot_err = solve_iterative_6dof_or_7dof( + chain, + target, + cand_seed, + include_tcp=include_tcp, + pos_tol_m=pos_tol_m, + rot_tol_rad=r_tol, + ) + jac = chain.jacobian(q_sol, include_tcp=include_tcp) + jac_mm = jac.copy() + jac_mm[:3, :] *= 1000.0 + s_min = float(np.min(np.linalg.svd(jac_mm, compute_uv=False))) + label = "iterative-7dof-redundant" if chain.dof == 7 else "iterative-6dof" + return IKStepResult(q_sol, False, 0.0, s_min, pos_err, rot_err, label) + except ValueError as exc: + last_exc = exc + raise ValueError(f"{chain.robot_key} iterative IK failed: {last_exc}") + + +# ------------------------------------------------------------------ Firmware-aligned native [mm, rad] DLS step + + +def solve_cartesian_step( + chain: CalibratedKinematicsChain, + target_se3: FloatArray, + seed_q_rad: Sequence[float] | FloatArray, + *, + allow_approx_motion: bool, + approx_config: ApproxMotionConfig | None = None, + dt_s: float | None = None, + include_tcp: bool = True, + force_approx: bool = False, +) -> IKStepResult: + """Solve one Cartesian control tick with optional firmware-aligned DLS singularity avoidance. + + When ``allow_approx_motion`` is ``False``, this strictly executes exact IK + and never relaxes orientation or position. When ``True``, entering the + Chiaverini singularity neighborhood (``sigma_min(J_mm) < sigma_0``), exact + IK non-convergence, or exact single-step joint speed exceeding + ``trigger_joint_speed_rad_s`` switches smoothly to the native ``[mm, rad]`` + single-step DLS law ``dq = (J_mm^T J_mm + lam_eff^2 I)^-1 J_mm^T e_mm`` + and enforces fail-closed position/orientation ceilings. + """ + + seed = chain.validate_q(seed_q_rad) + target = np.asarray(target_se3, dtype=np.float64).reshape(4, 4) + + if not allow_approx_motion: + return solve_exact_ik(chain, target, seed, include_tcp=include_tcp) + + cfg = approx_config or ApproxMotionConfig() + cur_se3, jac = chain.forward_and_jacobian(seed, include_tcp=include_tcp) + jac_mm = jac.copy() + jac_mm[:3, :] *= cfg.position_unit_scale + s_min = float(np.min(np.linalg.svd(jac_mm, compute_uv=False))) + + in_singular_band = cfg.singular_value_threshold > 0.0 and s_min < cfg.singular_value_threshold + use_dls = bool(force_approx) or in_singular_band + exact_res: IKStepResult | None = None + + if not use_dls: + try: + exact_res = solve_exact_ik(chain, target, seed, include_tcp=include_tcp) + if ( + cfg.trigger_joint_speed_rad_s is not None + and dt_s is not None + and dt_s > 0.0 + and float(np.max(np.abs(exact_res.q_rad - seed))) / float(dt_s) > cfg.trigger_joint_speed_rad_s + ): + use_dls = True + except ValueError: + use_dls = True + + if not use_dls and exact_res is not None: + return exact_res + + # Compute effective damping: Chiaverini C1 ramp inside singular band, full damping on speed/failure fallback + if not force_approx and in_singular_band and exact_res is None and cfg.singular_value_threshold > 0.0: + ratio = min(1.0, max(0.0, s_min / cfg.singular_value_threshold)) + eff_lam = cfg.damping * math.sqrt(max(0.0, 1.0 - ratio * ratio)) + else: + eff_lam = cfg.damping + + dp_mm = (target[:3, 3] - cur_se3[:3, 3]) * cfg.position_unit_scale + dw = so3_log(target[:3, :3] @ cur_se3[:3, :3].T) + e_mm = np.concatenate((dp_mm, dw)) + + n = chain.dof + gram = jac_mm.T @ jac_mm + (eff_lam * eff_lam) * np.eye(n, dtype=np.float64) + dq = np.linalg.solve(gram, jac_mm.T @ e_mm) + q_next = seed + dq + + if not _within_limits(q_next, chain.lower, chain.upper): + raise ValueError(f"{chain.robot_key} approximate DLS step exceeded joint position limits") + q_next = _clip_to_limits(q_next, chain.lower, chain.upper) + + next_se3 = chain.forward_matrix(q_next, include_tcp=include_tcp) + pos_err, rot_err = chain.pose_error(target, next_se3) + if pos_err > cfg.max_position_error_m or rot_err > cfg.max_orientation_error_rad: + raise ValueError( + f"{chain.robot_key} approximate DLS residual {pos_err * 1e3:.3f} mm / {math.degrees(rot_err):.3f} deg " + f"exceeds safety ceiling ({cfg.max_position_error_m * 1e3:.2f} mm / " + f"{math.degrees(cfg.max_orientation_error_rad):.2f} deg)" + ) + return IKStepResult( + q_rad=q_next, + used_approx=True, + effective_damping=eff_lam, + min_singular_value=s_min, + position_error_m=pos_err, + orientation_error_rad=rot_err, + solver="approx-dls-mm-rad", + ) diff --git a/ufactory/grippers/__init__.py b/ufactory/grippers/__init__.py index 9977950..874a0df 100644 --- a/ufactory/grippers/__init__.py +++ b/ufactory/grippers/__init__.py @@ -1,6 +1,8 @@ """Gripper control and command-space conversion helpers.""" from ufactory.grippers.bio_g2 import ( + BIO_G2_BLOCKED_MODES, + BIO_G2_CONTROLLER_VALIDATED, BIO_G2_JOINT_NAMES, BIO_GRIPPER_G2_CLOSED_GAP_M, BIO_GRIPPER_G2_CLOSED_GAP_MM, @@ -9,7 +11,9 @@ BIO_GRIPPER_G2_OPEN_GAP_MM, BIO_GRIPPER_G2_SIM_CLOSED_DRIVE, BIO_GRIPPER_G2_SIM_OPEN_DRIVE, + BIO_GRIPPER_G2_TCP_IN_FLANGE_M, BioGripperG2, + bio_g2_controller_mode_error, bio_gripper_g2_gap_m_to_sdk_pos_mm, bio_gripper_g2_gap_m_to_sim_drive, bio_gripper_g2_sim_drive_to_gap_m, @@ -65,10 +69,22 @@ Robotiq2F85Adapter, Robotiq2F140Adapter, RobotiqAdapter, + VacuumProfileAdapter, create_gripper_adapter, ) +from ufactory.grippers.vacuum import ( + VACUUM_GRIPPER_COM_FLANGE_MM, + VACUUM_GRIPPER_MASS_KG, + VACUUM_GRIPPER_SUPPORTED_ROBOTS, + VACUUM_GRIPPER_TCP_OFFSET_MM_DEG, + VacuumGripperAdapter, + vacuum_controller_mode_error, + vacuum_io_pins, +) __all__ = [ + "BIO_G2_BLOCKED_MODES", + "BIO_G2_CONTROLLER_VALIDATED", "BIO_G2_JOINT_NAMES", "BIO_GRIPPER_G2_CLOSED_GAP_M", "BIO_GRIPPER_G2_CLOSED_GAP_MM", @@ -77,8 +93,10 @@ "BIO_GRIPPER_G2_OPEN_GAP_MM", "BIO_GRIPPER_G2_SIM_CLOSED_DRIVE", "BIO_GRIPPER_G2_SIM_OPEN_DRIVE", + "BIO_GRIPPER_G2_TCP_IN_FLANGE_M", "BioG2Adapter", "BioGripperG2", + "bio_g2_controller_mode_error", "bio_gripper_g2_gap_m_to_sdk_pos_mm", "bio_gripper_g2_gap_m_to_sim_drive", "bio_gripper_g2_sim_drive_to_gap_m", @@ -127,5 +145,13 @@ "RobotiqAdapter", "Robotiq2F85Adapter", "Robotiq2F140Adapter", + "VACUUM_GRIPPER_COM_FLANGE_MM", + "VACUUM_GRIPPER_MASS_KG", + "VACUUM_GRIPPER_SUPPORTED_ROBOTS", + "VACUUM_GRIPPER_TCP_OFFSET_MM_DEG", + "VacuumGripperAdapter", + "VacuumProfileAdapter", "create_gripper_adapter", + "vacuum_controller_mode_error", + "vacuum_io_pins", ] diff --git a/ufactory/grippers/adapters.py b/ufactory/grippers/adapters.py index ecd9dac..1fa709b 100644 --- a/ufactory/grippers/adapters.py +++ b/ufactory/grippers/adapters.py @@ -11,6 +11,7 @@ from ufactory.grippers.bio_g2 import bio_gripper_g2_gap_m_to_sim_drive, bio_gripper_g2_sim_drive_to_gap_m from ufactory.grippers.g2 import gripper_g2_gap_m_to_sim_drive, gripper_g2_sim_drive_to_gap_m from ufactory.grippers.robotiq import RobotiqSpec, get_robotiq_spec, robotiq_percent_to_register +from ufactory.grippers.vacuum import VacuumGripperAdapter @dataclass(frozen=True) @@ -135,6 +136,37 @@ def send_real_gap(self, arm: object, gap_m: float) -> int: class BioG2Adapter(ConfiguredGripperAdapter): + """Adapter for BIO Gripper G2 over xArm RS-485 Modbus.""" + + SPEED_MIN_RPM = 500 + SPEED_MAX_RPM = 4000 + FORCE_MIN_PERCENT = 1 + FORCE_MAX_PERCENT = 100 + DEDUP_TOL_MM = 0.05 + + def __init__( + self, + profile: GripperProfile, + *, + speed_rpm: float = 2000.0, + force_percent: float = 50.0, + ) -> None: + super().__init__(profile) + self.speed_rpm: int = self._bounded_int(speed_rpm, self.SPEED_MIN_RPM, self.SPEED_MAX_RPM, "speed_rpm") + self.force_percent: int = self._bounded_int( + force_percent, self.FORCE_MIN_PERCENT, self.FORCE_MAX_PERCENT, "force_percent" + ) + self._last_sent_mm: float | None = None + + @staticmethod + def _bounded_int(value: float, lo: int, hi: int, name: str) -> int: + if isinstance(value, bool): + raise ValueError(f"{name} must be finite, in [{lo}, {hi}]") + numeric = float(value) + if not math.isfinite(numeric) or not lo <= numeric <= hi: + raise ValueError(f"{name} must be finite, in [{lo}, {hi}], got {numeric}") + return int(round(numeric)) + def gap_to_drive(self, gap_m: float) -> float: gap = self._finite(gap_m, "gap_m") if not self.profile.closed_gap_m <= gap <= self.profile.open_gap_m: @@ -149,18 +181,38 @@ def drive_to_gap(self, drive: float) -> float: return bio_gripper_g2_sim_drive_to_gap_m(value) def prepare_real(self, arm: object) -> int: + self._last_sent_mm = None code, error = getattr(arm, "get_bio_gripper_error")() if int(code) != 0: return int(code) if int(error) != 0: raise RuntimeError(f"Bio Gripper G2 has error {error}; recover manually before real motion") - return int(getattr(arm, "set_bio_gripper_enable")(True)) + enable_code = int(getattr(arm, "set_bio_gripper_enable")(True)) + if enable_code != 0: + return enable_code + # Pre-cache SDK _bio_gripper_version/_bio_gripper_mode before real-time streaming. + pos_code, _ = getattr(arm, "get_bio_gripper_g2_position")() + return int(pos_code) def send_real_gap(self, arm: object, gap_m: float) -> int: if not self.capabilities.real_command: raise RuntimeError("real Bio Gripper G2 commands are not enabled for this robot profile") + pos_mm = self._finite(gap_m, "gap_m") * 1000.0 + if self._last_sent_mm is not None and abs(pos_mm - self._last_sent_mm) < self.DEDUP_TOL_MM: + return 0 method = getattr(arm, "set_bio_gripper_g2_position") - return int(method(pos=self._finite(gap_m, "gap_m") * 1000.0, wait=False)) + code = int( + method( + pos=pos_mm, + speed=self.speed_rpm, + force=self.force_percent, + wait=False, + wait_motion=False, + ) + ) + if code == 0: + self._last_sent_mm = pos_mm + return code class RobotiqAdapter(ConfiguredGripperAdapter): @@ -245,18 +297,106 @@ class Robotiq2F140Adapter(RobotiqAdapter): """Robotiq 2F-140 adapter.""" +class VacuumProfileAdapter(ConfiguredGripperAdapter): + """0-DOF pneumatic vacuum gripper adapter for runtime GripperProfile streaming.""" + + def __init__(self, profile: GripperProfile, *, hardware_version: int = 1) -> None: + super().__init__(profile) + self._vacuum = VacuumGripperAdapter(hardware_version=hardware_version) + self.hardware_version: int = self._vacuum.hardware_version + self._last_suction_on: bool | None = None + + def gap_to_drive(self, gap_m: float) -> float: + gap = self._finite(gap_m, "gap_m") + if not self.profile.closed_gap_m <= gap <= self.profile.open_gap_m: + raise ValueError(f"gap_m {gap} outside [{self.profile.closed_gap_m}, {self.profile.open_gap_m}]") + return 0.0 + + def drive_to_gap(self, drive: float) -> float: + self._finite(drive, "drive") + return float(self.profile.open_gap_m) + + def prepare_real(self, arm: object) -> int: + self._last_suction_on = None + missing = [ + name + for name in ("set_vacuum_gripper", "get_tgpio_output_digital") + if not callable(getattr(arm, name, None)) + ] + if missing: + raise RuntimeError(f"Vacuum gripper SDK capability is unavailable: {', '.join(missing)}") + # Keep SDK default sync=True: on xArm v2.8.2, sync=False drops one of the two + # back-to-back TGPIO writes in MODE_SERVO (leaving [1, 1] energized), whereas + # sync=True completes in <1 ms and switches both pins reliably. + code = self._vacuum.send_real_suction(arm, False) + if code == 0: + self._last_suction_on = False + return code + + def send_real_gap(self, arm: object, gap_m: float) -> int: + if not self.capabilities.real_command: + raise RuntimeError("real vacuum gripper commands are not enabled for this robot profile") + gap = self._finite(gap_m, "gap_m") + midpoint = (self.profile.open_gap_m + self.profile.closed_gap_m) / 2.0 + suction_on = gap < midpoint + if self._last_suction_on is suction_on: + return 0 + code = self._vacuum.send_real_suction(arm, suction_on) + if code == 0: + self._last_suction_on = suction_on + return code + + def shutdown_real(self, arm: object) -> int: + """Safely release suction on exit without deadlocking in paused controller state. + + ``XArmAPI.set_vacuum_gripper`` is decorated with ``@xarm_wait_until_not_pause``, + which blocks indefinitely after ``execute_real`` pauses the arm (``state=3``). + Check live TGPIO outputs first; if suction is still on while paused/stopped, + fall back to raw ``arm._arm.arm_cmd.tgpio_set_digital`` so the valve turns off + without unpausing arm motion. + """ + get_out = getattr(arm, "get_tgpio_output_digital", None) + if callable(get_out): + out_code, pair = self._vacuum.read_real_output(arm) + if out_code == 0 and pair == (0, 1): + self._last_suction_on = False + return 0 + raw_state = getattr(arm, "state", None) + if isinstance(raw_state, int) and not isinstance(raw_state, bool) and raw_state in (3, 4): + inner = getattr(arm, "_arm", None) + arm_cmd = getattr(inner, "arm_cmd", None) + tgpio_set = getattr(arm_cmd, "tgpio_set_digital", None) + if callable(tgpio_set): + r1 = tgpio_set(self._vacuum.on_pin + 1, 0, sync=True) + r2 = tgpio_set(self._vacuum.off_pin + 1, 1, sync=True) + c1 = int(r1[0]) if isinstance(r1, (list, tuple)) else int(r1) + c2 = int(r2[0]) if isinstance(r2, (list, tuple)) else int(r2) + code = c1 if c2 == 0 else c2 + if code == 0: + self._last_suction_on = False + return code + return 0 + code = self._vacuum.send_real_suction(arm, False) + if code == 0: + self._last_suction_on = False + return code + + _ADAPTERS = { "g2": G2Adapter, "bio_g2": BioG2Adapter, "lite6": Lite6Adapter, "robotiq_2f_85": Robotiq2F85Adapter, "robotiq_2f_140": Robotiq2F140Adapter, + "vacuum_gripper": VacuumProfileAdapter, } -def create_gripper_adapter(profile: GripperProfile) -> GripperAdapter: +def create_gripper_adapter(profile: GripperProfile, *, hardware_version: int = 1) -> GripperAdapter: try: adapter_type = _ADAPTERS[profile.adapter] except KeyError as exc: raise ValueError(f"unknown gripper adapter: {profile.adapter}") from exc + if adapter_type is VacuumProfileAdapter: + return VacuumProfileAdapter(profile, hardware_version=hardware_version) return adapter_type(profile) diff --git a/ufactory/grippers/bio_g2.py b/ufactory/grippers/bio_g2.py index 85230d8..0298d74 100644 --- a/ufactory/grippers/bio_g2.py +++ b/ufactory/grippers/bio_g2.py @@ -46,6 +46,25 @@ BIO_GRIPPER_G2_DEMO_HOLD_S = 0.5 BIO_GRIPPER_G2_ARRIVAL_TOL_MM = 1.0 +# TCP (gripping-ridge centre at bio_gripper_g2_tcp_link) expressed in the xArm flange frame (link6), metres. +BIO_GRIPPER_G2_TCP_IN_FLANGE_M: tuple[float, float, float] = (0.15764, 0.0, 0.05752) + +BIO_G2_BLOCKED_MODES = frozenset(("sdk-sim", "real")) +BIO_G2_CONTROLLER_VALIDATED = frozenset({("pick_place", "xarm6")}) + + +def bio_g2_controller_mode_error(task: str, robot: str, gripper: str, mode: str) -> str | None: + """CLI error for Bio Gripper G2 in a controller mode not yet hardware-validated, else ``None``.""" + if gripper != "bio_gripper_g2" or mode not in BIO_G2_BLOCKED_MODES: + return None + if (task, robot) in BIO_G2_CONTROLLER_VALIDATED: + return None + validated = ", ".join(f"{t} on {r}" for t, r in sorted(BIO_G2_CONTROLLER_VALIDATED)) + return ( + f"--gripper bio_gripper_g2 currently requires --mode sim or dry-run for {task} on {robot}: " + f"Bio Gripper G2 on a real controller has only been validated on hardware for {validated}" + ) + def clamp_bio_gripper_g2_gap_m(gap_m: float) -> float: """Clamp a two-finger gap in metres to the Bio Gripper G2 physical range [0.071, 0.150].""" diff --git a/ufactory/grippers/lite6.py b/ufactory/grippers/lite6.py index 009e733..44ab450 100644 --- a/ufactory/grippers/lite6.py +++ b/ufactory/grippers/lite6.py @@ -35,7 +35,9 @@ LITE6_GRIPPER_FRICTIONLOSS = 0.0 LITE6_GRIPPER_HOLD_BIAS_GAP_M = 0.018 -_FINGER_MESH_DIR = Path(__file__).resolve().parents[2] / "assets" / "urdf" / "lite6_gripper" / "meshes" / "collision" +_FINGER_MESH_DIR = ( + Path(__file__).resolve().parents[2] / "assets" / "urdf" / "end_effectors" / "lite6_gripper" / "meshes" / "collision" +) _FINGER1_VISUAL_ORIGIN_M = np.asarray((0.0, 0.0, 0.0), dtype=np.float64) _FINGER2_VISUAL_ORIGIN_M = np.asarray((0.0, 0.0, 0.0), dtype=np.float64) _FINGER1_VERTS: np.ndarray | None = None diff --git a/ufactory/grippers/vacuum.py b/ufactory/grippers/vacuum.py new file mode 100644 index 0000000..9bfb07c --- /dev/null +++ b/ufactory/grippers/vacuum.py @@ -0,0 +1,88 @@ +"""xArm / UF850 vacuum gripper SDK adapter and TGPIO pin mapping.""" + +from __future__ import annotations + +_VACUUM_IO_PINS: dict[int, tuple[int, int]] = { + 1: (0, 1), + 2: (3, 4), +} + +VACUUM_GRIPPER_SUPPORTED_ROBOTS: frozenset[str] = frozenset({"xarm5", "xarm6", "xarm7", "uf850"}) +VACUUM_GRIPPER_TCP_OFFSET_MM_DEG: tuple[float, float, float, float, float, float] = ( + 0.0, + 0.0, + 126.0, + 0.0, + 0.0, + 0.0, +) +VACUUM_GRIPPER_MASS_KG: float = 0.61 +VACUUM_GRIPPER_COM_FLANGE_MM: tuple[float, float, float] = (0.0, 0.0, 53.0) + + +def vacuum_io_pins(hardware_version: int) -> tuple[int, int]: + """Return ``(on_pin, off_pin)`` TGPIO numbers for vacuum gripper ``hardware_version`` (1 or 2).""" + if isinstance(hardware_version, bool) or not isinstance(hardware_version, int): + raise ValueError(f"hardware_version must be integer 1 or 2, got {hardware_version!r}") + try: + return _VACUUM_IO_PINS[hardware_version] + except KeyError as exc: + raise ValueError(f"unsupported vacuum gripper hardware_version={hardware_version}; expected 1 or 2") from exc + + +def vacuum_controller_mode_error(task: str, robot: str, gripper: str, mode: str) -> str | None: + """Return an error message when a vacuum gripper CLI mode/robot combination is unsupported.""" + if gripper != "vacuum_gripper": + return None + if robot not in VACUUM_GRIPPER_SUPPORTED_ROBOTS: + return "--gripper vacuum_gripper requires --robot xarm5, xarm6, xarm7 or uf850" + if mode == "sim": + return ( + f"vacuum_gripper {task} does not model suction physics for --mode sim; " + "use --mode dry-run, --mode sdk-sim, or --mode real (optionally with --visual)" + ) + return None + + +class VacuumGripperAdapter: + """Adapter for xArm / UF850 pneumatic vacuum gripper driven over TGPIO.""" + + def __init__(self, *, hardware_version: int = 1) -> None: + self.on_pin, self.off_pin = vacuum_io_pins(hardware_version) + self.hardware_version = int(hardware_version) + + def prepare_real(self, arm: object) -> int: + missing = [ + name for name in ("set_vacuum_gripper", "get_vacuum_gripper") if not callable(getattr(arm, name, None)) + ] + if missing: + raise RuntimeError(f"Vacuum gripper SDK capability is unavailable: {', '.join(missing)}") + code, _state = getattr(arm, "get_vacuum_gripper")(hardware_version=self.hardware_version) + return int(code) + + def send_real_suction(self, arm: object, on: bool, *, sync: bool | None = None) -> int: + if isinstance(on, bool): + suction_on = on + elif isinstance(on, (int, float)) and on in (0, 1): + suction_on = bool(on) + else: + raise ValueError(f"on must be a boolean, got {on!r}") + method = getattr(arm, "set_vacuum_gripper") + if sync is None: + return int(method(suction_on, wait=False, hardware_version=self.hardware_version)) + return int(method(suction_on, wait=False, sync=bool(sync), hardware_version=self.hardware_version)) + + def read_real(self, arm: object) -> tuple[int, int]: + code, state = getattr(arm, "get_vacuum_gripper")(hardware_version=self.hardware_version) + return int(code), int(state) + + def read_real_output(self, arm: object) -> tuple[int, tuple[int, int]]: + """Read ``(on_pin, off_pin)`` TGPIO output levels without relying on object-suction detection.""" + code, outputs = getattr(arm, "get_tgpio_output_digital")() + if int(code) != 0: + return int(code), (-1, -1) + values = list(outputs) + max_pin = max(self.on_pin, self.off_pin) + if len(values) <= max_pin: + raise RuntimeError(f"get_tgpio_output_digital returned {len(values)} pins; expected > {max_pin}") + return 0, (int(values[self.on_pin]), int(values[self.off_pin])) diff --git a/ufactory/hardware/__init__.py b/ufactory/hardware/__init__.py index 5ab689b..6580fbb 100644 --- a/ufactory/hardware/__init__.py +++ b/ufactory/hardware/__init__.py @@ -1,5 +1,32 @@ """Real UFACTORY hardware runtime helpers (xArm5/6/7, Lite6, UF850 via the xArm Python SDK).""" +from ufactory.hardware.ft_sensor import ( + AI1500_COM_FLANGE_MM, + AI1500_MASS_KG, + AI1500_NAME, + AI1500_OVERLOAD, + AI1500_RANGE, + AI1500_RESOLUTION, + AI1500_SAMPLE_RATE_HZ, + AI1500_TOOL_OFFSET_Z_MM, + FT_COORD_BASE, + FT_COORD_TOOL, + FT_COORDS, + FT_MODE_ADMITTANCE, + FT_MODE_FORCE, + FT_MODE_OFF, + FT_MODES, + FT_SENSOR_ERROR_DESCRIPTIONS, + FTAdmittanceParams, + FTCollisionConfig, + FTForceControlParams, + FTLoadOffset, + FTSensorConfigSnapshot, + FTSensorReading, + FTSensorStatus, + XArmFTSensor, + describe_ft_sensor_error, +) from ufactory.hardware.session import ( MOVE_STRATEGIES, MOVE_STRATEGY_AXIS_SEQUENTIAL, @@ -41,4 +68,29 @@ "prepare_arm_for_motion", "verify_controller_robot", "XArmTransport", + "AI1500_COM_FLANGE_MM", + "AI1500_MASS_KG", + "AI1500_NAME", + "AI1500_OVERLOAD", + "AI1500_RANGE", + "AI1500_RESOLUTION", + "AI1500_SAMPLE_RATE_HZ", + "AI1500_TOOL_OFFSET_Z_MM", + "FT_COORD_BASE", + "FT_COORD_TOOL", + "FT_COORDS", + "FT_MODE_ADMITTANCE", + "FT_MODE_FORCE", + "FT_MODE_OFF", + "FT_MODES", + "FT_SENSOR_ERROR_DESCRIPTIONS", + "FTAdmittanceParams", + "FTCollisionConfig", + "FTForceControlParams", + "FTLoadOffset", + "FTSensorConfigSnapshot", + "FTSensorReading", + "FTSensorStatus", + "XArmFTSensor", + "describe_ft_sensor_error", ] diff --git a/ufactory/hardware/ft_sensor.py b/ufactory/hardware/ft_sensor.py new file mode 100644 index 0000000..c059ae9 --- /dev/null +++ b/ufactory/hardware/ft_sensor.py @@ -0,0 +1,830 @@ +"""Real UFACTORY six-axis Force/Torque sensor (AI1500) SDK control and safety wrapper.""" + +from __future__ import annotations + +from collections.abc import Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +import math +import time +from typing import Any, Protocol + +import numpy as np + +from ufactory.hardware.xarm import MODE_POSITION, STATE_MOTION, assert_motion_ready, prepare_arm_for_motion +from ufactory.robots.assembly import supports_ft_sensor +from ufactory.robots.registry import get_profile_key_for_robot_name + +# F/T controller application modes (XArmAPI.set_ft_sensor_mode). +FT_MODE_OFF = 0 +FT_MODE_ADMITTANCE = 1 +FT_MODE_FORCE = 2 +FT_MODES: tuple[int, ...] = (FT_MODE_OFF, FT_MODE_ADMITTANCE, FT_MODE_FORCE) + +# F/T task coordinate frames. +FT_COORD_BASE = 0 +FT_COORD_TOOL = 1 +FT_COORDS: tuple[int, ...] = (FT_COORD_BASE, FT_COORD_TOOL) + +# AI1500 official hardware specifications & Studio defaults. +AI1500_NAME = "ft_sensor_ai1500" +AI1500_TOOL_OFFSET_Z_MM = 58.6 +AI1500_MASS_KG = 0.6 +AI1500_COM_FLANGE_MM: tuple[float, float, float] = (0.0, 0.0, 22.0) +AI1500_SAMPLE_RATE_HZ = 200.0 +AI1500_RESOLUTION: tuple[float, float, float, float, float, float] = (0.4, 0.4, 0.4, 0.01, 0.01, 0.01) +AI1500_RANGE: tuple[float, float, float, float, float, float] = (400.0, 400.0, 400.0, 20.0, 20.0, 20.0) +AI1500_OVERLOAD: tuple[float, float, float, float, float, float] = (600.0, 600.0, 600.0, 30.0, 30.0, 30.0) + +# xArm Python SDK (v1.18.4) parameter bounds. +ADMITTANCE_M_LINEAR_BOUNDS: tuple[float, float] = (0.02, 1.0) +ADMITTANCE_M_ANGULAR_BOUNDS: tuple[float, float] = (0.0001, 0.01) +ADMITTANCE_K_LINEAR_BOUNDS: tuple[float, float] = (0.0, 2000.0) +ADMITTANCE_K_ANGULAR_BOUNDS: tuple[float, float] = (0.0, 20.0) +ADMITTANCE_THRESHOLD_FORCE_BOUNDS: tuple[float, float] = (0.1, 50.0) +ADMITTANCE_THRESHOLD_TORQUE_BOUNDS: tuple[float, float] = (0.01, 2.0) + +FORCE_REF_LIMITS: tuple[float, float, float, float, float, float] = (150.0, 150.0, 200.0, 4.0, 4.0, 4.0) +FORCE_KP_BOUNDS: tuple[float, float] = (0.0, 0.05) +FORCE_KI_BOUNDS: tuple[float, float] = (0.0, 0.0005) +FORCE_KD_BOUNDS: tuple[float, float] = (0.0, 0.05) +FORCE_XE_LIMIT_BOUNDS: tuple[float, float] = (0.0, 200.0) + +COLLISION_FORCE_THRESHOLD_BOUNDS: tuple[float, float] = (5.0, 200.0) +COLLISION_TORQUE_THRESHOLD_BOUNDS: tuple[float, float] = (0.1, 4.0) +COLLISION_REBOUND_POS_MM_BOUNDS: tuple[float, float] = (2.0, 500.0) +COLLISION_REBOUND_ROT_DEG_BOUNDS: tuple[float, float] = (0.2, 50.0) + +# Mirrors xarm.core.config.x_code.FtSensorErrorCodeMap. +FT_SENSOR_ERROR_DESCRIPTIONS: dict[int, str] = { + 0: "Normal", + 64: "Six-axis Force Torque Sensor Communication Failure", + 65: "The Data Collected by the Six-axis Force Torque Sensor is Abnormal", + 66: "Six-axis Force Torque Sensor Fx Exceeds Limit", + 67: "Six-axis Force Torque Sensor Fy Exceeds Limit", + 68: "Six-axis Force Torque Sensor Fz Exceeds Limit", + 69: "Six-axis Force Torque Sensor Tx Exceeds Limit", + 70: "Six-axis Force Torque Sensor Ty Exceeds Limit", + 71: "Six-axis Force Torque Sensor Tz Exceeds Limit", + 73: "Six-axis Force Torque Sensor Failed to Initialize", +} + + +class FTSensorSDK(Protocol): + """Minimal structural protocol covering XArmAPI F/T sensor attributes and methods.""" + + state: int + mode: int + error_code: int + warn_code: int + + @property + def ft_raw_force(self) -> Sequence[float]: ... + + @property + def ft_ext_force(self) -> Sequence[float]: ... + + def get_state(self) -> tuple[int, int]: ... + + def motion_enable(self, enable: bool = True, **kwargs: Any) -> int: ... + + def set_mode(self, mode: int = 0, **kwargs: Any) -> int: ... + + def set_state(self, state: int = 0) -> int: ... + + def set_ft_sensor_enable(self, on_off: int | bool) -> int: ... + + def set_ft_sensor_mode(self, mode: int, **kwargs: Any) -> int: ... + + def get_ft_sensor_mode(self) -> tuple[int, int]: ... + + def set_ft_sensor_zero(self) -> int: ... + + def iden_ft_sensor_load_offset(self) -> tuple[int, Sequence[float]]: ... + + def set_ft_sensor_load_offset( + self, + iden_result_list: list[float], + association_setting_tcp_load: bool = False, + **kwargs: Any, + ) -> int: ... + + def set_ft_sensor_admittance_parameters( + self, + coord: int | None = None, + c_axis: Sequence[int] | None = None, + M: Sequence[float] | None = None, + K: Sequence[float] | None = None, + B: Sequence[float] | None = None, + **kwargs: Any, + ) -> int: ... + + def set_ft_sensor_force_parameters( + self, + coord: int | None = None, + c_axis: Sequence[int] | None = None, + f_ref: Sequence[float] | None = None, + limits: Sequence[float] | None = None, + kp: Sequence[float] | None = None, + ki: Sequence[float] | None = None, + kd: Sequence[float] | None = None, + xe_limit: Sequence[float] | None = None, + **kwargs: Any, + ) -> int: ... + + def get_ft_sensor_data(self, is_raw: bool = False) -> tuple[int, Sequence[float]]: ... + + def get_ft_sensor_config(self) -> tuple[int, Sequence[Any]]: ... + + def get_ft_sensor_error(self) -> tuple[int, int]: ... + + def get_ft_sensor_sn(self) -> tuple[int, str]: ... + + def get_ft_sensor_version(self) -> tuple[int, str]: ... + + def set_ft_collision_detection(self, on_off: int | bool) -> int: ... + + def get_ft_collision_detection(self) -> tuple[int, int]: ... + + def set_ft_collision_threshold(self, thresholds: list[float]) -> int: ... + + def get_ft_collision_threshold(self) -> tuple[int, Sequence[float]]: ... + + def set_ft_collision_rebound(self, on_off: int | bool) -> int: ... + + def get_ft_collision_rebound(self) -> tuple[int, int]: ... + + def set_ft_collision_reb_distance(self, distances: list[float], is_radian: bool | None = None) -> int: ... + + def get_ft_collision_reb_distance(self, is_radian: bool | None = None) -> tuple[int, Sequence[float]]: ... + + def set_ft_admittance_ctrl_threshold(self, thresholds: list[float]) -> int: ... + + def get_ft_admittance_ctrl_threshold(self) -> tuple[int, Sequence[float]]: ... + + +def describe_ft_sensor_error(code: int) -> str: + """Return a human-readable message for an xArm six-axis F/T sensor error code.""" + if isinstance(code, bool) or not isinstance(code, int): + raise ValueError(f"error code must be an int, got {code!r}") + if code in FT_SENSOR_ERROR_DESCRIPTIONS: + return FT_SENSOR_ERROR_DESCRIPTIONS[code] + return f"Six-axis Force Torque Sensor Error (code={code})" + + +def _finite_float(value: Any, name: str) -> float: + if isinstance(value, bool): + raise ValueError(f"{name} must be a finite number, not bool") + num = float(value) + if not math.isfinite(num): + raise ValueError(f"{name} must be finite, got {value!r}") + return num + + +def _finite_vector(values: Sequence[Any], length: int, name: str) -> tuple[float, ...]: + if isinstance(values, (str, bytes)): + raise ValueError(f"{name} must be a sequence of {length} finite floats") + seq = tuple(_finite_float(v, f"{name}[{i}]") for i, v in enumerate(values)) + if len(seq) != length: + raise ValueError(f"{name} must have length {length}, got {len(seq)}") + return seq + + +def _bounded_vector( + values: Sequence[Any], + bounds: Sequence[tuple[float, float]], + name: str, +) -> tuple[float, ...]: + vec = _finite_vector(values, len(bounds), name) + for i, (val, (lo, hi)) in enumerate(zip(vec, bounds, strict=True)): + if not (lo <= val <= hi): + raise ValueError(f"{name}[{i}]={val} outside [{lo}, {hi}]") + return vec + + +def _binary_axis_mask(values: Sequence[Any], name: str) -> tuple[int, ...]: + if isinstance(values, (str, bytes)): + raise ValueError(f"{name} must be a 6-element binary mask") + items = list(values) + if len(items) != 6: + raise ValueError(f"{name} must have length 6, got {len(items)}") + out: list[int] = [] + for i, val in enumerate(items): + if isinstance(val, bool) or not isinstance(val, (int, np.integer)): + raise ValueError(f"{name}[{i}] must be integer 0 or 1, got {val!r}") + ival = int(val) + if ival not in (0, 1): + raise ValueError(f"{name}[{i}] must be 0 or 1, got {ival}") + out.append(ival) + return tuple(out) + + +def _check_int_choice(value: Any, allowed: tuple[int, ...], name: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, np.integer)): + raise ValueError(f"{name} must be an integer in {allowed}, got {value!r}") + ival = int(value) + if ival not in allowed: + raise ValueError(f"{name} must be in {allowed}, got {ival}") + return ival + + +def _check_bool(value: Any, name: str) -> bool: + if not isinstance(value, bool): + raise TypeError(f"{name} must be a bool, got {type(value).__name__}") + return value + + +def _check_sdk_code(label: str, code: Any) -> None: + if int(code) != 0: + raise RuntimeError(f"{label} failed with SDK code {int(code)}") + + +def _unwrap_sdk_tuple(label: str, result: Any) -> Any: + if not isinstance(result, (tuple, list)) or len(result) < 2: + raise RuntimeError(f"{label} returned unexpected response {result!r}") + _check_sdk_code(label, result[0]) + return result[1] + + +@dataclass(frozen=True) +class FTSensorReading: + """Six-axis wrench reading ``[Fx, Fy, Fz, Tx, Ty, Tz]`` in ``[N, Nm]``.""" + + wrench: tuple[float, float, float, float, float, float] + is_raw: bool + monotonic_ns: int + overrange: tuple[bool, bool, bool, bool, bool, bool] + overload: tuple[bool, bool, bool, bool, bool, bool] + + def __post_init__(self) -> None: + vec = _finite_vector(self.wrench, 6, "wrench") + object.__setattr__(self, "wrench", vec) + if len(self.overrange) != 6 or not all(isinstance(v, bool) for v in self.overrange): + raise ValueError("overrange must contain 6 booleans") + if len(self.overload) != 6 or not all(isinstance(v, bool) for v in self.overload): + raise ValueError("overload must contain 6 booleans") + + @classmethod + def from_wrench( + cls, + wrench: Sequence[float], + *, + is_raw: bool, + monotonic_ns: int | None = None, + ) -> FTSensorReading: + vec = _finite_vector(wrench, 6, "wrench") + overrange = tuple(abs(val) > limit for val, limit in zip(vec, AI1500_RANGE, strict=True)) + overload = tuple(abs(val) >= limit for val, limit in zip(vec, AI1500_OVERLOAD, strict=True)) + return cls( + wrench=(vec[0], vec[1], vec[2], vec[3], vec[4], vec[5]), + is_raw=bool(is_raw), + monotonic_ns=time.monotonic_ns() if monotonic_ns is None else int(monotonic_ns), + overrange=(overrange[0], overrange[1], overrange[2], overrange[3], overrange[4], overrange[5]), + overload=(overload[0], overload[1], overload[2], overload[3], overload[4], overload[5]), + ) + + @property + def force_n(self) -> tuple[float, float, float]: + return self.wrench[:3] + + @property + def torque_nm(self) -> tuple[float, float, float]: + return self.wrench[3:] + + @property + def any_overrange(self) -> bool: + return any(self.overrange) + + @property + def any_overload(self) -> bool: + return any(self.overload) + + def as_array(self) -> np.ndarray: + arr: np.ndarray = np.asarray(self.wrench, dtype=np.float64) + return arr + + +@dataclass(frozen=True) +class FTLoadOffset: + """Identified or configured tool load & sensor zero-offset parameters.""" + + mass_kg: float + centroid_mm: tuple[float, float, float] + wrench_offset: tuple[float, float, float, float, float, float] + + def __post_init__(self) -> None: + mass = _finite_float(self.mass_kg, "mass_kg") + if mass < 0.0: + raise ValueError(f"mass_kg must be non-negative, got {mass}") + centroid = _finite_vector(self.centroid_mm, 3, "centroid_mm") + offset = _finite_vector(self.wrench_offset, 6, "wrench_offset") + object.__setattr__(self, "mass_kg", mass) + object.__setattr__(self, "centroid_mm", (centroid[0], centroid[1], centroid[2])) + object.__setattr__( + self, + "wrench_offset", + (offset[0], offset[1], offset[2], offset[3], offset[4], offset[5]), + ) + + @classmethod + def from_sdk_list(cls, values: Sequence[float]) -> FTLoadOffset: + vec = _finite_vector(values, 10, "load_offset") + return cls( + mass_kg=vec[0], + centroid_mm=(vec[1], vec[2], vec[3]), + wrench_offset=(vec[4], vec[5], vec[6], vec[7], vec[8], vec[9]), + ) + + def to_sdk_list(self) -> list[float]: + return [self.mass_kg, *self.centroid_mm, *self.wrench_offset] + + +@dataclass(frozen=True) +class FTAdmittanceParams: + """Parameters for ``XArmAPI.set_ft_sensor_admittance_parameters`` (``mode=1``).""" + + coord: int + c_axis: tuple[int, ...] + M: tuple[float, ...] + K: tuple[float, ...] + B: tuple[float, ...] + + def __post_init__(self) -> None: + coord = _check_int_choice(self.coord, FT_COORDS, "coord") + c_axis = _binary_axis_mask(self.c_axis, "c_axis") + m_bounds = (ADMITTANCE_M_LINEAR_BOUNDS,) * 3 + (ADMITTANCE_M_ANGULAR_BOUNDS,) * 3 + k_bounds = (ADMITTANCE_K_LINEAR_BOUNDS,) * 3 + (ADMITTANCE_K_ANGULAR_BOUNDS,) * 3 + b_bounds = ((0.0, math.inf),) * 6 + object.__setattr__(self, "coord", coord) + object.__setattr__(self, "c_axis", c_axis) + object.__setattr__(self, "M", _bounded_vector(self.M, m_bounds, "M")) + object.__setattr__(self, "K", _bounded_vector(self.K, k_bounds, "K")) + object.__setattr__(self, "B", _bounded_vector(self.B, b_bounds, "B")) + + +@dataclass(frozen=True) +class FTForceControlParams: + """Parameters for ``XArmAPI.set_ft_sensor_force_parameters`` (``mode=2``).""" + + coord: int + c_axis: tuple[int, ...] + f_ref: tuple[float, ...] + limits: tuple[float, ...] + kp: tuple[float, ...] + ki: tuple[float, ...] + kd: tuple[float, ...] + xe_limit: tuple[float, ...] + + def __post_init__(self) -> None: + coord = _check_int_choice(self.coord, FT_COORDS, "coord") + c_axis = _binary_axis_mask(self.c_axis, "c_axis") + f_ref_bounds = tuple((-lim, lim) for lim in FORCE_REF_LIMITS) + limit_bounds = ((0.0, math.inf),) * 6 + object.__setattr__(self, "coord", coord) + object.__setattr__(self, "c_axis", c_axis) + object.__setattr__(self, "f_ref", _bounded_vector(self.f_ref, f_ref_bounds, "f_ref")) + object.__setattr__(self, "limits", _bounded_vector(self.limits, limit_bounds, "limits")) + object.__setattr__(self, "kp", _bounded_vector(self.kp, (FORCE_KP_BOUNDS,) * 6, "kp")) + object.__setattr__(self, "ki", _bounded_vector(self.ki, (FORCE_KI_BOUNDS,) * 6, "ki")) + object.__setattr__(self, "kd", _bounded_vector(self.kd, (FORCE_KD_BOUNDS,) * 6, "kd")) + object.__setattr__(self, "xe_limit", _bounded_vector(self.xe_limit, (FORCE_XE_LIMIT_BOUNDS,) * 6, "xe_limit")) + + +@dataclass(frozen=True) +class FTCollisionConfig: + """F/T collision detection and rebound configuration snapshot.""" + + enabled: bool + thresholds: tuple[float, ...] + rebound_enabled: bool + rebound_distance: tuple[float, ...] + is_radian: bool = True + + def __post_init__(self) -> None: + object.__setattr__(self, "enabled", bool(self.enabled)) + object.__setattr__(self, "rebound_enabled", bool(self.rebound_enabled)) + object.__setattr__(self, "thresholds", _finite_vector(self.thresholds, 6, "collision_thresholds")) + object.__setattr__(self, "rebound_distance", _finite_vector(self.rebound_distance, 6, "rebound_distance")) + object.__setattr__(self, "is_radian", _check_bool(self.is_radian, "is_radian")) + + +@dataclass(frozen=True) +class FTSensorConfigSnapshot: + """Typed snapshot of the 22-element list returned by ``get_ft_sensor_config()``.""" + + ft_mode: int + ft_enabled: bool + ft_type: int + ft_id: int + ft_freq: int + ft_mass_kg: float + ft_dir_bias: float + ft_centroid: tuple[float, float, float] + ft_zero: tuple[float, float, float, float, float, float] + imp_coord: int + imp_c_axis: tuple[int, ...] + M: tuple[float, ...] + K: tuple[float, ...] + B: tuple[float, ...] + f_coord: int + f_c_axis: tuple[int, ...] + f_ref: tuple[float, ...] + f_limits: tuple[float, ...] + kp: tuple[float, ...] + ki: tuple[float, ...] + kd: tuple[float, ...] + xe_limit: tuple[float, ...] + + @classmethod + def from_sdk_config(cls, config: Sequence[Any]) -> FTSensorConfigSnapshot: + if len(config) < 22: + raise ValueError(f"expected at least 22 elements from get_ft_sensor_config(), got {len(config)}") + centroid = _finite_vector(config[7], 3, "ft_centroid") + zero = _finite_vector(config[8], 6, "ft_zero") + return cls( + ft_mode=int(config[0]), + ft_enabled=bool(config[1]), + ft_type=int(config[2]), + ft_id=int(config[3]), + ft_freq=int(config[4]), + ft_mass_kg=_finite_float(config[5], "ft_mass"), + ft_dir_bias=_finite_float(config[6], "ft_dir_bias"), + ft_centroid=(centroid[0], centroid[1], centroid[2]), + ft_zero=(zero[0], zero[1], zero[2], zero[3], zero[4], zero[5]), + imp_coord=int(config[9]), + imp_c_axis=tuple(int(v) for v in config[10][:6]), + M=_finite_vector(config[11][:6], 6, "M"), + K=_finite_vector(config[12][:6], 6, "K"), + B=_finite_vector(config[13][:6], 6, "B"), + f_coord=int(config[14]), + f_c_axis=tuple(int(v) for v in config[15][:6]), + f_ref=_finite_vector(config[16][:6], 6, "f_ref"), + f_limits=_finite_vector(config[17][:6], 6, "f_limits"), + kp=_finite_vector(config[18][:6], 6, "kp"), + ki=_finite_vector(config[19][:6], 6, "ki"), + kd=_finite_vector(config[20][:6], 6, "kd"), + xe_limit=_finite_vector(config[21][:6], 6, "xe_limit"), + ) + + +@dataclass(frozen=True) +class FTSensorStatus: + """High-level status of the attached F/T sensor.""" + + mode: int + error_code: int + error_message: str + enabled: bool | None = None + serial_number: str | None = None + firmware_version: str | None = None + + +def validate_admittance_threshold(thresholds: Sequence[float]) -> tuple[float, ...]: + bounds = (ADMITTANCE_THRESHOLD_FORCE_BOUNDS,) * 3 + (ADMITTANCE_THRESHOLD_TORQUE_BOUNDS,) * 3 + return _bounded_vector(thresholds, bounds, "admittance_threshold") + + +def validate_collision_thresholds(thresholds: Sequence[float]) -> tuple[float, ...]: + bounds = (COLLISION_FORCE_THRESHOLD_BOUNDS,) * 3 + (COLLISION_TORQUE_THRESHOLD_BOUNDS,) * 3 + return _bounded_vector(thresholds, bounds, "collision_thresholds") + + +def validate_collision_rebound_distance(distances: Sequence[float], *, is_radian: bool = True) -> tuple[float, ...]: + lo_deg, hi_deg = COLLISION_REBOUND_ROT_DEG_BOUNDS + rot_bounds = (math.radians(lo_deg), math.radians(hi_deg)) if is_radian else (lo_deg, hi_deg) + bounds = (COLLISION_REBOUND_POS_MM_BOUNDS,) * 3 + (rot_bounds,) * 3 + return _bounded_vector(distances, bounds, "rebound_distance") + + +class XArmFTSensor: + """Fail-closed wrapper around XArmAPI six-axis Force/Torque sensor commands. + + Physical activation (``identify_load_offset`` and entering active force/admittance + modes ``1`` or ``2``) requires ``confirm_real=True`` and a fault-free controller + plus fault-free F/T sensor. It never calls ``clean_error()`` or ``clean_warn()``. + """ + + def __init__( + self, + arm: FTSensorSDK | Any, + *, + robot_key: str | None = None, + sensor_name: str = AI1500_NAME, + ) -> None: + if robot_key is not None: + resolved_key = get_profile_key_for_robot_name(robot_key) + if not supports_ft_sensor(resolved_key, sensor_name): + raise ValueError(f"Robot {resolved_key} does not support F/T sensor {sensor_name}") + self.robot_key: str | None = resolved_key + else: + self.robot_key = None + self.arm = arm + self.sensor_name = sensor_name + + def _assert_healthy_for_active_ft(self) -> None: + assert_motion_ready(self.arm) + if int(getattr(self.arm, "warn_code", 0)) != 0: + raise RuntimeError( + f"Controller has active warning warn_code={getattr(self.arm, 'warn_code', None)}; " + "inspect and recover manually in UFACTORY Studio" + ) + err_code, err_msg = self.read_error() + if err_code != 0: + raise RuntimeError(f"F/T sensor has active error {err_code}: {err_msg}") + + # --- Read-only queries (no motion, no confirm_real needed) --- + + def read_config(self) -> FTSensorConfigSnapshot: + raw_cfg = _unwrap_sdk_tuple("get_ft_sensor_config", self.arm.get_ft_sensor_config()) + return FTSensorConfigSnapshot.from_sdk_config(raw_cfg) + + def read_mode(self) -> int: + mode = _unwrap_sdk_tuple("get_ft_sensor_mode", self.arm.get_ft_sensor_mode()) + return _check_int_choice(mode, FT_MODES, "ft_mode") + + def read_error(self) -> tuple[int, str]: + err = _unwrap_sdk_tuple("get_ft_sensor_error", self.arm.get_ft_sensor_error()) + code = int(err) + return code, describe_ft_sensor_error(code) + + def _resolve_sdk_method(self, name: str) -> Any: + """Resolve an F/T SDK method on ``self.arm`` or fallback to ``self.arm._arm``. + + ``xarm-python-sdk`` 1.18.4 implements ``get_ft_sensor_sn`` and + ``get_ft_sensor_version`` on the underlying ``XArm`` instance (``arm._arm``) + without forwarding them on ``XArmAPI``. + """ + fn = getattr(self.arm, name, None) + if callable(fn): + return fn + inner = getattr(self.arm, "_arm", None) + inner_fn = getattr(inner, name, None) if inner is not None else None + if callable(inner_fn): + return inner_fn + raise RuntimeError(f"Connected xArm SDK object does not expose {name}()") + + def read_serial_number(self) -> str: + sn = _unwrap_sdk_tuple("get_ft_sensor_sn", self._resolve_sdk_method("get_ft_sensor_sn")()) + text = str(sn).strip() + if not text or set(text) == {"*"}: + raise RuntimeError(f"Invalid F/T sensor serial number readback: {sn!r}") + return text + + def read_firmware_version(self) -> str: + ver = _unwrap_sdk_tuple("get_ft_sensor_version", self._resolve_sdk_method("get_ft_sensor_version")()) + text = str(ver).strip() + if not text: + raise RuntimeError(f"Invalid F/T sensor version readback: {ver!r}") + return text + + def read_status(self, *, include_identity: bool = False) -> FTSensorStatus: + mode = self.read_mode() + err_code, err_msg = self.read_error() + enabled: bool | None = None + config_getter = getattr(self.arm, "get_ft_sensor_config", None) + if callable(config_getter): + enabled = self.read_config().ft_enabled + serial_number = self.read_serial_number() if include_identity else None + firmware_version = self.read_firmware_version() if include_identity else None + return FTSensorStatus( + mode=mode, + error_code=err_code, + error_message=err_msg, + enabled=enabled, + serial_number=serial_number, + firmware_version=firmware_version, + ) + + def read_wrench(self, *, is_raw: bool = False, from_report: bool = False) -> FTSensorReading: + raw_flag = _check_bool(is_raw, "is_raw") + report_flag = _check_bool(from_report, "from_report") + if report_flag: + values = self.arm.ft_raw_force if raw_flag else self.arm.ft_ext_force + else: + values = _unwrap_sdk_tuple("get_ft_sensor_data", self.arm.get_ft_sensor_data(is_raw=raw_flag)) + return FTSensorReading.from_wrench(values, is_raw=raw_flag) + + def read_admittance_threshold(self) -> tuple[float, ...]: + values = _unwrap_sdk_tuple( + "get_ft_admittance_ctrl_threshold", + self.arm.get_ft_admittance_ctrl_threshold(), + ) + return _finite_vector(values[:6], 6, "admittance_threshold") + + def read_collision_config(self, *, is_radian: bool = True) -> FTCollisionConfig: + rad_flag = _check_bool(is_radian, "is_radian") + enabled = bool(_unwrap_sdk_tuple("get_ft_collision_detection", self.arm.get_ft_collision_detection())) + thresholds = _unwrap_sdk_tuple("get_ft_collision_threshold", self.arm.get_ft_collision_threshold()) + rebound_enabled = bool(_unwrap_sdk_tuple("get_ft_collision_rebound", self.arm.get_ft_collision_rebound())) + rebound_distance = _unwrap_sdk_tuple( + "get_ft_collision_reb_distance", + self.arm.get_ft_collision_reb_distance(is_radian=rad_flag), + ) + return FTCollisionConfig( + enabled=enabled, + thresholds=_finite_vector(thresholds[:6], 6, "collision_thresholds"), + rebound_enabled=rebound_enabled, + rebound_distance=_finite_vector(rebound_distance[:6], 6, "rebound_distance"), + is_radian=rad_flag, + ) + + # --- Sensor enable, zeroing & load identification --- + + def set_enable(self, enabled: bool) -> None: + flag = _check_bool(enabled, "enabled") + _check_sdk_code(f"set_ft_sensor_enable({flag})", self.arm.set_ft_sensor_enable(flag)) + + def zero(self, *, settle_s: float = 0.2) -> None: + """Zero static F/T bias and wait briefly for controller write-through. + + Note: In xArm firmware, ``set_ft_sensor_zero`` overwrites prior sensor zero + offset and payload compensation; official SDK examples wait ``0.2 s`` after + calling it so the updated offset takes effect before reading or activating + force modes. + """ + wait_s = _finite_float(settle_s, "settle_s") + if wait_s < 0.0: + raise ValueError(f"settle_s must be non-negative, got {wait_s}") + self._assert_healthy_for_active_ft() + _check_sdk_code("set_ft_sensor_zero", self.arm.set_ft_sensor_zero()) + if wait_s > 0.0: + time.sleep(wait_s) + + def identify_load_offset(self, *, confirm_real: bool = False) -> FTLoadOffset: + if not confirm_real: + raise RuntimeError("identify_load_offset drives physical robot poses; pass confirm_real=True to execute") + self._assert_healthy_for_active_ft() + prepare_arm_for_motion(self.arm, mode=MODE_POSITION) + raw = self.arm.iden_ft_sensor_load_offset() + if isinstance(raw, (tuple, list)) and len(raw) >= 1 and int(raw[0]) == 10: + raise RuntimeError( + "iden_ft_sensor_load_offset failed with SDK code 10 (RET_IS_INVALID); " + "ensure a rigid external payload is mounted (bare sensor mass ~0 kg can make centroid " + "identification ill-conditioned) and the arm has workspace clearance" + ) + values = _unwrap_sdk_tuple("iden_ft_sensor_load_offset", raw) + return FTLoadOffset.from_sdk_list(values) + + def set_load_offset(self, offset: FTLoadOffset, *, update_tcp_load: bool = False) -> None: + """Write identified F/T load/zero offset to the controller. + + Note: ``xarm-python-sdk`` 1.18.4's ``association_setting_tcp_load=True`` uses + hardcoded legacy-sensor mass/CoM defaults (0.270 kg) with mixed m/mm units; for + AI1500 keep ``update_tcp_load=False`` and configure controller TCP load/offset + explicitly. + """ + flag = _check_bool(update_tcp_load, "update_tcp_load") + code = self.arm.set_ft_sensor_load_offset(offset.to_sdk_list(), association_setting_tcp_load=flag) + _check_sdk_code("set_ft_sensor_load_offset", code) + + # --- Force / admittance / collision configuration & mode switching --- + + def configure_admittance( + self, + params: FTAdmittanceParams, + *, + reaction_threshold: Sequence[float] | None = None, + ) -> None: + validated_threshold = ( + validate_admittance_threshold(reaction_threshold) if reaction_threshold is not None else None + ) + _check_sdk_code( + "set_ft_sensor_admittance_parameters", + self.arm.set_ft_sensor_admittance_parameters( + coord=params.coord, + c_axis=list(params.c_axis), + M=list(params.M), + K=list(params.K), + B=list(params.B), + ), + ) + if validated_threshold is not None: + _check_sdk_code( + "set_ft_admittance_ctrl_threshold", + self.arm.set_ft_admittance_ctrl_threshold(list(validated_threshold)), + ) + + def configure_force_control(self, params: FTForceControlParams) -> None: + _check_sdk_code( + "set_ft_sensor_force_parameters", + self.arm.set_ft_sensor_force_parameters( + coord=params.coord, + c_axis=list(params.c_axis), + f_ref=list(params.f_ref), + limits=list(params.limits), + kp=list(params.kp), + ki=list(params.ki), + kd=list(params.kd), + xe_limit=list(params.xe_limit), + ), + ) + + def configure_collision_detection( + self, + *, + enabled: bool | None = None, + thresholds: Sequence[float] | None = None, + rebound: bool | None = None, + rebound_distance: Sequence[float] | None = None, + is_radian: bool = True, + ) -> None: + rad_flag = _check_bool(is_radian, "is_radian") + validated_thresholds = validate_collision_thresholds(thresholds) if thresholds is not None else None + validated_distance = ( + validate_collision_rebound_distance(rebound_distance, is_radian=rad_flag) + if rebound_distance is not None + else None + ) + enabled_flag = _check_bool(enabled, "enabled") if enabled is not None else None + rebound_flag = _check_bool(rebound, "rebound") if rebound is not None else None + + if validated_thresholds is not None: + _check_sdk_code( + "set_ft_collision_threshold", self.arm.set_ft_collision_threshold(list(validated_thresholds)) + ) + if validated_distance is not None: + _check_sdk_code( + "set_ft_collision_reb_distance", + self.arm.set_ft_collision_reb_distance(list(validated_distance), is_radian=rad_flag), + ) + if rebound_flag is not None: + _check_sdk_code("set_ft_collision_rebound", self.arm.set_ft_collision_rebound(rebound_flag)) + if enabled_flag is not None: + _check_sdk_code("set_ft_collision_detection", self.arm.set_ft_collision_detection(enabled_flag)) + + def set_mode(self, mode: int, *, confirm_real: bool = False) -> None: + target_mode = _check_int_choice(mode, FT_MODES, "mode") + if target_mode != FT_MODE_OFF: + if not confirm_real: + raise RuntimeError( + f"Entering active F/T mode {target_mode} allows physical motion; pass confirm_real=True" + ) + self._assert_healthy_for_active_ft() + prepare_arm_for_motion(self.arm, mode=MODE_POSITION) + _check_sdk_code(f"set_ft_sensor_mode({target_mode})", self.arm.set_ft_sensor_mode(target_mode)) + if target_mode != FT_MODE_OFF: + # Switching into admittance/force mode leaves controller in state=5 until set_state(0). + _check_sdk_code("set_state(0)", self.arm.set_state(STATE_MOTION)) + + def stop_force_mode(self, *, disable_sensor: bool = False) -> None: + disable_flag = _check_bool(disable_sensor, "disable_sensor") + mode_code = self.arm.set_ft_sensor_mode(FT_MODE_OFF) + disable_code = 0 + if disable_flag: + disable_code = self.arm.set_ft_sensor_enable(False) + _check_sdk_code("set_ft_sensor_mode(0)", mode_code) + if disable_flag: + _check_sdk_code("set_ft_sensor_enable(False)", disable_code) + + @contextmanager + def admittance_session( + self, + params: FTAdmittanceParams, + *, + confirm_real: bool = False, + reaction_threshold: Sequence[float] | None = None, + zero_on_enter: bool = False, + disable_on_exit: bool = False, + ) -> Iterator[XArmFTSensor]: + """Enter admittance control safely and always exit back to ``FT_MODE_OFF``.""" + if not confirm_real: + raise RuntimeError("admittance_session enables physical motion; pass confirm_real=True") + zero_flag = _check_bool(zero_on_enter, "zero_on_enter") + disable_flag = _check_bool(disable_on_exit, "disable_on_exit") + self._assert_healthy_for_active_ft() + self.set_enable(True) + time.sleep(0.2) + try: + if zero_flag: + self.zero() + self.configure_admittance(params, reaction_threshold=reaction_threshold) + self.set_mode(FT_MODE_ADMITTANCE, confirm_real=True) + yield self + finally: + self.stop_force_mode(disable_sensor=disable_flag) + + @contextmanager + def force_control_session( + self, + params: FTForceControlParams, + *, + confirm_real: bool = False, + zero_on_enter: bool = False, + disable_on_exit: bool = False, + ) -> Iterator[XArmFTSensor]: + """Enter force control safely and always exit back to ``FT_MODE_OFF``.""" + if not confirm_real: + raise RuntimeError("force_control_session enables physical motion; pass confirm_real=True") + zero_flag = _check_bool(zero_on_enter, "zero_on_enter") + disable_flag = _check_bool(disable_on_exit, "disable_on_exit") + self._assert_healthy_for_active_ft() + self.set_enable(True) + time.sleep(0.2) + try: + if zero_flag: + self.zero() + self.configure_force_control(params) + self.set_mode(FT_MODE_FORCE, confirm_real=True) + yield self + finally: + self.stop_force_mode(disable_sensor=disable_flag) diff --git a/ufactory/hardware/transport.py b/ufactory/hardware/transport.py index e6068b9..e32acb5 100644 --- a/ufactory/hardware/transport.py +++ b/ufactory/hardware/transport.py @@ -8,6 +8,7 @@ import numpy as np +from ufactory.hardware.ft_sensor import XArmFTSensor from ufactory.hardware.xarm import ( MODE_POSITION, MODE_SERVO, @@ -125,9 +126,36 @@ def pause(self) -> int: def stop(self) -> int: return int(self.arm.set_state(4)) + def set_allow_approx_motion(self, on_off: bool) -> int: + """Enable or disable controller singularity approximate motion (mirrors xArm SDK).""" + + if not isinstance(on_off, bool): + raise TypeError("on_off must be a bool") + return int(self.arm.set_allow_approx_motion(on_off)) + + def get_allow_approx_motion(self) -> tuple[int, int]: + """Return ``(sdk_code, enabled_int)`` from the controller.""" + + code, enabled = self.arm.get_allow_approx_motion() + return int(code), int(enabled) + + @property + def is_approx_motion(self) -> bool: + """Whether controller approximate motion is currently enabled.""" + + code, enabled = self.get_allow_approx_motion() + if code != 0: + raise RuntimeError(f"get_allow_approx_motion failed with SDK code {code}") + return bool(enabled) + def disconnect(self) -> None: self.arm.disconnect() + def ft_sensor(self) -> XArmFTSensor: + """Return a safe F/T sensor controller bound to this transport's arm and robot key.""" + + return XArmFTSensor(self.arm, robot_key=self.robot_key) + def leave_software_stop(self) -> None: """Exit controller STOP when there is no active error (Studio Enable equivalent). diff --git a/ufactory/kinematics/controller_fk.py b/ufactory/kinematics/controller_fk.py new file mode 100644 index 0000000..a58002b --- /dev/null +++ b/ufactory/kinematics/controller_fk.py @@ -0,0 +1,436 @@ +"""Per-unit joint origins identified from the controller's forward kinematics. + +The controller's FK is a rigid chain: every joint is a fixed screw axis. With +all other joints at 0, moving one joint shows its axis directly, so the zero +pose plus a few single-joint sweeps identify the whole chain (product of +exponentials). This module turns those axes into schema-v1 calibration joint +origins (``joint: {x, y, z, roll, pitch, yaw}``) for the project URDF: + +* joints 1..N-1: the nominal joint frame, minimally rotated onto the + identified axis, at the foot of the perpendicular from the nominal origin; +* joint N: the controller flange frame at q = 0, rotating about its own z. + +The controller puts the flange slightly off its last axis (measured +38-240 um, 8-22 mdeg tilt). Joint origins cannot express that, so the model is +exact whenever the last joint is at 0, and its error grows with |q_N| up to +about twice the offset. The register-8 export uses the same last-joint form. +Every identification is checked against controller FK at random +configurations it did not use. + +No SDK import: callers pass ``flange_fk(q) -> 4x4`` (metres, base frame). +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass +import math +from pathlib import Path +import xml.etree.ElementTree as ET + +import numpy as np + +from ufactory.kinematics.tcp_offset import pose_to_matrix, rpy_matrix +from ufactory.types import FloatArray + +CALIBRATION_FIELDS = ("x", "y", "z", "roll", "pitch", "yaw") +SWEEP_ANGLES_RAD = (-1.5, -1.0, -0.5, 0.5, 1.0, 1.5) +SAMPLE_SPAN_RAD = 2.5 +VERIFICATION_SAMPLES = 100 +VERIFICATION_SEED = 20261126 + +# Acceptance: the same limits as the FK validation against the controller +# (ufactory.kinematics.validation PASS_POS_MM / PASS_RPY_DEG). +MAX_MODEL_POSITION_ERROR_M = 1.0e-3 +MAX_MODEL_ROTATION_ERROR_RAD = math.radians(0.5) +# The controller FK must be a rigid chain; measured <= 1.55 um on four arms. +MAX_RIGID_CHAIN_ERROR_M = 10.0e-6 +# Plausibility guard against a wrong URDF, not an accuracy limit: identified +# axes and origins, accumulated along the chain, versus the nominal URDF. +# Measured: four arms <= 0.30 deg / 2.5 mm, xArm7 XS130502F56A0C 1.46 deg / 5.4 mm. +MAX_AXIS_DEVIATION_RAD = math.radians(5.0) +MAX_ORIGIN_DEVIATION_M = 20.0e-3 + + +class CalibrationIdentificationError(ValueError): + """The controller FK cannot be turned into trustworthy joint origins.""" + + +@dataclass(frozen=True) +class NominalChain: + """Revolute joint chain ``joint1..N`` of a URDF, in the base link frame.""" + + joint_names: tuple[str, ...] + origins: FloatArray # (N, 6): xyz (m) + rpy (rad), URDF convention + axes: FloatArray # (N, 3): unit axis in each joint frame + lower: FloatArray + upper: FloatArray + ee_link: str + + +@dataclass(frozen=True) +class ScrewAxis: + """Joint axis at q = 0 in the base frame: unit direction and closest point to the origin.""" + + direction: FloatArray + point: FloatArray + + +@dataclass(frozen=True) +class ControllerFkIdentification: + """Joint origins plus the evidence that they reproduce the controller.""" + + origins: FloatArray + identification_samples: int + verification_samples: int + rigid_chain_error_m: float + mean_position_error_m: float + max_position_error_m: float + max_rotation_error_rad: float + flange_axis_offset_m: float + flange_axis_tilt_rad: float + max_axis_deviation_rad: float + max_origin_deviation_m: float + + def joints(self, joint_names: Sequence[str]) -> dict[str, dict[str, float]]: + return { + name: {field: float(value) for field, value in zip(CALIBRATION_FIELDS, row, strict=True)} + for name, row in zip(joint_names, self.origins, strict=True) + } + + +# ---------------------------------------------------------------- geometry + + +def _transform( + rotation: FloatArray | None = None, translation: Sequence[float] | FloatArray = (0.0, 0.0, 0.0) +) -> FloatArray: + matrix: FloatArray = np.eye(4, dtype=np.float64) + if rotation is not None: + matrix[:3, :3] = rotation + matrix[:3, 3] = np.asarray(translation, dtype=np.float64) + return matrix + + +def _skew(vector: FloatArray) -> FloatArray: + x, y, z = (float(v) for v in vector) + return np.array([[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]], dtype=np.float64) + + +def axis_angle_matrix(axis: FloatArray, angle: float) -> FloatArray: + """Rotation by ``angle`` about the unit vector ``axis`` (Rodrigues).""" + + k = _skew(np.asarray(axis, dtype=np.float64)) + return np.eye(3) + math.sin(angle) * k + (1.0 - math.cos(angle)) * (k @ k) + + +def rotation_vector(rotation: FloatArray) -> FloatArray: + """Inverse of ``axis_angle_matrix`` for angles below pi.""" + + r = np.asarray(rotation, dtype=np.float64) + vee = 0.5 * np.array([r[2, 1] - r[1, 2], r[0, 2] - r[2, 0], r[1, 0] - r[0, 1]]) + sin_angle = float(np.linalg.norm(vee)) + angle = math.atan2(sin_angle, (float(np.trace(r)) - 1.0) / 2.0) + if sin_angle < 1e-15: + return np.zeros(3) + return vee / sin_angle * angle + + +def rotation_angle(a: FloatArray, b: FloatArray) -> float: + """Angle (rad) of the rotation taking ``a`` to ``b``.""" + + return float(np.linalg.norm(rotation_vector(np.asarray(a).T @ np.asarray(b)))) + + +def _vector_angle(a: FloatArray, b: FloatArray) -> float: + return math.atan2(float(np.linalg.norm(np.cross(a, b))), float(np.dot(a, b))) + + +def _minimal_rotation(a: FloatArray, b: FloatArray) -> FloatArray: + """Smallest rotation taking unit vector ``a`` onto unit vector ``b``.""" + + cross = np.cross(a, b) + norm = float(np.linalg.norm(cross)) + if norm < 1e-15: + if float(np.dot(a, b)) > 0.0: + return np.eye(3) + raise CalibrationIdentificationError("identified joint axis is opposite to the nominal axis") + return axis_angle_matrix(cross / norm, math.atan2(norm, float(np.dot(a, b)))) + + +def matrix_rpy(rotation: FloatArray) -> tuple[float, float, float]: + """URDF roll/pitch/yaw of ``rotation`` (R = Rz(yaw) Ry(pitch) Rx(roll)), exact at gimbal lock.""" + + r = np.asarray(rotation, dtype=np.float64) + cos_pitch = math.hypot(float(r[0, 0]), float(r[1, 0])) + pitch = math.atan2(-float(r[2, 0]), cos_pitch) + if cos_pitch > 1e-9: + return math.atan2(float(r[2, 1]), float(r[2, 2])), pitch, math.atan2(float(r[1, 0]), float(r[0, 0])) + # pitch = +-pi/2: only roll - yaw (or roll + yaw) is defined; take yaw = 0. + return math.atan2(-float(r[1, 2]), float(r[1, 1])), pitch, 0.0 + + +def chain_pose(origins: FloatArray, axes: FloatArray, q: Sequence[float] | FloatArray) -> FloatArray: + """URDF chain FK: per joint, fixed origin then rotation ``q_i`` about the local axis.""" + + pose = np.eye(4) + for row, axis, angle in zip(np.asarray(origins), np.asarray(axes), np.asarray(q, dtype=np.float64), strict=True): + pose = ( + pose + @ _transform(rpy_matrix(float(row[3]), float(row[4]), float(row[5])), row[:3]) + @ _transform(axis_angle_matrix(axis, float(angle))) + ) + return pose + + +def screw_pose(zero_pose: FloatArray, axes: Sequence[ScrewAxis], q: Sequence[float] | FloatArray) -> FloatArray: + """Product-of-exponentials FK of identified screw axes.""" + + pose = np.eye(4) + for axis, angle in zip(axes, np.asarray(q, dtype=np.float64), strict=True): + rotation = axis_angle_matrix(axis.direction, float(angle)) + pose = pose @ _transform(rotation, (np.eye(3) - rotation) @ axis.point) + return pose @ zero_pose + + +def pose_errors(model: Sequence[FloatArray], reference: Sequence[FloatArray]) -> tuple[FloatArray, FloatArray]: + """Position (m) and rotation (rad) error per sample.""" + + position = np.array([np.linalg.norm(a[:3, 3] - b[:3, 3]) for a, b in zip(model, reference, strict=True)]) + rotation = np.array([rotation_angle(a[:3, :3], b[:3, :3]) for a, b in zip(model, reference, strict=True)]) + return position, rotation + + +# ---------------------------------------------------------------- nominal model + + +def _floats(text: str | None, default: tuple[float, float, float]) -> FloatArray: + return np.asarray(default if text is None else [float(v) for v in text.split()], dtype=np.float64) + + +def load_nominal_chain(urdf_path: str | Path, joint_names: Sequence[str]) -> NominalChain: + """Read ``joint_names`` as a direct revolute chain (each joint's parent is the previous joint's child).""" + + root = ET.parse(str(urdf_path)).getroot() + joints = {joint.get("name"): joint for joint in root.findall("joint")} + origins, axes, lower, upper = [], [], [], [] + previous_child: str | None = None + for name in joint_names: + joint = joints.get(name) + if joint is None or joint.get("type") not in {"revolute", "continuous"}: + raise CalibrationIdentificationError(f"{urdf_path}: {name} is not a revolute joint") + parent, child = joint.find("parent"), joint.find("child") + if parent is None or child is None: + raise CalibrationIdentificationError(f"{urdf_path}: {name} lacks parent or child") + if previous_child is not None and parent.get("link") != previous_child: + raise CalibrationIdentificationError(f"{urdf_path}: {name} does not follow the previous joint directly") + previous_child = child.get("link") + origin = joint.find("origin") + xyz = _floats(None if origin is None else origin.get("xyz"), (0.0, 0.0, 0.0)) + rpy = _floats(None if origin is None else origin.get("rpy"), (0.0, 0.0, 0.0)) + axis_element = joint.find("axis") + axis = _floats(None if axis_element is None else axis_element.get("xyz"), (1.0, 0.0, 0.0)) + limit = joint.find("limit") + lo = -math.pi if limit is None or limit.get("lower") is None else float(limit.get("lower", "")) + hi = math.pi if limit is None or limit.get("upper") is None else float(limit.get("upper", "")) + origins.append([*xyz, *rpy]) + axes.append(axis / np.linalg.norm(axis)) + lower.append(lo) + upper.append(hi) + assert previous_child is not None + return NominalChain( + joint_names=tuple(joint_names), + origins=np.asarray(origins, dtype=np.float64), + axes=np.asarray(axes, dtype=np.float64), + lower=np.asarray(lower, dtype=np.float64), + upper=np.asarray(upper, dtype=np.float64), + ee_link=previous_child, + ) + + +# ---------------------------------------------------------------- sampling + + +def sweep_angles(lower: float, upper: float) -> tuple[float, ...]: + """Non-zero angles for one joint's sweep, within its limits and +-SAMPLE_SPAN_RAD.""" + + lo, hi = max(lower, -SAMPLE_SPAN_RAD), min(upper, SAMPLE_SPAN_RAD) + values = [value for value in SWEEP_ANGLES_RAD if lo <= value <= hi] + if len(values) < 4: # one-sided joint (e.g. xArm5 J3): spread over its range + values = [float(value) for value in np.linspace(lo, hi, 6) if abs(value) > 0.04] + if len(values) < 2: + raise CalibrationIdentificationError(f"joint range [{lower:.3f}, {upper:.3f}] rad is too small to sweep") + return tuple(values) + + +def verification_configurations(chain: NominalChain, count: int, seed: int) -> FloatArray: + lo = np.maximum(chain.lower, -SAMPLE_SPAN_RAD) + hi = np.minimum(chain.upper, SAMPLE_SPAN_RAD) + return np.random.default_rng(seed).uniform(lo, hi, size=(count, len(chain.joint_names))) + + +# ---------------------------------------------------------------- identification + + +def identify_screw_axes( + zero_pose: FloatArray, + sweeps: Sequence[Sequence[tuple[float, FloatArray]]], +) -> list[ScrewAxis]: + """Screw axis of each joint from ``sweeps[j] = [(angle, controller pose with only joint j moved), ...]``.""" + + axes: list[ScrewAxis] = [] + zero_inverse = np.linalg.inv(zero_pose) + for samples in sweeps: + directions, rows, rhs = [], [], [] + for angle, pose in samples: + motion = pose @ zero_inverse # = exp([S_j] angle) + directions.append(rotation_vector(motion[:3, :3]) / angle) + rows.append(np.eye(3) - motion[:3, :3]) + rhs.append(motion[:3, 3]) + direction = np.mean(directions, axis=0) + direction /= np.linalg.norm(direction) + point = np.linalg.lstsq(np.vstack(rows), np.concatenate(rhs), rcond=None)[0] + axes.append(ScrewAxis(direction=direction, point=point - float(point @ direction) * direction)) + return axes + + +def joint_origins_from_axes( + chain: NominalChain, + zero_pose: FloatArray, + axes: Sequence[ScrewAxis], +) -> tuple[FloatArray, float, float]: + """Joint origins for identified axes; returns (origins, max axis deviation rad, max origin deviation m).""" + + count = len(chain.joint_names) + nominal_frames, frame = [], np.eye(4) + for row in chain.origins: + frame = frame @ _transform(rpy_matrix(float(row[3]), float(row[4]), float(row[5])), row[:3]) + nominal_frames.append(frame.copy()) + frames: list[FloatArray] = [] + max_axis = max_origin = 0.0 + for index, (nominal, axis) in enumerate(zip(nominal_frames, axes, strict=True)): + nominal_axis = nominal[:3, :3] @ chain.axes[index] + axis_deviation = _vector_angle(nominal_axis, axis.direction) + if index < count - 1: + rotation = _minimal_rotation(nominal_axis, axis.direction) @ nominal[:3, :3] + offset = nominal[:3, 3] - axis.point + position = axis.point + float(offset @ axis.direction) * axis.direction + origin_deviation = float(np.linalg.norm(position - nominal[:3, 3])) + else: + rotation, position = zero_pose[:3, :3], zero_pose[:3, 3] + origin_deviation = float(np.linalg.norm(position - nominal[:3, 3])) + axis_deviation = max(axis_deviation, rotation_angle(nominal[:3, :3], rotation)) + if axis_deviation > MAX_AXIS_DEVIATION_RAD or origin_deviation > MAX_ORIGIN_DEVIATION_M: + raise CalibrationIdentificationError( + f"{chain.joint_names[index]}: controller axis is {math.degrees(axis_deviation):.3f} deg / " + f"{origin_deviation * 1e3:.3f} mm from the nominal URDF (limits " + f"{math.degrees(MAX_AXIS_DEVIATION_RAD):.1f} deg / {MAX_ORIGIN_DEVIATION_M * 1e3:.0f} mm); " + "is the controller the same robot model as the URDF?" + ) + max_axis, max_origin = max(max_axis, axis_deviation), max(max_origin, origin_deviation) + frames.append(_transform(rotation, position)) + origins, previous = [], np.eye(4) + for frame in frames: + relative = np.linalg.inv(previous) @ frame + origins.append([*relative[:3, 3], *matrix_rpy(relative[:3, :3])]) + previous = frame + result = np.asarray(origins, dtype=np.float64) + rebuilt = chain_pose(result, chain.axes, np.zeros(count)) + if ( + float(np.linalg.norm(rebuilt[:3, 3] - zero_pose[:3, 3])) > 1e-9 + or rotation_angle(rebuilt[:3, :3], zero_pose[:3, :3]) > 1e-9 + ): + raise CalibrationIdentificationError("joint origins do not rebuild the controller zero pose") + return result, max_axis, max_origin + + +def identify_from_controller_fk( + flange_fk: Callable[[FloatArray], FloatArray], + chain: NominalChain, + *, + verification_samples: int = VERIFICATION_SAMPLES, + seed: int = VERIFICATION_SEED, +) -> ControllerFkIdentification: + """Identify joint origins from controller FK and verify them on held-out configurations. + + Raises ``CalibrationIdentificationError`` when the controller FK is not a + rigid chain, the geometry is far from the nominal URDF, or the result + misses the FK validation limits on the held-out configurations. + """ + + count = len(chain.joint_names) + zero_pose = np.asarray(flange_fk(np.zeros(count)), dtype=np.float64) + sweeps: list[list[tuple[float, FloatArray]]] = [] + for index in range(count): + samples = [] + for angle in sweep_angles(float(chain.lower[index]), float(chain.upper[index])): + q = np.zeros(count) + q[index] = angle + samples.append((angle, np.asarray(flange_fk(q), dtype=np.float64))) + sweeps.append(samples) + axes = identify_screw_axes(zero_pose, sweeps) + origins, max_axis, max_origin = joint_origins_from_axes(chain, zero_pose, axes) + + configurations = verification_configurations(chain, verification_samples, seed) + controller = [np.asarray(flange_fk(q), dtype=np.float64) for q in configurations] + rigid_position, rigid_rotation = pose_errors([screw_pose(zero_pose, axes, q) for q in configurations], controller) + position, rotation = pose_errors([chain_pose(origins, chain.axes, q) for q in configurations], controller) + + last = axes[-1] + flange_offset = zero_pose[:3, 3] - last.point + flange_offset -= float(flange_offset @ last.direction) * last.direction + result = ControllerFkIdentification( + origins=origins, + identification_samples=1 + sum(len(samples) for samples in sweeps), + verification_samples=len(configurations), + rigid_chain_error_m=float(rigid_position.max(initial=0.0)), + mean_position_error_m=float(position.mean()) if position.size else 0.0, + max_position_error_m=float(position.max(initial=0.0)), + max_rotation_error_rad=float(rotation.max(initial=0.0)), + flange_axis_offset_m=float(np.linalg.norm(flange_offset)), + flange_axis_tilt_rad=_vector_angle(zero_pose[:3, :3] @ chain.axes[-1], last.direction), + max_axis_deviation_rad=max_axis, + max_origin_deviation_m=max_origin, + ) + if result.rigid_chain_error_m > MAX_RIGID_CHAIN_ERROR_M: + raise CalibrationIdentificationError( + f"controller FK is not a rigid chain: screw model misses held-out samples by " + f"{result.rigid_chain_error_m * 1e6:.2f} um (limit {MAX_RIGID_CHAIN_ERROR_M * 1e6:.0f} um, " + f"rotation {math.degrees(float(rigid_rotation.max(initial=0.0))) * 1e3:.3f} mdeg)" + ) + if ( + result.max_position_error_m > MAX_MODEL_POSITION_ERROR_M + or result.max_rotation_error_rad > MAX_MODEL_ROTATION_ERROR_RAD + ): + raise CalibrationIdentificationError( + f"joint origins miss controller FK by {result.max_position_error_m * 1e3:.4f} mm / " + f"{math.degrees(result.max_rotation_error_rad):.4f} deg (limits {MAX_MODEL_POSITION_ERROR_M * 1e3:.1f} mm / " + f"{math.degrees(MAX_MODEL_ROTATION_ERROR_RAD):.1f} deg); flange is " + f"{result.flange_axis_offset_m * 1e6:.0f} um off the last axis" + ) + return result + + +# ---------------------------------------------------------------- SDK adapter + + +def controller_flange_fk(arm: object, tcp_offset: Sequence[float] | FloatArray) -> Callable[[FloatArray], FloatArray]: + """``q -> flange pose`` from ``arm.get_forward_kinematics`` with the controller TCP offset removed. + + ``tcp_offset`` is ``[x, y, z, roll, pitch, yaw]`` (mm, rad), as read from the + controller; the SDK returns the TCP pose ``T_flange @ T_offset``. + """ + + remove_offset = np.linalg.inv(pose_to_matrix(tcp_offset)) + get_fk = getattr(arm, "get_forward_kinematics") + + def flange_fk(q: FloatArray) -> FloatArray: + code, pose = get_fk([float(v) for v in q], input_is_radian=True, return_is_radian=True) + values = np.asarray(pose, dtype=np.float64).reshape(-1) + if int(code) != 0 or values.shape != (6,) or not np.all(np.isfinite(values)): + raise RuntimeError(f"controller FK failed (SDK code={code})") + flange = pose_to_matrix(values) @ remove_offset + flange[:3, 3] /= 1000.0 + return flange + + return flange_fk diff --git a/ufactory/kinematics/genesis.py b/ufactory/kinematics/genesis.py index b4d7882..a8287be 100644 --- a/ufactory/kinematics/genesis.py +++ b/ufactory/kinematics/genesis.py @@ -39,14 +39,56 @@ def down_quat(device=None, dtype=None) -> torch.Tensor: HOME_IK_MAX_ROT_ERR_RAD = 5e-3 -def solve_home_ik(robot, ik_link, pos, quat, *, arm_dof_idx, init_qpos=None): +def solve_home_ik( + robot, + ik_link, + pos, + quat, + *, + arm_dof_idx, + init_qpos=None, + arm_controller=None, + target_pos_base=None, + default_qpos_rad=None, +): """Solve a held start pose to micrometres on the joint branch Genesis's default IK picks. - The first solve is the plain Genesis call (default tolerances, random restarts) and chooses the branch. The second - starts from its result with a single sample, so it cannot restart on another branch, and iterates to - ``HOME_IK_POS_TOL_M`` / ``HOME_IK_ROT_TOL_RAD``. Returns the joint vector as Genesis returns it. Raises - :class:`ValueError` if the residual is still above ``HOME_IK_MAX_POS_ERR_M`` / ``HOME_IK_MAX_ROT_ERR_RAD``. + When ``arm_controller`` and ``target_pos_base`` are provided, uses the unified + pure-NumPy :class:`~ufactory.control.ArmMotionController` (Pieper analytical + + polish for Lite6/UF850, 5-DOF position-priority IK for xArm5, iterative SE(3) + for xArm6/xArm7) so preflight, simulation, and hardware start on the identical + exact joint configuration. Otherwise falls back to two-pass Genesis IK. """ + if arm_controller is not None and target_pos_base is not None: + from ufactory.trajectory.ik import solve_arm_home_q + + seed_q = None + if default_qpos_rad is not None: + seed_q = np.asarray(default_qpos_rad, dtype=np.float64).reshape(-1) + elif init_qpos is not None: + seed_arr = init_qpos.detach().cpu().numpy() if hasattr(init_qpos, "detach") else np.asarray(init_qpos) + seed_flat = np.asarray(seed_arr, dtype=np.float64).reshape(-1) + if seed_flat.size == len(arm_dof_idx): + seed_q = seed_flat + elif seed_flat.size > max(arm_dof_idx): + seed_q = seed_flat[list(arm_dof_idx)] + q_rad = solve_arm_home_q( + arm_controller, + target_pos_base, + default_qpos_rad=seed_q, + include_tcp=False, + pos_tol_m=HOME_IK_POS_TOL_M, + rot_tol_rad=HOME_IK_ROT_TOL_RAD, + max_pos_err_m=HOME_IK_MAX_POS_ERR_M, + max_rot_err_rad=HOME_IK_MAX_ROT_ERR_RAD, + ) + device = pos.device if hasattr(pos, "device") else gs.device + dtype = pos.dtype if hasattr(pos, "dtype") else gs.tc_float + n_dofs = int(getattr(robot, "n_dofs", getattr(robot, "n_qs", max(arm_dof_idx) + 1))) + refined = torch.zeros((1, n_dofs), device=device, dtype=dtype) + for i, idx in enumerate(arm_dof_idx): + refined[0, idx] = float(q_rad[i]) + return refined seed = {} if init_qpos is None else {"init_qpos": init_qpos} coarse = robot.inverse_kinematics(link=ik_link, pos=pos, quat=quat, dofs_idx_local=arm_dof_idx, **seed) refined, error = robot.inverse_kinematics( diff --git a/ufactory/manipulation/commands.py b/ufactory/manipulation/commands.py index 64ae232..0f8a459 100644 --- a/ufactory/manipulation/commands.py +++ b/ufactory/manipulation/commands.py @@ -12,6 +12,7 @@ import numpy as np from ufactory.config import RepositoryAssetStore +from ufactory.control import ArmMotionController from ufactory.grippers import create_gripper_adapter from ufactory.hardware import XArmTransport from ufactory.hardware.xarm import verify_controller_robot, wait_for_servo_motion_ready @@ -19,11 +20,28 @@ from ufactory.robots.assembly import resolve_robot_urdf from ufactory.kinematics.orientation import GRIPPER_DOWN_RPY_RAD from ufactory.kinematics.tcp_offset import pose_flange_to_tcp, read_tcp_offset -from ufactory.safety.adapters import EnvironmentObstacle, PinocchioCollisionBackend, PinocchioKinematicsBackend +from ufactory.safety.adapters import EnvironmentObstacle, PinocchioCollisionBackend from ufactory.safety.adapters.pinocchio import StageAwareObjectCollisionBackend from ufactory.safety.gate import sha256_file +def build_arm_controller( + config: Any, + urdf: Path, + *, + tcp_offset: Sequence[float] | np.ndarray | None = None, +) -> ArmMotionController: + """Construct the unified pure-NumPy ArmMotionController for runtime config + URDF.""" + + return ArmMotionController.from_robot( + config.robot.key, + urdf_path=urdf, + tcp_offset_mm_rpy=tcp_offset, + servo_rate_hz=float(config.motion.rate_hz), + allow_approx_motion=bool(getattr(config.motion, "allow_approx_motion", False)), + ) + + def build_manipulation_backends( config: Any, urdf: Path, @@ -35,13 +53,12 @@ def build_manipulation_backends( object_width_m: float, calibrated_g2: bool = False, ) -> tuple[Any, Any]: - passive = {config.gripper.drive_joint: config.gripper.open_drive} if config.gripper is not None else {} - kinematics = PinocchioKinematicsBackend( - urdf, - joint_names=config.robot.joint_names, - ee_link=config.robot.ee_link, - passive_joint_positions=passive, + passive = ( + {config.gripper.drive_joint: config.gripper.open_drive} + if config.gripper is not None and config.gripper.drive_joint + else {} ) + kinematics = build_arm_controller(config, urdf) collision: Any = StageAwareObjectCollisionBackend( PinocchioCollisionBackend( urdf, @@ -131,8 +148,10 @@ def prepare_real_gripper_sender( arm: Any, transport: XArmTransport, gripper_config: Any, + *, + hardware_version: int = 1, ) -> tuple[list[float], Callable[[float], int] | None]: - gripper_adapter = create_gripper_adapter(gripper_config) + gripper_adapter = create_gripper_adapter(gripper_config, hardware_version=hardware_version) if gripper_adapter.capabilities.real_command: prepare_code = gripper_adapter.prepare_real(arm) if prepare_code != 0: @@ -148,6 +167,22 @@ def send_gripper(gap_m: float) -> int: return current_drive, gripper_sender +def shutdown_real_gripper( + arm: Any, + gripper_config: Any, + *, + hardware_version: int = 1, +) -> int: + """Safely release stateless real end effectors (e.g. pneumatic vacuum suction) on exit.""" + if gripper_config is None or not bool(getattr(gripper_config, "real_command", False)): + return 0 + adapter = create_gripper_adapter(gripper_config, hardware_version=hardware_version) + shutdown = getattr(adapter, "shutdown_real", None) + if callable(shutdown): + return int(shutdown(arm)) + return 0 + + def print_real_execution_summary(execution: Any) -> None: print(f"real_execution={'PASS' if execution.completed else 'FAIL'} sent_samples={execution.sent_samples}") if execution.fault is not None: @@ -166,7 +201,9 @@ def print_sdk_sim_failures(evidence: Any, evidence_path: Path | None) -> None: print( f"sdk_sim_failures={len(evidence.failures)} max_joint_error_rad={float(evidence.max_joint_error_rad):.6g} " - f"max_ee_error_m={float(evidence.max_ee_error_m):.6g}", + f"max_ee_error_m={float(evidence.max_ee_error_m):.6g} " + f"max_ee_rotation_error_rad={float(evidence.max_ee_rotation_error_rad):.6g} " + f"self_motion_allowed={bool(evidence.self_motion_allowed)}", file=sys.stderr, ) for failure in evidence.failures: @@ -306,13 +343,15 @@ def sdk_sim_feedback( expected_start_q: np.ndarray, *, tcp_offset: Sequence[float] | np.ndarray | None = None, + allow_approx_motion: bool | None = None, ) -> np.ndarray: """Replay against the controller's virtual robot from the approved start. The virtual preposition happens only after SDK simulation mode is enabled. This keeps ``sdk-sim`` independent of the physical arm pose and prevents a validation-only command from moving the real robot. The controller is - always returned to non-simulation mode, including on replay failures. + always returned to non-simulation mode (and its original + ``allow_approx_motion`` setting restored), including on replay failures. MoveL samples are flange poses; they are converted to the controller TCP frame with ``tcp_offset`` (read from the controller when omitted). @@ -324,13 +363,29 @@ def sdk_sim_feedback( offset = read_tcp_offset(arm) if tcp_offset is None else np.asarray(tcp_offset, dtype=np.float64).reshape(-1) if offset.shape != (6,) or not np.all(np.isfinite(offset)): raise ValueError("tcp_offset must contain 6 finite values") + approx_flag = ( + bool(getattr(getattr(config, "motion", None), "allow_approx_motion", False)) + if allow_approx_motion is None + else bool(allow_approx_motion) + ) + has_approx_api = callable(getattr(arm, "get_allow_approx_motion", None)) and callable( + getattr(arm, "set_allow_approx_motion", None) + ) + if approx_flag and not has_approx_api: + raise RuntimeError("SDK simulation allow_approx_motion=True requires controller get/set_allow_approx_motion") def require_ok(label: str, code: int) -> None: if int(code) != 0: raise RuntimeError(f"SDK simulation {label} failed with code {code}") simulation_requested = bool(getattr(arm, "is_simulation_robot", False)) + approx_prev: bool | None = None + approx_changed = False try: + if has_approx_api: + read_code, prev_val = arm.get_allow_approx_motion() + require_ok("get_allow_approx_motion", int(read_code)) + approx_prev = bool(prev_val) if not simulation_requested: # The SDK deliberately suppresses motion_enable once its report # stream says simulation mode is active. Prepare readiness first, @@ -345,6 +400,9 @@ def require_ok(label: str, code: int) -> None: time.sleep(0.05) if not bool(getattr(arm, "is_simulation_robot", False)): raise RuntimeError("SDK simulation mode was not confirmed by the controller report stream") + if has_approx_api: + require_ok("set_allow_approx_motion", arm.set_allow_approx_motion(approx_flag)) + approx_changed = True require_ok("set_mode(position)", arm.set_mode(0)) require_ok("set_state", arm.set_state(0)) @@ -366,7 +424,7 @@ def require_ok(label: str, code: int) -> None: require_ok("set_state", arm.set_state(0)) wait_for_servo_motion_ready(arm) print(f" [sdk-sim] virtual start reached max_err={start_error:.4f}rad; physical arm was not prepositioned") - print(f" [sdk-sim] tcp_offset={offset.tolist()} (flange targets converted to TCP)") + print(f" [sdk-sim] tcp_offset={offset.tolist()} allow_approx_motion={approx_flag} (flange targets -> TCP)") rows = [virtual_start] orientation = GRIPPER_DOWN_RPY_RAD dt = 1.0 / program.rate @@ -382,14 +440,30 @@ def require_ok(label: str, code: int) -> None: else: code = 0 if int(code) != 0: + err_warn: object = None + state: object = None + try: + if callable(getattr(arm, "get_err_warn_code", None)): + err_warn = arm.get_err_warn_code() + if callable(getattr(arm, "get_state", None)): + state = arm.get_state() + except Exception: + pass arm.set_state(4) - raise RuntimeError(f"SDK simulation command failed with code {code}") + raise RuntimeError( + f"SDK simulation command failed with code {code} " + f"(segment={segment.label}, err_warn={err_warn}, state={state})" + ) time.sleep(dt) rows.append(read_q(arm, config.robot.dof)) return np.stack(rows) finally: + cleanup_failures: list[str] = [] + if approx_changed and approx_prev is not None: + restore_code = int(arm.set_allow_approx_motion(approx_prev)) + if restore_code != 0: + cleanup_failures.append(f"restore allow_approx_motion={approx_prev} failed with code {restore_code}") if simulation_requested: - cleanup_failures: list[str] = [] pause_code = int(arm.set_state(3)) if pause_code != 0: cleanup_failures.append(f"pause failed with code {pause_code}") @@ -401,8 +475,8 @@ def require_ok(label: str, code: int) -> None: time.sleep(0.05) if bool(getattr(arm, "is_simulation_robot", False)): cleanup_failures.append("controller report still says simulation mode is active") - if cleanup_failures: - raise RuntimeError("SDK simulation cleanup failed: " + "; ".join(cleanup_failures)) + if cleanup_failures: + raise RuntimeError("SDK simulation cleanup failed: " + "; ".join(cleanup_failures)) def validate_robot_identity(arm: Any, config: Any, serial: str) -> None: @@ -417,7 +491,12 @@ def print_summary(config: Any) -> None: print("configuration_sources:") for source in config.sources: print(f" - {source}") - print(f"robot={config.robot.key} rate_hz={config.motion.rate_hz} z_min_m={config.safety.z_min_m}") + print( + f"robot={config.robot.key} rate_hz={config.motion.rate_hz} " + f"sim_rate_hz={config.simulation.rate_hz} " + f"allow_approx_motion={config.motion.allow_approx_motion} " + f"z_min_m={config.safety.z_min_m}" + ) print(f"config_sha256={config.sha256}") @@ -459,6 +538,8 @@ def print_preflight_complete(preflight: Any) -> None: f"collision_s={collision_s:.3f} total_s={total_s:.3f}", flush=True, ) + for warning in getattr(preflight, "warnings", ()): + print(f"[preflight] warning: {warning}", flush=True) def print_preflight_violation_summary(preflight: Any, report_path: Path | None) -> None: diff --git a/ufactory/manipulation/packaging/scene.py b/ufactory/manipulation/packaging/scene.py index acd5432..d870d5b 100644 --- a/ufactory/manipulation/packaging/scene.py +++ b/ufactory/manipulation/packaging/scene.py @@ -311,7 +311,7 @@ def _add_packaging_robot(scene: gs.Scene, layout: PackagingSceneLayout, urdf_pat def build_packaging_scene( table_top_z: float = DEFAULT_TABLE_TOP_Z, *, - sim_dt: float = 0.02, + sim_dt: float | None = None, show_viewer: bool = True, build_scene: bool = True, renderer=None, @@ -321,18 +321,19 @@ def build_packaging_scene( runtime_config=None, ): config = runtime_config or load_runtime_config("xarm6", task="packaging_showcase") + resolved_sim_dt = 1.0 / float(config.simulation.rate_hz) if sim_dt is None else float(sim_dt) layout = make_layout(table_top_z, config) substeps = int(config.simulation.substeps) if config.gripper.adapter == "g2": - validate_g2_contact_substeps(dt=sim_dt, substeps=substeps) + validate_g2_contact_substeps(dt=resolved_sim_dt, substeps=substeps) elif config.gripper.adapter in {"robotiq_2f_85", "robotiq_2f_140"}: - validate_robotiq_contact_substeps(dt=sim_dt, substeps=substeps, variant=config.gripper.adapter) + validate_robotiq_contact_substeps(dt=resolved_sim_dt, substeps=substeps, variant=config.gripper.adapter) cam_pos, cam_lookat = packaging_camera(layout) scene_kwargs: dict = {} if renderer is not None: scene_kwargs["renderer"] = renderer scene = gs.Scene( - sim_options=gs.options.SimOptions(dt=sim_dt, substeps=substeps), + sim_options=gs.options.SimOptions(dt=resolved_sim_dt, substeps=substeps), rigid_options=make_rigid_options( gs, constraint_solver=config.simulation.constraint_solver, diff --git a/ufactory/manipulation/packaging/simulation.py b/ufactory/manipulation/packaging/simulation.py index 6851c40..0872adf 100644 --- a/ufactory/manipulation/packaging/simulation.py +++ b/ufactory/manipulation/packaging/simulation.py @@ -75,6 +75,8 @@ class ShowcaseRobotCtx: home_settle_steps: int = SETTLE_STEPS g2_controller: object | None = None robotiq_controller: object | None = None + sim_dt: float = SIM_DT + arm_controller: object | None = None def _scale_steps(steps: int, speed: float) -> int: @@ -215,11 +217,22 @@ def _init_home_qpos( home_pos, *, gripper_open_drive: float, + arm_controller=None, + target_pos_base=None, + default_qpos_rad=None, ): home_link6_pos = torch.tensor([home_pos], device=gs.device, dtype=gs.tc_float) init_qpos = torch.zeros(1, robot.n_dofs, device=gs.device, dtype=gs.tc_float) home_qpos_result = solve_home_ik( - robot, ik_link, home_link6_pos, down_quat, arm_dof_idx=arm_dof_idx, init_qpos=init_qpos + robot, + ik_link, + home_link6_pos, + down_quat, + arm_dof_idx=arm_dof_idx, + init_qpos=init_qpos, + arm_controller=arm_controller, + target_pos_base=target_pos_base, + default_qpos_rad=default_qpos_rad, ) for i, idx in enumerate(arm_dof_idx): init_qpos[:, idx] = home_qpos_result[0, arm_dof_idx[i]] @@ -270,6 +283,25 @@ def init_showcase_robot( else: open_drive = float(gripper.open_drive) home_pos = _world_home(layout, cartesian_xy_offset_m=cartesian_xy_offset_m) + offset_x, offset_y = ( + layout.simulation_grasp_center_compensation_xy if cartesian_xy_offset_m is None else cartesian_xy_offset_m + ) + home_pos_base = ( + float(layout.home_position_base[0]) + float(offset_x), + float(layout.home_position_base[1]) + float(offset_y), + float(layout.home_position_base[2]), + ) + urdf_model_path = getattr(robot, "_ufactory_model_path", "") + arm_controller = None + if urdf_model_path: + from ufactory.control import ArmMotionController + + arm_controller = ArmMotionController.from_robot( + config.robot.key, + urdf_path=urdf_model_path, + servo_rate_hz=float(config.motion.rate_hz), + allow_approx_motion=bool(config.motion.allow_approx_motion), + ) home_qpos_saved = _init_home_qpos( robot, ik_link, @@ -278,6 +310,9 @@ def init_showcase_robot( down_quat, home_pos, gripper_open_drive=open_drive, + arm_controller=arm_controller, + target_pos_base=home_pos_base, + default_qpos_rad=config.arm.default_qpos_rad, ) scene.step() finger_z_offset = _measure_finger_offset(ik_link, left_finger, right_finger) @@ -309,21 +344,24 @@ def init_showcase_robot( gripper_initial_open_clearance_m=0.0, g2_controller=adapter, robotiq_controller=robotiq_adapter, - home_settle_steps=max(1, int(round(task_layout.simulation_home_settle_s * config.motion.rate_hz))), + home_settle_steps=max(1, int(round(task_layout.simulation_home_settle_s * config.simulation.rate_hz))), + sim_dt=1.0 / float(config.simulation.rate_hz), + arm_controller=arm_controller, ) def hold_robot_home(robot, scene, ctx: ShowcaseRobotCtx, *, steps: int = 1) -> None: target_qpos = ctx.home_qpos_saved gripper_open = torch.full((1, 1), ctx.gripper_open_drive, device=gs.device, dtype=gs.tc_float) + step_dt = float(getattr(ctx, "sim_dt", SIM_DT)) for _ in range(steps): robot.control_dofs_position(target_qpos[:, ctx.arm_dof_idx], ctx.arm_dof_idx) if ctx.g2_controller is not None: ctx.g2_controller.command(84) - ctx.g2_controller.apply(SIM_DT) + ctx.g2_controller.apply(step_dt) elif ctx.robotiq_controller is not None: ctx.robotiq_controller.command(ctx.robotiq_controller.model.spec.open_gap_mm) - ctx.robotiq_controller.apply(SIM_DT) + ctx.robotiq_controller.apply(step_dt) else: robot.control_dofs_position(gripper_open, ctx.gripper_dof_idx) scene.step() @@ -497,6 +535,7 @@ def _trajectory_context( robotiq_controller=ctx.robotiq_controller, simulation_parameters={ "rate_hz": config.motion.rate_hz, + "sim_rate_hz": float(config.simulation.rate_hz), "substeps": config.simulation.substeps, "constraint_time_constant_s": config.simulation.constraint_time_constant_s, "constraint_solver": config.simulation.constraint_solver, @@ -506,6 +545,8 @@ def _trajectory_context( "contact_resolution": config.simulation.contact_resolution, "use_gjk_collision": config.simulation.use_gjk_collision, }, + sim_rate_hz=float(config.simulation.rate_hz), + arm_controller=getattr(ctx, "arm_controller", None), ) @@ -733,7 +774,7 @@ def _run_packaging_sim_body(args: PackagingSimulationOptions, runtime_config) -> ) scene, robot, block, layout = build_packaging_scene( table_top_z, - sim_dt=SIM_DT, + sim_dt=1.0 / float(runtime_config.simulation.rate_hz), build_scene=True, show_viewer=False, runtime_config=runtime_config, diff --git a/ufactory/manipulation/tcp.py b/ufactory/manipulation/tcp.py new file mode 100644 index 0000000..4aaba70 --- /dev/null +++ b/ufactory/manipulation/tcp.py @@ -0,0 +1,210 @@ +"""Unified tool TCP offset geometry and real-controller consistency checks. + +Runtime YAML configs store ``gripper.tcp_offset`` as a 6-element vector +``[x_mm, y_mm, z_mm, roll_deg, pitch_deg, yaw_deg]`` matching the default +``xarm-python-sdk`` (``is_radian=False``) and UFACTORY Studio conventions. +Internal kinematics (:mod:`ufactory.kinematics.tcp_offset`, +:class:`~ufactory.control.ArmMotionController`) use ``[mm, mm, mm, rad, rad, rad]``. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import math +from typing import Any + +import numpy as np + +from ufactory.kinematics.orientation import GRIPPER_DOWN_RPY_RAD +from ufactory.kinematics.tcp_offset import pose_flange_to_tcp, pose_tcp_to_flange, rpy_matrix +from ufactory.types import FloatArray + +DEFAULT_REAL_TCP_POS_TOL_MM = 10.0 +DEFAULT_REAL_TCP_ROT_TOL_DEG = 2.0 + +_ADAPTER_TOOL_TIP_LINKS: dict[str, str] = { + "bio_g2": "bio_gripper_g2_tcp_link", + "bio_gripper_g2": "bio_gripper_g2_tcp_link", + "vacuum_gripper": "vacuum_tcp", + "lite6_vacuum_gripper": "link_tcp", +} + + +def _as_vec6(values: Sequence[float] | np.ndarray[Any, Any], *, name: str) -> FloatArray: + arr: FloatArray = np.asarray(values, dtype=np.float64).reshape(-1) + if arr.size != 6 or not np.all(np.isfinite(arr)): + raise ValueError(f"{name} must contain 6 finite values") + out: FloatArray = arr.copy() + return out + + +def tcp_offset_mm_deg_to_mm_rad(tcp_offset_mm_deg: Sequence[float] | np.ndarray[Any, Any]) -> FloatArray: + """Convert ``[x_mm, y_mm, z_mm, r_deg, p_deg, y_deg]`` to ``[mm, mm, mm, rad, rad, rad]``.""" + arr = _as_vec6(tcp_offset_mm_deg, name="tcp_offset_mm_deg") + arr[3:] = np.deg2rad(arr[3:]) + return arr + + +def tcp_offset_mm_rad_to_mm_deg(tcp_offset_mm_rad: Sequence[float] | np.ndarray[Any, Any]) -> FloatArray: + """Convert ``[x_mm, y_mm, z_mm, r_rad, p_rad, y_rad]`` to ``[mm, mm, mm, deg, deg, deg]``.""" + arr = _as_vec6(tcp_offset_mm_rad, name="tcp_offset_mm_rad") + arr[3:] = np.rad2deg(arr[3:]) + return arr + + +@dataclass(frozen=True) +class ToolTcpSpec: + """Flange-to-tool-TCP specification used for task planning and mirroring.""" + + tcp_offset_mm_deg: tuple[float, float, float, float, float, float] = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + tool_tip_link: str | None = None + grasp_table_clearance_m: float = 0.0 + grasp_height_extra_m: float = 0.0 + + def __post_init__(self) -> None: + vec = _as_vec6(self.tcp_offset_mm_deg, name="tcp_offset_mm_deg") + object.__setattr__( + self, + "tcp_offset_mm_deg", + (float(vec[0]), float(vec[1]), float(vec[2]), float(vec[3]), float(vec[4]), float(vec[5])), + ) + for name in ("grasp_table_clearance_m", "grasp_height_extra_m"): + val = float(getattr(self, name)) + if not math.isfinite(val) or val < 0.0: + raise ValueError(f"{name} must be finite and non-negative") + object.__setattr__(self, name, val) + + @property + def tcp_offset_mm_rad(self) -> FloatArray: + """Return ``[x_mm, y_mm, z_mm, r_rad, p_rad, y_rad]`` for SDK / ArmMotionController.""" + return tcp_offset_mm_deg_to_mm_rad(self.tcp_offset_mm_deg) + + @property + def tcp_offset_flange_m(self) -> tuple[float, float, float]: + """Return ``(x_m, y_m, z_m)`` of the TCP expressed in the flange frame.""" + return ( + self.tcp_offset_mm_deg[0] / 1000.0, + self.tcp_offset_mm_deg[1] / 1000.0, + self.tcp_offset_mm_deg[2] / 1000.0, + ) + + @property + def grasp_tcp_z_m(self) -> float: + """Configured TCP height above table (m) at grasp/place contact.""" + return self.grasp_table_clearance_m + self.grasp_height_extra_m + + def tcp_to_flange_xyz( + self, + tcp_xyz_base_m: Sequence[float] | np.ndarray[Any, Any], + *, + orientation_rpy_rad: Sequence[float] = GRIPPER_DOWN_RPY_RAD, + ) -> FloatArray: + """Convert base-frame TCP xyz (m) to flange (link6) xyz (m) at the given tool orientation.""" + xyz: FloatArray = np.asarray(tcp_xyz_base_m, dtype=np.float64).reshape(3) + rpy = tuple(float(v) for v in orientation_rpy_rad) + tcp_pose_mm_rpy = [xyz[0] * 1000.0, xyz[1] * 1000.0, xyz[2] * 1000.0, rpy[0], rpy[1], rpy[2]] + flange_pose_mm_rpy = pose_tcp_to_flange(tcp_pose_mm_rpy, self.tcp_offset_mm_rad) + result: FloatArray = np.asarray(flange_pose_mm_rpy[:3], dtype=np.float64) / 1000.0 + return result + + def flange_to_tcp_xyz( + self, + flange_xyz_base_m: Sequence[float] | np.ndarray[Any, Any], + *, + orientation_rpy_rad: Sequence[float] = GRIPPER_DOWN_RPY_RAD, + ) -> FloatArray: + """Convert base-frame flange (link6) xyz (m) to TCP xyz (m) at the given tool orientation.""" + xyz: FloatArray = np.asarray(flange_xyz_base_m, dtype=np.float64).reshape(3) + rpy = tuple(float(v) for v in orientation_rpy_rad) + flange_pose_mm_rpy = [xyz[0] * 1000.0, xyz[1] * 1000.0, xyz[2] * 1000.0, rpy[0], rpy[1], rpy[2]] + tcp_pose_mm_rpy = pose_flange_to_tcp(flange_pose_mm_rpy, self.tcp_offset_mm_rad) + result: FloatArray = np.asarray(tcp_pose_mm_rpy[:3], dtype=np.float64) / 1000.0 + return result + + +def resolve_tool_tcp_spec(config_or_gripper: Any) -> ToolTcpSpec: + """Resolve a :class:`ToolTcpSpec` from runtime config, GripperProfile, GripperControlParams, or ``None``.""" + if config_or_gripper is None: + return ToolTcpSpec() + if hasattr(config_or_gripper, "gripper") and hasattr(config_or_gripper, "robot"): + return resolve_tool_tcp_spec(config_or_gripper.gripper) + if hasattr(config_or_gripper, "tcp_offset"): + adapter = str(getattr(config_or_gripper, "adapter", "")) + vec = _as_vec6(config_or_gripper.tcp_offset, name="gripper.tcp_offset") + return ToolTcpSpec( + tcp_offset_mm_deg=( + float(vec[0]), + float(vec[1]), + float(vec[2]), + float(vec[3]), + float(vec[4]), + float(vec[5]), + ), + tool_tip_link=_ADAPTER_TOOL_TIP_LINKS.get(adapter), + grasp_table_clearance_m=float(getattr(config_or_gripper, "grasp_table_clearance_m", 0.0)), + grasp_height_extra_m=float(getattr(config_or_gripper, "grasp_height_extra_m", 0.0)), + ) + if hasattr(config_or_gripper, "tcp_offset_mm_deg"): + vec = _as_vec6(config_or_gripper.tcp_offset_mm_deg, name="gripper.tcp_offset_mm_deg") + family = str(getattr(config_or_gripper, "family", "")) + tip_link = getattr(config_or_gripper, "tool_tip_link", None) or _ADAPTER_TOOL_TIP_LINKS.get(family) + return ToolTcpSpec( + tcp_offset_mm_deg=( + float(vec[0]), + float(vec[1]), + float(vec[2]), + float(vec[3]), + float(vec[4]), + float(vec[5]), + ), + tool_tip_link=tip_link, + ) + raise TypeError(f"unsupported object for resolve_tool_tcp_spec: {type(config_or_gripper).__name__}") + + +def tcp_offset_difference( + controller_tcp_mm_rad: Sequence[float] | np.ndarray[Any, Any], + expected_tcp_mm_deg: Sequence[float] | np.ndarray[Any, Any], +) -> tuple[float, float]: + """Return ``(pos_diff_mm, rot_diff_deg)`` between live controller TCP (mm, rad) and YAML TCP (mm, deg).""" + ctrl = _as_vec6(controller_tcp_mm_rad, name="controller_tcp_mm_rad") + exp = tcp_offset_mm_deg_to_mm_rad(expected_tcp_mm_deg) + pos_diff_mm = float(np.linalg.norm(ctrl[:3] - exp[:3])) + r_ctrl = rpy_matrix(float(ctrl[3]), float(ctrl[4]), float(ctrl[5])) + r_exp = rpy_matrix(float(exp[3]), float(exp[4]), float(exp[5])) + cos_angle = float(np.clip((np.trace(r_ctrl.T @ r_exp) - 1.0) / 2.0, -1.0, 1.0)) + rot_diff_deg = math.degrees(math.acos(cos_angle)) + return pos_diff_mm, rot_diff_deg + + +def check_controller_tcp_offset( + controller_tcp_mm_rad: Sequence[float] | np.ndarray[Any, Any], + expected_tcp_mm_deg: Sequence[float] | np.ndarray[Any, Any], + *, + mode: str, + pos_tol_mm: float = DEFAULT_REAL_TCP_POS_TOL_MM, + rot_tol_deg: float = DEFAULT_REAL_TCP_ROT_TOL_DEG, +) -> tuple[float, float]: + """Verify controller TCP offset against YAML; fail closed in ``real`` mode on mismatch.""" + pos_diff_mm, rot_diff_deg = tcp_offset_difference(controller_tcp_mm_rad, expected_tcp_mm_deg) + ctrl_deg = np.round(tcp_offset_mm_rad_to_mm_deg(controller_tcp_mm_rad), 3).tolist() + exp_deg = np.round(_as_vec6(expected_tcp_mm_deg, name="expected_tcp_mm_deg"), 3).tolist() + if pos_diff_mm > float(pos_tol_mm) or rot_diff_deg > float(rot_tol_deg): + detail = ( + f"controller tcp_offset {ctrl_deg} (mm, deg) differs from YAML tcp_offset {exp_deg} (mm, deg) " + f"by pos={pos_diff_mm:.2f} mm / rot={rot_diff_deg:.2f} deg " + f"(limits: {float(pos_tol_mm):.1f} mm / {float(rot_tol_deg):.1f} deg)" + ) + if str(mode) == "real": + raise RuntimeError( + f"real motion refused: {detail}; verify the physically mounted end effector " + "and UFACTORY Studio TCP offset match the selected --gripper" + ) + print(f"[hardware] WARNING: {detail}", flush=True) + return pos_diff_mm, rot_diff_deg + print( + f"[hardware] tcp_offset check PASS pos_diff={pos_diff_mm:.2f}mm rot_diff={rot_diff_deg:.2f}deg", + flush=True, + ) + return pos_diff_mm, rot_diff_deg diff --git a/ufactory/quality/project_check.py b/ufactory/quality/project_check.py index 463d3e7..d4878ea 100644 --- a/ufactory/quality/project_check.py +++ b/ufactory/quality/project_check.py @@ -358,6 +358,11 @@ def fast(self) -> None: "--strict", "--follow-imports=skip", "ufactory/config", + "ufactory/control", + "ufactory/grippers/vacuum.py", + "ufactory/hardware/ft_sensor.py", + "ufactory/kinematics/controller_fk.py", + "ufactory/manipulation/tcp.py", "ufactory/safety/models.py", "ufactory/safety/interfaces.py", "ufactory/safety/statistics.py", diff --git a/ufactory/robots/__init__.py b/ufactory/robots/__init__.py index ff2eee9..ae45cc2 100644 --- a/ufactory/robots/__init__.py +++ b/ufactory/robots/__init__.py @@ -11,20 +11,27 @@ ) from ufactory.robots.assembly import ( AssemblyError, + FTSensor, accessories, adapters, compose_robot_urdf, compose_standalone_adapter_urdf, + compose_standalone_ft_sensor_urdf, + ft_sensors, get_adapter, + get_ft_sensor, mounting_plate_for, mounting_plates, parse_assembly_ref, supported_accessories, supported_end_effectors, + supported_ft_sensors, + supports_ft_sensor, ) from ufactory.robots.paths import ( DYNAMICS_VALIDATION_POSES_YAML, bio_gripper_g2_movable_visual_urdf, + ft_sensor_ai1500_urdf, gripper_g2_movable_visual_urdf, kinematics_user_dir, lite6_gripper_movable_visual_urdf, @@ -59,9 +66,15 @@ "RobotModelSpec", "RobotRuntimeProfile", "AssemblyError", + "FTSensor", "adapters", "get_adapter", + "ft_sensors", + "get_ft_sensor", + "supported_ft_sensors", + "supports_ft_sensor", "compose_standalone_adapter_urdf", + "compose_standalone_ft_sensor_urdf", "mounting_plate_for", "mounting_plates", "compose_robot_urdf", @@ -77,5 +90,6 @@ "robot_urdf", "robot_visual_glb_urdf", "robotiq_mounting_urdf", + "ft_sensor_ai1500_urdf", "kinematics_user_dir", ] diff --git a/ufactory/robots/assembly.py b/ufactory/robots/assembly.py index e1063a4..156f802 100644 --- a/ufactory/robots/assembly.py +++ b/ufactory/robots/assembly.py @@ -10,13 +10,14 @@ Runtime configurations and :func:`ufactory.robots.paths.robot_urdf` accept an assembly reference in place of a URDF file name:: - assembly:[+][+mounting_plate][:] + assembly:[+][+][+mounting_plate][:] + assembly:bare+[+][+mounting_plate][:] assembly:bare+[+mounting_plate][:] assembly:bare+mounting_plate[:] ``bare`` means no end effector. ``visual`` is ``glb`` (default, per-link GLB arm and gripper visuals) or ``stl`` (the -arm's dynamics URDF; end-effector GLB visuals are replaced by their collision geometry; cameras and mounting plates draw -their collision geometry). +arm's dynamics URDF; end-effector GLB visuals are replaced by their collision geometry; cameras, F/T sensors, and +mounting plates draw their STL/collision geometry). """ from __future__ import annotations @@ -44,6 +45,7 @@ BARE = "bare" MOUNTING_PLATE = "mounting_plate" +FT_SENSOR_PREFIX = "ft_sensor_" class AssemblyError(ValueError): @@ -91,6 +93,22 @@ class Adapter: stl_materials: Mapping[str, str] +@dataclass(frozen=True) +class FTSensor: + name: str + source: str + base_link: str + output_link: str + mount_joint: str + flange: str + robots: tuple[str, ...] + mount: Pose + tool_lift_m: float + glb_visuals: Mapping[str, str] + stl_visuals: Mapping[str, str] + stl_materials: Mapping[str, str] + + @dataclass(frozen=True) class Spacer: name: str @@ -150,6 +168,7 @@ def stl_materials(self) -> Mapping[str, str]: ... class _Catalog: end_effectors: dict[str, EndEffector] adapters: dict[str, Adapter] + ft_sensors: dict[str, FTSensor] spacers: dict[str, Spacer] cameras: dict[str, Camera] mounting_plates: dict[str, MountingPlate] @@ -161,6 +180,7 @@ class AssemblyRef: visual: str = "glb" accessory: str | None = None mounting_plate: bool = False + ft_sensor: str | None = None def __str__(self) -> str: return assembly_ref( @@ -168,6 +188,7 @@ def __str__(self) -> str: visual=self.visual, accessory=self.accessory, mounting_plate=self.mounting_plate, + ft_sensor=self.ft_sensor, ) @@ -205,7 +226,7 @@ def _str_map(value: Any) -> dict[str, str]: @lru_cache(maxsize=8) def _load_catalog(path: Path, mtime_ns: int) -> _Catalog: data = yaml.safe_load(path.read_text(encoding="utf-8")) - if not isinstance(data, dict) or data.get("schema_version") not in (3, 4, 5): + if not isinstance(data, dict) or data.get("schema_version") not in (3, 4, 5, 6): raise AssemblyError(f"{path}: unsupported assembly schema") flanges = _load_flanges(data, path) @@ -251,6 +272,33 @@ def flanges_of(name: str, spec: Mapping[str, Any]) -> tuple[str, ...]: stl_materials=_str_map(spec.get("stl_materials")), ) + ft_sensor_map: dict[str, FTSensor] = {} + for name, spec in (data.get("ft_sensors") or {}).items(): + sensor_name = str(name) + if not sensor_name.startswith(FT_SENSOR_PREFIX): + raise AssemblyError(f"{sensor_name}: ft_sensors entry name must start with {FT_SENSOR_PREFIX!r}") + flange = flange_of(sensor_name, spec) + lift_m = float(spec.get("tool_lift_m", 0.0)) + if lift_m < 0.0: + raise AssemblyError(f"{sensor_name}: tool_lift_m must be non-negative") + output_link = str(spec.get("output_link", "")).strip() + if not output_link: + raise AssemblyError(f"{sensor_name}: output_link is required") + ft_sensor_map[sensor_name] = FTSensor( + name=sensor_name, + source=str(spec["source"]), + base_link=str(spec["base_link"]), + output_link=output_link, + mount_joint=str(spec["mount_joint"]), + flange=flange, + robots=flanges[flange], + mount=_pose(spec, sensor_name), + tool_lift_m=lift_m, + glb_visuals=_str_map(spec.get("glb_visuals")), + stl_visuals=_str_map(spec.get("stl_visuals")), + stl_materials=_str_map(spec.get("stl_materials")), + ) + out: dict[str, EndEffector] = {} for name, spec in (data.get("end_effectors") or {}).items(): ee_name = str(name) @@ -345,7 +393,7 @@ def flanges_of(name: str, spec: Mapping[str, Any]) -> tuple[str, ...]: stl_visuals=_str_map(spec.get("stl_visuals")), stl_materials=_str_map(spec.get("stl_materials")), ) - sections = (set(out), set(adapter_map), set(spacers), set(cameras), set(plates)) + sections = (set(out), set(adapter_map), set(ft_sensor_map), set(spacers), set(cameras), set(plates)) seen: set[str] = set() clash: set[str] = set() for sec in sections: @@ -356,7 +404,7 @@ def flanges_of(name: str, spec: Mapping[str, Any]) -> tuple[str, ...]: raise AssemblyError( f"{path}: part names must be unique across sections and not {BARE!r}/{MOUNTING_PLATE!r}: {sorted(clash)}" ) - return _Catalog(out, adapter_map, spacers, cameras, plates) + return _Catalog(out, adapter_map, ft_sensor_map, spacers, cameras, plates) def _catalog(root: Path | None = None) -> _Catalog: @@ -382,6 +430,30 @@ def get_adapter(name: str, root: Path | None = None) -> Adapter: return parts[name] +def ft_sensors(root: Path | None = None) -> dict[str, FTSensor]: + """Six-axis force/torque sensors declared in ``assets/urdf/assembly.yaml``.""" + return _catalog(root).ft_sensors + + +def get_ft_sensor(name: str, root: Path | None = None) -> FTSensor: + """Return a declared six-axis force/torque sensor by name.""" + parts = ft_sensors(root) + if name not in parts: + raise AssemblyError(f"unknown F/T sensor {name!r}; expected one of {sorted(parts)}") + return parts[name] + + +def supported_ft_sensors(robot_key: str, root: Path | None = None) -> tuple[str, ...]: + """F/T sensors compatible with ``robot_key``.""" + key = get_profile_key_for_robot_name(robot_key) + return tuple(name for name, sensor in ft_sensors(root).items() if key in sensor.robots) + + +def supports_ft_sensor(robot_key: str, ft_sensor: str, root: Path | None = None) -> bool: + """Whether ``ft_sensor`` fits ``robot_key``.""" + return ft_sensor in supported_ft_sensors(robot_key, root) + + def spacers(root: Path | None = None) -> dict[str, Spacer]: """Spacers (camera stands) declared in ``assets/urdf/assembly.yaml``.""" return _catalog(root).spacers @@ -472,11 +544,14 @@ def assembly_ref( visual: str = "glb", accessory: str | None = None, mounting_plate: bool = False, + ft_sensor: str | None = None, ) -> str: """Canonical reference string, omitting default fields.""" - if end_effector is None and accessory is None and not mounting_plate: - raise AssemblyError("an assembly needs an end effector or an accessory, or a mounting plate") + if end_effector is None and ft_sensor is None and accessory is None and not mounting_plate: + raise AssemblyError("an assembly needs an end effector or an accessory, an F/T sensor, or a mounting plate") tokens = [end_effector or BARE] + if ft_sensor: + tokens.append(ft_sensor) if accessory: tokens.append(accessory) if mounting_plate: @@ -488,7 +563,7 @@ def assembly_ref( def parse_assembly_ref(value: str) -> AssemblyRef | None: - """Parse ``assembly:[+][+mounting_plate][:]``; ``None`` for a file name.""" + """Parse ``assembly:[+][+][+mounting_plate][:]``; ``None`` for a file name.""" if not value.startswith(ASSEMBLY_PREFIX): return None fields = value[len(ASSEMBLY_PREFIX) :].split(":") @@ -498,19 +573,21 @@ def parse_assembly_ref(value: str) -> AssemblyRef | None: if any(not tok for tok in tokens): raise AssemblyError(f"malformed assembly reference {value!r}") head, *extras = tokens - if head == MOUNTING_PLATE or extras.count(MOUNTING_PLATE) > 1: + if head == MOUNTING_PLATE or head.startswith(FT_SENSOR_PREFIX) or extras.count(MOUNTING_PLATE) > 1: raise AssemblyError(f"malformed assembly reference {value!r}") has_mounting_plate = MOUNTING_PLATE in extras - acc_tokens = [tok for tok in extras if tok != MOUNTING_PLATE] - if len(acc_tokens) > 1: + ft_tokens = [tok for tok in extras if tok.startswith(FT_SENSOR_PREFIX)] + acc_tokens = [tok for tok in extras if tok != MOUNTING_PLATE and not tok.startswith(FT_SENSOR_PREFIX)] + if len(ft_tokens) > 1 or len(acc_tokens) > 1: raise AssemblyError(f"malformed assembly reference {value!r}") + ft_sensor = ft_tokens[0] if ft_tokens else None accessory = acc_tokens[0] if acc_tokens else None - if head == BARE and accessory is None and not has_mounting_plate: + if head == BARE and ft_sensor is None and accessory is None and not has_mounting_plate: raise AssemblyError(f"malformed assembly reference {value!r}") visual = fields[1] if len(fields) > 1 else "glb" if visual not in VISUALS: raise AssemblyError(f"{value!r}: visual must be one of {VISUALS}") - return AssemblyRef(None if head == BARE else head, visual, accessory, has_mounting_plate) + return AssemblyRef(None if head == BARE else head, visual, accessory, has_mounting_plate, ft_sensor) def validate_assembly( @@ -520,6 +597,7 @@ def validate_assembly( visual: str = "glb", accessory: str | None = None, mounting_plate: bool = False, + ft_sensor: str | None = None, root: Path | None = None, ) -> EndEffector | None: """Check that the assembly can be composed, without writing anything.""" @@ -527,13 +605,18 @@ def validate_assembly( key = get_profile_key_for_robot_name(robot_key) if visual not in VISUALS: raise AssemblyError(f"visual must be one of {VISUALS}") - if end_effector is None and accessory is None and not mounting_plate: - raise AssemblyError("an assembly needs an end effector or an accessory, or a mounting plate") + if end_effector is None and ft_sensor is None and accessory is None and not mounting_plate: + raise AssemblyError("an assembly needs an end effector or an accessory, an F/T sensor, or a mounting plate") urdf_root = root / "assets" / "urdf" sources = [_arm_source(key, visual, root)] if mounting_plate: plate = mounting_plate_for(key, root) sources.append(urdf_root / plate.source) + if ft_sensor is not None: + ft = get_ft_sensor(ft_sensor, root) + if key not in ft.robots: + raise AssemblyError(f"{ft_sensor} is not supported on {key}; supported robots: {list(ft.robots)}") + sources.append(urdf_root / ft.source) ee = None if end_effector is not None: ee = get_end_effector(end_effector, root) @@ -563,7 +646,7 @@ def validate_assembly( def _arm_source(robot_key: str, visual: str, root: Path) -> Path: profile = ROBOT_PROFILES[robot_key] name = str(profile.visual_glb_urdf if visual == "glb" else profile.default_urdf) - return root / "assets" / "urdf" / str(profile.assets_dir.name) / name + return root / "assets" / "urdf" / "robots" / str(profile.assets_dir.name) / name def _fmt(values: tuple[float, float, float]) -> str: @@ -585,7 +668,7 @@ def _link_ref(joint: ET.Element, tag: str) -> str | None: def _tool_elements( - ee: EndEffector | Adapter | Spacer | Camera | MountingPlate, source: Path + ee: EndEffector | Adapter | FTSensor | Spacer | Camera | MountingPlate, source: Path ) -> tuple[list[ET.Element], dict[str, ET.Element]]: root = ET.parse(source).getroot() attach = [j for j in root.findall("joint") if _link_ref(j, "child") == ee.base_link] @@ -653,7 +736,7 @@ def _fixed_joint(robot: ET.Element, name: str, parent: str, child: str, origin: def _attach_part( robot: ET.Element, - part: Adapter | Spacer | Camera | MountingPlate, + part: Adapter | FTSensor | Spacer | Camera | MountingPlate, parent: str, visual: str, urdf_root: Path, @@ -661,7 +744,7 @@ def _attach_part( *, z_offset: float = 0.0, ) -> None: - """Append an adapter, spacer, camera, or mounting-plate part, fixed to ``parent`` at its mount pose.""" + """Append an adapter, F/T sensor, spacer, camera, or mounting-plate part, fixed to ``parent`` at its mount pose.""" source = urdf_root / part.source elems, materials = _tool_elements(part, source) _apply_visual_mode(elems, part, visual, urdf_root) @@ -687,9 +770,21 @@ def _lift_link_eef(robot: ET.Element, lift_m: float) -> None: origin.set("xyz", _fmt((x, y, z + lift_m))) -def _assembly_label(end_effector: str | None, accessory: str | None, mounting_plate: bool = False) -> str: - label = f"{end_effector or BARE}__{accessory}" if accessory else (end_effector or BARE) - return f"{label}__{MOUNTING_PLATE}" if mounting_plate else label +def _assembly_label( + end_effector: str | None, + accessory: str | None, + mounting_plate: bool = False, + ft_sensor: str | None = None, +) -> str: + if ft_sensor is None: + label = f"{end_effector or BARE}__{accessory}" if accessory else (end_effector or BARE) + return f"{label}__{MOUNTING_PLATE}" if mounting_plate else label + parts = [end_effector or BARE, ft_sensor] + if accessory: + parts.append(accessory) + if mounting_plate: + parts.append(MOUNTING_PLATE) + return "__".join(parts) def build_assembly_tree( @@ -699,6 +794,7 @@ def build_assembly_tree( visual: str = "glb", accessory: str | None = None, mounting_plate: bool = False, + ft_sensor: str | None = None, root: Path | None = None, out_dir: Path | None = None, ) -> ET.Element: @@ -712,18 +808,22 @@ def build_assembly_tree( visual=visual, accessory=accessory, mounting_plate=mounting_plate, + ft_sensor=ft_sensor, root=root, ) urdf_root = root / "assets" / "urdf" arm_file = _arm_source(key, visual, root) flange = get_robot_profile(key).ee_link plate = mounting_plate_for(key, root) if mounting_plate else None + ft = get_ft_sensor(ft_sensor, root) if ft_sensor is not None else None spacer, camera = resolve_accessory(accessory, root) if accessory is not None else (None, None) adapter = get_adapter(ee.adapter, root) if ee is not None and ee.adapter is not None else None sources = [arm_file] if plate is not None: sources.append(urdf_root / plate.source) + if ft is not None: + sources.append(urdf_root / ft.source) if spacer is not None: sources.append(urdf_root / spacer.source) if camera is not None: @@ -732,7 +832,7 @@ def build_assembly_tree( sources.append(urdf_root / adapter.source) if ee is not None: sources.append(urdf_root / ee.source) - label = _assembly_label(end_effector, accessory, mounting_plate) + label = _assembly_label(end_effector, accessory, mounting_plate, ft_sensor) robot = ET.Element("robot", {"name": f"{key}__{label}__{visual}"}) robot.append( ET.Comment( @@ -748,16 +848,27 @@ def build_assembly_tree( if plate is not None: _attach_part(robot, plate, "link_base", visual, urdf_root, out_dir) - lift = 0.0 + tool_parent = flange + local_lift = 0.0 + total_lift = 0.0 + if ft is not None: + _attach_part(robot, ft, flange, visual, urdf_root, out_dir) + if robot.find(f"./link[@name='{ft.output_link}']") is None: + raise AssemblyError(f"{ft.name}: output_link {ft.output_link!r} missing from {ft.source}") + tool_parent = ft.output_link + total_lift += ft.tool_lift_m + if spacer is not None: - _attach_part(robot, spacer, flange, visual, urdf_root, out_dir) - lift = spacer.tool_lift_m + _attach_part(robot, spacer, tool_parent, visual, urdf_root, out_dir, z_offset=local_lift) + local_lift += spacer.tool_lift_m + total_lift += spacer.tool_lift_m if camera is not None: _attach_part(robot, camera, spacer.base_link, visual, urdf_root, out_dir) if adapter is not None: - _attach_part(robot, adapter, flange, visual, urdf_root, out_dir, z_offset=lift) - lift += adapter.tool_lift_m + _attach_part(robot, adapter, tool_parent, visual, urdf_root, out_dir, z_offset=local_lift) + local_lift += adapter.tool_lift_m + total_lift += adapter.tool_lift_m if ee is not None: tool_file = urdf_root / ee.source @@ -768,13 +879,13 @@ def build_assembly_tree( _merge_part_materials(robot, elems, tool_materials) xyz, rpy = ee.mount - if lift: - xyz = (xyz[0], xyz[1], xyz[2] + lift) + if local_lift: + xyz = (xyz[0], xyz[1], xyz[2] + local_lift) origin = {"xyz": _fmt(xyz), "rpy": _fmt(rpy)} - _fixed_joint(robot, ee.mount_joint, flange, ee.base_link, origin) + _fixed_joint(robot, ee.mount_joint, tool_parent, ee.base_link, origin) robot.extend(elems) - elif lift: - _lift_link_eef(robot, lift) + elif total_lift: + _lift_link_eef(robot, total_lift) names = [e.get("name") for e in robot if e.tag in ("link", "joint")] duplicates = sorted({n for n in names if names.count(n) > 1 and n is not None}) @@ -803,7 +914,7 @@ def _write_composed_urdf(out_dir: Path, stem: str, tree: ET.Element) -> str: def _build_standalone_part_tree( - part: EndEffector | Adapter | MountingPlate, + part: EndEffector | Adapter | FTSensor | MountingPlate, *, mount_pose: Pose, visual: str = "glb", @@ -918,6 +1029,45 @@ def compose_standalone_adapter_urdf( return _write_composed_urdf(resolved_out, f"standalone__{adapter.name}__{visual}", tree) +def build_standalone_ft_sensor_tree( + name: str, + *, + visual: str = "glb", + root: Path | None = None, + out_dir: Path | None = None, +) -> ET.Element: + """Return a standalone ```` element (rooted at ``world``) for one F/T sensor.""" + resolved_root = (root or PROJECT_ROOT).resolve() + sensor = get_ft_sensor(name, resolved_root) + return _build_standalone_part_tree( + sensor, + mount_pose=sensor.mount, + visual=visual, + root=resolved_root, + out_dir=out_dir, + ) + + +def compose_standalone_ft_sensor_urdf( + name: str, + *, + visual: str = "glb", + root: Path | None = None, + out_dir: Path | None = None, +) -> str: + """Compose (or reuse) a standalone F/T sensor URDF with visuals resolved from ``assembly.yaml``.""" + resolved_root = (root or PROJECT_ROOT).resolve() + resolved_out = (out_dir or resolved_root / COMPOSED_DIR).resolve() + tree = build_standalone_ft_sensor_tree( + name, + visual=visual, + root=resolved_root, + out_dir=resolved_out, + ) + sensor = get_ft_sensor(name, resolved_root) + return _write_composed_urdf(resolved_out, f"standalone__{sensor.name}__{visual}", tree) + + def build_standalone_mounting_plate_tree( name: str, *, @@ -964,12 +1114,13 @@ def compose_robot_urdf( visual: str = "glb", accessory: str | None = None, mounting_plate: bool = False, + ft_sensor: str | None = None, root: Path | None = None, out_dir: Path | None = None, ) -> str: """Compose (or reuse) the assembled URDF and return its absolute path. - ``end_effector`` may be ``None`` (bare arm) when ``accessory`` or ``mounting_plate=True`` is given. + ``end_effector`` may be ``None`` (bare arm) when ``ft_sensor``, ``accessory``, or ``mounting_plate=True`` is given. """ root = (root or PROJECT_ROOT).resolve() out_dir = (out_dir or root / COMPOSED_DIR).resolve() @@ -980,12 +1131,13 @@ def compose_robot_urdf( visual=visual, accessory=accessory, mounting_plate=mounting_plate, + ft_sensor=ft_sensor, root=root, out_dir=out_dir, ) return _write_composed_urdf( out_dir, - f"{key}__{_assembly_label(end_effector, accessory, mounting_plate)}__{visual}", + f"{key}__{_assembly_label(end_effector, accessory, mounting_plate, ft_sensor)}__{visual}", tree, ) @@ -1008,6 +1160,7 @@ def resolve_robot_urdf( visual=ref.visual, accessory=ref.accessory, mounting_plate=ref.mounting_plate, + ft_sensor=ref.ft_sensor, root=root, ) ) @@ -1038,5 +1191,6 @@ def validate_robot_urdf( visual=ref.visual, accessory=ref.accessory, mounting_plate=ref.mounting_plate, + ft_sensor=ref.ft_sensor, root=store.root, ) diff --git a/ufactory/robots/paths.py b/ufactory/robots/paths.py index 921a6fb..105a203 100644 --- a/ufactory/robots/paths.py +++ b/ufactory/robots/paths.py @@ -6,10 +6,11 @@ compose_robot_urdf, compose_standalone_adapter_urdf, compose_standalone_end_effector_urdf, + compose_standalone_ft_sensor_urdf, compose_standalone_mounting_plate_urdf, parse_assembly_ref, ) -from ufactory.robots.registry import PROJECT_ROOT, get_robot_profile +from ufactory.robots.registry import PROJECT_ROOT, URDF_ROOT, get_robot_profile DYNAMICS_VALIDATION_POSES_YAML = PROJECT_ROOT / "assets" / "configs" / "dynamics_validation_pose.yaml" @@ -69,6 +70,7 @@ def robot_urdf(robot_key: str, name: str | None = None) -> str: visual=ref.visual, accessory=ref.accessory, mounting_plate=ref.mounting_plate, + ft_sensor=ref.ft_sensor, ) return _urdf_path(profile.assets_dir, urdf_name) @@ -97,8 +99,9 @@ def robot_visual_glb_urdf( movable: bool = False, accessory: str | None = None, mounting_plate: bool = False, + ft_sensor: str | None = None, ) -> str: - """GLB-visual URDF of an arm, optionally composed with an end effector, accessory, and/or mounting plate. + """GLB-visual URDF of an arm, optionally composed with an F/T sensor, end effector, accessory, and/or mounting plate. Without parts this is the arm's ``*_visual.glb.urdf``. With any, the arm and parts are assembled at runtime using per-link visuals; ``movable`` is kept for compatibility (grippers always use per-link movable visuals). @@ -128,40 +131,54 @@ def robot_visual_glb_urdf( "movable=True requires with_gripper_g2=True, with_robotiq_2f_85=True, " "with_robotiq_2f_140=True, with_lite6_gripper=True, or with_bio_gripper_g2=True" ) + if ft_sensor is not None and not profile.supports_ft_sensor(ft_sensor): + raise ValueError(f"Robot {robot_key} does not support F/T sensor {ft_sensor}") if not selected: - if accessory is None and not mounting_plate: + if accessory is None and not mounting_plate and ft_sensor is None: return _urdf_path(profile.assets_dir, profile.visual_glb_urdf) if accessory is not None and not profile.supports_accessory(accessory): raise ValueError(f"Robot {robot_key} does not support {accessory}") - return compose_robot_urdf(profile.key, None, visual="glb", accessory=accessory, mounting_plate=mounting_plate) + return compose_robot_urdf( + profile.key, + None, + visual="glb", + accessory=accessory, + mounting_plate=mounting_plate, + ft_sensor=ft_sensor, + ) end_effector, label = selected[0] if not profile.supports(end_effector): raise ValueError(f"Robot {robot_key} does not support {label}") if accessory is not None and not profile.supports_accessory(accessory, end_effector): raise ValueError(f"{accessory} does not fit {label} on {robot_key}") return compose_robot_urdf( - profile.key, end_effector, visual="glb", accessory=accessory, mounting_plate=mounting_plate + profile.key, + end_effector, + visual="glb", + accessory=accessory, + mounting_plate=mounting_plate, + ft_sensor=ft_sensor, ) def lite6_gripper_movable_visual_urdf() -> str: """Standalone Lite6 gripper-only movable visual URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "lite6_gripper" / "lite6_gripper_movable_visual.urdf") def gripper_g2_movable_visual_urdf() -> str: """Standalone gripper-only movable visual URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "gripper_g2" / "gripper_g2_movable_visual.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "gripper_g2" / "gripper_g2_movable_visual.urdf") def robotiq_2f_85_movable_visual_urdf() -> str: """Standalone Robotiq 2F-85 gripper-only movable visual URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "robotiq_2f_85" / "robotiq_2f_85_movable_visual.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "robotiq_2f_85" / "robotiq_2f_85_movable_visual.urdf") def robotiq_2f_140_movable_visual_urdf() -> str: """Standalone Robotiq 2F-140 gripper-only movable visual URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "robotiq_2f_140" / "robotiq_2f_140_movable_visual.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "robotiq_2f_140" / "robotiq_2f_140_movable_visual.urdf") def robotiq_mounting_urdf() -> str: @@ -169,19 +186,24 @@ def robotiq_mounting_urdf() -> str: return compose_standalone_adapter_urdf("robotiq_mounting", visual="glb") +def ft_sensor_ai1500_urdf() -> str: + """Standalone UFACTORY AI1500 six-axis F/T sensor URDF with GLB visual resolved from assembly.yaml.""" + return compose_standalone_ft_sensor_urdf("ft_sensor_ai1500", visual="glb") + + def bio_gripper_g2_urdf() -> str: """Standalone Bio Gripper G2 URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "bio_gripper_g2" / "bio_gripper_g2.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "bio_gripper_g2" / "bio_gripper_g2.urdf") def bio_gripper_g2_movable_visual_urdf() -> str: """Standalone Bio Gripper G2 movable visual URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf") def vacuum_gripper_urdf() -> str: """Standalone xArm / UF850 vacuum gripper URDF (no arm).""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "vacuum_gripper" / "vacuum_gripper.urdf") + return _existing_path(URDF_ROOT / "end_effectors" / "vacuum_gripper" / "vacuum_gripper.urdf") def lite6_vacuum_gripper_visual_glb_urdf() -> str: @@ -206,4 +228,4 @@ def lite6_mounting_plate_urdf() -> str: def microplate_sbs_96_well_urdf() -> str: """SBS 96-well microplate URDF for Bio Gripper G2 pick-and-place.""" - return _existing_path(PROJECT_ROOT / "assets" / "urdf" / "microplate" / "sbs_96_well.urdf") + return _existing_path(URDF_ROOT / "objects" / "microplate" / "sbs_96_well.urdf") diff --git a/ufactory/robots/registry.py b/ufactory/robots/registry.py index 7a1af2f..8f89ef3 100644 --- a/ufactory/robots/registry.py +++ b/ufactory/robots/registry.py @@ -6,6 +6,7 @@ from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[2] +URDF_ROOT = PROJECT_ROOT / "assets" / "urdf" @dataclass(frozen=True) @@ -68,6 +69,16 @@ def supports_accessory(self, accessory: str, end_effector: str | None = None) -> def supports_camera_stand(self) -> bool: return self.supports_accessory("camera_stand") + def supports_ft_sensor(self, ft_sensor: str) -> bool: + """Whether a six-axis force/torque sensor fits this arm's tool flange.""" + from ufactory.robots.assembly import supports_ft_sensor + + return supports_ft_sensor(self.key, ft_sensor) + + @property + def supports_ft_sensor_ai1500(self) -> bool: + return self.supports_ft_sensor("ft_sensor_ai1500") + @property def supports_mounting_plate(self) -> bool: return True @@ -81,7 +92,7 @@ def mounting_plate(self) -> str: def _assets(robot: str) -> Path: - return PROJECT_ROOT / "assets" / "urdf" / robot + return URDF_ROOT / "robots" / robot def _xarm_profile(dof: int) -> RobotModelSpec: diff --git a/ufactory/robots/runtime.py b/ufactory/robots/runtime.py index 0841ee3..e28c3fd 100644 --- a/ufactory/robots/runtime.py +++ b/ufactory/robots/runtime.py @@ -7,6 +7,13 @@ import xml.etree.ElementTree as ET from ufactory.robots.registry import RobotModelSpec, get_robot_profile, joint_names, robot_cli_choices +from ufactory.grippers.bio_g2 import ( + BIO_G2_JOINT_NAMES, + BIO_GRIPPER_G2_CLOSED_GAP_M, + BIO_GRIPPER_G2_OPEN_GAP_M, + BIO_GRIPPER_G2_SIM_CLOSED_DRIVE, + BIO_GRIPPER_G2_SIM_OPEN_DRIVE, +) from ufactory.grippers.g2 import G2_JOINT_NAMES, GRIPPER_G2_SIM_OPEN_DRIVE, GRIPPER_G2_SIM_CLOSE_DRIVE from ufactory.grippers.robotiq import ( ROBOTIQ_2F_85_JOINT_NAMES, @@ -77,9 +84,9 @@ class GripperControlParams: """ family: str - drive_joint: str + drive_joint: str | None all_joint_names: tuple[str, ...] - finger_link_names: tuple[str, str] + finger_link_names: tuple[str, ...] open_pos: float close_pos: float closed_gap_m: float @@ -90,6 +97,16 @@ class GripperControlParams: force_upper: float damping: float frictionloss: float + tool_tip_link: str | None = None + tcp_offset_mm_deg: tuple[float, float, float, float, float, float] = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + @property + def has_actuated_joints(self) -> bool: + return bool(self.drive_joint and self.all_joint_names) + + @property + def has_finger_links(self) -> bool: + return len(self.finger_link_names) >= 2 @dataclass(frozen=True) @@ -137,6 +154,7 @@ class RobotRuntimeProfile: force_upper=5.0, damping=0.1, frictionloss=0.0, + tcp_offset_mm_deg=(0.0, 0.0, 178.6, 0.0, 0.0, 0.0), ) LITE6_GRIPPER_PARAMS = GripperControlParams( @@ -154,6 +172,7 @@ class RobotRuntimeProfile: force_upper=20.0, damping=0.05, frictionloss=0.0, + tcp_offset_mm_deg=(0.0, 0.0, 75.3, 0.0, 0.0, 0.0), ) ROBOTIQ_2F_85_GRIPPER_PARAMS = GripperControlParams( @@ -171,6 +190,7 @@ class RobotRuntimeProfile: force_upper=30.0, damping=0.1, frictionloss=0.0, + tcp_offset_mm_deg=(0.0, 0.0, 173.8, 0.0, 0.0, 0.0), ) ROBOTIQ_2F_140_GRIPPER_PARAMS = GripperControlParams( @@ -188,6 +208,64 @@ class RobotRuntimeProfile: force_upper=30.0, damping=0.1, frictionloss=0.0, + tcp_offset_mm_deg=(0.0, 0.0, 246.1, 0.0, 0.0, 0.0), +) + +BIO_GRIPPER_G2_GRIPPER_PARAMS = GripperControlParams( + family="bio_gripper_g2", + drive_joint="bio_gripper_g2_right_finger_joint", + all_joint_names=BIO_G2_JOINT_NAMES, + finger_link_names=("bio_gripper_g2_left_finger", "bio_gripper_g2_right_finger"), + open_pos=BIO_GRIPPER_G2_SIM_OPEN_DRIVE, + close_pos=BIO_GRIPPER_G2_SIM_CLOSED_DRIVE, + closed_gap_m=BIO_GRIPPER_G2_CLOSED_GAP_M, + open_gap_m=BIO_GRIPPER_G2_OPEN_GAP_M, + kp=16000.0, + kv=40.0, + force_lower=-20.0, + force_upper=20.0, + damping=0.1, + frictionloss=0.0, + tool_tip_link="bio_gripper_g2_tcp_link", + tcp_offset_mm_deg=(157.64, 0.0, 59.5, 0.0, 0.0, 0.0), +) + +VACUUM_GRIPPER_PARAMS = GripperControlParams( + family="vacuum_gripper", + drive_joint=None, + all_joint_names=(), + finger_link_names=(), + open_pos=0.0, + close_pos=0.0, + closed_gap_m=0.0, + open_gap_m=0.0, + kp=0.0, + kv=0.0, + force_lower=0.0, + force_upper=0.0, + damping=0.0, + frictionloss=0.0, + tool_tip_link="vacuum_tcp", + tcp_offset_mm_deg=(0.0, 0.0, 126.0, 0.0, 0.0, 0.0), +) + +LITE6_VACUUM_GRIPPER_PARAMS = GripperControlParams( + family="lite6_vacuum_gripper", + drive_joint=None, + all_joint_names=(), + finger_link_names=(), + open_pos=0.0, + close_pos=0.0, + closed_gap_m=0.0, + open_gap_m=0.0, + kp=0.0, + kv=0.0, + force_lower=0.0, + force_upper=0.0, + damping=0.0, + frictionloss=0.0, + tool_tip_link="link_tcp", + tcp_offset_mm_deg=(0.0, 0.0, 61.0, 0.0, 0.0, 0.0), ) @@ -336,6 +414,20 @@ def _gripper_params_for(profile: RobotModelSpec, *, gripper: str | None = None) if not profile.supports_robotiq_2f_140: raise ValueError(f"Robot {profile.key} does not support gripper {choice!r}") return ROBOTIQ_2F_140_GRIPPER_PARAMS + if choice == "bare": + return None + if choice in {"bio_gripper_g2", "bio_g2"}: + if not profile.supports_bio_gripper_g2: + raise ValueError(f"Robot {profile.key} does not support gripper {choice!r}") + return BIO_GRIPPER_G2_GRIPPER_PARAMS + if choice == "vacuum_gripper": + if not profile.supports_vacuum_gripper: + raise ValueError(f"Robot {profile.key} does not support gripper {choice!r}") + return VACUUM_GRIPPER_PARAMS + if choice == "lite6_vacuum_gripper": + if not profile.supports_lite6_vacuum_gripper: + raise ValueError(f"Robot {profile.key} does not support gripper {choice!r}") + return LITE6_VACUUM_GRIPPER_PARAMS raise ValueError(f"Unknown gripper {choice!r} for robot {profile.key}") diff --git a/ufactory/safety/__init__.py b/ufactory/safety/__init__.py index b4ee39e..fd05cd0 100644 --- a/ufactory/safety/__init__.py +++ b/ufactory/safety/__init__.py @@ -7,9 +7,12 @@ from ufactory.safety.interfaces import ( ArmState, ArmTransport, + CartesianStepController, + CartesianStepOutcome, Clock, CollisionBackend, CollisionResult, + JacobianKinematicsBackend, KinematicsBackend, MarginCollisionBackend, ) @@ -44,11 +47,14 @@ def __getattr__(name: str) -> Any: "ApprovedProgram", "ArmState", "ArmTransport", + "CartesianStepController", + "CartesianStepOutcome", "Clock", "CollisionBackend", "CollisionExemption", "CollisionResult", "FaultClass", + "JacobianKinematicsBackend", "KinematicsBackend", "MarginCollisionBackend", "PreflightCheck", diff --git a/ufactory/safety/adapters/pinocchio.py b/ufactory/safety/adapters/pinocchio.py index c1a44ac..ae8c806 100644 --- a/ufactory/safety/adapters/pinocchio.py +++ b/ufactory/safety/adapters/pinocchio.py @@ -46,7 +46,14 @@ def __init__( self.urdf_path = Path(urdf_path).expanduser().resolve() if not self.urdf_path.is_file(): raise FileNotFoundError(self.urdf_path) - self.model = pin.buildModelFromUrdf(str(self.urdf_path), mimic=True) + try: + self.model = pin.buildModelFromUrdf(str(self.urdf_path), mimic=True) + self._mimic_fallback = False + except ValueError as exc: + if "mimic" not in str(exc).lower(): + raise + self.model = pin.buildModelFromUrdf(str(self.urdf_path)) + self._mimic_fallback = True self.data = self.model.createData() self.joint_names = joint_names self.ee_link = ee_link @@ -78,6 +85,39 @@ def __init__( index = int(joint.idx_q) self.passive_q_indices[name] = index self.neutral[index] = float(value) + self._mimic_map: tuple[tuple[int, int, float, float], ...] = ( + self._parse_mimic_map() if self._mimic_fallback else () + ) + if self._mimic_fallback: + self._apply_mimic_map(self.neutral) + + def _parse_mimic_map(self) -> tuple[tuple[int, int, float, float], ...]: + root = ET.parse(self.urdf_path).getroot() + mappings: list[tuple[int, int, float, float]] = [] + for joint_elem in root.findall("joint"): + mimic_elem = joint_elem.find("mimic") + if mimic_elem is None: + continue + child_name = joint_elem.get("name") or "" + parent_name = mimic_elem.get("joint") or "" + if not child_name or not parent_name: + continue + child_id = int(self.model.getJointId(child_name)) + parent_id = int(self.model.getJointId(parent_name)) + if child_id == 0 or parent_id == 0: + continue + child_joint = self.model.joints[child_id] + parent_joint = self.model.joints[parent_id] + if child_joint.nq != 1 or parent_joint.nq != 1: + continue + multiplier = float(mimic_elem.get("multiplier", "1")) + offset = float(mimic_elem.get("offset", "0")) + mappings.append((int(child_joint.idx_q), int(parent_joint.idx_q), multiplier, offset)) + return tuple(mappings) + + def _apply_mimic_map(self, q: np.ndarray) -> None: + for child_idx, parent_idx, multiplier, offset in self._mimic_map: + q[child_idx] = multiplier * q[parent_idx] + offset def full_q(self, q_rad: np.ndarray, *, gripper_drive: float | None = None) -> np.ndarray: values = np.asarray(q_rad, dtype=np.float64).reshape(-1) @@ -89,6 +129,8 @@ def full_q(self, q_rad: np.ndarray, *, gripper_drive: float | None = None) -> np if len(self.passive_q_indices) != 1: raise ValueError("gripper_drive requires exactly one configured passive drive joint") q[next(iter(self.passive_q_indices.values()))] = float(gripper_drive) + if self._mimic_fallback: + self._apply_mimic_map(q) return q def xyz(self, q_rad: np.ndarray) -> np.ndarray: diff --git a/ufactory/safety/gate.py b/ufactory/safety/gate.py index 9441cea..413be55 100644 --- a/ufactory/safety/gate.py +++ b/ufactory/safety/gate.py @@ -17,7 +17,12 @@ from ufactory.grippers.robotiq import robotiq_gap_m_to_sim_drive from ufactory.kinematics.orientation import GRIPPER_DOWN_QUAT_XYZW from ufactory.safety.approved import ApprovedProgram, issue_approved_program -from ufactory.safety.interfaces import CollisionBackend, CollisionResult, KinematicsBackend +from ufactory.safety.interfaces import ( + CartesianStepController, + CollisionBackend, + CollisionResult, + KinematicsBackend, +) from ufactory.safety.models import ( PreflightCheck, PreflightReport, @@ -45,6 +50,9 @@ class _Timeline: stages: tuple[str, ...] gripper_drive: FloatArray quaternion_xyzw: FloatArray + approx_steps: int = 0 + max_approx_position_error_m: float = 0.0 + max_approx_orientation_error_rad: float = 0.0 def sha256_file(path: str | Path) -> str: @@ -204,12 +212,44 @@ def _build_timeline(self, program: Program) -> tuple[_Timeline | None, list[Safe _violation(ViolationType.BACKEND_UNAVAILABLE, "preflight", "kinematics backend is required") ) return None, violations + step_controller = self.kinematics if isinstance(self.kinematics, CartesianStepController) else None + if self.config.motion.allow_approx_motion: + if step_controller is None: + violations.append( + _violation( + ViolationType.BACKEND_UNAVAILABLE, + "preflight", + "allow_approx_motion requires a CartesianStepController kinematics backend", + ) + ) + return None, violations + if not step_controller.is_approx_motion: + violations.append( + _violation( + ViolationType.INVALID_INPUT, + "preflight", + "controller allow_approx_motion does not match runtime configuration", + ) + ) + return None, violations + elif step_controller is not None and step_controller.is_approx_motion: + violations.append( + _violation( + ViolationType.INVALID_INPUT, + "preflight", + "controller allow_approx_motion is enabled while runtime configuration disables it", + ) + ) + return None, violations current_q: FloatArray | None = None q_rows: list[FloatArray] = [] xyz_rows: list[FloatArray] = [] stages: list[str] = [] drive_rows: list[float] = [] quaternion_rows: list[FloatArray] = [] + approx_steps = 0 + max_approx_pos_err_m = 0.0 + max_approx_rot_err_rad = 0.0 current_drive = self.config.gripper.open_drive if self.config.gripper is not None else 0.0 sample_index = 0 for segment in program.segments: @@ -260,11 +300,22 @@ def _build_timeline(self, program: Program) -> tuple[_Timeline | None, list[Safe continue shadow: list[FloatArray] = [] seed = current_q.copy() + step_dt = 1.0 / float(program.rate) for offset, row in enumerate(samples): row_index = sample_index + offset try: pose = np.concatenate((row, np.asarray(GRIPPER_DOWN_QUAT_XYZW, dtype=np.float64))) - q = np.asarray(self.kinematics.inverse(pose, seed), dtype=np.float64).reshape(-1) + if step_controller is not None: + step_result = step_controller.solve_step(pose, seed, dt_s=step_dt, include_tcp=False) + q = np.asarray(step_result.q_rad, dtype=np.float64).reshape(-1) + if bool(step_result.used_approx): + approx_steps += 1 + max_approx_pos_err_m = max(max_approx_pos_err_m, float(step_result.position_error_m)) + max_approx_rot_err_rad = max( + max_approx_rot_err_rad, float(step_result.orientation_error_rad) + ) + else: + q = np.asarray(self.kinematics.inverse(pose, seed), dtype=np.float64).reshape(-1) except Exception as exc: violations.append( _violation(ViolationType.INVALID_INPUT, stage, f"IK failed: {exc}", sample_index=row_index) @@ -313,12 +364,20 @@ def _build_timeline(self, program: Program) -> tuple[_Timeline | None, list[Safe gaps = samples.reshape(-1) closed_gap = self.config.gripper.closed_gap_m gap_span = self.config.gripper.open_gap_m - closed_gap - ratios = (gaps - closed_gap) / gap_span - if np.any(ratios < -1e-12) or np.any(ratios > 1.0 + 1e-12): - violations.append( - _violation(ViolationType.INVALID_INPUT, stage, "gripper gap exceeds configured range") - ) - continue + if gap_span == 0.0: + if np.any(np.abs(gaps - closed_gap) > 1e-12): + violations.append( + _violation(ViolationType.INVALID_INPUT, stage, "gripper gap exceeds configured range") + ) + continue + ratios = np.zeros_like(gaps, dtype=np.float64) + else: + ratios = (gaps - closed_gap) / gap_span + if np.any(ratios < -1e-12) or np.any(ratios > 1.0 + 1e-12): + violations.append( + _violation(ViolationType.INVALID_INPUT, stage, "gripper gap exceeds configured range") + ) + continue if self.config.gripper.adapter == "g2": drive_segment = np.asarray([gripper_g2_gap_m_to_sim_drive(gap) for gap in gaps]) elif self.config.gripper.adapter in {"robotiq_2f_85", "robotiq_2f_140"}: @@ -390,6 +449,9 @@ def _build_timeline(self, program: Program) -> tuple[_Timeline | None, list[Safe tuple(stages), np.asarray(drive_rows, dtype=np.float64), np.stack(quaternion_rows), + approx_steps=approx_steps, + max_approx_position_error_m=max_approx_pos_err_m, + max_approx_orientation_error_rad=max_approx_rot_err_rad, ), violations def _allowed_contact(self, result: CollisionResult, stage: str) -> bool: @@ -422,20 +484,23 @@ def _collision_results_for_margin( if self.collision is None: return () + effective_drive = ( + gripper_drive if self.config.gripper is not None and self.config.gripper.has_actuated_joints else None + ) within_margin = getattr(self.collision, "check_all_within_margin", None) if callable(within_margin): return tuple( within_margin( q_rad, stage=stage, - gripper_drive=gripper_drive, + gripper_drive=effective_drive, margin_m=self.config.safety.min_collision_distance_m, ) ) check_all = getattr(self.collision, "check_all", None) if callable(check_all): - return tuple(check_all(q_rad, stage=stage, gripper_drive=gripper_drive)) - return (self.collision.check(q_rad, stage=stage, gripper_drive=gripper_drive),) + return tuple(check_all(q_rad, stage=stage, gripper_drive=effective_drive)) + return (self.collision.check(q_rad, stage=stage, gripper_drive=effective_drive),) def _collision_query_mode(self) -> str: if self.collision is None: @@ -479,12 +544,26 @@ def preflight(self, program: Program, *, executor: str) -> PreflightReport: build_started = time.perf_counter_ns() timeline, build_violations = self._build_timeline(program) violations.extend(build_violations) + warnings: list[str] = [] + timeline_details = { + "allow_approx_motion": bool(self.config.motion.allow_approx_motion), + "approx_steps": 0 if timeline is None else timeline.approx_steps, + "max_approx_position_error_m": 0.0 if timeline is None else timeline.max_approx_position_error_m, + "max_approx_orientation_error_rad": 0.0 if timeline is None else timeline.max_approx_orientation_error_rad, + } + if timeline is not None and timeline.approx_steps > 0: + warnings.append( + f"allow_approx_motion activated on {timeline.approx_steps} sample(s) " + f"(max_pos_err={timeline.max_approx_position_error_m * 1e3:.3f} mm, " + f"max_rot_err={math.degrees(timeline.max_approx_orientation_error_rad):.3f} deg)" + ) checks.append( PreflightCheck( "timeline", timeline is not None and not build_violations, 0 if timeline is None else len(timeline.q_rad), (time.perf_counter_ns() - build_started) / 1e6, + timeline_details, ) ) if timeline is not None: @@ -748,6 +827,7 @@ def preflight(self, program: Program, *, executor: str) -> PreflightReport: scene_sha256=self.scene_sha256, checks=tuple(checks), violations=tuple(violations), + warnings=tuple(warnings), exemption_ids=tuple( f"{item.link_a}/{item.link_b}:{item.stage}:{item.expires_version}" for item in self.config.safety.exemptions diff --git a/ufactory/safety/interfaces.py b/ufactory/safety/interfaces.py index 49a58d5..17761db 100644 --- a/ufactory/safety/interfaces.py +++ b/ufactory/safety/interfaces.py @@ -49,6 +49,48 @@ def inverse(self, pose: FloatArray, seed_q_rad: FloatArray) -> FloatArray: """Solve xyz or xyz+quaternion_xyzw while preserving seed continuity.""" +@runtime_checkable +class JacobianKinematicsBackend(KinematicsBackend, Protocol): + """Kinematics backend exposing base-frame spatial geometric Jacobian.""" + + def jacobian(self, q_rad: FloatArray) -> FloatArray: + """Return 6xN spatial Jacobian ``[v_m; w_rad]`` in base frame.""" + + +@runtime_checkable +class CartesianStepOutcome(Protocol): + """Result of one Cartesian control step returned by a step controller.""" + + @property + def q_rad(self) -> FloatArray: ... + + @property + def used_approx(self) -> bool: ... + + @property + def position_error_m(self) -> float: ... + + @property + def orientation_error_rad(self) -> float: ... + + +@runtime_checkable +class CartesianStepController(KinematicsBackend, Protocol): + """Unified controller capability supporting single-step Cartesian IK and approx motion.""" + + @property + def is_approx_motion(self) -> bool: ... + + def solve_step( + self, + target_pose: FloatArray, + seed_q_rad: FloatArray, + *, + dt_s: float | None = None, + include_tcp: bool = False, + ) -> CartesianStepOutcome: ... + + @runtime_checkable class CollisionBackend(Protocol): def check(self, q_rad: FloatArray, *, stage: str, gripper_drive: float | None = None) -> CollisionResult: ... diff --git a/ufactory/safety/sdk_sim.py b/ufactory/safety/sdk_sim.py index c11eaf8..9354531 100644 --- a/ufactory/safety/sdk_sim.py +++ b/ufactory/safety/sdk_sim.py @@ -19,6 +19,22 @@ SDK_SIMULATION_EVIDENCE_MAX_AGE_S = 300.0 +SDK_SIMULATION_EVIDENCE_SCHEMA_VERSION = 2 +# servo_cartesian commands a full pose (6 DoF). An arm with more joints is +# redundant: its firmware may resolve the extra DoF (xArm7 elbow) differently +# from the host IK while the end effector stays on the commanded pose. +TASK_SPACE_DOF = 6 + + +def _quaternion_angle(a: FloatArray, b: FloatArray) -> float: + """Rotation angle (rad) between two xyzw quaternions, robust for small angles.""" + + qa = np.asarray(a, dtype=np.float64) / np.linalg.norm(a) + qb = np.asarray(b, dtype=np.float64) / np.linalg.norm(b) + if float(qa @ qb) < 0.0: + qb = -qb + # |qa - qb| = 2 sin(phi/2), |qa + qb| = 2 cos(phi/2) with cos(phi) = qa.qb; the rotation angle is 2 phi. + return 4.0 * math.atan2(float(np.linalg.norm(qa - qb)), float(np.linalg.norm(qa + qb))) def stream_sha256(stream: FloatArray) -> str: @@ -44,6 +60,8 @@ class SdkSimulationEvidence: samples: int max_joint_error_rad: float max_ee_error_m: float + max_ee_rotation_error_rad: float + self_motion_allowed: bool min_distance_m: float failures: tuple[str, ...] = () @@ -61,9 +79,20 @@ def validate_sdk_simulation( kinematics: KinematicsBackend, collision: CollisionBackend, allowed_collision: Callable[[CollisionResult, str], bool] | None = None, + joint_lower_rad: FloatArray | None = None, + joint_upper_rad: FloatArray | None = None, created_at_unix_s: float | None = None, ) -> SdkSimulationEvidence: - """Compare host shadow and firmware feedback and recheck every sample.""" + """Compare host shadow and firmware feedback and recheck every sample. + + Both streams must reach the same end-effector pose: position within + ``max_shadow_ee_error_m``, rotation within ``max_shadow_joint_error_rad``. + A non-redundant arm must also match joint by joint. A redundant arm (more + joints than the 6-DoF pose) may differ by self-motion, e.g. the xArm7 + elbow angle, so its joints are not compared; the firmware stream is then + bounded by the joint limits (less ``joint_limit_margin_rad``), which are + required, as well as by the collision checks every sample gets. + """ shadow = np.asarray(shadow_joint_stream_rad, dtype=np.float64) firmware = np.asarray(firmware_joint_stream_rad, dtype=np.float64) @@ -72,17 +101,37 @@ def validate_sdk_simulation( failures.append("shadow, firmware, and stage timelines must have identical dimensions") if not np.all(np.isfinite(shadow)) or not np.all(np.isfinite(firmware)): failures.append("SDK simulation streams contain NaN or infinity") + self_motion_allowed = shadow.ndim == 2 and shadow.shape[1] > TASK_SPACE_DOF max_joint_error = math.inf max_ee_error = math.inf + max_ee_rotation_error = math.inf min_distance = math.inf if not failures: max_joint_error = float(np.max(np.abs(firmware - shadow), initial=0.0)) - if max_joint_error > policy.max_shadow_joint_error_rad: + if not self_motion_allowed and max_joint_error > policy.max_shadow_joint_error_rad: failures.append( f"firmware/shadow joint error {max_joint_error:.6g} rad exceeds " f"{policy.max_shadow_joint_error_rad:.6g} rad" ) + if joint_lower_rad is not None and joint_upper_rad is not None: + lower = np.asarray(joint_lower_rad, dtype=np.float64).reshape(-1) + policy.joint_limit_margin_rad + upper = np.asarray(joint_upper_rad, dtype=np.float64).reshape(-1) - policy.joint_limit_margin_rad + if lower.shape != (shadow.shape[1],) or upper.shape != (shadow.shape[1],): + failures.append("joint limits must have one value per joint") + else: + outside = np.argwhere((firmware < lower) | (firmware > upper)) + if outside.size: + sample, joint = (int(v) for v in outside[0]) + failures.append( + f"firmware stream exceeds joint {joint + 1} limit at sample {sample}: " + f"{firmware[sample, joint]:.6g} rad outside [{lower[joint]:.6g}, {upper[joint]:.6g}] " + f"({len(outside)} sample-joints)" + ) + elif self_motion_allowed: + failures.append("joint limits are required to accept self-motion of a redundant arm") ee_errors: list[float] = [] + rotation_errors: list[float] = [] + orientation_missing = False distances: list[float] = [] for index, (host_q, firmware_q, stage) in enumerate(zip(shadow, firmware, stages, strict=True)): host_pose = np.asarray(kinematics.forward(host_q), dtype=np.float64).reshape(-1) @@ -91,6 +140,10 @@ def validate_sdk_simulation( failures.append(f"FK returned an invalid pose at sample {index}") continue ee_errors.append(float(np.linalg.norm(host_pose[:3] - firmware_pose[:3]))) + if host_pose.size >= 7 and firmware_pose.size >= 7: + rotation_errors.append(_quaternion_angle(host_pose[3:7], firmware_pose[3:7])) + else: + orientation_missing = True check_all = getattr(collision, "check_all", None) results = ( tuple(check_all(firmware_q, stage=stage)) @@ -111,12 +164,22 @@ def validate_sdk_simulation( failures.append( f"firmware/shadow FK error {max_ee_error:.6g} m exceeds {policy.max_shadow_ee_error_m:.6g} m" ) + if orientation_missing: + if self_motion_allowed: + failures.append("FK must return xyz+quaternion to compare a redundant arm by end-effector pose") + else: + max_ee_rotation_error = max(rotation_errors, default=math.inf) + if max_ee_rotation_error > policy.max_shadow_joint_error_rad: + failures.append( + f"firmware/shadow FK rotation error {max_ee_rotation_error:.6g} rad exceeds " + f"{policy.max_shadow_joint_error_rad:.6g} rad" + ) start = shadow[:1] if shadow.ndim == 2 and len(shadow) else np.empty((0, 0)) created_at = time.time() if created_at_unix_s is None else float(created_at_unix_s) if not math.isfinite(created_at) or created_at <= 0.0: failures.append("SDK simulation evidence creation time is invalid") return SdkSimulationEvidence( - schema_version=1, + schema_version=SDK_SIMULATION_EVIDENCE_SCHEMA_VERSION, passed=not failures, robot_key=robot_key, serial_number=serial_number.strip(), @@ -129,6 +192,8 @@ def validate_sdk_simulation( samples=len(shadow) if shadow.ndim == 2 else 0, max_joint_error_rad=max_joint_error, max_ee_error_m=max_ee_error, + max_ee_rotation_error_rad=max_ee_rotation_error, + self_motion_allowed=self_motion_allowed, min_distance_m=min_distance, failures=tuple(failures), ) @@ -145,6 +210,6 @@ def load_sdk_simulation_evidence(path: str | Path) -> SdkSimulationEvidence: raise ValueError(f"SDK evidence fields must be exactly {sorted(expected)}") data["failures"] = tuple(data["failures"]) evidence = SdkSimulationEvidence(**data) - if evidence.schema_version != 1: + if evidence.schema_version != SDK_SIMULATION_EVIDENCE_SCHEMA_VERSION: raise ValueError("unsupported SDK simulation evidence schema") return evidence diff --git a/ufactory/simulation/bio_g2_microplate.py b/ufactory/simulation/bio_g2_microplate.py index e00929a..15007a8 100644 --- a/ufactory/simulation/bio_g2_microplate.py +++ b/ufactory/simulation/bio_g2_microplate.py @@ -11,7 +11,7 @@ from ufactory.robots.registry import PROJECT_ROOT from ufactory.simulation.bio_g2_model import sha256 -ASSET_DIR = PROJECT_ROOT / "assets" / "urdf" / "microplate" +ASSET_DIR = PROJECT_ROOT / "assets" / "urdf" / "objects" / "microplate" PLATE_JSON_PATH = ASSET_DIR / "SBS_96_well_plate.json" PLATE_URDF = ASSET_DIR / "sbs_96_well.urdf" PLATE_MASS_KG = 0.100 diff --git a/ufactory/simulation/bio_g2_model.py b/ufactory/simulation/bio_g2_model.py index 0407b83..c6d5183 100644 --- a/ufactory/simulation/bio_g2_model.py +++ b/ufactory/simulation/bio_g2_model.py @@ -174,6 +174,7 @@ def load(cls, urdf_path: str | Path | None = None) -> BioGripperG2Model: Path(__file__).resolve().parents[2] / "assets" / "urdf" + / "end_effectors" / "bio_gripper_g2" / "bio_gripper_g2_movable_visual.urdf" ) diff --git a/ufactory/training/pick_place_config.py b/ufactory/training/pick_place_config.py index 9ce706a..7f9ac9c 100644 --- a/ufactory/training/pick_place_config.py +++ b/ufactory/training/pick_place_config.py @@ -14,6 +14,8 @@ CUBE_SIZE = 0.030 CUBE_REST_Z = CUBE_SIZE / 2 SAFE_LIFT_Z = 0.080 +PRE_LIFT_PAD_FLOOR_Z = 0.02908 +TOUCHDOWN_REF_MARGIN_Z = 0.0022 HOME_EE_POS = (0.30, 0.0, 0.30) TABLE_SIZE = (0.60, 0.90, 0.04) TABLE_POS = (0.35, 0.15, -0.02) diff --git a/ufactory/trajectory/g2_replay.py b/ufactory/trajectory/g2_replay.py index 2149486..240bdab 100644 --- a/ufactory/trajectory/g2_replay.py +++ b/ufactory/trajectory/g2_replay.py @@ -198,7 +198,13 @@ def _replay_calibrated( ): from ufactory.trajectory.g2_confirmation import summarize from ufactory.trajectory.mirror_executor import resolve_tick_arm_q - from ufactory.trajectory.sim_executor import PhaseStatus, SimReport, _assert_finite_replay_state + from ufactory.trajectory.sim_executor import ( + PhaseStatus, + SimReport, + _assert_finite_replay_state, + _resolve_sim_rate_hz, + physics_steps_for_tick, + ) if not math.isfinite(final_metric_settle_s) or final_metric_settle_s < 0: raise ValueError("final_metric_settle_s must be finite and non-negative") @@ -206,19 +212,26 @@ def _replay_calibrated( adapter.command(open_mm, settings.speed_percent, settings.force_percent) report = SimReport(physics_profile=physics_profile, physics_parameters=physics_summary) report.physics_parameters["command"] = asdict(settings) - report.physics_parameters["rate_hz"] = program.rate report.physics_parameters.update(getattr(ctx, "simulation_parameters", {})) rate, dt = float(program.rate), 1 / float(program.rate) + sim_rate_hz = _resolve_sim_rate_hz(ctx, rate) + sim_dt = 1.0 / sim_rate_hz + report.physics_parameters["rate_hz"] = program.rate + report.physics_parameters["sim_rate_hz"] = sim_rate_hz + sim_time_acc = 0.0 q_arm = ctx.home_qpos[ctx.arm_dof_idx].astype(np.float64).copy() previous_gap = adapter.gap_mm() pending_confirmation = None def tick(segment, tick_index): - nonlocal previous_gap, pending_confirmation + nonlocal previous_gap, pending_confirmation, sim_time_acc actual_q = ctx.robot.get_dofs_position(ctx.arm_dof_idx) ctx.robot.control_dofs_position(actual_q.new_tensor(q_arm).reshape(actual_q.shape), ctx.arm_dof_idx) - output = adapter.apply(dt) - ctx.scene.step() + n_phys, sim_time_acc = physics_steps_for_tick(sim_rate_hz, rate, sim_time_acc) + output = None + for _ in range(max(1, n_phys)): + output = adapter.apply(sim_dt) + ctx.scene.step() _assert_finite_replay_state(ctx, phase=segment.label, tick=tick_index) row = _record( ctx, @@ -267,7 +280,7 @@ def tick(segment, tick_index): if segment.kind != "gripper": started = time.perf_counter_ns() try: - q_arm = resolve_tick_arm_q(ctx, segment, samples, t, init_qpos=q_arm) + q_arm = resolve_tick_arm_q(ctx, segment, samples, t, init_qpos=q_arm, dt_s=dt) except Exception: status.ik_failures += 1 raise diff --git a/ufactory/trajectory/ik.py b/ufactory/trajectory/ik.py index 293f5bd..3b4eca7 100644 --- a/ufactory/trajectory/ik.py +++ b/ufactory/trajectory/ik.py @@ -1,8 +1,9 @@ """Host-side IK compilation for trajectory programs. -The pick-place real ``servo_j`` path keeps the Cartesian waypoint program as -the source of truth, then compiles each MoveL tick into an explicit joint -target using the same Genesis link6 IK already used by sim and mirror replay. +The pick-place / packaging ``servo_j`` path keeps the Cartesian waypoint program +as the source of truth, then compiles each MoveL tick into an explicit joint +target using the unified pure-NumPy :class:`~ufactory.control.ArmMotionController` +(falling back to Genesis link6 IK only when no ``arm_controller`` is provided). After per-tick IK, the joint stream is plateau-collapsed and LSPB-retimed along the joint polyline so finite-difference ``servo_j`` acceleration stays within @@ -12,9 +13,13 @@ from __future__ import annotations +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + import numpy as np -from ufactory.kinematics.genesis import solve_link6_ik +from ufactory.kinematics.orientation import GRIPPER_DOWN_QUAT_XYZW from ufactory.trajectory.profile import ( _EPS, _lspb_alpha_for_duration, @@ -31,6 +36,66 @@ _UF850_IK_DAMPING = 0.05 _MAX_RETIME_SAMPLES = 1_000_000 +HOME_IK_POS_TOL_M = 1e-6 +HOME_IK_ROT_TOL_RAD = 1e-5 +HOME_IK_MAX_POS_ERR_M = 1e-5 +HOME_IK_MAX_ROT_ERR_RAD = 5e-3 + + +@dataclass(frozen=True) +class ArmIKContext: + """Genesis-free context for compiling MoveL streams with ``ArmMotionController``.""" + + arm_controller: Any + robot_key: str + robot_urdf_path: str = "" + kinematics_yaml_path: str | None = None + kinematics_suffix: str | None = None + include_tcp: bool = False + + +def solve_arm_home_q( + arm_controller: Any, + target_pos_base: Sequence[float] | np.ndarray, + *, + default_qpos_rad: Sequence[float] | np.ndarray | None = None, + include_tcp: bool = False, + pos_tol_m: float = HOME_IK_POS_TOL_M, + rot_tol_rad: float = HOME_IK_ROT_TOL_RAD, + max_pos_err_m: float = HOME_IK_MAX_POS_ERR_M, + max_rot_err_rad: float = HOME_IK_MAX_ROT_ERR_RAD, +) -> np.ndarray: + """Solve a gripper-down home pose to micrometres using pure-NumPy ``ArmMotionController``.""" + from ufactory.control.kinematics_chain import pose_to_se3 + from ufactory.control.solvers import solve_exact_ik + + base_xyz = np.asarray(target_pos_base, dtype=np.float64).reshape(3) + target_se3 = pose_to_se3( + np.concatenate((base_xyz, np.asarray(GRIPPER_DOWN_QUAT_XYZW, dtype=np.float64))), + position_in_mm=False, + ) + seed_q = None if default_qpos_rad is None else np.asarray(default_qpos_rad, dtype=np.float64).reshape(-1) + effective_rot_tol = max_rot_err_rad if getattr(arm_controller, "dof", 6) == 5 else rot_tol_rad + res = solve_exact_ik( + arm_controller.chain, + target_se3, + seed_q_rad=seed_q, + include_tcp=bool(include_tcp), + pos_tol_m=float(pos_tol_m), + rot_tol_rad=float(effective_rot_tol), + cold_start_fallback=True, + ) + if not (np.isfinite(res.position_error_m) and np.isfinite(res.orientation_error_rad)) or ( + res.position_error_m > max_pos_err_m or res.orientation_error_rad > max_rot_err_rad + ): + raise ValueError( + f"ArmMotionController home IK residual {res.position_error_m * 1e3:.4f} mm / " + f"{res.orientation_error_rad * 1e3:.4f} mrad exceeds " + f"{max_pos_err_m * 1e3:.3f} mm / {max_rot_err_rad * 1e3:.3f} mrad " + f"for target {base_xyz.round(6).tolist()}" + ) + return np.asarray(res.q_rad, dtype=np.float64).reshape(-1).copy() + def compile_cartesian_program_to_joint_stream(program: Program, ctx) -> Program: """Return a Program whose MoveL segments are explicit MoveJ target streams. @@ -241,6 +306,30 @@ def _solve_base_xyz( init_qpos: np.ndarray | None, damping: float | None = None, ) -> np.ndarray: + controller = getattr(ctx, "arm_controller", None) + if controller is not None: + include_tcp = bool(getattr(ctx, "include_tcp", False)) + xyz = np.asarray(xyz_base, dtype=np.float64).reshape(3) + pose = np.concatenate((xyz, np.asarray(GRIPPER_DOWN_QUAT_XYZW, dtype=np.float64))) + if init_qpos is None: + from ufactory.control.kinematics_chain import pose_to_se3 + from ufactory.control.solvers import solve_exact_ik + + res = solve_exact_ik( + controller.chain, + pose_to_se3(pose, position_in_mm=False), + include_tcp=include_tcp, + cold_start_fallback=True, + ) + return np.asarray(res.q_rad, dtype=np.float64).reshape(-1) + res = controller.solve_step( + pose, + np.asarray(init_qpos, dtype=np.float64).reshape(-1), + include_tcp=include_tcp, + ) + return np.asarray(res.q_rad, dtype=np.float64).reshape(-1) + from ufactory.kinematics.genesis import solve_link6_ik + return solve_link6_ik( ctx.robot, ctx.ik_link, diff --git a/ufactory/trajectory/mirror_executor.py b/ufactory/trajectory/mirror_executor.py index 435d83c..e8ee449 100644 --- a/ufactory/trajectory/mirror_executor.py +++ b/ufactory/trajectory/mirror_executor.py @@ -7,6 +7,7 @@ from __future__ import annotations +from collections.abc import Sequence import threading import time @@ -14,6 +15,7 @@ import torch from ufactory.kinematics.genesis import solve_link6_ik +from ufactory.kinematics.orientation import GRIPPER_DOWN_QUAT_XYZW from ufactory.trajectory.ik import _ik_damping_for_context from ufactory.trajectory.scene import TrajSceneContext, drive_for_gap_m from ufactory.trajectory.segments import Program, Segment @@ -22,11 +24,20 @@ def gap_m_from_drive(drive: float, gripper) -> float: """Map a gripper drive-DOF value back to a physical two-finger gap (m).""" + if gripper is None or not getattr(gripper, "all_joint_names", ()): + return 0.0 if gripper.family == "g2": from ufactory.grippers.g2 import gripper_g2_sim_drive_to_gap_m return gripper_g2_sim_drive_to_gap_m(drive) - open_fraction = (float(drive) - gripper.close_pos) / (gripper.open_pos - gripper.close_pos) + if gripper.family == "bio_gripper_g2": + from ufactory.grippers.bio_g2 import bio_gripper_g2_sim_drive_to_gap_m + + return bio_gripper_g2_sim_drive_to_gap_m(drive) + span = float(gripper.open_pos) - float(gripper.close_pos) + if abs(span) < 1e-12: + return float(getattr(gripper, "closed_gap_m", 0.0)) + open_fraction = (float(drive) - gripper.close_pos) / span open_fraction = max(0.0, min(1.0, open_fraction)) closed_gap = float(getattr(gripper, "closed_gap_m", 0.0)) return closed_gap + open_fraction * (float(gripper.open_gap_m) - closed_gap) @@ -43,6 +54,35 @@ def _default_ik_seed(ctx: TrajSceneContext) -> np.ndarray | None: return None +def _solve_controller_base_xyz( + controller, + xyz_base, + *, + seed: np.ndarray | None, + dt_s: float | None = None, +) -> np.ndarray: + xyz = np.asarray(xyz_base, dtype=np.float64).reshape(3) + pose = np.concatenate((xyz, np.asarray(GRIPPER_DOWN_QUAT_XYZW, dtype=np.float64))) + if seed is None: + from ufactory.control.kinematics_chain import pose_to_se3 + from ufactory.control.solvers import solve_exact_ik + + res = solve_exact_ik( + controller.chain, + pose_to_se3(pose, position_in_mm=False), + include_tcp=False, + cold_start_fallback=True, + ) + return np.asarray(res.q_rad, dtype=np.float64).reshape(-1) + res = controller.solve_step( + pose, + np.asarray(seed, dtype=np.float64).reshape(-1), + dt_s=dt_s, + include_tcp=False, + ) + return np.asarray(res.q_rad, dtype=np.float64).reshape(-1) + + def resolve_segment_start_arm_q( ctx: TrajSceneContext, seg: Segment, @@ -61,6 +101,11 @@ def resolve_segment_start_arm_q( if seg.pose_start is None: raise ValueError(f"MoveL segment {seg.label!r} has no pose_start") seed = _default_ik_seed(ctx) if init_qpos is None else init_qpos + controller = getattr(ctx, "arm_controller", None) + if controller is not None: + q = _solve_controller_base_xyz(controller, seg.pose_start, seed=seed) + ctx._last_ik_qpos = q.copy() + return q ik_damping = _ik_damping_for_context(ctx) if damping is None else float(damping) pose_world = ctx.base_to_world(seg.pose_start) q = solve_link6_ik( @@ -85,6 +130,7 @@ def resolve_tick_arm_q( *, init_qpos: np.ndarray | None = None, damping: float | None = None, + dt_s: float | None = None, ) -> np.ndarray: """Resolve arm joint targets for one tick (same logic as sim replay).""" if seg.kind == "movej": @@ -93,6 +139,13 @@ def resolve_tick_arm_q( return q if seg.kind == "movel": seed = _default_ik_seed(ctx) if init_qpos is None else init_qpos + controller = getattr(ctx, "arm_controller", None) + if controller is not None: + if seed is None and tick_idx == 0 and seg.pose_start is not None: + seed = _solve_controller_base_xyz(controller, seg.pose_start, seed=None, dt_s=dt_s) + q = _solve_controller_base_xyz(controller, samples[tick_idx], seed=seed, dt_s=dt_s) + ctx._last_ik_qpos = q.copy() + return q ik_damping = _ik_damping_for_context(ctx) if damping is None else float(damping) if tick_idx == 0 and seg.pose_start is not None: seed = solve_link6_ik( @@ -140,7 +193,9 @@ def mirror_grip_drive_for_gap_m(ctx: TrajSceneContext, gap_m: float) -> float: """ gap = float(gap_m) gripper = ctx.gripper - family = getattr(gripper, "family", None) if gripper is not None else None + if gripper is None or not getattr(gripper, "all_joint_names", ()): + return 0.0 + family = getattr(gripper, "family", None) obj_w = float(min(ctx.obj_size[0], ctx.obj_size[1])) shrink = None if family == "lite6": @@ -168,45 +223,75 @@ def _set_kinematic_pose( arm_idx: list[int], grip_drive: float, all_grip_idx: list[int], + grip_multipliers: Sequence[float] | None = None, ) -> None: robot.set_dofs_position(q_arm, arm_idx, zero_velocity=True) if all_grip_idx: - grip_target = np.full(len(all_grip_idx), float(grip_drive)) + if grip_multipliers is not None and len(grip_multipliers) > 0 and len(grip_multipliers) == len(all_grip_idx): + grip_target = float(grip_drive) * np.asarray(grip_multipliers, dtype=np.float64) + else: + grip_target = np.full(len(all_grip_idx), float(grip_drive)) robot.set_dofs_position(grip_target, all_grip_idx, zero_velocity=True) def _update_mirror_entities(context, entities: tuple[object, ...]) -> None: """Upload only moving rigid entities to the rasterizer node buffers.""" - visualizer = context.visualizer - visualizer.update_visual_states(force_render=True) + visualizer = getattr(context, "visualizer", None) + update_visual_states = getattr(visualizer, "update_visual_states", None) + rigid_nodes = getattr(context, "rigid_nodes", None) + if not callable(update_visual_states) or rigid_nodes is None: + # Genesis 1.5+ replaced rigid_nodes with changelog-tracked _sync_shapes(). + context.update(force_render=True) + return + + update_visual_states(force_render=True) context._scene._bounds = None + rigid_geoms_t = getattr(context, "rigid_geoms_T", None) + geoms_t_cache: dict[tuple[int, bool], np.ndarray] = {} + for entity in entities: if getattr(entity._morph, "enable_custom_vverts", False): # Custom per-vertex geometry needs Genesis' complete update path. context.update(force_render=True) return solver = entity._solver - if entity.surface.vis_mode == "visual": - geoms = entity.vgeoms - geoms_t = solver._vgeoms_render_T + is_visual = entity.surface.vis_mode == "visual" + geoms = entity.vgeoms if is_visual else entity.geoms + + if callable(rigid_geoms_t): + # Genesis 1.4.7+: shape (n_rendered_envs, n_geoms, 4, 4), already indexed + # by context.rendered_envs_idx. + cache_key = (id(solver), is_visual) + geoms_t = geoms_t_cache.get(cache_key) + if geoms_t is None: + geoms_t = rigid_geoms_t(solver, is_visual) + geoms_t_cache[cache_key] = geoms_t + rendered_layout = True else: - geoms = entity.geoms - geoms_t = solver._geoms_render_T + render_attr = "_vgeoms_render_T" if is_visual else "_geoms_render_T" + geoms_t = getattr(solver, render_attr, None) + if geoms_t is None: + context.update(force_render=True) + return + rendered_layout = False + for geom in geoms: - if geom.uid not in context.rigid_nodes: + if geom.uid not in rigid_nodes: continue geom_envs_idx = context._get_geom_active_envs_idx(geom, context.rendered_envs_idx) if len(geom_envs_idx) == 0: continue - if len(geom_envs_idx) < len(context.rendered_envs_idx): + if rendered_layout: + geom_t = geoms_t[:, geom.idx] + elif len(geom_envs_idx) < len(context.rendered_envs_idx): geom_t = geoms_t[geom.idx][context.rendered_envs_idx] else: geom_t = geoms_t[geom.idx][geom_envs_idx] - node = context.rigid_nodes[geom.uid] + node = rigid_nodes[geom.uid] node.mesh._bounds = None node.mesh.primitives[0].poses = geom_t - context.jit.update_buffer(node, "model", geom_t.transpose((0, 2, 1))) + context.jit.update_buffer(node, "model", np.ascontiguousarray(geom_t.transpose((0, 2, 1)))) def update_scene_visualizer(scene, *, entities: tuple[object, ...] | None = None) -> bool: @@ -288,7 +373,14 @@ def kinematic_step( arm_idx = ctx.arm_dof_idx all_grip_idx = ctx.all_gripper_dof_idx - _set_kinematic_pose(robot, q_arm, arm_idx, grip_drive, all_grip_idx) + _set_kinematic_pose( + robot, + q_arm, + arm_idx, + grip_drive, + all_grip_idx, + grip_multipliers=getattr(ctx, "gripper_dof_multipliers", None) or None, + ) if update_visualizer: update_scene_visualizer(scene, entities=(ctx.robot, ctx.obj)) @@ -306,7 +398,8 @@ def __init__(self, ctx: TrajSceneContext, program: Program) -> None: else: self._last_q_arm = np.zeros(len(arm_idx), dtype=np.float64) ctx._last_ik_qpos = self._last_q_arm.copy() - self._grip_drive = drive_for_gap_m(ctx.gripper.open_gap_m, ctx.gripper) + self._has_gripper_dofs = bool(ctx.gripper is not None and ctx.all_gripper_dof_idx) + self._grip_drive = drive_for_gap_m(ctx.gripper.open_gap_m, ctx.gripper) if self._has_gripper_dofs else 0.0 _disable_pd(ctx.robot, arm_idx) _disable_pd(ctx.robot, ctx.all_gripper_dof_idx) @@ -319,6 +412,8 @@ def grip_drive(self) -> float: return self._grip_drive def _visual_grip_drive(self) -> float: + if not self._has_gripper_dofs: + return 0.0 return mirror_grip_drive_for_gap_m(self.ctx, gap_m_from_drive(self._grip_drive, self.ctx.gripper)) def prime_to_home(self) -> None: @@ -326,7 +421,9 @@ def prime_to_home(self) -> None: if len(self.ctx.home_qpos): self._last_q_arm = self.ctx.home_qpos[arm_idx].astype(np.float64).copy() self.ctx._last_ik_qpos = self._last_q_arm.copy() - self._grip_drive = drive_for_gap_m(self.ctx.gripper.open_gap_m, self.ctx.gripper) + self._grip_drive = ( + drive_for_gap_m(self.ctx.gripper.open_gap_m, self.ctx.gripper) if self._has_gripper_dofs else 0.0 + ) kinematic_step(self.ctx, self._last_q_arm, self._visual_grip_drive()) def prime_to_segment_start(self, seg: Segment) -> None: @@ -346,10 +443,13 @@ def tick(self, seg: Segment, tick_idx: int, *, update_visualizer: bool = True) - if tick_idx < 0 or tick_idx >= n: raise IndexError(f"tick {tick_idx} out of range for segment {seg.label!r} (N={n})") if seg.kind == "gripper": - gap_m = float(samples[tick_idx, 0]) - # Keep the planned drive for attach/release gap logic; clamp only the - # teleported visual pose so Lite6 pads do not penetrate the cube. - self._grip_drive = drive_for_gap_m(gap_m, self.ctx.gripper) + if self._has_gripper_dofs: + gap_m = float(samples[tick_idx, 0]) + # Keep the planned drive for attach/release gap logic; clamp only the + # teleported visual pose so Lite6 pads do not penetrate the cube. + self._grip_drive = drive_for_gap_m(gap_m, self.ctx.gripper) + else: + self._grip_drive = 0.0 kinematic_step( self.ctx, self._last_q_arm, @@ -363,6 +463,7 @@ def tick(self, seg: Segment, tick_idx: int, *, update_visualizer: bool = True) - samples, tick_idx, init_qpos=self._last_q_arm, + dt_s=1.0 / self.rate, ) kinematic_step( self.ctx, @@ -491,10 +592,29 @@ def warm_up(self, *, iterations: int = 2) -> None: self.ctx.obj.set_quat(obj_quat, zero_velocity=True) update_scene_visualizer(self.ctx.scene, entities=(self.ctx.robot, self.ctx.obj)) + def _tool_center(self) -> torch.Tensor: + lf = getattr(self.ctx, "left_finger", None) + rf = getattr(self.ctx, "right_finger", None) + if lf is not None and rf is not None: + return (lf.get_pos()[0] + rf.get_pos()[0]) / 2 + tip_link = getattr(self.ctx, "tool_tip_link", None) + if tip_link is not None: + return tip_link.get_pos()[0] + flange_pos = self.ctx.ik_link.get_pos()[0] + offset_m = getattr(self.ctx, "tcp_offset_flange_m", (0.0, 0.0, 0.0)) + if not any(abs(float(v)) > 1e-12 for v in offset_m): + return flange_pos + vec = flange_pos.new_tensor(tuple(float(v) for v in offset_m)) + quat_getter = getattr(self.ctx.ik_link, "get_quat", None) + if callable(quat_getter): + q = quat_getter()[0] # Genesis WXYZ + qw, qv = q[0], q[1:4] + t = 2.0 * torch.linalg.cross(qv, vec) + return flange_pos + vec + qw * t + torch.linalg.cross(qv, t) + return flange_pos + flange_pos.new_tensor((float(offset_m[0]), -float(offset_m[1]), -float(offset_m[2]))) + def _finger_center(self) -> torch.Tensor: - lf = self.ctx.left_finger.get_pos()[0] - rf = self.ctx.right_finger.get_pos()[0] - return (lf + rf) / 2 + return self._tool_center() def _capture_spawn_freeze_pose(self) -> None: self._spawn_freeze_pos = self.ctx.obj.get_pos()[0].clone() diff --git a/ufactory/trajectory/scene.py b/ufactory/trajectory/scene.py index 4d99cb5..75e1c61 100644 --- a/ufactory/trajectory/scene.py +++ b/ufactory/trajectory/scene.py @@ -3,7 +3,7 @@ Robot-generic Genesis scene builder for the pick-place trajectory pipeline (originally written for xArm6 scripted pick-place demos). Returns a typed context (entities, dof indices, PD gains, finger offsets, key heights) reused -across xArm5/6/7, UF850 (Gripper G2) and Lite6 (parallel gripper). Single +across xArm5/6/7, UF850 (Gripper G2 / Bio Gripper G2) and Lite6 (parallel gripper). Single environment, robot base at table height. """ @@ -72,8 +72,8 @@ class TrajSceneContext: obj: object target_marker: object ik_link: object - left_finger: object - right_finger: object + left_finger: object | None + right_finger: object | None arm_dof_idx: list[int] gripper_dof_idx: list[int] all_gripper_dof_idx: list[int] @@ -116,6 +116,11 @@ class TrajSceneContext: robotiq_settings: object | None = None robotiq_controller: object | None = None simulation_parameters: dict = field(default_factory=dict) + sim_rate_hz: float = 50.0 + arm_controller: object | None = None + gripper_dof_multipliers: tuple[float, ...] = () + tool_tip_link: object | None = None + tcp_offset_flange_m: tuple[float, float, float] = (0.0, 0.0, 0.0) def base_to_world(self, pos_base) -> list[float]: """Convert a base-frame xyz (m) to the Genesis world frame (m).""" @@ -159,28 +164,75 @@ def _robot_urdf_for_visual_model(runtime: RobotRuntimeProfile, visual_model: str return compose_robot_urdf(profile.key, "gripper_g2", visual="stl"), False if model != "glb": raise ValueError("visual_model must be 'glb' or 'stl'") - if gripper is not None and gripper.family == "lite6": + if gripper is None: + from ufactory.robots.paths import robot_visual_glb_urdf + + return robot_visual_glb_urdf(profile.key), True + if gripper.family == "lite6": return compose_robot_urdf(profile.key, "lite6_gripper"), True - if gripper is not None and gripper.family == "g2": + if gripper.family == "g2": return compose_robot_urdf(profile.key, "gripper_g2"), True - if gripper is not None and gripper.family in {"robotiq_2f_85", "robotiq_2f_140"}: + if gripper.family == "bio_gripper_g2": + return compose_robot_urdf(profile.key, "bio_gripper_g2"), True + if gripper.family in {"robotiq_2f_85", "robotiq_2f_140", "vacuum_gripper", "lite6_vacuum_gripper"}: return compose_robot_urdf(profile.key, gripper.family), True raise ValueError(f"{profile.key} has no supported gripper for the trajectory scene") +def gripper_dof_multipliers(gripper: GripperControlParams | None) -> tuple[float, ...]: + """Return per-DOF sign multipliers aligned with ``gripper.all_joint_names``. + + In ``bio_gripper_g2``, ``bio_gripper_g2_left_finger_joint`` mimics the right + finger with ``multiplier="-1"`` and joint limits ``[-0.0395, 0]``. + """ + if gripper is None or not gripper.all_joint_names: + return () + if gripper.family == "bio_gripper_g2": + from ufactory.grippers.bio_g2 import LEFT_JOINT + + return tuple(-1.0 if name == LEFT_JOINT else 1.0 for name in gripper.all_joint_names) + return tuple(1.0 for _ in gripper.all_joint_names) + + def _robot_defaults(robot_key: str, *, gripper: str | None = None) -> dict: """Per-robot default scene geometry (object/place xy, key heights).""" + from ufactory.manipulation.tcp import resolve_tool_tcp_spec + runtime = get_robot_runtime_profile(robot_key, gripper=gripper) - config = load_runtime_config(runtime.model.key, gripper=gripper) + is_zero_dof_choice = gripper in {"bare", "vacuum_gripper", "lite6_vacuum_gripper"} + config = load_runtime_config(runtime.model.key, gripper=None if is_zero_dof_choice else gripper) params = config.task.parameters object_spec = resolve_pick_place_object_spec(config) - gripper_profile = config.gripper - if gripper_profile is None: - raise ValueError(f"{runtime.model.key} has no configured gripper geometry") obj_pos_base = tuple(float(value) for value in params["fixed_object_position_m"]) place_pos_base = tuple(float(value) for value in params["fixed_target_position_m"]) default_ee = tuple(float(value) for value in params["default_ee_position_m"]) is_lite6 = runtime.model.key == "lite6" + if is_zero_dof_choice: + tool_tcp = resolve_tool_tcp_spec(runtime.gripper) + return { + "base_pos": DEFAULT_ROBOT_BASE_POS, + "obj_xy": obj_pos_base[:2], + "place_xy": place_pos_base[:2], + "obj_pos_base": obj_pos_base, + "place_pos_base": place_pos_base, + "obj_size": object_spec.size_m, + "obj_mass_kg": object_spec.mass_kg, + "lift_z": default_ee[2], + "home_z": default_ee[2], + "grasp_gap_m": 0.0, + "tool_tip_offset_z_m": tool_tcp.tcp_offset_flange_m[2], + "finger_pad_below_center_m": 0.0, + "finger_close_descent_m": 0.0, + "grasp_table_clearance_m": 0.010, + "grasp_height_extra_m": 0.0, + "excluded_geometry_pairs": (), + "default_qpos_rad": config.arm.default_qpos_rad, + "tcp_offset_flange_m": tool_tcp.tcp_offset_flange_m, + } + gripper_profile = config.gripper + if gripper_profile is None: + raise ValueError(f"{runtime.model.key} has no configured gripper geometry") + tool_tcp = resolve_tool_tcp_spec(config) return { "base_pos": DEFAULT_ROBOT_BASE_POS, "obj_xy": obj_pos_base[:2], @@ -198,6 +250,8 @@ def _robot_defaults(robot_key: str, *, gripper: str | None = None) -> dict: "grasp_table_clearance_m": gripper_profile.grasp_table_clearance_m, "grasp_height_extra_m": gripper_profile.grasp_height_extra_m, "excluded_geometry_pairs": gripper_profile.excluded_geometry_pairs, + "default_qpos_rad": config.arm.default_qpos_rad, + "tcp_offset_flange_m": tool_tcp.tcp_offset_flange_m, } @@ -219,14 +273,14 @@ class DryHeights: grasp_link6_z: float pre_grasp_link6_z: float lift_link6_z: float - gripper: GripperControlParams + gripper: GripperControlParams | None def dry_heights(robot_key: str, *, gripper: str | None = None) -> DryHeights: """Build a :class:`DryHeights` for ``robot_key`` without a Genesis scene.""" runtime = get_robot_runtime_profile(robot_key, gripper=gripper) resolved_gripper = runtime.gripper - if resolved_gripper is None: + if resolved_gripper is None and gripper != "bare": raise ValueError(f"{runtime.model.key} has no supported gripper for the trajectory scene") defaults = _robot_defaults(runtime.model.key, gripper=gripper) obj_xy = defaults["obj_xy"] @@ -280,6 +334,8 @@ def build_scene( robotiq_settings: object | None = None, gripper: str | None = None, excluded_geometry_pairs: tuple[tuple[str, str], ...] | None = None, + arm_controller: object | None = None, + home_xy_base: tuple[float, float] | None = None, ) -> TrajSceneContext: """Build the single-env Genesis scene and configure PD gains + finger offsets. @@ -291,17 +347,18 @@ def build_scene( runtime = get_robot_runtime_profile(robot_key, gripper=gripper) profile = runtime.model resolved_gripper = runtime.gripper - if resolved_gripper is None: + if resolved_gripper is None and gripper != "bare": raise ValueError(f"{profile.key} has no supported gripper for the trajectory scene") defaults = _robot_defaults(profile.key, gripper=gripper) gripper_spec = resolved_gripper - # Keep local name ``gripper`` bound to GripperControlParams cleanly below. + gripper_family = gripper_spec.family if gripper_spec is not None else None + # Keep local name ``gripper`` bound cleanly below. dt = 1.0 / float(rate) - if gripper_spec.family == "g2": + if gripper_family == "g2": validate_g2_contact_substeps(dt=dt, substeps=substeps) - elif gripper_spec.family in {"robotiq_2f_85", "robotiq_2f_140"}: - validate_robotiq_contact_substeps(dt=dt, substeps=substeps, variant=gripper_spec.family) + elif gripper_family in {"robotiq_2f_85", "robotiq_2f_140"}: + validate_robotiq_contact_substeps(dt=dt, substeps=substeps, variant=gripper_family) substeps = int(substeps) robot_base = tuple(float(v) for v in (base_pos if base_pos is not None else defaults["base_pos"])) @@ -332,6 +389,12 @@ def build_scene( raise ValueError("obj_mass_kg must be finite and positive") obj_xy = obj_pos_base[:2] place_xy = place_pos_base[:2] + if home_xy_base is not None: + if len(home_xy_base) != 2 or not all(math.isfinite(float(value)) for value in home_xy_base): + raise ValueError("home_xy_base must contain two finite values") + resolved_home_xy = (float(home_xy_base[0]), float(home_xy_base[1])) + else: + resolved_home_xy = obj_xy lift_z = float(lift_z) if lift_z is not None else defaults["lift_z"] home_z = float(home_z) if home_z is not None else defaults["home_z"] @@ -348,10 +411,12 @@ def build_scene( robot_name=profile.robot_name, joint_count=profile.dof, ) - is_robotiq = gripper_spec.family in {"robotiq_2f_85", "robotiq_2f_140"} - is_calibrated_g2 = calibrated_g2 and gripper_spec.family == "g2" + is_robotiq = gripper_family in {"robotiq_2f_85", "robotiq_2f_140"} + is_calibrated_g2 = calibrated_g2 and gripper_family == "g2" is_calibrated_robotiq = calibrated_g2 and is_robotiq is_calibrated_adaptive = is_calibrated_g2 or is_calibrated_robotiq + has_finger_links = bool(gripper_spec is not None and gripper_spec.has_finger_links) + has_actuated_joints = bool(gripper_spec is not None and gripper_spec.has_actuated_joints) if constraint_timeconst is None: constraint_timeconst = 0.00125 if is_calibrated_adaptive else RIGID_CONSTRAINT_TIMECONST substep_dt = dt / int(substeps) @@ -436,21 +501,29 @@ def build_scene( ee_link_name = profile.ee_link ik_link = robot.get_link(ee_link_name) - left_finger = robot.get_link(gripper_spec.finger_link_names[0]) - right_finger = robot.get_link(gripper_spec.finger_link_names[1]) - - if gripper_spec.family == "g2": + left_finger = robot.get_link(gripper_spec.finger_link_names[0]) if has_finger_links and gripper_spec else None + right_finger = robot.get_link(gripper_spec.finger_link_names[1]) if has_finger_links and gripper_spec else None + tool_tip_link = None + if gripper_spec is not None and gripper_spec.tool_tip_link: + try: + tool_tip_link = robot.get_link(gripper_spec.tool_tip_link) + except Exception: + tool_tip_link = None + + if gripper_family == "g2": configure_g2_mimic_constraints(robot) - elif is_robotiq: - configure_robotiq_mimic_constraints(robot, gripper_spec.family) + elif is_robotiq and gripper_family is not None: + configure_robotiq_mimic_constraints(robot, gripper_family) if contact_sol_params is not None: - _set_contact_sol_params((obj, left_finger, right_finger), contact_sol_params) + sol_targets = tuple(item for item in (obj, left_finger, right_finger) if item is not None) + _set_contact_sol_params(sol_targets, contact_sol_params) # Configured painted-wood cube + silicone fingertip pads (μ=1.2). # Stiffness: leave default rigid contact sol_params. Set before any stepping. obj.set_friction(float(OBJ_FRICTION)) - left_finger.set_friction(float(FINGER_FRICTION)) - right_finger.set_friction(float(FINGER_FRICTION)) + if left_finger is not None and right_finger is not None: + left_finger.set_friction(float(FINGER_FRICTION)) + right_finger.set_friction(float(FINGER_FRICTION)) if hasattr(obj, "set_links_mass"): obj.set_links_mass(torch.tensor([obj_mass_kg], device=gs.device, dtype=gs.tc_float)) else: @@ -458,8 +531,12 @@ def build_scene( jnames = joint_names(profile) arm_dof_idx = [robot.get_joint(n).dofs_idx_local[0] for n in jnames] - gripper_dof_idx = [robot.get_joint(gripper_spec.drive_joint).dofs_idx_local[0]] - all_gripper_dof_idx = [robot.get_joint(n).dofs_idx_local[0] for n in gripper_spec.all_joint_names] + if has_actuated_joints and gripper_spec is not None and gripper_spec.drive_joint is not None: + gripper_dof_idx = [robot.get_joint(gripper_spec.drive_joint).dofs_idx_local[0]] + all_gripper_dof_idx = [robot.get_joint(n).dofs_idx_local[0] for n in gripper_spec.all_joint_names] + else: + gripper_dof_idx = [] + all_gripper_dof_idx = [] runtime_arm = runtime.arm robot.set_dofs_kp( @@ -475,90 +552,118 @@ def build_scene( torch.tensor(runtime_arm.force_upper, device=gs.device, dtype=gs.tc_float), arm_dof_idx, ) - robot.set_dofs_kp( - torch.tensor([gripper_spec.kp], device=gs.device, dtype=gs.tc_float), - gripper_dof_idx, - ) - robot.set_dofs_kv( - torch.tensor([gripper_spec.kv], device=gs.device, dtype=gs.tc_float), - gripper_dof_idx, - ) - robot.set_dofs_force_range( - torch.tensor([gripper_spec.force_lower], device=gs.device, dtype=gs.tc_float), - torch.tensor([gripper_spec.force_upper], device=gs.device, dtype=gs.tc_float), - gripper_dof_idx, - ) - n_grip = len(all_gripper_dof_idx) - robot.set_dofs_damping( - torch.full((n_grip,), gripper_spec.damping, device=gs.device, dtype=gs.tc_float), - all_gripper_dof_idx, - ) - robot.set_dofs_frictionloss( - torch.full((n_grip,), gripper_spec.frictionloss, device=gs.device, dtype=gs.tc_float), - all_gripper_dof_idx, - ) - if is_calibrated_g2: - from ufactory.simulation.g2_adapter import configure_g2_drive - - configure_g2_drive(robot, damping=gripper_spec.damping, frictionloss=gripper_spec.frictionloss) - elif is_calibrated_robotiq: - from ufactory.simulation.robotiq_adapter import configure_robotiq_drive - - configure_robotiq_drive( - robot, - gripper_spec.family, - damping=gripper_spec.damping, - frictionloss=gripper_spec.frictionloss, + if has_actuated_joints and gripper_spec is not None: + robot.set_dofs_kp( + torch.tensor([gripper_spec.kp], device=gs.device, dtype=gs.tc_float), + gripper_dof_idx, ) - elif gripper_spec.family == "lite6": - from ufactory.grippers.lite6 import configure_lite6_gripper_drive - - configure_lite6_gripper_drive( - robot, + robot.set_dofs_kv( + torch.tensor([gripper_spec.kv], device=gs.device, dtype=gs.tc_float), + gripper_dof_idx, + ) + robot.set_dofs_force_range( + torch.tensor([gripper_spec.force_lower], device=gs.device, dtype=gs.tc_float), + torch.tensor([gripper_spec.force_upper], device=gs.device, dtype=gs.tc_float), gripper_dof_idx, + ) + n_grip = len(all_gripper_dof_idx) + robot.set_dofs_damping( + torch.full((n_grip,), gripper_spec.damping, device=gs.device, dtype=gs.tc_float), + all_gripper_dof_idx, + ) + robot.set_dofs_frictionloss( + torch.full((n_grip,), gripper_spec.frictionloss, device=gs.device, dtype=gs.tc_float), all_gripper_dof_idx, - kp=gripper_spec.kp, - kv=gripper_spec.kv, - force_lower_n=gripper_spec.force_lower, - force_upper_n=gripper_spec.force_upper, - damping=gripper_spec.damping, - frictionloss=gripper_spec.frictionloss, ) + if is_calibrated_g2: + from ufactory.simulation.g2_adapter import configure_g2_drive + + configure_g2_drive(robot, damping=gripper_spec.damping, frictionloss=gripper_spec.frictionloss) + elif is_calibrated_robotiq: + from ufactory.simulation.robotiq_adapter import configure_robotiq_drive + + configure_robotiq_drive( + robot, + gripper_spec.family, + damping=gripper_spec.damping, + frictionloss=gripper_spec.frictionloss, + ) + elif gripper_spec.family == "lite6": + from ufactory.grippers.lite6 import configure_lite6_gripper_drive + + configure_lite6_gripper_drive( + robot, + gripper_dof_idx, + all_gripper_dof_idx, + kp=gripper_spec.kp, + kv=gripper_spec.kv, + force_lower_n=gripper_spec.force_lower, + force_upper_n=gripper_spec.force_upper, + damping=gripper_spec.damping, + frictionloss=gripper_spec.frictionloss, + ) dq = xyz_to_quat( torch.tensor([GRIPPER_DOWN_RPY_RAD], device=gs.device, dtype=gs.tc_float), rpy=True, degrees=False, ) - home_pos_base = [obj_xy[0], obj_xy[1], home_z] + home_pos_base = [resolved_home_xy[0], resolved_home_xy[1], home_z] home_pos = _base_to_world(robot_base, home_pos_base) home_link6_pos = torch.tensor([home_pos], device=gs.device, dtype=gs.tc_float) - home_qpos_result = solve_home_ik(robot, ik_link, home_link6_pos, dq, arm_dof_idx=arm_dof_idx) + home_controller = arm_controller + if home_controller is None and profile.dof == 5: + from ufactory.control import ArmMotionController + + home_controller = ArmMotionController.from_robot(profile.key, urdf_path=robot_urdf_path) + home_qpos_result = solve_home_ik( + robot, + ik_link, + home_link6_pos, + dq, + arm_dof_idx=arm_dof_idx, + arm_controller=home_controller, + target_pos_base=home_pos_base, + default_qpos_rad=defaults["default_qpos_rad"], + ) init_qpos = torch.zeros(1, robot.n_dofs, device=gs.device, dtype=gs.tc_float) for i, idx in enumerate(arm_dof_idx): init_qpos[:, idx] = home_qpos_result[0, arm_dof_idx[i]] - for idx in all_gripper_dof_idx: - if is_calibrated_g2: - from ufactory.simulation.g2_model import G2Model - - init_qpos[:, idx] = G2Model.load().linkage.drive_for_gap_m(0.084) - elif is_calibrated_robotiq: - from ufactory.simulation.robotiq_model import RobotiqModel - - init_qpos[:, idx] = RobotiqModel.load(gripper_spec.family).linkage.drive_for_gap_m(gripper_spec.open_gap_m) - else: - init_qpos[:, idx] = gripper_spec.open_pos + multipliers = gripper_dof_multipliers(gripper_spec) + if has_actuated_joints and gripper_spec is not None: + for i, idx in enumerate(all_gripper_dof_idx): + if is_calibrated_g2: + from ufactory.simulation.g2_model import G2Model + + init_qpos[:, idx] = G2Model.load().linkage.drive_for_gap_m(0.084) + elif is_calibrated_robotiq: + from ufactory.simulation.robotiq_model import RobotiqModel + + init_qpos[:, idx] = RobotiqModel.load(gripper_spec.family).linkage.drive_for_gap_m( + gripper_spec.open_gap_m + ) + else: + init_qpos[:, idx] = gripper_spec.open_pos * multipliers[i] robot.set_qpos(init_qpos) scene.step() link6_pos = ik_link.get_pos()[0] - lf_pos = left_finger.get_pos()[0] - rf_pos = right_finger.get_pos()[0] - fc_pos = (lf_pos + rf_pos) / 2 - finger_z_offset = (link6_pos[2] - fc_pos[2]).item() - # Finger-span across the open gap: fingers separate mainly along y when - # the gripper points down, so use the larger of |dy|/|dx| as the span. - finger_y_gap = max(abs(lf_pos[1] - rf_pos[1]).item(), abs(lf_pos[0] - rf_pos[0]).item()) + tcp_offset_flange_m = tuple(float(v) for v in defaults["tcp_offset_flange_m"]) + if left_finger is not None and right_finger is not None: + lf_pos = left_finger.get_pos()[0] + rf_pos = right_finger.get_pos()[0] + fc_pos = (lf_pos + rf_pos) / 2 + finger_z_offset = (link6_pos[2] - fc_pos[2]).item() + # Finger-span across the open gap: fingers separate mainly along y when + # the gripper points down, so use the larger of |dy|/|dx| as the span. + finger_y_gap = max(abs(lf_pos[1] - rf_pos[1]).item(), abs(lf_pos[0] - rf_pos[0]).item()) + elif tool_tip_link is not None: + tip_pos = tool_tip_link.get_pos()[0] + finger_z_offset = (link6_pos[2] - tip_pos[2]).item() + finger_y_gap = 0.0 + else: + finger_z_offset = float(tcp_offset_flange_m[2]) + finger_y_gap = 0.0 pad_below_fc = float(defaults["finger_pad_below_center_m"]) close_descent = float(defaults["finger_close_descent_m"]) @@ -566,7 +671,7 @@ def build_scene( grasp_extra = float(defaults["grasp_height_extra_m"]) grasp_link6_z = table_clearance + close_descent + pad_below_fc + finger_z_offset + grasp_extra - if is_calibrated_adaptive: + if is_calibrated_adaptive and gripper_spec is not None: grasp_link6_z = dry_heights(profile.key, gripper=gripper_spec.family).grasp_link6_z pre_grasp_link6_z = grasp_link6_z + 0.10 lift_link6_z = lift_z @@ -609,6 +714,7 @@ def build_scene( robotiq_settings=robotiq_settings, simulation_parameters={ "rate_hz": rate, + "sim_rate_hz": float(rate), "substeps": substeps, "constraint_time_constant_s": constraint_timeconst, "constraint_solver": constraint_solver, @@ -618,6 +724,11 @@ def build_scene( "contact_resolution": contact_resolution, "use_gjk_collision": use_gjk_collision, }, + sim_rate_hz=float(rate), + arm_controller=arm_controller if arm_controller is not None else home_controller, + gripper_dof_multipliers=multipliers, + tool_tip_link=tool_tip_link, + tcp_offset_flange_m=(tcp_offset_flange_m[0], tcp_offset_flange_m[1], tcp_offset_flange_m[2]), ) if is_calibrated_g2: from ufactory.simulation.g2_adapter import G2GenesisController @@ -642,12 +753,18 @@ def build_scene( return ctx -def drive_for_gap_m(gap_m: float, gripper: GripperControlParams) -> float: +def drive_for_gap_m(gap_m: float, gripper: GripperControlParams | None) -> float: """Convert pad gap (m) using G2/Robotiq geometry or linear prismatic travel.""" + if gripper is None or not getattr(gripper, "has_actuated_joints", bool(getattr(gripper, "all_joint_names", ()))): + return 0.0 if gripper.family == "g2": from ufactory.grippers.g2 import gripper_g2_gap_m_to_sim_drive return gripper_g2_gap_m_to_sim_drive(gap_m) + if gripper.family == "bio_gripper_g2": + from ufactory.grippers.bio_g2 import bio_gripper_g2_gap_m_to_sim_drive + + return bio_gripper_g2_gap_m_to_sim_drive(gap_m) if gripper.family in {"robotiq_2f_85", "robotiq_2f_140"}: from ufactory.grippers.robotiq import robotiq_gap_m_to_sim_drive diff --git a/ufactory/trajectory/sim_executor.py b/ufactory/trajectory/sim_executor.py index 00cf24a..d371542 100644 --- a/ufactory/trajectory/sim_executor.py +++ b/ufactory/trajectory/sim_executor.py @@ -10,6 +10,7 @@ from collections.abc import Callable from dataclasses import dataclass, field +import math import time import numpy as np @@ -72,6 +73,45 @@ class SimReport: record_paths: dict = field(default_factory=dict) +def physics_steps_for_tick( + sim_rate_hz: float, + control_rate_hz: float, + accumulator_s: float = 0.0, +) -> tuple[int, float]: + """Return ``(physics_steps, next_accumulator_s)`` for one control tick. + + When ``sim_rate_hz == control_rate_hz`` (default 50 Hz), returns ``(1, 0.0)``. + When Genesis runs at a higher rate (e.g. 100 Hz or 250 Hz with a 50 Hz servo + stream), executes matching sub-ticks so simulated time tracks command time. + """ + sim_r = float(sim_rate_hz) + ctrl_r = float(control_rate_hz) + if not math.isfinite(sim_r) or sim_r <= 0.0: + raise ValueError("sim_rate_hz must be finite and positive") + if not math.isfinite(ctrl_r) or ctrl_r <= 0.0: + raise ValueError("control_rate_hz must be finite and positive") + if math.isclose(sim_r, ctrl_r, rel_tol=1e-9, abs_tol=1e-9): + return 1, 0.0 + sim_dt = 1.0 / sim_r + total = float(accumulator_s) + (1.0 / ctrl_r) + steps = int(math.floor((total + 1e-12) / sim_dt)) + remainder = max(0.0, total - steps * sim_dt) + if abs(remainder - sim_dt) <= 1e-12: + steps += 1 + remainder = 0.0 + return steps, remainder + + +def _resolve_sim_rate_hz(ctx: TrajSceneContext, default_rate_hz: float) -> float: + sim_params = getattr(ctx, "simulation_parameters", None) + if isinstance(sim_params, dict) and sim_params.get("sim_rate_hz") is not None: + return float(sim_params["sim_rate_hz"]) + sim_rate = getattr(ctx, "sim_rate_hz", None) + if sim_rate is not None and isinstance(sim_rate, (int, float)) and not isinstance(sim_rate, bool): + return float(sim_rate) + return float(default_rate_hz) + + def replay_sim( program: Program, ctx: TrajSceneContext, @@ -148,6 +188,8 @@ def replay_sim( gripper_buffer_width = max(len(grip_control_idx), len(all_opening_grip_control_idx)) opening_only_grip_idx = [idx for idx in all_opening_grip_control_idx if idx not in grip_control_idx] rate = float(program.rate) + sim_rate_hz = _resolve_sim_rate_hz(ctx, rate) + sim_time_acc = 0.0 if not np.isfinite(final_metric_settle_s) or final_metric_settle_s < 0.0: raise ValueError("final_metric_settle_s must be finite and non-negative") report = SimReport(total_duration=program.total_duration, total_ticks=program.total_ticks) @@ -252,6 +294,7 @@ def replay_sim( current_grip_drive = float(drive_start + alpha * (final_target_drive - drive_start)) elif not is_holding_gap: current_grip_drive = contact_hold_drive if contact_hold_drive is not None else planned_grip_drive + n_phys, sim_time_acc = physics_steps_for_tick(sim_rate_hz, rate, sim_time_acc) _step( robot, scene, @@ -261,6 +304,7 @@ def replay_sim( grip_drive=current_grip_drive, grip_targets=grip_targets, buffers=buffers, + physics_steps=n_phys, ) _assert_finite_replay_state(ctx, phase=status.label, tick=t) if on_tick is not None: @@ -297,7 +341,7 @@ def replay_sim( for t in range(n): ik_started = time.perf_counter_ns() try: - q_arm = resolve_tick_arm_q(ctx, seg, samples, t, init_qpos=last_q_arm) + q_arm = resolve_tick_arm_q(ctx, seg, samples, t, init_qpos=last_q_arm, dt_s=1.0 / rate) except Exception: status.ik_failures += 1 raise @@ -305,6 +349,7 @@ def replay_sim( if seg.kind == "movel": status.ik_duration_ms += (time.perf_counter_ns() - ik_started) / 1e6 last_q_arm = q_arm + n_phys, sim_time_acc = physics_steps_for_tick(sim_rate_hz, rate, sim_time_acc) _step( robot, scene, @@ -313,6 +358,7 @@ def replay_sim( q_arm, grip_drive=current_grip_drive, buffers=buffers, + physics_steps=n_phys, ) _assert_finite_replay_state(ctx, phase=status.label, tick=t) if on_tick is not None: @@ -339,7 +385,9 @@ def replay_sim( # settle. Bare steps retain Genesis' latched arm/gripper control targets. report.metric_settle_ticks = int(np.ceil(float(final_metric_settle_s) * rate)) for settle_tick in range(report.metric_settle_ticks): - scene.step() + n_phys, sim_time_acc = physics_steps_for_tick(sim_rate_hz, rate, sim_time_acc) + for _ in range(n_phys): + scene.step() _assert_finite_replay_state(ctx, phase="final-settle", tick=settle_tick) # Final metrics: place error + home drift, both against the complete @@ -409,6 +457,7 @@ def _step( *, buffers: _TensorBuffers, grip_targets: np.ndarray | None = None, + physics_steps: int = 1, ): """Send one PD control tick and step the scene.""" if q_arm_target is not None: @@ -424,7 +473,8 @@ def _step( np.copyto(buffers.gripper_numpy[0, :width], np.asarray(grip_targets, dtype=buffers.gripper_numpy.dtype)) buffers.gripper.copy_(buffers.gripper_cpu, non_blocking=True) robot.control_dofs_position(buffers.gripper[:, : len(grip_control_idx)], grip_control_idx) - scene.step() + for _ in range(int(physics_steps)): + scene.step() def _current_drive(robot, grip_idx) -> float: diff --git a/ufactory/visualization/standalone_gripper.py b/ufactory/visualization/standalone_gripper.py index d13ad57..b6a804a 100644 --- a/ufactory/visualization/standalone_gripper.py +++ b/ufactory/visualization/standalone_gripper.py @@ -11,6 +11,7 @@ from ufactory.robots.paths import ( bio_gripper_g2_movable_visual_urdf, + ft_sensor_ai1500_urdf, gripper_g2_movable_visual_urdf, lite6_gripper_movable_visual_urdf, lite6_mounting_plate_urdf, @@ -159,6 +160,15 @@ def _setup(robot: object) -> Callable[[int], None]: camera_pos=ADAPTER_CAMERA_POS, camera_lookat=ADAPTER_CAMERA_LOOKAT, ), + "ft_sensor_ai1500": StandaloneToolSpec( + name="ft_sensor_ai1500", + description="UFACTORY AI1500 six-axis force/torque sensor static preview (standalone)", + urdf_loader=ft_sensor_ai1500_urdf, + base_pos=(0.0, 0.0, 0.005), + base_quat=UPRIGHT_QUAT_WXYZ, + camera_pos=(0.18, -0.22, 0.14), + camera_lookat=(0.0, 0.0, 0.03), + ), "bio_gripper_g2": StandaloneToolSpec( name="bio_gripper_g2", description="Bio Gripper G2 open/close demo (standalone)", diff --git a/uv.lock b/uv.lock index 689ee9f..eb491bb 100644 --- a/uv.lock +++ b/uv.lock @@ -888,7 +888,7 @@ wheels = [ [[package]] name = "genesis-ufactory" -version = "0.3.10" +version = "0.3.11" source = { editable = "." } dependencies = [ { name = "numpy" },