diff --git a/CHANGELOG.md b/CHANGELOG.md index 235fc78..75f3eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.3.12] — 2026-12-04 + +### Added + +- **Breaking (config `sha256`):** Added identified arm joint dynamics to the five runtime robot configs (`assets/configs/runtime/robots/{xarm5_1305,xarm6_1305,xarm7_1305,uf850,lite6}.yaml`): `arm.dynamics_profile` (default `compensated`) and `arm.dynamics` (`kt_output_nm_per_a`, `profiles.{compensated,raw}.{armature,damping,frictionloss}`, and `domain_randomization` relative ranges, which are validated but not yet applied). `compensated` uses the identified rotor armature and viscous damping with zero Coulomb friction, because the controller compensates dry friction; `raw` adds the identified Coulomb `frictionloss`. `apply_arm_joint_dynamics(...)` (`ufactory.dynamics.calibration`) applies the selected profile in the pick-place and packaging scenes, the robot viewers and both RL environments. Previously Genesis used the URDF `` damping/friction (kept as the upstream `xarm_ros2` baseline) and its default armature of `0.1`. The new fields are part of the runtime config `sha256` (`xarm6` + `gripper_g2`: `f4ecfc73…` → `f2ef50f1…`). The published v0.3.11 Pick & Place checkpoint is therefore refused at load (runtime config hash); both the Pick & Place and Reach checkpoints were retrained under the new dynamics (see Changed). +- Added per-unit dynamics calibration overlays (`ufactory.dynamics.calibration.load_dynamics_calibration`; schema 1, bound to `robot_key` and the full serial number; optional per-joint `armature` / `damping` / `frictionloss`, where `frictionloss` applies only under `raw`) and `--dynamics-profile {compensated,raw}` / `--dynamics-calibration` in the dynamics checks, whose reports now record the profile, the calibration path and `sha256`, and the applied joint armature and damping. + +### Changed + +- Updated the moving-link (`link1..linkN`) inertials of `xarm5_1305`, `xarm6_1305` and `xarm7_1305` (STL and GLB URDFs) from `xarm_ros2` `HT_BR2` to the official `UJ_BR_2403` parameters for `>= 1305` hardware (moving mass: xArm5 `8.1568 → 8.5270 kg`, xArm6 `9.35164 → 9.6710 kg`, xArm7 `10.4315 → 11.7844 kg`), keeping the unified `Xarm+_P01` `link_base`, and refreshed `assets/manifest.json`. On a bare-flange xArm7 the mean static gravity-torque error of the reference poses fell from `1.47` to `0.15 N·m`. `urdf_sha256` bindings of xArm5/6/7 and composed URDFs change. +- `lite6_visual.glb.urdf` now carries the same `link_base` inertia tensor as `lite6.urdf` (it was zero; no effect on the fixed-base arm). +- Retrained the five Reach checkpoints at `989a5fb` under the new physics (`compensated` joint dynamics, `UJ_BR_2403` inertials; seed `7`, `-B 4096`, `300` iterations) and replaced them on Hugging Face (`UFACTORY-Developer/ufactory_genesis_rl`, `reach/`). Selected checkpoints: `model_250.pt` (xArm5), `model_275.pt` (xArm6) and `model_299.pt` (xArm7, UF850, Lite6). Holdout evaluation (`17000` / `17001`, 512 episodes each): success `97.1–100%` / `97.9–100%`, mean terminal distance `4.23–5.78` / `4.19–5.71 mm`; peak VRAM `1.92–2.56 GB` on an RTX 4060 Ti. Updated the bilingual Reach README benchmark and examples. +- Retrained the `xArm6` + `Gripper G2` Pick & Place RL checkpoint (`C10` recipe, `-B 2048`, `v0.3.12` physics with `compensated` joint dynamics and `UJ_BR_2403` inertials) across a 10-seed benchmark (`seeds 1..10`, up to `1200` iterations): `9/10 (90%)` passed strict blind evaluation and `GLB B=1` replay (`574/576 = 99.65%` combined blind success across passing seeds, `0.00` IK rejects). Replaced `seed-7` on Hugging Face (`UFACTORY-Developer/ufactory_genesis_rl`) with `pick_place/xarm6-pick-place/seed-2/model_best.pt` (early-stopped at `700` iterations): `100%` dual-holdout (`64/64` on seed `17000`, `128/128` on seed `17500`), `100%` (`64/64`) blind evaluation on seed `18002` on both Colab L4 (`max_press = 0.496 mm`, mean/median error `7.55 / 7.28 mm`) and local RTX 4060 Ti (`max_press = 0.339 mm`, mean/median error `7.36 / 7.38 mm`), and `GLB B=1` replay PASS. Updated bilingual Pick & Place README benchmark and inference examples. + +### Fixed + +- `scripts/gen_kinematics_params.py` skips a unit whose SN model code rules out per-unit kinematics compensation (Lite6 `< 1006`, xArm `< 1304`) with exit code `2` before it picks a file suffix. Previously the auto-filled suffix made the eligibility check raise `ValueError`, or print a misleading "loading it anyway" warning when a matching user YAML existed. `--force` still exports such units. + ## [0.3.11] — 2026-11-28 ### Added diff --git a/README.md b/README.md index 25b7584..10a887d 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.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) +![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.12-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. diff --git a/README_zh.md b/README_zh.md index 7a0b95a..23bfc12 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.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) +![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.12-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 机械臂仿真与强化学习示例。 diff --git a/SECURITY.md b/SECURITY.md index 82dd094..bef989b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ ## Supported version -Only the current `0.3.11` development line receives security fixes. This is Alpha robotics software and is not safety-certified. +Only the current `0.3.12` development line receives security fixes. This is Alpha robotics software and is not safety-certified. ## Reporting diff --git a/assets/configs/runtime/robots/lite6.yaml b/assets/configs/runtime/robots/lite6.yaml index 1f5abe7..0121141 100644 --- a/assets/configs/runtime/robots/lite6.yaml +++ b/assets/configs/runtime/robots/lite6.yaml @@ -17,6 +17,22 @@ arm: force_lower_nm: [-81.6, -81.6, -30.6, -1.364505, -3.274812, -1.364505] force_upper_nm: [81.6, 81.6, 30.6, 1.364505, 3.274812, 1.364505] effort_limits_nm: [81.6, 81.6, 30.6, 1.364505, 3.274812, 1.364505] + dynamics_profile: compensated + dynamics: + kt_output_nm_per_a: [6.12, 6.12, 6.78165, 0.67, 1.608, 0.67] + profiles: + compensated: + armature: [0.17, 0.048, 0.111, 0.002, 0.001, 0.001] + damping: [1.8, 1.79, 1.7, 0.002, 0.01, 0.002] + frictionloss: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + raw: + armature: [0.17, 0.048, 0.111, 0.002, 0.001, 0.001] + damping: [1.8, 1.79, 1.7, 0.002, 0.01, 0.002] + frictionloss: [2.43, 1.47, 1.79, 0.03, 0.19, 0.03] + domain_randomization: + armature_rel_range: [0.85, 1.15] + damping_rel_range: [0.65, 1.35] + frictionloss_rel_range: [0.80, 1.20] gripper: adapter: lite6 drive_joint: finger_joint1 diff --git a/assets/configs/runtime/robots/uf850.yaml b/assets/configs/runtime/robots/uf850.yaml index 6b0c936..1e5a99f 100644 --- a/assets/configs/runtime/robots/uf850.yaml +++ b/assets/configs/runtime/robots/uf850.yaml @@ -17,6 +17,22 @@ arm: force_lower_nm: [-382.5, -382.5, -243.525, -117.3, -38.25, -38.25] force_upper_nm: [382.5, 382.5, 243.525, 117.3, 38.25, 38.25] effort_limits_nm: [382.5, 382.5, 243.525, 117.3, 38.25, 38.25] + dynamics_profile: compensated + dynamics: + kt_output_nm_per_a: [14.0, 14.0, 12.51, 10.4286, 10.887, 10.887] + profiles: + compensated: + armature: [1.382, 1.008, 0.354, 0.429, 0.368, 0.286] + damping: [16.48, 9.71, 6.23, 4.53, 2.48, 1.92] + frictionloss: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + raw: + armature: [1.382, 1.008, 0.354, 0.429, 0.368, 0.286] + damping: [16.48, 9.71, 6.23, 4.53, 2.48, 1.92] + frictionloss: [5.67, 4.92, 4.81, 2.03, 1.78, 1.49] + domain_randomization: + armature_rel_range: [0.85, 1.15] + damping_rel_range: [0.65, 1.35] + frictionloss_rel_range: [0.80, 1.20] gripper: adapter: g2 drive_joint: drive_joint diff --git a/assets/configs/runtime/robots/xarm5_1305.yaml b/assets/configs/runtime/robots/xarm5_1305.yaml index af16098..1eee661 100644 --- a/assets/configs/runtime/robots/xarm5_1305.yaml +++ b/assets/configs/runtime/robots/xarm5_1305.yaml @@ -17,6 +17,22 @@ arm: force_lower_nm: [-179.4445, -179.4445, -92.0, -30.6, -30.6] force_upper_nm: [179.4445, 179.4445, 92.0, 30.6, 30.6] effort_limits_nm: [179.4445, 179.4445, 92.0, 30.6, 30.6] + dynamics_profile: compensated + dynamics: + kt_output_nm_per_a: [6.7, 6.7, 5.73, 5.6, 5.6] + profiles: + compensated: + armature: [0.781, 0.756, 0.485, 0.295, 0.305] + damping: [15.24, 11.82, 5.22, 2.65, 3.41] + frictionloss: [0.0, 0.0, 0.0, 0.0, 0.0] + raw: + armature: [0.781, 0.756, 0.485, 0.295, 0.305] + damping: [15.24, 11.82, 5.22, 2.65, 3.41] + frictionloss: [4.67, 4.58, 3.12, 1.55, 1.64] + domain_randomization: + armature_rel_range: [0.85, 1.15] + damping_rel_range: [0.65, 1.35] + frictionloss_rel_range: [0.80, 1.20] gripper: adapter: g2 drive_joint: drive_joint diff --git a/assets/configs/runtime/robots/xarm6_1305.yaml b/assets/configs/runtime/robots/xarm6_1305.yaml index 167de2a..ad8c670 100644 --- a/assets/configs/runtime/robots/xarm6_1305.yaml +++ b/assets/configs/runtime/robots/xarm6_1305.yaml @@ -17,6 +17,22 @@ arm: force_lower_nm: [-179.4445, -179.4445, -92.0, -81.558, -30.6, -30.6] force_upper_nm: [179.4445, 179.4445, 92.0, 81.558, 30.6, 30.6] effort_limits_nm: [179.4445, 179.4445, 92.0, 81.558, 30.6, 30.6] + dynamics_profile: compensated + dynamics: + kt_output_nm_per_a: [6.7, 6.7, 5.73, 5.73, 5.6, 5.6] + profiles: + compensated: + armature: [0.781, 0.806, 0.434, 0.469, 0.293, 0.291] + damping: [13.31, 6.24, 3.83, 5.85, 1.99, 2.04] + frictionloss: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + raw: + armature: [0.781, 0.806, 0.434, 0.469, 0.293, 0.291] + damping: [13.31, 6.24, 3.83, 5.85, 1.99, 2.04] + frictionloss: [4.53, 4.16, 3.17, 2.36, 1.40, 1.51] + domain_randomization: + armature_rel_range: [0.85, 1.15] + damping_rel_range: [0.65, 1.35] + frictionloss_rel_range: [0.80, 1.20] gripper: adapter: g2 drive_joint: drive_joint diff --git a/assets/configs/runtime/robots/xarm7_1305.yaml b/assets/configs/runtime/robots/xarm7_1305.yaml index 8bbfa75..2358720 100644 --- a/assets/configs/runtime/robots/xarm7_1305.yaml +++ b/assets/configs/runtime/robots/xarm7_1305.yaml @@ -17,6 +17,22 @@ arm: force_lower_nm: [-179.4445, -179.4445, -92.0, -92.0, -81.558, -30.6, -30.6] force_upper_nm: [179.4445, 179.4445, 92.0, 92.0, 81.558, 30.6, 30.6] effort_limits_nm: [179.4445, 179.4445, 92.0, 92.0, 81.558, 30.6, 30.6] + dynamics_profile: compensated + dynamics: + kt_output_nm_per_a: [6.7, 6.7, 5.73, 5.73, 5.73, 5.6, 5.6] + profiles: + compensated: + armature: [0.752, 0.785, 0.547, 0.529, 0.439, 0.325, 0.305] + damping: [10.39, 8.15, 6.24, 6.72, 5.96, 3.37, 2.39] + frictionloss: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + raw: + armature: [0.752, 0.785, 0.547, 0.529, 0.439, 0.325, 0.305] + damping: [10.39, 8.15, 6.24, 6.72, 5.96, 3.37, 2.39] + frictionloss: [3.61, 4.03, 3.05, 3.44, 3.18, 1.75, 1.34] + domain_randomization: + armature_rel_range: [0.85, 1.15] + damping_rel_range: [0.65, 1.35] + frictionloss_rel_range: [0.80, 1.20] gripper: adapter: g2 drive_joint: drive_joint diff --git a/assets/manifest.json b/assets/manifest.json index 53a7168..6ff1cb4 100644 --- a/assets/manifest.json +++ b/assets/manifest.json @@ -1,5 +1,5 @@ { - "manifest_version": "0.3.11", + "manifest_version": "0.3.12", "required_paths": [ "assets/configs/runtime/motion/default.yaml", "assets/configs/runtime/safety/default.yaml", @@ -49,11 +49,11 @@ "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/robots/lite6.yaml": "2907c760cfdc24bf46d60b1426cb68897588a059080445b20d6faa57210f6895", + "assets/configs/runtime/robots/uf850.yaml": "ec323f4f706378b2bb60aaeed326c3eaf9d4868b023c80f3451f068aae8397b9", + "assets/configs/runtime/robots/xarm5_1305.yaml": "c8b8dacf1331c95f8edba53d470159d88693fe45345697afff87bc01b0044fa1", + "assets/configs/runtime/robots/xarm6_1305.yaml": "06c11799e8d9bd7bdb9100501dd702a0ceb58039a00571a8a025b01dc3549ed0", + "assets/configs/runtime/robots/xarm7_1305.yaml": "799823b86be4cd844ce7c7af09af2c76087e876c9f2fb3f03728394f1922fbb4", "assets/configs/runtime/safety/default.yaml": "29fd72f5863759e2b9167b34fe25723868fc5a633cf1837e7776e12112d71c06", "assets/configs/runtime/simulation/default.yaml": "b779c272ecd951d555be22a7420cfa284ad08e678624ca1eff7da7a66ff75bea", "assets/configs/runtime/tasks/packaging_showcase.yaml": "164aff6a872a60bd241a7edb2b807371b26616a3c154f6ea672e37e7b57f203a", @@ -81,8 +81,8 @@ "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" + "assets/urdf/robots/xarm5/xarm5_1305.urdf": "99a81c665cb33292c1c811158a7f027aa59abfaacb9d3ad43e02e6f11720d707", + "assets/urdf/robots/xarm6/xarm6_1305.urdf": "7c13f419574a5a23b4de711ca4373d029bd8ab51095aac7a2a56ce181b09aa51", + "assets/urdf/robots/xarm7/xarm7_1305.urdf": "74f4c7ddf14f8bbef9856550104032aea818f85d5126f6712584ef6aa147215c" } } diff --git a/assets/urdf/robots/lite6/README.md b/assets/urdf/robots/lite6/README.md index 5f3174d..2d1b47f 100644 --- a/assets/urdf/robots/lite6/README.md +++ b/assets/urdf/robots/lite6/README.md @@ -7,7 +7,7 @@ Lite6 arm description. | Path | Content | |---|---| | `lite6.urdf` | Default URDF, STL visuals | -| `lite6_visual.glb.urdf` | GLB visuals. Same physics, except that the `link_base` inertia tensor is zero (fixed base, no effect on dynamics) | +| `lite6_visual.glb.urdf` | Same physics and inertials, GLB visuals | | `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 (19) | @@ -25,6 +25,10 @@ End effectors for the `lite6` flange: [`lite6_gripper`](../../end_effectors/lite Why the other links use several hulls: see [xArm6 collision meshes](../xarm6/README.md#collision-meshes). +## Joint dynamics + +URDF `` tags preserve the upstream `xarm_ros2` baseline. Runtime Genesis joint dynamics (`armature`, `damping`, `frictionloss`, `kt_output_nm_per_a`) are managed centrally in [lite6.yaml](../../../configs/runtime/robots/lite6.yaml) (`compensated` default / `raw` optional) and can be overlaid per unit via `load_dynamics_calibration(...)`. + ## Source / License - URDF and STL derive from the upstream xArm ROS / xarm_ros2 family (see [NOTICE](../../../../NOTICE)). diff --git a/assets/urdf/robots/lite6/lite6_visual.glb.urdf b/assets/urdf/robots/lite6/lite6_visual.glb.urdf index b91aca1..836a707 100644 --- a/assets/urdf/robots/lite6/lite6_visual.glb.urdf +++ b/assets/urdf/robots/lite6/lite6_visual.glb.urdf @@ -22,7 +22,7 @@ - + diff --git a/assets/urdf/robots/uf850/README.md b/assets/urdf/robots/uf850/README.md index 768bfe1..bf596c1 100644 --- a/assets/urdf/robots/uf850/README.md +++ b/assets/urdf/robots/uf850/README.md @@ -27,6 +27,10 @@ Why the links use several hulls: see [xArm6 collision meshes](../xarm6/README.md `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`). +## Joint dynamics + +URDF `` tags preserve the upstream `xarm_ros2` baseline. Runtime Genesis joint dynamics (`armature`, `damping`, `frictionloss`, `kt_output_nm_per_a`) are managed centrally in [uf850.yaml](../../../configs/runtime/robots/uf850.yaml) (`compensated` default / `raw` optional) and can be overlaid per unit via `load_dynamics_calibration(...)`. + ## Source / License - URDF and STL derive from the upstream UFACTORY / xArm ROS descriptions (see [NOTICE](../../../../NOTICE)). diff --git a/assets/urdf/robots/xarm5/README.md b/assets/urdf/robots/xarm5/README.md index 9ded215..2131f6a 100644 --- a/assets/urdf/robots/xarm5/README.md +++ b/assets/urdf/robots/xarm5/README.md @@ -23,9 +23,13 @@ No arm + end-effector URDFs are stored: `ufactory.robots.assembly` composes them - 22 hulls in total. xArm5 J4/J5 are xArm6 J5/J6. - `test_xarm5_is_xarm6_with_j4_locked` (`tests/robots/test_asset_integrity.py`) checks that the link poses and mesh placements equal the xArm6's at J4 = 0. -- Moving-link inertials are not shared: xArm5 link3 is 2.121 kg, 1.07 kg lighter than xArm6 link3 + link4 (no J4 module). `link_base` shares the unified xArm5/6/7 inertial parameters (`2.788411 kg`; see [xArm6 shared parts](../xarm6/README.md#shared-parts)). +- Moving-link inertials are not shared and use official upstream `xarm_ros2` `UJ_BR_2403` parameters (`>= 1305` hardware, moving mass `8.5270 kg`): xArm5 `link3` is `2.240 kg`, `1.14 kg` lighter than xArm6 `link3 + link4` (`2.019 + 1.361 = 3.380 kg`, no J4 module). `link_base` shares the unified xArm5/6/7 inertial parameters (`2.788411 kg`; see [xArm6 shared parts](../xarm6/README.md#shared-parts)). - Why the links use several hulls: see [xArm6 collision meshes](../xarm6/README.md#collision-meshes). +## Joint dynamics + +URDF `` tags preserve the upstream `xarm_ros2` baseline. Runtime Genesis joint dynamics (`armature`, `damping`, `frictionloss`, `kt_output_nm_per_a`) are managed centrally in [xarm5_1305.yaml](../../../configs/runtime/robots/xarm5_1305.yaml) (`compensated` default / `raw` optional) and can be overlaid per unit via `load_dynamics_calibration(...)`. + ## Source / License - URDF derives from the upstream xArm ROS descriptions (see [NOTICE](../../../../NOTICE); typically BSD-3-Clause). diff --git a/assets/urdf/robots/xarm5/xarm5_1305.urdf b/assets/urdf/robots/xarm5/xarm5_1305.urdf index 2216211..72ba9ec 100644 --- a/assets/urdf/robots/xarm5/xarm5_1305.urdf +++ b/assets/urdf/robots/xarm5/xarm5_1305.urdf @@ -46,9 +46,9 @@ - - - + + + @@ -80,9 +80,9 @@ - - - + + + @@ -132,9 +132,9 @@ - - - + + + @@ -222,9 +222,9 @@ - - - + + + @@ -256,9 +256,9 @@ - - - + + + diff --git a/assets/urdf/robots/xarm5/xarm5_1305_visual.glb.urdf b/assets/urdf/robots/xarm5/xarm5_1305_visual.glb.urdf index 81717d7..d678f7e 100644 --- a/assets/urdf/robots/xarm5/xarm5_1305_visual.glb.urdf +++ b/assets/urdf/robots/xarm5/xarm5_1305_visual.glb.urdf @@ -46,9 +46,9 @@ - - - + + + @@ -80,9 +80,9 @@ - - - + + + @@ -132,9 +132,9 @@ - - - + + + @@ -222,9 +222,9 @@ - - - + + + @@ -256,9 +256,9 @@ - - - + + + diff --git a/assets/urdf/robots/xarm6/README.md b/assets/urdf/robots/xarm6/README.md index f583d43..88c37f8 100644 --- a/assets/urdf/robots/xarm6/README.md +++ b/assets/urdf/robots/xarm6/README.md @@ -30,7 +30,11 @@ Other arms reference these meshes directly, so editing them changes those arms t - [xArm5](../xarm5/README.md): every link. The xArm5 is an xArm6 with J4 locked at 0. - [xArm7](../xarm7/README.md): `link_base`, and `link6` as the xArm7 flange link `link7`. -The base is the production version A: flat top at z = 150.35 mm, body Ø95.4 mm. Its STL matches upstream `xarm6_1305`; its GLB comes from the CAD export `1305-xarm5-P01-95-3`. The prototype version B (body Ø98.0 mm, top rising to 152.55 mm) is not used. All three arms also share the unified `link_base` inertial parameters evaluated in SolidWorks on the production base assembly `Xarm+_P01` (`2.788411 kg`, CoM `(-2.587, -0.269, 103.569) mm`, standard URDF negative off-diagonal product-of-inertia convention). +The base is the production version A: flat top at z = 150.35 mm, body Ø95.4 mm. Its STL matches upstream `xarm6_1305`; its GLB comes from the CAD export `1305-xarm5-P01-95-3`. The prototype version B (body Ø98.0 mm, top rising to 152.55 mm) is not used. All three arms also share the unified `link_base` inertial parameters evaluated in SolidWorks on the production base assembly `Xarm+_P01` (`2.788411 kg`, CoM `(-2.587, -0.269, 103.569) mm`, standard URDF negative off-diagonal product-of-inertia convention). Moving links (`link1..link6`, `9.6710 kg`) use the official upstream `xarm_ros2` `UJ_BR_2403` inertial parameters (`>= 1305` hardware). + +## Joint dynamics + +URDF `` tags preserve the upstream `xarm_ros2` baseline. Runtime Genesis joint dynamics (`armature`, `damping`, `frictionloss`, `kt_output_nm_per_a`) are managed centrally in [xarm6_1305.yaml](../../../configs/runtime/robots/xarm6_1305.yaml) (`compensated` default / `raw` optional) and can be overlaid per unit via `load_dynamics_calibration(...)`. ## Source / License diff --git a/assets/urdf/robots/xarm6/xarm6_1305.urdf b/assets/urdf/robots/xarm6/xarm6_1305.urdf index 80cfa27..28f387f 100644 --- a/assets/urdf/robots/xarm6/xarm6_1305.urdf +++ b/assets/urdf/robots/xarm6/xarm6_1305.urdf @@ -40,9 +40,9 @@ - - - + + + @@ -74,9 +74,9 @@ - - - + + + @@ -126,9 +126,9 @@ - - - + + + @@ -178,9 +178,9 @@ - - - + + + @@ -230,9 +230,9 @@ - - - + + + @@ -264,9 +264,9 @@ - - - + + + diff --git a/assets/urdf/robots/xarm6/xarm6_1305_visual.glb.urdf b/assets/urdf/robots/xarm6/xarm6_1305_visual.glb.urdf index c392f25..63af6f6 100644 --- a/assets/urdf/robots/xarm6/xarm6_1305_visual.glb.urdf +++ b/assets/urdf/robots/xarm6/xarm6_1305_visual.glb.urdf @@ -39,9 +39,9 @@ - - - + + + @@ -72,9 +72,9 @@ - - - + + + @@ -123,9 +123,9 @@ - - - + + + @@ -174,9 +174,9 @@ - - - + + + @@ -225,9 +225,9 @@ - - - + + + @@ -258,9 +258,9 @@ - - - + + + diff --git a/assets/urdf/robots/xarm7/README.md b/assets/urdf/robots/xarm7/README.md index 3c02225..d41e288 100644 --- a/assets/urdf/robots/xarm7/README.md +++ b/assets/urdf/robots/xarm7/README.md @@ -25,7 +25,11 @@ xArm7 arm description (1305 variant). ## Shared parts -`link_base` and `link7` use the visual and collision meshes of xArm6 `link_base` and `link6` (see [xArm6 shared parts](../xarm6/README.md#shared-parts)): the production base (version A, also sharing the unified `2.788411 kg` / CoM `(-2.587, -0.269, 103.569) mm` `link_base` inertial parameters), and the flange link that xArm5/6/7 share. +`link_base` and `link7` use the visual and collision meshes of xArm6 `link_base` and `link6` (see [xArm6 shared parts](../xarm6/README.md#shared-parts)): the production base (version A, also sharing the unified `2.788411 kg` / CoM `(-2.587, -0.269, 103.569) mm` `link_base` inertial parameters), and the flange link that xArm5/6/7 share. Moving links (`link1..link7`, `11.7844 kg`) use the official upstream `xarm_ros2` `UJ_BR_2403` inertial parameters (`>= 1305` hardware). + +## Joint dynamics + +URDF `` tags preserve the upstream `xarm_ros2` baseline. Runtime Genesis joint dynamics (`armature`, `damping`, `frictionloss`, `kt_output_nm_per_a`) are managed centrally in [xarm7_1305.yaml](../../../configs/runtime/robots/xarm7_1305.yaml) (`compensated` default / `raw` optional) and can be overlaid per unit via `load_dynamics_calibration(...)`. ## Source / License diff --git a/assets/urdf/robots/xarm7/xarm7_1305.urdf b/assets/urdf/robots/xarm7/xarm7_1305.urdf index 4271bc6..746657c 100644 --- a/assets/urdf/robots/xarm7/xarm7_1305.urdf +++ b/assets/urdf/robots/xarm7/xarm7_1305.urdf @@ -46,9 +46,9 @@ - - - + + + @@ -80,9 +80,9 @@ - - - + + + @@ -132,9 +132,9 @@ - - - + + + @@ -178,9 +178,9 @@ - - - + + + @@ -230,9 +230,9 @@ - - - + + + @@ -282,9 +282,9 @@ - - - + + + @@ -316,9 +316,9 @@ - + - + diff --git a/assets/urdf/robots/xarm7/xarm7_1305_visual.glb.urdf b/assets/urdf/robots/xarm7/xarm7_1305_visual.glb.urdf index 91d7fe4..936c635 100644 --- a/assets/urdf/robots/xarm7/xarm7_1305_visual.glb.urdf +++ b/assets/urdf/robots/xarm7/xarm7_1305_visual.glb.urdf @@ -46,9 +46,9 @@ - - - + + + @@ -80,9 +80,9 @@ - - - + + + @@ -132,9 +132,9 @@ - - - + + + @@ -178,9 +178,9 @@ - - - + + + @@ -230,9 +230,9 @@ - - - + + + @@ -282,9 +282,9 @@ - - - + + + @@ -316,9 +316,9 @@ - + - + diff --git a/examples/rl/pick_place/README.md b/examples/rl/pick_place/README.md index 78efca9..34fd7d0 100644 --- a/examples/rl/pick_place/README.md +++ b/examples/rl/pick_place/README.md @@ -50,13 +50,13 @@ python -m examples.rl.pick_place.train \ ## Benchmark -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%`). +Across a 10-seed `C10` benchmark (`seeds 1..10`, `-B 2048`, up to `1200` iterations, `v0.3.12`), **9/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 **`574/576 (99.65%)`** combined blind success across passing seeds with **`0.00`** IK rejects (seven seeds at `64/64 = 100.0%`, two 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)**: +The pretrained checkpoint hosted on Hugging Face (`pick_place/xarm6-pick-place/seed-2/model_best.pt`, early-stopped at `700` 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 | +| Robot + Gripper | Obs / Act Dim | Checkpoint | Dual Holdout (`17000` / `17500`) | Blind Eval (`18002`, 64 eps) | Max Press (`18002`) | Mean / Median Target Err (`18002`) | 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** | +| `xarm6` + `gripper_g2` | 70 / 4 | `seed-2/model_best.pt` | **100%** (64/64) / **100%** (128/128) | **100%** (64/64) | `0.339 mm` (≤1.0 mm) | `7.36` / `7.38 mm` (≤20 mm) | **PASS** | ## Evaluation and inference @@ -67,18 +67,18 @@ If you do not need to train from scratch locally, download the pretrained checkp 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. +The examples below use the downloaded checkpoint `outputs/rl/pick_place/xarm6-pick-place/seed-2/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 hosted seed-7 checkpoint, requiring ≥98% success rate and ≤1 mm maximum pressing over 64 episodes: +The example below evaluates the hosted seed-2 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/xarm6-pick-place/seed-7/model_best.pt \ - -B 32 --episodes 64 --seed 18007 \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt \ + -B 32 --episodes 64 --seed 18002 \ --min-success-rate 0.98 --max-press-mm 1.0 \ - --quiet-episodes --out outputs/rl/pick_place/xarm6-pick-place/seed-7/test.json + --quiet-episodes --out outputs/rl/pick_place/xarm6-pick-place/seed-2/test.json ``` `--out` writes both a JSON summary and a per-episode CSV table; exits with code `1` if the thresholds are not met. @@ -88,13 +88,13 @@ python -m examples.rl.pick_place.evaluate \ ```bash # Open interactive viewer python -m examples.rl.pick_place.visualize \ - --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt -B 1 + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt -B 1 # Record a single-episode headless video python -m examples.rl.pick_place.visualize \ - --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt \ -B 1 --episodes 1 --headless \ - --record outputs/rl/pick_place/xarm6-pick-place/seed-7/replay.mp4 + --record outputs/rl/pick_place/xarm6-pick-place/seed-2/replay.mp4 ``` `-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. diff --git a/examples/rl/pick_place/README_zh.md b/examples/rl/pick_place/README_zh.md index c773e66..331510e 100644 --- a/examples/rl/pick_place/README_zh.md +++ b/examples/rl/pick_place/README_zh.md @@ -50,13 +50,13 @@ python -m examples.rl.pick_place.train \ ## 基准与预训练结果 -在 `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%`)。 +在 `v0.3.12` 的 10 种子 `C10` 基准(`seeds 1..10`,`-B 2048`,上限 `1200` 轮)中,**9/10** 个种子通过独立盲测(`seed = 18000 + s`,64 回合成功率 ≥98%、最大下压 ≤1.0 mm)与单环境 `GLB` 回放,通过种子合计盲测成功率 **`574/576 (99.65%)`**,全种子 `ik_rejects = 0.00`(其中 7 个种子 `64/64 = 100.0%`,2 个种子 `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)** 上双重验证通过: +托管于 Hugging Face 的预训练检查点(`pick_place/xarm6-pick-place/seed-2/model_best.pt`,第 `700` 轮早停)已在 Colab L4 与本地 **NVIDIA GeForce RTX 4060 Ti (8 GB)** 上双重验证通过: -| 机械臂 + 夹爪 | 观测 / 动作维 | 检查点 | 双验证集 (`17000` / `17500`) | 独立盲测 (`18007`, 64 回合) | 最大下压 (`18007`) | 落点误差均值 / 中位 (`18007`) | GLB `B=1` 回放 | +| 机械臂 + 夹爪 | 观测 / 动作维 | 检查点 | 双验证集 (`17000` / `17500`) | 独立盲测 (`18002`, 64 回合) | 最大下压 (`18002`) | 落点误差均值 / 中位 (`18002`) | 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** | +| `xarm6` + `gripper_g2` | 70 / 4 | `seed-2/model_best.pt` | **100%** (64/64) / **100%** (128/128) | **100%** (64/64) | `0.339 mm` (≤1.0 mm) | `7.36` / `7.38 mm` (≤20 mm) | **PASS** | ## 评估与推理 @@ -67,18 +67,18 @@ python -m examples.rl.pick_place.train \ 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`)。请先评估检查点,再用于推理。 +以下命令以下载后的 `outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt` 为例(若使用本地训练结果,将 `--checkpoint` 替换为 `outputs/rl/pick_place/pick_place_e2e_s1/model_best.pt` 或传入 `-e pick_place_e2e_s1`)。请先评估检查点,再用于推理。 ### 评估 -以下示例评估预训练种子 7 的最佳检查点,要求 64 回合成功率 ≥98%、最大下压 ≤1 mm: +以下示例评估预训练种子 2 的最佳检查点,要求 64 回合成功率 ≥98%、最大下压 ≤1 mm: ```bash python -m examples.rl.pick_place.evaluate \ - --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ - -B 32 --episodes 64 --seed 18007 \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt \ + -B 32 --episodes 64 --seed 18002 \ --min-success-rate 0.98 --max-press-mm 1.0 \ - --quiet-episodes --out outputs/rl/pick_place/xarm6-pick-place/seed-7/test.json + --quiet-episodes --out outputs/rl/pick_place/xarm6-pick-place/seed-2/test.json ``` `--out` 同时生成 JSON 汇总和 CSV 逐回合结果;未达到门限时命令返回退出码 `1`。 @@ -88,13 +88,13 @@ python -m examples.rl.pick_place.evaluate \ ```bash # 打开交互窗口 python -m examples.rl.pick_place.visualize \ - --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt -B 1 + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt -B 1 # 无头录制单回合视频 python -m examples.rl.pick_place.visualize \ - --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-7/model_best.pt \ + --checkpoint outputs/rl/pick_place/xarm6-pick-place/seed-2/model_best.pt \ -B 1 --episodes 1 --headless \ - --record outputs/rl/pick_place/xarm6-pick-place/seed-7/replay.mp4 + --record outputs/rl/pick_place/xarm6-pick-place/seed-2/replay.mp4 ``` `-e` 指定 `outputs/rl/pick_place/` 下的实验名,默认加载对应目录中的 `model_best.pt`;也可使用 `--checkpoint` 显式指定检查点文件。`--headless` 无需桌面窗口,`--record` 指定 MP4 输出路径。检查点、`config.yaml` 与 `model_best.checkpoint_manifest.json` 需放在同一目录。 diff --git a/examples/rl/reach/README.md b/examples/rl/reach/README.md index 62c3b02..eb3d6c7 100644 --- a/examples/rl/reach/README.md +++ b/examples/rl/reach/README.md @@ -37,11 +37,11 @@ Measured on an **NVIDIA GeForce RTX 4060 Ti (8 GB)** with the [one-command run]( | `--robot` | VRAM | 300-iteration training time (total / PPO iterations) | Selected checkpoint | Validation success rate (17000 / 17001) | Mean terminal distance (17000 / 17001) | |---|---|---|---|---|---| -| `xarm5` | 1.82 GB | 192 s / 159 s | `model_299.pt` | 99.6% / 99.8% | 4.48 / 4.50 mm | -| `xarm6` | 2.16 GB | 257 s / 240 s | `model_299.pt` | 100% / 100% | 4.23 / 4.24 mm | -| `xarm7` | 2.60 GB | 272 s / 255 s | `model_299.pt` | 99.8% / 99.2% | 4.39 / 4.52 mm | -| `uf850` | 2.32 GB | 297 s / 280 s | `model_299.pt` | 99.6% / 99.6% | 4.26 / 4.34 mm | -| `lite6` | 1.94 GB | 200 s / 167 s | `model_299.pt` | 99.8% / 99.6% | 4.66 / 4.71 mm | +| `xarm5` | 1.92 GB | 193 s / 152 s | `model_250.pt` | 97.1% / 97.9% | 5.78 / 5.71 mm | +| `xarm6` | 2.11 GB | 171 s / 125 s | `model_275.pt` | 99.2% / 98.8% | 4.45 / 4.49 mm | +| `xarm7` | 2.56 GB | 215 s / 176 s | `model_299.pt` | 100% / 100% | 4.30 / 4.30 mm | +| `uf850` | 2.26 GB | 170 s / 130 s | `model_299.pt` | 99.8% / 99.8% | 4.23 / 4.19 mm | +| `lite6` | 2.04 GB | 176 s / 136 s | `model_299.pt` | 100% / 99.6% | 4.72 / 4.71 mm | - VRAM is the training process peak; total time includes Genesis initialization and scene building. - Reduce `-B` (number of parallel environments) if VRAM is insufficient. When resuming, `-B` must match the original run. @@ -121,17 +121,17 @@ hf download UFACTORY-Developer/ufactory_genesis_rl --include "reach/xarm6-reach/ The selected checkpoint is not necessarily the last one. Check the selection result first: ```bash -# Example output: "selected_checkpoint": "model_299.pt", +# Example output: "selected_checkpoint": "model_275.pt", grep selected_checkpoint outputs/rl/reach/xarm6-reach/seed-7/checkpoint-selection.json ``` -The examples below use `outputs/rl/reach/xarm6-reach/seed-7/model_299.pt`; replace `--checkpoint` with the file name shown above. +The examples below use `outputs/rl/reach/xarm6-reach/seed-7/model_275.pt`; replace `--checkpoint` with the file name shown above. ### Evaluate a checkpoint ```bash python -m examples.rl.reach.evaluate \ - --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_299.pt \ + --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_275.pt \ -B 128 --episodes 512 --seed 17000 \ --min-success-rate 0.95 --max-mean-distance-m 0.010 \ --quiet-episodes --summary-json outputs/rl/reach/xarm6-reach/seed-7/evaluation-17000.json @@ -146,11 +146,11 @@ python -m examples.rl.reach.evaluate \ ```bash # Single arm python -m examples.rl.reach.visualize \ - --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_299.pt + --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_275.pt # Four arms python -m examples.rl.reach.visualize \ - --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_299.pt -b 4 + --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_275.pt -b 4 ``` - Robots are rendered with GLB visual models. Each arm holds for 1 s after success before starting its next episode. Close the window or press Ctrl+C to exit. diff --git a/examples/rl/reach/README_zh.md b/examples/rl/reach/README_zh.md index 33e3e3e..d29c0ba 100644 --- a/examples/rl/reach/README_zh.md +++ b/examples/rl/reach/README_zh.md @@ -37,11 +37,11 @@ | `--robot` | 显存占用 | 300 轮训练时间(总 / PPO 迭代) | 选中检查点 | 验收成功率(17000 / 17001) | 平均终止距离(17000 / 17001) | |---|---|---|---|---|---| -| `xarm5` | 1.82 GB | 192 s / 159 s | `model_299.pt` | 99.6% / 99.8% | 4.48 / 4.50 mm | -| `xarm6` | 2.16 GB | 257 s / 240 s | `model_299.pt` | 100% / 100% | 4.23 / 4.24 mm | -| `xarm7` | 2.60 GB | 272 s / 255 s | `model_299.pt` | 99.8% / 99.2% | 4.39 / 4.52 mm | -| `uf850` | 2.32 GB | 297 s / 280 s | `model_299.pt` | 99.6% / 99.6% | 4.26 / 4.34 mm | -| `lite6` | 1.94 GB | 200 s / 167 s | `model_299.pt` | 99.8% / 99.6% | 4.66 / 4.71 mm | +| `xarm5` | 1.92 GB | 193 s / 152 s | `model_250.pt` | 97.1% / 97.9% | 5.78 / 5.71 mm | +| `xarm6` | 2.11 GB | 171 s / 125 s | `model_275.pt` | 99.2% / 98.8% | 4.45 / 4.49 mm | +| `xarm7` | 2.56 GB | 215 s / 176 s | `model_299.pt` | 100% / 100% | 4.30 / 4.30 mm | +| `uf850` | 2.26 GB | 170 s / 130 s | `model_299.pt` | 99.8% / 99.8% | 4.23 / 4.19 mm | +| `lite6` | 2.04 GB | 176 s / 136 s | `model_299.pt` | 100% / 99.6% | 4.72 / 4.71 mm | - 显存占用为训练进程峰值;总时间包含 Genesis 初始化与场景构建。 - 显存不足时减小 `-B`(并行环境数),续训时 `-B` 须与原训练一致。 @@ -121,17 +121,17 @@ hf download UFACTORY-Developer/ufactory_genesis_rl --include "reach/xarm6-reach/ 筛选选中的检查点不一定是最后一个,可先通过以下命令查看: ```bash -# 输出示例:"selected_checkpoint": "model_299.pt", +# 输出示例:"selected_checkpoint": "model_275.pt", grep selected_checkpoint outputs/rl/reach/xarm6-reach/seed-7/checkpoint-selection.json ``` -以下以 `outputs/rl/reach/xarm6-reach/seed-7/model_299.pt` 为例,按实际查到的文件名替换 `--checkpoint`。 +以下以 `outputs/rl/reach/xarm6-reach/seed-7/model_275.pt` 为例,按实际查到的文件名替换 `--checkpoint`。 ### 单独评估 ```bash python -m examples.rl.reach.evaluate \ - --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_299.pt \ + --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_275.pt \ -B 128 --episodes 512 --seed 17000 \ --min-success-rate 0.95 --max-mean-distance-m 0.010 \ --quiet-episodes --summary-json outputs/rl/reach/xarm6-reach/seed-7/evaluation-17000.json @@ -146,11 +146,11 @@ python -m examples.rl.reach.evaluate \ ```bash # 单臂 python -m examples.rl.reach.visualize \ - --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_299.pt + --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_275.pt # 四臂 python -m examples.rl.reach.visualize \ - --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_299.pt -b 4 + --checkpoint outputs/rl/reach/xarm6-reach/seed-7/model_275.pt -b 4 ``` - 使用 GLB 外观模型显示;每台机械臂成功后独立保持 1 s 再开始下一回合。关闭窗口或按 Ctrl+C 退出。 diff --git a/examples/rl/reach/env.py b/examples/rl/reach/env.py index 2f3a821..7f80b6a 100644 --- a/examples/rl/reach/env.py +++ b/examples/rl/reach/env.py @@ -135,6 +135,12 @@ def _init_state(self) -> None: torch.tensor(robot_cfg["force_upper"], device=self.device), self.dof_idx, ) + if "armature" in robot_cfg and hasattr(self.robot, "set_dofs_armature"): + self.robot.set_dofs_armature(torch.tensor(robot_cfg["armature"], device=self.device), self.dof_idx) + if "damping" in robot_cfg and hasattr(self.robot, "set_dofs_damping"): + self.robot.set_dofs_damping(torch.tensor(robot_cfg["damping"], device=self.device), self.dof_idx) + if "frictionloss" in robot_cfg and hasattr(self.robot, "set_dofs_frictionloss"): + self.robot.set_dofs_frictionloss(torch.tensor(robot_cfg["frictionloss"], device=self.device), self.dof_idx) self.default_qpos = torch.tensor(robot_cfg["default_qpos"], dtype=gs.tc_float, device=self.device) lower, upper = parse_joint_limits(robot_cfg["urdf_path"], self.joint_names) self.joint_lower = torch.tensor(lower, device=self.device, dtype=gs.tc_float) diff --git a/pyproject.toml b/pyproject.toml index 3c42064..da3526e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "genesis-ufactory" -version = "0.3.11" +version = "0.3.12" description = "UFACTORY robot models and Genesis simulation utilities" requires-python = ">=3.12" license = {text = "MIT"} diff --git a/scripts/gen_kinematics_params.py b/scripts/gen_kinematics_params.py index e578ab5..a3734b4 100644 --- a/scripts/gen_kinematics_params.py +++ b/scripts/gen_kinematics_params.py @@ -96,25 +96,28 @@ def _export(arm, args: argparse.Namespace) -> int: if not sn: print("[Failed] controller did not report a serial number") return 1 + print(f"robot_name : {robot_name}") + if not args.force and not has_per_unit_kinematics_calibration(sn, robot_name): + log_kinematics_sn_status(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 + 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, + kinematics_yaml_dir=args.output_dir, ) - 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 tcp_offset = read_tcp_offset(arm) world_offset = _read_world_offset(arm) diff --git a/tests/config/test_runtime_config.py b/tests/config/test_runtime_config.py index 335db39..f906a52 100644 --- a/tests/config/test_runtime_config.py +++ b/tests/config/test_runtime_config.py @@ -265,9 +265,9 @@ def test_default_g2_and_robotiq_hashes_are_unchanged(): 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" + assert g2_cfg.sha256 == "f2ef50f14da18f7b5ba7516f061506b32f7bd66d91198e5150739b5360e663d8" + assert robotiq_cfg.sha256 == "ac29036844145ffe1be1fcb728f97c3928f2f8c2ee15eddb58ae15f5d4ac9a3c" + assert bio_cfg.sha256 == "d636c5f31b5247e171dbc344462ca35342f2bf9b2e18c1599989005a86706267" 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 @@ -305,3 +305,48 @@ def test_allow_approx_motion_and_sim_rate_overrides_change_hash_and_validate(tmp 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) + + +@pytest.mark.parametrize("robot", ROBOTS) +def test_all_robots_define_compensated_and_raw_joint_dynamics(robot: str) -> None: + cfg = load_runtime_config(robot) + dof = cfg.robot.dof + assert cfg.arm.dynamics_profile == "compensated" + assert cfg.arm.dynamics is not None + assert len(cfg.arm.dynamics.kt_output_nm_per_a) == dof + assert all(val > 0.0 for val in cfg.arm.dynamics.kt_output_nm_per_a) + + comp = cfg.arm.resolve_joint_dynamics("compensated") + raw = cfg.arm.resolve_joint_dynamics("raw") + assert comp is not None and raw is not None + assert comp == cfg.arm.resolve_joint_dynamics() + assert comp.frictionloss == tuple(0.0 for _ in range(dof)) + assert any(val > 0.0 for val in raw.frictionloss) + assert comp.armature == raw.armature + assert comp.damping == raw.damping + + raw_cfg = load_runtime_config(robot, overrides={"arm.dynamics_profile": "raw"}) + assert raw_cfg.arm.dynamics_profile == "raw" + assert raw_cfg.arm.resolve_joint_dynamics() == raw + assert raw_cfg.sha256 != cfg.sha256 + + +def test_invalid_dynamics_profile_and_values_are_rejected(tmp_path: Path) -> None: + with pytest.raises(ConfigError, match="arm.dynamics_profile"): + load_runtime_config("xarm6", overrides={"arm.dynamics_profile": "unknown"}) + + bad_neg = tmp_path / "bad_dyn.yaml" + bad_neg.write_text( + "schema_version: 1\narm:\n dynamics:\n profiles:\n raw:\n frictionloss: [-1.0, 0, 0, 0, 0, 0]\n", + encoding="utf-8", + ) + with pytest.raises(ConfigError, match="non-negative"): + load_runtime_config("xarm6", config_path=bad_neg) + + bad_dr = tmp_path / "bad_dr.yaml" + bad_dr.write_text( + "schema_version: 1\narm:\n dynamics:\n domain_randomization:\n damping_rel_range: [1.5, 0.5]\n", + encoding="utf-8", + ) + with pytest.raises(ConfigError, match="0 < low <= high"): + load_runtime_config("xarm6", config_path=bad_dr) diff --git a/tests/dynamics/test_dynamics_calibration.py b/tests/dynamics/test_dynamics_calibration.py new file mode 100644 index 0000000..09bd72b --- /dev/null +++ b/tests/dynamics/test_dynamics_calibration.py @@ -0,0 +1,127 @@ +"""Unit tests for per-unit serial-bound dynamics calibration and Genesis injection.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest +import yaml + +from ufactory.dynamics import ( + apply_arm_joint_dynamics, + apply_dynamics_calibration, + load_dynamics_calibration, + resolve_arm_joint_dynamics, +) +from ufactory.robots.runtime import get_robot_runtime_profile + + +class _FakeRobot: + def __init__(self) -> None: + self.calls: dict[str, tuple[list[float], list[int]]] = {} + + def set_dofs_armature(self, values, dof_idx) -> None: + self.calls["armature"] = (np.asarray(values, dtype=float).tolist(), list(dof_idx)) + + def set_dofs_damping(self, values, dof_idx) -> None: + self.calls["damping"] = (np.asarray(values, dtype=float).tolist(), list(dof_idx)) + + def set_dofs_frictionloss(self, values, dof_idx) -> None: + self.calls["frictionloss"] = (np.asarray(values, dtype=float).tolist(), list(dof_idx)) + + +def _write_xarm7_calib(path: Path, *, sn: str = "XS130510D43A04", include_armature: bool = False) -> Path: + joints = {} + for idx in range(1, 8): + entry = {"damping": float(idx) * 1.5, "frictionloss": float(idx) * 0.5} + if include_armature: + entry["armature"] = float(idx) * 0.1 + joints[f"joint{idx}"] = entry + payload = { + "schema_version": 1, + "robot_key": "xarm7_1305", + "serial_number": sn, + "source": "unit_test", + "temperatures_c_ref": [30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0], + "joints": joints, + } + path.write_text(yaml.safe_dump(payload, sort_keys=False), encoding="utf-8") + return path + + +def test_load_and_apply_dynamics_calibration_orthogonal_to_profiles(tmp_path: Path) -> None: + calib_path = _write_xarm7_calib(tmp_path / "xarm7_calib.yaml") + calib = load_dynamics_calibration(calib_path, robot_key="xarm7", serial_number="XS130510D43A04") + assert calib.robot_key == "xarm7_1305" + assert calib.serial_number == "XS130510D43A04" + assert len(calib.sha256) == 64 + + runtime = get_robot_runtime_profile("xarm7") + base_comp = runtime.arm.resolve_joint_dynamics("compensated") + base_raw = runtime.arm.resolve_joint_dynamics("raw") + assert base_comp is not None and base_raw is not None + + # Under compensated: damping overridden, armature stays nominal, frictionloss stays 0.0 + comp_applied = apply_dynamics_calibration(base_comp, calib, profile_name="compensated") + assert comp_applied.armature == base_comp.armature + assert comp_applied.damping == pytest.approx((1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5)) + assert comp_applied.frictionloss == (0.0,) * 7 + + # Under raw: both damping and frictionloss are overridden + raw_applied = apply_dynamics_calibration(base_raw, calib, profile_name="raw") + assert raw_applied.armature == base_raw.armature + assert raw_applied.damping == pytest.approx((1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5)) + assert raw_applied.frictionloss == pytest.approx((0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5)) + + +def test_dynamics_calibration_rejects_mismatched_serial_and_robot(tmp_path: Path) -> None: + calib_path = _write_xarm7_calib(tmp_path / "xarm7_calib.yaml", sn="XS130510D43A04") + with pytest.raises(ValueError, match="serial_number mismatch"): + load_dynamics_calibration(calib_path, robot_key="xarm7", serial_number="XS130502F56A0C") + + with pytest.raises(ValueError, match="robot_key mismatch"): + load_dynamics_calibration(calib_path, robot_key="xarm6") + + loaded = load_dynamics_calibration(calib_path, robot_key="xarm7") + loaded.validate_serial("XS130510D43A04") + with pytest.raises(ValueError, match="serial_number mismatch"): + loaded.validate_serial("XS130502F56A0C") + + +def test_dynamics_calibration_rejects_short_serial_and_bad_values(tmp_path: Path) -> None: + short_sn = _write_xarm7_calib(tmp_path / "short.yaml", sn="D43A04") + with pytest.raises(ValueError, match="complete hardware serial number"): + load_dynamics_calibration(short_sn, robot_key="xarm7") + + bad_neg = tmp_path / "neg.yaml" + data = yaml.safe_load(_write_xarm7_calib(tmp_path / "ok.yaml").read_text(encoding="utf-8")) + data["joints"]["joint1"]["damping"] = -0.1 + bad_neg.write_text(yaml.safe_dump(data), encoding="utf-8") + with pytest.raises(ValueError, match="non-negative"): + load_dynamics_calibration(bad_neg, robot_key="xarm7") + + +def test_apply_arm_joint_dynamics_injects_all_three_arrays(tmp_path: Path) -> None: + calib_path = _write_xarm7_calib(tmp_path / "xarm7_full.yaml", include_armature=True) + calib = load_dynamics_calibration(calib_path, robot_key="xarm7") + runtime = get_robot_runtime_profile("xarm7") + fake = _FakeRobot() + dof_idx = list(range(7)) + + applied = apply_arm_joint_dynamics(fake, dof_idx, runtime, dynamics_profile="raw", dynamics_calibration=calib) + assert applied is not None + assert fake.calls["armature"][0] == pytest.approx([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]) + assert fake.calls["damping"][0] == pytest.approx([1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5]) + assert fake.calls["frictionloss"][0] == pytest.approx([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]) + + # zero_joint_frictionloss override forces frictionloss to zero even on raw + name, vals = resolve_arm_joint_dynamics( + runtime, + dynamics_profile="raw", + dynamics_calibration=calib, + zero_joint_frictionloss=True, + ) + assert name == "raw" + assert vals is not None + assert vals.frictionloss == (0.0,) * 7 diff --git a/tests/kinematics/test_controller_fk.py b/tests/kinematics/test_controller_fk.py index cb21524..d65a55a 100644 --- a/tests/kinematics/test_controller_fk.py +++ b/tests/kinematics/test_controller_fk.py @@ -119,12 +119,21 @@ def test_matrix_rpy_round_trips_including_gimbal_lock(rpy): 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") + """Controller double: SDK FK returns the TCP pose (mm, rad) of a synthetic arm.""" + + def __init__( + self, + *, + robot: str = "xarm6", + sn: str = "XI130505TEST01", + world_offset=(0.0,) * 6, + fail=False, + ): + profile = get_robot_profile(robot) + self.axis = profile.dof + self.device_type = profile.controller_device_type + self._sn = sn + chain = _chain(robot) 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) @@ -132,7 +141,7 @@ def __init__(self, *, world_offset=(0.0,) * 6, fail=False): self.calls = 0 def get_robot_sn(self): - return 0, "XI130505TEST01" + return 0, self._sn def get_forward_kinematics(self, angles, input_is_radian=None, return_is_radian=None): assert input_is_radian and return_is_radian @@ -189,3 +198,88 @@ def test_export_refuses_a_world_offset_and_writes_nothing(tmp_path, capsys): assert script._export(arm, args) == 1 assert "world_offset" in capsys.readouterr().out assert arm.calls == 0 and not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize( + ("robot", "sn", "expected_code"), + [ + ("lite6", "LI100307TEST01", "1003"), + ("lite6", "LI100501TEST01", "1005"), + ("xarm6", "XI130312TEST01", "1303"), + ], +) +@pytest.mark.parametrize("kinematics_suffix", [None, "custom"]) +def test_export_skips_low_batch_sn_without_force( + tmp_path, monkeypatch, capsys, robot, sn, expected_code, kinematics_suffix +): + script = _script() + monkeypatch.setattr(script, "_read_world_offset", lambda arm: np.asarray(arm.world_offset)) + arm = FakeArm(robot=robot, sn=sn) + args = argparse.Namespace(kinematics_suffix=kinematics_suffix, output_dir=str(tmp_path), force=False) + + assert script._export(arm, args) == 2 + out = capsys.readouterr().out + assert "[Skipped]" in out + assert expected_code in out + assert "loading it anyway" not in out + assert arm.calls == 0 and not list(tmp_path.iterdir()) + + +def test_export_skips_low_batch_sn_even_when_existing_yaml_present(tmp_path, monkeypatch, capsys): + script = _script() + monkeypatch.setattr(script, "_read_world_offset", lambda arm: np.asarray(arm.world_offset)) + existing = tmp_path / "lite6_kinematics_TEST01.yaml" + sentinel = "# keep existing calibration\n" + existing.write_text(sentinel, encoding="utf-8") + arm = FakeArm(robot="lite6", sn="LI100307TEST01") + args = argparse.Namespace(kinematics_suffix=None, output_dir=str(tmp_path), force=False) + + assert script._export(arm, args) == 2 + out = capsys.readouterr().out + assert "[Skipped]" in out + assert "loading it anyway" not in out + assert arm.calls == 0 + assert existing.read_text(encoding="utf-8") == sentinel + + +@pytest.mark.parametrize( + ("robot", "sn"), + [ + ("lite6", "LI100307TEST01"), + ("xarm6", "XI130312TEST01"), + ], +) +def test_export_allows_low_batch_sn_with_force(tmp_path, monkeypatch, capsys, robot, sn): + script = _script() + monkeypatch.setattr(script, "_read_world_offset", lambda arm: np.asarray(arm.world_offset)) + arm = FakeArm(robot=robot, sn=sn) + args = argparse.Namespace(kinematics_suffix=None, output_dir=str(tmp_path), force=True) + + assert script._export(arm, args) == 0 + out = capsys.readouterr().out + assert "SN rule overridden" in out + profile = get_robot_profile(robot) + path = tmp_path / f"{profile.kinematics_prefix}_kinematics_TEST01.yaml" + calibration = load_kinematics_calibration(str(path), robot_key=robot, serial_number=sn) + assert calibration.serial_number == sn + + +@pytest.mark.parametrize( + ("robot", "sn"), + [ + ("lite6", "LI100609TEST01"), + ("xarm6", "XI130412TEST01"), + ("uf850", "FX851005TEST01"), + ], +) +def test_export_accepts_threshold_and_uf850_without_force(tmp_path, monkeypatch, robot, sn): + script = _script() + monkeypatch.setattr(script, "_read_world_offset", lambda arm: np.asarray(arm.world_offset)) + arm = FakeArm(robot=robot, sn=sn) + args = argparse.Namespace(kinematics_suffix=None, output_dir=str(tmp_path), force=False) + + assert script._export(arm, args) == 0 + profile = get_robot_profile(robot) + path = tmp_path / f"{profile.kinematics_prefix}_kinematics_TEST01.yaml" + calibration = load_kinematics_calibration(str(path), robot_key=robot, serial_number=sn) + assert calibration.serial_number == sn diff --git a/tests/robots/test_asset_integrity.py b/tests/robots/test_asset_integrity.py index 52bd56d..848cc65 100644 --- a/tests/robots/test_asset_integrity.py +++ b/tests/robots/test_asset_integrity.py @@ -1096,6 +1096,248 @@ def test_uf850_base_uses_solidworks_inertial_parameters() -> None: np.testing.assert_allclose(eig, expected_principal, rtol=0.0, atol=1e-11) +def test_xarm_1305_moving_links_use_uj_br_2403_inertials() -> None: + """xArm5/6/7 STL and GLB URDFs use official xarm_ros2 UJ_BR_2403 moving-link inertials (>= 1305).""" + expected_moving_mass = {"xarm5": 8.5270, "xarm6": 9.6710, "xarm7": 11.7844} + expected_links: dict[str, dict[str, tuple[float, tuple[float, float, float], dict[str, float]]]] = { + "xarm5": { + "link1": ( + 2.527, + (-0.000164, 0.03594, -0.0065), + { + "ixx": 0.005692, + "ixy": -2.375e-05, + "ixz": 3.47e-07, + "iyy": 0.003851, + "iyz": -0.000607, + "izz": 0.004606, + }, + ), + "link2": ( + 2.242, + (0.04084, -0.2403, 0.03254), + { + "ixx": 0.023064, + "ixy": 0.004092, + "ixz": 0.0005122, + "iyy": 0.0059781, + "iyz": -0.003718, + "izz": 0.021902, + }, + ), + "link3": ( + 2.24, + (0.072, 0.2363, 0.00083), + { + "ixx": 0.035477, + "ixy": -0.0030302, + "ixz": 0.0010594, + "iyy": 0.005848, + "iyz": 0.00612, + "izz": 0.033753, + }, + ), + "link4": ( + 1.345, + (0.06824, 0.03342, 0.00264), + { + "ixx": 0.001624, + "ixy": -0.0003378, + "ixz": 0.00024388, + "iyy": 0.00173, + "iyz": 0.00011526, + "izz": 0.0022881, + }, + ), + "link5": ( + 0.173, + (0.0008, -0.00359, -0.01326), + {"ixx": 0.0001119, "ixy": 0.0, "ixz": 0.0, "iyy": 8.951e-05, "iyz": -2.94e-06, "izz": 0.00017916}, + ), + }, + "xarm6": { + "link1": ( + 2.531, + (-0.00017, 0.03575, -0.00647), + {"ixx": 0.005645, "ixy": -2.2e-05, "ixz": 0.0, "iyy": 0.0038, "iyz": -0.000597, "izz": 0.004567}, + ), + "link2": ( + 2.242, + (0.04084, -0.2403, 0.0324), + {"ixx": 0.023006, "ixy": 0.00408, "ixz": 0.000515, "iyy": 0.005974, "iyz": -0.003713, "izz": 0.02183}, + ), + "link3": ( + 2.019, + (0.0714, 0.1268, 0.0109), + {"ixx": 0.007602, "ixy": -0.001578, "ixz": 0.000916, "iyy": 0.004263, "iyz": 0.0021, "izz": 0.00708}, + ), + "link4": ( + 1.361, + (0.000185, 0.01466, -0.02197), + {"ixx": 0.004888, "ixy": -1.2e-05, "ixz": -4e-06, "iyy": 0.004184, "iyz": 7e-06, "izz": 0.001731}, + ), + "link5": ( + 1.345, + (0.0682, 0.03342, 0.00263), + {"ixx": 0.001622, "ixy": -0.000335, "ixz": 0.000246, "iyy": 0.00171, "iyz": 0.000114, "izz": 0.002286}, + ), + "link6": ( + 0.173, + (0.00084, -0.00359, -0.01326), + {"ixx": 0.000112, "ixy": 0.0, "ixz": 0.0, "iyy": 9e-05, "iyz": -3e-06, "izz": 0.00018}, + ), + }, + "xarm7": { + "link1": ( + 2.507, + (0.0002, 0.03578, -0.006443), + {"ixx": 0.0056406, "ixy": 3e-05, "ixz": -1.7e-06, "iyy": 0.003777, "iyz": -0.0005894, "izz": 0.0045654}, + ), + "link2": ( + 2.2812, + (-0.00022, -0.13322, 0.02018), + { + "ixx": 0.014141, + "ixy": 1.46e-05, + "ixz": -1.97e-05, + "iyy": 0.0054715, + "iyz": -0.004761, + "izz": 0.011189, + }, + ), + "link3": ( + 2.0, + (0.0464, -0.022, -0.00804), + { + "ixx": 0.004105, + "ixy": 0.0003006, + "ixz": -0.00073, + "iyy": 0.0034706, + "iyz": 0.0003843, + "izz": 0.0038088, + }, + ), + "link4": ( + 2.1212, + (0.0703, -0.12318, 0.0131), + { + "ixx": 0.008728, + "ixy": 0.001837, + "ixz": 0.0010806, + "iyy": 0.0048968, + "iyz": -0.0025029, + "izz": 0.0080239, + }, + ), + "link5": ( + 1.36, + (0.000192, 0.014597, -0.02198), + { + "ixx": 0.0048876, + "ixy": -1.13e-05, + "ixz": -3.8e-06, + "iyy": 0.0041832, + "iyz": 7.5e-06, + "izz": 0.001731, + }, + ), + "link6": ( + 1.345, + (0.06824, 0.033418, 0.00264), + { + "ixx": 0.001624, + "ixy": -0.0003378, + "ixz": 0.0002439, + "iyy": 0.0017304, + "iyz": 0.0001153, + "izz": 0.002288, + }, + ), + "link7": ( + 0.17, + (0.0, -0.0036, -0.01325), + {"ixx": 0.00011, "ixy": 0.0, "ixz": 0.0, "iyy": 8.95e-05, "iyz": -2.9e-06, "izz": 0.00018}, + ), + }, + } + + for robot_dir, links_spec in expected_links.items(): + variant_blocks: list[dict[str, str]] = [] + for variant in _XARM_URDF_VARIANTS: + urdf = _URDF_ROOT / "robots" / robot_dir / variant.format(robot_dir) + root = ET.parse(urdf).getroot() + blocks: dict[str, str] = {} + moving_mass = 0.0 + for link_name, (exp_mass, exp_com, exp_inertia) in links_spec.items(): + inertial = root.find(f"./link[@name='{link_name}']/inertial") + assert inertial is not None, (_rel(urdf), link_name) + mass = float(inertial.find("mass").attrib["value"]) + assert mass == pytest.approx(exp_mass, rel=0.0, abs=1e-12), (_rel(urdf), link_name) + moving_mass += mass + + 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(exp_com, rel=0.0, abs=1e-12), (_rel(urdf), link_name) + assert rpy == pytest.approx((0.0, 0.0, 0.0), rel=0.0, abs=1e-12), (_rel(urdf), link_name) + + inertia = {k: float(v) for k, v in inertial.find("inertia").attrib.items()} + for key, expected_val in exp_inertia.items(): + assert inertia[key] == pytest.approx(expected_val, rel=0.0, abs=1e-12), (_rel(urdf), link_name, key) + + tensor = np.array( + [ + [inertia["ixx"], inertia["ixy"], inertia["ixz"]], + [inertia["ixy"], inertia["iyy"], inertia["iyz"]], + [inertia["ixz"], inertia["iyz"], inertia["izz"]], + ], + dtype=np.float64, + ) + eig = np.linalg.eigvalsh(tensor) + assert eig.min() > 0.0, (_rel(urdf), link_name, eig) + assert eig[0] + eig[1] > eig[2], (_rel(urdf), link_name, eig) + blocks[link_name] = ET.tostring(inertial, encoding="unicode").strip() + + assert moving_mass == pytest.approx(expected_moving_mass[robot_dir], rel=0.0, abs=1e-12), _rel(urdf) + variant_blocks.append(blocks) + assert variant_blocks[0] == variant_blocks[1], robot_dir + + +def test_lite6_stl_and_glb_urdfs_share_identical_inertials() -> None: + """Lite 6 STL and GLB URDFs share identical physical inertials on link_base and link1..link6.""" + stl_root = ET.parse(_URDF_ROOT / "robots" / "lite6" / "lite6.urdf").getroot() + glb_root = ET.parse(_URDF_ROOT / "robots" / "lite6" / "lite6_visual.glb.urdf").getroot() + + for link_name in ("link_base", *(f"link{i}" for i in range(1, 7))): + stl_in = stl_root.find(f"./link[@name='{link_name}']/inertial") + glb_in = glb_root.find(f"./link[@name='{link_name}']/inertial") + assert stl_in is not None and glb_in is not None, link_name + + assert float(glb_in.find("mass").attrib["value"]) == pytest.approx( + float(stl_in.find("mass").attrib["value"]), rel=0.0, abs=1e-12 + ), link_name + stl_xyz = tuple(float(v) for v in stl_in.find("origin").attrib["xyz"].split()) + glb_xyz = tuple(float(v) for v in glb_in.find("origin").attrib["xyz"].split()) + assert glb_xyz == pytest.approx(stl_xyz, rel=0.0, abs=1e-12), link_name + + stl_i = {k: float(v) for k, v in stl_in.find("inertia").attrib.items()} + glb_i = {k: float(v) for k, v in glb_in.find("inertia").attrib.items()} + for comp in ("ixx", "ixy", "ixz", "iyy", "iyz", "izz"): + assert glb_i[comp] == pytest.approx(stl_i[comp], rel=0.0, abs=1e-12), (link_name, comp) + + tensor = np.array( + [ + [glb_i["ixx"], glb_i["ixy"], glb_i["ixz"]], + [glb_i["ixy"], glb_i["iyy"], glb_i["iyz"]], + [glb_i["ixz"], glb_i["iyz"], glb_i["izz"]], + ], + dtype=np.float64, + ) + eig = np.linalg.eigvalsh(tensor) + assert eig.min() > 0.0, (link_name, eig) + assert eig[0] + eig[1] > eig[2], (link_name, eig) + + 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. diff --git a/tests/simulation/test_bio_g2_grasp_geometry.py b/tests/simulation/test_bio_g2_grasp_geometry.py index 31da940..f7f19ae 100644 --- a/tests/simulation/test_bio_g2_grasp_geometry.py +++ b/tests/simulation/test_bio_g2_grasp_geometry.py @@ -29,7 +29,7 @@ def test_gravity_matches_potential_gradient_including_fixed_gripper(q): _, minus = model.compute(positions | {name: positions[name] - 1e-6}) assert torque[idx] == pytest.approx((plus - minus) / 2e-6, abs=1e-7) assert abs(torque[1]) > 1 - assert sum(mass for mass, _ in model.inertials.values()) == pytest.approx(12.930051) + assert sum(mass for mass, _ in model.inertials.values()) == pytest.approx(13.249411) assert model.inertials["bio_gripper_g2_base_link"][0] > 0.7 diff --git a/ufactory/config/__init__.py b/ufactory/config/__init__.py index d066e58..b8e592f 100644 --- a/ufactory/config/__init__.py +++ b/ufactory/config/__init__.py @@ -6,12 +6,23 @@ RepositoryAssetStore, discover_asset_store, ) -from ufactory.config.loader import ConfigError, dump_runtime_config, load_runtime_config, runtime_config_dict +from ufactory.config.loader import ( + ConfigError, + dump_runtime_config, + load_arm_dynamics_spec, + load_runtime_config, + runtime_config_dict, +) from ufactory.config.models import ( ArmControlProfile, + ArmDynamicsSpec, + DYNAMICS_PROFILE_COMPENSATED, + DYNAMICS_PROFILE_RAW, + DynamicsDomainRandomization, GraspObjectSpec, GripperProfile, G2SimulationConfig, + JointDynamicsValues, MotionConfig, ROBOTIQ_2F_140_PHYSICS_PROFILE, ROBOTIQ_2F_85_PHYSICS_PROFILE, @@ -20,18 +31,24 @@ RobotiqSimulationConfig, SimulationConfig, TaskProfile, + VALID_DYNAMICS_PROFILES, resolve_pick_place_object_spec, resolve_manipulation_object_spec, ) __all__ = [ "ArmControlProfile", + "ArmDynamicsSpec", "AssetLayoutError", "AssetStore", "ConfigError", + "DYNAMICS_PROFILE_COMPENSATED", + "DYNAMICS_PROFILE_RAW", + "DynamicsDomainRandomization", "GripperProfile", "G2SimulationConfig", "GraspObjectSpec", + "JointDynamicsValues", "MotionConfig", "ROBOTIQ_2F_140_PHYSICS_PROFILE", "ROBOTIQ_2F_85_PHYSICS_PROFILE", @@ -41,8 +58,10 @@ "RobotiqSimulationConfig", "SimulationConfig", "TaskProfile", + "VALID_DYNAMICS_PROFILES", "discover_asset_store", "dump_runtime_config", + "load_arm_dynamics_spec", "load_runtime_config", "runtime_config_dict", "resolve_pick_place_object_spec", diff --git a/ufactory/config/loader.py b/ufactory/config/loader.py index 7495d13..fc471a9 100644 --- a/ufactory/config/loader.py +++ b/ufactory/config/loader.py @@ -15,15 +15,20 @@ from ufactory.config.assets import RepositoryAssetStore from ufactory.config.models import ( ArmControlProfile, + ArmDynamicsSpec, + DYNAMICS_PROFILE_COMPENSATED, + DynamicsDomainRandomization, G2_NOSLIP_ITERATIONS, GripperProfile, G2SimulationConfig, + JointDynamicsValues, MotionConfig, ResolvedRuntimeConfig, RobotiqSimulationConfig, RobotSpec, SimulationConfig, TaskProfile, + VALID_DYNAMICS_PROFILES, ) from ufactory.robots.assembly import AssemblyError, validate_assembly, validate_robot_urdf from ufactory.robots.registry import get_profile_key_for_robot_name @@ -125,6 +130,79 @@ def config_sha256(payload: dict[str, Any]) -> str: return hashlib.sha256(encoded).hexdigest() +def _parse_joint_dynamics_values(raw: Any, *, field: str, dof: int) -> JointDynamicsValues: + if not isinstance(raw, Mapping): + raise ConfigError(f"{field} must be a mapping") + armature = _tuple_floats(raw["armature"], field=f"{field}.armature", size=dof) + damping = _tuple_floats(raw["damping"], field=f"{field}.damping", size=dof) + frictionloss = _tuple_floats(raw["frictionloss"], field=f"{field}.frictionloss", size=dof) + for name, vals in (("armature", armature), ("damping", damping), ("frictionloss", frictionloss)): + if any(v < 0.0 for v in vals): + raise ConfigError(f"{field}.{name} values must be non-negative") + return JointDynamicsValues(armature=armature, damping=damping, frictionloss=frictionloss) + + +def _parse_arm_dynamics(raw: Any, *, dof: int) -> ArmDynamicsSpec: + if not isinstance(raw, Mapping): + raise ConfigError("arm.dynamics must be a mapping") + kt = _tuple_floats(raw["kt_output_nm_per_a"], field="arm.dynamics.kt_output_nm_per_a", size=dof) + if any(v <= 0.0 for v in kt): + raise ConfigError("arm.dynamics.kt_output_nm_per_a values must be positive") + profiles_raw = raw["profiles"] + if not isinstance(profiles_raw, Mapping): + raise ConfigError("arm.dynamics.profiles must be a mapping") + compensated = _parse_joint_dynamics_values( + profiles_raw["compensated"], field="arm.dynamics.profiles.compensated", dof=dof + ) + raw_profile = _parse_joint_dynamics_values(profiles_raw["raw"], field="arm.dynamics.profiles.raw", dof=dof) + dr_raw = raw["domain_randomization"] + if not isinstance(dr_raw, Mapping): + raise ConfigError("arm.dynamics.domain_randomization must be a mapping") + ranges: dict[str, tuple[float, float]] = {} + for key in ("armature_rel_range", "damping_rel_range", "frictionloss_rel_range"): + pair = _tuple_floats(dr_raw[key], field=f"arm.dynamics.domain_randomization.{key}", size=2) + if pair[0] <= 0.0 or pair[0] > pair[1]: + raise ConfigError(f"arm.dynamics.domain_randomization.{key} must satisfy 0 < low <= high") + ranges[key] = (pair[0], pair[1]) + dr = DynamicsDomainRandomization( + armature_rel_range=ranges["armature_rel_range"], + damping_rel_range=ranges["damping_rel_range"], + frictionloss_rel_range=ranges["frictionloss_rel_range"], + ) + return ArmDynamicsSpec( + kt_output_nm_per_a=kt, + compensated=compensated, + raw=raw_profile, + domain_randomization=dr, + ) + + +def load_arm_dynamics_spec( + robot_key: str, + *, + asset_store: RepositoryAssetStore | None = None, +) -> tuple[str, ArmDynamicsSpec] | None: + """Load the model-level default dynamics profile name and spec from robot YAML.""" + store = asset_store or RepositoryAssetStore.discover() + try: + canonical = get_profile_key_for_robot_name(robot_key) + except ValueError: + return None + rel = f"assets/configs/runtime/robots/{canonical}.yaml" + yaml_path = store.root / rel + if not yaml_path.is_file(): + return None + data = _read_yaml(yaml_path) + dof = int(data["robot"]["dof"]) + arm_data = data["arm"] + if "dynamics" not in arm_data: + return None + profile_name = str(arm_data.get("dynamics_profile", DYNAMICS_PROFILE_COMPENSATED)) + if profile_name not in VALID_DYNAMICS_PROFILES: + raise ConfigError(f"{yaml_path}: arm.dynamics_profile must be one of {VALID_DYNAMICS_PROFILES}") + return profile_name, _parse_arm_dynamics(arm_data["dynamics"], dof=dof) + + def _build_resolved(data: dict[str, Any], sources: tuple[str, ...]) -> ResolvedRuntimeConfig: _validate_finite(data) robot_data = data["robot"] @@ -144,6 +222,10 @@ def _build_resolved(data: dict[str, Any], sources: tuple[str, ...]) -> ResolvedR ), ) arm_data = data["arm"] + raw_dyn_profile = arm_data.get("dynamics_profile", DYNAMICS_PROFILE_COMPENSATED) + if not isinstance(raw_dyn_profile, str) or raw_dyn_profile not in VALID_DYNAMICS_PROFILES: + raise ConfigError(f"arm.dynamics_profile must be one of {VALID_DYNAMICS_PROFILES}, got {raw_dyn_profile!r}") + arm_dynamics = _parse_arm_dynamics(arm_data["dynamics"], dof=dof) if "dynamics" in arm_data else None arm = ArmControlProfile( default_qpos_rad=_tuple_floats(arm_data["default_qpos_rad"], field="arm.default_qpos_rad", size=dof), kp=_tuple_floats(arm_data["kp"], field="arm.kp", size=dof), @@ -151,6 +233,8 @@ def _build_resolved(data: dict[str, Any], sources: tuple[str, ...]) -> ResolvedR force_lower_nm=_tuple_floats(arm_data["force_lower_nm"], field="arm.force_lower_nm", size=dof), force_upper_nm=_tuple_floats(arm_data["force_upper_nm"], field="arm.force_upper_nm", size=dof), effort_limits_nm=_tuple_floats(arm_data["effort_limits_nm"], field="arm.effort_limits_nm", size=dof), + dynamics_profile=raw_dyn_profile, + dynamics=arm_dynamics, ) if any(lo >= hi for lo, hi in zip(arm.force_lower_nm, arm.force_upper_nm, strict=True)): raise ConfigError("each arm force lower bound must be below its upper bound") diff --git a/ufactory/config/models.py b/ufactory/config/models.py index c712934..9b18651 100644 --- a/ufactory/config/models.py +++ b/ufactory/config/models.py @@ -12,6 +12,9 @@ FloatTuple = tuple[float, ...] TcpOffsetTuple = tuple[float, float, float, float, float, float] +DYNAMICS_PROFILE_COMPENSATED = "compensated" +DYNAMICS_PROFILE_RAW = "raw" +VALID_DYNAMICS_PROFILES: tuple[str, str] = (DYNAMICS_PROFILE_COMPENSATED, DYNAMICS_PROFILE_RAW) 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" @@ -59,6 +62,69 @@ def __post_init__(self) -> None: raise ValueError("each environment contact pair must contain two distinct names") +@dataclass(frozen=True) +class JointDynamicsValues: + """Per-joint passive dynamics applied to Genesis arm DOFs.""" + + armature: FloatTuple + damping: FloatTuple + frictionloss: FloatTuple + + def validate_dof(self, dof: int, *, prefix: str = "arm.dynamics") -> None: + for name in ("armature", "damping", "frictionloss"): + values = getattr(self, name) + if len(values) != dof: + raise ValueError(f"{prefix}.{name} expected {dof} values") + if any(not math.isfinite(val) or val < 0.0 for val in values): + raise ValueError(f"{prefix}.{name} values must be finite and non-negative") + + +@dataclass(frozen=True) +class DynamicsDomainRandomization: + """Recommended relative scale ranges for cross-unit RL domain randomization.""" + + armature_rel_range: tuple[float, float] + damping_rel_range: tuple[float, float] + frictionloss_rel_range: tuple[float, float] + + def __post_init__(self) -> None: + for name in ("armature_rel_range", "damping_rel_range", "frictionloss_rel_range"): + pair = getattr(self, name) + if len(pair) != 2: + raise ValueError(f"arm.dynamics.domain_randomization.{name} expected 2 values") + lo, hi = float(pair[0]), float(pair[1]) + if not (math.isfinite(lo) and math.isfinite(hi)) or lo <= 0.0 or lo > hi: + raise ValueError( + f"arm.dynamics.domain_randomization.{name} must satisfy 0 < low <= high, got ({lo}, {hi})" + ) + object.__setattr__(self, name, (lo, hi)) + + +@dataclass(frozen=True) +class ArmDynamicsSpec: + """Model-level nominal joint dynamics profiles and torque constants.""" + + kt_output_nm_per_a: FloatTuple + compensated: JointDynamicsValues + raw: JointDynamicsValues + domain_randomization: DynamicsDomainRandomization + + def validate_dof(self, dof: int) -> None: + if len(self.kt_output_nm_per_a) != dof: + raise ValueError(f"arm.dynamics.kt_output_nm_per_a expected {dof} values") + if any(not math.isfinite(val) or val <= 0.0 for val in self.kt_output_nm_per_a): + raise ValueError("arm.dynamics.kt_output_nm_per_a values must be finite and positive") + self.compensated.validate_dof(dof, prefix="arm.dynamics.profiles.compensated") + self.raw.validate_dof(dof, prefix="arm.dynamics.profiles.raw") + + def profile(self, name: str) -> JointDynamicsValues: + if name == DYNAMICS_PROFILE_COMPENSATED: + return self.compensated + if name == DYNAMICS_PROFILE_RAW: + return self.raw + raise ValueError(f"unknown dynamics_profile: {name!r}; expected one of {VALID_DYNAMICS_PROFILES}") + + @dataclass(frozen=True) class ArmControlProfile: """Joint-space controller defaults, with explicit SI-unit field names.""" @@ -69,6 +135,20 @@ class ArmControlProfile: force_lower_nm: FloatTuple force_upper_nm: FloatTuple effort_limits_nm: FloatTuple + dynamics_profile: str = DYNAMICS_PROFILE_COMPENSATED + dynamics: ArmDynamicsSpec | None = None + + def __post_init__(self) -> None: + if self.dynamics_profile not in VALID_DYNAMICS_PROFILES: + raise ValueError( + f"arm.dynamics_profile must be one of {VALID_DYNAMICS_PROFILES}, got {self.dynamics_profile!r}" + ) + + def resolve_joint_dynamics(self, profile_name: str | None = None) -> JointDynamicsValues | None: + if self.dynamics is None: + return None + chosen = self.dynamics_profile if profile_name is None else str(profile_name) + return self.dynamics.profile(chosen) def validate_dof(self, dof: int) -> None: for name in ( @@ -81,6 +161,8 @@ def validate_dof(self, dof: int) -> None: ): if len(getattr(self, name)) != dof: raise ValueError(f"arm.{name} expected {dof} values") + if self.dynamics is not None: + self.dynamics.validate_dof(dof) @dataclass(frozen=True) diff --git a/ufactory/dynamics/__init__.py b/ufactory/dynamics/__init__.py index 8bfea67..0ae433f 100644 --- a/ufactory/dynamics/__init__.py +++ b/ufactory/dynamics/__init__.py @@ -4,6 +4,14 @@ implementation modules and are intentionally not bulk re-exported. """ +from ufactory.dynamics.calibration import ( + DynamicsCalibration, + JointDynamicsOverride, + apply_arm_joint_dynamics, + apply_dynamics_calibration, + load_dynamics_calibration, + resolve_arm_joint_dynamics, +) from ufactory.dynamics.report import ( REPORT_SCHEMA_VERSION, DynamicsRunConfig, @@ -15,6 +23,8 @@ ) __all__ = [ + "DynamicsCalibration", + "JointDynamicsOverride", "REPORT_SCHEMA_VERSION", "DynamicsRunConfig", "DynamicsSample", @@ -22,4 +32,8 @@ "SafePose", "UrdfDynamicsIssue", "ValidationStatus", + "apply_arm_joint_dynamics", + "apply_dynamics_calibration", + "load_dynamics_calibration", + "resolve_arm_joint_dynamics", ] diff --git a/ufactory/dynamics/calibration.py b/ufactory/dynamics/calibration.py new file mode 100644 index 0000000..2ac538f --- /dev/null +++ b/ufactory/dynamics/calibration.py @@ -0,0 +1,267 @@ +"""Per-unit serial-bound joint dynamics calibration and unified Genesis injection. + +Mirrors :mod:`ufactory.kinematics.calibration` so real-hardware users who swap +between physical units of the same model can optionally layer unit-specific +friction/damping (and optional armature) overrides on top of the model-level +nominal profiles in ``assets/configs/runtime/robots/*.yaml`` without risk of +silently applying a previous robot's calibration file. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import hashlib +import math +from pathlib import Path +from typing import Any + +import numpy as np +import yaml + +from ufactory.config.models import ( + DYNAMICS_PROFILE_COMPENSATED, + DYNAMICS_PROFILE_RAW, + JointDynamicsValues, + VALID_DYNAMICS_PROFILES, +) +from ufactory.robots.registry import get_profile_key_for_robot_name, get_robot_profile, joint_names + + +@dataclass(frozen=True) +class JointDynamicsOverride: + """Optional per-joint calibrated physical dynamics overrides.""" + + damping: float | None = None + frictionloss: float | None = None + armature: float | None = None + + def __post_init__(self) -> None: + for name in ("damping", "frictionloss", "armature"): + val = getattr(self, name) + if val is not None: + fval = float(val) + if not math.isfinite(fval) or fval < 0.0: + raise ValueError(f"joint dynamics calibration {name} must be finite and non-negative, got {val!r}") + object.__setattr__(self, name, fval) + + +@dataclass(frozen=True) +class DynamicsCalibration: + """Strictly validated, robot- and serial-number-bound dynamics calibration.""" + + robot_key: str + serial_number: str + joint_names: tuple[str, ...] + joints: Mapping[str, JointDynamicsOverride] + sha256: str + source_path: str | None = None + source: str | None = None + temperatures_c_ref: tuple[float, ...] | None = None + + def validate_serial(self, serial_number: str | None) -> None: + """Raise ValueError if ``serial_number`` is provided and does not match.""" + if serial_number is None: + return + actual = str(serial_number).strip() + if actual and actual != self.serial_number: + raise ValueError( + f"dynamics calibration serial_number mismatch: calibration is for {self.serial_number!r}, " + f"but connected robot reported {actual!r}" + ) + + +def _validate_non_negative_optional(raw: Mapping[str, Any], key: str, *, context: str) -> float | None: + if key not in raw or raw[key] is None: + return None + val = raw[key] + if isinstance(val, bool) or not isinstance(val, int | float): + raise ValueError(f"{context}.{key} must be numeric, got {val!r}") + fval = float(val) + if not math.isfinite(fval) or fval < 0.0: + raise ValueError(f"{context}.{key} must be finite and non-negative, got {val!r}") + return fval + + +def load_dynamics_calibration( + yaml_path: str | Path, + *, + robot_key: str, + serial_number: str | None = None, +) -> DynamicsCalibration: + """Load schema-v1 per-unit dynamics calibration with strict robot & SN checks.""" + path = Path(yaml_path).expanduser().resolve() + raw_bytes = path.read_bytes() + digest = hashlib.sha256(raw_bytes).hexdigest() + data = yaml.safe_load(raw_bytes.decode("utf-8")) + if not isinstance(data, Mapping): + raise ValueError(f"{path}: dynamics calibration root must be a mapping") + if data.get("schema_version") != 1: + raise ValueError(f"{path}: schema_version must be 1") + + allowed_root = {"schema_version", "robot_key", "serial_number", "joints", "source", "temperatures_c_ref"} + unknown_root = sorted(set(data.keys()) - allowed_root) + if unknown_root: + raise ValueError(f"{path}: unknown top-level field(s): {unknown_root}") + + expected_robot = get_profile_key_for_robot_name(robot_key) + file_robot_raw = data.get("robot_key") + if not isinstance(file_robot_raw, str) or not file_robot_raw.strip(): + raise ValueError(f"{path}: robot_key is required") + file_robot = get_profile_key_for_robot_name(file_robot_raw) + if file_robot != expected_robot: + raise ValueError(f"{path}: robot_key mismatch (file={file_robot!r}, expected={expected_robot!r})") + + file_serial_raw = data.get("serial_number") + if not isinstance(file_serial_raw, str) or len(file_serial_raw.strip()) < 8: + raise ValueError(f"{path}: serial_number must be a complete hardware serial number (len >= 8)") + file_serial = file_serial_raw.strip() + if serial_number is not None: + expected_serial = str(serial_number).strip() + if expected_serial and file_serial != expected_serial: + raise ValueError(f"{path}: serial_number mismatch (file={file_serial!r}, expected={expected_serial!r})") + + spec = get_robot_profile(expected_robot) + expected_joints = joint_names(spec) + raw_joints = data.get("joints") + if not isinstance(raw_joints, Mapping): + raise ValueError(f"{path}: joints must be a mapping") + missing = [name for name in expected_joints if name not in raw_joints] + extra = sorted(set(raw_joints.keys()) - set(expected_joints)) + if missing or extra: + raise ValueError(f"{path}: calibration joint set mismatch; missing={missing}, extra={extra}") + + parsed_joints: dict[str, JointDynamicsOverride] = {} + allowed_joint_fields = {"damping", "frictionloss", "armature"} + for jname in expected_joints: + entry = raw_joints[jname] + if not isinstance(entry, Mapping): + raise ValueError(f"{path}: joints.{jname} must be a mapping") + unknown_j = sorted(set(entry.keys()) - allowed_joint_fields) + if unknown_j: + raise ValueError(f"{path}: unknown field(s) in joints.{jname}: {unknown_j}") + parsed_joints[jname] = JointDynamicsOverride( + damping=_validate_non_negative_optional(entry, "damping", context=f"{path}: joints.{jname}"), + frictionloss=_validate_non_negative_optional(entry, "frictionloss", context=f"{path}: joints.{jname}"), + armature=_validate_non_negative_optional(entry, "armature", context=f"{path}: joints.{jname}"), + ) + + temps_raw = data.get("temperatures_c_ref") + temps: tuple[float, ...] | None = None + if temps_raw is not None: + if not isinstance(temps_raw, list | tuple) or len(temps_raw) != len(expected_joints): + raise ValueError(f"{path}: temperatures_c_ref must have {len(expected_joints)} finite values") + temps = tuple(float(t) for t in temps_raw) + if not all(math.isfinite(t) for t in temps): + raise ValueError(f"{path}: temperatures_c_ref must contain only finite values") + + source_val = data.get("source") + source_str = str(source_val).strip() if source_val is not None else None + + return DynamicsCalibration( + robot_key=expected_robot, + serial_number=file_serial, + joint_names=expected_joints, + joints=parsed_joints, + sha256=digest, + source_path=str(path), + source=source_str, + temperatures_c_ref=temps, + ) + + +def apply_dynamics_calibration( + base_values: JointDynamicsValues, + calibration: DynamicsCalibration, + *, + profile_name: str = DYNAMICS_PROFILE_COMPENSATED, +) -> JointDynamicsValues: + """Layer a per-unit calibration onto nominal profile values orthogonally. + + - ``armature`` and ``damping`` are overridden whenever specified in ``calibration``. + - ``frictionloss`` is overridden ONLY under ``raw``; under ``compensated`` + it remains equal to ``base_values.frictionloss`` (0.0) because dry Coulomb + friction is treated as compensated by the controller servo loop. + """ + if profile_name not in VALID_DYNAMICS_PROFILES: + raise ValueError(f"unknown dynamics_profile: {profile_name!r}; expected one of {VALID_DYNAMICS_PROFILES}") + dof = len(calibration.joint_names) + base_values.validate_dof(dof) + + armature: list[float] = [] + damping: list[float] = [] + frictionloss: list[float] = [] + for idx, jname in enumerate(calibration.joint_names): + ov = calibration.joints[jname] + armature.append(base_values.armature[idx] if ov.armature is None else ov.armature) + damping.append(base_values.damping[idx] if ov.damping is None else ov.damping) + if profile_name == DYNAMICS_PROFILE_RAW and ov.frictionloss is not None: + frictionloss.append(ov.frictionloss) + else: + frictionloss.append(base_values.frictionloss[idx]) + return JointDynamicsValues( + armature=tuple(armature), + damping=tuple(damping), + frictionloss=tuple(frictionloss), + ) + + +def resolve_arm_joint_dynamics( + arm_source: Any, + *, + dynamics_profile: str | None = None, + dynamics_calibration: DynamicsCalibration | None = None, + zero_joint_frictionloss: bool = False, +) -> tuple[str, JointDynamicsValues | None]: + """Resolve effective ``(profile_name, JointDynamicsValues)`` from runtime/config objects.""" + arm = getattr(arm_source, "arm", arm_source) + default_profile = str(getattr(arm, "dynamics_profile", DYNAMICS_PROFILE_COMPENSATED)) + profile_name = default_profile if dynamics_profile is None else str(dynamics_profile) + if profile_name not in VALID_DYNAMICS_PROFILES: + raise ValueError(f"unknown dynamics_profile: {profile_name!r}; expected one of {VALID_DYNAMICS_PROFILES}") + + spec = getattr(arm, "dynamics", None) + if spec is None: + return profile_name, None + values: JointDynamicsValues = spec.profile(profile_name) + if dynamics_calibration is not None: + values = apply_dynamics_calibration(values, dynamics_calibration, profile_name=profile_name) + if zero_joint_frictionloss: + values = JointDynamicsValues( + armature=values.armature, + damping=values.damping, + frictionloss=tuple(0.0 for _ in values.frictionloss), + ) + return profile_name, values + + +def apply_arm_joint_dynamics( + robot: Any, + dof_idx: Sequence[int], + arm_source: Any, + *, + dynamics_profile: str | None = None, + dynamics_calibration: DynamicsCalibration | None = None, + zero_joint_frictionloss: bool = False, +) -> JointDynamicsValues | None: + """Apply resolved arm ``armature``, ``damping``, and ``frictionloss`` to a Genesis robot.""" + _profile_name, values = resolve_arm_joint_dynamics( + arm_source, + dynamics_profile=dynamics_profile, + dynamics_calibration=dynamics_calibration, + zero_joint_frictionloss=zero_joint_frictionloss, + ) + if values is None: + if zero_joint_frictionloss and hasattr(robot, "set_dofs_frictionloss"): + robot.set_dofs_frictionloss(np.zeros(len(dof_idx), dtype=np.float32), dof_idx) + return None + if len(values.armature) != len(dof_idx): + raise ValueError(f"joint dynamics DOF count ({len(values.armature)}) != dof_idx count ({len(dof_idx)})") + + if hasattr(robot, "set_dofs_armature"): + robot.set_dofs_armature(np.asarray(values.armature, dtype=np.float32), dof_idx) + if hasattr(robot, "set_dofs_damping"): + robot.set_dofs_damping(np.asarray(values.damping, dtype=np.float32), dof_idx) + if hasattr(robot, "set_dofs_frictionloss"): + robot.set_dofs_frictionloss(np.asarray(values.frictionloss, dtype=np.float32), dof_idx) + return values diff --git a/ufactory/dynamics/cli.py b/ufactory/dynamics/cli.py index 1a4cc80..17de256 100644 --- a/ufactory/dynamics/cli.py +++ b/ufactory/dynamics/cli.py @@ -16,8 +16,12 @@ import numpy as np +from ufactory.config.models import DYNAMICS_PROFILE_COMPENSATED, VALID_DYNAMICS_PROFILES +from ufactory.dynamics.calibration import DynamicsCalibration, load_dynamics_calibration from ufactory.dynamics.probe import ( build_genesis_scene, + read_joint_armature, + read_joint_damping, read_joint_frictionloss, compute_ee_z_table_from_sim, genesis_pd_hold_torque_at_q, @@ -403,6 +407,18 @@ def cli_hardware_check(argv: Sequence[str] | None = None) -> int: parser.add_argument("--poses", type=str, default=None, help="Comma-separated pose names to run") parser.add_argument("--include-stress", action="store_true", help="Include stress/saturation pose set") parser.add_argument("--require-reference", action="store_true", help="Fail if Pinocchio is unavailable") + parser.add_argument( + "--dynamics-profile", + choices=VALID_DYNAMICS_PROFILES, + default=DYNAMICS_PROFILE_COMPENSATED, + help="Arm joint dynamics profile: compensated (default) or raw (full dry friction)", + ) + parser.add_argument( + "--dynamics-calibration", + type=str, + default=None, + help="Optional per-unit schema-v1 dynamics calibration YAML (validated against robot & SN)", + ) parser.add_argument( "--zero-joint-frictionloss", action="store_true", @@ -467,6 +483,14 @@ def cli_hardware_check(argv: Sequence[str] | None = None) -> int: serial_number=resolved_sn, ) + dyn_calib: DynamicsCalibration | None = None + if args.dynamics_calibration: + dyn_calib = load_dynamics_calibration( + args.dynamics_calibration, + robot_key=runtime.model.key, + serial_number=resolved_sn, + ) + print("=" * 78) print(f"{runtime.model.key} Static Dynamics Validation: Genesis PD hold vs Real Robot") print(f"PD hold torque: {_PD_HOLD_TORQUE_DEF}") @@ -474,9 +498,11 @@ def cli_hardware_check(argv: Sequence[str] | None = None) -> int: print(f"URDF : {urdf_path_str}") if kinematics_yaml_path: print(f"Calib: {kinematics_yaml_path}") + if dyn_calib is not None: + print(f"DynCl: {dyn_calib.source_path} (SN={dyn_calib.serial_number})") print( f"z_min: {args.z_min_mm:.1f} mm speed: {args.speed:.4f} rad/s move_strategy: {args.move_strategy} " - f"zero_joint_frictionloss: {args.zero_joint_frictionloss}" + f"dynamics_profile: {args.dynamics_profile} zero_joint_frictionloss: {args.zero_joint_frictionloss}" ) urdf_issues = validate_urdf_dynamics(urdf_path_str) @@ -503,6 +529,8 @@ def cli_hardware_check(argv: Sequence[str] | None = None) -> int: runtime_profile=runtime, show_viewer=args.vis, zero_joint_frictionloss=args.zero_joint_frictionloss, + dynamics_profile=args.dynamics_profile, + dynamics_calibration=dyn_calib, ) ee_z_table = compute_ee_z_table_from_sim(robot, scene, ee_link, dof_idx, configs) safe_poses, rejected = filter_safe_configs(configs, ee_z_table, args.z_min_mm) @@ -586,6 +614,8 @@ def cli_hardware_check(argv: Sequence[str] | None = None) -> int: sn = get_robot_sn(session.arm) run_config.robot_sn = sn or run_config.robot_sn + if dyn_calib is not None: + dyn_calib.validate_serial(sn) validate_kinematics_calibration_request( sn, runtime.model.robot_name, @@ -757,6 +787,11 @@ def cli_hardware_check(argv: Sequence[str] | None = None) -> int: jsonl_report=args.jsonl_report, stamp=stamp, ) + run_config.dynamics_profile = args.dynamics_profile + run_config.dynamics_calibration_path = dyn_calib.source_path if dyn_calib is not None else None + run_config.dynamics_calibration_sha256 = dyn_calib.sha256 if dyn_calib is not None else None + run_config.joint_armature = read_joint_armature(robot, dof_idx).tolist() + run_config.joint_damping = read_joint_damping(robot, dof_idx).tolist() run_config.joint_frictionloss = read_joint_frictionloss(robot, dof_idx).tolist() write_csv_report(results, csv_path, runtime_profile=runtime) write_jsonl_report(results, jsonl_path, run_config=run_config, urdf_issues=urdf_issues, runtime_profile=runtime) @@ -818,6 +853,18 @@ def cli_sim_check(argv: Sequence[str] | None = None) -> int: parser.add_argument("--z-min-mm", type=float, default=None) parser.add_argument("--random-count", type=int, default=100) parser.add_argument("--require-reference", action="store_true", help="Fail if Pinocchio is unavailable") + parser.add_argument( + "--dynamics-profile", + choices=VALID_DYNAMICS_PROFILES, + default=DYNAMICS_PROFILE_COMPENSATED, + help="Arm joint dynamics profile: compensated (default) or raw (full dry friction)", + ) + parser.add_argument( + "--dynamics-calibration", + type=str, + default=None, + help="Optional per-unit schema-v1 dynamics calibration YAML (validated against robot & SN)", + ) parser.add_argument( "--zero-joint-frictionloss", action="store_true", @@ -882,10 +929,20 @@ def cli_sim_check(argv: Sequence[str] | None = None) -> int: ] configs = merge_test_configs(dynamics_default_configs(runtime.model.key), random_configs) + dyn_calib: DynamicsCalibration | None = None + if args.dynamics_calibration: + dyn_calib = load_dynamics_calibration( + args.dynamics_calibration, + robot_key=runtime.model.key, + serial_number=resolved_sn, + ) + scene, robot, ee_link, dof_idx = build_genesis_scene( urdf_path_str, runtime_profile=runtime, zero_joint_frictionloss=args.zero_joint_frictionloss, + dynamics_profile=args.dynamics_profile, + dynamics_calibration=dyn_calib, ) ee_z_table = compute_ee_z_table_from_sim(robot, scene, ee_link, dof_idx, configs) safe_poses, rejected = filter_safe_configs(configs, ee_z_table, args.z_min_mm) @@ -924,6 +981,11 @@ def cli_sim_check(argv: Sequence[str] | None = None) -> int: jsonl_report=args.jsonl_report, stamp=stamp, ) + run_config.dynamics_profile = args.dynamics_profile + run_config.dynamics_calibration_path = dyn_calib.source_path if dyn_calib is not None else None + run_config.dynamics_calibration_sha256 = dyn_calib.sha256 if dyn_calib is not None else None + run_config.joint_armature = read_joint_armature(robot, dof_idx).tolist() + run_config.joint_damping = read_joint_damping(robot, dof_idx).tolist() run_config.joint_frictionloss = read_joint_frictionloss(robot, dof_idx).tolist() write_csv_report(results, csv_path, runtime_profile=runtime) write_jsonl_report(results, jsonl_path, run_config=run_config, urdf_issues=issues, runtime_profile=runtime) diff --git a/ufactory/dynamics/probe.py b/ufactory/dynamics/probe.py index c2abb16..c12df1b 100644 --- a/ufactory/dynamics/probe.py +++ b/ufactory/dynamics/probe.py @@ -17,6 +17,7 @@ import numpy as np +from ufactory.dynamics.calibration import DynamicsCalibration, apply_arm_joint_dynamics from ufactory.dynamics.report import ( POS_ERR_TOL, SATURATION_MARGIN, @@ -60,16 +61,17 @@ def build_genesis_scene( sim_substeps: int = SIM_SUBSTEPS, backend: str = "gpu", zero_joint_frictionloss: bool = False, - default_armature: float | None = 0.1, + default_armature: float | None = None, + dynamics_profile: str | None = None, + dynamics_calibration: DynamicsCalibration | None = None, ): """Create a minimal fixed-base Genesis scene for dynamics checks. - ``default_armature`` is forwarded to ``gs.morphs.URDF`` and matches Genesis's - own default (0.1 kg*m^2 reflected rotor inertia applied uniformly to every - joint). Override to ``None`` (disable) or a smaller value to diagnose - simulation-side torque anomalies on light distal joints -- see - ``uf_dynamics.md`` section 4.8 (Lite6 wrist anomaly) -- without touching the - production default used by the CLI entry points. + Joint ``armature``, ``damping`` and ``frictionloss`` are applied from the + model-level ``dynamics_profile`` (``compensated`` by default, or ``raw``) + in ``assets/configs/runtime/robots/*.yaml`` plus optional per-unit + ``dynamics_calibration``. Pass an explicit scalar ``default_armature`` + only for diagnostic overrides. """ gs = require_genesis_runtime() @@ -95,7 +97,7 @@ def build_genesis_scene( file=str(Path(urdf_path).resolve()), pos=(0, 0, 0), fixed=True, - default_armature=default_armature, + default_armature=0.0 if default_armature is None else default_armature, ) ) scene.build() @@ -106,11 +108,29 @@ def build_genesis_scene( for name in runtime.arm.joint_names ] ee_link = robot.get_link(resolve_entity_name(robot, runtime.arm.ee_link, "link")) - if zero_joint_frictionloss: - robot.set_dofs_frictionloss(np.zeros(len(dof_idx), dtype=np.float32), dof_idx) + apply_arm_joint_dynamics( + robot, + dof_idx, + runtime, + dynamics_profile=dynamics_profile, + dynamics_calibration=dynamics_calibration, + zero_joint_frictionloss=zero_joint_frictionloss, + ) + if default_armature is not None and hasattr(robot, "set_dofs_armature"): + robot.set_dofs_armature(np.full(len(dof_idx), float(default_armature), dtype=np.float32), dof_idx) return scene, robot, ee_link, dof_idx +def read_joint_armature(robot, dof_idx: Sequence[int]) -> np.ndarray: + """Read per-joint reflected rotor armature (kg*m^2) applied on the robot DOFs.""" + return _to_np(robot.get_dofs_armature(dof_idx)).flatten().astype(np.float64) + + +def read_joint_damping(robot, dof_idx: Sequence[int]) -> np.ndarray: + """Read per-joint passive viscous damping (Nm*s/rad) applied on the robot DOFs.""" + return _to_np(robot.get_dofs_damping(dof_idx)).flatten().astype(np.float64) + + def read_joint_frictionloss(robot, dof_idx: Sequence[int]) -> np.ndarray: """Read per-joint frictionloss (Nm) applied on the robot DOFs.""" return _to_np(robot.get_dofs_frictionloss(dof_idx)).flatten().astype(np.float64) diff --git a/ufactory/dynamics/report.py b/ufactory/dynamics/report.py index b835a29..dc709ae 100644 --- a/ufactory/dynamics/report.py +++ b/ufactory/dynamics/report.py @@ -97,6 +97,11 @@ class DynamicsRunConfig: robot_sn: str | None = None tcp_load: list[float] | None = None gravity_direction: list[float] | None = None + dynamics_profile: str | None = None + dynamics_calibration_path: str | None = None + dynamics_calibration_sha256: str | None = None + joint_armature: list[float] | None = None + joint_damping: list[float] | None = None # Joint-frictionloss actually applied during this run (per joint, Nm). joint_frictionloss: list[float] | None = None git_sha: str | None = None diff --git a/ufactory/manipulation/packaging/simulation.py b/ufactory/manipulation/packaging/simulation.py index 0872adf..1a14dad 100644 --- a/ufactory/manipulation/packaging/simulation.py +++ b/ufactory/manipulation/packaging/simulation.py @@ -153,6 +153,9 @@ def _setup_robot(robot, layout, config, *, arm_kp_scale: float | None = None, ca torch.tensor(config.arm.force_upper_nm, device=gs.device, dtype=gs.tc_float), arm_dof_idx, ) + from ufactory.dynamics.calibration import apply_arm_joint_dynamics + + apply_arm_joint_dynamics(robot, arm_dof_idx, config) robot.set_dofs_kp( torch.full((len(opening_gripper_dof_idx),), gripper.kp, device=gs.device, dtype=gs.tc_float), opening_gripper_dof_idx, diff --git a/ufactory/robots/runtime.py b/ufactory/robots/runtime.py index e28c3fd..f889861 100644 --- a/ufactory/robots/runtime.py +++ b/ufactory/robots/runtime.py @@ -6,6 +6,11 @@ import math import xml.etree.ElementTree as ET +from ufactory.config.models import ( + ArmDynamicsSpec, + DYNAMICS_PROFILE_COMPENSATED, + JointDynamicsValues, +) from ufactory.robots.registry import RobotModelSpec, get_robot_profile, joint_names, robot_cli_choices from ufactory.grippers.bio_g2 import ( BIO_G2_JOINT_NAMES, @@ -47,6 +52,14 @@ class ArmControlParams: force_lower: FloatTuple force_upper: FloatTuple effort_limits: FloatTuple + dynamics_profile: str = DYNAMICS_PROFILE_COMPENSATED + dynamics: ArmDynamicsSpec | None = None + + def resolve_joint_dynamics(self, profile_name: str | None = None) -> JointDynamicsValues | None: + if self.dynamics is None: + return None + chosen = self.dynamics_profile if profile_name is None else str(profile_name) + return self.dynamics.profile(chosen) @dataclass(frozen=True) @@ -345,6 +358,11 @@ def _arm_params(profile: RobotModelSpec) -> ArmControlParams: else: kp = _fit((3000.0, 3000.0, 2000.0, 2000.0, 1000.0, 1000.0, 800.0), profile.dof, fill=800.0) kv = _fit((300.0, 300.0, 200.0, 200.0, 100.0, 100.0, 80.0), profile.dof, fill=80.0) + from ufactory.config.loader import load_arm_dynamics_spec + + loaded_dyn = load_arm_dynamics_spec(profile.key) + dyn_profile_name = loaded_dyn[0] if loaded_dyn is not None else DYNAMICS_PROFILE_COMPENSATED + dyn_spec = loaded_dyn[1] if loaded_dyn is not None else None return ArmControlParams( joint_names=joint_names(profile), ee_link=profile.ee_link, @@ -355,6 +373,8 @@ def _arm_params(profile: RobotModelSpec) -> ArmControlParams: force_lower=tuple(-abs(v) for v in efforts), force_upper=efforts, effort_limits=efforts, + dynamics_profile=dyn_profile_name, + dynamics=dyn_spec, ) diff --git a/ufactory/training/tasks.py b/ufactory/training/tasks.py index b71cedb..8c9e4f0 100644 --- a/ufactory/training/tasks.py +++ b/ufactory/training/tasks.py @@ -259,7 +259,8 @@ def build_reach_task_configs( "use_gjk_collision": config.simulation.use_gjk_collision, } ) - robot_cfg = { + joint_dyn = config.arm.resolve_joint_dynamics() + robot_cfg: dict[str, Any] = { "urdf_path": robot_urdf(config.robot.key, config.robot.urdf), "base_pos": [0.0, 0.0, 0.0], "ee_link_name": config.robot.ee_link, @@ -269,5 +270,10 @@ def build_reach_task_configs( "kv": list(config.arm.kv), "force_lower": list(config.arm.force_lower_nm), "force_upper": list(config.arm.force_upper_nm), + "dynamics_profile": config.arm.dynamics_profile, } + if joint_dyn is not None: + robot_cfg["armature"] = list(joint_dyn.armature) + robot_cfg["damping"] = list(joint_dyn.damping) + robot_cfg["frictionloss"] = list(joint_dyn.frictionloss) return env_cfg, deepcopy(recipe["reward"]), robot_cfg diff --git a/ufactory/trajectory/scene.py b/ufactory/trajectory/scene.py index 75e1c61..31a4f80 100644 --- a/ufactory/trajectory/scene.py +++ b/ufactory/trajectory/scene.py @@ -552,6 +552,9 @@ def build_scene( torch.tensor(runtime_arm.force_upper, device=gs.device, dtype=gs.tc_float), arm_dof_idx, ) + from ufactory.dynamics.calibration import apply_arm_joint_dynamics + + apply_arm_joint_dynamics(robot, arm_dof_idx, runtime) 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), diff --git a/ufactory/visualization/robot_viewer.py b/ufactory/visualization/robot_viewer.py index e14c883..a2bfbfc 100644 --- a/ufactory/visualization/robot_viewer.py +++ b/ufactory/visualization/robot_viewer.py @@ -102,7 +102,15 @@ def update_tcp_marker(marker, ee_link) -> None: marker.set_pos(ee_link.get_pos()) -def setup_arm_pd(robot, dof_idx: list[int], profile: RobotModelSpec) -> None: +def setup_arm_pd( + robot, + dof_idx: list[int], + profile: RobotModelSpec, + *, + dynamics_profile: str | None = None, +) -> None: + from ufactory.dynamics.calibration import apply_arm_joint_dynamics + runtime = get_robot_runtime_profile(profile.key) robot.set_dofs_kp(np.array(runtime.arm.kp), dof_idx) robot.set_dofs_kv(np.array(runtime.arm.kv), dof_idx) @@ -111,6 +119,7 @@ def setup_arm_pd(robot, dof_idx: list[int], profile: RobotModelSpec) -> None: np.array(runtime.arm.force_upper), dof_idx, ) + apply_arm_joint_dynamics(robot, dof_idx, runtime, dynamics_profile=dynamics_profile) def _to_numpy3(pos) -> np.ndarray: diff --git a/uv.lock b/uv.lock index eb491bb..376a917 100644 --- a/uv.lock +++ b/uv.lock @@ -888,7 +888,7 @@ wheels = [ [[package]] name = "genesis-ufactory" -version = "0.3.11" +version = "0.3.12" source = { editable = "." } dependencies = [ { name = "numpy" },