From c793faa48e6d5bcb199716be36985a1692fb0c81 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Thu, 5 Nov 2026 20:43:10 -0800 Subject: [PATCH 01/39] docs(control): spec for shared sim/hardware torque controllers --- docs/development/controller_interface.md | 181 +++++++++++++++++++++++ docs/development/index.md | 1 + 2 files changed, 182 insertions(+) create mode 100644 docs/development/controller_interface.md diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md new file mode 100644 index 000000000..af0bb1d95 --- /dev/null +++ b/docs/development/controller_interface.md @@ -0,0 +1,181 @@ +# Spec: Shared Torque Controllers for Sim and Hardware + +Status: draft, implemented step by step on branch `feat/controller-interface`. + +## Goal + +Run the *same* low-level controller code in MuJoCo and on real hardware, so +that a policy sees the same closed-loop behaviour (compliance, tracking lag, +clipping) in both. + +Today the two differ: + +| | Joint commands | Cartesian commands | +|---|---|---| +| Sim (`SimRobot`) | MuJoCo `` actuator (PD inside MuJoCo) | Pinocchio IK, then the same position actuator | +| FR3 hardware (`Franka`) | RCS joint PD at 1 kHz (`Franka::joint_controller`) | RCS OSC at 1 kHz (`Franka::osc`) | + +## Non-goals + +- Hardware is **not** required to use the interface. UR5e, xArm, Flexiv, + YAM and SO101 keep their vendor servo modes. +- No changes to the Python env / wrapper layer or the action spaces. + `ControlMode.JOINTS` and `ControlMode.CARTESIAN_*` keep working and are + routed to whichever controller is installed. +- No whole-body or multi-robot controller. A robot is controlled on its own; + coordination stays above this layer. +- Controllers written in Python. They are C++ only. + +## Concepts + +``` +policy rate (e.g. 20 Hz) servo rate (sim: model timestep, FR3: 1 kHz) + set_goal(goal) ──► Interpolator ──► setpoint ──► Controller ──► joint torque ──► backend + ▲ (no gravity) + ControllerState (q, dq, M, c, g, J, tcp pose, dt) +``` + +- **ControllerState**: everything a torque controller needs about one robot, + filled by the *backend* (MuJoCo or libfranka) on every servo tick. All + Cartesian quantities are in the **robot base frame** at the **TCP** + (`tcp_offset` applied). +- **Interpolator**: turns sparse goals into a smooth setpoint (position plus + velocity) on every servo tick. +- **Controller**: owns an interpolator. `set_goal()` is called at policy rate, + `step(state)` at servo rate, and `step()` returns joint torques. +- **Backend**: builds the `ControllerState`, calls `step()` and applies the + torque. Only the backend knows the hardware. + +### Gravity convention + +Controllers return torque **without gravity compensation**, because Franka +compensates gravity in firmware. A backend whose actuators don't do that (the +MuJoCo backend) adds `state.gravity` itself. Coriolis compensation is the +controller's job, using `state.coriolis`. + +### Threading + +The interfaces aren't thread-safe. A backend that calls `set_goal()` and +`step()` from different threads (FR3) has to serialise those calls itself, as +it already does today with `interpolator_mutex`. + +## Interfaces (core package, `include/rcs/`) + +`Interpolator.h` + +```cpp +struct JointSetpoint { VectorXd q; VectorXd dq; }; +struct CartesianSetpoint { Pose pose; Vector6d twist; }; // twist = [v; w], base frame + +class JointInterpolator { + virtual void reset(const VectorXd& q) = 0; // hold q, no motion + virtual void set_goal(const VectorXd& q_goal) = 0; // start a new segment from the current setpoint + virtual JointSetpoint step(double dt) = 0; // advance by dt, return the setpoint +}; +class CartesianInterpolator { /* same, with Pose */ }; +``` + +`Controller.h` + +```cpp +struct ControllerState { + VectorXd q, dq; // n + MatrixXd mass; // n x n + VectorXd coriolis; // n, C(q, dq) * dq + VectorXd gravity; // n + Eigen::Matrix jacobian; // TCP, base frame, rows [v; w] + Pose tcp_pose; // base frame + double dt; // seconds since the previous step() +}; + +class JointController { + virtual void reset(const ControllerState& state) = 0; // hold the current configuration + virtual void set_goal(const VectorXd& q_goal) = 0; + virtual VectorXd step(const ControllerState& state) = 0; // joint torque without gravity +}; +class CartesianController { /* same, with a Pose goal in the base frame */ }; +``` + +Joint and Cartesian are separate interfaces on purpose. Each is about ten +lines, the goal type is checked at compile time, and the backend only has to +know "is the last command a joint or a Cartesian one". + +## Where the implementations live + +| Implementation | Package | Notes | +|---|---|---| +| `LinearJointInterpolator`, `LinearCartesianInterpolator` | core | Straight line (slerp for rotation) from the current setpoint to the goal over a fixed duration, then hold. Generalises the 7-DoF `LinearPoseTrajInterpolator.h`, which is deleted once FR3 has moved over. | +| `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | +| `OSC` | core | Decoupled operational-space control with null-space posture: `tau = Jpᵀ Λp (Kp_p e_p + Kd_p (v_d - v)) + Joᵀ Λo (Kp_o e_o + Kd_o (w_d - w)) + N (posture term) + coriolis` | +| `FrankaJointController`, `FrankaOSC` | `rcs_fr3` | The current `Franka::joint_controller` / `Franka::osc` maths moved out of the libfranka lambdas: residual mass, null-space posture, joint-limit avoidance and guard, deadband, `franka::limitRate`, torque clip. The rate limit uses the controller's own previous output instead of `tau_J_d`, so it runs in sim too. | +| Ruckig interpolator | open | See open questions. | + +## Backends + +### MuJoCo (`SimRobot`) + +- New: `set_joint_controller(shared_ptr)` and + `set_cartesian_controller(shared_ptr)`. Without a + controller, `SimRobot` behaves exactly as today (native MuJoCo PD). +- With a controller installed: + - On install, the arm actuators are switched to torque mode at runtime, the + same way `set_config` already rewrites `gainprm`/`biasprm` (gain 1, + bias 0). The torque is clamped to the actuator's `forcerange`/`ctrlrange`. + - The controller is stepped from a per-step `Sim` callback, i.e. after + `mj_step1` (where `qM`, `qfrc_bias` and kinematics are current) and before + `mj_step2`. That is the same position as robosuite's + `step1 → _pre_action → step2`. + - State: `q`/`dq` from the robot's joints; `mass` from `mj_fullM`, + restricted to the robot's DoFs; `gravity` from `qfrc_gravcomp`-style + evaluation (RNE with zero velocity); `coriolis = qfrc_bias - gravity`; + `jacobian` from `mj_jac` at the TCP point, rotated into the base frame. + - `ctrl = step(state) + gravity`. + - `set_joint_position(q)` goes to the joint controller if one is installed. + `set_cartesian_position(pose)` goes to the Cartesian controller if one is + installed, otherwise IK and the joint path as today. Switching between + the two calls `reset()` on the newly active controller. + - The convergence callback (`step_until_convergence`) compares the TCP pose + instead of joint angles while a Cartesian controller is active. + +### FR3 hardware (`Franka`) + +- The bodies of the two `robot.control(...)` lambdas become: fill the + `ControllerState` from `franka::Model` and `RobotState`, call + `controller->step()`, return the torque. +- By default `Franka` builds a `FrankaJointController` / `FrankaOSC` from + `FrankaConfig`, so the Python API and configs are unchanged. +- The missing Coriolis compensation in the current OSC and joint controller is + fixed in a separate commit, because it changes how the real robot behaves. + +### Using hardware controllers in sim + +`FrankaOSC` only needs a `ControllerState`. With `rcs_fr3` installed it can +be passed to `SimRobot.set_cartesian_controller()`, so the sim runs the exact +FR3 controller, including its clipping. Franka firmware behaviour (reflexes, +collision thresholds, internal torque tracking) is **not** modelled. + +## Implementation steps (each step is reviewable on its own) + +1. Spec and interfaces (header only, no behaviour change). +2. Linear interpolators in core, plus pybind and unit tests. +3. `JointPD` and `OSC` in core, plus pybind. +4. MuJoCo backend in `SimRobot`. Sim tests: hold under gravity, reach a joint + goal, reach a Cartesian goal, switch modes. +5. `FrankaJointController` / `FrankaOSC` in `rcs_fr3`; `Franka` uses them; + delete `LinearPoseTrajInterpolator.h`. Sim test with the FR3 controllers. +6. Fix: add Coriolis compensation to the FR3 controllers (needs testing on + hardware). + +## Open questions + +- **Ruckig** (MIT community version) as a jerk-limited interpolator: core or + an optional extension? It is only an extra `JointInterpolator`, so it can be + added later without interface changes. +- **Timestep**: FR3 runs at 1 kHz, the sim model at 500 Hz (default 2 ms). + Use 1 ms in torque-controlled scenes so gains carry over? +- **Linear interpolator start point**: the current FR3 interpolator starts + each segment at the *previous goal*. The new one starts at the *current + setpoint*, which avoids a setpoint jump when a goal arrives before the last + segment is finished. That is a small behaviour change for FR3. +- **FR3 default `torque_limit` of 5 Nm** is very conservative and will + saturate in sim with tuned gains. diff --git a/docs/development/index.md b/docs/development/index.md index 42cc9a5fa..c18de57e9 100644 --- a/docs/development/index.md +++ b/docs/development/index.md @@ -5,5 +5,6 @@ python_extension cpp_extension +controller_interface ../contributing/index ``` From c9bc499a49d2c661e749697c3d579236e35d0289 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Thu, 5 Nov 2026 20:43:10 -0800 Subject: [PATCH 02/39] feat(control): add controller and interpolator interfaces Header-only interfaces in the core package. Nothing uses them yet. --- include/rcs/Controller.h | 53 ++++++++++++++++++++++++++++++++++++++ include/rcs/Interpolator.h | 44 +++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 include/rcs/Controller.h create mode 100644 include/rcs/Interpolator.h diff --git a/include/rcs/Controller.h b/include/rcs/Controller.h new file mode 100644 index 000000000..9ca9b742f --- /dev/null +++ b/include/rcs/Controller.h @@ -0,0 +1,53 @@ +#ifndef RCS_CONTROLLER_H +#define RCS_CONTROLLER_H + +#include + +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// Everything a torque controller needs to know about one robot. Filled by the +// backend (MuJoCo or the hardware driver) on every servo tick. +// Cartesian quantities are in the robot base frame, at the TCP. +struct ControllerState { + VectorXd q; + VectorXd dq; + Eigen::MatrixXd mass; + VectorXd coriolis; // C(q, dq) * dq + VectorXd gravity; + Eigen::Matrix jacobian; // rows: [linear; angular] + Pose tcp_pose; + double dt = 0.0; // seconds since the previous step() +}; + +// Controllers return joint torques WITHOUT gravity compensation. Backends whose +// actuators don't compensate gravity themselves add state.gravity. +// The interfaces aren't thread-safe: a backend that calls set_goal() and step() +// from different threads has to serialise the calls. + +class JointController { + public: + virtual ~JointController() = default; + // Hold the current configuration. + virtual void reset(const ControllerState& state) = 0; + // Called at policy rate. + virtual void set_goal(const VectorXd& q_goal) = 0; + // Called at servo rate. Returns joint torques without gravity. + virtual VectorXd step(const ControllerState& state) = 0; +}; + +class CartesianController { + public: + virtual ~CartesianController() = default; + virtual void reset(const ControllerState& state) = 0; + // TCP goal in the robot base frame. + virtual void set_goal(const Pose& pose_goal) = 0; + virtual VectorXd step(const ControllerState& state) = 0; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_CONTROLLER_H diff --git a/include/rcs/Interpolator.h b/include/rcs/Interpolator.h new file mode 100644 index 000000000..fe856d96f --- /dev/null +++ b/include/rcs/Interpolator.h @@ -0,0 +1,44 @@ +#ifndef RCS_INTERPOLATOR_H +#define RCS_INTERPOLATOR_H + +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// Desired joint state for one servo tick. +struct JointSetpoint { + VectorXd q; + VectorXd dq; +}; + +// Desired TCP state for one servo tick, in the robot base frame. +struct CartesianSetpoint { + Pose pose; + Vector6d twist; // [linear velocity; angular velocity] +}; + +// Turns sparse goals (policy rate) into a smooth setpoint (servo rate). +class JointInterpolator { + public: + virtual ~JointInterpolator() = default; + // Hold q, with zero velocity. + virtual void reset(const VectorXd& q) = 0; + // Start moving from the current setpoint towards q_goal. + virtual void set_goal(const VectorXd& q_goal) = 0; + // Advance by dt seconds and return the new setpoint. + virtual JointSetpoint step(double dt) = 0; +}; + +class CartesianInterpolator { + public: + virtual ~CartesianInterpolator() = default; + virtual void reset(const Pose& pose) = 0; + virtual void set_goal(const Pose& pose_goal) = 0; + virtual CartesianSetpoint step(double dt) = 0; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_INTERPOLATOR_H From 180c572e1d530394e46e6adff55660629d762366 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 16:54:04 -0800 Subject: [PATCH 03/39] docs(control): update spec for sim control hook and gravcomp Run sim controllers in a control hook between mj_step1 and mj_step2, since callbacks now run after integration. Use MuJoCo gravity compensation in place of the Franka firmware. Drop the Coriolis step and the torque limit question, both are fixed on master. --- docs/development/controller_interface.md | 38 ++++++++++++------------ 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index af0bb1d95..5125a7321 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -49,8 +49,11 @@ policy rate (e.g. 20 Hz) servo rate (sim: model timestep, FR3: 1 kH ### Gravity convention Controllers return torque **without gravity compensation**, because Franka -compensates gravity in firmware. A backend whose actuators don't do that (the -MuJoCo backend) adds `state.gravity` itself. Coriolis compensation is the +compensates gravity in firmware. In sim, MuJoCo's gravity compensation +(`add_gravcomp` in the scene config) plays the part of the firmware, so the +MuJoCo backend doesn't add gravity either. Loads that the real robot doesn't +compensate (e.g. a wrist camera) are excluded with `gravcomp_ignore` and then +act on the arm in both sim and real. Coriolis compensation is the controller's job, using `state.coriolis`. ### Threading @@ -107,7 +110,7 @@ know "is the last command a joint or a Cartesian one". | `LinearJointInterpolator`, `LinearCartesianInterpolator` | core | Straight line (slerp for rotation) from the current setpoint to the goal over a fixed duration, then hold. Generalises the 7-DoF `LinearPoseTrajInterpolator.h`, which is deleted once FR3 has moved over. | | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Decoupled operational-space control with null-space posture: `tau = Jpᵀ Λp (Kp_p e_p + Kd_p (v_d - v)) + Joᵀ Λo (Kp_o e_o + Kd_o (w_d - w)) + N (posture term) + coriolis` | -| `FrankaJointController`, `FrankaOSC` | `rcs_fr3` | The current `Franka::joint_controller` / `Franka::osc` maths moved out of the libfranka lambdas: residual mass, null-space posture, joint-limit avoidance and guard, deadband, `franka::limitRate`, torque clip. The rate limit uses the controller's own previous output instead of `tau_J_d`, so it runs in sim too. | +| `FrankaJointController`, `FrankaOSC` | `rcs_fr3` | The current `Franka::joint_controller` / `Franka::osc` maths moved out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, `franka::limitRate`, torque clip. The rate limit uses the controller's own previous output instead of `tau_J_d`, so it runs in sim too. | | Ruckig interpolator | open | See open questions. | ## Backends @@ -121,15 +124,18 @@ know "is the last command a joint or a Cartesian one". - On install, the arm actuators are switched to torque mode at runtime, the same way `set_config` already rewrites `gainprm`/`biasprm` (gain 1, bias 0). The torque is clamped to the actuator's `forcerange`/`ctrlrange`. - - The controller is stepped from a per-step `Sim` callback, i.e. after - `mj_step1` (where `qM`, `qfrc_bias` and kinematics are current) and before - `mj_step2`. That is the same position as robosuite's - `step1 → _pre_action → step2`. + The scene must use `add_gravcomp` (see the gravity convention). + - `Sim` gets a separate **control hook**: `Sim::step` runs + `mj_step1 → control hooks → mj_step2 → callbacks`. Control hooks see + `qM`, `qfrc_bias` and kinematics that match the current state, which the + existing callbacks (called after integration) don't. That is the same + position as robosuite's `step1 → _pre_action → step2`. `mj_step1`/`mj_step2` + support every integrator except RK4. - State: `q`/`dq` from the robot's joints; `mass` from `mj_fullM`, - restricted to the robot's DoFs; `gravity` from `qfrc_gravcomp`-style - evaluation (RNE with zero velocity); `coriolis = qfrc_bias - gravity`; - `jacobian` from `mj_jac` at the TCP point, rotated into the base frame. - - `ctrl = step(state) + gravity`. + restricted to the robot's DoFs; `gravity` from RNE with zero velocity; + `coriolis = qfrc_bias - gravity`; `jacobian` from `mj_jac` at the TCP + point, rotated into the base frame. + - `ctrl = step(state)`. Gravity comes from MuJoCo's gravity compensation. - `set_joint_position(q)` goes to the joint controller if one is installed. `set_cartesian_position(pose)` goes to the Cartesian controller if one is installed, otherwise IK and the joint path as today. Switching between @@ -144,8 +150,6 @@ know "is the last command a joint or a Cartesian one". `controller->step()`, return the torque. - By default `Franka` builds a `FrankaJointController` / `FrankaOSC` from `FrankaConfig`, so the Python API and configs are unchanged. -- The missing Coriolis compensation in the current OSC and joint controller is - fixed in a separate commit, because it changes how the real robot behaves. ### Using hardware controllers in sim @@ -159,12 +163,10 @@ collision thresholds, internal torque tracking) is **not** modelled. 1. Spec and interfaces (header only, no behaviour change). 2. Linear interpolators in core, plus pybind and unit tests. 3. `JointPD` and `OSC` in core, plus pybind. -4. MuJoCo backend in `SimRobot`. Sim tests: hold under gravity, reach a joint - goal, reach a Cartesian goal, switch modes. +4. Control hook in `Sim` and MuJoCo backend in `SimRobot`. Sim tests: hold + under gravity, reach a joint goal, reach a Cartesian goal, switch modes. 5. `FrankaJointController` / `FrankaOSC` in `rcs_fr3`; `Franka` uses them; delete `LinearPoseTrajInterpolator.h`. Sim test with the FR3 controllers. -6. Fix: add Coriolis compensation to the FR3 controllers (needs testing on - hardware). ## Open questions @@ -177,5 +179,3 @@ collision thresholds, internal torque tracking) is **not** modelled. each segment at the *previous goal*. The new one starts at the *current setpoint*, which avoids a setpoint jump when a goal arrives before the last segment is finished. That is a small behaviour change for FR3. -- **FR3 default `torque_limit` of 5 Nm** is very conservative and will - saturate in sim with tuned gains. From 03bfe9f52c123baa5edb5d8d360b2fe34f062981 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:03:07 -0800 Subject: [PATCH 04/39] docs(control): compute controller state with pinocchio in sim and real Both backends fill ControllerState with a shared PinocchioDynamics instead of MuJoCo and franka::Model. The FR3 controllers then need nothing from libfranka and move to core, so the sim can use them without rcs_fr3. --- docs/development/controller_interface.md | 97 ++++++++++++++++++------ 1 file changed, 74 insertions(+), 23 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 5125a7321..a7650e590 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -33,18 +33,23 @@ policy rate (e.g. 20 Hz) servo rate (sim: model timestep, FR3: 1 kH set_goal(goal) ──► Interpolator ──► setpoint ──► Controller ──► joint torque ──► backend ▲ (no gravity) ControllerState (q, dq, M, c, g, J, tcp pose, dt) + ▲ + backend (q, dq) ──► PinocchioDynamics ``` - **ControllerState**: everything a torque controller needs about one robot, - filled by the *backend* (MuJoCo or libfranka) on every servo tick. All - Cartesian quantities are in the **robot base frame** at the **TCP** - (`tcp_offset` applied). + computed on every servo tick by `PinocchioDynamics` from the `q` and `dq` + that the backend measured. All Cartesian quantities are in the **robot base + frame** at the **TCP** (`tcp_offset` applied). +- **PinocchioDynamics**: the robot's dynamics model. Sim and real use the + same class, so both run the same dynamics code and not only the same + controller. - **Interpolator**: turns sparse goals into a smooth setpoint (position plus velocity) on every servo tick. - **Controller**: owns an interpolator. `set_goal()` is called at policy rate, `step(state)` at servo rate, and `step()` returns joint torques. -- **Backend**: builds the `ControllerState`, calls `step()` and applies the - torque. Only the backend knows the hardware. +- **Backend**: reads `q` and `dq`, calls `PinocchioDynamics` and `step()`, + and applies the torque. Only the backend knows the hardware. ### Gravity convention @@ -103,6 +108,36 @@ Joint and Cartesian are separate interfaces on purpose. Each is about ten lines, the goal type is checked at compile time, and the backend only has to know "is the last command a joint or a Cartesian one". +## Dynamics model (core package) + +`PinocchioDynamics.h` + +```cpp +struct Payload { // load at the flange, in the flange frame + double mass = 0.0; + Eigen::Vector3d com = Eigen::Vector3d::Zero(); + Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero(); // about the CoM +}; + +class PinocchioDynamics { + public: + PinocchioDynamics(const std::string& model_path, bool urdf, + const std::string& flange_frame, const Pose& tcp_offset); + void set_payload(const Payload& payload); + ControllerState compute(const VectorXd& q, const VectorXd& dq, double dt); +}; +``` + +- `compute()` does the same as libfranka's `franka::Model`, which (since + libfranka 0.14) is itself Pinocchio: `mass` from `crba`, `gravity` from + `computeGeneralizedGravity`, `coriolis` from `rnea(q, dq, 0) - gravity`, + `jacobian` and `tcp_pose` from the frame at `flange * tcp_offset` + (`LOCAL_WORLD_ALIGNED`, i.e. base frame). +- `set_payload()` adds the payload to the inertia of the flange body, as + libfranka does with `I_total`, `m_total` and `F_x_Ctotal`. +- The model file must contain only the arm. The gripper is part of the + payload, so that sim and real describe it the same way. + ## Where the implementations live | Implementation | Package | Notes | @@ -110,7 +145,8 @@ know "is the last command a joint or a Cartesian one". | `LinearJointInterpolator`, `LinearCartesianInterpolator` | core | Straight line (slerp for rotation) from the current setpoint to the goal over a fixed duration, then hold. Generalises the 7-DoF `LinearPoseTrajInterpolator.h`, which is deleted once FR3 has moved over. | | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Decoupled operational-space control with null-space posture: `tau = Jpᵀ Λp (Kp_p e_p + Kd_p (v_d - v)) + Joᵀ Λo (Kp_o e_o + Kd_o (w_d - w)) + N (posture term) + coriolis` | -| `FrankaJointController`, `FrankaOSC` | `rcs_fr3` | The current `Franka::joint_controller` / `Franka::osc` maths moved out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, `franka::limitRate`, torque clip. The rate limit uses the controller's own previous output instead of `tau_J_d`, so it runs in sim too. | +| `PinocchioDynamics` | core | See above. | +| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | | Ruckig interpolator | open | See open questions. | ## Backends @@ -131,11 +167,13 @@ know "is the last command a joint or a Cartesian one". existing callbacks (called after integration) don't. That is the same position as robosuite's `step1 → _pre_action → step2`. `mj_step1`/`mj_step2` support every integrator except RK4. - - State: `q`/`dq` from the robot's joints; `mass` from `mj_fullM`, - restricted to the robot's DoFs; `gravity` from RNE with zero velocity; - `coriolis = qfrc_bias - gravity`; `jacobian` from `mj_jac` at the TCP - point, rotated into the base frame. + - State: `q`/`dq` from the robot's joints, then + `PinocchioDynamics::compute()`. The payload is configured, e.g. the + Franka Hand. - `ctrl = step(state)`. Gravity comes from MuJoCo's gravity compensation. + - The controller's model (Pinocchio) is not exactly the plant (MuJoCo). + That is intended: it plays the part of the model error on the real + robot. - `set_joint_position(q)` goes to the joint controller if one is installed. `set_cartesian_position(pose)` goes to the Cartesian controller if one is installed, otherwise IK and the joint path as today. Switching between @@ -145,31 +183,44 @@ know "is the last command a joint or a Cartesian one". ### FR3 hardware (`Franka`) -- The bodies of the two `robot.control(...)` lambdas become: fill the - `ControllerState` from `franka::Model` and `RobotState`, call - `controller->step()`, return the torque. -- By default `Franka` builds a `FrankaJointController` / `FrankaOSC` from +- libfranka is only used for the connection: `robot.control(...)` with + torques, the robot state, error recovery and collision behaviour. + `franka::Model` is no longer used. +- The bodies of the two `robot.control(...)` lambdas become: take `q`/`dq` + from `RobotState`, `PinocchioDynamics::compute()`, `controller->step()`, + return the torque. The payload is set from `RobotState` (`I_total`, + `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. +- By default `Franka` builds an `FR3JointController` / `FR3OSC` from `FrankaConfig`, so the Python API and configs are unchanged. -### Using hardware controllers in sim +### Using the FR3 controllers in sim -`FrankaOSC` only needs a `ControllerState`. With `rcs_fr3` installed it can -be passed to `SimRobot.set_cartesian_controller()`, so the sim runs the exact -FR3 controller, including its clipping. Franka firmware behaviour (reflexes, -collision thresholds, internal torque tracking) is **not** modelled. +`FR3OSC` and `FR3JointController` live in core and only need a +`ControllerState`, so they can be passed to `SimRobot.set_*_controller()`. The +sim then runs the exact FR3 controller, including its clipping. Franka +firmware behaviour (reflexes, collision thresholds, internal torque tracking) +is **not** modelled. ## Implementation steps (each step is reviewable on its own) 1. Spec and interfaces (header only, no behaviour change). 2. Linear interpolators in core, plus pybind and unit tests. -3. `JointPD` and `OSC` in core, plus pybind. -4. Control hook in `Sim` and MuJoCo backend in `SimRobot`. Sim tests: hold +3. `PinocchioDynamics` in core, plus pybind. Test: same mass matrix, Coriolis + and Jacobian as MuJoCo for the same model file. +4. `JointPD` and `OSC` in core, plus pybind. +5. Control hook in `Sim` and MuJoCo backend in `SimRobot`. Sim tests: hold under gravity, reach a joint goal, reach a Cartesian goal, switch modes. -5. `FrankaJointController` / `FrankaOSC` in `rcs_fr3`; `Franka` uses them; - delete `LinearPoseTrajInterpolator.h`. Sim test with the FR3 controllers. +6. `FR3JointController` / `FR3OSC` in core. Sim test with them. +7. `Franka` uses `PinocchioDynamics` and the FR3 controllers; delete + `LinearPoseTrajInterpolator.h`. Before that, a read-only check on the + robot that `PinocchioDynamics` matches `franka::Model` on live states. ## Open questions +- **Model file**: the URDF the robot reports (`getRobotModel()`), Franka's + public `franka_description` URDF, or the MJCF in `assets/robots/fr3/`. + To be decided by comparing the URDFs of our two FR3s with each other, with + the public one and with the MJCF. - **Ruckig** (MIT community version) as a jerk-limited interpolator: core or an optional extension? It is only an extra `JointInterpolator`, so it can be added later without interface changes. From 13b71796632f5aec081f650fde57f9517a1d0267 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:03:07 -0800 Subject: [PATCH 05/39] docs(control): state that PinocchioDynamics fills ControllerState --- include/rcs/Controller.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/rcs/Controller.h b/include/rcs/Controller.h index 9ca9b742f..2cfd18a06 100644 --- a/include/rcs/Controller.h +++ b/include/rcs/Controller.h @@ -9,8 +9,8 @@ namespace rcs { namespace common { -// Everything a torque controller needs to know about one robot. Filled by the -// backend (MuJoCo or the hardware driver) on every servo tick. +// Everything a torque controller needs to know about one robot. Computed by +// PinocchioDynamics from the measured q and dq on every servo tick. // Cartesian quantities are in the robot base frame, at the TCP. struct ControllerState { VectorXd q; From d2e27454e86405626e8b78705fa0cedc613314e9 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:22:50 -0800 Subject: [PATCH 06/39] docs(control): compensate gravity with the configured payload in sim The sim backend adds PinocchioDynamics gravity for the arm plus the configured payload, as the firmware does, instead of using MuJoCo gravcomp. A wrong tool configuration then acts on the simulated arm as it does on the real robot. Use the FR3 MJCF without armature as the model, which matches the URDF both of our robots report. --- docs/development/controller_interface.md | 61 +++++++++++++++++------- 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index a7650e590..61684bec1 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -53,13 +53,28 @@ policy rate (e.g. 20 Hz) servo rate (sim: model timestep, FR3: 1 kH ### Gravity convention -Controllers return torque **without gravity compensation**, because Franka -compensates gravity in firmware. In sim, MuJoCo's gravity compensation -(`add_gravcomp` in the scene config) plays the part of the firmware, so the -MuJoCo backend doesn't add gravity either. Loads that the real robot doesn't -compensate (e.g. a wrist camera) are excluded with `gravcomp_ignore` and then -act on the arm in both sim and real. Coriolis compensation is the -controller's job, using `state.coriolis`. +Controllers return torque **without gravity compensation**. Gravity is +compensated the way the real robot does it: + +- **Real robot**: the firmware compensates the arm plus the tool configured on + the robot (for Franka: the end effector set in Desk). The backend adds + nothing. +- **Sim**: the backend plays the firmware's part and adds `state.gravity`, + which `PinocchioDynamics` computes from the arm model plus the **configured + payload**. MuJoCo's own gravity compensation is switched off for the + robot's bodies. + +The MuJoCo plant keeps the true gripper bodies. Any gap between the +configured payload and the simulated gripper therefore acts on the arm, as a +wrong tool configuration does on the real robot. Attachments that aren't +part of the payload (e.g. a wrist camera) are not compensated, in sim and on +the real robot alike. + +This is the general rule for any robot that uses the interface: the backend +reproduces what the robot itself does. A robot whose firmware doesn't +compensate gravity has its real backend add `state.gravity` too. + +Coriolis compensation is the controller's job, using `state.coriolis`. ### Threading @@ -134,9 +149,16 @@ class PinocchioDynamics { `jacobian` and `tcp_pose` from the frame at `flange * tcp_offset` (`LOCAL_WORLD_ALIGNED`, i.e. base frame). - `set_payload()` adds the payload to the inertia of the flange body, as - libfranka does with `I_total`, `m_total` and `F_x_Ctotal`. + libfranka does with `I_total`, `m_total` and `F_x_Ctotal`. The payload + enters the mass matrix, Coriolis and gravity. - The model file must contain only the arm. The gripper is part of the payload, so that sim and real describe it the same way. +- **FR3 model file**: `assets/robots/fr3/fr3.xml`, loaded with its joint + armature set to zero. Both of our FR3s report the same URDF through + `getRobotModel()`. It is Franka's public `franka_description` `fr3` (v1) + model, and its link masses, centres of mass, inertias and kinematics are + identical to this MJCF. The MJCF only adds joint armature (rotor inertia), + which the robot's model and `franka::Model` don't have. ## Where the implementations live @@ -160,7 +182,9 @@ class PinocchioDynamics { - On install, the arm actuators are switched to torque mode at runtime, the same way `set_config` already rewrites `gainprm`/`biasprm` (gain 1, bias 0). The torque is clamped to the actuator's `forcerange`/`ctrlrange`. - The scene must use `add_gravcomp` (see the gravity convention). + MuJoCo gravity compensation (`body_gravcomp`) is switched off for the + robot's bodies, and the backend logs that it did (see the gravity + convention). - `Sim` gets a separate **control hook**: `Sim::step` runs `mj_step1 → control hooks → mj_step2 → callbacks`. Control hooks see `qM`, `qfrc_bias` and kinematics that match the current state, which the @@ -168,9 +192,14 @@ class PinocchioDynamics { position as robosuite's `step1 → _pre_action → step2`. `mj_step1`/`mj_step2` support every integrator except RK4. - State: `q`/`dq` from the robot's joints, then - `PinocchioDynamics::compute()`. The payload is configured, e.g. the - Franka Hand. - - `ctrl = step(state)`. Gravity comes from MuJoCo's gravity compensation. + `PinocchioDynamics::compute()`. + - Payload: from the sim robot config, set to the values configured on the + real robot. If none is configured, it defaults to the MJCF bodies + attached after the flange (summed mass, centre of mass and inertia), + i.e. a perfectly configured tool. The backend warns when the configured + payload differs noticeably from those bodies, because then either the + robot's tool configuration or the MJCF gripper is off. + - `ctrl = step(state) + state.gravity`. - The controller's model (Pinocchio) is not exactly the plant (MuJoCo). That is intended: it plays the part of the model error on the real robot. @@ -189,7 +218,9 @@ class PinocchioDynamics { - The bodies of the two `robot.control(...)` lambdas become: take `q`/`dq` from `RobotState`, `PinocchioDynamics::compute()`, `controller->step()`, return the torque. The payload is set from `RobotState` (`I_total`, - `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. + `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. The + backend warns when it differs noticeably from the payload in the robot + config, so that sim and real can be kept equal. - By default `Franka` builds an `FR3JointController` / `FR3OSC` from `FrankaConfig`, so the Python API and configs are unchanged. @@ -217,10 +248,6 @@ is **not** modelled. ## Open questions -- **Model file**: the URDF the robot reports (`getRobotModel()`), Franka's - public `franka_description` URDF, or the MJCF in `assets/robots/fr3/`. - To be decided by comparing the URDFs of our two FR3s with each other, with - the public one and with the MJCF. - **Ruckig** (MIT community version) as a jerk-limited interpolator: core or an optional extension? It is only an extra `JointInterpolator`, so it can be added later without interface changes. From 50057c935a7e03cbabaa8bb4ac68321171c2d8e2 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:23:26 -0800 Subject: [PATCH 07/39] docs(control): run the sim controller in a regular per-step callback With the state coming from PinocchioDynamics, the controller no longer needs MuJoCo quantities from between mj_step1 and mj_step2, so Sim needs no control hook. Clarify the step 3 and step 5 tests. --- docs/development/controller_interface.md | 25 ++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 61684bec1..db6fe185f 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -185,12 +185,15 @@ class PinocchioDynamics { MuJoCo gravity compensation (`body_gravcomp`) is switched off for the robot's bodies, and the backend logs that it did (see the gravity convention). - - `Sim` gets a separate **control hook**: `Sim::step` runs - `mj_step1 → control hooks → mj_step2 → callbacks`. Control hooks see - `qM`, `qfrc_bias` and kinematics that match the current state, which the - existing callbacks (called after integration) don't. That is the same - position as robosuite's `step1 → _pre_action → step2`. `mj_step1`/`mj_step2` - support every integrator except RK4. + - The controller runs in an ordinary `Sim` callback registered with + `seconds_between_calls = 0`, i.e. after every integration step. It reads + `q`/`dq` of the new state and writes `ctrl`, which the next `mj_step` + applies. `Sim` itself doesn't change: the state comes from + `PinocchioDynamics`, so nothing depends on MuJoCo's `qM` or `qfrc_bias` + being current. `ctrl` is also computed once right away on install, and the + callback's `on_restart` (reset, time going backwards) and + `set_joints_hard()` reset the controller and recompute `ctrl`, so no step + runs with a torque from an old state. - State: `q`/`dq` from the robot's joints, then `PinocchioDynamics::compute()`. - Payload: from the sim robot config, set to the values configured on the @@ -236,11 +239,13 @@ is **not** modelled. 1. Spec and interfaces (header only, no behaviour change). 2. Linear interpolators in core, plus pybind and unit tests. -3. `PinocchioDynamics` in core, plus pybind. Test: same mass matrix, Coriolis - and Jacobian as MuJoCo for the same model file. +3. `PinocchioDynamics` in core, plus pybind. Test: same mass matrix, Coriolis, + gravity and Jacobian as MuJoCo for the FR3 model file, with the armature + zeroed on both sides. 4. `JointPD` and `OSC` in core, plus pybind. -5. Control hook in `Sim` and MuJoCo backend in `SimRobot`. Sim tests: hold - under gravity, reach a joint goal, reach a Cartesian goal, switch modes. +5. MuJoCo backend in `SimRobot`, including the payload default and warning. + Sim tests: hold under gravity, reach a joint goal, reach a Cartesian goal, + switch modes, configured payload different from the gripper bodies. 6. `FR3JointController` / `FR3OSC` in core. Sim test with them. 7. `Franka` uses `PinocchioDynamics` and the FR3 controllers; delete `LinearPoseTrajInterpolator.h`. Before that, a read-only check on the From 75204134e99404c1ce9a17c6eea30fe389e0ae56 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:27:04 -0800 Subject: [PATCH 08/39] feat(control): document interpolator timing, allow per-goal duration Segments have a fixed duration and start at the current setpoint. An optional duration on set_goal overrides it for one goal, e.g. for the slow approach when control starts far from the goal. --- include/rcs/Controller.h | 15 ++++++++++----- include/rcs/Interpolator.h | 23 ++++++++++++++++++++--- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/include/rcs/Controller.h b/include/rcs/Controller.h index 2cfd18a06..62895b102 100644 --- a/include/rcs/Controller.h +++ b/include/rcs/Controller.h @@ -2,6 +2,7 @@ #define RCS_CONTROLLER_H #include +#include #include "Pose.h" #include "utils.h" @@ -23,8 +24,9 @@ struct ControllerState { double dt = 0.0; // seconds since the previous step() }; -// Controllers return joint torques WITHOUT gravity compensation. Backends whose -// actuators don't compensate gravity themselves add state.gravity. +// Controllers return joint torques WITHOUT gravity compensation. The backend +// compensates gravity the way the robot does (see the spec in +// docs/development/controller_interface.md). // The interfaces aren't thread-safe: a backend that calls set_goal() and step() // from different threads has to serialise the calls. @@ -33,8 +35,10 @@ class JointController { virtual ~JointController() = default; // Hold the current configuration. virtual void reset(const ControllerState& state) = 0; - // Called at policy rate. - virtual void set_goal(const VectorXd& q_goal) = 0; + // Called at policy rate. duration overrides the interpolator's segment + // duration for this goal only (see JointInterpolator::set_goal). + virtual void set_goal(const VectorXd& q_goal, + std::optional duration = std::nullopt) = 0; // Called at servo rate. Returns joint torques without gravity. virtual VectorXd step(const ControllerState& state) = 0; }; @@ -44,7 +48,8 @@ class CartesianController { virtual ~CartesianController() = default; virtual void reset(const ControllerState& state) = 0; // TCP goal in the robot base frame. - virtual void set_goal(const Pose& pose_goal) = 0; + virtual void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) = 0; virtual VectorXd step(const ControllerState& state) = 0; }; diff --git a/include/rcs/Interpolator.h b/include/rcs/Interpolator.h index fe856d96f..5fc9d062c 100644 --- a/include/rcs/Interpolator.h +++ b/include/rcs/Interpolator.h @@ -1,6 +1,8 @@ #ifndef RCS_INTERPOLATOR_H #define RCS_INTERPOLATOR_H +#include + #include "Pose.h" #include "utils.h" @@ -20,13 +22,27 @@ struct CartesianSetpoint { }; // Turns sparse goals (policy rate) into a smooth setpoint (servo rate). +// +// Timing: every goal starts a segment that takes a fixed duration, set by +// the implementation (typically one policy period, 1 / policy_rate). The +// interpolator counts time only through the dt passed to step(), so it runs +// the same in sim and on hardware. Once the segment is finished, the setpoint +// holds the goal with zero velocity until the next goal arrives. +// +// A new segment starts at the current setpoint, never at the previous goal or +// the measured robot state, so the setpoint doesn't jump when a goal arrives +// before the previous segment is finished. The measured state is only used +// through reset(). class JointInterpolator { public: virtual ~JointInterpolator() = default; // Hold q, with zero velocity. virtual void reset(const VectorXd& q) = 0; - // Start moving from the current setpoint towards q_goal. - virtual void set_goal(const VectorXd& q_goal) = 0; + // Start moving from the current setpoint towards q_goal. duration + // overrides the segment duration for this goal only, e.g. for a slow + // approach when control starts far from the goal. + virtual void set_goal(const VectorXd& q_goal, + std::optional duration = std::nullopt) = 0; // Advance by dt seconds and return the new setpoint. virtual JointSetpoint step(double dt) = 0; }; @@ -35,7 +51,8 @@ class CartesianInterpolator { public: virtual ~CartesianInterpolator() = default; virtual void reset(const Pose& pose) = 0; - virtual void set_goal(const Pose& pose_goal) = 0; + virtual void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) = 0; virtual CartesianSetpoint step(double dt) = 0; }; From f0f959fe0ee3695e9c9de67329d03524da529e56 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:27:04 -0800 Subject: [PATCH 09/39] docs(control): record interpolator timing and open-question decisions Linear interpolators only, 1 ms timestep in torque-controlled sim scenes, segments start at the current setpoint. --- docs/development/controller_interface.md | 46 +++++++++++++++++------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index db6fe185f..008ea67d5 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -92,12 +92,30 @@ struct CartesianSetpoint { Pose pose; Vector6d twist; }; // twist = [v; w], ba class JointInterpolator { virtual void reset(const VectorXd& q) = 0; // hold q, no motion - virtual void set_goal(const VectorXd& q_goal) = 0; // start a new segment from the current setpoint + virtual void set_goal(const VectorXd& q_goal, // start a new segment from the current setpoint + std::optional duration = std::nullopt) = 0; virtual JointSetpoint step(double dt) = 0; // advance by dt, return the setpoint }; class CartesianInterpolator { /* same, with Pose */ }; ``` +Timing: + +- Every goal starts a segment with a fixed duration, set by the + implementation (`LinearJointInterpolator(duration)`), typically one policy + period, `1 / policy_rate`. That is today's FR3 behaviour + (`traj_interpolation_time_fraction = 1.0`). +- The interpolator counts time only through the `dt` passed to `step()`; + progress is `clamp(elapsed / duration, 0, 1)`. When the segment is finished, + the setpoint holds the goal with zero velocity. +- A new segment starts at the **current setpoint**, never at the previous + goal or the measured robot state, so the setpoint doesn't jump when a goal + arrives before the previous segment is finished. The measured state is + only used through `reset()`, when control (re)starts. +- The optional `duration` argument overrides the duration for that one goal. + The FR3 backend uses it for the slow approach when control starts far from + the first goal (`blocking_move_on_start`). + `Controller.h` ```cpp @@ -113,7 +131,8 @@ struct ControllerState { class JointController { virtual void reset(const ControllerState& state) = 0; // hold the current configuration - virtual void set_goal(const VectorXd& q_goal) = 0; + virtual void set_goal(const VectorXd& q_goal, // forwarded to the interpolator + std::optional duration = std::nullopt) = 0; virtual VectorXd step(const ControllerState& state) = 0; // joint torque without gravity }; class CartesianController { /* same, with a Pose goal in the base frame */ }; @@ -169,7 +188,6 @@ class PinocchioDynamics { | `OSC` | core | Decoupled operational-space control with null-space posture: `tau = Jpᵀ Λp (Kp_p e_p + Kd_p (v_d - v)) + Joᵀ Λo (Kp_o e_o + Kd_o (w_d - w)) + N (posture term) + coriolis` | | `PinocchioDynamics` | core | See above. | | `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | -| Ruckig interpolator | open | See open questions. | ## Backends @@ -253,12 +271,16 @@ is **not** modelled. ## Open questions -- **Ruckig** (MIT community version) as a jerk-limited interpolator: core or - an optional extension? It is only an extra `JointInterpolator`, so it can be - added later without interface changes. -- **Timestep**: FR3 runs at 1 kHz, the sim model at 500 Hz (default 2 ms). - Use 1 ms in torque-controlled scenes so gains carry over? -- **Linear interpolator start point**: the current FR3 interpolator starts - each segment at the *previous goal*. The new one starts at the *current - setpoint*, which avoids a setpoint jump when a goal arrives before the last - segment is finished. That is a small behaviour change for FR3. +None at the moment. + +## Decisions + +- **Interpolators**: only linear ones for now. A jerk-limited Ruckig + interpolator would be one more `JointInterpolator` and can be added later + without interface changes. +- **Timestep**: torque-controlled sim scenes use a 1 ms MuJoCo timestep, so + the controller runs at 1 kHz as on the FR3 and gains carry over. +- **Linear interpolator start point**: the current setpoint (see Timing). + The current FR3 interpolator starts each segment at the previous goal, + which jumps when a goal arrives early; this is a small, intended behaviour + change for FR3. From 5ab4063ad20afe165d80e785c2afd5a8d0ad5e1c Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:29:33 -0800 Subject: [PATCH 10/39] feat(control): add linear joint and cartesian interpolators Each goal starts a segment from the current setpoint that moves with constant velocity over a fixed duration, with slerp for the orientation, then holds the goal. Time advances only through the dt passed to step(). --- include/rcs/LinearInterpolator.h | 55 ++++++++++++ python/rcs/_core/common.pyi | 36 ++++++++ python/tests/test_interpolators.py | 138 +++++++++++++++++++++++++++++ src/pybind/rcs.cpp | 37 ++++++++ src/rcs/CMakeLists.txt | 2 +- src/rcs/LinearInterpolator.cpp | 117 ++++++++++++++++++++++++ 6 files changed, 384 insertions(+), 1 deletion(-) create mode 100644 include/rcs/LinearInterpolator.h create mode 100644 python/tests/test_interpolators.py create mode 100644 src/rcs/LinearInterpolator.cpp diff --git a/include/rcs/LinearInterpolator.h b/include/rcs/LinearInterpolator.h new file mode 100644 index 000000000..ba3ce215b --- /dev/null +++ b/include/rcs/LinearInterpolator.h @@ -0,0 +1,55 @@ +#ifndef RCS_LINEAR_INTERPOLATOR_H +#define RCS_LINEAR_INTERPOLATOR_H + +#include + +#include "Interpolator.h" +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// Moves the setpoint on a straight line from the current setpoint to the goal +// with constant velocity, over `duration` seconds, then holds the goal. +class LinearJointInterpolator : public JointInterpolator { + public: + // duration: seconds per segment, typically 1 / policy_rate. + explicit LinearJointInterpolator(double duration); + void reset(const VectorXd& q) override; + void set_goal(const VectorXd& q_goal, + std::optional duration = std::nullopt) override; + JointSetpoint step(double dt) override; + + private: + double default_duration; + double duration = 0.0; // of the current segment + double elapsed = 0.0; // since the start of the current segment + VectorXd start; + VectorXd goal; + VectorXd q; // current setpoint +}; + +// Like LinearJointInterpolator for a TCP pose: straight line for the +// position, slerp for the orientation. +class LinearCartesianInterpolator : public CartesianInterpolator { + public: + explicit LinearCartesianInterpolator(double duration); + void reset(const Pose& pose) override; + void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) override; + CartesianSetpoint step(double dt) override; + + private: + double default_duration; + double duration = 0.0; + double elapsed = 0.0; + bool initialized = false; + Pose start; + Pose goal; + Pose pose; // current setpoint +}; + +} // namespace common +} // namespace rcs +#endif // RCS_LINEAR_INTERPOLATOR_H diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 307ff9ef5..f3659eb87 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -11,6 +11,8 @@ import pybind11_stubgen.typing_ext __all__: list[str] = [ "BaseCameraConfig", + "CartesianInterpolator", + "CartesianSetpoint", "FrankaHandTCPOffset", "GraspType", "Gripper", @@ -25,8 +27,12 @@ __all__: list[str] = [ "IdentityRotMatrix", "IdentityRotQuatVec", "IdentityTranslation", + "JointInterpolator", + "JointSetpoint", "Kinematics", "LATERAL_GRASP", + "LinearCartesianInterpolator", + "LinearJointInterpolator", "POWER_GRASP", "PRECISION_GRASP", "Pin", @@ -52,6 +58,17 @@ class BaseCameraConfig: def __deepcopy__(self, arg0: dict) -> BaseCameraConfig: ... def __init__(self, identifier: str, frame_rate: int, resolution_width: int, resolution_height: int) -> None: ... +class CartesianInterpolator: + def reset(self, pose: Pose) -> None: ... + def set_goal(self, pose_goal: Pose, duration: float | None = None) -> None: ... + def step(self, dt: float) -> CartesianSetpoint: ... + +class CartesianSetpoint: + @property + def pose(self) -> Pose: ... + @property + def twist(self) -> numpy.ndarray[tuple[typing.Literal[6]], numpy.dtype[numpy.float64]]: ... + class GraspType: """ Members: @@ -156,6 +173,19 @@ class HandType: @property def id(self) -> str: ... +class JointInterpolator: + def reset(self, q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]) -> None: ... + def set_goal( + self, q_goal: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], duration: float | None = None + ) -> None: ... + def step(self, dt: float) -> JointSetpoint: ... + +class JointSetpoint: + @property + def dq(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + @property + def q(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + class Kinematics: def __init__(self) -> None: ... def forward(self, q0: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], tcp_offset: Pose = ...) -> Pose: ... @@ -339,6 +369,12 @@ class RotVec: self, ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... +class LinearCartesianInterpolator(CartesianInterpolator): + def __init__(self, duration: float) -> None: ... + +class LinearJointInterpolator(JointInterpolator): + def __init__(self, duration: float) -> None: ... + class Pin(Kinematics): def __init__( self, diff --git a/python/tests/test_interpolators.py b/python/tests/test_interpolators.py new file mode 100644 index 000000000..5e9015dfc --- /dev/null +++ b/python/tests/test_interpolators.py @@ -0,0 +1,138 @@ +import numpy as np +import pytest + +from rcs import common + +DURATION = 0.05 # one policy period at 20 Hz +DT = 0.001 # 1 kHz servo rate +STEPS = round(DURATION / DT) + + +def rot_z(angle: float) -> np.ndarray: + c, s = np.cos(angle), np.sin(angle) + return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) + + +def run(interpolator, steps: int): + setpoint = None + for _ in range(steps): + setpoint = interpolator.step(DT) + return setpoint + + +class TestLinearJointInterpolator: + start = np.zeros(7) + goal = np.linspace(0.1, 0.7, 7) + + def make(self) -> common.LinearJointInterpolator: + interpolator = common.LinearJointInterpolator(DURATION) + interpolator.reset(self.start) + return interpolator + + def test_reset_holds(self): + setpoint = run(self.make(), 10) + assert np.allclose(setpoint.q, self.start) + assert np.allclose(setpoint.dq, 0.0) + + def test_moves_linearly_with_constant_velocity(self): + interpolator = self.make() + interpolator.set_goal(self.goal) + velocity = (self.goal - self.start) / DURATION + half = run(interpolator, STEPS // 2) + assert np.allclose(half.q, (self.start + self.goal) / 2) + assert np.allclose(half.dq, velocity) + + def test_reaches_goal_after_duration_and_holds(self): + interpolator = self.make() + interpolator.set_goal(self.goal) + assert np.allclose(run(interpolator, STEPS).q, self.goal) + held = run(interpolator, 10) + assert np.allclose(held.q, self.goal) + assert np.allclose(held.dq, 0.0) + + def test_new_goal_starts_at_current_setpoint(self): + interpolator = self.make() + interpolator.set_goal(self.goal) + before = run(interpolator, STEPS // 2).q + # back to the start before the first segment is finished + interpolator.set_goal(self.start) + after = interpolator.step(DT) + velocity = (self.start - before) / DURATION + assert np.allclose(after.q, before + velocity * DT) + assert np.allclose(after.dq, velocity) + assert np.allclose(run(interpolator, STEPS).q, self.start) + + def test_duration_override_for_one_goal(self): + interpolator = self.make() + interpolator.set_goal(self.goal, duration=4 * DURATION) + assert np.allclose(run(interpolator, 2 * STEPS).q, (self.start + self.goal) / 2) + assert np.allclose(run(interpolator, 2 * STEPS).q, self.goal) + # the next goal uses the default duration again + interpolator.set_goal(self.start) + assert np.allclose(run(interpolator, STEPS).q, self.start) + + def test_invalid_use_raises(self): + with pytest.raises(ValueError): + common.LinearJointInterpolator(0.0) + with pytest.raises(RuntimeError): + common.LinearJointInterpolator(DURATION).set_goal(self.goal) + with pytest.raises(ValueError): + self.make().set_goal(np.zeros(6)) + + +class TestLinearCartesianInterpolator: + start = common.Pose(rotation=rot_z(0.0), translation=np.array([0.3, 0.0, 0.5])) + goal = common.Pose(rotation=rot_z(0.4), translation=np.array([0.4, -0.1, 0.4])) + + def make(self) -> common.LinearCartesianInterpolator: + interpolator = common.LinearCartesianInterpolator(DURATION) + interpolator.reset(self.start) + return interpolator + + def test_reset_holds(self): + setpoint = run(self.make(), 10) + assert setpoint.pose.is_close(self.start) + assert np.allclose(setpoint.twist, 0.0) + + def test_half_way_and_twist(self): + interpolator = self.make() + interpolator.set_goal(self.goal) + half = run(interpolator, STEPS // 2) + expected = common.Pose(rotation=rot_z(0.2), translation=np.array([0.35, -0.05, 0.45])) + assert half.pose.is_close(expected, eps_r=1e-9, eps_t=1e-9) + linear = (self.goal.translation() - self.start.translation()) / DURATION + angular = np.array([0.0, 0.0, 0.4]) / DURATION + assert np.allclose(half.twist, np.concatenate([linear, angular])) + + def test_reaches_goal_after_duration_and_holds(self): + interpolator = self.make() + interpolator.set_goal(self.goal) + assert run(interpolator, STEPS).pose.is_close(self.goal) + held = run(interpolator, 10) + assert held.pose.is_close(self.goal) + assert np.allclose(held.twist, 0.0) + + def test_rotates_the_short_way(self): + interpolator = self.make() + # 350 degrees about z is -10 degrees the short way round + goal = common.Pose(rotation=rot_z(np.deg2rad(350)), translation=self.start.translation()) + interpolator.set_goal(goal) + half = run(interpolator, STEPS // 2) + assert half.pose.is_close(common.Pose(rotation=rot_z(np.deg2rad(-5)), translation=self.start.translation())) + assert np.allclose(half.twist[3:], [0.0, 0.0, np.deg2rad(-10) / DURATION]) + + def test_new_goal_starts_at_current_setpoint(self): + interpolator = self.make() + interpolator.set_goal(self.goal) + before = run(interpolator, STEPS // 2).pose + interpolator.set_goal(self.start) + after = interpolator.step(DT).pose + # one servo tick moves only a small step away from the current setpoint + assert np.linalg.norm(after.translation() - before.translation()) < 1e-2 + assert run(interpolator, STEPS).pose.is_close(self.start) + + def test_invalid_use_raises(self): + with pytest.raises(ValueError): + common.LinearCartesianInterpolator(-1.0) + with pytest.raises(RuntimeError): + common.LinearCartesianInterpolator(DURATION).step(DT) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index b36004d8a..881e53db1 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -14,6 +14,7 @@ #include "rcs/Camera.h" #include "rcs/Kinematics.h" +#include "rcs/LinearInterpolator.h" #include "rcs/Pose.h" #include "rcs/Robot.h" #include "rcs/utils.h" @@ -409,6 +410,42 @@ PYBIND11_MODULE(_core, m) { py::arg("base_frame") = std::nullopt, py::arg("joint_limits") = std::nullopt); + py::class_(common, "JointSetpoint") + .def_readonly("q", &rcs::common::JointSetpoint::q) + .def_readonly("dq", &rcs::common::JointSetpoint::dq); + + py::class_(common, "CartesianSetpoint") + .def_readonly("pose", &rcs::common::CartesianSetpoint::pose) + .def_readonly("twist", &rcs::common::CartesianSetpoint::twist); + + py::class_>( + common, "JointInterpolator") + .def("reset", &rcs::common::JointInterpolator::reset, py::arg("q")) + .def("set_goal", &rcs::common::JointInterpolator::set_goal, + py::arg("q_goal"), py::arg("duration") = std::nullopt) + .def("step", &rcs::common::JointInterpolator::step, py::arg("dt")); + + py::class_>( + common, "LinearJointInterpolator") + .def(py::init(), py::arg("duration")); + + py::class_>( + common, "CartesianInterpolator") + .def("reset", &rcs::common::CartesianInterpolator::reset, py::arg("pose")) + .def("set_goal", &rcs::common::CartesianInterpolator::set_goal, + py::arg("pose_goal"), py::arg("duration") = std::nullopt) + .def("step", &rcs::common::CartesianInterpolator::step, py::arg("dt")); + + py::class_>( + common, "LinearCartesianInterpolator") + .def(py::init(), py::arg("duration")); + bind_type_class(common, "RobotType") .def_readonly_static("FR3", &rcs::common::RobotType::FR3) .def_readonly_static("Panda", &rcs::common::RobotType::Panda) diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index bd1eb07b1..1922cb752 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/LinearInterpolator.cpp b/src/rcs/LinearInterpolator.cpp new file mode 100644 index 000000000..5373c8fee --- /dev/null +++ b/src/rcs/LinearInterpolator.cpp @@ -0,0 +1,117 @@ +#include "rcs/LinearInterpolator.h" + +#include +#include + +namespace rcs { +namespace common { + +namespace { +double check_duration(double duration) { + if (!(duration > 0.0)) { + throw std::invalid_argument("interpolation duration must be positive"); + } + return duration; +} + +// Fraction of the segment that is done, in [0, 1]. +double progress(double elapsed, double duration) { + return std::clamp(elapsed / duration, 0.0, 1.0); +} + +// Rotation from `from` to `to` as a rotation vector in the base frame, along +// the shortest path. +Eigen::Vector3d rotation_between(const Eigen::Quaterniond& from, + const Eigen::Quaterniond& to) { + Eigen::Quaterniond delta = to * from.inverse(); + if (delta.w() < 0.0) { + delta.coeffs() *= -1.0; // same rotation, shorter way round + } + Eigen::AngleAxisd angle_axis(delta); + return angle_axis.angle() * angle_axis.axis(); +} +} // namespace + +LinearJointInterpolator::LinearJointInterpolator(double duration) + : default_duration(check_duration(duration)) {} + +void LinearJointInterpolator::reset(const VectorXd& q) { + this->q = q; + this->start = q; + this->goal = q; + this->duration = this->default_duration; + this->elapsed = this->duration; // nothing left to do: hold q +} + +void LinearJointInterpolator::set_goal(const VectorXd& q_goal, + std::optional duration) { + if (this->q.size() == 0) { + throw std::logic_error("call reset() before set_goal()"); + } + if (q_goal.size() != this->q.size()) { + throw std::invalid_argument("goal has the wrong number of joints"); + } + this->start = this->q; + this->goal = q_goal; + this->duration = check_duration(duration.value_or(this->default_duration)); + this->elapsed = 0.0; +} + +JointSetpoint LinearJointInterpolator::step(double dt) { + if (this->q.size() == 0) { + throw std::logic_error("call reset() before step()"); + } + this->elapsed += dt; + double t = progress(this->elapsed, this->duration); + this->q = this->start + t * (this->goal - this->start); + VectorXd dq = VectorXd::Zero(this->q.size()); + if (t < 1.0) { + dq = (this->goal - this->start) / this->duration; + } + return {this->q, dq}; +} + +LinearCartesianInterpolator::LinearCartesianInterpolator(double duration) + : default_duration(check_duration(duration)) {} + +void LinearCartesianInterpolator::reset(const Pose& pose) { + this->pose = pose; + this->start = pose; + this->goal = pose; + this->duration = this->default_duration; + this->elapsed = this->duration; + this->initialized = true; +} + +void LinearCartesianInterpolator::set_goal(const Pose& pose_goal, + std::optional duration) { + if (!this->initialized) { + throw std::logic_error("call reset() before set_goal()"); + } + this->start = this->pose; + this->goal = pose_goal; + this->duration = check_duration(duration.value_or(this->default_duration)); + this->elapsed = 0.0; +} + +CartesianSetpoint LinearCartesianInterpolator::step(double dt) { + if (!this->initialized) { + throw std::logic_error("call reset() before step()"); + } + this->elapsed += dt; + double t = progress(this->elapsed, this->duration); + // translation on a straight line, orientation by slerp (shortest path) + this->pose = this->start.interpolate(this->goal, t); + Vector6d twist = Vector6d::Zero(); + if (t < 1.0) { + twist.head<3>() = + (this->goal.translation() - this->start.translation()) / this->duration; + twist.tail<3>() = + rotation_between(this->start.quaternion(), this->goal.quaternion()) / + this->duration; + } + return {this->pose, twist}; +} + +} // namespace common +} // namespace rcs From a4c96a2bca09beb4f754e8555365a8449544aaec Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:33:42 -0800 Subject: [PATCH 11/39] feat(control): add PinocchioDynamics to compute the controller state Computes mass matrix, Coriolis, gravity, TCP Jacobian and TCP pose for one arm like libfranka's franka::Model: the payload is added to the flange body, joint armature is ignored. Matches MuJoCo on the FR3 model to 1e-8. --- include/rcs/PinocchioDynamics.h | 63 ++++++++++++++ python/rcs/_core/common.pyi | 53 ++++++++++++ python/tests/test_pinocchio_dynamics.py | 108 ++++++++++++++++++++++++ src/pybind/rcs.cpp | 51 +++++++++++ src/rcs/CMakeLists.txt | 2 +- src/rcs/PinocchioDynamics.cpp | 100 ++++++++++++++++++++++ 6 files changed, 376 insertions(+), 1 deletion(-) create mode 100644 include/rcs/PinocchioDynamics.h create mode 100644 python/tests/test_pinocchio_dynamics.py create mode 100644 src/rcs/PinocchioDynamics.cpp diff --git a/include/rcs/PinocchioDynamics.h b/include/rcs/PinocchioDynamics.h new file mode 100644 index 000000000..98ae65746 --- /dev/null +++ b/include/rcs/PinocchioDynamics.h @@ -0,0 +1,63 @@ +#ifndef RCS_PINOCCHIO_DYNAMICS_H +#define RCS_PINOCCHIO_DYNAMICS_H + +#include +#include + +#include "Controller.h" +#include "Pose.h" +#include "pinocchio/multibody/data.hpp" +#include "pinocchio/multibody/model.hpp" +#include "utils.h" + +namespace rcs { +namespace common { + +// Load fixed to the flange, e.g. a gripper, expressed in the flange frame. +// Same meaning as libfranka's m_total, F_x_Ctotal and I_total. +struct Payload { + double mass = 0.0; + Eigen::Vector3d com = Eigen::Vector3d::Zero(); + Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero(); // about the CoM +}; + +// Rigid-body dynamics of one arm, used by sim and real alike to fill the +// ControllerState. Computes the same quantities as libfranka's franka::Model, +// which is itself built on Pinocchio. +// +// The model file must contain only the arm, with the robot base at the model +// root. Joint armature (rotor inertia) in the file is ignored, as in +// franka::Model. +class PinocchioDynamics { + public: + // model_path: MJCF or URDF file of the arm. + // flange_frame: frame the payload and the TCP are attached to, e.g. the + // attachment site. + // tcp_offset: TCP relative to the flange. + PinocchioDynamics(const std::string& model_path, bool urdf, + const std::string& flange_frame, + const Pose& tcp_offset = Pose::Identity()); + + void set_payload(const Payload& payload); + Payload get_payload() const; + void set_tcp_offset(const Pose& tcp_offset); + // Gravity acceleration in the robot base frame, default (0, 0, -9.81). + void set_gravity(const Eigen::Vector3d& gravity); + size_t dof() const; + + // All Cartesian quantities are in the robot base frame, at the TCP. + ControllerState compute(const VectorXd& q, const VectorXd& dq, double dt); + + private: + pinocchio::Model model; + pinocchio::Data data; + pinocchio::JointIndex flange_joint; // joint that moves the flange + pinocchio::SE3 flange_placement; // flange in that joint's frame + pinocchio::Inertia arm_inertia; // of that joint's body, no payload + pinocchio::FrameIndex tcp_frame; + Payload payload; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_PINOCCHIO_DYNAMICS_H diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index f3659eb87..54c3ad115 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -13,6 +13,7 @@ __all__: list[str] = [ "BaseCameraConfig", "CartesianInterpolator", "CartesianSetpoint", + "ControllerState", "FrankaHandTCPOffset", "GraspType", "Gripper", @@ -35,7 +36,9 @@ __all__: list[str] = [ "LinearJointInterpolator", "POWER_GRASP", "PRECISION_GRASP", + "Payload", "Pin", + "PinocchioDynamics", "Pose", "RPY", "Robot", @@ -69,6 +72,17 @@ class CartesianSetpoint: @property def twist(self) -> numpy.ndarray[tuple[typing.Literal[6]], numpy.dtype[numpy.float64]]: ... +class ControllerState: + coriolis: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + dq: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + dt: float + gravity: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + jacobian: numpy.ndarray[tuple[typing.Literal[6], M], numpy.dtype[numpy.float64]] + mass: numpy.ndarray[tuple[M, M], numpy.dtype[numpy.float64]] + q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + tcp_pose: Pose + def __init__(self) -> None: ... + class GraspType: """ Members: @@ -193,6 +207,45 @@ class Kinematics: self, pose: Pose, q0: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], tcp_offset: Pose = ... ) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None: ... +class Payload: + com: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] + inertia: numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]] + mass: float + @typing.overload + def __init__(self) -> None: ... + @typing.overload + def __init__( + self, + mass: float, + com: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]], + inertia: numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]], + ) -> None: ... + +class PinocchioDynamics: + def __init__(self, model_path: str, urdf: bool, flange_frame: str, tcp_offset: Pose = ...) -> None: + """ + Rigid-body dynamics of one arm, the same quantities as libfranka's franka::Model. + + Args: + model_path: MJCF or URDF file containing only the arm, robot base at the model root. + Joint armature in the file is ignored. + urdf: Load ``model_path`` as URDF instead of MJCF. + flange_frame: Frame the payload and the TCP are attached to, e.g. the attachment site. + tcp_offset: TCP relative to the flange. + """ + + def compute( + self, + q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + dq: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + dt: float = 0.0, + ) -> ControllerState: ... + def dof(self) -> int: ... + def get_payload(self) -> Payload: ... + def set_gravity(self, gravity: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]]) -> None: ... + def set_payload(self, payload: Payload) -> None: ... + def set_tcp_offset(self, tcp_offset: Pose) -> None: ... + class Pose: def __getstate__(self) -> typing.Annotated[list[float], pybind11_stubgen.typing_ext.FixedSize(16)]: ... @typing.overload diff --git a/python/tests/test_pinocchio_dynamics.py b/python/tests/test_pinocchio_dynamics.py new file mode 100644 index 000000000..7930bceae --- /dev/null +++ b/python/tests/test_pinocchio_dynamics.py @@ -0,0 +1,108 @@ +"""PinocchioDynamics must compute the same dynamics as MuJoCo for the same model.""" + +import mujoco +import numpy as np +import pytest + +import rcs +from rcs import common + +FLANGE = "attachment_site" +TCP_OFFSET = np.array([0.0, 0.0, 0.1493]) +# the end effector configured on our FR3s +PAYLOAD = common.Payload( + mass=0.9, + com=np.array([0.0, 0.0, 0.057]), + inertia=np.diag([0.002768, 0.003149, 0.000564]), +) + + +def fr3_xml() -> str: + return str(rcs.ROBOTS[common.RobotType.FR3].mjcf_model_path) + + +def mujoco_model(payload: common.Payload | None = None) -> mujoco.MjModel: + spec = mujoco.MjSpec.from_file(fr3_xml()) + if payload is not None: + flange = spec.site(FLANGE) + body = spec.body("fr3_link7").add_body(pos=flange.pos, quat=flange.quat) + body.mass = payload.mass + body.ipos = payload.com + i = payload.inertia + body.fullinertia = [i[0, 0], i[1, 1], i[2, 2], i[0, 1], i[0, 2], i[1, 2]] + body.explicitinertial = True + model = spec.compile() + model.dof_armature[:] = 0.0 # PinocchioDynamics ignores armature, like franka::Model + return model + + +def mujoco_state(model: mujoco.MjModel, q: np.ndarray, dq: np.ndarray, tcp_offset: np.ndarray): + data = mujoco.MjData(model) + data.qpos[:] = q + mujoco.mj_forward(model, data) + gravity = data.qfrc_bias.copy() + data.qvel[:] = dq + mujoco.mj_forward(model, data) + coriolis = data.qfrc_bias - gravity + mass = np.zeros((model.nv, model.nv)) + mujoco.mj_fullM(model, data, mass) + + site = model.site(FLANGE).id + rotation = data.site_xmat[site].reshape(3, 3) + tcp = data.site_xpos[site] + rotation @ tcp_offset + jacp, jacr = np.zeros((3, model.nv)), np.zeros((3, model.nv)) + mujoco.mj_jac(model, data, jacp, jacr, tcp, model.site_bodyid[site]) + return mass, gravity, coriolis, np.vstack([jacp, jacr]), tcp, rotation + + +def random_states(model: mujoco.MjModel, n: int = 20): + rng = np.random.default_rng(0) + low, high = model.jnt_range[:7, 0], model.jnt_range[:7, 1] + for _ in range(n): + yield low + (high - low) * rng.random(7), rng.uniform(-2.0, 2.0, 7) + + +@pytest.mark.parametrize("payload", [None, PAYLOAD], ids=["no_payload", "payload"]) +def test_matches_mujoco(payload): + tcp = common.Pose(translation=TCP_OFFSET) + dynamics = common.PinocchioDynamics(fr3_xml(), False, FLANGE, tcp) + if payload is not None: + dynamics.set_payload(payload) + model = mujoco_model(payload) + for q, dq in random_states(model): + state = dynamics.compute(q, dq, 0.001) + mass, gravity, coriolis, jacobian, tcp_pos, tcp_rot = mujoco_state(model, q, dq, TCP_OFFSET) + np.testing.assert_allclose(state.mass, mass, atol=1e-8) + np.testing.assert_allclose(state.gravity, gravity, atol=1e-8) + np.testing.assert_allclose(state.coriolis, coriolis, atol=1e-8) + np.testing.assert_allclose(state.jacobian, jacobian, atol=1e-8) + np.testing.assert_allclose(state.tcp_pose.translation(), tcp_pos, atol=1e-10) + np.testing.assert_allclose(state.tcp_pose.rotation_m(), tcp_rot, atol=1e-10) + assert state.dt == 0.001 + + +def test_gravity_follows_the_configured_direction(): + dynamics = common.PinocchioDynamics(fr3_xml(), False, FLANGE) + q = np.array([0.0, -0.5, 0.0, -2.0, 0.0, 1.5, 0.8]) + down = dynamics.compute(q, np.zeros(7)).gravity + dynamics.set_gravity(np.array([0.0, 0.0, 9.81])) # robot mounted upside down + np.testing.assert_allclose(dynamics.compute(q, np.zeros(7)).gravity, -down, atol=1e-10) + + +def test_payload_can_be_replaced(): + dynamics = common.PinocchioDynamics(fr3_xml(), False, FLANGE) + q, dq = np.array([0.0, -0.5, 0.0, -2.0, 0.0, 1.5, 0.8]), np.zeros(7) + without = dynamics.compute(q, dq).gravity + dynamics.set_payload(PAYLOAD) + assert not np.allclose(dynamics.compute(q, dq).gravity, without) + dynamics.set_payload(common.Payload()) + np.testing.assert_allclose(dynamics.compute(q, dq).gravity, without, atol=1e-12) + + +def test_rejects_wrong_sizes_and_unknown_frame(): + with pytest.raises(RuntimeError): + common.PinocchioDynamics(fr3_xml(), False, "no_such_frame") + dynamics = common.PinocchioDynamics(fr3_xml(), False, FLANGE) + assert dynamics.dof() == 7 + with pytest.raises(ValueError): + dynamics.compute(np.zeros(6), np.zeros(6)) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 881e53db1..358bea886 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -15,6 +15,7 @@ #include "rcs/Camera.h" #include "rcs/Kinematics.h" #include "rcs/LinearInterpolator.h" +#include "rcs/PinocchioDynamics.h" #include "rcs/Pose.h" #include "rcs/Robot.h" #include "rcs/utils.h" @@ -446,6 +447,56 @@ PYBIND11_MODULE(_core, m) { common, "LinearCartesianInterpolator") .def(py::init(), py::arg("duration")); + py::class_(common, "ControllerState") + .def(py::init<>()) + .def_readwrite("q", &rcs::common::ControllerState::q) + .def_readwrite("dq", &rcs::common::ControllerState::dq) + .def_readwrite("mass", &rcs::common::ControllerState::mass) + .def_readwrite("coriolis", &rcs::common::ControllerState::coriolis) + .def_readwrite("gravity", &rcs::common::ControllerState::gravity) + .def_readwrite("jacobian", &rcs::common::ControllerState::jacobian) + .def_readwrite("tcp_pose", &rcs::common::ControllerState::tcp_pose) + .def_readwrite("dt", &rcs::common::ControllerState::dt); + + py::class_(common, "Payload") + .def(py::init<>()) + .def(py::init([](double mass, const Eigen::Vector3d& com, + const Eigen::Matrix3d& inertia) { + return rcs::common::Payload{mass, com, inertia}; + }), + py::arg("mass"), py::arg("com"), py::arg("inertia")) + .def_readwrite("mass", &rcs::common::Payload::mass) + .def_readwrite("com", &rcs::common::Payload::com) + .def_readwrite("inertia", &rcs::common::Payload::inertia); + + py::class_>( + common, "PinocchioDynamics") + .def( + py::init(), + R"doc(Rigid-body dynamics of one arm, the same quantities as libfranka's franka::Model. + +Args: + model_path: MJCF or URDF file containing only the arm, robot base at the model root. + Joint armature in the file is ignored. + urdf: Load ``model_path`` as URDF instead of MJCF. + flange_frame: Frame the payload and the TCP are attached to, e.g. the attachment site. + tcp_offset: TCP relative to the flange. +)doc", + py::arg("model_path"), py::arg("urdf"), py::arg("flange_frame"), + py::arg("tcp_offset") = rcs::common::Pose::Identity()) + .def("set_payload", &rcs::common::PinocchioDynamics::set_payload, + py::arg("payload")) + .def("get_payload", &rcs::common::PinocchioDynamics::get_payload) + .def("set_tcp_offset", &rcs::common::PinocchioDynamics::set_tcp_offset, + py::arg("tcp_offset")) + .def("set_gravity", &rcs::common::PinocchioDynamics::set_gravity, + py::arg("gravity")) + .def("dof", &rcs::common::PinocchioDynamics::dof) + .def("compute", &rcs::common::PinocchioDynamics::compute, py::arg("q"), + py::arg("dq"), py::arg("dt") = 0.0); + bind_type_class(common, "RobotType") .def_readonly_static("FR3", &rcs::common::RobotType::FR3) .def_readonly_static("Panda", &rcs::common::RobotType::Panda) diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index 1922cb752..02da4621b 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/PinocchioDynamics.cpp b/src/rcs/PinocchioDynamics.cpp new file mode 100644 index 000000000..fef31eb8e --- /dev/null +++ b/src/rcs/PinocchioDynamics.cpp @@ -0,0 +1,100 @@ +#include "rcs/PinocchioDynamics.h" + +#include +#include +#include +#include +#include +#include + +namespace rcs { +namespace common { + +PinocchioDynamics::PinocchioDynamics(const std::string& model_path, bool urdf, + const std::string& flange_frame, + const Pose& tcp_offset) { + if (urdf) { + pinocchio::urdf::buildModel(model_path, this->model); + } else { + pinocchio::mjcf::buildModel(model_path, this->model); + } + if (!this->model.existFrame(flange_frame)) { + throw std::runtime_error("frame " + flange_frame + " not found in " + + model_path); + } + // franka::Model has no rotor inertia either + this->model.armature.setZero(); + + const pinocchio::Frame& flange = + this->model.frames[this->model.getFrameId(flange_frame)]; + this->flange_joint = flange.parentJoint; + this->flange_placement = flange.placement; + this->arm_inertia = this->model.inertias[this->flange_joint]; + + this->tcp_frame = this->model.addFrame( + pinocchio::Frame("rcs_tcp", this->flange_joint, this->flange_placement, + pinocchio::OP_FRAME)); + this->data = pinocchio::Data(this->model); + this->set_tcp_offset(tcp_offset); +} + +void PinocchioDynamics::set_payload(const Payload& payload) { + this->payload = payload; + // add the payload to the body that carries the flange, as libfranka does + pinocchio::Inertia load(payload.mass, payload.com, payload.inertia); + this->model.inertias[this->flange_joint] = + this->arm_inertia + this->flange_placement.act(load); +} + +Payload PinocchioDynamics::get_payload() const { return this->payload; } + +void PinocchioDynamics::set_tcp_offset(const Pose& tcp_offset) { + pinocchio::SE3 offset(tcp_offset.rotation_m(), tcp_offset.translation()); + this->model.frames[this->tcp_frame].placement = + this->flange_placement * offset; +} + +void PinocchioDynamics::set_gravity(const Eigen::Vector3d& gravity) { + this->model.gravity.linear(gravity); +} + +size_t PinocchioDynamics::dof() const { return this->model.nv; } + +ControllerState PinocchioDynamics::compute(const VectorXd& q, + const VectorXd& dq, double dt) { + if (q.size() != this->model.nq || dq.size() != this->model.nv) { + throw std::invalid_argument("q and dq must have " + + std::to_string(this->model.nv) + " entries"); + } + ControllerState state; + state.q = q; + state.dq = dq; + state.dt = dt; + + // crba fills only the upper triangle + pinocchio::crba(this->model, this->data, q); + this->data.M.triangularView() = + this->data.M.transpose().triangularView(); + state.mass = this->data.M; + + state.gravity = + pinocchio::computeGeneralizedGravity(this->model, this->data, q); + // rnea with zero acceleration gives Coriolis + gravity + VectorXd zero = VectorXd::Zero(this->model.nv); + state.coriolis = + pinocchio::rnea(this->model, this->data, q, dq, zero) - state.gravity; + + pinocchio::framesForwardKinematics(this->model, this->data, q); + const pinocchio::SE3& tcp = this->data.oMf[this->tcp_frame]; + state.tcp_pose = + Pose(Eigen::Matrix3d(tcp.rotation()), Eigen::Vector3d(tcp.translation())); + + state.jacobian.setZero(6, this->model.nv); + pinocchio::computeFrameJacobian(this->model, this->data, q, this->tcp_frame, + pinocchio::LOCAL_WORLD_ALIGNED, + state.jacobian); + return state; +} + +} // namespace common +} // namespace rcs From 97be0609a05aa8cc7d0cf0186bfb9878c84a369a Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:36:09 -0800 Subject: [PATCH 12/39] refactor(control): share the rotation vector helper Move the shortest-path rotation vector from the linear interpolator to utils.h, so that the OSC can use it too. --- include/rcs/utils.h | 12 ++++++++++++ src/rcs/LinearInterpolator.cpp | 11 ----------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/include/rcs/utils.h b/include/rcs/utils.h index 75ecf41f9..566fd4018 100644 --- a/include/rcs/utils.h +++ b/include/rcs/utils.h @@ -118,6 +118,18 @@ class ThreadSafeFixedBuffer { } }; +// Rotation from `from` to `to` as a rotation vector (axis * angle) in the +// frame both are expressed in, along the shortest path. +inline Eigen::Vector3d rotation_between(const Eigen::Quaterniond& from, + const Eigen::Quaterniond& to) { + Eigen::Quaterniond delta = to * from.inverse(); + if (delta.w() < 0.0) { + delta.coeffs() *= -1.0; // same rotation, shorter way round + } + Eigen::AngleAxisd angle_axis(delta); + return angle_axis.angle() * angle_axis.axis(); +} + } // namespace common } // namespace rcs diff --git a/src/rcs/LinearInterpolator.cpp b/src/rcs/LinearInterpolator.cpp index 5373c8fee..7aa79b3e3 100644 --- a/src/rcs/LinearInterpolator.cpp +++ b/src/rcs/LinearInterpolator.cpp @@ -19,17 +19,6 @@ double progress(double elapsed, double duration) { return std::clamp(elapsed / duration, 0.0, 1.0); } -// Rotation from `from` to `to` as a rotation vector in the base frame, along -// the shortest path. -Eigen::Vector3d rotation_between(const Eigen::Quaterniond& from, - const Eigen::Quaterniond& to) { - Eigen::Quaterniond delta = to * from.inverse(); - if (delta.w() < 0.0) { - delta.coeffs() *= -1.0; // same rotation, shorter way round - } - Eigen::AngleAxisd angle_axis(delta); - return angle_axis.angle() * angle_axis.axis(); -} } // namespace LinearJointInterpolator::LinearJointInterpolator(double duration) From 05ccac84d3e329f574d391217545de2932fcb7fa Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:36:09 -0800 Subject: [PATCH 13/39] feat(control): add JointPD and OSC controllers JointPD is a joint-space PD around the interpolated setpoint with velocity feed-forward. OSC is decoupled operational-space control, critically damped, with a posture task in the dynamically consistent null space. Both add the Coriolis torque. --- include/rcs/Controllers.h | 65 ++++++++++++++++++ python/rcs/_core/common.pyi | 35 ++++++++++ python/tests/test_controllers.py | 109 ++++++++++++++++++++++++++++++ src/pybind/rcs.cpp | 36 ++++++++++ src/rcs/CMakeLists.txt | 2 +- src/rcs/Controllers.cpp | 112 +++++++++++++++++++++++++++++++ 6 files changed, 358 insertions(+), 1 deletion(-) create mode 100644 include/rcs/Controllers.h create mode 100644 python/tests/test_controllers.py create mode 100644 src/rcs/Controllers.cpp diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h new file mode 100644 index 000000000..8423def29 --- /dev/null +++ b/include/rcs/Controllers.h @@ -0,0 +1,65 @@ +#ifndef RCS_CONTROLLERS_H +#define RCS_CONTROLLERS_H + +#include +#include +#include + +#include "Controller.h" +#include "Interpolator.h" +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// Joint-space PD around the interpolated setpoint: +// tau = kp (q_d - q) + kd (dq_d - dq) + coriolis +class JointPD : public JointController { + public: + JointPD(const VectorXd& kp, const VectorXd& kd, + std::shared_ptr interpolator); + void reset(const ControllerState& state) override; + void set_goal(const VectorXd& q_goal, + std::optional duration = std::nullopt) override; + VectorXd step(const ControllerState& state) override; + + private: + VectorXd kp; + VectorXd kd; + std::shared_ptr interpolator; +}; + +struct OSCConfig { + Eigen::Vector3d kp_position = Eigen::Vector3d::Constant(150.0); + Eigen::Vector3d kp_orientation = Eigen::Vector3d::Constant(250.0); + // Posture task in the null space of the TCP task. nullspace_q empty: hold + // the configuration of the last reset(). + double kp_nullspace = 10.0; + VectorXd nullspace_q; +}; + +// Operational-space control (Khatib), position and orientation decoupled, +// critically damped (kd = 2 sqrt(kp)), with a posture task in the null space: +// F = kp e + kd (v_d - v) for position and orientation +// tau = Jp' Lp Fp + Jo' Lo Fo + N' tau_posture + coriolis +// with Lp = (Jp M^-1 Jp')^-1, Lo likewise, and N the dynamically consistent +// null-space projector of the full TCP Jacobian. +class OSC : public CartesianController { + public: + OSC(const OSCConfig& config, + std::shared_ptr interpolator); + void reset(const ControllerState& state) override; + void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) override; + VectorXd step(const ControllerState& state) override; + + private: + OSCConfig config; + VectorXd nullspace_q; + std::shared_ptr interpolator; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_CONTROLLERS_H diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 54c3ad115..df6ada2a3 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -11,6 +11,7 @@ import pybind11_stubgen.typing_ext __all__: list[str] = [ "BaseCameraConfig", + "CartesianController", "CartesianInterpolator", "CartesianSetpoint", "ControllerState", @@ -28,12 +29,16 @@ __all__: list[str] = [ "IdentityRotMatrix", "IdentityRotQuatVec", "IdentityTranslation", + "JointController", "JointInterpolator", + "JointPD", "JointSetpoint", "Kinematics", "LATERAL_GRASP", "LinearCartesianInterpolator", "LinearJointInterpolator", + "OSC", + "OSCConfig", "POWER_GRASP", "PRECISION_GRASP", "Payload", @@ -61,6 +66,11 @@ class BaseCameraConfig: def __deepcopy__(self, arg0: dict) -> BaseCameraConfig: ... def __init__(self, identifier: str, frame_rate: int, resolution_width: int, resolution_height: int) -> None: ... +class CartesianController: + def reset(self, state: ControllerState) -> None: ... + def set_goal(self, pose_goal: Pose, duration: float | None = None) -> None: ... + def step(self, state: ControllerState) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + class CartesianInterpolator: def reset(self, pose: Pose) -> None: ... def set_goal(self, pose_goal: Pose, duration: float | None = None) -> None: ... @@ -187,6 +197,13 @@ class HandType: @property def id(self) -> str: ... +class JointController: + def reset(self, state: ControllerState) -> None: ... + def set_goal( + self, q_goal: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], duration: float | None = None + ) -> None: ... + def step(self, state: ControllerState) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + class JointInterpolator: def reset(self, q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]) -> None: ... def set_goal( @@ -207,6 +224,13 @@ class Kinematics: self, pose: Pose, q0: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], tcp_offset: Pose = ... ) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None: ... +class OSCConfig: + kp_nullspace: float + kp_orientation: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] + kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] + nullspace_q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __init__(self) -> None: ... + class Payload: com: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] inertia: numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]] @@ -422,9 +446,20 @@ class RotVec: self, ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... +class OSC(CartesianController): + def __init__(self, config: OSCConfig, interpolator: CartesianInterpolator) -> None: ... + class LinearCartesianInterpolator(CartesianInterpolator): def __init__(self, duration: float) -> None: ... +class JointPD(JointController): + def __init__( + self, + kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + interpolator: JointInterpolator, + ) -> None: ... + class LinearJointInterpolator(JointInterpolator): def __init__(self, duration: float) -> None: ... diff --git a/python/tests/test_controllers.py b/python/tests/test_controllers.py new file mode 100644 index 000000000..a27a65a60 --- /dev/null +++ b/python/tests/test_controllers.py @@ -0,0 +1,109 @@ +"""Control laws of JointPD and OSC on FR3 states from PinocchioDynamics.""" + +import numpy as np +import pytest + +import rcs +from rcs import common + +DT = 0.001 +Q0 = np.array([0.0, -0.5, 0.0, -2.2, 0.0, 1.8, 0.8]) + + +@pytest.fixture +def dynamics() -> common.PinocchioDynamics: + path = str(rcs.ROBOTS[common.RobotType.FR3].mjcf_model_path) + return common.PinocchioDynamics(path, False, "attachment_site", common.Pose(translation=np.array([0, 0, 0.1]))) + + +def rot_z(angle: float) -> np.ndarray: + c, s = np.cos(angle), np.sin(angle) + return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) + + +class TestJointPD: + kp = np.full(7, 100.0) + kd = np.full(7, 20.0) + + def make(self, state) -> common.JointPD: + controller = common.JointPD(self.kp, self.kd, common.LinearJointInterpolator(0.05)) + controller.reset(state) + return controller + + def test_holds_without_torque_at_rest(self, dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + np.testing.assert_allclose(self.make(state).step(state), 0.0, atol=1e-12) + + def test_pd_law_with_setpoint_velocity_and_coriolis(self, dynamics): + controller = self.make(dynamics.compute(Q0, np.zeros(7), DT)) + goal = Q0 + 0.1 + controller.set_goal(goal) + dq = np.full(7, 0.3) + state = dynamics.compute(Q0, dq, DT) + velocity = (goal - Q0) / 0.05 + expected = self.kp * (Q0 + velocity * DT - Q0) + self.kd * (velocity - dq) + state.coriolis + np.testing.assert_allclose(controller.step(state), expected, atol=1e-10) + + def test_rejects_mismatched_gains(self): + with pytest.raises(ValueError): + common.JointPD(np.ones(7), np.ones(6), common.LinearJointInterpolator(0.05)) + + +class TestOSC: + def make(self, state, **config) -> common.OSC: + cfg = common.OSCConfig() + for key, value in config.items(): + setattr(cfg, key, value) + controller = common.OSC(cfg, common.LinearCartesianInterpolator(0.05)) + controller.reset(state) + return controller + + @staticmethod + def task_acceleration(state, tau) -> np.ndarray: + """TCP acceleration the torque causes at rest (without gravity, Coriolis).""" + return state.jacobian @ np.linalg.solve(state.mass, tau - state.coriolis) + + def test_holds_without_torque_at_rest(self, dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + np.testing.assert_allclose(self.make(state).step(state), 0.0, atol=1e-9) + + def test_position_error_gives_kp_times_error(self, dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + controller = self.make(state) + offset = np.array([0.01, -0.02, 0.005]) + goal = common.Pose(rotation=state.tcp_pose.rotation_m(), translation=state.tcp_pose.translation() + offset) + controller.set_goal(goal, duration=DT) # reached after one step, zero setpoint velocity + acceleration = self.task_acceleration(state, controller.step(state)) + np.testing.assert_allclose(acceleration[:3], 150.0 * offset, atol=1e-9) + + def test_orientation_error_gives_kp_times_error(self, dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + controller = self.make(state) + goal = common.Pose(rotation=rot_z(0.1) @ state.tcp_pose.rotation_m(), translation=state.tcp_pose.translation()) + controller.set_goal(goal, duration=DT) + acceleration = self.task_acceleration(state, controller.step(state)) + np.testing.assert_allclose(acceleration[3:], [0.0, 0.0, 250.0 * 0.1], atol=1e-9) + + def test_damps_tcp_velocity(self, dynamics): + rest = dynamics.compute(Q0, np.zeros(7), DT) + controller = self.make(rest) + # purely linear TCP motion: with position and orientation decoupled, an + # angular velocity error would also act on the linear acceleration + velocity = np.array([0.1, -0.05, 0.08, 0.0, 0.0, 0.0]) + dq = np.linalg.pinv(rest.jacobian) @ velocity + state = dynamics.compute(Q0, dq, DT) + acceleration = self.task_acceleration(state, controller.step(state)) + np.testing.assert_allclose(acceleration[:3], -2.0 * np.sqrt(150.0) * velocity[:3], atol=1e-9) + + def test_posture_task_does_not_move_the_tcp(self, dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + # posture goal away from the current configuration, TCP already at its goal + controller = self.make(state, nullspace_q=Q0 + np.array([0.3, 0, 0.3, 0, 0.3, 0, 0.3]), kp_nullspace=20.0) + tau = controller.step(state) + assert np.linalg.norm(tau) > 0.1 + np.testing.assert_allclose(self.task_acceleration(state, tau), 0.0, atol=1e-9) + + def test_step_before_reset_raises(self, dynamics): + controller = common.OSC(common.OSCConfig(), common.LinearCartesianInterpolator(0.05)) + with pytest.raises(RuntimeError): + controller.step(dynamics.compute(Q0, np.zeros(7), DT)) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 358bea886..5fe3a8e56 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -13,6 +13,7 @@ #include #include "rcs/Camera.h" +#include "rcs/Controllers.h" #include "rcs/Kinematics.h" #include "rcs/LinearInterpolator.h" #include "rcs/PinocchioDynamics.h" @@ -497,6 +498,41 @@ PYBIND11_MODULE(_core, m) { .def("compute", &rcs::common::PinocchioDynamics::compute, py::arg("q"), py::arg("dq"), py::arg("dt") = 0.0); + py::class_>(common, + "JointController") + .def("reset", &rcs::common::JointController::reset, py::arg("state")) + .def("set_goal", &rcs::common::JointController::set_goal, + py::arg("q_goal"), py::arg("duration") = std::nullopt) + .def("step", &rcs::common::JointController::step, py::arg("state")); + + py::class_>( + common, "CartesianController") + .def("reset", &rcs::common::CartesianController::reset, py::arg("state")) + .def("set_goal", &rcs::common::CartesianController::set_goal, + py::arg("pose_goal"), py::arg("duration") = std::nullopt) + .def("step", &rcs::common::CartesianController::step, py::arg("state")); + + py::class_>(common, "JointPD") + .def(py::init>(), + py::arg("kp"), py::arg("kd"), py::arg("interpolator")); + + py::class_(common, "OSCConfig") + .def(py::init<>()) + .def_readwrite("kp_position", &rcs::common::OSCConfig::kp_position) + .def_readwrite("kp_orientation", &rcs::common::OSCConfig::kp_orientation) + .def_readwrite("kp_nullspace", &rcs::common::OSCConfig::kp_nullspace) + .def_readwrite("nullspace_q", &rcs::common::OSCConfig::nullspace_q); + + py::class_>(common, "OSC") + .def(py::init>(), + py::arg("config"), py::arg("interpolator")); + bind_type_class(common, "RobotType") .def_readonly_static("FR3", &rcs::common::RobotType::FR3) .def_readonly_static("Panda", &rcs::common::RobotType::Panda) diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index 02da4621b..7d845bbab 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/Controllers.cpp b/src/rcs/Controllers.cpp new file mode 100644 index 000000000..c21517c92 --- /dev/null +++ b/src/rcs/Controllers.cpp @@ -0,0 +1,112 @@ +#include "rcs/Controllers.h" + +#include +#include +#include + +namespace rcs { +namespace common { + +JointPD::JointPD(const VectorXd& kp, const VectorXd& kd, + std::shared_ptr interpolator) + : kp(kp), kd(kd), interpolator(std::move(interpolator)) { + if (kp.size() != kd.size()) { + throw std::invalid_argument("kp and kd must have the same size"); + } + if (!this->interpolator) { + throw std::invalid_argument("interpolator must not be null"); + } +} + +void JointPD::reset(const ControllerState& state) { + this->interpolator->reset(state.q); +} + +void JointPD::set_goal(const VectorXd& q_goal, std::optional duration) { + this->interpolator->set_goal(q_goal, duration); +} + +VectorXd JointPD::step(const ControllerState& state) { + if (state.q.size() != this->kp.size()) { + throw std::invalid_argument("state has the wrong number of joints"); + } + JointSetpoint setpoint = this->interpolator->step(state.dt); + return this->kp.cwiseProduct(setpoint.q - state.q) + + this->kd.cwiseProduct(setpoint.dq - state.dq) + state.coriolis; +} + +OSC::OSC(const OSCConfig& config, + std::shared_ptr interpolator) + : config(config), interpolator(std::move(interpolator)) { + if (!this->interpolator) { + throw std::invalid_argument("interpolator must not be null"); + } +} + +void OSC::reset(const ControllerState& state) { + this->interpolator->reset(state.tcp_pose); + this->nullspace_q = + this->config.nullspace_q.size() > 0 ? this->config.nullspace_q : state.q; +} + +void OSC::set_goal(const Pose& pose_goal, std::optional duration) { + this->interpolator->set_goal(pose_goal, duration); +} + +VectorXd OSC::step(const ControllerState& state) { + if (this->nullspace_q.size() != state.q.size()) { + throw std::logic_error("call reset() before step()"); + } + CartesianSetpoint setpoint = this->interpolator->step(state.dt); + const Eigen::Index n = state.q.size(); + const auto Jp = state.jacobian.topRows<3>(); + const auto Jo = state.jacobian.bottomRows<3>(); + const Eigen::MatrixXd M_inv = + state.mass.ldlt().solve(Eigen::MatrixXd::Identity(n, n)); + + // desired task-space accelerations + Vector6d velocity = state.jacobian * state.dq; + Eigen::Vector3d kd_position = 2.0 * this->config.kp_position.cwiseSqrt(); + Eigen::Vector3d kd_orientation = + 2.0 * this->config.kp_orientation.cwiseSqrt(); + Eigen::Vector3d position_error = + setpoint.pose.translation() - state.tcp_pose.translation(); + Eigen::Vector3d rotation_error = + rotation_between(state.tcp_pose.quaternion(), setpoint.pose.quaternion()); + Eigen::Vector3d F_position = + this->config.kp_position.cwiseProduct(position_error) + + kd_position.cwiseProduct(setpoint.twist.head<3>() - velocity.head<3>()); + Eigen::Vector3d F_orientation = + this->config.kp_orientation.cwiseProduct(rotation_error) + + kd_orientation.cwiseProduct(setpoint.twist.tail<3>() - + velocity.tail<3>()); + + // decoupled task-space inertias + Eigen::Matrix3d L_position = (Jp * M_inv * Jp.transpose()) + .completeOrthogonalDecomposition() + .pseudoInverse(); + Eigen::Matrix3d L_orientation = (Jo * M_inv * Jo.transpose()) + .completeOrthogonalDecomposition() + .pseudoInverse(); + VectorXd tau = Jp.transpose() * (L_position * F_position) + + Jo.transpose() * (L_orientation * F_orientation); + + // posture task, projected into the null space of the TCP task + Eigen::Matrix L = + (state.jacobian * M_inv * state.jacobian.transpose()) + .completeOrthogonalDecomposition() + .pseudoInverse(); + Eigen::MatrixXd J_bar = M_inv * state.jacobian.transpose() * L; + Eigen::MatrixXd N_transposed = Eigen::MatrixXd::Identity(n, n) - + state.jacobian.transpose() * J_bar.transpose(); + double kd_nullspace = 2.0 * std::sqrt(this->config.kp_nullspace); + VectorXd tau_posture = + state.mass * (this->config.kp_nullspace * (this->nullspace_q - state.q) - + kd_nullspace * state.dq); + tau += N_transposed * tau_posture; + + return tau + state.coriolis; +} + +} // namespace common +} // namespace rcs From 6e9439f8cf5dacb00bc4bf9f8ccae7db79d50e58 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:44:11 -0800 Subject: [PATCH 14/39] fix(control): couple position and orientation in the OSC Use the full 6x6 task-space inertia instead of separate position and orientation inertias. The cross terms of the decoupled form slowed convergence for combined translation and rotation: on a plant equal to the controller model, an 11 cm / 13 degree move took 4 s instead of 1 s. --- docs/development/controller_interface.md | 2 +- include/rcs/Controllers.h | 14 ++++--- python/tests/test_controllers.py | 3 +- src/rcs/Controllers.cpp | 48 ++++++++---------------- 4 files changed, 26 insertions(+), 41 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 008ea67d5..1a5c06b54 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -185,7 +185,7 @@ class PinocchioDynamics { |---|---|---| | `LinearJointInterpolator`, `LinearCartesianInterpolator` | core | Straight line (slerp for rotation) from the current setpoint to the goal over a fixed duration, then hold. Generalises the 7-DoF `LinearPoseTrajInterpolator.h`, which is deleted once FR3 has moved over. | | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | -| `OSC` | core | Decoupled operational-space control with null-space posture: `tau = Jpᵀ Λp (Kp_p e_p + Kd_p (v_d - v)) + Joᵀ Λo (Kp_o e_o + Kd_o (w_d - w)) + N (posture term) + coriolis` | +| `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | | `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h index 8423def29..7d7e01d14 100644 --- a/include/rcs/Controllers.h +++ b/include/rcs/Controllers.h @@ -39,12 +39,14 @@ struct OSCConfig { VectorXd nullspace_q; }; -// Operational-space control (Khatib), position and orientation decoupled, -// critically damped (kd = 2 sqrt(kp)), with a posture task in the null space: -// F = kp e + kd (v_d - v) for position and orientation -// tau = Jp' Lp Fp + Jo' Lo Fo + N' tau_posture + coriolis -// with Lp = (Jp M^-1 Jp')^-1, Lo likewise, and N the dynamically consistent -// null-space projector of the full TCP Jacobian. +// Operational-space control (Khatib), critically damped (kd = 2 sqrt(kp)), +// with a posture task in the null space: +// F = kp e + kd (v_d - v) e: position and rotation error +// tau = J' L F + N' tau_posture + coriolis +// with the task-space inertia L = (J M^-1 J')^-1 and N the dynamically +// consistent null-space projector. Position and orientation are coupled +// through L, so the TCP follows the setpoint as a decoupled second-order +// system when the model is exact. class OSC : public CartesianController { public: OSC(const OSCConfig& config, diff --git a/python/tests/test_controllers.py b/python/tests/test_controllers.py index a27a65a60..2a48d97c3 100644 --- a/python/tests/test_controllers.py +++ b/python/tests/test_controllers.py @@ -87,8 +87,7 @@ def test_orientation_error_gives_kp_times_error(self, dynamics): def test_damps_tcp_velocity(self, dynamics): rest = dynamics.compute(Q0, np.zeros(7), DT) controller = self.make(rest) - # purely linear TCP motion: with position and orientation decoupled, an - # angular velocity error would also act on the linear acceleration + # purely linear TCP motion velocity = np.array([0.1, -0.05, 0.08, 0.0, 0.0, 0.0]) dq = np.linalg.pinv(rest.jacobian) @ velocity state = dynamics.compute(Q0, dq, DT) diff --git a/src/rcs/Controllers.cpp b/src/rcs/Controllers.cpp index c21517c92..3a752d28d 100644 --- a/src/rcs/Controllers.cpp +++ b/src/rcs/Controllers.cpp @@ -59,46 +59,30 @@ VectorXd OSC::step(const ControllerState& state) { } CartesianSetpoint setpoint = this->interpolator->step(state.dt); const Eigen::Index n = state.q.size(); - const auto Jp = state.jacobian.topRows<3>(); - const auto Jo = state.jacobian.bottomRows<3>(); + const auto& J = state.jacobian; const Eigen::MatrixXd M_inv = state.mass.ldlt().solve(Eigen::MatrixXd::Identity(n, n)); - // desired task-space accelerations - Vector6d velocity = state.jacobian * state.dq; - Eigen::Vector3d kd_position = 2.0 * this->config.kp_position.cwiseSqrt(); - Eigen::Vector3d kd_orientation = - 2.0 * this->config.kp_orientation.cwiseSqrt(); - Eigen::Vector3d position_error = - setpoint.pose.translation() - state.tcp_pose.translation(); - Eigen::Vector3d rotation_error = + // desired TCP acceleration: critically damped spring to the setpoint + Vector6d kp; + kp << this->config.kp_position, this->config.kp_orientation; + Vector6d kd = 2.0 * kp.cwiseSqrt(); + Vector6d error; + error << setpoint.pose.translation() - state.tcp_pose.translation(), rotation_between(state.tcp_pose.quaternion(), setpoint.pose.quaternion()); - Eigen::Vector3d F_position = - this->config.kp_position.cwiseProduct(position_error) + - kd_position.cwiseProduct(setpoint.twist.head<3>() - velocity.head<3>()); - Eigen::Vector3d F_orientation = - this->config.kp_orientation.cwiseProduct(rotation_error) + - kd_orientation.cwiseProduct(setpoint.twist.tail<3>() - - velocity.tail<3>()); + Vector6d F = + kp.cwiseProduct(error) + kd.cwiseProduct(setpoint.twist - J * state.dq); - // decoupled task-space inertias - Eigen::Matrix3d L_position = (Jp * M_inv * Jp.transpose()) - .completeOrthogonalDecomposition() - .pseudoInverse(); - Eigen::Matrix3d L_orientation = (Jo * M_inv * Jo.transpose()) + // task-space inertia + Eigen::Matrix L = (J * M_inv * J.transpose()) .completeOrthogonalDecomposition() .pseudoInverse(); - VectorXd tau = Jp.transpose() * (L_position * F_position) + - Jo.transpose() * (L_orientation * F_orientation); + VectorXd tau = J.transpose() * (L * F); - // posture task, projected into the null space of the TCP task - Eigen::Matrix L = - (state.jacobian * M_inv * state.jacobian.transpose()) - .completeOrthogonalDecomposition() - .pseudoInverse(); - Eigen::MatrixXd J_bar = M_inv * state.jacobian.transpose() * L; - Eigen::MatrixXd N_transposed = Eigen::MatrixXd::Identity(n, n) - - state.jacobian.transpose() * J_bar.transpose(); + // posture task, projected into the dynamically consistent null space + Eigen::MatrixXd J_bar = M_inv * J.transpose() * L; + Eigen::MatrixXd N_transposed = + Eigen::MatrixXd::Identity(n, n) - J.transpose() * J_bar.transpose(); double kd_nullspace = 2.0 * std::sqrt(this->config.kp_nullspace); VectorXd tau_posture = state.mass * (this->config.kp_nullspace * (this->nullspace_q - state.q) - From 3324b73fdc560fa7bfb587b25d2973665ab0494b Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:44:26 -0800 Subject: [PATCH 15/39] feat(sim): torque control of SimRobot with the shared controllers With PinocchioDynamics and a joint and/or Cartesian controller installed, the arm actuators become motors and a per-step callback applies the controller torque plus gravity from the configured payload, as the firmware does. MuJoCo gravity compensation is switched off for the robot. Without a configured payload the MJCF bodies after the flange are used, and a configured payload that differs from them is reported. --- docs/development/controller_interface.md | 17 +- python/rcs/_core/sim.pyi | 14 ++ python/tests/test_sim_torque_control.py | 158 +++++++++++++++ src/pybind/rcs.cpp | 15 +- src/sim/SimRobot.cpp | 232 ++++++++++++++++++++++- src/sim/SimRobot.h | 31 +++ 6 files changed, 461 insertions(+), 6 deletions(-) create mode 100644 python/tests/test_sim_torque_control.py diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 1a5c06b54..be09d7dd1 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -193,9 +193,12 @@ class PinocchioDynamics { ### MuJoCo (`SimRobot`) -- New: `set_joint_controller(shared_ptr)` and +- New: `set_dynamics(shared_ptr)`, then + `set_joint_controller(shared_ptr)` and/or `set_cartesian_controller(shared_ptr)`. Without a controller, `SimRobot` behaves exactly as today (native MuJoCo PD). + Installing a controller switches the arm to torque control for good and + makes it hold its current configuration. - With a controller installed: - On install, the arm actuators are switched to torque mode at runtime, the same way `set_config` already rewrites `gainprm`/`biasprm` (gain 1, @@ -213,7 +216,10 @@ class PinocchioDynamics { `set_joints_hard()` reset the controller and recompute `ctrl`, so no step runs with a torque from an old state. - State: `q`/`dq` from the robot's joints, then - `PinocchioDynamics::compute()`. + `PinocchioDynamics::compute()`. Gravity is set in the robot base frame + from the base orientation in the world, because arms can be mounted + tilted (the right arm of our duo is tilted by about 52°, as fitted from + its logged torques). - Payload: from the sim robot config, set to the values configured on the real robot. If none is configured, it defaults to the MJCF bodies attached after the flange (summed mass, centre of mass and inertia), @@ -226,8 +232,11 @@ class PinocchioDynamics { robot. - `set_joint_position(q)` goes to the joint controller if one is installed. `set_cartesian_position(pose)` goes to the Cartesian controller if one is - installed, otherwise IK and the joint path as today. Switching between - the two calls `reset()` on the newly active controller. + installed, otherwise IK and the joint path as today. With only a + Cartesian controller, `set_joint_position(q)` moves the TCP to the pose + that `q` gives. Switching between the two calls `reset()` on the newly + active controller. `kp`/`kv` in the config are rejected under torque + control. - The convergence callback (`step_until_convergence`) compares the TCP pose instead of joint angles while a Cartesian controller is active. diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index ca800634e..ab358aac5 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -182,8 +182,12 @@ class SimRobot(rcs._core.common.Robot): ) -> None: ... def clear_collision_flag(self) -> None: ... def get_config(self) -> SimRobotConfig: ... + def get_simulated_payload(self) -> rcs._core.common.Payload: ... def get_state(self) -> SimRobotState: ... + def set_cartesian_controller(self, controller: rcs._core.common.CartesianController) -> None: ... def set_config(self, cfg: SimRobotConfig) -> bool: ... + def set_dynamics(self, dynamics: rcs._core.common.PinocchioDynamics) -> None: ... + def set_joint_controller(self, controller: rcs._core.common.JointController) -> None: ... def set_joints_hard(self, q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]) -> None: ... class SimRobotConfig(rcs._core.common.RobotConfig[M]): @@ -259,6 +263,14 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): @kv.setter def kv(self, arg0: list[float] | None) -> None: ... + @property + def payload(self) -> rcs._core.common.Payload | None: + """ + Tool as configured on the real robot, used for gravity compensation under torque control; None uses the MJCF bodies after the flange + """ + + @payload.setter + def payload(self, arg0: rcs._core.common.Payload | None) -> None: ... class SimRobotState(rcs._core.common.RobotState): def __init__(self) -> None: ... @@ -276,6 +288,8 @@ class SimRobotState(rcs._core.common.RobotState): def previous_angles(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... @property def target_angles(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + @property + def target_pose(self) -> rcs._core.common.Pose: ... class SimTilburgHand(rcs._core.common.Hand): def __init__(self, sim: Sim, cfg: SimTilburgHandConfig) -> None: ... diff --git a/python/tests/test_sim_torque_control.py b/python/tests/test_sim_torque_control.py new file mode 100644 index 000000000..ad6862e02 --- /dev/null +++ b/python/tests/test_sim_torque_control.py @@ -0,0 +1,158 @@ +"""SimRobot under torque control with the shared controllers (1 ms timestep).""" + +import numpy as np +import pytest +from rcs.envs.configs import EmptyWorldFR3 + +import rcs +from rcs import common, sim + +TIMESTEP = 0.001 +POLICY_PERIOD = 0.05 +# the FR3 joint impedance gains from FrankaConfig +KP = np.array([100.0, 100.0, 100.0, 100.0, 75.0, 150.0, 50.0]) +KD = np.array([20.0, 20.0, 20.0, 20.0, 7.5, 15.0, 5.0]) + + +class Setup: + def __init__(self, payload: common.Payload | None = None, friction: bool = True): + scene = EmptyWorldFR3() + cfg = scene.prefixed_cfg(scene.config()) + name = scene.lead_robot_name(cfg) + robot_cfg = cfg.robot_cfgs[name] + robot_cfg.payload = payload + model = scene.create_model(cfg) + model.spec.option.timestep = TIMESTEP + if not friction: + for joint in model.spec.joints: + joint.frictionloss = 0.0 + self.sim = sim.Sim(model, sim.SimConfig(async_control=True)) + path, site = scene.kinematics_cfg(cfg)[name] + ik = common.Pin(path, site, joint_limits=robot_cfg.joint_limits) + self.robot = sim.SimRobot(self.sim, ik, robot_cfg) + self.robot.set_dynamics(common.PinocchioDynamics(path, False, site)) + self.sim.step(1) + + def joint_pd(self) -> common.JointPD: + controller = common.JointPD(KP, KD, common.LinearJointInterpolator(POLICY_PERIOD)) + self.robot.set_joint_controller(controller) + return controller + + def osc(self) -> common.OSC: + controller = common.OSC(common.OSCConfig(), common.LinearCartesianInterpolator(POLICY_PERIOD)) + self.robot.set_cartesian_controller(controller) + return controller + + def run(self, seconds: float): + self.sim.step(round(seconds / TIMESTEP)) + + +def pose_error(a: common.Pose, b: common.Pose) -> tuple[float, float]: + rotation = a.rotation_m().T @ b.rotation_m() + angle = np.degrees(np.arccos(np.clip((np.trace(rotation) - 1) / 2, -1, 1))) + return float(np.linalg.norm(a.translation() - b.translation())), float(angle) + + +def test_simulated_payload_is_the_gripper(): + setup = Setup() + payload = setup.robot.get_simulated_payload() + # the Franka Hand with its fingers + assert 0.5 < payload.mass < 1.2 + assert 0.0 < payload.com[2] < 0.1 # in front of the flange + assert np.allclose(payload.inertia, payload.inertia.T) + + +def test_joint_pd_holds_under_gravity(): + setup = Setup() + q0 = setup.robot.get_joint_position() + setup.joint_pd() + setup.run(1.0) + assert np.max(np.abs(setup.robot.get_joint_position() - q0)) < 1e-3 + + +def test_joint_pd_reaches_goal(): + setup = Setup() + setup.joint_pd() + goal = setup.robot.get_joint_position() + np.array([0.2, -0.1, 0.1, 0.2, -0.2, 0.1, 0.3]) + setup.robot.set_joint_position(goal) + setup.run(2.0) + # joint friction in the model leaves a small steady-state error + assert np.max(np.abs(setup.robot.get_joint_position() - goal)) < 0.02 + + +@pytest.mark.parametrize( + "friction, max_error_m, max_error_deg", + # joint friction (frictionloss in the MJCF) stops the arm short of the goal, + # as on the real robot. Without it the position converges exactly; the + # orientation keeps a small offset because the rotational stiffness at the + # wrist is low and the fingers are not rigid like the payload model. + [(False, 1e-4, 0.5), (True, 0.015, 3.0)], + ids=["no_friction", "friction"], +) +def test_osc_holds_and_reaches_goal(friction, max_error_m, max_error_deg): + setup = Setup(friction=friction) + start = setup.robot.get_cartesian_position() + setup.osc() + setup.run(1.0) + held = pose_error(setup.robot.get_cartesian_position(), start) + assert held[0] < 2e-3 and held[1] < 0.5 + + goal = common.Pose( + rotation=start.rotation_m() @ common.RPY(0.1, -0.1, 0.2).rotation_matrix(), + translation=start.translation() + np.array([0.05, -0.08, -0.06]), + ) + setup.robot.set_cartesian_position(goal) + setup.run(2.0) + reached = pose_error(setup.robot.get_cartesian_position(), goal) + assert reached[0] < max_error_m and reached[1] < max_error_deg + + +def test_switching_between_controllers(): + setup = Setup(friction=False) + setup.joint_pd() + setup.osc() + start = setup.robot.get_cartesian_position() + goal = common.Pose(rotation=start.rotation_m(), translation=start.translation() + np.array([0.0, 0.05, 0.0])) + setup.robot.set_cartesian_position(goal) + setup.run(1.5) + assert pose_error(setup.robot.get_cartesian_position(), goal)[0] < 1e-3 + + q_goal = setup.robot.get_joint_position() + 0.1 + setup.robot.set_joint_position(q_goal) # back to the joint controller + setup.run(1.5) + assert np.max(np.abs(setup.robot.get_joint_position() - q_goal)) < 1e-3 + + +def test_wrong_payload_acts_on_the_arm(): + reference = Setup() # keep the Sim alive, it owns the MuJoCo model + simulated = reference.robot.get_simulated_payload() + heavier = common.Payload(mass=simulated.mass + 1.0, com=simulated.com, inertia=simulated.inertia) + errors = {} + for name, payload in [("correct", None), ("wrong", heavier)]: + setup = Setup(payload) + q0 = setup.robot.get_joint_position() + setup.joint_pd() + setup.run(1.0) + errors[name] = np.max(np.abs(setup.robot.get_joint_position() - q0)) + # 1 kg too much compensation lifts the arm, as a wrong Desk setting would + assert errors["wrong"] > 10 * errors["correct"] + + +def test_set_joints_hard_holds_the_new_configuration(): + setup = Setup() + setup.joint_pd() + q = setup.robot.get_joint_position() + 0.2 + setup.robot.set_joints_hard(q) + setup.run(0.5) + assert np.max(np.abs(setup.robot.get_joint_position() - q)) < 1e-2 + + +def test_controller_needs_dynamics(): + scene = EmptyWorldFR3() + cfg = scene.prefixed_cfg(scene.config()) + name = scene.lead_robot_name(cfg) + simulation = sim.Sim(scene.create_model(cfg), sim.SimConfig()) + path, site = scene.kinematics_cfg(cfg)[name] + robot = sim.SimRobot(simulation, common.Pin(path, site), cfg.robot_cfgs[name]) + with pytest.raises(RuntimeError): + robot.set_joint_controller(common.JointPD(KP, KD, common.LinearJointInterpolator(POLICY_PERIOD))) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 5fe3a8e56..10c7280c7 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -783,6 +783,11 @@ PYBIND11_MODULE(_core, m) { "kv", &rcs::sim::SimRobotConfig::kv, "Per-joint velocity gains; None uses the MuJoCo XML values") .def_readwrite("base", &rcs::sim::SimRobotConfig::base) + .def_readwrite( + "payload", &rcs::sim::SimRobotConfig::payload, + "Tool as configured on the real robot, used for gravity " + "compensation under torque control; None uses the MJCF bodies " + "after the flange") .def_readwrite("dof", &rcs::sim::SimRobotConfig::dof) .def_readwrite("joint_limits", &rcs::sim::SimRobotConfig::joint_limits) .def("__copy__", @@ -800,6 +805,7 @@ PYBIND11_MODULE(_core, m) { .def_readonly("previous_angles", &rcs::sim::SimRobotState::previous_angles) .def_readonly("target_angles", &rcs::sim::SimRobotState::target_angles) + .def_readonly("target_pose", &rcs::sim::SimRobotState::target_pose) .def_readonly("inverse_tcp_offset", &rcs::sim::SimRobotState::inverse_tcp_offset) .def_readonly("ik_success", &rcs::sim::SimRobotState::ik_success) @@ -1002,7 +1008,14 @@ PYBIND11_MODULE(_core, m) { .def("set_joints_hard", &rcs::sim::SimRobot::set_joints_hard, py::arg("q")) .def("clear_collision_flag", &rcs::sim::SimRobot::clear_collision_flag) - .def("get_state", &rcs::sim::SimRobot::get_state); + .def("get_state", &rcs::sim::SimRobot::get_state) + .def("set_dynamics", &rcs::sim::SimRobot::set_dynamics, + py::arg("dynamics")) + .def("set_joint_controller", &rcs::sim::SimRobot::set_joint_controller, + py::arg("controller")) + .def("set_cartesian_controller", + &rcs::sim::SimRobot::set_cartesian_controller, py::arg("controller")) + .def("get_simulated_payload", &rcs::sim::SimRobot::get_simulated_payload); // SimTilburgHandState py::class_( diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index 6e785cee7..39f27988c 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -102,6 +102,12 @@ void SimRobot::init_ids() { bool SimRobot::set_config(const SimRobotConfig& cfg) { this->cfg = cfg; this->state.inverse_tcp_offset = cfg.tcp_offset.inverse(); + if (this->dynamics) { + this->configure_dynamics(); + } + if (this->torque_control && cfg.kp.has_value()) { + throw std::runtime_error("kp/kv have no effect under torque control"); + } if (cfg.kp.has_value() != cfg.kv.has_value()) throw std::runtime_error("kp and kv must both be set or unset"); if (cfg.kp.has_value()) { @@ -147,10 +153,24 @@ common::Pose SimRobot::get_cartesian_flange_position() { } void SimRobot::set_joint_position(const common::VectorXd& q) { + if (this->torque_control && !this->joint_controller) { + // only a Cartesian controller: move the TCP to where q would put it + this->set_cartesian_position( + this->dynamics->compute(q, common::VectorXd::Zero(q.size()), 0.0) + .tcp_pose); + return; + } this->state.target_angles = q; this->state.previous_angles = this->get_joint_position(); this->state.is_moving = true; this->state.is_arrived = false; + if (this->torque_control) { + if (this->control_mode != ControlMode::joint) { + this->activate(ControlMode::joint); + } + this->joint_controller->set_goal(q); + return; + } for (size_t i = 0; i < std::size(this->ids.actuators); ++i) { this->sim->d->ctrl[this->ids.actuators[i]] = q[i]; } @@ -174,6 +194,18 @@ std::optional> SimRobot::get_ik() { void SimRobot::set_cartesian_position(const common::Pose& pose) { // pose is assumed to be in the robots coordinate frame + if (this->cartesian_controller) { + this->state.target_pose = pose; + this->state.previous_angles = this->get_joint_position(); + this->state.ik_success = true; + this->state.is_moving = true; + this->state.is_arrived = false; + if (this->control_mode != ControlMode::cartesian) { + this->activate(ControlMode::cartesian); + } + this->cartesian_controller->set_goal(pose); + return; + } auto joint_vals = this->m_ik->inverse(pose, this->get_joint_position(), this->cfg.tcp_offset); if (joint_vals.has_value()) { @@ -193,6 +225,12 @@ void SimRobot::is_moving_callback() { } void SimRobot::is_arrived_callback() { + if (this->control_mode == ControlMode::cartesian) { + // TCP within 1 mm and 1 degree of the goal + this->state.is_arrived = this->get_cartesian_position().is_close( + this->state.target_pose, std::numbers::pi / 180.0, 1e-3); + return; + } common::VectorXd current_angles = this->get_joint_position(); this->state.is_arrived = (current_angles - this->state.target_angles).cwiseAbs().maxCoeff() < @@ -241,7 +279,14 @@ void SimRobot::set_joints_hard(const common::VectorXd& q) { size_t jnt_id = this->ids.joints[i]; size_t jnt_qposadr = this->sim->m->jnt_qposadr[jnt_id]; this->sim->d->qpos[jnt_qposadr] = q[i]; - this->sim->d->ctrl[this->ids.actuators[i]] = q[i]; + if (!this->torque_control) { + this->sim->d->ctrl[this->ids.actuators[i]] = q[i]; + } + } + if (this->torque_control) { + // hold the new configuration instead of the old setpoint + this->activate(this->control_mode); + this->control_step(0.0); } } @@ -254,5 +299,190 @@ common::Pose SimRobot::get_base_pose_in_world_coordinates() { } void SimRobot::reset() { this->m_reset(); } + +void SimRobot::set_dynamics( + std::shared_ptr dynamics) { + if (dynamics->dof() != std::size(this->ids.joints)) { + throw std::invalid_argument( + "dynamics model and robot have a different number of joints"); + } + this->dynamics = dynamics; + this->configure_dynamics(); +} + +void SimRobot::configure_dynamics() { + this->dynamics->set_tcp_offset(this->cfg.tcp_offset); + common::Payload simulated = this->get_simulated_payload(); // runs kinematics + // gravity in the robot base frame, for robots that are mounted tilted + Eigen::Map gravity_world(this->sim->m->opt.gravity); + this->dynamics->set_gravity( + this->get_base_pose_in_world_coordinates().rotation_m().transpose() * + gravity_world); + if (!this->cfg.payload.has_value()) { + this->dynamics->set_payload(simulated); + return; + } + const common::Payload& configured = this->cfg.payload.value(); + this->dynamics->set_payload(configured); + // a gap acts on the arm like a wrong tool configuration on the real robot + if (std::abs(configured.mass - simulated.mass) > 0.05 || + (configured.com - simulated.com).norm() > 0.01) { + std::cerr << "Warning: the configured payload (" << configured.mass + << " kg, CoM " << configured.com.transpose() + << ") differs from the simulated bodies after the flange (" + << simulated.mass << " kg, CoM " << simulated.com.transpose() + << ")." << std::endl; + } +} + +common::Payload SimRobot::get_simulated_payload() { + mjModel* m = this->sim->m; + mjData* d = this->sim->d; + mj_kinematics(m, d); + int flange_body = m->site_bodyid[this->ids.attachment_site]; + // all bodies in the subtree below the flange body + double mass = 0.0; + Eigen::Vector3d moment = Eigen::Vector3d::Zero(); + std::vector bodies; + for (int b = flange_body + 1; b < m->nbody; ++b) { + int parent = m->body_parentid[b]; + while (parent != 0 && parent != flange_body) { + parent = m->body_parentid[parent]; + } + if (parent == flange_body) { + bodies.push_back(b); + mass += m->body_mass[b]; + moment += m->body_mass[b] * Eigen::Map(d->xipos + 3 * b); + } + } + common::Payload payload; + if (mass <= 0.0) { + return payload; + } + Eigen::Vector3d com = moment / mass; + Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero(); // about com, world axes + for (int b : bodies) { + Eigen::Matrix R(d->ximat + 9 * b); + Eigen::Vector3d r = Eigen::Map(d->xipos + 3 * b) - com; + inertia += + R * Eigen::Map(m->body_inertia + 3 * b).asDiagonal() * + R.transpose() + + m->body_mass[b] * + (r.squaredNorm() * Eigen::Matrix3d::Identity() - r * r.transpose()); + } + // express in the flange frame + Eigen::Matrix R_flange( + d->site_xmat + 9 * this->ids.attachment_site); + Eigen::Vector3d p_flange(d->site_xpos + 3 * this->ids.attachment_site); + payload.mass = mass; + payload.com = R_flange.transpose() * (com - p_flange); + payload.inertia = R_flange.transpose() * inertia * R_flange; + return payload; +} + +void SimRobot::set_joint_controller( + std::shared_ptr controller) { + this->joint_controller = controller; + this->enable_torque_control(); + this->activate(ControlMode::joint); + this->control_step(0.0); +} + +void SimRobot::set_cartesian_controller( + std::shared_ptr controller) { + this->cartesian_controller = controller; + this->enable_torque_control(); + this->activate(ControlMode::cartesian); + this->state.target_pose = this->get_cartesian_position(); + this->control_step(0.0); +} + +void SimRobot::enable_torque_control() { + if (!this->dynamics) { + throw std::logic_error( + "call set_dynamics() before installing a controller"); + } + if (this->torque_control) { + return; + } + mjModel* m = this->sim->m; + // actuators: position servos -> motors, limited to the joint torque range + for (size_t i = 0; i < std::size(this->ids.actuators); ++i) { + int act = this->ids.actuators[i]; + int jnt = this->ids.joints[i]; + m->actuator_gaintype[act] = mjGAIN_FIXED; + m->actuator_biastype[act] = mjBIAS_NONE; + std::fill_n(m->actuator_gainprm + act * mjNGAIN, mjNGAIN, 0.0); + std::fill_n(m->actuator_biasprm + act * mjNBIAS, mjNBIAS, 0.0); + m->actuator_gainprm[act * mjNGAIN] = 1.0; + m->actuator_ctrllimited[act] = m->jnt_actfrclimited[jnt]; + m->actuator_ctrlrange[2 * act] = m->jnt_actfrcrange[2 * jnt]; + m->actuator_ctrlrange[2 * act + 1] = m->jnt_actfrcrange[2 * jnt + 1]; + m->jnt_actgravcomp[jnt] = 0; + } + // gravity is compensated from the configured payload, as by the firmware + size_t compensated = 0; + for (int b = this->ids.base; b < m->nbody; ++b) { + int parent = b; + while (parent != 0 && parent != this->ids.base) { + parent = m->body_parentid[parent]; + } + if (parent == this->ids.base && m->body_gravcomp[b] != 0) { + m->body_gravcomp[b] = 0; + compensated++; + } + } + if (compensated > 0) { + std::cerr << "Torque control: switched off MuJoCo gravity compensation of " + << compensated << " bodies of robot " << this->cfg.base + << std::endl; + } + this->torque_control = true; + // after every physics step; on a restart (reset, time going backwards) + // hold the configuration the robot is in now + this->sim->register_cb( + [this]() { this->control_step(this->sim->m->opt.timestep); }, 0.0, + [this]() { + this->activate(this->control_mode); + this->control_step(0.0); + }); +} + +void SimRobot::activate(ControlMode mode) { + common::ControllerState state = this->controller_state(0.0); + if (mode == ControlMode::joint) { + this->joint_controller->reset(state); + } else if (mode == ControlMode::cartesian) { + this->cartesian_controller->reset(state); + } + this->control_mode = mode; +} + +common::ControllerState SimRobot::controller_state(double dt) { + mjModel* m = this->sim->m; + mjData* d = this->sim->d; + size_t n = std::size(this->ids.joints); + common::VectorXd q(n), dq(n); + for (size_t i = 0; i < n; ++i) { + q[i] = d->qpos[m->jnt_qposadr[this->ids.joints[i]]]; + dq[i] = d->qvel[m->jnt_dofadr[this->ids.joints[i]]]; + } + return this->dynamics->compute(q, dq, dt); +} + +void SimRobot::control_step(double dt) { + if (this->control_mode == ControlMode::native) { + return; + } + common::ControllerState state = this->controller_state(dt); + common::VectorXd tau = this->control_mode == ControlMode::joint + ? this->joint_controller->step(state) + : this->cartesian_controller->step(state); + tau += state.gravity; // the firmware's part + for (size_t i = 0; i < std::size(this->ids.actuators); ++i) { + this->sim->d->ctrl[this->ids.actuators[i]] = tau[i]; + } +} + } // namespace sim } // namespace rcs diff --git a/src/sim/SimRobot.h b/src/sim/SimRobot.h index 56d701118..074bcd50b 100644 --- a/src/sim/SimRobot.h +++ b/src/sim/SimRobot.h @@ -1,7 +1,9 @@ #ifndef RCS_SIMROBOT_H #define RCS_SIMROBOT_H #include +#include #include +#include #include #include #include @@ -34,6 +36,10 @@ struct SimRobotConfig : common::RobotConfig { std::optional> kp; std::optional> kv; std::string base = "base"; + // Tool as configured on the real robot (for Franka: the end effector set in + // Desk), used for gravity compensation and the dynamics in torque control. + // None: the MJCF bodies attached after the flange. + std::optional payload; void add_prefix(const std::string& id) { for (auto& s : this->arm_collision_geoms) { @@ -53,6 +59,7 @@ struct SimRobotConfig : common::RobotConfig { struct SimRobotState : common::RobotState { common::VectorXd previous_angles; common::VectorXd target_angles; + common::Pose target_pose; common::Pose inverse_tcp_offset; bool ik_success = true; bool collision = false; @@ -82,6 +89,19 @@ class SimRobot : public common::Robot { void clear_collision_flag(); void close() override {}; + // Torque control with the shared controllers, see + // docs/development/controller_interface.md. set_dynamics() must come first. + // Installing a controller switches the arm to torque control for good and + // makes it hold the current configuration. + void set_dynamics(std::shared_ptr dynamics); + void set_joint_controller( + std::shared_ptr controller); + void set_cartesian_controller( + std::shared_ptr controller); + // The MJCF bodies attached after the flange, as a payload in the flange + // frame. + common::Payload get_simulated_payload(); + private: SimRobotConfig cfg; SimRobotState state; @@ -94,6 +114,17 @@ class SimRobot : public common::Robot { std::vector actuators; int base; } ids; + enum class ControlMode { native, joint, cartesian }; + ControlMode control_mode = ControlMode::native; + bool torque_control = false; + std::shared_ptr dynamics; + std::shared_ptr joint_controller; + std::shared_ptr cartesian_controller; + void configure_dynamics(); + void enable_torque_control(); + void activate(ControlMode mode); + common::ControllerState controller_state(double dt); + void control_step(double dt); void is_moving_callback(); void is_arrived_callback(); bool collision_callback(); From 51b7fe2b53d2d7f1be5f7706d1c0c7d3ada2ccd9 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:49:31 -0800 Subject: [PATCH 16/39] feat(control): port the FR3 joint and OSC controllers to core FR3JointController and FR3OSC are the control laws of Franka::joint_controller and Franka::osc, moved out of the libfranka loop: same gains, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit and clip. Dynamics come from the ControllerState, and the rate limit uses the controller's previous output, so the sim can run them too. --- include/rcs/FR3Controllers.h | 102 +++++++++++++++ python/rcs/_core/common.pyi | 32 +++++ python/tests/test_fr3_controllers.py | 123 ++++++++++++++++++ src/pybind/rcs.cpp | 39 ++++++ src/rcs/CMakeLists.txt | 2 +- src/rcs/FR3Controllers.cpp | 182 +++++++++++++++++++++++++++ 6 files changed, 479 insertions(+), 1 deletion(-) create mode 100644 include/rcs/FR3Controllers.h create mode 100644 python/tests/test_fr3_controllers.py create mode 100644 src/rcs/FR3Controllers.cpp diff --git a/include/rcs/FR3Controllers.h b/include/rcs/FR3Controllers.h new file mode 100644 index 000000000..e99a74a9a --- /dev/null +++ b/include/rcs/FR3Controllers.h @@ -0,0 +1,102 @@ +#ifndef RCS_FR3_CONTROLLERS_H +#define RCS_FR3_CONTROLLERS_H + +#include +#include +#include + +#include "Controller.h" +#include "Interpolator.h" +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// The torque controllers that run on the FR3, ported one to one from +// Franka::joint_controller() and Franka::osc() (deoxys), so that the sim can +// run them too. Differences to the original: +// - The torque rate limit uses the controller's own previous output instead +// of franka::RobotState::tau_J_d (on the robot they are the same). +// - Dynamics come from the ControllerState (PinocchioDynamics) instead of +// franka::Model, which computes the same quantities. + +// Safety stage shared by both controllers, applied after the control law. +struct FR3TorqueLimits { + // joint limits for the guard; the values hard coded in Franka.cpp + Vector7d joint_min = (Vector7d() << -2.8973, -1.7628, -2.8973, -3.0718, + -2.8973, -0.0175, -2.8973) + .finished(); + Vector7d joint_max = + (Vector7d() << 2.8978, 1.7628, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973) + .finished(); + // per-joint torque clip, FrankaConfig::torque_limit + Vector7d torque_limit = + (Vector7d() << 87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0).finished(); +}; + +struct FR3JointControllerConfig { + Vector7d kp = + (Vector7d() << 100.0, 100.0, 100.0, 100.0, 75.0, 150.0, 50.0).finished(); + Vector7d kd = + (Vector7d() << 20.0, 20.0, 20.0, 20.0, 7.5, 15.0, 5.0).finished(); + FR3TorqueLimits limits; +}; + +// Joint impedance: tau = kp (q_d - q) - kd dq + coriolis, then the safety +// stage. Note: no setpoint velocity feed-forward, as on the robot. +class FR3JointController : public JointController { + public: + FR3JointController(const FR3JointControllerConfig& config, + std::shared_ptr interpolator); + void reset(const ControllerState& state) override; + void set_goal(const VectorXd& q_goal, + std::optional duration = std::nullopt) override; + VectorXd step(const ControllerState& state) override; + + private: + FR3JointControllerConfig config; + std::shared_ptr interpolator; + Vector7d last_tau = Vector7d::Zero(); +}; + +struct FR3OSCConfig { + Eigen::Vector3d kp_position = Eigen::Vector3d::Constant(150.0); // kp_p + double kp_orientation = 250.0; // kp_r + // posture held in the null space (unit gain) + Vector7d nullspace_q = + (Vector7d() << 0.09017809387254755, -0.9824203501652151, + 0.030509718397568178, -2.694229634937343, 0.057700675144720104, + 1.860298714876101, 0.8713759453244422) + .finished(); + // added to the diagonal of the mass matrix + Vector7d residual_mass = + (Vector7d() << 0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.5).finished(); + // null-space push away from joints that are 0.1 to 0.25 rad from a limit + Vector7d avoidance_weights = + (Vector7d() << 1.0, 1.0, 1.0, 1.0, 1.0, 10.0, 10.0).finished(); + FR3TorqueLimits limits; +}; + +// Decoupled operational-space control as on the FR3 (deoxys): separate +// position and orientation task inertias, damping on the TCP velocity only, +// orientation error from the quaternion vector part, small errors cut off, +// posture and joint-limit avoidance in the null space, then the safety stage. +class FR3OSC : public CartesianController { + public: + FR3OSC(const FR3OSCConfig& config, + std::shared_ptr interpolator); + void reset(const ControllerState& state) override; + void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) override; + VectorXd step(const ControllerState& state) override; + + private: + FR3OSCConfig config; + std::shared_ptr interpolator; + Vector7d last_tau = Vector7d::Zero(); +}; + +} // namespace common +} // namespace rcs +#endif // RCS_FR3_CONTROLLERS_H diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index df6ada2a3..389f1ff8e 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -15,6 +15,11 @@ __all__: list[str] = [ "CartesianInterpolator", "CartesianSetpoint", "ControllerState", + "FR3JointController", + "FR3JointControllerConfig", + "FR3OSC", + "FR3OSCConfig", + "FR3TorqueLimits", "FrankaHandTCPOffset", "GraspType", "Gripper", @@ -93,6 +98,27 @@ class ControllerState: tcp_pose: Pose def __init__(self) -> None: ... +class FR3JointControllerConfig: + kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + limits: FR3TorqueLimits + def __init__(self) -> None: ... + +class FR3OSCConfig: + avoidance_weights: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + kp_orientation: float + kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] + limits: FR3TorqueLimits + nullspace_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + residual_mass: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + def __init__(self) -> None: ... + +class FR3TorqueLimits: + joint_max: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + joint_min: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + def __init__(self) -> None: ... + class GraspType: """ Members: @@ -446,12 +472,18 @@ class RotVec: self, ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... +class FR3OSC(CartesianController): + def __init__(self, config: FR3OSCConfig, interpolator: CartesianInterpolator) -> None: ... + class OSC(CartesianController): def __init__(self, config: OSCConfig, interpolator: CartesianInterpolator) -> None: ... class LinearCartesianInterpolator(CartesianInterpolator): def __init__(self, duration: float) -> None: ... +class FR3JointController(JointController): + def __init__(self, config: FR3JointControllerConfig, interpolator: JointInterpolator) -> None: ... + class JointPD(JointController): def __init__( self, diff --git a/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py new file mode 100644 index 000000000..776982ef4 --- /dev/null +++ b/python/tests/test_fr3_controllers.py @@ -0,0 +1,123 @@ +"""The FR3 controllers ported from Franka.cpp: control laws, safety stage, and +their use in the torque-controlled sim.""" + +import numpy as np +import pytest +from test_sim_torque_control import Setup, pose_error + +import rcs +from rcs import common + +DT = 0.001 +Q0 = np.array([0.0, -0.8, 0.0, -2.4, 0.0, 1.6, 0.8]) # away from the joint limits + + +@pytest.fixture +def dynamics() -> common.PinocchioDynamics: + path = str(rcs.ROBOTS[common.RobotType.FR3].mjcf_model_path) + return common.PinocchioDynamics(path, False, "attachment_site", common.Pose(translation=np.array([0, 0, 0.1]))) + + +def joint_controller(state) -> common.FR3JointController: + controller = common.FR3JointController(common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05)) + controller.reset(state) + return controller + + +def osc(state, **config) -> common.FR3OSC: + cfg = common.FR3OSCConfig() + for key, value in config.items(): + setattr(cfg, key, value) + controller = common.FR3OSC(cfg, common.LinearCartesianInterpolator(0.05)) + controller.reset(state) + return controller + + +def test_joint_controller_law(dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + controller = joint_controller(state) + # small error and velocity, so that the rate limit doesn't act + q = Q0 + 0.002 + dq = np.full(7, 0.01) + state = dynamics.compute(q, dq, DT) + cfg = common.FR3JointControllerConfig() + expected = cfg.kp * (Q0 - q) - cfg.kd * dq + state.coriolis # no setpoint velocity feed-forward + np.testing.assert_allclose(controller.step(state), expected, atol=1e-10) + + +def test_torque_rate_is_limited_to_1000_nm_per_s(dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + controller = joint_controller(state) + controller.set_goal(Q0 + 0.5, duration=DT) # large error at once + first = controller.step(state) + second = controller.step(state) + assert np.all(np.abs(first) <= 1.0) + assert np.all(np.abs(second - first) <= 1.0) + assert np.max(np.abs(second)) > 1.5 + + +def test_torque_is_clipped(dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + controller = joint_controller(state) + controller.set_goal(Q0 + 1.0, duration=DT) + for _ in range(200): + tau = controller.step(state) + np.testing.assert_allclose(np.abs(tau), common.FR3TorqueLimits().torque_limit) + + +def test_no_torque_towards_a_close_joint_limit(dynamics): + limits = common.FR3TorqueLimits() + q = Q0.copy() + q[0] = limits.joint_max[0] - 0.05 + state = dynamics.compute(q, np.zeros(7), DT) + controller = joint_controller(state) + controller.set_goal(q + 0.3, duration=DT) # pulls joint 1 into the limit + for _ in range(20): + tau = controller.step(state) + assert tau[0] == 0.0 + assert tau[1] > 0.0 + + +def test_osc_holds_without_torque_at_its_posture(dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + np.testing.assert_allclose(osc(state, nullspace_q=Q0).step(state), 0.0, atol=1e-9) + + +def test_osc_pulls_towards_the_goal(dynamics): + state = dynamics.compute(Q0, np.zeros(7), DT) + controller = osc(state, nullspace_q=Q0) + offset = np.array([0.02, 0.0, -0.01]) + goal = common.Pose(rotation=state.tcp_pose.rotation_m(), translation=state.tcp_pose.translation() + offset) + controller.set_goal(goal, duration=DT) + for _ in range(20): # let the rate limit settle + tau = controller.step(state) + # the controller's own mass matrix includes the residual mass on joints 5-7 + mass = state.mass + np.diag(common.FR3OSCConfig().residual_mass) + acceleration = state.jacobian[:3] @ np.linalg.solve(mass, tau - state.coriolis) + np.testing.assert_allclose(acceleration, 150.0 * offset, atol=1e-6) + + +@pytest.mark.parametrize("controller", ["joint", "osc"]) +def test_fr3_controllers_in_sim(controller): + setup = Setup() + if controller == "joint": + setup.robot.set_joint_controller( + common.FR3JointController(common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05)) + ) + goal = setup.robot.get_joint_position() + np.array([0.1, -0.1, 0.1, 0.1, -0.1, 0.1, 0.2]) + setup.robot.set_joint_position(goal) + setup.run(2.0) + # joint friction in the model leaves a steady-state error + assert np.max(np.abs(setup.robot.get_joint_position() - goal)) < 0.03 + else: + q_home = setup.robot.get_joint_position() + setup.robot.set_cartesian_controller( + common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05)) + ) + start = setup.robot.get_cartesian_position() + goal = common.Pose(rotation=start.rotation_m(), translation=start.translation() + np.array([0.05, -0.05, 0.0])) + setup.robot.set_cartesian_position(goal) + setup.run(3.0) + position_error, _ = pose_error(setup.robot.get_cartesian_position(), goal) + assert position_error < 0.02 + assert np.max(np.abs(setup.robot.get_joint_position() - q_home)) < 1.0 # no runaway in the null space diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 10c7280c7..33ca3a468 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -14,6 +14,7 @@ #include "rcs/Camera.h" #include "rcs/Controllers.h" +#include "rcs/FR3Controllers.h" #include "rcs/Kinematics.h" #include "rcs/LinearInterpolator.h" #include "rcs/PinocchioDynamics.h" @@ -533,6 +534,44 @@ PYBIND11_MODULE(_core, m) { std::shared_ptr>(), py::arg("config"), py::arg("interpolator")); + py::class_(common, "FR3TorqueLimits") + .def(py::init<>()) + .def_readwrite("joint_min", &rcs::common::FR3TorqueLimits::joint_min) + .def_readwrite("joint_max", &rcs::common::FR3TorqueLimits::joint_max) + .def_readwrite("torque_limit", + &rcs::common::FR3TorqueLimits::torque_limit); + + py::class_(common, + "FR3JointControllerConfig") + .def(py::init<>()) + .def_readwrite("kp", &rcs::common::FR3JointControllerConfig::kp) + .def_readwrite("kd", &rcs::common::FR3JointControllerConfig::kd) + .def_readwrite("limits", &rcs::common::FR3JointControllerConfig::limits); + + py::class_>( + common, "FR3JointController") + .def(py::init>(), + py::arg("config"), py::arg("interpolator")); + + py::class_(common, "FR3OSCConfig") + .def(py::init<>()) + .def_readwrite("kp_position", &rcs::common::FR3OSCConfig::kp_position) + .def_readwrite("kp_orientation", + &rcs::common::FR3OSCConfig::kp_orientation) + .def_readwrite("nullspace_q", &rcs::common::FR3OSCConfig::nullspace_q) + .def_readwrite("residual_mass", &rcs::common::FR3OSCConfig::residual_mass) + .def_readwrite("avoidance_weights", + &rcs::common::FR3OSCConfig::avoidance_weights) + .def_readwrite("limits", &rcs::common::FR3OSCConfig::limits); + + py::class_>(common, "FR3OSC") + .def(py::init>(), + py::arg("config"), py::arg("interpolator")); + bind_type_class(common, "RobotType") .def_readonly_static("FR3", &rcs::common::RobotType::FR3) .def_readonly_static("Panda", &rcs::common::RobotType::Panda) diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index 7d845bbab..cebf583f9 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp FR3Controllers.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/FR3Controllers.cpp b/src/rcs/FR3Controllers.cpp new file mode 100644 index 000000000..e000f5bc0 --- /dev/null +++ b/src/rcs/FR3Controllers.cpp @@ -0,0 +1,182 @@ +#include "rcs/FR3Controllers.h" + +#include +#include +#include +#include + +namespace rcs { +namespace common { + +namespace { + +// franka::limitRate with franka::kMaxTorqueRate: at most (1000 - 1e-3) Nm/s +// per joint, for the fixed 1 ms cycle libfranka assumes. +constexpr double kMaxTorqueStep = (1000.0 - 1e-3) * 1e-3; + +// PInverse from Franka.cpp: SVD pseudo-inverse, singular values below +// epsilon are dropped. +Eigen::MatrixXd pseudo_inverse(const Eigen::MatrixXd& M, + double epsilon = 0.00025) { + Eigen::JacobiSVD svd( + M, Eigen::ComputeFullU | Eigen::ComputeFullV); + Eigen::MatrixXd S_inv = Eigen::MatrixXd::Zero(M.cols(), M.rows()); + for (Eigen::Index i = 0; i < svd.singularValues().size(); i++) { + double s = svd.singularValues()(i); + S_inv(i, i) = s < epsilon ? 0.0 : 1.0 / s; + } + return svd.matrixV() * S_inv * svd.matrixU().transpose(); +} + +// The end of both control loops in Franka.cpp: no torque that pushes a joint +// that is closer than 0.1 rad to its limit further, the torque rate limit, +// and the per-joint torque clip. +Vector7d safety_stage(Vector7d tau, const Vector7d& q, + const FR3TorqueLimits& limits, Vector7d& last_tau) { + for (int i = 0; i < 7; i++) { + if (limits.joint_max[i] - q[i] < 0.1 && tau[i] > 0.) tau[i] = 0.; + if (q[i] - limits.joint_min[i] < 0.1 && tau[i] < 0.) tau[i] = 0.; + } + for (int i = 0; i < 7; i++) { + tau[i] = last_tau[i] + + std::clamp(tau[i] - last_tau[i], -kMaxTorqueStep, kMaxTorqueStep); + tau[i] = + std::clamp(tau[i], -limits.torque_limit[i], limits.torque_limit[i]); + } + last_tau = tau; + return tau; +} + +void check_seven_joints(const ControllerState& state) { + if (state.q.size() != 7) { + throw std::invalid_argument("FR3 controllers need 7 joints"); + } +} + +} // namespace + +FR3JointController::FR3JointController( + const FR3JointControllerConfig& config, + std::shared_ptr interpolator) + : config(config), interpolator(std::move(interpolator)) { + if (!this->interpolator) { + throw std::invalid_argument("interpolator must not be null"); + } +} + +void FR3JointController::reset(const ControllerState& state) { + check_seven_joints(state); + this->interpolator->reset(state.q); + this->last_tau.setZero(); +} + +void FR3JointController::set_goal(const VectorXd& q_goal, + std::optional duration) { + this->interpolator->set_goal(q_goal, duration); +} + +VectorXd FR3JointController::step(const ControllerState& state) { + check_seven_joints(state); + const Vector7d q = state.q; + const Vector7d dq = state.dq; + Vector7d desired_q = this->interpolator->step(state.dt).q; + + Vector7d tau = this->config.kp.cwiseProduct(desired_q - q) - + this->config.kd.cwiseProduct(dq); + tau += state.coriolis; + return safety_stage(tau, q, this->config.limits, this->last_tau); +} + +FR3OSC::FR3OSC(const FR3OSCConfig& config, + std::shared_ptr interpolator) + : config(config), interpolator(std::move(interpolator)) { + if (!this->interpolator) { + throw std::invalid_argument("interpolator must not be null"); + } +} + +void FR3OSC::reset(const ControllerState& state) { + check_seven_joints(state); + this->interpolator->reset(state.tcp_pose); + this->last_tau.setZero(); +} + +void FR3OSC::set_goal(const Pose& pose_goal, std::optional duration) { + this->interpolator->set_goal(pose_goal, duration); +} + +VectorXd FR3OSC::step(const ControllerState& state) { + check_seven_joints(state); + const FR3OSCConfig& cfg = this->config; + const Vector7d q = state.q; + const Vector7d dq = state.dq; + CartesianSetpoint setpoint = this->interpolator->step(state.dt); + + Eigen::Matrix3d Kp_p = cfg.kp_position.asDiagonal(); + Eigen::Matrix3d Kp_r = Eigen::Matrix3d::Identity() * cfg.kp_orientation; + Eigen::Matrix3d Kd_p = 2.0 * Kp_p.cwiseSqrt(); + Eigen::Matrix3d Kd_r = 2.0 * Kp_r.cwiseSqrt(); + + Eigen::Matrix M = state.mass; + M += cfg.residual_mass.asDiagonal(); + const Eigen::Matrix jacobian = state.jacobian; + const Eigen::Matrix jacobian_pos = jacobian.topRows<3>(); + const Eigen::Matrix jacobian_ori = jacobian.bottomRows<3>(); + + // errors of the TCP, in the base frame + Eigen::Vector3d pos_EE = state.tcp_pose.translation(); + Eigen::Quaterniond quat_EE = state.tcp_pose.quaternion(); + Eigen::Quaterniond desired_quat = setpoint.pose.quaternion(); + if (desired_quat.coeffs().dot(quat_EE.coeffs()) < 0.0) { + quat_EE.coeffs() << -quat_EE.coeffs(); + } + Eigen::Vector3d pos_error = setpoint.pose.translation() - pos_EE; + Eigen::Quaterniond quat_error(desired_quat.inverse() * quat_EE); + Eigen::Vector3d ori_error(quat_error.x(), quat_error.y(), quat_error.z()); + ori_error = -state.tcp_pose.rotation_m() * ori_error; + + // task-space inertias and the null-space projector + Eigen::Matrix M_inv = M.inverse(); + Eigen::MatrixXd Lambda = + pseudo_inverse(jacobian * M_inv * jacobian.transpose()); + Eigen::Matrix J_inv = M_inv * jacobian.transpose() * Lambda; + Eigen::Matrix Nullspace = + Eigen::Matrix::Identity() - + jacobian.transpose() * J_inv.transpose(); + Eigen::MatrixXd Lambda_pos = + pseudo_inverse(jacobian_pos * M_inv * jacobian_pos.transpose()); + Eigen::MatrixXd Lambda_ori = + pseudo_inverse(jacobian_ori * M_inv * jacobian_ori.transpose()); + + pos_error = pos_error.unaryExpr( + [](double x) { return (std::abs(x) < 1e-4) ? 0. : x; }); + ori_error = ori_error.unaryExpr( + [](double x) { return (std::abs(x) < 5e-3) ? 0. : x; }); + + Vector7d tau = + jacobian_pos.transpose() * + (Lambda_pos * (Kp_p * pos_error - Kd_p * (jacobian_pos * dq))) + + jacobian_ori.transpose() * + (Lambda_ori * (Kp_r * ori_error - Kd_r * (jacobian_ori * dq))); + + // posture in the null space + tau += Nullspace * (cfg.nullspace_q - q); + + // joint-limit avoidance in the null space + Vector7d avoidance = Vector7d::Zero(); + for (int i = 0; i < 7; i++) { + double to_max = cfg.limits.joint_max[i] - q[i]; + double to_min = q[i] - cfg.limits.joint_min[i]; + if (to_max < 0.25 && to_max > 0.1) + avoidance[i] += -cfg.avoidance_weights[i] * to_max; + if (to_min < 0.25 && to_min > 0.1) + avoidance[i] += cfg.avoidance_weights[i] * to_min; + } + tau += Nullspace * avoidance; + + tau += state.coriolis; + return safety_stage(tau, q, cfg.limits, this->last_tau); +} + +} // namespace common +} // namespace rcs From cf87eaa9522d0acaa9ff84c4c59160fbdb1226f6 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 17:52:45 -0800 Subject: [PATCH 17/39] refactor(fr3): run the core FR3 controllers in the libfranka loops Franka::osc and Franka::joint_controller now step FR3OSC and FR3JointController with the ControllerState from PinocchioDynamics, which matches franka::Model on logged states of our FR3s. The controllers are created with the gains from FrankaConfig when a control thread starts. libfranka is no longer used for the model or the rate limit, and the old interpolator header is gone. --- docs/development/controller_interface.md | 37 ++- extensions/rcs_fr3/src/hw/Franka.cpp | 393 ++++------------------- extensions/rcs_fr3/src/hw/Franka.h | 19 +- include/rcs/LinearPoseTrajInterpolator.h | 187 ----------- 4 files changed, 115 insertions(+), 521 deletions(-) delete mode 100644 include/rcs/LinearPoseTrajInterpolator.h diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index be09d7dd1..8cbd6c151 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -248,9 +248,12 @@ class PinocchioDynamics { - The bodies of the two `robot.control(...)` lambdas become: take `q`/`dq` from `RobotState`, `PinocchioDynamics::compute()`, `controller->step()`, return the torque. The payload is set from `RobotState` (`I_total`, - `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. The - backend warns when it differs noticeably from the payload in the robot - config, so that sim and real can be kept equal. + `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. + `FrankaConfig` has no tool payload to compare it with, so there is no + warning on hardware (a possible follow-up). +- `PinocchioDynamics` is built from `kinematic_model_path` and + `attachment_site` of `FrankaConfig` when a controller starts, so Desk-only + uses of `Franka` don't need a model. - By default `Franka` builds an `FR3JointController` / `FR3OSC` from `FrankaConfig`, so the Python API and configs are unchanged. @@ -278,9 +281,35 @@ is **not** modelled. `LinearPoseTrajInterpolator.h`. Before that, a read-only check on the robot that `PinocchioDynamics` matches `franka::Model` on live states. +## Validation + +Against the real FR3s on `ai2duo` (read only: the URDF from `getRobotModel()` +and logged 1 kHz control states of the right arm, recorded with the OSC on +2026-11-16): + +- **Kinematics**: `PinocchioDynamics` TCP pose vs the robot's `O_T_EE` on + 40 s of logged states: within 0.0001 mm and 0.02°. +- **Dynamics**: vs `franka::Model` built from the robot's URDF, with the Desk + payload, on 500 logged states: mass matrix within 1e-6, Coriolis within + 2e-7, Jacobian within 2e-15. +- **Gravity and payload**: `tau_J - tau_J_d` at rest (the firmware's gravity + compensation) is reproduced to 0.05–0.23 Nm per joint by `PinocchioDynamics` + with the Desk payload, once the gravity direction is fitted: the arm is + mounted tilted by about 52°, and the fitted gravity is 9.94 m/s². Without + the payload the fit is clearly worse. +- **FR3 OSC port**: open-loop replay of the logged states and 15 Hz goals + through `FR3OSC` + `PinocchioDynamics` vs the logged commanded torque + `tau_J_d`: correlation 0.95–0.997 per joint; with the goals delayed by the + measured ~15 ms latency, mean absolute error 0.02–0.13 Nm on torques with + an RMS of 0.6–1.6 Nm. Samples within 0.3 rad of a joint limit are left out, + because the recordings ran a newer joint-limit guard than master. + +The FR3 backend with the new controllers has been built but **not yet run on +the robot**. + ## Open questions -None at the moment. +- First run of step 7 on the robot. ## Decisions diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index d9425371a..7f5135008 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -2,8 +2,6 @@ #include #include -#include -#include #include #include @@ -15,6 +13,7 @@ #include #include "FrankaMotionGenerator.h" +#include "rcs/LinearInterpolator.h" #include "rcs/Pose.h" namespace rcs { @@ -158,51 +157,25 @@ void Franka::set_guiding_mode(bool x, bool y, bool z, bool roll, bool pitch, this->robot.setGuidingMode(activated, elbow); } -void PInverse(const Eigen::MatrixXd& M, Eigen::MatrixXd& M_inv, - double epsilon = 0.00025) { - Eigen::JacobiSVD svd( - M, Eigen::ComputeFullU | Eigen::ComputeFullV); - Eigen::JacobiSVD::SingularValuesType singular_vals = - svd.singularValues(); - - Eigen::MatrixXd S_inv = M; - S_inv.setZero(); - for (int i = 0; i < singular_vals.size(); i++) { - if (singular_vals(i) < epsilon) { - S_inv(i, i) = 0.; - } else { - S_inv(i, i) = 1. / singular_vals(i); - } - } - M_inv = Eigen::MatrixXd(svd.matrixV() * S_inv * svd.matrixU().transpose()); -} - -void TorqueSafetyGuardFn(std::array& tau_d_array, - const common::Vector7d& torque_limit) { - for (size_t i = 0; i < tau_d_array.size(); i++) { - if (tau_d_array[i] < -torque_limit[i]) { - tau_d_array[i] = -torque_limit[i]; - } else if (tau_d_array[i] > torque_limit[i]) { - tau_d_array[i] = torque_limit[i]; - } - } -} - void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { this->check_for_background_errors(); - // from deoxys/config/osc-position-controller.yml - double traj_interpolation_time_fraction = 1.0; // in s - // form deoxys/config/charmander.yml - int traj_rate = 500; - const bool starting_fresh = this->running_controller.load() == Controller::none; if (starting_fresh) { this->controller_time = 0.0; - this->m_active_policy_rate = this->m_cfg.policy_rate; this->get_joint_position(); - this->joint_interpolator = common::LinearJointPositionTrajInterpolator(); + this->create_dynamics(); + common::FR3JointControllerConfig config; + config.kp = this->m_cfg.kp; + config.kd = this->m_cfg.kd; + config.limits.torque_limit = this->m_cfg.torque_limit; + // a goal per policy step, interpolated over one policy period + this->fr3_joint_controller = std::make_shared( + config, std::make_shared( + 1.0 / this->m_cfg.policy_rate)); + this->fr3_joint_controller->reset( + this->controller_state(this->curr_state.load(), 0.0)); } else if (this->running_controller.load() != Controller::jsc) { // runtime error throw std::runtime_error( @@ -229,9 +202,9 @@ void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { std::clamp(max_gap / speed, kMinApproachTime, kMaxApproachTime); } - this->joint_interpolator.reset( - this->controller_time, q_now, desired_q, this->m_active_policy_rate, - traj_rate, traj_interpolation_time_fraction, approach_time); + this->fr3_joint_controller->set_goal( + desired_q, + approach_on_start ? std::optional(approach_time) : std::nullopt); // if not thread is running, then start if (starting_fresh) { @@ -284,19 +257,22 @@ void Franka::clear_background_error() { void Franka::osc_set_cartesian_position( const common::Pose& desired_pose_EE_in_base_frame) { this->check_for_background_errors(); - // from deoxys/config/osc-position-controller.yml - double traj_interpolation_time_fraction = 1.0; - // form deoxys/config/charmander.yml - int traj_rate = 500; - const bool starting_fresh = this->running_controller.load() == Controller::none; if (starting_fresh) { this->controller_time = 0.0; - this->m_active_policy_rate = this->m_cfg.policy_rate; this->curr_state.store(this->robot.readOnce()); - this->traj_interpolator = common::LinearPoseTrajInterpolator(); + this->create_dynamics(); + common::FR3OSCConfig config; + config.kp_position = this->m_cfg.kp_p; + config.kp_orientation = this->m_cfg.kp_r; + config.limits.torque_limit = this->m_cfg.torque_limit; + // a goal per policy step, interpolated over one policy period + this->fr3_osc = std::make_shared( + config, std::make_shared( + 1.0 / this->m_cfg.policy_rate)); + this->fr3_osc->reset(this->controller_state(this->curr_state.load(), 0.0)); } else if (this->running_controller.load() != Controller::osc) { throw std::runtime_error( "Controller type must but osc but is " + @@ -331,11 +307,9 @@ void Franka::osc_set_cartesian_position( kMinApproachTime, kMaxApproachTime); } - this->traj_interpolator.reset( - this->controller_time, curr_pose.translation(), curr_pose.quaternion(), - desired_pose_EE_in_base_frame.translation(), - desired_pose_EE_in_base_frame.quaternion(), this->m_active_policy_rate, - traj_rate, traj_interpolation_time_fraction, approach_time); + this->fr3_osc->set_goal( + desired_pose_EE_in_base_frame, + approach_on_start ? std::optional(approach_time) : std::nullopt); // if not thread is running, then start if (starting_fresh) { @@ -394,11 +368,36 @@ void Franka::stop_control_thread() { } } +void Franka::create_dynamics() { + if (!this->dynamics) { + const std::string& path = this->m_cfg.kinematic_model_path; + const bool urdf = path.size() >= 5 && path.ends_with(".urdf"); + this->dynamics = std::make_shared( + path, urdf, this->m_cfg.attachment_site); + } + this->dynamics->set_tcp_offset(this->m_cfg.tcp_offset); +} + +common::ControllerState Franka::controller_state( + const franka::RobotState& robot_state, double dt) { + // the end effector and load configured in Desk, as franka::Model uses them + common::Payload payload; + payload.mass = robot_state.m_total; + payload.com = + Eigen::Map(robot_state.F_x_Ctotal.data()); + payload.inertia = + Eigen::Map(robot_state.I_total.data()); + common::Payload current = this->dynamics->get_payload(); + if (payload.mass != current.mass || payload.com != current.com || + payload.inertia != current.inertia) { + this->dynamics->set_payload(payload); + } + return this->dynamics->compute( + Eigen::Map(robot_state.q.data()), + Eigen::Map(robot_state.dq.data()), dt); +} + void Franka::osc() { - franka::Model model = this->robot.loadModel(); - const Eigen::Vector3d kp_p_cfg = this->m_cfg.kp_p; - const double kp_r_cfg = this->m_cfg.kp_r; - const common::Vector7d torque_limit = this->m_cfg.torque_limit; const bool allow_high_collision = this->m_cfg.allow_high_collision; this->controller_time = 0.0; @@ -415,212 +414,21 @@ void Franka::osc() { {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0}}); } - // from bench mark - // ([150.0, 150.0, 60.0], 250.0), // kp_translation, kp_rotation - // ([60.0, 150.0, 150.0], 250.0), // kd_translation, kd_rotation - - // from config file - // Kp: - // translation: [150.0, 150.0, 150.0] - // rotation: 250.0 - - Eigen::Matrix Kp_p = Eigen::Matrix3d::Zero(); - Eigen::Matrix Kp_r = Eigen::Matrix3d::Zero(); - Eigen::Matrix Kd_p = Eigen::Matrix3d::Zero(); - Eigen::Matrix Kd_r = Eigen::Matrix3d::Zero(); - Eigen::Matrix static_q_task_; - Eigen::Matrix residual_mass_vec_; - Eigen::Array joint_max_; - Eigen::Array joint_min_; - Eigen::Array avoidance_weights_; - - Kp_p.diagonal() << kp_p_cfg; - Kp_r.diagonal() << kp_r_cfg, kp_r_cfg, kp_r_cfg; - - Kd_p << Kp_p.cwiseSqrt() * 2.0; - Kd_r << Kp_r.cwiseSqrt() * 2.0; - - static_q_task_ << 0.09017809387254755, -0.9824203501652151, - 0.030509718397568178, -2.694229634937343, 0.057700675144720104, - 1.860298714876101, 0.8713759453244422; - - // The manual residual mass matrix to add on the internal mass matrix - residual_mass_vec_ << 0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.5; - - joint_max_ << 2.8978, 1.7628, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973; - joint_min_ << -2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973; - avoidance_weights_ << 1., 1., 1., 1., 1., 10., 10.; - try { this->robot.control([&](const franka::RobotState& robot_state, franka::Duration period) -> franka::Torques { - std::chrono::high_resolution_clock::time_point t1 = - std::chrono::high_resolution_clock::now(); - - // torques handler if (this->running_controller.load() == Controller::none) { return franka::MotionFinished(franka::Torques(robot_state.tau_J_d)); } - // TO BE replaced - // if (!this->control_thread_running && dq.maxCoeff() < 0.0001) { - // return franka::MotionFinished(franka::Torques(tau_d_array)); - // } - - Eigen::Vector3d desired_pos_EE_in_base_frame; - Eigen::Quaterniond desired_quat_EE_in_base_frame; - - // form deoxys/config/charmander.yml - int policy_rate = 20; - int traj_rate = 500; - this->curr_state.store(robot_state); - this->interpolator_mutex.lock(); + std::lock_guard lock(this->interpolator_mutex); this->controller_time += period.toSec(); - this->traj_interpolator.next_step(this->controller_time, - desired_pos_EE_in_base_frame, - desired_quat_EE_in_base_frame); - this->interpolator_mutex.unlock(); - - // end torques handler - - Eigen::Matrix tau_d; - - std::array mass_array = model.mass(robot_state); - Eigen::Map> M(mass_array.data()); - - M = M + Eigen::Matrix(residual_mass_vec_.asDiagonal()); - - // coriolis and gravity - std::array coriolis_array = model.coriolis(robot_state); - Eigen::Map> coriolis( - coriolis_array.data()); - - std::array gravity_array = model.gravity(robot_state); - Eigen::Map> gravity( - gravity_array.data()); - - std::array jacobian_array = model.zeroJacobian( - franka::Frame::kEndEffector, robot_state.q, - this->m_cfg.tcp_offset.affine_array(), robot_state.EE_T_K); - Eigen::Map> jacobian( - jacobian_array.data()); - - Eigen::MatrixXd jacobian_pos(3, 7); - Eigen::MatrixXd jacobian_ori(3, 7); - jacobian_pos << jacobian.block(0, 0, 3, 7); - jacobian_ori << jacobian.block(3, 0, 3, 7); - - // Express OSC feedback in the same TCP frame exposed by the public - // Cartesian API. - common::Pose T_EE_in_base_frame_pose = - GetTCPInBaseFrame(robot_state, this->m_cfg.tcp_offset); - Eigen::Affine3d T_EE_in_base_frame = - T_EE_in_base_frame_pose.affine_matrix(); - - Eigen::Vector3d pos_EE_in_base_frame(T_EE_in_base_frame.translation()); - Eigen::Quaterniond quat_EE_in_base_frame(T_EE_in_base_frame.linear()); - - // Nullspace goal - Eigen::Map> q(robot_state.q.data()); - - // Joint velocity - Eigen::Map> dq(robot_state.dq.data()); - - if (desired_quat_EE_in_base_frame.coeffs().dot( - quat_EE_in_base_frame.coeffs()) < 0.0) { - quat_EE_in_base_frame.coeffs() << -quat_EE_in_base_frame.coeffs(); - } - - Eigen::Vector3d pos_error; - - pos_error << desired_pos_EE_in_base_frame - pos_EE_in_base_frame; - Eigen::Quaterniond quat_error(desired_quat_EE_in_base_frame.inverse() * - quat_EE_in_base_frame); - Eigen::Vector3d ori_error; - ori_error << quat_error.x(), quat_error.y(), quat_error.z(); - ori_error << -T_EE_in_base_frame.linear() * ori_error; - - // Compute matrices - Eigen::Matrix M_inv(M.inverse()); - Eigen::MatrixXd Lambda_inv(6, 6); - Lambda_inv << jacobian * M_inv * jacobian.transpose(); - Eigen::MatrixXd Lambda(6, 6); - PInverse(Lambda_inv, Lambda); - - Eigen::Matrix J_inv; - J_inv << M_inv * jacobian.transpose() * Lambda; - Eigen::Matrix Nullspace; - Nullspace << Eigen::MatrixXd::Identity(7, 7) - - jacobian.transpose() * J_inv.transpose(); - - // Decoupled mass matrices - Eigen::MatrixXd Lambda_pos_inv(3, 3); - Lambda_pos_inv << jacobian_pos * M_inv * jacobian_pos.transpose(); - Eigen::MatrixXd Lambda_ori_inv(3, 3); - Lambda_ori_inv << jacobian_ori * M_inv * jacobian_ori.transpose(); - - Eigen::MatrixXd Lambda_pos(3, 3); - Eigen::MatrixXd Lambda_ori(3, 3); - PInverse(Lambda_pos_inv, Lambda_pos); - PInverse(Lambda_ori_inv, Lambda_ori); - - pos_error = pos_error.unaryExpr( - [](double x) { return (abs(x) < 1e-4) ? 0. : x; }); - ori_error = ori_error.unaryExpr( - [](double x) { return (abs(x) < 5e-3) ? 0. : x; }); - - tau_d << jacobian_pos.transpose() * - (Lambda_pos * - (Kp_p * pos_error - Kd_p * (jacobian_pos * dq))) + - jacobian_ori.transpose() * - (Lambda_ori * - (Kp_r * ori_error - Kd_r * (jacobian_ori * dq))); - - // nullspace control - tau_d << tau_d + Nullspace * (static_q_task_ - q); - - // Add joint avoidance potential - Eigen::Matrix avoidance_force; - avoidance_force.setZero(); - Eigen::Matrix dist2joint_max; - Eigen::Matrix dist2joint_min; - - dist2joint_max = joint_max_.matrix() - q; - dist2joint_min = q - joint_min_.matrix(); - - for (int i = 0; i < 7; i++) { - if (dist2joint_max[i] < 0.25 && dist2joint_max[i] > 0.1) - avoidance_force[i] += -avoidance_weights_[i] * dist2joint_max[i]; - if (dist2joint_min[i] < 0.25 && dist2joint_min[i] > 0.1) - avoidance_force[i] += avoidance_weights_[i] * dist2joint_min[i]; - } - tau_d << tau_d + Nullspace * avoidance_force; - - // Coriolis feed-forward: libfranka compensates gravity, not Coriolis / - // centrifugal torques (see the impedance examples of libfranka) - tau_d << tau_d + coriolis; - - for (int i = 0; i < 7; i++) { - if (dist2joint_max[i] < 0.1 && tau_d[i] > 0.) tau_d[i] = 0.; - if (dist2joint_min[i] < 0.1 && tau_d[i] < 0.) tau_d[i] = 0.; - } - - std::array tau_d_array{}; - Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_d; - - // end of controller - std::chrono::high_resolution_clock::time_point t2 = - std::chrono::high_resolution_clock::now(); - auto time = - std::chrono::duration_cast(t2 - t1); - - std::array tau_d_rate_limited = franka::limitRate( - franka::kMaxTorqueRate, tau_d_array, robot_state.tau_J_d); - - TorqueSafetyGuardFn(tau_d_rate_limited, torque_limit); - - return tau_d_rate_limited; + common::VectorXd tau = this->fr3_osc->step( + this->controller_state(robot_state, period.toSec())); + std::array tau_array{}; + common::VectorXd::Map(tau_array.data(), 7) = tau; + return tau_array; }); } catch (...) { this->background_exception.store(std::current_exception()); @@ -631,10 +439,6 @@ void Franka::osc() { } void Franka::joint_controller() { - franka::Model model = this->robot.loadModel(); - const common::Vector7d Kp = this->m_cfg.kp; - const common::Vector7d Kd = this->m_cfg.kd; - const common::Vector7d torque_limit = this->m_cfg.torque_limit; const bool allow_high_collision = this->m_cfg.allow_high_collision; this->controller_time = 0.0; @@ -650,80 +454,21 @@ void Franka::joint_controller() { {{100.0, 100.0, 100.0, 100.0, 100.0, 100.0}}); } - Eigen::Array joint_max_; - Eigen::Array joint_min_; - - joint_max_ << 2.8978, 1.7628, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973; - joint_min_ << -2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973; - try { this->robot.control([&](const franka::RobotState& robot_state, franka::Duration period) -> franka::Torques { - std::chrono::high_resolution_clock::time_point t1 = - std::chrono::high_resolution_clock::now(); - - // torques handler if (this->running_controller.load() == Controller::none) { return franka::MotionFinished(franka::Torques(robot_state.tau_J_d)); } - - common::Vector7d desired_q; - this->curr_state.store(robot_state); - this->interpolator_mutex.lock(); + std::lock_guard lock(this->interpolator_mutex); this->controller_time += period.toSec(); - this->joint_interpolator.next_step(this->controller_time, desired_q); - this->interpolator_mutex.unlock(); - // end torques handler - - Eigen::Matrix tau_d; - - // Current joint velocity - Eigen::Map> dq(robot_state.dq.data()); - - // Current joint position - Eigen::Map> q(robot_state.q.data()); - - Eigen::MatrixXd joint_pos_error(7, 1); - - joint_pos_error << desired_q - q; - - tau_d << Kp.cwiseProduct(joint_pos_error) - Kd.cwiseProduct(dq); - - // Coriolis feed-forward: libfranka compensates gravity, not Coriolis / - // centrifugal torques (see the impedance examples of libfranka) - std::array coriolis_array = model.coriolis(robot_state); - Eigen::Map> coriolis( - coriolis_array.data()); - tau_d << tau_d + coriolis; - - Eigen::Matrix dist2joint_max; - Eigen::Matrix dist2joint_min; - - dist2joint_max = joint_max_.matrix() - q; - dist2joint_min = q - joint_min_.matrix(); - - for (int i = 0; i < 7; i++) { - if (dist2joint_max[i] < 0.1 && tau_d[i] > 0.) tau_d[i] = 0.; - if (dist2joint_min[i] < 0.1 && tau_d[i] < 0.) tau_d[i] = 0.; - } - - std::array tau_d_array{}; - Eigen::VectorXd::Map(&tau_d_array[0], 7) = tau_d; - - // end of controller - std::chrono::high_resolution_clock::time_point t2 = - std::chrono::high_resolution_clock::now(); - auto time = - std::chrono::duration_cast(t2 - t1); - - std::array tau_d_rate_limited = franka::limitRate( - franka::kMaxTorqueRate, tau_d_array, robot_state.tau_J_d); - - TorqueSafetyGuardFn(tau_d_rate_limited, torque_limit); - - return tau_d_rate_limited; + common::VectorXd tau = this->fr3_joint_controller->step( + this->controller_state(robot_state, period.toSec())); + std::array tau_array{}; + common::VectorXd::Map(tau_array.data(), 7) = tau; + return tau_array; }); } catch (...) { this->background_exception.store(std::current_exception()); diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 5834ae950..fbedcc112 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -12,8 +12,10 @@ #include #include +#include "rcs/Controller.h" +#include "rcs/FR3Controllers.h" #include "rcs/Kinematics.h" -#include "rcs/LinearPoseTrajInterpolator.h" +#include "rcs/PinocchioDynamics.h" #include "rcs/Pose.h" #include "rcs/Robot.h" #include "rcs/utils.h" @@ -115,18 +117,23 @@ class Franka : public common::Robot { FrankaConfig m_cfg; std::optional> m_ik; std::optional control_thread = std::nullopt; - common::LinearPoseTrajInterpolator traj_interpolator; double controller_time = 0.0; - // Snapshot of m_cfg.policy_rate taken when a controller thread is started, so - // the interpolation window stays consistent for the controller's lifetime. - int m_active_policy_rate = 20; - common::LinearJointPositionTrajInterpolator joint_interpolator; + // The shared torque controllers (core), stepped in the libfranka control + // loop. They are created when a controller thread starts, so the gains and + // the interpolation window (1 / policy_rate) stay fixed for its lifetime. + std::shared_ptr dynamics; + std::shared_ptr fr3_joint_controller; + std::shared_ptr fr3_osc; common::ThreadSafeValue curr_state; + // guards the controllers between set_goal() and the control loop std::mutex interpolator_mutex; std::atomic running_controller{Controller::none}; common::ThreadSafeValue background_exception; void osc(); void joint_controller(); + void create_dynamics(); + common::ControllerState controller_state(const franka::RobotState& state, + double dt); void zero_torque_controller(); void check_for_background_errors(); void clear_background_error(); diff --git a/include/rcs/LinearPoseTrajInterpolator.h b/include/rcs/LinearPoseTrajInterpolator.h deleted file mode 100644 index ed126f421..000000000 --- a/include/rcs/LinearPoseTrajInterpolator.h +++ /dev/null @@ -1,187 +0,0 @@ -#ifndef RCS_LINEAR_POSE_TRAJ_INTERPOLATOR_H -#define RCS_LINEAR_POSE_TRAJ_INTERPOLATOR_H -#include - -namespace rcs { -namespace common { - -class LinearPoseTrajInterpolator { - private: - Eigen::Vector3d p_start_; - Eigen::Vector3d p_goal_; - Eigen::Vector3d last_p_t_; - Eigen::Vector3d prev_p_goal_; - - Eigen::Quaterniond q_start_; - Eigen::Quaterniond q_goal_; - Eigen::Quaterniond last_q_t_; - Eigen::Quaterniond prev_q_goal_; - - double dt_; - double last_time_; - double max_time_; - double start_time_; - bool start_; - bool first_goal_; - - public: - inline LinearPoseTrajInterpolator() - : dt_(0.), - last_time_(0.), - max_time_(1.), - start_time_(0.), - start_(false), - first_goal_(true){}; - - inline ~LinearPoseTrajInterpolator(){}; - - inline void reset(const double &time_sec, const Eigen::Vector3d &p_start, - const Eigen::Quaterniond &q_start, - const Eigen::Vector3d &p_goal, - const Eigen::Quaterniond &q_goal, const int &policy_rate, - const int &rate, - const double &traj_interpolator_time_fraction, - const double &explicit_max_time = -1.0) { - dt_ = 1. / static_cast(rate); - last_time_ = time_sec; - // A positive explicit_max_time overrides the default (1 / policy_rate) - // interpolation window; used for a longer, gap-scaled approach on (re)start. - max_time_ = - explicit_max_time > 0.0 - ? explicit_max_time - : 1. / static_cast(policy_rate) * - traj_interpolator_time_fraction; - start_time_ = time_sec; - - start_ = false; - - if (first_goal_) { - p_start_ = p_start; - q_start_ = q_start; - - prev_p_goal_ = p_start; - prev_q_goal_ = q_start; - first_goal_ = false; - } else { - // If the goal is already set, use prev goal as the starting point of - // interpolation. - prev_p_goal_ = p_goal_; - prev_q_goal_ = q_goal_; - - p_start_ = prev_p_goal_; - q_start_ = prev_q_goal_; - } - - p_goal_ = p_goal; - q_goal_ = q_goal; - - // Flip the sign if the dot product of quaternions is negative - if (q_goal_.coeffs().dot(q_start_.coeffs()) < 0.0) { - q_start_.coeffs() << -q_start_.coeffs(); - } - }; - - inline void next_step(const double &time_sec, Eigen::Vector3d &p_t, - Eigen::Quaterniond &q_t) { - if (!start_) { - start_time_ = time_sec; - last_p_t_ = p_start_; - last_q_t_ = q_start_; - start_ = true; - } - - if (last_time_ + dt_ <= time_sec) { - double t = - std::min(std::max((time_sec - start_time_) / max_time_, 0.), 1.); - last_p_t_ = p_start_ + t * (p_goal_ - p_start_); - last_q_t_ = q_start_.slerp(t, q_goal_); - last_time_ = time_sec; - } - p_t = last_p_t_; - q_t = last_q_t_; - }; -}; -class LinearJointPositionTrajInterpolator { - private: - using Vector7d = Eigen::Matrix; - using Vector7i = Eigen::Matrix; - - Vector7d q_start_; - Vector7d q_goal_; - - Vector7d last_q_t_; - Vector7d prev_q_goal_; - - double dt_; - double last_time_; - double max_time_; - double start_time_; - bool start_; - bool first_goal_; - - double interpolation_fraction_; // fraction of actual interpolation within an - // interval - - public: - inline LinearJointPositionTrajInterpolator() - : dt_(0.), - last_time_(0.), - max_time_(1.), - start_time_(0.), - start_(false), - first_goal_(true){}; - - inline ~LinearJointPositionTrajInterpolator(){}; - - inline void reset(const double &time_sec, - const Eigen::Matrix &q_start, - const Eigen::Matrix &q_goal, - const int &policy_rate, const int &rate, - const double &traj_interpolator_time_fraction, - const double &explicit_max_time = -1.0) { - dt_ = 1. / static_cast(rate); - last_time_ = time_sec; - - // A positive explicit_max_time overrides the default (1 / policy_rate) - // interpolation window; used for a longer, gap-scaled approach on (re)start. - max_time_ = - explicit_max_time > 0.0 - ? explicit_max_time - : 1. / static_cast(policy_rate) * - traj_interpolator_time_fraction; - start_time_ = time_sec; - - start_ = false; - - if (first_goal_) { - q_start_ = q_start; - prev_q_goal_ = q_start; - first_goal_ = false; - // std::cout << "First goal of the interpolation" << std::endl; - } else { - prev_q_goal_ = q_goal_; - q_start_ = prev_q_goal_; - } - q_goal_ = q_goal; - }; - - inline void next_step(const double &time_sec, Vector7d &q_t) { - if (!start_) { - start_time_ = time_sec; - last_q_t_ = q_start_; - start_ = true; - } - // std::cout << q_start_.transpose() << " | " << q_goal_.transpose() << - // std::endl; - if (last_time_ + dt_ <= time_sec) { - double t = - std::min(std::max((time_sec - start_time_) / max_time_, 0.), 1.); - last_q_t_ = q_start_ + t * (q_goal_ - q_start_); - last_time_ = time_sec; - } - q_t = last_q_t_; - }; -}; -} // namespace common -} // namespace rcs -#endif // RCS_LINEAR_POSE_TRAJ_INTERPOLATOR_H From f48c39be3fd195ac5ad863b3057ef53756cae721 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 23:02:52 -0800 Subject: [PATCH 18/39] fix(fr3): take the guard's joint limits from the robot config The FR3 controllers used joint limits hard coded in Franka.cpp, which were the Panda limits (e.g. joint 6 from -0.02 instead of 0.44 rad on the FR3). They now take RobotConfig::joint_limits in their constructors, and FR3TorqueLimits is replaced by a torque_limit field in the configs. --- docs/development/controller_interface.md | 2 +- extensions/rcs_fr3/src/hw/Franka.cpp | 16 +++++---- include/rcs/FR3Controllers.h | 35 +++++++++---------- python/rcs/_core/common.pyi | 23 +++++++------ python/tests/test_fr3_controllers.py | 31 +++++++++++++---- src/pybind/rcs.cpp | 23 ++++++------- src/rcs/FR3Controllers.cpp | 43 ++++++++++++++++-------- 7 files changed, 105 insertions(+), 68 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 8cbd6c151..3005e7815 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -187,7 +187,7 @@ class PinocchioDynamics { | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | -| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | +| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. The joint-limit guard and avoidance use the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | ## Backends diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 7f5135008..5888e2295 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -169,11 +169,13 @@ void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { common::FR3JointControllerConfig config; config.kp = this->m_cfg.kp; config.kd = this->m_cfg.kd; - config.limits.torque_limit = this->m_cfg.torque_limit; + config.torque_limit = this->m_cfg.torque_limit; // a goal per policy step, interpolated over one policy period this->fr3_joint_controller = std::make_shared( - config, std::make_shared( - 1.0 / this->m_cfg.policy_rate)); + config, + std::make_shared( + 1.0 / this->m_cfg.policy_rate), + this->m_cfg.joint_limits); this->fr3_joint_controller->reset( this->controller_state(this->curr_state.load(), 0.0)); } else if (this->running_controller.load() != Controller::jsc) { @@ -267,11 +269,13 @@ void Franka::osc_set_cartesian_position( common::FR3OSCConfig config; config.kp_position = this->m_cfg.kp_p; config.kp_orientation = this->m_cfg.kp_r; - config.limits.torque_limit = this->m_cfg.torque_limit; + config.torque_limit = this->m_cfg.torque_limit; // a goal per policy step, interpolated over one policy period this->fr3_osc = std::make_shared( - config, std::make_shared( - 1.0 / this->m_cfg.policy_rate)); + config, + std::make_shared( + 1.0 / this->m_cfg.policy_rate), + this->m_cfg.joint_limits); this->fr3_osc->reset(this->controller_state(this->curr_state.load(), 0.0)); } else if (this->running_controller.load() != Controller::osc) { throw std::runtime_error( diff --git a/include/rcs/FR3Controllers.h b/include/rcs/FR3Controllers.h index e99a74a9a..4599fee98 100644 --- a/include/rcs/FR3Controllers.h +++ b/include/rcs/FR3Controllers.h @@ -21,26 +21,21 @@ namespace common { // - Dynamics come from the ControllerState (PinocchioDynamics) instead of // franka::Model, which computes the same quantities. -// Safety stage shared by both controllers, applied after the control law. -struct FR3TorqueLimits { - // joint limits for the guard; the values hard coded in Franka.cpp - Vector7d joint_min = (Vector7d() << -2.8973, -1.7628, -2.8973, -3.0718, - -2.8973, -0.0175, -2.8973) - .finished(); - Vector7d joint_max = - (Vector7d() << 2.8978, 1.7628, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973) - .finished(); - // per-joint torque clip, FrankaConfig::torque_limit - Vector7d torque_limit = - (Vector7d() << 87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0).finished(); -}; +// Safety stage shared by both controllers, applied after the control law: no +// torque that pushes a joint closer than 0.1 rad to its limit further, the +// torque rate limit and the per-joint torque clip. The joint limits are those +// of the robot (RobotConfig::joint_limits, lower limits in the first row), +// passed to the constructors. +using JointLimits = Eigen::Matrix; struct FR3JointControllerConfig { Vector7d kp = (Vector7d() << 100.0, 100.0, 100.0, 100.0, 75.0, 150.0, 50.0).finished(); Vector7d kd = (Vector7d() << 20.0, 20.0, 20.0, 20.0, 7.5, 15.0, 5.0).finished(); - FR3TorqueLimits limits; + // per-joint torque clip, FrankaConfig::torque_limit + Vector7d torque_limit = + (Vector7d() << 87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0).finished(); }; // Joint impedance: tau = kp (q_d - q) - kd dq + coriolis, then the safety @@ -48,7 +43,8 @@ struct FR3JointControllerConfig { class FR3JointController : public JointController { public: FR3JointController(const FR3JointControllerConfig& config, - std::shared_ptr interpolator); + std::shared_ptr interpolator, + const JointLimits& joint_limits); void reset(const ControllerState& state) override; void set_goal(const VectorXd& q_goal, std::optional duration = std::nullopt) override; @@ -57,6 +53,7 @@ class FR3JointController : public JointController { private: FR3JointControllerConfig config; std::shared_ptr interpolator; + Vector7d joint_min, joint_max; Vector7d last_tau = Vector7d::Zero(); }; @@ -75,7 +72,9 @@ struct FR3OSCConfig { // null-space push away from joints that are 0.1 to 0.25 rad from a limit Vector7d avoidance_weights = (Vector7d() << 1.0, 1.0, 1.0, 1.0, 1.0, 10.0, 10.0).finished(); - FR3TorqueLimits limits; + // per-joint torque clip, FrankaConfig::torque_limit + Vector7d torque_limit = + (Vector7d() << 87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0).finished(); }; // Decoupled operational-space control as on the FR3 (deoxys): separate @@ -85,7 +84,8 @@ struct FR3OSCConfig { class FR3OSC : public CartesianController { public: FR3OSC(const FR3OSCConfig& config, - std::shared_ptr interpolator); + std::shared_ptr interpolator, + const JointLimits& joint_limits); void reset(const ControllerState& state) override; void set_goal(const Pose& pose_goal, std::optional duration = std::nullopt) override; @@ -94,6 +94,7 @@ class FR3OSC : public CartesianController { private: FR3OSCConfig config; std::shared_ptr interpolator; + Vector7d joint_min, joint_max; Vector7d last_tau = Vector7d::Zero(); }; diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 389f1ff8e..0b036fdcb 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -19,7 +19,6 @@ __all__: list[str] = [ "FR3JointControllerConfig", "FR3OSC", "FR3OSCConfig", - "FR3TorqueLimits", "FrankaHandTCPOffset", "GraspType", "Gripper", @@ -101,21 +100,15 @@ class ControllerState: class FR3JointControllerConfig: kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - limits: FR3TorqueLimits + torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] def __init__(self) -> None: ... class FR3OSCConfig: avoidance_weights: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] kp_orientation: float kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] - limits: FR3TorqueLimits nullspace_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] residual_mass: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - def __init__(self) -> None: ... - -class FR3TorqueLimits: - joint_max: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - joint_min: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] def __init__(self) -> None: ... @@ -473,7 +466,12 @@ class RotVec: ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... class FR3OSC(CartesianController): - def __init__(self, config: FR3OSCConfig, interpolator: CartesianInterpolator) -> None: ... + def __init__( + self, + config: FR3OSCConfig, + interpolator: CartesianInterpolator, + joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], + ) -> None: ... class OSC(CartesianController): def __init__(self, config: OSCConfig, interpolator: CartesianInterpolator) -> None: ... @@ -482,7 +480,12 @@ class LinearCartesianInterpolator(CartesianInterpolator): def __init__(self, duration: float) -> None: ... class FR3JointController(JointController): - def __init__(self, config: FR3JointControllerConfig, interpolator: JointInterpolator) -> None: ... + def __init__( + self, + config: FR3JointControllerConfig, + interpolator: JointInterpolator, + joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], + ) -> None: ... class JointPD(JointController): def __init__( diff --git a/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py index 776982ef4..3c600da20 100644 --- a/python/tests/test_fr3_controllers.py +++ b/python/tests/test_fr3_controllers.py @@ -10,6 +10,7 @@ DT = 0.001 Q0 = np.array([0.0, -0.8, 0.0, -2.4, 0.0, 1.6, 0.8]) # away from the joint limits +JOINT_LIMITS = rcs.ROBOTS[common.RobotType.FR3].joint_limits @pytest.fixture @@ -19,7 +20,9 @@ def dynamics() -> common.PinocchioDynamics: def joint_controller(state) -> common.FR3JointController: - controller = common.FR3JointController(common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05)) + controller = common.FR3JointController( + common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05), JOINT_LIMITS + ) controller.reset(state) return controller @@ -28,7 +31,7 @@ def osc(state, **config) -> common.FR3OSC: cfg = common.FR3OSCConfig() for key, value in config.items(): setattr(cfg, key, value) - controller = common.FR3OSC(cfg, common.LinearCartesianInterpolator(0.05)) + controller = common.FR3OSC(cfg, common.LinearCartesianInterpolator(0.05), JOINT_LIMITS) controller.reset(state) return controller @@ -62,13 +65,12 @@ def test_torque_is_clipped(dynamics): controller.set_goal(Q0 + 1.0, duration=DT) for _ in range(200): tau = controller.step(state) - np.testing.assert_allclose(np.abs(tau), common.FR3TorqueLimits().torque_limit) + np.testing.assert_allclose(np.abs(tau), common.FR3JointControllerConfig().torque_limit) def test_no_torque_towards_a_close_joint_limit(dynamics): - limits = common.FR3TorqueLimits() q = Q0.copy() - q[0] = limits.joint_max[0] - 0.05 + q[0] = JOINT_LIMITS[1, 0] - 0.05 state = dynamics.compute(q, np.zeros(7), DT) controller = joint_controller(state) controller.set_goal(q + 0.3, duration=DT) # pulls joint 1 into the limit @@ -78,6 +80,19 @@ def test_no_torque_towards_a_close_joint_limit(dynamics): assert tau[1] > 0.0 +def test_guard_uses_the_limits_of_the_robot(dynamics): + # the lower limit of joint 6 is 0.44 rad on the FR3 (-0.02 rad on the Panda) + q = Q0.copy() + q[5] = JOINT_LIMITS[0, 5] + 0.05 + state = dynamics.compute(q, np.zeros(7), DT) + controller = joint_controller(state) + controller.set_goal(q - 0.3, duration=DT) # pulls joint 6 into the limit + for _ in range(20): + tau = controller.step(state) + assert tau[5] == 0.0 + assert tau[4] < 0.0 + + def test_osc_holds_without_torque_at_its_posture(dynamics): state = dynamics.compute(Q0, np.zeros(7), DT) np.testing.assert_allclose(osc(state, nullspace_q=Q0).step(state), 0.0, atol=1e-9) @@ -102,7 +117,9 @@ def test_fr3_controllers_in_sim(controller): setup = Setup() if controller == "joint": setup.robot.set_joint_controller( - common.FR3JointController(common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05)) + common.FR3JointController( + common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05), JOINT_LIMITS + ) ) goal = setup.robot.get_joint_position() + np.array([0.1, -0.1, 0.1, 0.1, -0.1, 0.1, 0.2]) setup.robot.set_joint_position(goal) @@ -112,7 +129,7 @@ def test_fr3_controllers_in_sim(controller): else: q_home = setup.robot.get_joint_position() setup.robot.set_cartesian_controller( - common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05)) + common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05), JOINT_LIMITS) ) start = setup.robot.get_cartesian_position() goal = common.Pose(rotation=start.rotation_m(), translation=start.translation() + np.array([0.05, -0.05, 0.0])) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 33ca3a468..876103609 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -534,26 +534,21 @@ PYBIND11_MODULE(_core, m) { std::shared_ptr>(), py::arg("config"), py::arg("interpolator")); - py::class_(common, "FR3TorqueLimits") - .def(py::init<>()) - .def_readwrite("joint_min", &rcs::common::FR3TorqueLimits::joint_min) - .def_readwrite("joint_max", &rcs::common::FR3TorqueLimits::joint_max) - .def_readwrite("torque_limit", - &rcs::common::FR3TorqueLimits::torque_limit); - py::class_(common, "FR3JointControllerConfig") .def(py::init<>()) .def_readwrite("kp", &rcs::common::FR3JointControllerConfig::kp) .def_readwrite("kd", &rcs::common::FR3JointControllerConfig::kd) - .def_readwrite("limits", &rcs::common::FR3JointControllerConfig::limits); + .def_readwrite("torque_limit", + &rcs::common::FR3JointControllerConfig::torque_limit); py::class_>( common, "FR3JointController") .def(py::init>(), - py::arg("config"), py::arg("interpolator")); + std::shared_ptr, + const rcs::common::JointLimits&>(), + py::arg("config"), py::arg("interpolator"), py::arg("joint_limits")); py::class_(common, "FR3OSCConfig") .def(py::init<>()) @@ -564,13 +559,15 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("residual_mass", &rcs::common::FR3OSCConfig::residual_mass) .def_readwrite("avoidance_weights", &rcs::common::FR3OSCConfig::avoidance_weights) - .def_readwrite("limits", &rcs::common::FR3OSCConfig::limits); + .def_readwrite("torque_limit", + &rcs::common::FR3OSCConfig::torque_limit); py::class_>(common, "FR3OSC") .def(py::init>(), - py::arg("config"), py::arg("interpolator")); + std::shared_ptr, + const rcs::common::JointLimits&>(), + py::arg("config"), py::arg("interpolator"), py::arg("joint_limits")); bind_type_class(common, "RobotType") .def_readonly_static("FR3", &rcs::common::RobotType::FR3) diff --git a/src/rcs/FR3Controllers.cpp b/src/rcs/FR3Controllers.cpp index e000f5bc0..a14ccac0c 100644 --- a/src/rcs/FR3Controllers.cpp +++ b/src/rcs/FR3Controllers.cpp @@ -28,20 +28,19 @@ Eigen::MatrixXd pseudo_inverse(const Eigen::MatrixXd& M, return svd.matrixV() * S_inv * svd.matrixU().transpose(); } -// The end of both control loops in Franka.cpp: no torque that pushes a joint -// that is closer than 0.1 rad to its limit further, the torque rate limit, -// and the per-joint torque clip. -Vector7d safety_stage(Vector7d tau, const Vector7d& q, - const FR3TorqueLimits& limits, Vector7d& last_tau) { +// The end of both control loops in Franka.cpp, see FR3Controllers.h. +Vector7d safety_stage(Vector7d tau, const Vector7d& q, const Vector7d& joint_min, + const Vector7d& joint_max, const Vector7d& torque_limit, + Vector7d& last_tau) { for (int i = 0; i < 7; i++) { - if (limits.joint_max[i] - q[i] < 0.1 && tau[i] > 0.) tau[i] = 0.; - if (q[i] - limits.joint_min[i] < 0.1 && tau[i] < 0.) tau[i] = 0.; + if (joint_max[i] - q[i] < 0.1 && tau[i] > 0.) tau[i] = 0.; + if (q[i] - joint_min[i] < 0.1 && tau[i] < 0.) tau[i] = 0.; } for (int i = 0; i < 7; i++) { tau[i] = last_tau[i] + std::clamp(tau[i] - last_tau[i], -kMaxTorqueStep, kMaxTorqueStep); tau[i] = - std::clamp(tau[i], -limits.torque_limit[i], limits.torque_limit[i]); + std::clamp(tau[i], -torque_limit[i], torque_limit[i]); } last_tau = tau; return tau; @@ -53,12 +52,22 @@ void check_seven_joints(const ControllerState& state) { } } +void check_joint_limits(const JointLimits& joint_limits) { + if (joint_limits.cols() != 7) { + throw std::invalid_argument("FR3 controllers need the limits of 7 joints"); + } +} + } // namespace FR3JointController::FR3JointController( const FR3JointControllerConfig& config, - std::shared_ptr interpolator) + std::shared_ptr interpolator, + const JointLimits& joint_limits) : config(config), interpolator(std::move(interpolator)) { + check_joint_limits(joint_limits); + this->joint_min = joint_limits.row(0).transpose(); + this->joint_max = joint_limits.row(1).transpose(); if (!this->interpolator) { throw std::invalid_argument("interpolator must not be null"); } @@ -84,12 +93,17 @@ VectorXd FR3JointController::step(const ControllerState& state) { Vector7d tau = this->config.kp.cwiseProduct(desired_q - q) - this->config.kd.cwiseProduct(dq); tau += state.coriolis; - return safety_stage(tau, q, this->config.limits, this->last_tau); + return safety_stage(tau, q, this->joint_min, this->joint_max, + this->config.torque_limit, this->last_tau); } FR3OSC::FR3OSC(const FR3OSCConfig& config, - std::shared_ptr interpolator) + std::shared_ptr interpolator, + const JointLimits& joint_limits) : config(config), interpolator(std::move(interpolator)) { + check_joint_limits(joint_limits); + this->joint_min = joint_limits.row(0).transpose(); + this->joint_max = joint_limits.row(1).transpose(); if (!this->interpolator) { throw std::invalid_argument("interpolator must not be null"); } @@ -165,8 +179,8 @@ VectorXd FR3OSC::step(const ControllerState& state) { // joint-limit avoidance in the null space Vector7d avoidance = Vector7d::Zero(); for (int i = 0; i < 7; i++) { - double to_max = cfg.limits.joint_max[i] - q[i]; - double to_min = q[i] - cfg.limits.joint_min[i]; + double to_max = this->joint_max[i] - q[i]; + double to_min = q[i] - this->joint_min[i]; if (to_max < 0.25 && to_max > 0.1) avoidance[i] += -cfg.avoidance_weights[i] * to_max; if (to_min < 0.25 && to_min > 0.1) @@ -175,7 +189,8 @@ VectorXd FR3OSC::step(const ControllerState& state) { tau += Nullspace * avoidance; tau += state.coriolis; - return safety_stage(tau, q, cfg.limits, this->last_tau); + return safety_stage(tau, q, this->joint_min, this->joint_max, + cfg.torque_limit, this->last_tau); } } // namespace common From c7a2bc155572e2287041bc9052e27cbb0f3c2c87 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 23:06:23 -0800 Subject: [PATCH 19/39] feat(sim): timestep in SimConfig, 1 ms by default SimConfig::timestep replaces the model's timestep, so torque control runs at 1 kHz like the FR3 loop. FrankaConfig::timestep rejects anything other than 1 ms. max_convergence_steps defaults to 1000 so that synchronous control keeps waiting up to 1 s. --- docs/development/controller_interface.md | 7 +++++-- extensions/rcs_fr3/src/hw/Franka.cpp | 12 ++++++++++++ extensions/rcs_fr3/src/hw/Franka.h | 3 +++ extensions/rcs_fr3/src/pybind/rcs.cpp | 1 + extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 1 + python/rcs/_core/sim.pyi | 4 +++- python/rcs/envs/configs.py | 6 +++--- python/tests/test_sim_torque_control.py | 12 ++++++++++-- src/pybind/rcs.cpp | 7 +++++-- src/sim/sim.cpp | 4 ++++ src/sim/sim.h | 5 ++++- 11 files changed, 51 insertions(+), 11 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 3005e7815..56285dbe0 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -316,8 +316,11 @@ the robot**. - **Interpolators**: only linear ones for now. A jerk-limited Ruckig interpolator would be one more `JointInterpolator` and can be added later without interface changes. -- **Timestep**: torque-controlled sim scenes use a 1 ms MuJoCo timestep, so - the controller runs at 1 kHz as on the FR3 and gains carry over. +- **Timestep**: `SimConfig::timestep` (default 1 ms) replaces the timestep + of the scene, so the controller runs at 1 kHz as on the FR3 and gains carry + over. `FrankaConfig::timestep` exists for symmetry and must be 1 ms, the + period of the libfranka loop. The default `max_convergence_steps` doubled to + 1000 so that synchronous control still waits up to 1 s. - **Linear interpolator start point**: the current setpoint (see Timing). The current FR3 interpolator starts each segment at the previous goal, which jumps when a goal arrives early; this is a small, intended behaviour diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 5888e2295..73a72da6c 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -28,12 +29,22 @@ common::Pose GetTCPInBaseFrame(const franka::RobotState& robot_state, return GetFlangeInBaseFrame(robot_state) * tcp_offset; } +namespace { +void check_timestep(const FrankaConfig& cfg) { + if (cfg.timestep != 0.001) { + throw std::invalid_argument( + "the Franka control loop runs at 1 ms, timestep must be 0.001"); + } +} +} // namespace + Franka::Franka(const FrankaConfig& cfg, std::optional> ik) : m_cfg(cfg), m_ik(ik), robot(cfg.ip, cfg.ignore_realtime ? franka::RealtimeConfig::kIgnore : franka::RealtimeConfig::kEnforce) { + check_timestep(cfg); // set collision behavior and impedance this->set_default_robot_behavior(); this->set_guiding_mode(true, true, true, true, true, true, true); @@ -53,6 +64,7 @@ Franka::~Franka() { * otherwise the call will fail */ bool Franka::set_config(const FrankaConfig& cfg) { + check_timestep(cfg); this->m_cfg = cfg; this->m_cfg.speed_factor = std::min(std::max(cfg.speed_factor, 0.0), 1.0); diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index fbedcc112..06d411f37 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -43,6 +43,9 @@ struct FrankaConfig : common::RobotConfig { // Rate (Hz) at which set-point commands are streamed from the Python side. // Used to size the interpolation window between successive targets. int policy_rate = 20; + // period of the control loop in seconds; libfranka runs it at 1 kHz, so + // anything else is rejected + double timestep = 0.001; // values from deoxys/config/joint-impedance-controller.yml common::Vector7d kp = (common::Vector7d() << 100., 100., 100., 100., 75., 150., 50.).finished(); diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index fc3ddc188..f977d814c 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -129,6 +129,7 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("ik_solver", &rcs::hw::FrankaConfig::ik_solver) .def_readwrite("speed_factor", &rcs::hw::FrankaConfig::speed_factor) .def_readwrite("policy_rate", &rcs::hw::FrankaConfig::policy_rate) + .def_readwrite("timestep", &rcs::hw::FrankaConfig::timestep) .def_readwrite("kp", &rcs::hw::FrankaConfig::kp) .def_readwrite("kd", &rcs::hw::FrankaConfig::kd) .def_readwrite("torque_limit", &rcs::hw::FrankaConfig::torque_limit) diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 5b9ab3eb7..95efa5a75 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -122,6 +122,7 @@ class FrankaConfig(rcs._core.common.RobotConfig): speed_factor: float tcp_offset: rcs._core.common.Pose tcp_offset_explicit: bool + timestep: float torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] world_to_robot: rcs._core.common.Pose | None diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index ab358aac5..d3246a501 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -112,6 +112,7 @@ class SimConfig: memory: int realtime: bool renderer: RendererBackend + timestep: float def __copy__(self) -> SimConfig: ... def __deepcopy__(self, arg0: dict) -> SimConfig: ... def __init__( @@ -119,9 +120,10 @@ class SimConfig: async_control: bool = False, realtime: bool = False, frequency: float = 30.0, - max_convergence_steps: int = 500, + max_convergence_steps: int = 1000, memory: int = -1, renderer: RendererBackend = ..., + timestep: float = 0.001, ) -> None: ... class SimGripper(rcs._core.common.Gripper): diff --git a/python/rcs/envs/configs.py b/python/rcs/envs/configs.py index d79ad936f..a35792752 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -75,7 +75,7 @@ def config(self) -> SimEnvCreatorConfig: ) robot_cfgs: dict[str, SimRobotConfig] = {self.robot_prefix_template: robot_cfg} - sim_cfg: SimConfig = SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=500) + sim_cfg: SimConfig = SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=1000) control_mode: ControlMode = ControlMode.CARTESIAN_TQuat task_cfg = None @@ -318,7 +318,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfg_right.q_home = rcs.HOME_POSITIONS["FR3_DUO_RIGHT"] robot_cfgs: dict[str, SimRobotConfig] = {"left": robot_cfg, "right": robot_cfg_right} - sim_cfg: SimConfig = SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=500) + sim_cfg: SimConfig = SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=1000) control_mode: ControlMode = ControlMode.CARTESIAN_TQuat task_cfg = None @@ -810,7 +810,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfgs=robot_cfgs, gripper_cfgs=gripper_cfgs, gripper_offsets={"left": grav_offset, "right": grav_offset}, - sim_cfg=SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=500), + sim_cfg=SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=1000), control_mode=ControlMode.CARTESIAN_TQuat, scene=SCENE_PATHS["empty_world"], robot_frame_objects=robot_frame_objects, diff --git a/python/tests/test_sim_torque_control.py b/python/tests/test_sim_torque_control.py index ad6862e02..ec813d419 100644 --- a/python/tests/test_sim_torque_control.py +++ b/python/tests/test_sim_torque_control.py @@ -22,11 +22,10 @@ def __init__(self, payload: common.Payload | None = None, friction: bool = True) robot_cfg = cfg.robot_cfgs[name] robot_cfg.payload = payload model = scene.create_model(cfg) - model.spec.option.timestep = TIMESTEP if not friction: for joint in model.spec.joints: joint.frictionloss = 0.0 - self.sim = sim.Sim(model, sim.SimConfig(async_control=True)) + self.sim = sim.Sim(model, sim.SimConfig(async_control=True)) # 1 ms timestep by default path, site = scene.kinematics_cfg(cfg)[name] ik = common.Pin(path, site, joint_limits=robot_cfg.joint_limits) self.robot = sim.SimRobot(self.sim, ik, robot_cfg) @@ -53,6 +52,15 @@ def pose_error(a: common.Pose, b: common.Pose) -> tuple[float, float]: return float(np.linalg.norm(a.translation() - b.translation())), float(angle) +def test_sim_config_sets_the_timestep(): + setup = Setup() + assert setup.sim.model.opt.timestep == TIMESTEP + setup.sim.set_config(sim.SimConfig(timestep=0.002)) + assert setup.sim.model.opt.timestep == 0.002 + with pytest.raises(ValueError): + setup.sim.set_config(sim.SimConfig(timestep=0.0)) + + def test_simulated_payload_is_the_gripper(): setup = Setup() payload = setup.robot.get_simulated_payload() diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 876103609..512e65119 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -947,7 +947,7 @@ PYBIND11_MODULE(_core, m) { py::class_(sim, "SimConfig") .def(py::init([](bool async_control, bool realtime, double frequency, int max_convergence_steps, long long memory, - rcs::sim::RendererBackend renderer) { + rcs::sim::RendererBackend renderer, double timestep) { rcs::sim::SimConfig config; config.async_control = async_control; config.realtime = realtime; @@ -955,6 +955,7 @@ PYBIND11_MODULE(_core, m) { config.max_convergence_steps = max_convergence_steps; config.memory = memory; config.renderer = renderer; + config.timestep = timestep; return config; }), py::arg("async_control") = default_sim_cfg.async_control, @@ -963,7 +964,8 @@ PYBIND11_MODULE(_core, m) { py::arg("max_convergence_steps") = default_sim_cfg.max_convergence_steps, py::arg("memory") = default_sim_cfg.memory, - py::arg("renderer") = default_sim_cfg.renderer) + py::arg("renderer") = default_sim_cfg.renderer, + py::arg("timestep") = default_sim_cfg.timestep) .def_readwrite("async_control", &rcs::sim::SimConfig::async_control) .def_readwrite("realtime", &rcs::sim::SimConfig::realtime) .def_readwrite("frequency", &rcs::sim::SimConfig::frequency) @@ -971,6 +973,7 @@ PYBIND11_MODULE(_core, m) { &rcs::sim::SimConfig::max_convergence_steps) .def_readwrite("memory", &rcs::sim::SimConfig::memory) .def_readwrite("renderer", &rcs::sim::SimConfig::renderer) + .def_readwrite("timestep", &rcs::sim::SimConfig::timestep) .def("__copy__", [](const rcs::sim::SimConfig& self) { return rcs::sim::SimConfig(self); diff --git a/src/sim/sim.cpp b/src/sim/sim.cpp index a55221fd9..91208120b 100644 --- a/src/sim/sim.cpp +++ b/src/sim/sim.cpp @@ -79,7 +79,11 @@ Sim::Sim(mjModel* m, mjData* d) : m(m), d(d) { }; bool Sim::set_config(const SimConfig& cfg) { + if (cfg.timestep <= 0.0) { + throw std::invalid_argument("timestep must be positive"); + } this->cfg = cfg; + this->m->opt.timestep = cfg.timestep; return true; } diff --git a/src/sim/sim.h b/src/sim/sim.h index 60c503226..804481e11 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -22,13 +22,16 @@ struct SimConfig { bool async_control = false; bool realtime = false; double frequency = 30; // in Hz - int max_convergence_steps = 500; + int max_convergence_steps = 1000; // physics steps, 1 s at the default timestep // MuJoCo arena (stack + constraint) size in bytes, applied when a scene is // compiled from a ModelComposer. -1 keeps the model's or // MuJoCo's automatic sizing, which can be too small for scenes with many // contacts ("mj_stackAlloc: insufficient memory"). long long memory = -1; RendererBackend renderer = RendererBackend::CLASSIC; + // physics timestep in seconds, replaces the one of the model; torque + // control runs the controllers once per step, as the 1 ms loop of the FR3 + double timestep = 0.001; }; /* Fixed schedule of a callback in simulation time: the k-th call is due at From 09c89a86898615a81959e370eb234ab52497a86c Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 23:10:09 -0800 Subject: [PATCH 20/39] fix(fr3): stop FrankaConfig from hiding RobotConfig::joint_limits FrankaConfig and PandaConfig redeclared joint_limits, so the limits set from Python (RobotConfig::joint_limits, rcs.ROBOTS) never reached Franka.cpp, which read the hidden member with conservative defaults. PandaConfig now sets the inherited member instead. --- extensions/rcs_fr3/src/hw/Franka.h | 37 ++++++++++++++---------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 06d411f37..c405f8178 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -83,31 +83,28 @@ struct FrankaConfig : common::RobotConfig { double approach_cartesian_speed = 0.1; double approach_rotation_speed = 0.5; bool ignore_realtime = false; - size_t dof = 7; - Eigen::Matrix joint_limits = - (Eigen::Matrix(2, 7) << - // low 7‐tuple - -2.3476, - -1.5454, -2.4937, -2.7714, -2.5100, 0.7773, -2.7045, - // high 7‐tuple - 2.3476, 1.5454, 2.4937, -0.4226, 2.5100, 4.2841, 2.7045) - .finished(); + // dof and joint_limits are those of RobotConfig, set them per robot (from + // rcs.ROBOTS in Python) }; struct FR3Config : FrankaConfig {}; struct PandaConfig : FrankaConfig { common::RobotType robot_type = common::RobotType::Panda; - Eigen::Matrix joint_limits = - (Eigen::Matrix(2, 7) << - // low 7‐tuple - -166. / 180. * M_PI, - -101. / 180. * M_PI, -166. / 180. * M_PI, -176. / 180. * M_PI, - -166. / 180. * M_PI, -1. / 180. * M_PI, -166. / 180. * M_PI, - // high 7‐tuple - 166. / 180. * M_PI, 101. / 180. * M_PI, 166. / 180. * M_PI, - -4. / 180. * M_PI, 166. / 180. * M_PI, 215. / 180. * M_PI, - 166. / 180. * M_PI) - .finished(); + PandaConfig() { + // set the inherited limits; a member of the same name would hide them + // from Franka, which works on a FrankaConfig + this->joint_limits = + (Eigen::Matrix(2, 7) << + // low 7‐tuple + -166. / 180. * M_PI, + -101. / 180. * M_PI, -166. / 180. * M_PI, -176. / 180. * M_PI, + -166. / 180. * M_PI, -1. / 180. * M_PI, -166. / 180. * M_PI, + // high 7‐tuple + 166. / 180. * M_PI, 101. / 180. * M_PI, 166. / 180. * M_PI, + -4. / 180. * M_PI, 166. / 180. * M_PI, 215. / 180. * M_PI, + 166. / 180. * M_PI) + .finished(); + } }; struct FrankaState : common::RobotState { From 6343ee4cc1586ac8b687e0fcdeace9157a095889 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 23:12:50 -0800 Subject: [PATCH 21/39] feat(control): select the controller with RobotConfig::controller The controller is identified by its config (JointPDConfig, OSCConfig, FR3JointControllerConfig, FR3OSCConfig); make_controller() builds it with an interpolator over one control period and the robot's joint limits. SimRobot installs it once it has the dynamics, which the env creators now set when a controller is configured. Franka uses it instead of its default FR3 controllers. Goals of the other kind go through IK or forward kinematics, and a configured controller needs asynchronous control. --- docs/development/controller_interface.md | 35 +++++++ extensions/rcs_fr3/src/hw/Franka.cpp | 90 +++++++++++------ extensions/rcs_fr3/src/hw/Franka.h | 15 ++- include/rcs/ControllerConfig.h | 49 +++++++++ include/rcs/Robot.h | 4 + python/rcs/_core/common.pyi | 11 ++ python/rcs/envs/scenes.py | 11 +- python/tests/test_controller_config.py | 123 +++++++++++++++++++++++ python/tests/test_sim_torque_control.py | 4 +- src/pybind/rcs.cpp | 13 ++- src/rcs/CMakeLists.txt | 2 +- src/rcs/ControllerConfig.cpp | 40 ++++++++ src/sim/SimRobot.cpp | 30 ++++++ src/sim/SimRobot.h | 6 +- 14 files changed, 394 insertions(+), 39 deletions(-) create mode 100644 include/rcs/ControllerConfig.h create mode 100644 python/tests/test_controller_config.py create mode 100644 src/rcs/ControllerConfig.cpp diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 56285dbe0..35a489225 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -191,6 +191,38 @@ class PinocchioDynamics { ## Backends +### Selecting a controller (`RobotConfig::controller`) + +A controller is identified by its config, so one optional field in the +common `RobotConfig` selects it for any backend: + +```python +robot_cfg.controller = common.FR3OSCConfig() # FR3OSC +robot_cfg.controller = common.OSCConfig() # core OSC +robot_cfg.controller = common.FR3JointControllerConfig() +robot_cfg.controller = common.JointPDConfig(kp=..., kd=...) +robot_cfg.controller = None # native control +``` + +`make_controller()` (`ControllerConfig.h`) builds it with a linear +interpolator over one control period (sim: `1 / SimConfig::frequency`, +FR3: `1 / FrankaConfig::policy_rate`) and the robot's joint limits. A goal of +the other kind is converted: with a joint controller, Cartesian goals go +through IK; with a Cartesian controller, joint goals through forward +kinematics. A configured controller needs asynchronous control (sim: +`SimConfig::async_control`, FR3: `FrankaConfig::async_control`), because +synchronous control steps until the goal is reached, which friction can +prevent under torque control. + +- Sim: `SimRobot` installs the configured controller once it also has the + dynamics. The env creators set them (`SimEnvCreator.add_robot_env`) from + the robot's kinematic model, the same file and site as its IK, so nothing + else needs configuring. The sim timestep is `SimConfig::timestep` + (default 1 ms). +- FR3: without a configured controller `Franka` keeps its defaults: + `FR3JointController` for joint goals and `FR3OSC` for Cartesian goals, + with the gains of `FrankaConfig`. + ### MuJoCo (`SimRobot`) - New: `set_dynamics(shared_ptr)`, then @@ -256,6 +288,7 @@ class PinocchioDynamics { uses of `Franka` don't need a model. - By default `Franka` builds an `FR3JointController` / `FR3OSC` from `FrankaConfig`, so the Python API and configs are unchanged. + `RobotConfig::controller` replaces them (see above). ### Using the FR3 controllers in sim @@ -280,6 +313,8 @@ is **not** modelled. 7. `Franka` uses `PinocchioDynamics` and the FR3 controllers; delete `LinearPoseTrajInterpolator.h`. Before that, a read-only check on the robot that `PinocchioDynamics` matches `franka::Model` on live states. +8. `RobotConfig::controller` selects the controller in both backends and the + env creators; `SimConfig::timestep` defaults to 1 ms. ## Validation diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 73a72da6c..5fc829f3c 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -30,11 +30,14 @@ common::Pose GetTCPInBaseFrame(const franka::RobotState& robot_state, } namespace { -void check_timestep(const FrankaConfig& cfg) { +void check_config(const FrankaConfig& cfg) { if (cfg.timestep != 0.001) { throw std::invalid_argument( "the Franka control loop runs at 1 ms, timestep must be 0.001"); } + if (cfg.controller.has_value() && !cfg.async_control) { + throw std::invalid_argument("a configured controller needs async_control"); + } } } // namespace @@ -44,7 +47,7 @@ Franka::Franka(const FrankaConfig& cfg, m_ik(ik), robot(cfg.ip, cfg.ignore_realtime ? franka::RealtimeConfig::kIgnore : franka::RealtimeConfig::kEnforce) { - check_timestep(cfg); + check_config(cfg); // set collision behavior and impedance this->set_default_robot_behavior(); this->set_guiding_mode(true, true, true, true, true, true, true); @@ -64,7 +67,7 @@ Franka::~Franka() { * otherwise the call will fail */ bool Franka::set_config(const FrankaConfig& cfg) { - check_timestep(cfg); + check_config(cfg); this->m_cfg = cfg; this->m_cfg.speed_factor = std::min(std::max(cfg.speed_factor, 0.0), 1.0); @@ -143,6 +146,18 @@ common::Pose Franka::get_cartesian_flange_position() { void Franka::set_joint_position(const common::VectorXd& q) { if (this->m_cfg.async_control) { + if (this->m_cfg.controller.has_value() && + common::is_cartesian(this->m_cfg.controller.value())) { + // only a Cartesian controller: move the TCP to where q would put it + // (forward kinematics of the IK model, the dynamics belong to the loop) + if (!this->m_ik.has_value()) { + throw std::runtime_error( + "joint goals for a Cartesian controller need kinematics"); + } + this->osc_set_cartesian_position( + this->m_ik.value()->forward(q, this->m_cfg.tcp_offset)); + return; + } this->controller_set_joint_position(q); return; } @@ -178,17 +193,8 @@ void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { this->controller_time = 0.0; this->get_joint_position(); this->create_dynamics(); - common::FR3JointControllerConfig config; - config.kp = this->m_cfg.kp; - config.kd = this->m_cfg.kd; - config.torque_limit = this->m_cfg.torque_limit; - // a goal per policy step, interpolated over one policy period - this->fr3_joint_controller = std::make_shared( - config, - std::make_shared( - 1.0 / this->m_cfg.policy_rate), - this->m_cfg.joint_limits); - this->fr3_joint_controller->reset( + this->torque_joint_controller = this->make_torque_controller(false).joint; + this->torque_joint_controller->reset( this->controller_state(this->curr_state.load(), 0.0)); } else if (this->running_controller.load() != Controller::jsc) { // runtime error @@ -216,7 +222,7 @@ void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { std::clamp(max_gap / speed, kMinApproachTime, kMaxApproachTime); } - this->fr3_joint_controller->set_goal( + this->torque_joint_controller->set_goal( desired_q, approach_on_start ? std::optional(approach_time) : std::nullopt); @@ -278,17 +284,10 @@ void Franka::osc_set_cartesian_position( this->controller_time = 0.0; this->curr_state.store(this->robot.readOnce()); this->create_dynamics(); - common::FR3OSCConfig config; - config.kp_position = this->m_cfg.kp_p; - config.kp_orientation = this->m_cfg.kp_r; - config.torque_limit = this->m_cfg.torque_limit; - // a goal per policy step, interpolated over one policy period - this->fr3_osc = std::make_shared( - config, - std::make_shared( - 1.0 / this->m_cfg.policy_rate), - this->m_cfg.joint_limits); - this->fr3_osc->reset(this->controller_state(this->curr_state.load(), 0.0)); + this->torque_cartesian_controller = + this->make_torque_controller(true).cartesian; + this->torque_cartesian_controller->reset( + this->controller_state(this->curr_state.load(), 0.0)); } else if (this->running_controller.load() != Controller::osc) { throw std::runtime_error( "Controller type must but osc but is " + @@ -323,7 +322,7 @@ void Franka::osc_set_cartesian_position( kMinApproachTime, kMaxApproachTime); } - this->fr3_osc->set_goal( + this->torque_cartesian_controller->set_goal( desired_pose_EE_in_base_frame, approach_on_start ? std::optional(approach_time) : std::nullopt); @@ -384,6 +383,33 @@ void Franka::stop_control_thread() { } } +common::ControllerPair Franka::make_torque_controller(bool cartesian) { + common::ControllerConfig config; + if (this->m_cfg.controller.has_value()) { + config = this->m_cfg.controller.value(); + if (common::is_cartesian(config) != cartesian) { + throw std::runtime_error( + cartesian ? "the configured controller is a joint controller" + : "the configured controller is a Cartesian controller"); + } + } else if (cartesian) { + common::FR3OSCConfig osc; + osc.kp_position = this->m_cfg.kp_p; + osc.kp_orientation = this->m_cfg.kp_r; + osc.torque_limit = this->m_cfg.torque_limit; + config = osc; + } else { + common::FR3JointControllerConfig joint; + joint.kp = this->m_cfg.kp; + joint.kd = this->m_cfg.kd; + joint.torque_limit = this->m_cfg.torque_limit; + config = joint; + } + // a goal per policy step, interpolated over one policy period + return common::make_controller(config, 1.0 / this->m_cfg.policy_rate, + this->m_cfg.joint_limits); +} + void Franka::create_dynamics() { if (!this->dynamics) { const std::string& path = this->m_cfg.kinematic_model_path; @@ -440,7 +466,7 @@ void Franka::osc() { std::lock_guard lock(this->interpolator_mutex); this->controller_time += period.toSec(); - common::VectorXd tau = this->fr3_osc->step( + common::VectorXd tau = this->torque_cartesian_controller->step( this->controller_state(robot_state, period.toSec())); std::array tau_array{}; common::VectorXd::Map(tau_array.data(), 7) = tau; @@ -480,7 +506,7 @@ void Franka::joint_controller() { std::lock_guard lock(this->interpolator_mutex); this->controller_time += period.toSec(); - common::VectorXd tau = this->fr3_joint_controller->step( + common::VectorXd tau = this->torque_joint_controller->step( this->controller_state(robot_state, period.toSec())); std::array tau_array{}; common::VectorXd::Map(tau_array.data(), 7) = tau; @@ -624,6 +650,12 @@ std::optional> Franka::get_ik() { void Franka::set_cartesian_position(const common::Pose& x) { // pose is assumed to be in the robots coordinate frame if (this->m_cfg.async_control) { + if (this->m_cfg.controller.has_value() && + !common::is_cartesian(this->m_cfg.controller.value())) { + // only a joint controller: reach the pose through IK + this->set_cartesian_position_ik(x); + return; + } this->osc_set_cartesian_position(x); return; } diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index c405f8178..4d85ac45e 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -13,6 +13,7 @@ #include #include "rcs/Controller.h" +#include "rcs/ControllerConfig.h" #include "rcs/FR3Controllers.h" #include "rcs/Kinematics.h" #include "rcs/PinocchioDynamics.h" @@ -46,6 +47,9 @@ struct FrankaConfig : common::RobotConfig { // period of the control loop in seconds; libfranka runs it at 1 kHz, so // anything else is rejected double timestep = 0.001; + // The gains and torque limit below are for the default controllers, used + // when RobotConfig::controller is not set. A configured controller needs + // async_control. // values from deoxys/config/joint-impedance-controller.yml common::Vector7d kp = (common::Vector7d() << 100., 100., 100., 100., 75., 150., 50.).finished(); @@ -119,11 +123,14 @@ class Franka : public common::Robot { std::optional control_thread = std::nullopt; double controller_time = 0.0; // The shared torque controllers (core), stepped in the libfranka control - // loop. They are created when a controller thread starts, so the gains and - // the interpolation window (1 / policy_rate) stay fixed for its lifetime. + // loop: RobotConfig::controller, or without it FR3JointController and + // FR3OSC with the gains below. They are created when a controller thread + // starts, so the gains and the interpolation window (1 / policy_rate) stay + // fixed for its lifetime. std::shared_ptr dynamics; - std::shared_ptr fr3_joint_controller; - std::shared_ptr fr3_osc; + std::shared_ptr torque_joint_controller; + std::shared_ptr torque_cartesian_controller; + common::ControllerPair make_torque_controller(bool cartesian); common::ThreadSafeValue curr_state; // guards the controllers between set_goal() and the control loop std::mutex interpolator_mutex; diff --git a/include/rcs/ControllerConfig.h b/include/rcs/ControllerConfig.h new file mode 100644 index 000000000..e3a84f089 --- /dev/null +++ b/include/rcs/ControllerConfig.h @@ -0,0 +1,49 @@ +#ifndef RCS_CONTROLLER_CONFIG_H +#define RCS_CONTROLLER_CONFIG_H + +#include +#include + +#include "Controller.h" +#include "Controllers.h" +#include "FR3Controllers.h" +#include "utils.h" + +namespace rcs { +namespace common { + +struct JointPDConfig { + // one gain per joint, no defaults as they depend on the robot + VectorXd kp; + VectorXd kd; +}; + +// A controller, identified by its config. RobotConfig::controller holds one; +// none means the robot's native control. The type of the config selects the +// controller; JointPDConfig and FR3JointControllerConfig give joint +// controllers, OSCConfig and FR3OSCConfig Cartesian ones. +using ControllerConfig = std::variant; + +// Whether the config gives a Cartesian controller (else a joint controller). +inline bool is_cartesian(const ControllerConfig& config) { + return std::holds_alternative(config) || + std::holds_alternative(config); +} + +// The controller built from a config, exactly one of the two is set. +struct ControllerPair { + std::shared_ptr joint; + std::shared_ptr cartesian; +}; + +// Builds the controller with a linear interpolator that spreads each goal +// over interpolation_time (the control period of the policy). The joint +// limits are the robot's, as in RobotConfig::joint_limits. +ControllerPair make_controller(const ControllerConfig& config, + double interpolation_time, + const JointLimits& joint_limits); + +} // namespace common +} // namespace rcs +#endif // RCS_CONTROLLER_CONFIG_H diff --git a/include/rcs/Robot.h b/include/rcs/Robot.h index 25ed354fc..e21166fba 100644 --- a/include/rcs/Robot.h +++ b/include/rcs/Robot.h @@ -7,6 +7,7 @@ #include #include +#include "ControllerConfig.h" #include "Kinematics.h" #include "Pose.h" #include "utils.h" @@ -76,6 +77,9 @@ struct RobotConfig { // high 7‐tuple 2.3476, 1.5454, 2.4937, -0.4226, 2.5100, 4.2841, 2.7045) .finished(); + // The controller to run, see ControllerConfig.h. None: the robot's native + // control (MuJoCo actuators in sim, the default controllers on hardware). + std::optional controller = std::nullopt; virtual ~RobotConfig() {}; }; struct RobotState { diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 0b036fdcb..b9cc65d8c 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -36,6 +36,7 @@ __all__: list[str] = [ "JointController", "JointInterpolator", "JointPD", + "JointPDConfig", "JointSetpoint", "Kinematics", "LATERAL_GRASP", @@ -230,6 +231,15 @@ class JointInterpolator: ) -> None: ... def step(self, dt: float) -> JointSetpoint: ... +class JointPDConfig: + kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __init__( + self, + kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + ) -> None: ... + class JointSetpoint: @property def dq(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... @@ -387,6 +397,7 @@ class Robot: class RobotConfig(typing.Generic[M]): attachment_site: str + controller: JointPDConfig | OSCConfig | FR3JointControllerConfig | FR3OSCConfig | None dof: int joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]] kinematic_model_path: str diff --git a/python/rcs/envs/scenes.py b/python/rcs/envs/scenes.py index 6b7832666..72962918e 100644 --- a/python/rcs/envs/scenes.py +++ b/python/rcs/envs/scenes.py @@ -478,7 +478,16 @@ def add_robot_env( ik: rcs.common.Kinematics, ): # rcs wrapper composition - robot = rcs.sim.SimRobot(sim=simulation, ik=ik, cfg=prefixed_cfg.robot_cfgs[robot_name]) + robot_cfg = prefixed_cfg.robot_cfgs[robot_name] + robot = rcs.sim.SimRobot(sim=simulation, ik=ik, cfg=robot_cfg) + if robot_cfg.controller is not None: + # installs the configured controller (torque control) + kinematic_model_path, attachment_site = self.kinematics_cfg(prefixed_cfg)[robot_name] + robot.set_dynamics( + rcs.common.PinocchioDynamics( + kinematic_model_path, kinematic_model_path.endswith(".urdf"), attachment_site + ) + ) env = RobotWrapper(env, robot, prefixed_cfg.control_mode, home_on_reset=prefixed_cfg.wrapper_cfg.home_on_reset) return RobotSimWrapper(env) diff --git a/python/tests/test_controller_config.py b/python/tests/test_controller_config.py new file mode 100644 index 000000000..dd782c47c --- /dev/null +++ b/python/tests/test_controller_config.py @@ -0,0 +1,123 @@ +"""Selecting a controller through RobotConfig.controller.""" + +import copy + +import numpy as np +import pytest +from rcs.envs.base import ControlMode, JointsDictType, RelativeTo, TQuatDictType +from rcs.envs.configs import EmptyWorldFR3, EmptyWorldFR3Duo +from test_sim_torque_control import KD, KP, Setup, pose_error + +from rcs import common, sim + +FREQUENCY = 20 # Hz, the env's control rate in async mode + + +def env_config(scene, control_mode: ControlMode, controller): + cfg = copy.deepcopy(scene.config()) + cfg.control_mode = control_mode + cfg.task_cfg = None + cfg.gripper_cfgs = None + cfg.gripper_offsets = None + cfg.camera_cfgs = None + cfg.camera_adds = None + cfg.headless = True + cfg.sim_cfg.realtime = False + cfg.sim_cfg.async_control = True + cfg.sim_cfg.frequency = FREQUENCY + cfg.max_relative_movement = None + cfg.relative_to = RelativeTo.NONE + for robot_cfg in cfg.robot_cfgs.values(): + robot_cfg.controller = controller + return cfg + + +def assert_torque_controlled(env): + # position servos became motors: no bias term (the scenes have no other actuators) + model = env.get_wrapper_attr("sim").model + assert model.nu > 0 + assert np.all(model.actuator_biastype == 0) + + +@pytest.mark.parametrize( + "config", + [common.JointPDConfig(kp=KP, kd=KD), common.OSCConfig(), common.FR3JointControllerConfig(), common.FR3OSCConfig()], +) +def test_robot_config_holds_any_controller_config(config): + robot_cfg = sim.SimRobotConfig() + assert robot_cfg.controller is None + robot_cfg.controller = config + assert type(robot_cfg.controller) is type(config) + assert type(copy.deepcopy(robot_cfg).controller) is type(config) + + +def test_joint_controller_in_both_arms_of_a_duo_env(): + scene = EmptyWorldFR3Duo() + env = scene.create_env(env_config(scene, ControlMode.JOINTS, common.FR3JointControllerConfig())) + assert_torque_controlled(env) + obs, _ = env.reset() + offset = np.array([0.1, -0.1, 0.1, 0.1, -0.1, 0.1, 0.2]) + goals = {name: obs[name]["joints"] + offset for name in obs} + for _ in range(2 * FREQUENCY): # 2 s + obs, *_ = env.step({name: JointsDictType(joints=goal) for name, goal in goals.items()}) + for name, goal in goals.items(): + # joint friction in the model leaves a steady-state error + assert np.max(np.abs(obs[name]["joints"] - goal)) < 0.03 + env.close() + + +def test_cartesian_controller_in_an_env(): + scene = EmptyWorldFR3() + env = scene.create_env(env_config(scene, ControlMode.CARTESIAN_TQuat, common.FR3OSCConfig())) + assert_torque_controlled(env) + obs, _ = env.reset() + name = scene.lead_robot_name(scene.config()) + goal = obs[name]["tquat"].copy() + goal[:3] += np.array([0.05, -0.05, 0.0]) + for _ in range(3 * FREQUENCY): # 3 s + obs, *_ = env.step({name: TQuatDictType(tquat=goal)}) + assert np.linalg.norm(obs[name]["tquat"][:3] - goal[:3]) < 0.02 + env.close() + + +def configured(controller, async_control=True) -> Setup: + setup = Setup(async_control=async_control) + cfg = setup.robot.get_config() + cfg.controller = controller + setup.robot.set_config(cfg) + return setup + + +def test_joint_controller_reaches_cartesian_goals_through_ik(): + setup = configured(common.JointPDConfig(kp=KP, kd=KD)) + start = setup.robot.get_cartesian_position() + goal = common.Pose(rotation=start.rotation_m(), translation=start.translation() + np.array([0.03, 0.0, -0.03])) + setup.robot.set_cartesian_position(goal) + setup.run(2.0) + position_error, _ = pose_error(setup.robot.get_cartesian_position(), goal) + assert position_error < 0.01 + + +def test_configured_controller_drives_motors(): + setup = configured(common.OSCConfig()) + model = setup.sim.model + # position servos became motors: no bias term + assert np.all(model.actuator_biastype[:7] == 0) + + +def test_configured_controller_needs_async_control(): + with pytest.raises(RuntimeError, match="async_control"): + configured(common.OSCConfig(), async_control=False) + + +def test_no_way_back_to_native_control(): + setup = configured(common.OSCConfig()) + cfg = setup.robot.get_config() + cfg.controller = None + with pytest.raises(RuntimeError): + setup.robot.set_config(cfg) + + +def test_joint_pd_config_needs_gains(): + with pytest.raises(ValueError): + configured(common.JointPDConfig(kp=np.array([]), kd=np.array([]))) diff --git a/python/tests/test_sim_torque_control.py b/python/tests/test_sim_torque_control.py index ec813d419..1b6b64458 100644 --- a/python/tests/test_sim_torque_control.py +++ b/python/tests/test_sim_torque_control.py @@ -15,7 +15,7 @@ class Setup: - def __init__(self, payload: common.Payload | None = None, friction: bool = True): + def __init__(self, payload: common.Payload | None = None, friction: bool = True, async_control: bool = True): scene = EmptyWorldFR3() cfg = scene.prefixed_cfg(scene.config()) name = scene.lead_robot_name(cfg) @@ -25,7 +25,7 @@ def __init__(self, payload: common.Payload | None = None, friction: bool = True) if not friction: for joint in model.spec.joints: joint.frictionloss = 0.0 - self.sim = sim.Sim(model, sim.SimConfig(async_control=True)) # 1 ms timestep by default + self.sim = sim.Sim(model, sim.SimConfig(async_control=async_control)) # 1 ms timestep by default path, site = scene.kinematics_cfg(cfg)[name] ik = common.Pin(path, site, joint_limits=robot_cfg.joint_limits) self.robot = sim.SimRobot(self.sim, ik, robot_cfg) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 512e65119..cbacfc3e9 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -13,6 +13,7 @@ #include #include "rcs/Camera.h" +#include "rcs/ControllerConfig.h" #include "rcs/Controllers.h" #include "rcs/FR3Controllers.h" #include "rcs/Kinematics.h" @@ -528,6 +529,15 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("kp_nullspace", &rcs::common::OSCConfig::kp_nullspace) .def_readwrite("nullspace_q", &rcs::common::OSCConfig::nullspace_q); + py::class_(common, "JointPDConfig") + .def(py::init([](const rcs::common::VectorXd& kp, + const rcs::common::VectorXd& kd) { + return rcs::common::JointPDConfig{kp, kd}; + }), + py::arg("kp"), py::arg("kd")) + .def_readwrite("kp", &rcs::common::JointPDConfig::kp) + .def_readwrite("kd", &rcs::common::JointPDConfig::kd); + py::class_>(common, "OSC") .def(py::init(common, "RobotState").def(py::init<>()); bind_type_class(common, "GripperType") diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index cebf583f9..cdb590b43 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp FR3Controllers.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp FR3Controllers.cpp ControllerConfig.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/ControllerConfig.cpp b/src/rcs/ControllerConfig.cpp new file mode 100644 index 000000000..42c2ece78 --- /dev/null +++ b/src/rcs/ControllerConfig.cpp @@ -0,0 +1,40 @@ +#include "rcs/ControllerConfig.h" + +#include + +#include "rcs/LinearInterpolator.h" + +namespace rcs { +namespace common { + +ControllerPair make_controller(const ControllerConfig& config, + double interpolation_time, + const JointLimits& joint_limits) { + auto joint_interpolator = [&] { + return std::make_shared(interpolation_time); + }; + auto cartesian_interpolator = [&] { + return std::make_shared(interpolation_time); + }; + ControllerPair controller; + if (auto* c = std::get_if(&config)) { + if (c->kp.size() == 0 || c->kd.size() == 0) { + throw std::invalid_argument("JointPDConfig needs kp and kd"); + } + controller.joint = + std::make_shared(c->kp, c->kd, joint_interpolator()); + } else if (auto* c = std::get_if(&config)) { + controller.cartesian = + std::make_shared(*c, cartesian_interpolator()); + } else if (auto* c = std::get_if(&config)) { + controller.joint = std::make_shared( + *c, joint_interpolator(), joint_limits); + } else if (auto* c = std::get_if(&config)) { + controller.cartesian = std::make_shared( + *c, cartesian_interpolator(), joint_limits); + } + return controller; +} + +} // namespace common +} // namespace rcs diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index 39f27988c..9fde2725c 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -100,10 +100,17 @@ void SimRobot::init_ids() { } bool SimRobot::set_config(const SimRobotConfig& cfg) { + if (this->cfg.controller.has_value() && this->torque_control && + !cfg.controller.has_value()) { + throw std::runtime_error("cannot switch back from torque control"); + } this->cfg = cfg; this->state.inverse_tcp_offset = cfg.tcp_offset.inverse(); if (this->dynamics) { this->configure_dynamics(); + if (cfg.controller.has_value()) { + this->install_configured_controller(); + } } if (this->torque_control && cfg.kp.has_value()) { throw std::runtime_error("kp/kv have no effect under torque control"); @@ -308,6 +315,29 @@ void SimRobot::set_dynamics( } this->dynamics = dynamics; this->configure_dynamics(); + if (this->cfg.controller.has_value()) { + this->install_configured_controller(); + } +} + +void SimRobot::install_configured_controller() { + SimConfig sim_cfg = this->sim->get_config(); + if (!sim_cfg.async_control) { + // synchronous control steps until the goal is reached, which friction + // can prevent under torque control + throw std::runtime_error( + "a configured controller needs SimConfig::async_control"); + } + common::ControllerPair controller = common::make_controller( + this->cfg.controller.value(), 1.0 / sim_cfg.frequency, + this->cfg.joint_limits); + this->joint_controller = nullptr; + this->cartesian_controller = nullptr; + if (controller.joint) { + this->set_joint_controller(controller.joint); + } else { + this->set_cartesian_controller(controller.cartesian); + } } void SimRobot::configure_dynamics() { diff --git a/src/sim/SimRobot.h b/src/sim/SimRobot.h index 074bcd50b..b729c4cec 100644 --- a/src/sim/SimRobot.h +++ b/src/sim/SimRobot.h @@ -92,7 +92,10 @@ class SimRobot : public common::Robot { // Torque control with the shared controllers, see // docs/development/controller_interface.md. set_dynamics() must come first. // Installing a controller switches the arm to torque control for good and - // makes it hold the current configuration. + // makes it hold the current configuration. A controller in + // SimRobotConfig::controller is installed as soon as both it and the + // dynamics are set; it needs SimConfig::async_control and spreads each goal + // over one control period (1 / SimConfig::frequency). void set_dynamics(std::shared_ptr dynamics); void set_joint_controller( std::shared_ptr controller); @@ -121,6 +124,7 @@ class SimRobot : public common::Robot { std::shared_ptr joint_controller; std::shared_ptr cartesian_controller; void configure_dynamics(); + void install_configured_controller(); void enable_torque_control(); void activate(ControlMode mode); common::ControllerState controller_state(double dt); From bb59b0b4f796757b945c67e8055e69fb78bffcfc Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 23:14:15 -0800 Subject: [PATCH 22/39] style: clang-format and ruff fixes for the controller work --- python/tests/test_controller_config.py | 2 +- python/tests/test_controllers.py | 4 ++-- python/tests/test_fr3_controllers.py | 2 +- python/tests/test_interpolators.py | 6 +++--- python/tests/test_pinocchio_dynamics.py | 2 +- python/tests/test_sim_torque_control.py | 5 ++--- src/pybind/rcs.cpp | 3 +-- src/rcs/ControllerConfig.cpp | 7 +++---- src/rcs/FR3Controllers.cpp | 9 ++++----- src/sim/SimRobot.cpp | 6 +++--- src/sim/sim.h | 3 ++- 11 files changed, 23 insertions(+), 26 deletions(-) diff --git a/python/tests/test_controller_config.py b/python/tests/test_controller_config.py index dd782c47c..bac4f2472 100644 --- a/python/tests/test_controller_config.py +++ b/python/tests/test_controller_config.py @@ -119,5 +119,5 @@ def test_no_way_back_to_native_control(): def test_joint_pd_config_needs_gains(): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="kp and kd"): configured(common.JointPDConfig(kp=np.array([]), kd=np.array([]))) diff --git a/python/tests/test_controllers.py b/python/tests/test_controllers.py index 2a48d97c3..9ff8f939e 100644 --- a/python/tests/test_controllers.py +++ b/python/tests/test_controllers.py @@ -10,7 +10,7 @@ Q0 = np.array([0.0, -0.5, 0.0, -2.2, 0.0, 1.8, 0.8]) -@pytest.fixture +@pytest.fixture() def dynamics() -> common.PinocchioDynamics: path = str(rcs.ROBOTS[common.RobotType.FR3].mjcf_model_path) return common.PinocchioDynamics(path, False, "attachment_site", common.Pose(translation=np.array([0, 0, 0.1]))) @@ -45,7 +45,7 @@ def test_pd_law_with_setpoint_velocity_and_coriolis(self, dynamics): np.testing.assert_allclose(controller.step(state), expected, atol=1e-10) def test_rejects_mismatched_gains(self): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="same size"): common.JointPD(np.ones(7), np.ones(6), common.LinearJointInterpolator(0.05)) diff --git a/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py index 3c600da20..71db4cff4 100644 --- a/python/tests/test_fr3_controllers.py +++ b/python/tests/test_fr3_controllers.py @@ -13,7 +13,7 @@ JOINT_LIMITS = rcs.ROBOTS[common.RobotType.FR3].joint_limits -@pytest.fixture +@pytest.fixture() def dynamics() -> common.PinocchioDynamics: path = str(rcs.ROBOTS[common.RobotType.FR3].mjcf_model_path) return common.PinocchioDynamics(path, False, "attachment_site", common.Pose(translation=np.array([0, 0, 0.1]))) diff --git a/python/tests/test_interpolators.py b/python/tests/test_interpolators.py index 5e9015dfc..488d8401a 100644 --- a/python/tests/test_interpolators.py +++ b/python/tests/test_interpolators.py @@ -72,11 +72,11 @@ def test_duration_override_for_one_goal(self): assert np.allclose(run(interpolator, STEPS).q, self.start) def test_invalid_use_raises(self): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="duration"): common.LinearJointInterpolator(0.0) with pytest.raises(RuntimeError): common.LinearJointInterpolator(DURATION).set_goal(self.goal) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="number of joints"): self.make().set_goal(np.zeros(6)) @@ -132,7 +132,7 @@ def test_new_goal_starts_at_current_setpoint(self): assert run(interpolator, STEPS).pose.is_close(self.start) def test_invalid_use_raises(self): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="duration"): common.LinearCartesianInterpolator(-1.0) with pytest.raises(RuntimeError): common.LinearCartesianInterpolator(DURATION).step(DT) diff --git a/python/tests/test_pinocchio_dynamics.py b/python/tests/test_pinocchio_dynamics.py index 7930bceae..7c392e8cb 100644 --- a/python/tests/test_pinocchio_dynamics.py +++ b/python/tests/test_pinocchio_dynamics.py @@ -104,5 +104,5 @@ def test_rejects_wrong_sizes_and_unknown_frame(): common.PinocchioDynamics(fr3_xml(), False, "no_such_frame") dynamics = common.PinocchioDynamics(fr3_xml(), False, FLANGE) assert dynamics.dof() == 7 - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="q and dq"): dynamics.compute(np.zeros(6), np.zeros(6)) diff --git a/python/tests/test_sim_torque_control.py b/python/tests/test_sim_torque_control.py index 1b6b64458..43fbb80af 100644 --- a/python/tests/test_sim_torque_control.py +++ b/python/tests/test_sim_torque_control.py @@ -4,7 +4,6 @@ import pytest from rcs.envs.configs import EmptyWorldFR3 -import rcs from rcs import common, sim TIMESTEP = 0.001 @@ -57,7 +56,7 @@ def test_sim_config_sets_the_timestep(): assert setup.sim.model.opt.timestep == TIMESTEP setup.sim.set_config(sim.SimConfig(timestep=0.002)) assert setup.sim.model.opt.timestep == 0.002 - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="timestep"): setup.sim.set_config(sim.SimConfig(timestep=0.0)) @@ -89,7 +88,7 @@ def test_joint_pd_reaches_goal(): @pytest.mark.parametrize( - "friction, max_error_m, max_error_deg", + ("friction", "max_error_m", "max_error_deg"), # joint friction (frictionloss in the MJCF) stops the arm short of the goal, # as on the real robot. Without it the position converges exactly; the # orientation keeps a small offset because the rotational stiffness at the diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index cbacfc3e9..6d176da98 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -569,8 +569,7 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("residual_mass", &rcs::common::FR3OSCConfig::residual_mass) .def_readwrite("avoidance_weights", &rcs::common::FR3OSCConfig::avoidance_weights) - .def_readwrite("torque_limit", - &rcs::common::FR3OSCConfig::torque_limit); + .def_readwrite("torque_limit", &rcs::common::FR3OSCConfig::torque_limit); py::class_>(common, "FR3OSC") diff --git a/src/rcs/ControllerConfig.cpp b/src/rcs/ControllerConfig.cpp index 42c2ece78..b9c9d3a8a 100644 --- a/src/rcs/ControllerConfig.cpp +++ b/src/rcs/ControllerConfig.cpp @@ -24,14 +24,13 @@ ControllerPair make_controller(const ControllerConfig& config, controller.joint = std::make_shared(c->kp, c->kd, joint_interpolator()); } else if (auto* c = std::get_if(&config)) { - controller.cartesian = - std::make_shared(*c, cartesian_interpolator()); + controller.cartesian = std::make_shared(*c, cartesian_interpolator()); } else if (auto* c = std::get_if(&config)) { controller.joint = std::make_shared( *c, joint_interpolator(), joint_limits); } else if (auto* c = std::get_if(&config)) { - controller.cartesian = std::make_shared( - *c, cartesian_interpolator(), joint_limits); + controller.cartesian = + std::make_shared(*c, cartesian_interpolator(), joint_limits); } return controller; } diff --git a/src/rcs/FR3Controllers.cpp b/src/rcs/FR3Controllers.cpp index a14ccac0c..e81ad7c4e 100644 --- a/src/rcs/FR3Controllers.cpp +++ b/src/rcs/FR3Controllers.cpp @@ -29,9 +29,9 @@ Eigen::MatrixXd pseudo_inverse(const Eigen::MatrixXd& M, } // The end of both control loops in Franka.cpp, see FR3Controllers.h. -Vector7d safety_stage(Vector7d tau, const Vector7d& q, const Vector7d& joint_min, - const Vector7d& joint_max, const Vector7d& torque_limit, - Vector7d& last_tau) { +Vector7d safety_stage(Vector7d tau, const Vector7d& q, + const Vector7d& joint_min, const Vector7d& joint_max, + const Vector7d& torque_limit, Vector7d& last_tau) { for (int i = 0; i < 7; i++) { if (joint_max[i] - q[i] < 0.1 && tau[i] > 0.) tau[i] = 0.; if (q[i] - joint_min[i] < 0.1 && tau[i] < 0.) tau[i] = 0.; @@ -39,8 +39,7 @@ Vector7d safety_stage(Vector7d tau, const Vector7d& q, const Vector7d& joint_min for (int i = 0; i < 7; i++) { tau[i] = last_tau[i] + std::clamp(tau[i] - last_tau[i], -kMaxTorqueStep, kMaxTorqueStep); - tau[i] = - std::clamp(tau[i], -torque_limit[i], torque_limit[i]); + tau[i] = std::clamp(tau[i], -torque_limit[i], torque_limit[i]); } last_tau = tau; return tau; diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index 9fde2725c..e99266e52 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -328,9 +328,9 @@ void SimRobot::install_configured_controller() { throw std::runtime_error( "a configured controller needs SimConfig::async_control"); } - common::ControllerPair controller = common::make_controller( - this->cfg.controller.value(), 1.0 / sim_cfg.frequency, - this->cfg.joint_limits); + common::ControllerPair controller = + common::make_controller(this->cfg.controller.value(), + 1.0 / sim_cfg.frequency, this->cfg.joint_limits); this->joint_controller = nullptr; this->cartesian_controller = nullptr; if (controller.joint) { diff --git a/src/sim/sim.h b/src/sim/sim.h index 804481e11..5b7ff82c2 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -22,7 +22,8 @@ struct SimConfig { bool async_control = false; bool realtime = false; double frequency = 30; // in Hz - int max_convergence_steps = 1000; // physics steps, 1 s at the default timestep + int max_convergence_steps = + 1000; // physics steps, 1 s at the default timestep // MuJoCo arena (stack + constraint) size in bytes, applied when a scene is // compiled from a ModelComposer. -1 keeps the model's or // MuJoCo's automatic sizing, which can be too small for scenes with many From 7c92f2e76a682f43fb3dfc4ecfaf6116c1c4114c Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:26:44 -0800 Subject: [PATCH 23/39] fix(config): stop FrankaConfig and SimRobotConfig from hiding robot_type and robot_platform FrankaConfig, PandaConfig and SimRobotConfig redeclared robot_type and robot_platform, which hid the RobotConfig members that Python and the backends use. Set the inherited members in the constructors instead. --- extensions/rcs_fr3/src/hw/Franka.h | 7 +++---- src/sim/SimRobot.h | 1 - 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 4d85ac45e..d783a7b1a 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -36,9 +36,8 @@ enum IKSolver { franka_ik = 0, rcs_ik }; // control enum Controller { none = 0, jsc, osc, ztc }; struct FrankaConfig : common::RobotConfig { + FrankaConfig() { this->robot_platform = common::RobotPlatform::HARDWARE; } std::string ip; - common::RobotType robot_type = common::RobotType::FR3; - common::RobotPlatform robot_platform = common::RobotPlatform::HARDWARE; IKSolver ik_solver = IKSolver::rcs_ik; double speed_factor = DEFAULT_SPEED_FACTOR; // Rate (Hz) at which set-point commands are streamed from the Python side. @@ -93,10 +92,10 @@ struct FrankaConfig : common::RobotConfig { struct FR3Config : FrankaConfig {}; struct PandaConfig : FrankaConfig { - common::RobotType robot_type = common::RobotType::Panda; PandaConfig() { - // set the inherited limits; a member of the same name would hide them + // set the inherited fields; members of the same name would hide them // from Franka, which works on a FrankaConfig + this->robot_type = common::RobotType::Panda; this->joint_limits = (Eigen::Matrix(2, 7) << // low 7‐tuple diff --git a/src/sim/SimRobot.h b/src/sim/SimRobot.h index b729c4cec..6b1932d9f 100644 --- a/src/sim/SimRobot.h +++ b/src/sim/SimRobot.h @@ -16,7 +16,6 @@ namespace rcs { namespace sim { struct SimRobotConfig : common::RobotConfig { - common::RobotPlatform robot_platform = common::RobotPlatform::SIMULATION; double joint_rotational_tolerance = .05 * (std::numbers::pi / 180.0); // 0.05 degree double seconds_between_callbacks = 0.1; // 10 Hz From f61ffe13a2357fc7a4d359649c92ab88f47d54d9 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:26:44 -0800 Subject: [PATCH 24/39] feat(config): take the robot specific fields from rcs.ROBOTS only RobotConfig and FrankaConfig no longer default to robot specific values (the C++ copies of the FR3 limits had drifted from rcs.ROBOTS). The defaults are now empty: no robot type, dof 0, 2x0 joint limits, empty model path and site. PandaConfig no longer sets the Panda limits. rcs.ROBOTS[robot_type].apply(cfg) sets type, model, IK site, dof, joint limits and home pose, and the configs use it. SimRobot and Franka reject a config without type, dof and matching joint limits. This also gives EmptyWorldUR5e its robot type, which it inherited as FR3 from EmptyWorldFR3. --- docs/development/controller_interface.md | 2 +- extensions/rcs_fr3/src/hw/Franka.cpp | 1 + extensions/rcs_fr3/src/hw/Franka.h | 23 ++---------- .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 8 ++-- extensions/rcs_fr3/src/rcs_fr3/configs.py | 7 +--- extensions/rcs_fr3/src/rcs_fr3/desk.py | 4 +- extensions/rcs_panda/src/rcs_panda/configs.py | 6 +-- extensions/rcs_panda/src/rcs_panda/desk.py | 4 +- include/rcs/Robot.h | 34 +++++++++++------ python/rcs/__init__.py | 24 +++++++++++- python/rcs/_core/common.pyi | 6 +-- python/rcs/_core/sim.pyi | 6 +-- python/rcs/envs/configs.py | 34 +++-------------- python/tests/test_robot_config.py | 37 +++++++++++++++++++ src/sim/SimRobot.cpp | 1 + 15 files changed, 111 insertions(+), 86 deletions(-) create mode 100644 python/tests/test_robot_config.py diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 35a489225..3f526b282 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -187,7 +187,7 @@ class PinocchioDynamics { | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | -| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. The joint-limit guard and avoidance use the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | +| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. The joint-limit guard and avoidance use the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | ## Backends diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 5fc829f3c..61a3d0983 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -31,6 +31,7 @@ common::Pose GetTCPInBaseFrame(const franka::RobotState& robot_state, namespace { void check_config(const FrankaConfig& cfg) { + common::check_robot_config(cfg); if (cfg.timestep != 0.001) { throw std::invalid_argument( "the Franka control loop runs at 1 ms, timestep must be 0.001"); diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index d783a7b1a..d9fc9e5f6 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -86,29 +86,12 @@ struct FrankaConfig : common::RobotConfig { double approach_cartesian_speed = 0.1; double approach_rotation_speed = 0.5; bool ignore_realtime = false; - // dof and joint_limits are those of RobotConfig, set them per robot (from - // rcs.ROBOTS in Python) + // robot_type, dof, joint_limits etc. are those of RobotConfig, set them per + // robot (in Python with rcs.ROBOTS[robot_type].apply(cfg)) }; struct FR3Config : FrankaConfig {}; -struct PandaConfig : FrankaConfig { - PandaConfig() { - // set the inherited fields; members of the same name would hide them - // from Franka, which works on a FrankaConfig - this->robot_type = common::RobotType::Panda; - this->joint_limits = - (Eigen::Matrix(2, 7) << - // low 7‐tuple - -166. / 180. * M_PI, - -101. / 180. * M_PI, -166. / 180. * M_PI, -176. / 180. * M_PI, - -166. / 180. * M_PI, -1. / 180. * M_PI, -166. / 180. * M_PI, - // high 7‐tuple - 166. / 180. * M_PI, 101. / 180. * M_PI, 166. / 180. * M_PI, - -4. / 180. * M_PI, 166. / 180. * M_PI, 215. / 180. * M_PI, - 166. / 180. * M_PI) - .finished(); - } -}; +struct PandaConfig : FrankaConfig {}; struct FrankaState : common::RobotState { franka::RobotState robot_state; diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 95efa5a75..54c6ddcd8 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -320,8 +320,8 @@ class FR3Config(FrankaConfig): async_control: bool = False, ignore_realtime: bool = False, tcp_offset: rcs._core.common.Pose = ..., - attachment_site: str = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", + attachment_site: str = "", + kinematic_model_path: str = "", torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., allow_high_collision: bool = False, ) -> None: ... @@ -341,8 +341,8 @@ class PandaConfig(FrankaConfig): async_control: bool = False, ignore_realtime: bool = False, tcp_offset: rcs._core.common.Pose = ..., - attachment_site: str = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", + attachment_site: str = "", + kinematic_model_path: str = "", torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., allow_high_collision: bool = False, ) -> None: ... diff --git a/extensions/rcs_fr3/src/rcs_fr3/configs.py b/extensions/rcs_fr3/src/rcs_fr3/configs.py index 4727c37e4..09f75367b 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/configs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/configs.py @@ -27,13 +27,8 @@ def config(self) -> FR3HardwareEnvCreatorConfig: async_control=False, ignore_realtime=False, tcp_offset=common.Pose(common.FrankaHandTCPOffset()), - attachment_site="attachment_site", - kinematic_model_path=fr3.mjcf_model_path, ) - robot_cfg.robot_type = common.RobotType.FR3 - robot_cfg.q_home = fr3.q_home - robot_cfg.joint_limits = fr3.joint_limits - robot_cfg.dof = fr3.dof + fr3.apply(robot_cfg) gripper_cfg = hw.FHConfig( ip=self.ip, diff --git a/extensions/rcs_fr3/src/rcs_fr3/desk.py b/extensions/rcs_fr3/src/rcs_fr3/desk.py index 100062523..97f5d960b 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/desk.py +++ b/extensions/rcs_fr3/src/rcs_fr3/desk.py @@ -17,6 +17,8 @@ from requests.packages import urllib3 # type: ignore[attr-defined] from websockets.sync.client import connect +import rcs + _logger = logging.getLogger("desk") TOKEN_PATH = "~/.rcs/token.conf" @@ -71,7 +73,7 @@ def gripper(ip: str, close_gripper: bool): def info(ip: str, include_hand: bool = False): - robot_cfg = rcs_fr3.hw.FR3Config(ip=ip) + robot_cfg = rcs.ROBOTS[rcs.common.RobotType.FR3].apply(rcs_fr3.hw.FR3Config(ip=ip)) robot_cfg.speed_factor = 0.2 robot_cfg.ignore_realtime = True f = rcs_fr3.hw.Franka(robot_cfg) diff --git a/extensions/rcs_panda/src/rcs_panda/configs.py b/extensions/rcs_panda/src/rcs_panda/configs.py index ba93631ef..9af2d1c88 100644 --- a/extensions/rcs_panda/src/rcs_panda/configs.py +++ b/extensions/rcs_panda/src/rcs_panda/configs.py @@ -19,12 +19,8 @@ class DefaultPandaHardwareEnv(RCSPandaConfigEnvCreator): ip = "192.168.4.100" def config(self) -> PandaHardwareEnvCreatorConfig: - robot_cfg = hw.PandaConfig(ip=self.ip) - robot_cfg.robot_type = RobotType.Panda - robot_cfg.kinematic_model_path = rcs.ROBOTS[RobotType.Panda].mjcf_model_path + robot_cfg = rcs.ROBOTS[RobotType.Panda].apply(hw.PandaConfig(ip=self.ip)) robot_cfg.tcp_offset = common.Pose(common.FrankaHandTCPOffset()) - robot_cfg.attachment_site = rcs.ROBOTS[RobotType.Panda].attachment_site - robot_cfg.joint_limits = rcs.ROBOTS[RobotType.Panda].joint_limits robot_cfg.speed_factor = 0.1 robot_cfg.ik_solver = hw.IKSolver.rcs_ik robot_cfg.async_control = False diff --git a/extensions/rcs_panda/src/rcs_panda/desk.py b/extensions/rcs_panda/src/rcs_panda/desk.py index 5ca6bd4d0..cd6991ad3 100644 --- a/extensions/rcs_panda/src/rcs_panda/desk.py +++ b/extensions/rcs_panda/src/rcs_panda/desk.py @@ -17,6 +17,8 @@ from requests.packages import urllib3 # type: ignore[attr-defined] from websockets.sync.client import connect +import rcs + _logger = logging.getLogger("desk") TOKEN_PATH = "~/.rcs/token.conf" @@ -70,7 +72,7 @@ def gripper(ip: str, close_gripper: bool): def info(ip: str, include_hand: bool = False): - robot_cfg = rcs_panda.hw.PandaConfig(ip=ip) + robot_cfg = rcs.ROBOTS[rcs.common.RobotType.Panda].apply(rcs_panda.hw.PandaConfig(ip=ip)) robot_cfg.speed_factor = 0.2 robot_cfg.ignore_realtime = True f = rcs_panda.hw.Franka(robot_cfg) diff --git a/include/rcs/Robot.h b/include/rcs/Robot.h index e21166fba..d243685ca 100644 --- a/include/rcs/Robot.h +++ b/include/rcs/Robot.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -27,6 +28,9 @@ struct TypeBase { return _registry; } + // empty id, not registered: a config whose type is not set yet + TypeBase() = default; + // Constructor automatically registers the instance TypeBase(std::string id_) : id(std::move(id_)) { registry().insert(id); } @@ -61,27 +65,35 @@ inline const RobotType RobotType::SO101{"SO101"}; inline const RobotType RobotType::Yam{"Yam"}; inline const RobotType RobotType::Rizon4S{"Rizon4S"}; +// The robot specific fields (type, model, dof, joint limits, home pose) have +// no robot specific defaults, set them per robot (in Python with +// rcs.ROBOTS[robot_type].apply(cfg)). check_robot_config() rejects a config +// where they are missing. struct RobotConfig { - RobotType robot_type = RobotType::FR3; + RobotType robot_type; RobotPlatform robot_platform = RobotPlatform::SIMULATION; rcs::common::Pose tcp_offset = rcs::common::Pose::Identity(); - std::string attachment_site = "attachment_site"; - std::string kinematic_model_path = "assets/scenes/fr3_empty_world/robot.xml"; + std::string attachment_site; + std::string kinematic_model_path; std::optional q_home = std::nullopt; - size_t dof = 7; + size_t dof = 0; + // lower limits in row 0, upper limits in row 1, one column per joint Eigen::Matrix joint_limits = - (Eigen::Matrix(2, 7) << - // low 7‐tuple - -2.3476, - -1.5454, -2.4937, -2.7714, -2.5100, 0.7773, -2.7045, - // high 7‐tuple - 2.3476, 1.5454, 2.4937, -0.4226, 2.5100, 4.2841, 2.7045) - .finished(); + Eigen::Matrix(2, 0); // The controller to run, see ControllerConfig.h. None: the robot's native // control (MuJoCo actuators in sim, the default controllers on hardware). std::optional controller = std::nullopt; virtual ~RobotConfig() {}; }; + +inline void check_robot_config(const RobotConfig& cfg) { + if (cfg.robot_type.id.empty() || cfg.dof == 0 || + cfg.joint_limits.cols() != static_cast(cfg.dof)) { + throw std::invalid_argument( + "robot_type, dof and joint_limits (2 x dof) must be set, e.g. with " + "rcs.ROBOTS[robot_type].apply(cfg)"); + } +} struct RobotState { virtual ~RobotState() {}; }; diff --git a/python/rcs/__init__.py b/python/rcs/__init__.py index 6db2f7ea4..831bd9164 100644 --- a/python/rcs/__init__.py +++ b/python/rcs/__init__.py @@ -123,10 +123,10 @@ def has_required_assets(prefix: Path) -> bool: @dataclass(kw_only=True) class RobotMetaConfig: + robot_type: common.RobotType + """Type of the robot. Checkout all registered types by RobotType.get_all()""" mjcf_model_path: str """Path to the Mujoco XML file that describes the kinematics.""" - # robot_type: common.RobotType - # """Type of the robot. Checkout all registered types by RobotType.get_all()""" dof: int "Number of degree of freedom of the robot arm" q_home: np.ndarray @@ -136,9 +136,23 @@ class RobotMetaConfig: attachment_site: str = "attachment_site" """mjcf site to use for IK""" + def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: + """Sets the robot specific fields of cfg (type, model, IK site, dof, joint limits, home pose). + + The C++ configs leave them empty, so that the values live only here. Returns cfg. + """ + cfg.robot_type = self.robot_type + cfg.kinematic_model_path = self.mjcf_model_path + cfg.attachment_site = self.attachment_site + cfg.dof = self.dof + cfg.joint_limits = self.joint_limits.copy() + cfg.q_home = self.q_home.copy() + return cfg + ROBOTS: dict[common.RobotType, RobotMetaConfig] = { common.RobotType.FR3: RobotMetaConfig( + robot_type=common.RobotType.FR3, mjcf_model_path="assets/robots/fr3/fr3.xml", dof=7, q_home=np.array([0.0, -np.pi / 4, 0.0, -3 * np.pi / 4, 0.0, np.pi / 2, 0.0]), @@ -150,6 +164,7 @@ class RobotMetaConfig: ), ), common.RobotType.Panda: RobotMetaConfig( + robot_type=common.RobotType.Panda, mjcf_model_path="assets/robots/panda/panda.xml", dof=7, q_home=np.array([0.0, -np.pi / 4, 0.0, -3 * np.pi / 4, 0.0, np.pi / 2, 0.0]), @@ -177,6 +192,7 @@ class RobotMetaConfig: ), ), common.RobotType.XArm7: RobotMetaConfig( + robot_type=common.RobotType.XArm7, mjcf_model_path="assets/robots/xarm7/xarm7.xml", dof=7, q_home=np.array([0, -45.0 / 180.0 * np.pi, 0, 15.0 / 180.0 * np.pi, 0, -25.0 / 180.0 * np.pi, 0]), @@ -188,6 +204,7 @@ class RobotMetaConfig: ), ), common.RobotType.UR5e: RobotMetaConfig( + robot_type=common.RobotType.UR5e, mjcf_model_path="assets/robots/ur5e/ur5e.xml", dof=6, q_home=np.array([0.0, -2.02711196, 1.64630026, -1.18999615, -1.57079762, 0.0]), @@ -199,6 +216,7 @@ class RobotMetaConfig: ), ), common.RobotType.SO101: RobotMetaConfig( + robot_type=common.RobotType.SO101, mjcf_model_path="assets/robots/so101/so101.xml", dof=5, q_home=np.array([-0.01914898, -1.90521916, 1.56476701, 1.04783839, -1.40323926]), @@ -217,6 +235,7 @@ class RobotMetaConfig: attachment_site="gripper", ), common.RobotType.Yam: RobotMetaConfig( + robot_type=common.RobotType.Yam, mjcf_model_path="assets/robots/yam/yam.xml", dof=6, q_home=np.array([0.0, 1.047, 1.047, 0.0, 0.0, 0.0]), @@ -229,6 +248,7 @@ class RobotMetaConfig: attachment_site="tcp_site", ), common.RobotType.Rizon4S: RobotMetaConfig( + robot_type=common.RobotType.Rizon4S, mjcf_model_path="assets/robots/rizon4s/rizon4s.xml", dof=7, # flange pointing straight down (joint2 - joint4 + joint6 = -pi/2), about 0.56 m in front of diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index b9cc65d8c..7f00f3b11 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -408,12 +408,12 @@ class RobotConfig(typing.Generic[M]): def __init__( self, robot_type: RobotType = ..., - dof: int = 7, + dof: int = 0, joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]] = ..., robot_platform: RobotPlatform = ..., tcp_offset: Pose = ..., - attachment_site: str = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", + attachment_site: str = "", + kinematic_model_path: str = "", q_home: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None = None, ) -> None: ... diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index d3246a501..bf7f4caf8 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -208,8 +208,8 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): self, robot_type: rcs._core.common.RobotType = ..., tcp_offset: rcs._core.common.Pose = ..., - attachment_site: str = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", + attachment_site: str = "", + kinematic_model_path: str = "", joint_rotational_tolerance: float = 0.0008726646259971648, seconds_between_callbacks: float = 0.1, trajectory_trace: bool = False, @@ -245,7 +245,7 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): kp: list[float] | None = None, kv: list[float] | None = None, base: str = "base", - dof: int = 7, + dof: int = 0, joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]] = ..., ) -> None: ... def add_prefix(self, id: str) -> None: ... diff --git a/python/rcs/envs/configs.py b/python/rcs/envs/configs.py index a35792752..9f72b9651 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -445,9 +445,8 @@ def config(self) -> SimEnvCreatorConfig: lead_robot_name = self.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[lead_robot_name] + rcs.ROBOTS[rt].apply(robot_cfg) robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] - robot_cfg.attachment_site = rcs.ROBOTS[rt].attachment_site - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path robot_cfg.arm_collision_geoms = [] robot_cfg.joints = [ "shoulder_pan_joint", @@ -458,9 +457,6 @@ def config(self) -> SimEnvCreatorConfig: "wrist_3_joint", ] robot_cfg.actuators = ["shoulder_pan", "shoulder_lift", "elbow", "wrist_1", "wrist_2", "wrist_3"] - robot_cfg.dof = rcs.ROBOTS[rt].dof - robot_cfg.joint_limits = rcs.ROBOTS[rt].joint_limits - robot_cfg.q_home = rcs.ROBOTS[rt].q_home robot_cfg.base = "base" assert cfg.gripper_cfgs is not None @@ -491,10 +487,8 @@ def config(self) -> SimEnvCreatorConfig: lead_robot_name = self.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[lead_robot_name] - robot_cfg.robot_type = rt + rcs.ROBOTS[rt].apply(robot_cfg) robot_cfg.tcp_offset = rcs.common.Pose() - robot_cfg.attachment_site = rcs.ROBOTS[rt].attachment_site - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path robot_cfg.arm_collision_geoms = [] robot_cfg.joints = [ "joint1", @@ -514,9 +508,6 @@ def config(self) -> SimEnvCreatorConfig: "act6", "act7", ] - robot_cfg.dof = rcs.ROBOTS[rt].dof - robot_cfg.joint_limits = rcs.ROBOTS[rt].joint_limits - robot_cfg.q_home = rcs.ROBOTS[rt].q_home robot_cfg.base = "base" cfg.gripper_cfgs = None @@ -537,16 +528,11 @@ def config(self) -> SimEnvCreatorConfig: lead_robot_name = self.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[lead_robot_name] - robot_cfg.robot_type = rt + rcs.ROBOTS[rt].apply(robot_cfg) robot_cfg.tcp_offset = rcs.common.Pose() - robot_cfg.attachment_site = "gripper" - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path robot_cfg.arm_collision_geoms = [] robot_cfg.joints = ["1", "2", "3", "4", "5"] robot_cfg.actuators = ["1", "2", "3", "4", "5"] - robot_cfg.dof = rcs.ROBOTS[rt].dof - robot_cfg.joint_limits = rcs.ROBOTS[rt].joint_limits - robot_cfg.q_home = rcs.ROBOTS[rt].q_home robot_cfg.base = "base" assert cfg.gripper_cfgs is not None @@ -578,16 +564,11 @@ def config(self) -> SimEnvCreatorConfig: lead_robot_name = self.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[lead_robot_name] - robot_cfg.robot_type = rt + rcs.ROBOTS[rt].apply(robot_cfg) robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[GripperType.Yam] - robot_cfg.attachment_site = rcs.ROBOTS[rt].attachment_site - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path robot_cfg.arm_collision_geoms = [] robot_cfg.joints = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"] robot_cfg.actuators = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"] - robot_cfg.dof = rcs.ROBOTS[rt].dof - robot_cfg.joint_limits = rcs.ROBOTS[rt].joint_limits - robot_cfg.q_home = rcs.ROBOTS[rt].q_home robot_cfg.base = "arm" assert cfg.gripper_cfgs is not None @@ -619,16 +600,11 @@ def config(self) -> SimEnvCreatorConfig: lead_robot_name = self.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[lead_robot_name] - robot_cfg.robot_type = rt + rcs.ROBOTS[rt].apply(robot_cfg) robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[GripperType.FlexivGrav] - robot_cfg.attachment_site = rcs.ROBOTS[rt].attachment_site - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path robot_cfg.arm_collision_geoms = [] robot_cfg.joints = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"] robot_cfg.actuators = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"] - robot_cfg.dof = rcs.ROBOTS[rt].dof - robot_cfg.joint_limits = rcs.ROBOTS[rt].joint_limits - robot_cfg.q_home = rcs.ROBOTS[rt].q_home robot_cfg.base = "base" assert cfg.gripper_cfgs is not None diff --git a/python/tests/test_robot_config.py b/python/tests/test_robot_config.py new file mode 100644 index 000000000..dc094b78e --- /dev/null +++ b/python/tests/test_robot_config.py @@ -0,0 +1,37 @@ +"""The robot specific fields of RobotConfig come from rcs.ROBOTS, not from C++ defaults.""" + +import numpy as np +import pytest +from test_sim_torque_control import Setup + +import rcs +from rcs import common, sim + + +def test_robot_config_has_no_robot_specific_defaults(): + cfg = sim.SimRobotConfig() + assert cfg.robot_type.id == "" + assert cfg.dof == 0 + assert cfg.joint_limits.shape == (2, 0) + assert cfg.kinematic_model_path == "" + assert cfg.q_home is None + # an unset type is not registered as a robot type + assert "" not in [t.id for t in common.RobotType.get_all()] + + +@pytest.mark.parametrize("robot_type", list(rcs.ROBOTS)) +def test_apply_sets_the_robot_specific_fields(robot_type): + meta = rcs.ROBOTS[robot_type] + cfg = meta.apply(sim.SimRobotConfig()) + assert cfg.robot_type == robot_type + assert cfg.dof == meta.dof + np.testing.assert_array_equal(cfg.joint_limits, meta.joint_limits) + np.testing.assert_array_equal(cfg.q_home, meta.q_home) + assert cfg.kinematic_model_path == meta.mjcf_model_path + assert cfg.attachment_site == meta.attachment_site + + +def test_sim_robot_rejects_a_config_without_robot_specific_fields(): + setup = Setup() + with pytest.raises(ValueError, match="apply"): + setup.robot.set_config(sim.SimRobotConfig()) diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index e99266e52..98ee23210 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -100,6 +100,7 @@ void SimRobot::init_ids() { } bool SimRobot::set_config(const SimRobotConfig& cfg) { + common::check_robot_config(cfg); if (this->cfg.controller.has_value() && this->torque_control && !cfg.controller.has_value()) { throw std::runtime_error("cannot switch back from torque control"); From a2be2d3402b6bea5b901456d97a43fdb2deb3607 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:36:54 -0800 Subject: [PATCH 25/39] feat(sim): no FR3 names as SimRobotConfig defaults The joint, actuator and collision geom names default to empty lists instead of the FR3's, they belong to the robot model of the scene. SimRobot rejects a config without one joint and one actuator name per dof. SimRobotConfig sets robot_platform to SIMULATION in its constructor, as FrankaConfig sets HARDWARE. --- python/rcs/_core/sim.pyi | 31 +++---------------------------- python/tests/test_robot_config.py | 13 +++++++++++++ src/sim/SimRobot.cpp | 13 ++++++++++++- src/sim/SimRobot.h | 19 +++++++------------ 4 files changed, 35 insertions(+), 41 deletions(-) diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index bf7f4caf8..f192ca4ef 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -213,35 +213,10 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): joint_rotational_tolerance: float = 0.0008726646259971648, seconds_between_callbacks: float = 0.1, trajectory_trace: bool = False, - arm_collision_geoms: list[str] = [ - "fr3_link0_collision", - "fr3_link1_collision", - "fr3_link2_collision", - "fr3_link3_collision", - "fr3_link4_collision", - "fr3_link5_collision", - "fr3_link6_collision", - "fr3_link7_collision", - ], - joints: list[str] = [ - "fr3_joint1", - "fr3_joint2", - "fr3_joint3", - "fr3_joint4", - "fr3_joint5", - "fr3_joint6", - "fr3_joint7", - ], + arm_collision_geoms: list[str] = [], + joints: list[str] = [], q_home: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None = None, - actuators: list[str] = [ - "fr3_joint1", - "fr3_joint2", - "fr3_joint3", - "fr3_joint4", - "fr3_joint5", - "fr3_joint6", - "fr3_joint7", - ], + actuators: list[str] = [], kp: list[float] | None = None, kv: list[float] | None = None, base: str = "base", diff --git a/python/tests/test_robot_config.py b/python/tests/test_robot_config.py index dc094b78e..f36d2a19c 100644 --- a/python/tests/test_robot_config.py +++ b/python/tests/test_robot_config.py @@ -35,3 +35,16 @@ def test_sim_robot_rejects_a_config_without_robot_specific_fields(): setup = Setup() with pytest.raises(ValueError, match="apply"): setup.robot.set_config(sim.SimRobotConfig()) + + +def test_sim_robot_needs_a_joint_and_actuator_per_dof(): + setup = Setup() + cfg = setup.robot.get_config() + cfg.actuators = cfg.actuators[:-1] + with pytest.raises(ValueError, match="per dof"): + setup.robot.set_config(cfg) + + +def test_platform_is_set_by_the_config_class(): + assert sim.SimRobotConfig().robot_platform == common.RobotPlatform.SIMULATION + diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index 98ee23210..d1149d511 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -24,10 +24,21 @@ namespace sim { // TODO: check dof contraints // TODO: use C++11 feature to call one constructor from another +namespace { +void check_config(const SimRobotConfig& cfg) { + common::check_robot_config(cfg); + if (cfg.joints.size() != cfg.dof || cfg.actuators.size() != cfg.dof) { + throw std::invalid_argument( + "SimRobotConfig needs one joint and one actuator name per dof"); + } +} +} // namespace + SimRobot::SimRobot(std::shared_ptr sim, std::shared_ptr ik, SimRobotConfig cfg, bool register_convergence_callback) : sim{sim}, cfg{cfg}, state{}, m_ik(ik) { + check_config(cfg); this->init_ids(); this->set_config(cfg); if (register_convergence_callback) { @@ -100,7 +111,7 @@ void SimRobot::init_ids() { } bool SimRobot::set_config(const SimRobotConfig& cfg) { - common::check_robot_config(cfg); + check_config(cfg); if (this->cfg.controller.has_value() && this->torque_control && !cfg.controller.has_value()) { throw std::runtime_error("cannot switch back from torque control"); diff --git a/src/sim/SimRobot.h b/src/sim/SimRobot.h index 6b1932d9f..bc1455b37 100644 --- a/src/sim/SimRobot.h +++ b/src/sim/SimRobot.h @@ -15,23 +15,18 @@ namespace rcs { namespace sim { +// The MJCF names (joints, actuators, collision geoms) have no defaults, they +// belong to the robot model of the scene. struct SimRobotConfig : common::RobotConfig { + SimRobotConfig() { this->robot_platform = common::RobotPlatform::SIMULATION; } double joint_rotational_tolerance = .05 * (std::numbers::pi / 180.0); // 0.05 degree double seconds_between_callbacks = 0.1; // 10 Hz bool trajectory_trace = false; - std::vector arm_collision_geoms{ - "fr3_link0_collision", "fr3_link1_collision", "fr3_link2_collision", - "fr3_link3_collision", "fr3_link4_collision", "fr3_link5_collision", - "fr3_link6_collision", "fr3_link7_collision"}; - std::vector joints = { - "fr3_joint1", "fr3_joint2", "fr3_joint3", "fr3_joint4", - "fr3_joint5", "fr3_joint6", "fr3_joint7", - }; - std::vector actuators = { - "fr3_joint1", "fr3_joint2", "fr3_joint3", "fr3_joint4", - "fr3_joint5", "fr3_joint6", "fr3_joint7", - }; + std::vector arm_collision_geoms; + // one joint and one actuator per degree of freedom + std::vector joints; + std::vector actuators; std::optional> kp; std::optional> kv; std::string base = "base"; From a90f3f785692235d48a0e91ad4a6126b75ef537b Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:36:54 -0800 Subject: [PATCH 26/39] feat(fr3): define FR3Config and PandaConfig in Python They were empty C++ subclasses of FrankaConfig. Now they are Python classes in rcs_fr3.hw and rcs_panda.hw that call rcs.ROBOTS[robot_type].apply() in their constructor, so a bare FR3Config(ip=...) has the FR3's type, model, dof, joint limits and home pose, defined only in rcs.ROBOTS. Further fields are keyword arguments, an unknown field raises TypeError. rcs_fr3.hw and rcs_panda.hw re-export the classes of the C++ module, the packages import hw from there. --- docs/development/controller_interface.md | 2 +- extensions/rcs_fr3/src/hw/Franka.h | 3 - extensions/rcs_fr3/src/pybind/rcs.cpp | 106 +----------------- extensions/rcs_fr3/src/rcs_fr3/__init__.py | 4 +- .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 45 +------- extensions/rcs_fr3/src/rcs_fr3/configs.py | 4 +- extensions/rcs_fr3/src/rcs_fr3/creators.py | 2 +- extensions/rcs_fr3/src/rcs_fr3/desk.py | 4 +- extensions/rcs_fr3/src/rcs_fr3/envs.py | 2 +- extensions/rcs_fr3/src/rcs_fr3/hw.py | 61 ++++++++++ .../rcs_panda/src/rcs_panda/__init__.py | 4 +- extensions/rcs_panda/src/rcs_panda/configs.py | 4 +- .../rcs_panda/src/rcs_panda/creators.py | 2 +- extensions/rcs_panda/src/rcs_panda/desk.py | 4 +- extensions/rcs_panda/src/rcs_panda/envs.py | 2 +- extensions/rcs_panda/src/rcs_panda/hw.py | 61 ++++++++++ python/tests/test_robot_config.py | 14 +++ 17 files changed, 154 insertions(+), 170 deletions(-) create mode 100644 extensions/rcs_fr3/src/rcs_fr3/hw.py create mode 100644 extensions/rcs_panda/src/rcs_panda/hw.py diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 3f526b282..0df35c5ec 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -187,7 +187,7 @@ class PinocchioDynamics { | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | -| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. The joint-limit guard and avoidance use the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | +| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. The joint-limit guard and avoidance use the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. `FR3Config` and `PandaConfig` are therefore Python classes (`rcs_fr3.hw`, `rcs_panda.hw`) that subclass the C++ `FrankaConfig` and call `apply()` in their constructor. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | ## Backends diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index d9fc9e5f6..0d50d546a 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -90,9 +90,6 @@ struct FrankaConfig : common::RobotConfig { // robot (in Python with rcs.ROBOTS[robot_type].apply(cfg)) }; -struct FR3Config : FrankaConfig {}; -struct PandaConfig : FrankaConfig {}; - struct FrankaState : common::RobotState { franka::RobotState robot_state; }; diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index f977d814c..b8fa9abb2 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -126,6 +126,9 @@ PYBIND11_MODULE(_core, m) { py::object robot_config = (py::object)py::module_::import("rcs").attr("common").attr("RobotConfig"); py::class_(hw, "FrankaConfig", robot_config) + // the robot specific subclasses (FR3Config, PandaConfig) are defined in + // Python, they fill in the values from rcs.ROBOTS + .def(py::init<>()) .def_readwrite("ik_solver", &rcs::hw::FrankaConfig::ik_solver) .def_readwrite("speed_factor", &rcs::hw::FrankaConfig::speed_factor) .def_readwrite("policy_rate", &rcs::hw::FrankaConfig::policy_rate) @@ -161,109 +164,6 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("ignore_realtime", &rcs::hw::FrankaConfig::ignore_realtime) .def_readwrite("ip", &rcs::hw::FrankaConfig::ip); - rcs::hw::FR3Config default_fr3_config; - py::class_(hw, "FR3Config") - .def( - py::init([](const std::string& ip, rcs::hw::IKSolver ik_solver, - double speed_factor, const rcs::common::Vector7d& kp, - const rcs::common::Vector7d& kd, - const Eigen::Vector3d& kp_p, double kp_r, - std::optional load_parameters, - std::optional world_to_robot, - bool async_control, bool ignore_realtime, - rcs::common::Pose tcp_offset, std::string attachment_site, - std::string kinematic_model_path, - const rcs::common::Vector7d& torque_limit, - bool allow_high_collision) { - rcs::hw::FR3Config cfg; - cfg.ik_solver = ik_solver; - cfg.speed_factor = speed_factor; - cfg.kp = kp; - cfg.kd = kd; - cfg.torque_limit = torque_limit; - cfg.allow_high_collision = allow_high_collision; - cfg.kp_p = kp_p; - cfg.kp_r = kp_r; - cfg.load_parameters = load_parameters; - cfg.world_to_robot = world_to_robot; - cfg.async_control = async_control; - cfg.ignore_realtime = ignore_realtime; - cfg.ip = ip; - cfg.tcp_offset = tcp_offset; - cfg.tcp_offset_explicit = true; - cfg.attachment_site = attachment_site; - cfg.kinematic_model_path = kinematic_model_path; - return cfg; - }), - py::arg("ip"), py::arg("ik_solver") = default_fr3_config.ik_solver, - py::arg("speed_factor") = default_fr3_config.speed_factor, - py::arg("kp") = default_fr3_config.kp, - py::arg("kd") = default_fr3_config.kd, - py::arg("kp_p") = default_fr3_config.kp_p, - py::arg("kp_r") = default_fr3_config.kp_r, - py::arg("load_parameters") = default_fr3_config.load_parameters, - py::arg("world_to_robot") = default_fr3_config.world_to_robot, - py::arg("async_control") = default_fr3_config.async_control, - py::arg("ignore_realtime") = default_fr3_config.ignore_realtime, - py::arg("tcp_offset") = default_fr3_config.tcp_offset, - py::arg("attachment_site") = default_fr3_config.attachment_site, - py::arg("kinematic_model_path") = - default_fr3_config.kinematic_model_path, - py::arg("torque_limit") = default_fr3_config.torque_limit, - py::arg("allow_high_collision") = - default_fr3_config.allow_high_collision); - rcs::hw::PandaConfig default_panda_config; - py::class_(hw, "PandaConfig") - .def( - py::init([](const std::string& ip, rcs::hw::IKSolver ik_solver, - double speed_factor, const rcs::common::Vector7d& kp, - const rcs::common::Vector7d& kd, - const Eigen::Vector3d& kp_p, double kp_r, - std::optional load_parameters, - std::optional world_to_robot, - bool async_control, bool ignore_realtime, - rcs::common::Pose tcp_offset, std::string attachment_site, - std::string kinematic_model_path, - const rcs::common::Vector7d& torque_limit, - bool allow_high_collision) { - rcs::hw::PandaConfig cfg; - cfg.ik_solver = ik_solver; - cfg.speed_factor = speed_factor; - cfg.kp = kp; - cfg.kd = kd; - cfg.torque_limit = torque_limit; - cfg.allow_high_collision = allow_high_collision; - cfg.kp_p = kp_p; - cfg.kp_r = kp_r; - cfg.load_parameters = load_parameters; - cfg.world_to_robot = world_to_robot; - cfg.async_control = async_control; - cfg.ignore_realtime = ignore_realtime; - cfg.ip = ip; - cfg.tcp_offset = tcp_offset; - cfg.tcp_offset_explicit = true; - cfg.attachment_site = attachment_site; - cfg.kinematic_model_path = kinematic_model_path; - return cfg; - }), - py::arg("ip"), py::arg("ik_solver") = default_panda_config.ik_solver, - py::arg("speed_factor") = default_panda_config.speed_factor, - py::arg("kp") = default_panda_config.kp, - py::arg("kd") = default_panda_config.kd, - py::arg("kp_p") = default_panda_config.kp_p, - py::arg("kp_r") = default_panda_config.kp_r, - py::arg("load_parameters") = default_panda_config.load_parameters, - py::arg("world_to_robot") = default_panda_config.world_to_robot, - py::arg("async_control") = default_panda_config.async_control, - py::arg("ignore_realtime") = default_panda_config.ignore_realtime, - py::arg("tcp_offset") = default_panda_config.tcp_offset, - py::arg("attachment_site") = default_panda_config.attachment_site, - py::arg("kinematic_model_path") = - default_panda_config.kinematic_model_path, - py::arg("torque_limit") = default_panda_config.torque_limit, - py::arg("allow_high_collision") = - default_panda_config.allow_high_collision); - py::object gripper_config = (py::object)py::module_::import("rcs").attr("common").attr( "GripperConfig"); diff --git a/extensions/rcs_fr3/src/rcs_fr3/__init__.py b/extensions/rcs_fr3/src/rcs_fr3/__init__.py index 56e60a9b0..187ff0564 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/__init__.py +++ b/extensions/rcs_fr3/src/rcs_fr3/__init__.py @@ -1,6 +1,6 @@ -from rcs_fr3._core import __version__, hw +from rcs_fr3._core import __version__ -from . import configs, desk, envs +from . import configs, desk, envs, hw __all__ = [ "configs", diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 54c6ddcd8..8f94d392d 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -15,14 +15,12 @@ from . import exceptions __all__: list[str] = [ "FHConfig", "FHState", - "FR3Config", "Franka", "FrankaConfig", "FrankaHand", "FrankaLoad", "FrankaState", "IKSolver", - "PandaConfig", "RobotMode", "RobotState", "exceptions", @@ -125,6 +123,7 @@ class FrankaConfig(rcs._core.common.RobotConfig): timestep: float torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] world_to_robot: rcs._core.common.Pose | None + def __init__(self) -> None: ... class FrankaHand(rcs._core.common.Gripper): def __init__(self, cfg: FHConfig) -> None: ... @@ -305,48 +304,6 @@ class RobotState: @property def theta(self) -> typing.Annotated[list[float], pybind11_stubgen.typing_ext.FixedSize(7)]: ... -class FR3Config(FrankaConfig): - def __init__( - self, - ip: str, - ik_solver: IKSolver = ..., - speed_factor: float = 0.2, - kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., - kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., - kp_p: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] = ..., - kp_r: float = 250.0, - load_parameters: FrankaLoad | None = None, - world_to_robot: rcs._core.common.Pose | None = None, - async_control: bool = False, - ignore_realtime: bool = False, - tcp_offset: rcs._core.common.Pose = ..., - attachment_site: str = "", - kinematic_model_path: str = "", - torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., - allow_high_collision: bool = False, - ) -> None: ... - -class PandaConfig(FrankaConfig): - def __init__( - self, - ip: str, - ik_solver: IKSolver = ..., - speed_factor: float = 0.2, - kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., - kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., - kp_p: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] = ..., - kp_r: float = 250.0, - load_parameters: FrankaLoad | None = None, - world_to_robot: rcs._core.common.Pose | None = None, - async_control: bool = False, - ignore_realtime: bool = False, - tcp_offset: rcs._core.common.Pose = ..., - attachment_site: str = "", - kinematic_model_path: str = "", - torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] = ..., - allow_high_collision: bool = False, - ) -> None: ... - class FrankaState(rcs._core.common.RobotState): def __init__(self) -> None: ... @property diff --git a/extensions/rcs_fr3/src/rcs_fr3/configs.py b/extensions/rcs_fr3/src/rcs_fr3/configs.py index 09f75367b..1482c2abd 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/configs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/configs.py @@ -2,7 +2,7 @@ import numpy as np from rcs.envs.base import ControlMode, RelativeTo -from rcs_fr3._core import hw +from rcs_fr3 import hw from rcs_fr3.creators import ( FR3HardwareEnvCreatorConfig, FR3MultiHardwareEnvCreatorConfig, @@ -19,7 +19,6 @@ class DefaultFR3HardwareEnv(RCSFR3ConfigEnvCreator): ip = "192.168.101.1" def config(self) -> FR3HardwareEnvCreatorConfig: - fr3 = rcs.ROBOTS[common.RobotType.FR3] robot_cfg = hw.FR3Config( ip=self.ip, ik_solver=hw.IKSolver.rcs_ik, @@ -28,7 +27,6 @@ def config(self) -> FR3HardwareEnvCreatorConfig: ignore_realtime=False, tcp_offset=common.Pose(common.FrankaHandTCPOffset()), ) - fr3.apply(robot_cfg) gripper_cfg = hw.FHConfig( ip=self.ip, diff --git a/extensions/rcs_fr3/src/rcs_fr3/creators.py b/extensions/rcs_fr3/src/rcs_fr3/creators.py index 69e25e215..0730dbe0c 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/creators.py +++ b/extensions/rcs_fr3/src/rcs_fr3/creators.py @@ -21,7 +21,7 @@ RobotWrapper, ) from rcs.envs.scenes import RCSEnvCreator, WrapperConfig -from rcs_fr3._core import hw +from rcs_fr3 import hw from rcs_fr3.envs import FR3HW import rcs diff --git a/extensions/rcs_fr3/src/rcs_fr3/desk.py b/extensions/rcs_fr3/src/rcs_fr3/desk.py index 97f5d960b..100062523 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/desk.py +++ b/extensions/rcs_fr3/src/rcs_fr3/desk.py @@ -17,8 +17,6 @@ from requests.packages import urllib3 # type: ignore[attr-defined] from websockets.sync.client import connect -import rcs - _logger = logging.getLogger("desk") TOKEN_PATH = "~/.rcs/token.conf" @@ -73,7 +71,7 @@ def gripper(ip: str, close_gripper: bool): def info(ip: str, include_hand: bool = False): - robot_cfg = rcs.ROBOTS[rcs.common.RobotType.FR3].apply(rcs_fr3.hw.FR3Config(ip=ip)) + robot_cfg = rcs_fr3.hw.FR3Config(ip=ip) robot_cfg.speed_factor = 0.2 robot_cfg.ignore_realtime = True f = rcs_fr3.hw.Franka(robot_cfg) diff --git a/extensions/rcs_fr3/src/rcs_fr3/envs.py b/extensions/rcs_fr3/src/rcs_fr3/envs.py index 3bd10c589..511ce8c68 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/envs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/envs.py @@ -3,7 +3,7 @@ import gymnasium as gym from rcs._core.common import RobotPlatform -from rcs_fr3._core import hw +from rcs_fr3 import hw _logger = logging.getLogger(__name__) diff --git a/extensions/rcs_fr3/src/rcs_fr3/hw.py b/extensions/rcs_fr3/src/rcs_fr3/hw.py new file mode 100644 index 000000000..d903136d2 --- /dev/null +++ b/extensions/rcs_fr3/src/rcs_fr3/hw.py @@ -0,0 +1,61 @@ +"""The Franka hardware classes of the C++ module, and the config of the FR3. + +The robot specific values (type, model, IK site, dof, joint limits, home pose) +are only defined in rcs.ROBOTS, so the robot specific config lives here and not +in C++. +""" + +from typing import Any + +from rcs_fr3._core.hw import ( + FHConfig, + FHState, + Franka, + FrankaConfig, + FrankaHand, + FrankaLoad, + FrankaState, + IKSolver, + RobotMode, + RobotState, + exceptions, +) + +import rcs +from rcs import common + + +class FR3Config(FrankaConfig): + """FrankaConfig of the FR3, with its values from rcs.ROBOTS. + + Further fields can be given as keyword arguments, e.g. + FR3Config(ip="192.168.1.11", async_control=True, policy_rate=15). + """ + + def __init__(self, ip: str, **kwargs: Any): + super().__init__() + rcs.ROBOTS[common.RobotType.FR3].apply(self) + self.ip = ip + # Cartesian control uses tcp_offset (identity unless given), as before + self.tcp_offset_explicit = True + for key, value in kwargs.items(): + if not hasattr(self, key): + msg = f"FR3Config has no field {key}" + raise TypeError(msg) + setattr(self, key, value) + + +__all__ = [ + "FHConfig", + "FHState", + "Franka", + "FrankaConfig", + "FrankaHand", + "FrankaLoad", + "FrankaState", + "FR3Config", + "IKSolver", + "RobotMode", + "RobotState", + "exceptions", +] diff --git a/extensions/rcs_panda/src/rcs_panda/__init__.py b/extensions/rcs_panda/src/rcs_panda/__init__.py index 4c4e503b8..d781e5435 100644 --- a/extensions/rcs_panda/src/rcs_panda/__init__.py +++ b/extensions/rcs_panda/src/rcs_panda/__init__.py @@ -1,6 +1,6 @@ -from rcs_panda._core import __version__, hw +from rcs_panda._core import __version__ -from . import configs, envs +from . import configs, envs, hw __all__ = [ "configs", diff --git a/extensions/rcs_panda/src/rcs_panda/configs.py b/extensions/rcs_panda/src/rcs_panda/configs.py index 9af2d1c88..122f1da6d 100644 --- a/extensions/rcs_panda/src/rcs_panda/configs.py +++ b/extensions/rcs_panda/src/rcs_panda/configs.py @@ -3,7 +3,7 @@ import numpy as np from rcs._core.common import RobotType from rcs.envs.base import ControlMode, RelativeTo -from rcs_panda._core import hw +from rcs_panda import hw from rcs_panda.creators import ( PandaHardwareEnvCreatorConfig, PandaMultiHardwareEnvCreatorConfig, @@ -19,7 +19,7 @@ class DefaultPandaHardwareEnv(RCSPandaConfigEnvCreator): ip = "192.168.4.100" def config(self) -> PandaHardwareEnvCreatorConfig: - robot_cfg = rcs.ROBOTS[RobotType.Panda].apply(hw.PandaConfig(ip=self.ip)) + robot_cfg = hw.PandaConfig(ip=self.ip) robot_cfg.tcp_offset = common.Pose(common.FrankaHandTCPOffset()) robot_cfg.speed_factor = 0.1 robot_cfg.ik_solver = hw.IKSolver.rcs_ik diff --git a/extensions/rcs_panda/src/rcs_panda/creators.py b/extensions/rcs_panda/src/rcs_panda/creators.py index fd93ec3e2..cacdaf301 100644 --- a/extensions/rcs_panda/src/rcs_panda/creators.py +++ b/extensions/rcs_panda/src/rcs_panda/creators.py @@ -17,7 +17,7 @@ RobotWrapper, ) from rcs.envs.scenes import RCSEnvCreator, WrapperConfig -from rcs_panda._core import hw +from rcs_panda import hw from rcs_panda.envs import PandaHW import rcs diff --git a/extensions/rcs_panda/src/rcs_panda/desk.py b/extensions/rcs_panda/src/rcs_panda/desk.py index cd6991ad3..5ca6bd4d0 100644 --- a/extensions/rcs_panda/src/rcs_panda/desk.py +++ b/extensions/rcs_panda/src/rcs_panda/desk.py @@ -17,8 +17,6 @@ from requests.packages import urllib3 # type: ignore[attr-defined] from websockets.sync.client import connect -import rcs - _logger = logging.getLogger("desk") TOKEN_PATH = "~/.rcs/token.conf" @@ -72,7 +70,7 @@ def gripper(ip: str, close_gripper: bool): def info(ip: str, include_hand: bool = False): - robot_cfg = rcs.ROBOTS[rcs.common.RobotType.Panda].apply(rcs_panda.hw.PandaConfig(ip=ip)) + robot_cfg = rcs_panda.hw.PandaConfig(ip=ip) robot_cfg.speed_factor = 0.2 robot_cfg.ignore_realtime = True f = rcs_panda.hw.Franka(robot_cfg) diff --git a/extensions/rcs_panda/src/rcs_panda/envs.py b/extensions/rcs_panda/src/rcs_panda/envs.py index 2e83794fa..1b332e084 100644 --- a/extensions/rcs_panda/src/rcs_panda/envs.py +++ b/extensions/rcs_panda/src/rcs_panda/envs.py @@ -3,7 +3,7 @@ import gymnasium as gym from rcs._core.common import RobotPlatform -from rcs_panda._core import hw +from rcs_panda import hw _logger = logging.getLogger(__name__) diff --git a/extensions/rcs_panda/src/rcs_panda/hw.py b/extensions/rcs_panda/src/rcs_panda/hw.py new file mode 100644 index 000000000..e25a68aec --- /dev/null +++ b/extensions/rcs_panda/src/rcs_panda/hw.py @@ -0,0 +1,61 @@ +"""The Franka hardware classes of the C++ module, and the config of the Panda. + +The robot specific values (type, model, IK site, dof, joint limits, home pose) +are only defined in rcs.ROBOTS, so the robot specific config lives here and not +in C++. +""" + +from typing import Any + +from rcs_panda._core.hw import ( + FHConfig, + FHState, + Franka, + FrankaConfig, + FrankaHand, + FrankaLoad, + FrankaState, + IKSolver, + RobotMode, + RobotState, + exceptions, +) + +import rcs +from rcs import common + + +class PandaConfig(FrankaConfig): + """FrankaConfig of the Panda, with its values from rcs.ROBOTS. + + Further fields can be given as keyword arguments, e.g. + PandaConfig(ip="192.168.1.11", async_control=True, policy_rate=15). + """ + + def __init__(self, ip: str, **kwargs: Any): + super().__init__() + rcs.ROBOTS[common.RobotType.Panda].apply(self) + self.ip = ip + # Cartesian control uses tcp_offset (identity unless given), as before + self.tcp_offset_explicit = True + for key, value in kwargs.items(): + if not hasattr(self, key): + msg = f"PandaConfig has no field {key}" + raise TypeError(msg) + setattr(self, key, value) + + +__all__ = [ + "FHConfig", + "FHState", + "Franka", + "FrankaConfig", + "FrankaHand", + "FrankaLoad", + "FrankaState", + "PandaConfig", + "IKSolver", + "RobotMode", + "RobotState", + "exceptions", +] diff --git a/python/tests/test_robot_config.py b/python/tests/test_robot_config.py index f36d2a19c..77f5412d5 100644 --- a/python/tests/test_robot_config.py +++ b/python/tests/test_robot_config.py @@ -48,3 +48,17 @@ def test_sim_robot_needs_a_joint_and_actuator_per_dof(): def test_platform_is_set_by_the_config_class(): assert sim.SimRobotConfig().robot_platform == common.RobotPlatform.SIMULATION + +def test_fr3_config_takes_its_values_from_rcs_robots(): + hw = pytest.importorskip("rcs_fr3.hw") + meta = rcs.ROBOTS[common.RobotType.FR3] + cfg = hw.FR3Config(ip="192.168.1.11", async_control=True, policy_rate=15) + assert cfg.robot_type == common.RobotType.FR3 + assert cfg.robot_platform == common.RobotPlatform.HARDWARE + assert cfg.dof == meta.dof + np.testing.assert_array_equal(cfg.joint_limits, meta.joint_limits) + assert cfg.ip == "192.168.1.11" + assert cfg.async_control + assert cfg.policy_rate == 15 + with pytest.raises(TypeError, match="no field"): + hw.FR3Config(ip="192.168.1.11", asynch_control=True) # typo From b495cf551bf0f8e620f661c982d15f087c4188ea Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:51:03 -0800 Subject: [PATCH 27/39] feat(control): safety stage for the torques of any controller SafetyStage is the safety stage of Franka.cpp for any number of joints: no torque towards a joint limit closer than a margin, a torque rate limit per step of the nominal control period (libfranka limits per command), and a per-joint torque clip, configured by SafetyConfig. SafeJointController and SafeCartesianController run a controller's torques through it. RobotConfig::safety holds the robot's SafetyConfig; make_controller wraps the configured controller with it, so the sim and the Franka backend use the same code. JointLimits moves to utils.h. --- extensions/rcs_fr3/src/hw/Franka.cpp | 3 +- include/rcs/ControllerConfig.h | 9 ++- include/rcs/FR3Controllers.h | 1 - include/rcs/Robot.h | 3 + include/rcs/SafetyStage.h | 82 +++++++++++++++++++++ include/rcs/utils.h | 2 + python/rcs/_core/common.pyi | 48 +++++++++++++ python/tests/test_safety_stage.py | 102 ++++++++++++++++++++++++++ src/pybind/rcs.cpp | 54 +++++++++++++- src/rcs/CMakeLists.txt | 2 +- src/rcs/ControllerConfig.cpp | 13 +++- src/rcs/SafetyStage.cpp | 103 +++++++++++++++++++++++++++ src/sim/SimRobot.cpp | 6 +- 13 files changed, 418 insertions(+), 10 deletions(-) create mode 100644 include/rcs/SafetyStage.h create mode 100644 python/tests/test_safety_stage.py create mode 100644 src/rcs/SafetyStage.cpp diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 61a3d0983..31db87ef9 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -408,7 +408,8 @@ common::ControllerPair Franka::make_torque_controller(bool cartesian) { } // a goal per policy step, interpolated over one policy period return common::make_controller(config, 1.0 / this->m_cfg.policy_rate, - this->m_cfg.joint_limits); + this->m_cfg.joint_limits, this->m_cfg.safety, + this->m_cfg.timestep); } void Franka::create_dynamics() { diff --git a/include/rcs/ControllerConfig.h b/include/rcs/ControllerConfig.h index e3a84f089..65ab7b730 100644 --- a/include/rcs/ControllerConfig.h +++ b/include/rcs/ControllerConfig.h @@ -7,6 +7,7 @@ #include "Controller.h" #include "Controllers.h" #include "FR3Controllers.h" +#include "SafetyStage.h" #include "utils.h" namespace rcs { @@ -39,10 +40,14 @@ struct ControllerPair { // Builds the controller with a linear interpolator that spreads each goal // over interpolation_time (the control period of the policy). The joint -// limits are the robot's, as in RobotConfig::joint_limits. +// limits are the robot's, as in RobotConfig::joint_limits. With a safety +// config (RobotConfig::safety), the controller's torques go through a +// SafetyStage; timestep is the period of the control loop. ControllerPair make_controller(const ControllerConfig& config, double interpolation_time, - const JointLimits& joint_limits); + const JointLimits& joint_limits, + const std::optional& safety, + double timestep); } // namespace common } // namespace rcs diff --git a/include/rcs/FR3Controllers.h b/include/rcs/FR3Controllers.h index 4599fee98..67a392b28 100644 --- a/include/rcs/FR3Controllers.h +++ b/include/rcs/FR3Controllers.h @@ -26,7 +26,6 @@ namespace common { // torque rate limit and the per-joint torque clip. The joint limits are those // of the robot (RobotConfig::joint_limits, lower limits in the first row), // passed to the constructors. -using JointLimits = Eigen::Matrix; struct FR3JointControllerConfig { Vector7d kp = diff --git a/include/rcs/Robot.h b/include/rcs/Robot.h index d243685ca..ac7698eaf 100644 --- a/include/rcs/Robot.h +++ b/include/rcs/Robot.h @@ -83,6 +83,9 @@ struct RobotConfig { // The controller to run, see ControllerConfig.h. None: the robot's native // control (MuJoCo actuators in sim, the default controllers on hardware). std::optional controller = std::nullopt; + // Limits on the torques of the controller (SafetyStage), from rcs.ROBOTS. + // None: the torques go to the robot as the controller computes them. + std::optional safety = std::nullopt; virtual ~RobotConfig() {}; }; diff --git a/include/rcs/SafetyStage.h b/include/rcs/SafetyStage.h new file mode 100644 index 000000000..ed9f1aaa2 --- /dev/null +++ b/include/rcs/SafetyStage.h @@ -0,0 +1,82 @@ +#ifndef RCS_SAFETY_STAGE_H +#define RCS_SAFETY_STAGE_H + +#include +#include +#include + +#include "Controller.h" +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// Limits applied to the torques of any controller, a property of the robot +// (RobotConfig::safety, set from rcs.ROBOTS in Python). +struct SafetyConfig { + // per-joint torque clip in Nm, empty: no clip + VectorXd torque_limit; + // per-joint torque rate limit in Nm/s (franka::limitRate on the FR3) + double max_torque_rate = std::numeric_limits::infinity(); + // no torque that pushes a joint closer than this to its limit (rad) + double joint_limit_margin = 0.1; +}; + +// The safety stage of Franka.cpp, for any robot and controller. In this order: +// 1. joint-limit guard: a joint closer than joint_limit_margin to a limit gets +// no torque towards it, +// 2. rate limit: each joint torque changes by at most +// max_torque_rate * timestep from the previous output per step (starting +// from zero after reset). timestep is the nominal period of the control +// loop, not the measured one: libfranka limits per command, assuming 1 ms. +// 3. clip to torque_limit. +class SafetyStage { + public: + SafetyStage(const SafetyConfig& config, const JointLimits& joint_limits, + double timestep); + // the output starts from zero torque again + void reset(const ControllerState& state); + VectorXd apply(const VectorXd& tau, const ControllerState& state); + + private: + SafetyConfig config; + JointLimits joint_limits; + double timestep; + VectorXd last_tau; +}; + +// A controller whose torques go through a SafetyStage. +class SafeJointController : public JointController { + public: + SafeJointController(std::shared_ptr controller, + const SafetyConfig& config, + const JointLimits& joint_limits, double timestep); + void reset(const ControllerState& state) override; + void set_goal(const VectorXd& q_goal, + std::optional duration = std::nullopt) override; + VectorXd step(const ControllerState& state) override; + + private: + std::shared_ptr controller; + SafetyStage stage; +}; + +class SafeCartesianController : public CartesianController { + public: + SafeCartesianController(std::shared_ptr controller, + const SafetyConfig& config, + const JointLimits& joint_limits, double timestep); + void reset(const ControllerState& state) override; + void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) override; + VectorXd step(const ControllerState& state) override; + + private: + std::shared_ptr controller; + SafetyStage stage; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_SAFETY_STAGE_H diff --git a/include/rcs/utils.h b/include/rcs/utils.h index 566fd4018..244c77c68 100644 --- a/include/rcs/utils.h +++ b/include/rcs/utils.h @@ -17,6 +17,8 @@ typedef Eigen::Matrix Vector7d; typedef Eigen::Matrix Vector16d; typedef Eigen::Matrix VectorXd; typedef Eigen::Matrix Vector7i; +// joint limits of a robot: lower limits in row 0, upper limits in row 1 +using JointLimits = Eigen::Matrix; /*** * @brief convert between eigen and flattened array (col major as required by diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 7f00f3b11..8ec26e1c5 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -58,6 +58,10 @@ __all__: list[str] = [ "RobotType", "RotVec", "SIMULATION", + "SafeCartesianController", + "SafeJointController", + "SafetyConfig", + "SafetyStage", "TRIPOD_GRASP", ] M = typing.TypeVar("M", bound=int) @@ -404,6 +408,7 @@ class RobotConfig(typing.Generic[M]): q_home: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None robot_platform: RobotPlatform robot_type: RobotType + safety: SafetyConfig | None tcp_offset: Pose def __init__( self, @@ -476,6 +481,31 @@ class RotVec: self, ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... +class SafetyConfig: + joint_limit_margin: float + max_torque_rate: float + torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __copy__(self) -> SafetyConfig: ... + def __deepcopy__(self, arg0: dict) -> SafetyConfig: ... + def __init__( + self, + torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + max_torque_rate: float = ..., + joint_limit_margin: float = 0.1, + ) -> None: ... + +class SafetyStage: + def __init__( + self, + config: SafetyConfig, + joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], + timestep: float, + ) -> None: ... + def apply( + self, tau: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], state: ControllerState + ) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + def reset(self, state: ControllerState) -> None: ... + class FR3OSC(CartesianController): def __init__( self, @@ -487,6 +517,15 @@ class FR3OSC(CartesianController): class OSC(CartesianController): def __init__(self, config: OSCConfig, interpolator: CartesianInterpolator) -> None: ... +class SafeCartesianController(CartesianController): + def __init__( + self, + controller: CartesianController, + config: SafetyConfig, + joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], + timestep: float, + ) -> None: ... + class LinearCartesianInterpolator(CartesianInterpolator): def __init__(self, duration: float) -> None: ... @@ -506,6 +545,15 @@ class JointPD(JointController): interpolator: JointInterpolator, ) -> None: ... +class SafeJointController(JointController): + def __init__( + self, + controller: JointController, + config: SafetyConfig, + joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], + timestep: float, + ) -> None: ... + class LinearJointInterpolator(JointInterpolator): def __init__(self, duration: float) -> None: ... diff --git a/python/tests/test_safety_stage.py b/python/tests/test_safety_stage.py new file mode 100644 index 000000000..000404a51 --- /dev/null +++ b/python/tests/test_safety_stage.py @@ -0,0 +1,102 @@ +"""The safety stage that limits the torques of any controller.""" + +import mujoco +import numpy as np +import pytest +from test_controller_config import configured +from test_sim_torque_control import KD, KP + +from rcs import common + +DT = 0.001 +LIMITS = np.array([[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]]) # any number of joints + + +def state(q=(0.0, 0.0, 0.0)) -> common.ControllerState: + s = common.ControllerState() + s.q = np.array(q, dtype=float) + s.dq = np.zeros(len(q)) + s.dt = DT + return s + + +def stage(**config) -> common.SafetyStage: + result = common.SafetyStage(common.SafetyConfig(**config), LIMITS, DT) + result.reset(state()) + return result + + +def test_torques_pass_unchanged_within_the_limits(): + np.testing.assert_allclose(stage().apply(np.array([5.0, -3.0, 0.5]), state()), [5.0, -3.0, 0.5]) + + +def test_torque_is_clipped(): + np.testing.assert_allclose( + stage(torque_limit=np.array([1.0, 2.0, 3.0])).apply(np.array([5.0, -5.0, 2.0]), state()), [1.0, -2.0, 2.0] + ) + + +def test_torque_rate_is_limited_per_step_of_the_timestep(): + s = stage(max_torque_rate=1000.0) # 1 Nm per 1 ms step + first = s.apply(np.array([5.0, -5.0, 0.5]), state()) + second = s.apply(np.array([5.0, -5.0, 0.5]), state()) + np.testing.assert_allclose(first, [1.0, -1.0, 0.5]) + np.testing.assert_allclose(second, [2.0, -2.0, 0.5]) + # the measured dt does not matter (libfranka limits per command) + late = state() + late.dt = 0.002 + np.testing.assert_allclose(s.apply(np.array([5.0, -5.0, 0.5]), late), [3.0, -3.0, 0.5]) + + +def test_reset_starts_from_zero_torque(): + s = stage(max_torque_rate=1000.0) + for _ in range(10): + s.apply(np.full(3, 5.0), state()) + s.reset(state()) + np.testing.assert_allclose(s.apply(np.full(3, 5.0), state()), 1.0) + + +def test_no_torque_towards_a_close_joint_limit(): + near = state(q=(0.95, -0.95, 0.0)) # 0.05 rad from the upper and the lower limit + tau = stage().apply(np.array([1.0, -1.0, 1.0]), near) + np.testing.assert_allclose(tau, [0.0, 0.0, 1.0]) + # away from the limit is allowed + np.testing.assert_allclose(stage().apply(np.array([-1.0, 1.0, 1.0]), near), [-1.0, 1.0, 1.0]) + + +def test_torque_limit_needs_one_entry_per_joint(): + with pytest.raises(ValueError, match="one entry per joint"): + common.SafetyStage(common.SafetyConfig(torque_limit=np.ones(2)), LIMITS, DT) + + +def controller_torque(setup) -> np.ndarray: + """Actuator torque without the gravity term the sim adds (the firmware's part).""" + model, data = setup.sim.model, setup.sim.data + still = mujoco.MjData(model) + still.qpos[:] = data.qpos + mujoco.mj_forward(model, still) # zero velocity: the bias is gravity only + return data.actuator_force[:7] - still.qfrc_bias[:7] + + +def test_safe_controller_limits_the_wrapped_controller(): + setup = configured(common.JointPDConfig(kp=KP, kd=KD)) + controller = common.SafeJointController( + common.JointPD(KP, KD, common.LinearJointInterpolator(0.05)), + common.SafetyConfig(torque_limit=np.full(7, 2.0), max_torque_rate=1000.0), + setup.robot.get_config().joint_limits, + DT, + ) + setup.robot.set_joint_controller(controller) + setup.robot.set_joint_position(setup.robot.get_joint_position() + 0.5) # large error + setup.run(0.1) + assert np.max(np.abs(controller_torque(setup))) <= 2.0 + 0.05 + + +def test_robot_config_safety_wraps_the_configured_controller(): + setup = configured(common.JointPDConfig(kp=KP, kd=KD)) + cfg = setup.robot.get_config() + cfg.safety = common.SafetyConfig(torque_limit=np.full(7, 2.0)) + setup.robot.set_config(cfg) + setup.robot.set_joint_position(setup.robot.get_joint_position() + 0.5) + setup.run(0.1) + assert np.max(np.abs(controller_torque(setup))) <= 2.0 + 0.05 diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 6d176da98..aaa710f13 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -578,6 +578,57 @@ PYBIND11_MODULE(_core, m) { const rcs::common::JointLimits&>(), py::arg("config"), py::arg("interpolator"), py::arg("joint_limits")); + rcs::common::SafetyConfig default_safety_config; + py::class_(common, "SafetyConfig") + .def(py::init([](const rcs::common::VectorXd& torque_limit, + double max_torque_rate, double joint_limit_margin) { + return rcs::common::SafetyConfig{torque_limit, max_torque_rate, + joint_limit_margin}; + }), + py::arg("torque_limit") = default_safety_config.torque_limit, + py::arg("max_torque_rate") = default_safety_config.max_torque_rate, + py::arg("joint_limit_margin") = + default_safety_config.joint_limit_margin) + .def_readwrite("torque_limit", &rcs::common::SafetyConfig::torque_limit) + .def_readwrite("max_torque_rate", + &rcs::common::SafetyConfig::max_torque_rate) + .def_readwrite("joint_limit_margin", + &rcs::common::SafetyConfig::joint_limit_margin) + .def("__copy__", + [](const rcs::common::SafetyConfig& self) { + return rcs::common::SafetyConfig(self); + }) + .def("__deepcopy__", [](const rcs::common::SafetyConfig& self, py::dict) { + return rcs::common::SafetyConfig(self); + }); + + py::class_(common, "SafetyStage") + .def(py::init(), + py::arg("config"), py::arg("joint_limits"), py::arg("timestep")) + .def("reset", &rcs::common::SafetyStage::reset, py::arg("state")) + .def("apply", &rcs::common::SafetyStage::apply, py::arg("tau"), + py::arg("state")); + + py::class_>( + common, "SafeJointController") + .def(py::init, + const rcs::common::SafetyConfig&, + const rcs::common::JointLimits&, double>(), + py::arg("controller"), py::arg("config"), py::arg("joint_limits"), + py::arg("timestep")); + + py::class_>( + common, "SafeCartesianController") + .def(py::init, + const rcs::common::SafetyConfig&, + const rcs::common::JointLimits&, double>(), + py::arg("controller"), py::arg("config"), py::arg("joint_limits"), + py::arg("timestep")); + bind_type_class(common, "RobotType") .def_readonly_static("FR3", &rcs::common::RobotType::FR3) .def_readonly_static("Panda", &rcs::common::RobotType::Panda) @@ -633,7 +684,8 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("robot_platform", &rcs::common::RobotConfig::robot_platform) .def_readwrite("q_home", &rcs::common::RobotConfig::q_home) - .def_readwrite("controller", &rcs::common::RobotConfig::controller); + .def_readwrite("controller", &rcs::common::RobotConfig::controller) + .def_readwrite("safety", &rcs::common::RobotConfig::safety); py::class_(common, "RobotState").def(py::init<>()); bind_type_class(common, "GripperType") diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index cdb590b43..2d28c920e 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp FR3Controllers.cpp ControllerConfig.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp LinearInterpolator.cpp PinocchioDynamics.cpp Controllers.cpp FR3Controllers.cpp ControllerConfig.cpp SafetyStage.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/ControllerConfig.cpp b/src/rcs/ControllerConfig.cpp index b9c9d3a8a..a4418c6a7 100644 --- a/src/rcs/ControllerConfig.cpp +++ b/src/rcs/ControllerConfig.cpp @@ -9,7 +9,9 @@ namespace common { ControllerPair make_controller(const ControllerConfig& config, double interpolation_time, - const JointLimits& joint_limits) { + const JointLimits& joint_limits, + const std::optional& safety, + double timestep) { auto joint_interpolator = [&] { return std::make_shared(interpolation_time); }; @@ -32,6 +34,15 @@ ControllerPair make_controller(const ControllerConfig& config, controller.cartesian = std::make_shared(*c, cartesian_interpolator(), joint_limits); } + if (safety.has_value()) { + if (controller.joint) { + controller.joint = std::make_shared( + controller.joint, *safety, joint_limits, timestep); + } else { + controller.cartesian = std::make_shared( + controller.cartesian, *safety, joint_limits, timestep); + } + } return controller; } diff --git a/src/rcs/SafetyStage.cpp b/src/rcs/SafetyStage.cpp new file mode 100644 index 000000000..53246f8ce --- /dev/null +++ b/src/rcs/SafetyStage.cpp @@ -0,0 +1,103 @@ +#include "rcs/SafetyStage.h" + +#include +#include +#include + +namespace rcs { +namespace common { + +SafetyStage::SafetyStage(const SafetyConfig& config, + const JointLimits& joint_limits, double timestep) + : config(config), joint_limits(joint_limits), timestep(timestep) { + if (!(timestep > 0.0)) { + throw std::invalid_argument("timestep must be positive"); + } + if (config.torque_limit.size() != 0 && + config.torque_limit.size() != joint_limits.cols()) { + throw std::invalid_argument( + "torque_limit needs one entry per joint of joint_limits"); + } +} + +void SafetyStage::reset(const ControllerState& state) { + if (state.q.size() != this->joint_limits.cols()) { + throw std::invalid_argument("state and joint_limits differ in joints"); + } + this->last_tau = VectorXd::Zero(state.q.size()); +} + +VectorXd SafetyStage::apply(const VectorXd& tau_in, + const ControllerState& state) { + if (this->last_tau.size() != tau_in.size()) { + throw std::logic_error("call reset() before apply()"); + } + VectorXd tau = tau_in; + const double margin = this->config.joint_limit_margin; + const double max_step = this->config.max_torque_rate * this->timestep; + for (Eigen::Index i = 0; i < tau.size(); i++) { + if (this->joint_limits(1, i) - state.q[i] < margin && tau[i] > 0.) + tau[i] = 0.; + if (state.q[i] - this->joint_limits(0, i) < margin && tau[i] < 0.) + tau[i] = 0.; + } + for (Eigen::Index i = 0; i < tau.size(); i++) { + tau[i] = this->last_tau[i] + + std::clamp(tau[i] - this->last_tau[i], -max_step, max_step); + if (this->config.torque_limit.size() != 0) { + tau[i] = std::clamp(tau[i], -this->config.torque_limit[i], + this->config.torque_limit[i]); + } + } + this->last_tau = tau; + return tau; +} + +SafeJointController::SafeJointController( + std::shared_ptr controller, const SafetyConfig& config, + const JointLimits& joint_limits, double timestep) + : controller(std::move(controller)), stage(config, joint_limits, timestep) { + if (!this->controller) { + throw std::invalid_argument("controller must not be null"); + } +} + +void SafeJointController::reset(const ControllerState& state) { + this->controller->reset(state); + this->stage.reset(state); +} + +void SafeJointController::set_goal(const VectorXd& q_goal, + std::optional duration) { + this->controller->set_goal(q_goal, duration); +} + +VectorXd SafeJointController::step(const ControllerState& state) { + return this->stage.apply(this->controller->step(state), state); +} + +SafeCartesianController::SafeCartesianController( + std::shared_ptr controller, const SafetyConfig& config, + const JointLimits& joint_limits, double timestep) + : controller(std::move(controller)), stage(config, joint_limits, timestep) { + if (!this->controller) { + throw std::invalid_argument("controller must not be null"); + } +} + +void SafeCartesianController::reset(const ControllerState& state) { + this->controller->reset(state); + this->stage.reset(state); +} + +void SafeCartesianController::set_goal(const Pose& pose_goal, + std::optional duration) { + this->controller->set_goal(pose_goal, duration); +} + +VectorXd SafeCartesianController::step(const ControllerState& state) { + return this->stage.apply(this->controller->step(state), state); +} + +} // namespace common +} // namespace rcs diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index d1149d511..b368af2dc 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -340,9 +340,9 @@ void SimRobot::install_configured_controller() { throw std::runtime_error( "a configured controller needs SimConfig::async_control"); } - common::ControllerPair controller = - common::make_controller(this->cfg.controller.value(), - 1.0 / sim_cfg.frequency, this->cfg.joint_limits); + common::ControllerPair controller = common::make_controller( + this->cfg.controller.value(), 1.0 / sim_cfg.frequency, + this->cfg.joint_limits, this->cfg.safety, sim_cfg.timestep); this->joint_controller = nullptr; this->cartesian_controller = nullptr; if (controller.joint) { From 49cc493f76351a25921da88be4ce22140a7b749f Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:53:31 -0800 Subject: [PATCH 28/39] refactor(control): FR3 controllers without their own safety stage The joint-limit guard, torque rate limit and torque clip at the end of FR3JointController and FR3OSC are now the shared SafetyStage, configured by RobotConfig::safety. The FR3 controllers keep only their control laws; FR3JointController no longer takes joint limits, the torque_limit fields of both configs and of FrankaConfig are gone. rcs.ROBOTS holds the safety values of the FR3 and the Panda (87/12 Nm, franka::limitRate's 999.999 Nm/s) and apply() sets RobotConfig::safety, so FR3Config, PandaConfig and the FR3 sim scenes have it. Franka refuses async (torque) control without it. The FR3 controllers with the stage give bit-identical torques to the previous controllers on an open-loop sequence that saturates, hits the rate limit and passes the joint-limit zones. --- docs/development/controller_interface.md | 3 +- extensions/rcs_fr3/src/hw/Franka.cpp | 8 +++-- extensions/rcs_fr3/src/hw/Franka.h | 10 +++--- extensions/rcs_fr3/src/pybind/rcs.cpp | 1 - .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 1 - include/rcs/FR3Controllers.h | 27 +++++--------- python/rcs/__init__.py | 17 ++++++++- python/rcs/_core/common.pyi | 9 +---- python/rcs/envs/configs.py | 18 ++++------ python/tests/test_fr3_controllers.py | 35 ++++++++++++------ python/tests/test_robot_config.py | 10 ++++++ src/pybind/rcs.cpp | 12 +++---- src/rcs/ControllerConfig.cpp | 4 +-- src/rcs/FR3Controllers.cpp | 36 ++----------------- 14 files changed, 86 insertions(+), 105 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 0df35c5ec..1853c2afe 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -187,7 +187,8 @@ class PinocchioDynamics { | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | -| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance and guard, deadband, torque rate limit, torque clip. They need nothing from libfranka: the rate limit (1000 Nm/s per joint, as `franka::limitRate`) is a few lines and uses the controller's own previous output instead of `tau_J_d`. The joint-limit guard and avoidance use the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. `FR3Config` and `PandaConfig` are therefore Python classes (`rcs_fr3.hw`, `rcs_panda.hw`) that subclass the C++ `FrankaConfig` and call `apply()` in their constructor. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | +| `SafetyStage`, `SafeJointController`, `SafeCartesianController` | core | The safety stage of `Franka.cpp` for any robot and controller, configured by `RobotConfig::safety` (`SafetyConfig`: torque limit, torque rate limit, joint-limit margin). In this order: no torque towards a joint limit closer than the margin, the rate limit per step of the nominal control period (as `franka::limitRate`, which limits per command assuming 1 ms, so the measured `dt` is not used), the clip. It keeps its own previous output instead of `tau_J_d`. `make_controller` wraps the configured controller with it, so sim and hardware run the same code. `rcs.ROBOTS` holds the values (FR3 and Panda: 87/12 Nm, 999.999 Nm/s), `apply()` sets them. `Franka` refuses async (torque) control without it; in sim it is used when set, which the FR3 scenes do. | +| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance, deadband. The safety stage at the end of both loops (joint-limit guard, torque rate limit, torque clip) is the `SafetyStage` (see below), which applies to any controller. The joint-limit avoidance uses the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. `FR3Config` and `PandaConfig` are therefore Python classes (`rcs_fr3.hw`, `rcs_panda.hw`) that subclass the C++ `FrankaConfig` and call `apply()` in their constructor. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | ## Backends diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 31db87ef9..834d5a286 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -39,6 +39,12 @@ void check_config(const FrankaConfig& cfg) { if (cfg.controller.has_value() && !cfg.async_control) { throw std::invalid_argument("a configured controller needs async_control"); } + // async control runs a torque controller, never without the safety stage + if (cfg.async_control && !cfg.safety.has_value()) { + throw std::invalid_argument( + "async_control needs safety (torque limits), FR3Config and " + "PandaConfig set it from rcs.ROBOTS"); + } } } // namespace @@ -397,13 +403,11 @@ common::ControllerPair Franka::make_torque_controller(bool cartesian) { common::FR3OSCConfig osc; osc.kp_position = this->m_cfg.kp_p; osc.kp_orientation = this->m_cfg.kp_r; - osc.torque_limit = this->m_cfg.torque_limit; config = osc; } else { common::FR3JointControllerConfig joint; joint.kp = this->m_cfg.kp; joint.kd = this->m_cfg.kd; - joint.torque_limit = this->m_cfg.torque_limit; config = joint; } // a goal per policy step, interpolated over one policy period diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 0d50d546a..8a64b0eb0 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -46,17 +46,15 @@ struct FrankaConfig : common::RobotConfig { // period of the control loop in seconds; libfranka runs it at 1 kHz, so // anything else is rejected double timestep = 0.001; - // The gains and torque limit below are for the default controllers, used - // when RobotConfig::controller is not set. A configured controller needs - // async_control. + // The gains below are for the default controllers, used when + // RobotConfig::controller is not set. A configured controller needs + // async_control. Async (torque) control needs RobotConfig::safety, the torque + // limits come from there. // values from deoxys/config/joint-impedance-controller.yml common::Vector7d kp = (common::Vector7d() << 100., 100., 100., 100., 75., 150., 50.).finished(); common::Vector7d kd = (common::Vector7d() << 20., 20., 20., 20., 7.5, 15.0, 5.0).finished(); - // FR3/Panda joint torque limits (Nm) from the Franka robot specification - common::Vector7d torque_limit = - (common::Vector7d() << 87., 87., 87., 87., 12., 12., 12.).finished(); bool allow_high_collision = false; // values from deoxys/config/osc-position-controller.yml Eigen::Vector3d kp_p = (Eigen::Vector3d() << 150., 150., 150.).finished(); diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index b8fa9abb2..96df2b4ae 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -135,7 +135,6 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("timestep", &rcs::hw::FrankaConfig::timestep) .def_readwrite("kp", &rcs::hw::FrankaConfig::kp) .def_readwrite("kd", &rcs::hw::FrankaConfig::kd) - .def_readwrite("torque_limit", &rcs::hw::FrankaConfig::torque_limit) .def_readwrite("allow_high_collision", &rcs::hw::FrankaConfig::allow_high_collision) .def_readwrite("kp_p", &rcs::hw::FrankaConfig::kp_p) diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 8f94d392d..18ad6e9a7 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -121,7 +121,6 @@ class FrankaConfig(rcs._core.common.RobotConfig): tcp_offset: rcs._core.common.Pose tcp_offset_explicit: bool timestep: float - torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] world_to_robot: rcs._core.common.Pose | None def __init__(self) -> None: ... diff --git a/include/rcs/FR3Controllers.h b/include/rcs/FR3Controllers.h index 67a392b28..5c53a17eb 100644 --- a/include/rcs/FR3Controllers.h +++ b/include/rcs/FR3Controllers.h @@ -21,29 +21,23 @@ namespace common { // - Dynamics come from the ControllerState (PinocchioDynamics) instead of // franka::Model, which computes the same quantities. -// Safety stage shared by both controllers, applied after the control law: no -// torque that pushes a joint closer than 0.1 rad to its limit further, the -// torque rate limit and the per-joint torque clip. The joint limits are those -// of the robot (RobotConfig::joint_limits, lower limits in the first row), -// passed to the constructors. +// - The safety stage at the end of both loops (joint-limit guard, torque rate +// limit, torque clip) is not part of the controllers, it is the SafetyStage +// that RobotConfig::safety adds to any controller (see SafetyStage.h). struct FR3JointControllerConfig { Vector7d kp = (Vector7d() << 100.0, 100.0, 100.0, 100.0, 75.0, 150.0, 50.0).finished(); Vector7d kd = (Vector7d() << 20.0, 20.0, 20.0, 20.0, 7.5, 15.0, 5.0).finished(); - // per-joint torque clip, FrankaConfig::torque_limit - Vector7d torque_limit = - (Vector7d() << 87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0).finished(); }; -// Joint impedance: tau = kp (q_d - q) - kd dq + coriolis, then the safety -// stage. Note: no setpoint velocity feed-forward, as on the robot. +// Joint impedance: tau = kp (q_d - q) - kd dq + coriolis. Note: no setpoint +// velocity feed-forward, as on the robot. class FR3JointController : public JointController { public: FR3JointController(const FR3JointControllerConfig& config, - std::shared_ptr interpolator, - const JointLimits& joint_limits); + std::shared_ptr interpolator); void reset(const ControllerState& state) override; void set_goal(const VectorXd& q_goal, std::optional duration = std::nullopt) override; @@ -52,8 +46,6 @@ class FR3JointController : public JointController { private: FR3JointControllerConfig config; std::shared_ptr interpolator; - Vector7d joint_min, joint_max; - Vector7d last_tau = Vector7d::Zero(); }; struct FR3OSCConfig { @@ -71,15 +63,13 @@ struct FR3OSCConfig { // null-space push away from joints that are 0.1 to 0.25 rad from a limit Vector7d avoidance_weights = (Vector7d() << 1.0, 1.0, 1.0, 1.0, 1.0, 10.0, 10.0).finished(); - // per-joint torque clip, FrankaConfig::torque_limit - Vector7d torque_limit = - (Vector7d() << 87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0).finished(); }; // Decoupled operational-space control as on the FR3 (deoxys): separate // position and orientation task inertias, damping on the TCP velocity only, // orientation error from the quaternion vector part, small errors cut off, -// posture and joint-limit avoidance in the null space, then the safety stage. +// posture and joint-limit avoidance in the null space. The joint limits are +// the robot's (RobotConfig::joint_limits), for the avoidance. class FR3OSC : public CartesianController { public: FR3OSC(const FR3OSCConfig& config, @@ -94,7 +84,6 @@ class FR3OSC : public CartesianController { FR3OSCConfig config; std::shared_ptr interpolator; Vector7d joint_min, joint_max; - Vector7d last_tau = Vector7d::Zero(); }; } // namespace common diff --git a/python/rcs/__init__.py b/python/rcs/__init__.py index 831bd9164..7d7e00f76 100644 --- a/python/rcs/__init__.py +++ b/python/rcs/__init__.py @@ -135,9 +135,13 @@ class RobotMetaConfig: """hard joint limits of this robot, shape (2, N)""" attachment_site: str = "attachment_site" """mjcf site to use for IK""" + torque_limit: np.ndarray | None = None + """joint torque limits in Nm for the safety stage of torque controllers, shape (N,), None: no safety stage""" + max_torque_rate: float = float("inf") + """joint torque rate limit in Nm/s for the safety stage""" def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: - """Sets the robot specific fields of cfg (type, model, IK site, dof, joint limits, home pose). + """Sets the robot specific fields of cfg (type, model, IK site, dof, joint limits, home pose, safety). The C++ configs leave them empty, so that the values live only here. Returns cfg. """ @@ -147,6 +151,11 @@ def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: cfg.dof = self.dof cfg.joint_limits = self.joint_limits.copy() cfg.q_home = self.q_home.copy() + cfg.safety = ( + common.SafetyConfig(torque_limit=self.torque_limit.copy(), max_torque_rate=self.max_torque_rate) + if self.torque_limit is not None + else None + ) return cfg @@ -162,6 +171,9 @@ def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: [2.9007, 1.8361, 2.9007, -0.1169, 2.8763, 4.6216, 3.0508], ] ), + # Franka robot specification; the rate limit is franka::limitRate (kMaxTorqueRate - kLimitEps) + torque_limit=np.array([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0]), + max_torque_rate=1000.0 - 1e-3, ), common.RobotType.Panda: RobotMetaConfig( robot_type=common.RobotType.Panda, @@ -190,6 +202,9 @@ def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: ], ] ), + # Franka robot specification; the rate limit is franka::limitRate (kMaxTorqueRate - kLimitEps) + torque_limit=np.array([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0]), + max_torque_rate=1000.0 - 1e-3, ), common.RobotType.XArm7: RobotMetaConfig( robot_type=common.RobotType.XArm7, diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 8ec26e1c5..226cba70f 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -105,7 +105,6 @@ class ControllerState: class FR3JointControllerConfig: kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] def __init__(self) -> None: ... class FR3OSCConfig: @@ -114,7 +113,6 @@ class FR3OSCConfig: kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] nullspace_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] residual_mass: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] def __init__(self) -> None: ... class GraspType: @@ -530,12 +528,7 @@ class LinearCartesianInterpolator(CartesianInterpolator): def __init__(self, duration: float) -> None: ... class FR3JointController(JointController): - def __init__( - self, - config: FR3JointControllerConfig, - interpolator: JointInterpolator, - joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], - ) -> None: ... + def __init__(self, config: FR3JointControllerConfig, interpolator: JointInterpolator) -> None: ... class JointPD(JointController): def __init__( diff --git a/python/rcs/envs/configs.py b/python/rcs/envs/configs.py index 9f72b9651..52c0c59dd 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -33,10 +33,7 @@ def config(self) -> SimEnvCreatorConfig: q_home = rcs.ROBOTS[RobotType.FR3].q_home.copy() q_home[-1] = np.pi / 4 robot_cfg: SimRobotConfig[Literal[7]] = SimRobotConfig( - robot_type=RobotType.FR3, tcp_offset=GRIPPER_TCP_OFFSETS[rcs.common.GripperType.FrankaHand], - attachment_site=rcs.ROBOTS[RobotType.FR3].attachment_site, - kinematic_model_path=rcs.ROBOTS[RobotType.FR3].mjcf_model_path, joint_rotational_tolerance=0.05 * (np.pi / 180.0), seconds_between_callbacks=0.1, trajectory_trace=False, @@ -69,10 +66,10 @@ def config(self) -> SimEnvCreatorConfig: "fr3_joint7", ], base="base", - dof=rcs.ROBOTS[RobotType.FR3].dof, - joint_limits=rcs.ROBOTS[RobotType.FR3].joint_limits, - q_home=q_home, ) + # type, model, dof, limits and the safety stage of torque control + rcs.ROBOTS[RobotType.FR3].apply(robot_cfg) + robot_cfg.q_home = q_home robot_cfgs: dict[str, SimRobotConfig] = {self.robot_prefix_template: robot_cfg} sim_cfg: SimConfig = SimConfig(async_control=False, realtime=True, frequency=1, max_convergence_steps=1000) @@ -275,9 +272,6 @@ class EmptyWorldFR3Duo(SimEnvCreator): def config(self) -> SimEnvCreatorConfig: robot_cfg: SimRobotConfig[Literal[7]] = SimRobotConfig( tcp_offset=GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85], - robot_type=RobotType.FR3, - attachment_site=rcs.ROBOTS[RobotType.FR3].attachment_site, - kinematic_model_path=rcs.ROBOTS[RobotType.FR3].mjcf_model_path, joint_rotational_tolerance=0.05 * (np.pi / 180.0), seconds_between_callbacks=0.1, trajectory_trace=False, @@ -310,10 +304,10 @@ def config(self) -> SimEnvCreatorConfig: "fr3_joint7", ], base="base", - dof=rcs.ROBOTS[RobotType.FR3].dof, - joint_limits=rcs.ROBOTS[RobotType.FR3].joint_limits, - q_home=rcs.HOME_POSITIONS["FR3_DUO_LEFT"], ) + # type, model, dof, limits and the safety stage of torque control + rcs.ROBOTS[RobotType.FR3].apply(robot_cfg) + robot_cfg.q_home = rcs.HOME_POSITIONS["FR3_DUO_LEFT"] robot_cfg_right: SimRobotConfig[Literal[7]] = copy.deepcopy(robot_cfg) robot_cfg_right.q_home = rcs.HOME_POSITIONS["FR3_DUO_RIGHT"] diff --git a/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py index 71db4cff4..2092e9bf6 100644 --- a/python/tests/test_fr3_controllers.py +++ b/python/tests/test_fr3_controllers.py @@ -1,5 +1,6 @@ -"""The FR3 controllers ported from Franka.cpp: control laws, safety stage, and -their use in the torque-controlled sim.""" +"""The FR3 controllers ported from Franka.cpp: control laws, with the FR3's +safety stage (from rcs.ROBOTS) as on the robot, and their use in the +torque-controlled sim.""" import numpy as np import pytest @@ -11,6 +12,8 @@ DT = 0.001 Q0 = np.array([0.0, -0.8, 0.0, -2.4, 0.0, 1.6, 0.8]) # away from the joint limits JOINT_LIMITS = rcs.ROBOTS[common.RobotType.FR3].joint_limits +# the FR3's safety stage, as RobotConfig.safety gets it from rcs.ROBOTS +SAFETY = rcs.ROBOTS[common.RobotType.FR3].apply(common.RobotConfig()).safety @pytest.fixture() @@ -19,19 +22,21 @@ def dynamics() -> common.PinocchioDynamics: return common.PinocchioDynamics(path, False, "attachment_site", common.Pose(translation=np.array([0, 0, 0.1]))) -def joint_controller(state) -> common.FR3JointController: - controller = common.FR3JointController( - common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05), JOINT_LIMITS - ) +def joint_controller(state, safety=True) -> common.JointController: + controller = common.FR3JointController(common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05)) + if safety: + controller = common.SafeJointController(controller, SAFETY, JOINT_LIMITS, DT) controller.reset(state) return controller -def osc(state, **config) -> common.FR3OSC: +def osc(state, safety=True, **config) -> common.CartesianController: cfg = common.FR3OSCConfig() for key, value in config.items(): setattr(cfg, key, value) controller = common.FR3OSC(cfg, common.LinearCartesianInterpolator(0.05), JOINT_LIMITS) + if safety: + controller = common.SafeCartesianController(controller, SAFETY, JOINT_LIMITS, DT) controller.reset(state) return controller @@ -65,7 +70,7 @@ def test_torque_is_clipped(dynamics): controller.set_goal(Q0 + 1.0, duration=DT) for _ in range(200): tau = controller.step(state) - np.testing.assert_allclose(np.abs(tau), common.FR3JointControllerConfig().torque_limit) + np.testing.assert_allclose(np.abs(tau), SAFETY.torque_limit) def test_no_torque_towards_a_close_joint_limit(dynamics): @@ -117,8 +122,11 @@ def test_fr3_controllers_in_sim(controller): setup = Setup() if controller == "joint": setup.robot.set_joint_controller( - common.FR3JointController( - common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05), JOINT_LIMITS + common.SafeJointController( + common.FR3JointController(common.FR3JointControllerConfig(), common.LinearJointInterpolator(0.05)), + SAFETY, + JOINT_LIMITS, + DT, ) ) goal = setup.robot.get_joint_position() + np.array([0.1, -0.1, 0.1, 0.1, -0.1, 0.1, 0.2]) @@ -129,7 +137,12 @@ def test_fr3_controllers_in_sim(controller): else: q_home = setup.robot.get_joint_position() setup.robot.set_cartesian_controller( - common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05), JOINT_LIMITS) + common.SafeCartesianController( + common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05), JOINT_LIMITS), + SAFETY, + JOINT_LIMITS, + DT, + ) ) start = setup.robot.get_cartesian_position() goal = common.Pose(rotation=start.rotation_m(), translation=start.translation() + np.array([0.05, -0.05, 0.0])) diff --git a/python/tests/test_robot_config.py b/python/tests/test_robot_config.py index 77f5412d5..5e63f3b05 100644 --- a/python/tests/test_robot_config.py +++ b/python/tests/test_robot_config.py @@ -62,3 +62,13 @@ def test_fr3_config_takes_its_values_from_rcs_robots(): assert cfg.policy_rate == 15 with pytest.raises(TypeError, match="no field"): hw.FR3Config(ip="192.168.1.11", asynch_control=True) # typo + + +def test_apply_sets_the_safety_stage_of_the_franka_robots_only(): + for robot_type in rcs.ROBOTS: + safety = rcs.ROBOTS[robot_type].apply(sim.SimRobotConfig()).safety + if robot_type in (common.RobotType.FR3, common.RobotType.Panda): + np.testing.assert_allclose(safety.torque_limit, [87.0] * 4 + [12.0] * 3) + assert safety.max_torque_rate == pytest.approx(1000.0 - 1e-3) + else: + assert safety is None diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index aaa710f13..093c8ae88 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -548,17 +548,14 @@ PYBIND11_MODULE(_core, m) { "FR3JointControllerConfig") .def(py::init<>()) .def_readwrite("kp", &rcs::common::FR3JointControllerConfig::kp) - .def_readwrite("kd", &rcs::common::FR3JointControllerConfig::kd) - .def_readwrite("torque_limit", - &rcs::common::FR3JointControllerConfig::torque_limit); + .def_readwrite("kd", &rcs::common::FR3JointControllerConfig::kd); py::class_>( common, "FR3JointController") .def(py::init, - const rcs::common::JointLimits&>(), - py::arg("config"), py::arg("interpolator"), py::arg("joint_limits")); + std::shared_ptr>(), + py::arg("config"), py::arg("interpolator")); py::class_(common, "FR3OSCConfig") .def(py::init<>()) @@ -568,8 +565,7 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("nullspace_q", &rcs::common::FR3OSCConfig::nullspace_q) .def_readwrite("residual_mass", &rcs::common::FR3OSCConfig::residual_mass) .def_readwrite("avoidance_weights", - &rcs::common::FR3OSCConfig::avoidance_weights) - .def_readwrite("torque_limit", &rcs::common::FR3OSCConfig::torque_limit); + &rcs::common::FR3OSCConfig::avoidance_weights); py::class_>(common, "FR3OSC") diff --git a/src/rcs/ControllerConfig.cpp b/src/rcs/ControllerConfig.cpp index a4418c6a7..6634c7b2d 100644 --- a/src/rcs/ControllerConfig.cpp +++ b/src/rcs/ControllerConfig.cpp @@ -28,8 +28,8 @@ ControllerPair make_controller(const ControllerConfig& config, } else if (auto* c = std::get_if(&config)) { controller.cartesian = std::make_shared(*c, cartesian_interpolator()); } else if (auto* c = std::get_if(&config)) { - controller.joint = std::make_shared( - *c, joint_interpolator(), joint_limits); + controller.joint = + std::make_shared(*c, joint_interpolator()); } else if (auto* c = std::get_if(&config)) { controller.cartesian = std::make_shared(*c, cartesian_interpolator(), joint_limits); diff --git a/src/rcs/FR3Controllers.cpp b/src/rcs/FR3Controllers.cpp index e81ad7c4e..0b52af2f6 100644 --- a/src/rcs/FR3Controllers.cpp +++ b/src/rcs/FR3Controllers.cpp @@ -1,7 +1,6 @@ #include "rcs/FR3Controllers.h" #include -#include #include #include @@ -10,10 +9,6 @@ namespace common { namespace { -// franka::limitRate with franka::kMaxTorqueRate: at most (1000 - 1e-3) Nm/s -// per joint, for the fixed 1 ms cycle libfranka assumes. -constexpr double kMaxTorqueStep = (1000.0 - 1e-3) * 1e-3; - // PInverse from Franka.cpp: SVD pseudo-inverse, singular values below // epsilon are dropped. Eigen::MatrixXd pseudo_inverse(const Eigen::MatrixXd& M, @@ -28,23 +23,6 @@ Eigen::MatrixXd pseudo_inverse(const Eigen::MatrixXd& M, return svd.matrixV() * S_inv * svd.matrixU().transpose(); } -// The end of both control loops in Franka.cpp, see FR3Controllers.h. -Vector7d safety_stage(Vector7d tau, const Vector7d& q, - const Vector7d& joint_min, const Vector7d& joint_max, - const Vector7d& torque_limit, Vector7d& last_tau) { - for (int i = 0; i < 7; i++) { - if (joint_max[i] - q[i] < 0.1 && tau[i] > 0.) tau[i] = 0.; - if (q[i] - joint_min[i] < 0.1 && tau[i] < 0.) tau[i] = 0.; - } - for (int i = 0; i < 7; i++) { - tau[i] = last_tau[i] + - std::clamp(tau[i] - last_tau[i], -kMaxTorqueStep, kMaxTorqueStep); - tau[i] = std::clamp(tau[i], -torque_limit[i], torque_limit[i]); - } - last_tau = tau; - return tau; -} - void check_seven_joints(const ControllerState& state) { if (state.q.size() != 7) { throw std::invalid_argument("FR3 controllers need 7 joints"); @@ -61,12 +39,8 @@ void check_joint_limits(const JointLimits& joint_limits) { FR3JointController::FR3JointController( const FR3JointControllerConfig& config, - std::shared_ptr interpolator, - const JointLimits& joint_limits) + std::shared_ptr interpolator) : config(config), interpolator(std::move(interpolator)) { - check_joint_limits(joint_limits); - this->joint_min = joint_limits.row(0).transpose(); - this->joint_max = joint_limits.row(1).transpose(); if (!this->interpolator) { throw std::invalid_argument("interpolator must not be null"); } @@ -75,7 +49,6 @@ FR3JointController::FR3JointController( void FR3JointController::reset(const ControllerState& state) { check_seven_joints(state); this->interpolator->reset(state.q); - this->last_tau.setZero(); } void FR3JointController::set_goal(const VectorXd& q_goal, @@ -92,8 +65,7 @@ VectorXd FR3JointController::step(const ControllerState& state) { Vector7d tau = this->config.kp.cwiseProduct(desired_q - q) - this->config.kd.cwiseProduct(dq); tau += state.coriolis; - return safety_stage(tau, q, this->joint_min, this->joint_max, - this->config.torque_limit, this->last_tau); + return tau; } FR3OSC::FR3OSC(const FR3OSCConfig& config, @@ -111,7 +83,6 @@ FR3OSC::FR3OSC(const FR3OSCConfig& config, void FR3OSC::reset(const ControllerState& state) { check_seven_joints(state); this->interpolator->reset(state.tcp_pose); - this->last_tau.setZero(); } void FR3OSC::set_goal(const Pose& pose_goal, std::optional duration) { @@ -188,8 +159,7 @@ VectorXd FR3OSC::step(const ControllerState& state) { tau += Nullspace * avoidance; tau += state.coriolis; - return safety_stage(tau, q, this->joint_min, this->joint_max, - cfg.torque_limit, this->last_tau); + return tau; } } // namespace common From e4ef75cd72e80a9c619e926fc5394709fa4ece4b Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 16:54:14 -0800 Subject: [PATCH 29/39] refactor(fr3): remove the controller gains from FrankaConfig kp, kd, kp_p and kp_r duplicated FR3JointControllerConfig and FR3OSCConfig. Without RobotConfig::controller, async control now runs the FR3 controllers with their default configs, which have the same values; other gains are set through RobotConfig::controller. --- extensions/rcs_fr3/src/hw/Franka.cpp | 10 ++-------- extensions/rcs_fr3/src/hw/Franka.h | 15 +++------------ extensions/rcs_fr3/src/pybind/rcs.cpp | 4 ---- .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 4 ---- 4 files changed, 5 insertions(+), 28 deletions(-) diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 834d5a286..19a590235 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -400,15 +400,9 @@ common::ControllerPair Franka::make_torque_controller(bool cartesian) { : "the configured controller is a Cartesian controller"); } } else if (cartesian) { - common::FR3OSCConfig osc; - osc.kp_position = this->m_cfg.kp_p; - osc.kp_orientation = this->m_cfg.kp_r; - config = osc; + config = common::FR3OSCConfig(); } else { - common::FR3JointControllerConfig joint; - joint.kp = this->m_cfg.kp; - joint.kd = this->m_cfg.kd; - config = joint; + config = common::FR3JointControllerConfig(); } // a goal per policy step, interpolated over one policy period return common::make_controller(config, 1.0 / this->m_cfg.policy_rate, diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 8a64b0eb0..d7b1770e4 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -46,19 +46,10 @@ struct FrankaConfig : common::RobotConfig { // period of the control loop in seconds; libfranka runs it at 1 kHz, so // anything else is rejected double timestep = 0.001; - // The gains below are for the default controllers, used when - // RobotConfig::controller is not set. A configured controller needs - // async_control. Async (torque) control needs RobotConfig::safety, the torque - // limits come from there. - // values from deoxys/config/joint-impedance-controller.yml - common::Vector7d kp = - (common::Vector7d() << 100., 100., 100., 100., 75., 150., 50.).finished(); - common::Vector7d kd = - (common::Vector7d() << 20., 20., 20., 20., 7.5, 15.0, 5.0).finished(); + // Without RobotConfig::controller, async control runs FR3JointController + // for joint goals and FR3OSC for Cartesian goals, with their default configs + // (deoxys gains). Async (torque) control needs RobotConfig::safety. bool allow_high_collision = false; - // values from deoxys/config/osc-position-controller.yml - Eigen::Vector3d kp_p = (Eigen::Vector3d() << 150., 150., 150.).finished(); - double kp_r = 250.0; std::optional load_parameters = std::nullopt; std::optional world_to_robot = std::nullopt; common::Pose tcp_offset = common::Pose::Identity(); diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index 96df2b4ae..2eaa5c081 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -133,12 +133,8 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("speed_factor", &rcs::hw::FrankaConfig::speed_factor) .def_readwrite("policy_rate", &rcs::hw::FrankaConfig::policy_rate) .def_readwrite("timestep", &rcs::hw::FrankaConfig::timestep) - .def_readwrite("kp", &rcs::hw::FrankaConfig::kp) - .def_readwrite("kd", &rcs::hw::FrankaConfig::kd) .def_readwrite("allow_high_collision", &rcs::hw::FrankaConfig::allow_high_collision) - .def_readwrite("kp_p", &rcs::hw::FrankaConfig::kp_p) - .def_readwrite("kp_r", &rcs::hw::FrankaConfig::kp_r) .def_readwrite("load_parameters", &rcs::hw::FrankaConfig::load_parameters) .def_readwrite("world_to_robot", &rcs::hw::FrankaConfig::world_to_robot) .def_property( diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 18ad6e9a7..08af1249d 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -111,10 +111,6 @@ class FrankaConfig(rcs._core.common.RobotConfig): ignore_realtime: bool ik_solver: IKSolver ip: str - kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] - kp_p: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] - kp_r: float load_parameters: FrankaLoad | None policy_rate: int speed_factor: float From 7f1d8c9b1d24fdd6b7e5e2cc3cab43f2a2c03dbe Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 17:16:46 -0800 Subject: [PATCH 30/39] feat(config): end effector config with the TCP offset and the payload RobotConfig::end_effector (EndEffectorConfig) holds the tool after the attachment site: tcp_offset, which replaces RobotConfig::tcp_offset, and the optional payload, which replaces SimRobotConfig::payload. Sim uses the payload as before; on a Franka the dynamics keep using the mass properties the robot reports. The Franka backend warns when connecting and in set_config() if Desk's end effector differs from the config: F_T_EE from tcp_offset (1 mm, 1 deg) and, if a payload is set, the reported total mass and centre of mass from it (50 g, 1 cm). FrankaConfig no longer redeclares tcp_offset, which hid the RobotConfig member, and the unused tcp_offset_explicit flag is gone. --- docs/development/controller_interface.md | 12 +- docs/getting_started/index.md | 5 +- docs/user_guide/conventions.md | 11 +- docs/user_guide/scene_configuration.md | 4 +- examples/fr3/fr3_direct_control.py | 2 +- extensions/rcs_flexiv/README.md | 2 +- .../rcs_flexiv/src/rcs_flexiv/configs.py | 2 +- extensions/rcs_flexiv/src/rcs_flexiv/hw.py | 6 +- .../src/rcs_flexiv/scripts/test_robot.py | 2 +- extensions/rcs_fr3/src/hw/Franka.cpp | 57 ++++++-- extensions/rcs_fr3/src/hw/Franka.h | 3 - extensions/rcs_fr3/src/pybind/rcs.cpp | 10 -- .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 2 - extensions/rcs_fr3/src/rcs_fr3/configs.py | 8 +- extensions/rcs_fr3/src/rcs_fr3/hw.py | 2 - extensions/rcs_panda/src/rcs_panda/configs.py | 4 +- extensions/rcs_panda/src/rcs_panda/hw.py | 2 - extensions/rcs_so101/src/rcs_so101/configs.py | 2 +- .../rcs_taxim/src/rcs_taxim/creators.py | 2 +- extensions/rcs_ur5e/src/rcs_ur5e/configs.py | 2 +- extensions/rcs_xarm7/src/rcs_xarm7/configs.py | 2 +- extensions/rcs_xarm7/src/rcs_xarm7/hw.py | 4 +- extensions/rcs_yam/src/rcs_yam/configs.py | 2 +- extensions/rcs_yam/src/rcs_yam/hw.py | 4 +- .../rcs_yam/src/rcs_yam/scripts/test_robot.py | 2 +- include/rcs/EndEffector.h | 36 +++++ include/rcs/PinocchioDynamics.h | 9 +- include/rcs/Robot.h | 4 +- python/rcs/_core/common.pyi | 24 ++- python/rcs/_core/sim.pyi | 10 +- python/rcs/common_typing.py | 2 +- python/rcs/envs/configs.py | 20 ++- python/tests/test_robot_config.py | 13 ++ python/tests/test_sim_torque_control.py | 2 +- src/pybind/rcs.cpp | 137 ++++++++++-------- src/sim/SimRobot.cpp | 12 +- src/sim/SimRobot.h | 4 - src/sim/test.cpp | 2 +- 38 files changed, 261 insertions(+), 168 deletions(-) create mode 100644 include/rcs/EndEffector.h diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 1853c2afe..3d110fb47 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -253,8 +253,8 @@ prevent under torque control. from the base orientation in the world, because arms can be mounted tilted (the right arm of our duo is tilted by about 52°, as fitted from its logged torques). - - Payload: from the sim robot config, set to the values configured on the - real robot. If none is configured, it defaults to the MJCF bodies + - Payload: `end_effector.payload` of the robot config, set to the values + configured on the real robot. If none is configured, it defaults to the MJCF bodies attached after the flange (summed mass, centre of mass and inertia), i.e. a perfectly configured tool. The backend warns when the configured payload differs noticeably from those bodies, because then either the @@ -281,9 +281,11 @@ prevent under torque control. - The bodies of the two `robot.control(...)` lambdas become: take `q`/`dq` from `RobotState`, `PinocchioDynamics::compute()`, `controller->step()`, return the torque. The payload is set from `RobotState` (`I_total`, - `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. - `FrankaConfig` has no tool payload to compare it with, so there is no - warning on hardware (a possible follow-up). + `m_total`, `F_x_Ctotal`) whenever it changes, as libfranka does. When + connecting and in `set_config()`, the backend warns if Desk's end effector + differs from `end_effector`: `F_T_EE` from `tcp_offset` (1 mm, 1°) and, + if `payload` is set, the reported mass and centre of mass from it (50 g, + 1 cm). RCS itself uses `tcp_offset`, not `F_T_EE`. - `PinocchioDynamics` is built from `kinematic_model_path` and `attachment_site` of `FrankaConfig` when a controller starts, so Desk-only uses of `Franka` don't need a model. diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md index 575d5418b..25d49a9ad 100644 --- a/docs/getting_started/index.md +++ b/docs/getting_started/index.md @@ -73,8 +73,9 @@ simulation = sim.Sim(rcs.SCENE_PATHS["empty_world"]) ik = rcs.common.Pin(robot_meta.mjcf_model_path, robot_meta.attachment_site, joint_limits=robot_meta.joint_limits) # Configure robot -cfg = sim.SimRobotConfig() -cfg.tcp_offset = rcs.common.Pose(rcs.common.FrankaHandTCPOffset()) +cfg = robot_meta.apply(sim.SimRobotConfig()) # type, model, dof, joint limits, home pose +cfg.joints = cfg.actuators = [f"fr3_joint{i}" for i in range(1, 8)] +cfg.end_effector.tcp_offset = rcs.common.Pose(rcs.common.FrankaHandTCPOffset()) robot = rcs.sim.SimRobot(simulation, ik, cfg) # Configure gripper diff --git a/docs/user_guide/conventions.md b/docs/user_guide/conventions.md index 81e67ad6f..a44e73ee5 100644 --- a/docs/user_guide/conventions.md +++ b/docs/user_guide/conventions.md @@ -66,16 +66,17 @@ Common examples in the repository are: If you are unsure which frame a robot uses, check its config or the relevant example scene in `python/rcs/envs/configs.py`. -### Tool frame: `tcp_offset` +### Tool frame: `end_effector.tcp_offset` -`tcp_offset` is applied on top of the attachment site to define the actual tool center point (TCP) used by motion commands and IK. +`end_effector.tcp_offset` is applied on top of the attachment site to define the actual tool center point (TCP) used by motion commands and IK. In practice: - `attachment_site` = frame coming from the robot model -- `tcp_offset` = extra transform from that frame to the tool you actually want to control +- `end_effector.tcp_offset` = extra transform from that frame to the tool you actually want to control +- `end_effector.payload` = optional mass properties of the tool, used by torque control (see the controller docs) -A typical example is a wrist-mounted gripper where the tool center point is slightly in front of the model's attachment site. +A typical example is a wrist-mounted gripper where the tool center point is slightly in front of the model's attachment site. On a Franka, Desk's end effector settings describe the same tool; RCS does not take them over but warns when they differ from `end_effector`. ## Pose representations @@ -213,7 +214,7 @@ When something looks wrong, check these first: 1. Are you working in **world frame** or **robot/base frame**? 2. Does your robot/base frame follow **x forward, y left, z up**? 3. Is your end-effector frame the correct `attachment_site`? -4. Did you apply the right `tcp_offset`? +4. Did you apply the right `end_effector.tcp_offset`? 5. Are your quaternions **xyzw** in RCS? 6. Are you accidentally feeding **MuJoCo `wxyz`** into an RCS API? 7. Are your Euler angles ordered as **roll, pitch, yaw** around **x, y, z**? diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index 5c7d443f5..15df2df3d 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -39,7 +39,7 @@ When building an RCS sim scene, it helps to think about five frames: - Low-level kinematics and Cartesian commands are expressed here. 5. **i-th robot `attachment_site`** - - The end-effector mounting frame for that robot, before any optional `tcp_offset`. + - The end-effector mounting frame for that robot, before any optional `end_effector.tcp_offset`. - Use this for wrist-mounted objects, cameras, and tools. A good rule of thumb is: @@ -128,7 +128,7 @@ Each robot entry usually defines things such as: - robot type - kinematic model path - `attachment_site` -- `tcp_offset` +- `end_effector` (`tcp_offset`, optional `payload`) - joint names and actuator names - base link name - degrees of freedom, joint limits, and `q_home` diff --git a/examples/fr3/fr3_direct_control.py b/examples/fr3/fr3_direct_control.py index e16a33c74..bdecb5cc2 100644 --- a/examples/fr3/fr3_direct_control.py +++ b/examples/fr3/fr3_direct_control.py @@ -103,7 +103,7 @@ def main(): default_env.ip = ROBOT_IP env_cfg = default_env.config() fr3_cfg = env_cfg.robot_cfg - fr3_cfg.tcp_offset = rcs.common.Pose(rcs.common.FrankaHandTCPOffset()) + fr3_cfg.end_effector.tcp_offset = rcs.common.Pose(rcs.common.FrankaHandTCPOffset()) ik = rcs.common.Pin( fr3_cfg.kinematic_model_path, fr3_cfg.attachment_site, diff --git a/extensions/rcs_flexiv/README.md b/extensions/rcs_flexiv/README.md index c7882cec0..412ee5f70 100644 --- a/extensions/rcs_flexiv/README.md +++ b/extensions/rcs_flexiv/README.md @@ -70,7 +70,7 @@ targets, so RCS never has to stream at 1 kHz. In the joint modes, RCS's Cartesian control modes go through the Pinocchio IK of the RCS robot model, exactly like in simulation. In `CARTESIAN_IMPEDANCE` the target pose is handed to the -robot's own Cartesian controller instead; RCS converts its TCP (`tcp_offset`) to the TCP of the +robot's own Cartesian controller instead; RCS converts its TCP (`end_effector.tcp_offset`) to the TCP of the active tool for that. Joint targets and `move_home` temporarily switch to joint impedance in that mode, mode switches stop the arm. diff --git a/extensions/rcs_flexiv/src/rcs_flexiv/configs.py b/extensions/rcs_flexiv/src/rcs_flexiv/configs.py index 46aa98971..3d357c754 100644 --- a/extensions/rcs_flexiv/src/rcs_flexiv/configs.py +++ b/extensions/rcs_flexiv/src/rcs_flexiv/configs.py @@ -38,7 +38,7 @@ def config(self) -> FlexivHardwareEnvCreatorConfig: dof=rcs.ROBOTS[robot_type].dof, joint_limits=rcs.ROBOTS[robot_type].joint_limits, q_home=rcs.ROBOTS[robot_type].q_home, - tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type], + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type]), ) gripper_cfg = FlexivGripperConfig( diff --git a/extensions/rcs_flexiv/src/rcs_flexiv/hw.py b/extensions/rcs_flexiv/src/rcs_flexiv/hw.py index a247aac31..e36a28e7d 100644 --- a/extensions/rcs_flexiv/src/rcs_flexiv/hw.py +++ b/extensions/rcs_flexiv/src/rcs_flexiv/hw.py @@ -266,7 +266,7 @@ def get_cartesian_flange_position(self) -> common.Pose: return self.ik.forward(self.get_joint_position(), common.Pose()) def get_cartesian_position(self) -> common.Pose: - return self.get_cartesian_flange_position() * self._config.tcp_offset + return self.get_cartesian_flange_position() * self._config.end_effector.tcp_offset def set_joint_position(self, q: np.ndarray[tuple[typing.Any], np.dtype[np.float64]]) -> None: q = np.asarray(q, dtype=np.float64) @@ -279,7 +279,7 @@ def set_joint_position(self, q: np.ndarray[tuple[typing.Any], np.dtype[np.float6 def set_cartesian_position(self, pose: common.Pose) -> None: if self._config.control_mode != FlexivControlMode.CARTESIAN_IMPEDANCE: - q = self.ik.inverse(pose, self.get_joint_position(), self._config.tcp_offset) + q = self.ik.inverse(pose, self.get_joint_position(), self._config.end_effector.tcp_offset) if q is None: logger.warning("IK failed for %s", pose) return @@ -289,7 +289,7 @@ def set_cartesian_position(self, pose: common.Pose) -> None: self._ensure_mode(FlexivControlMode.CARTESIAN_IMPEDANCE) # The RDK tracks the pose of the active tool's TCP in its world frame, RCS commands the pose of its own # TCP offset in the base frame. - rdk_target = self._world_from_base * pose * self._config.tcp_offset.inverse() * self._tool_tcp + rdk_target = self._world_from_base * pose * self._config.end_effector.tcp_offset.inverse() * self._tool_tcp self._robot.SendCartesianMotionForce( _pose_to_rdk(rdk_target), [0.0] * 6, diff --git a/extensions/rcs_flexiv/src/rcs_flexiv/scripts/test_robot.py b/extensions/rcs_flexiv/src/rcs_flexiv/scripts/test_robot.py index 91aef19f7..1a20221f5 100644 --- a/extensions/rcs_flexiv/src/rcs_flexiv/scripts/test_robot.py +++ b/extensions/rcs_flexiv/src/rcs_flexiv/scripts/test_robot.py @@ -41,7 +41,7 @@ def main() -> None: dof=rcs.ROBOTS[robot_type].dof, joint_limits=rcs.ROBOTS[robot_type].joint_limits, q_home=rcs.ROBOTS[robot_type].q_home, - tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type], + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type]), ) ik = rcs.common.Pin(robot_config.kinematic_model_path, robot_config.attachment_site) robot = Flexiv(robot_config, ik) diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index 19a590235..b3eaed0a7 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -46,6 +46,39 @@ void check_config(const FrankaConfig& cfg) { "PandaConfig set it from rcs.ROBOTS"); } } + +// Desk's end effector settings (F_T_EE, and the mass properties the robot +// reports, including a load set with setLoad) are not used by RCS: the TCP +// comes from end_effector.tcp_offset, the dynamics take the reported mass +// properties. Warn when Desk and the config disagree, sim would then differ. +void warn_if_desk_differs(const FrankaConfig& cfg, + const franka::RobotState& state) { + const common::Pose desk_tcp(state.F_T_EE); + const common::Pose& tcp = cfg.end_effector.tcp_offset; + const double distance = (desk_tcp.translation() - tcp.translation()).norm(); + const double angle = + Eigen::AngleAxisd(desk_tcp.quaternion().inverse() * tcp.quaternion()) + .angle(); + if (distance > 1e-3 || angle > 1.0 / 180.0 * M_PI) { + std::cerr << "Warning: the end effector in Desk (F_T_EE translation " + << desk_tcp.translation().transpose() + << ") differs from end_effector.tcp_offset (translation " + << tcp.translation().transpose() << ") by " << distance * 1000 + << " mm and " << angle * 180.0 / M_PI << " deg." << std::endl; + } + if (cfg.end_effector.payload.has_value()) { + const common::Payload& payload = cfg.end_effector.payload.value(); + const Eigen::Vector3d desk_com(state.F_x_Ctotal.data()); + if (std::abs(state.m_total - payload.mass) > 0.05 || + (desk_com - payload.com).norm() > 0.01) { + std::cerr << "Warning: the payload the robot reports (Desk end effector " + "and load: " + << state.m_total << " kg, CoM " << desk_com.transpose() + << ") differs from end_effector.payload (" << payload.mass + << " kg, CoM " << payload.com.transpose() << ")." << std::endl; + } + } +} } // namespace Franka::Franka(const FrankaConfig& cfg, @@ -55,6 +88,7 @@ Franka::Franka(const FrankaConfig& cfg, robot(cfg.ip, cfg.ignore_realtime ? franka::RealtimeConfig::kIgnore : franka::RealtimeConfig::kEnforce) { check_config(cfg); + warn_if_desk_differs(cfg, this->robot.readOnce()); // set collision behavior and impedance this->set_default_robot_behavior(); this->set_guiding_mode(true, true, true, true, true, true, true); @@ -92,6 +126,10 @@ bool Franka::set_config(const FrankaConfig& cfg) { common::eigen2array<3, 1>(load_value->f_x_cload.value()), common::eigen2array<3, 3>(load_value->load_inertia.value())); } + warn_if_desk_differs(this->m_cfg, + this->running_controller.load() == Controller::none + ? this->robot.readOnce() + : this->curr_state.load()); return true; } @@ -136,7 +174,7 @@ common::Pose Franka::get_cartesian_position() { } else { robot_state = this->curr_state.load(); } - return GetTCPInBaseFrame(robot_state, this->m_cfg.tcp_offset); + return GetTCPInBaseFrame(robot_state, this->m_cfg.end_effector.tcp_offset); } common::Pose Franka::get_cartesian_flange_position() { @@ -162,7 +200,7 @@ void Franka::set_joint_position(const common::VectorXd& q) { "joint goals for a Cartesian controller need kinematics"); } this->osc_set_cartesian_position( - this->m_ik.value()->forward(q, this->m_cfg.tcp_offset)); + this->m_ik.value()->forward(q, this->m_cfg.end_effector.tcp_offset)); return; } this->controller_set_joint_position(q); @@ -304,8 +342,8 @@ void Franka::osc_set_cartesian_position( this->interpolator_mutex.lock(); } - common::Pose curr_pose = - GetTCPInBaseFrame(this->curr_state.load(), this->m_cfg.tcp_offset); + common::Pose curr_pose = GetTCPInBaseFrame( + this->curr_state.load(), this->m_cfg.end_effector.tcp_offset); const bool approach_on_start = starting_fresh && this->m_cfg.blocking_move_on_start; @@ -358,7 +396,7 @@ void Franka::osc_set_cartesian_position( franka::RobotState state = this->curr_state.load(); const common::Vector7d dq = Eigen::Map(state.dq.data()); const common::Pose meas_pose = - GetTCPInBaseFrame(state, this->m_cfg.tcp_offset); + GetTCPInBaseFrame(state, this->m_cfg.end_effector.tcp_offset); const double pos_err = (target_p - meas_pose.translation()).norm(); double dot = std::abs(meas_pose.quaternion().normalized().dot(target_q)); dot = std::min(1.0, dot); @@ -417,7 +455,7 @@ void Franka::create_dynamics() { this->dynamics = std::make_shared( path, urdf, this->m_cfg.attachment_site); } - this->dynamics->set_tcp_offset(this->m_cfg.tcp_offset); + this->dynamics->set_tcp_offset(this->m_cfg.end_effector.tcp_offset); } common::ControllerState Franka::controller_state( @@ -662,7 +700,8 @@ void Franka::set_cartesian_position(const common::Pose& x) { if (this->m_cfg.ik_solver == IKSolver::franka_ik) { const franka::RobotState robot_state = this->robot.readOnce(); const common::Pose target_pose = - x * this->m_cfg.tcp_offset.inverse() * common::Pose(robot_state.F_T_EE); + x * this->m_cfg.end_effector.tcp_offset.inverse() * + common::Pose(robot_state.F_T_EE); this->set_cartesian_position_internal(target_pose, 1.0, std::nullopt, std::nullopt); @@ -677,8 +716,8 @@ void Franka::set_cartesian_position_ik(const common::Pose& pose) { "No inverse kinematics was provided. Cannot use IK to set cartesian " "position."); } - auto joints = this->m_ik.value()->inverse(pose, this->get_joint_position(), - this->m_cfg.tcp_offset); + auto joints = this->m_ik.value()->inverse( + pose, this->get_joint_position(), this->m_cfg.end_effector.tcp_offset); if (joints.has_value()) { this->set_joint_position(joints.value()); diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index d7b1770e4..afa8efa84 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -52,9 +52,6 @@ struct FrankaConfig : common::RobotConfig { bool allow_high_collision = false; std::optional load_parameters = std::nullopt; std::optional world_to_robot = std::nullopt; - common::Pose tcp_offset = common::Pose::Identity(); - // Indicates that Cartesian control uses tcp_offset. - bool tcp_offset_explicit = false; bool async_control = false; // When true, on every (re)start of the joint controller the controller first // holds the current measured position (~zero error) and ramps its target to diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index 2eaa5c081..3374e2a42 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -137,16 +137,6 @@ PYBIND11_MODULE(_core, m) { &rcs::hw::FrankaConfig::allow_high_collision) .def_readwrite("load_parameters", &rcs::hw::FrankaConfig::load_parameters) .def_readwrite("world_to_robot", &rcs::hw::FrankaConfig::world_to_robot) - .def_property( - "tcp_offset", - [](const rcs::hw::FrankaConfig& config) { return config.tcp_offset; }, - [](rcs::hw::FrankaConfig& config, - const rcs::common::Pose& tcp_offset) { - config.tcp_offset = tcp_offset; - config.tcp_offset_explicit = true; - }) - .def_readwrite("tcp_offset_explicit", - &rcs::hw::FrankaConfig::tcp_offset_explicit) .def_readwrite("async_control", &rcs::hw::FrankaConfig::async_control) .def_readwrite("blocking_move_on_start", &rcs::hw::FrankaConfig::blocking_move_on_start) diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 08af1249d..45b21c38b 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -114,8 +114,6 @@ class FrankaConfig(rcs._core.common.RobotConfig): load_parameters: FrankaLoad | None policy_rate: int speed_factor: float - tcp_offset: rcs._core.common.Pose - tcp_offset_explicit: bool timestep: float world_to_robot: rcs._core.common.Pose | None def __init__(self) -> None: ... diff --git a/extensions/rcs_fr3/src/rcs_fr3/configs.py b/extensions/rcs_fr3/src/rcs_fr3/configs.py index 1482c2abd..e2316f5b7 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/configs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/configs.py @@ -25,7 +25,7 @@ def config(self) -> FR3HardwareEnvCreatorConfig: speed_factor=0.1, async_control=False, ignore_realtime=False, - tcp_offset=common.Pose(common.FrankaHandTCPOffset()), + end_effector=common.EndEffectorConfig(tcp_offset=common.Pose(common.FrankaHandTCPOffset())), ) gripper_cfg = hw.FHConfig( @@ -111,7 +111,7 @@ def config(self) -> FR3MultiHardwareEnvCreatorConfig: cfg = base.config() cfg.robot_cfg.async_control = True cfg.robot_cfg.ip = self.robot_ip - cfg.robot_cfg.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] + cfg.robot_cfg.end_effector.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] cfg.robot_cfg.q_home = rcs.HOME_POSITIONS["FR3_DROID"] return FR3MultiHardwareEnvCreatorConfig( @@ -201,8 +201,8 @@ def config(self) -> FR3MultiHardwareEnvCreatorConfig: cfg = super().config() cfg.camera_cfgs = None - cfg.robot_cfgs["left"].tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] - cfg.robot_cfgs["right"].tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] + cfg.robot_cfgs["left"].end_effector.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] + cfg.robot_cfgs["right"].end_effector.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] cfg.robot_cfgs["left"].q_home = rcs.HOME_POSITIONS["FR3_DUO_LEFT"] cfg.robot_cfgs["right"].q_home = rcs.HOME_POSITIONS["FR3_DUO_RIGHT"] cfg.gripper_cfgs = { diff --git a/extensions/rcs_fr3/src/rcs_fr3/hw.py b/extensions/rcs_fr3/src/rcs_fr3/hw.py index d903136d2..1809efcb1 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/hw.py +++ b/extensions/rcs_fr3/src/rcs_fr3/hw.py @@ -36,8 +36,6 @@ def __init__(self, ip: str, **kwargs: Any): super().__init__() rcs.ROBOTS[common.RobotType.FR3].apply(self) self.ip = ip - # Cartesian control uses tcp_offset (identity unless given), as before - self.tcp_offset_explicit = True for key, value in kwargs.items(): if not hasattr(self, key): msg = f"FR3Config has no field {key}" diff --git a/extensions/rcs_panda/src/rcs_panda/configs.py b/extensions/rcs_panda/src/rcs_panda/configs.py index 122f1da6d..3edf36bb1 100644 --- a/extensions/rcs_panda/src/rcs_panda/configs.py +++ b/extensions/rcs_panda/src/rcs_panda/configs.py @@ -20,7 +20,7 @@ class DefaultPandaHardwareEnv(RCSPandaConfigEnvCreator): def config(self) -> PandaHardwareEnvCreatorConfig: robot_cfg = hw.PandaConfig(ip=self.ip) - robot_cfg.tcp_offset = common.Pose(common.FrankaHandTCPOffset()) + robot_cfg.end_effector.tcp_offset = common.Pose(common.FrankaHandTCPOffset()) robot_cfg.speed_factor = 0.1 robot_cfg.ik_solver = hw.IKSolver.rcs_ik robot_cfg.async_control = False @@ -58,7 +58,7 @@ def config(self) -> PandaMultiHardwareEnvCreatorConfig: cfg = base.config() cfg.robot_cfg.async_control = True cfg.robot_cfg.ip = self.robot_ip - cfg.robot_cfg.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] + cfg.robot_cfg.end_effector.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[common.GripperType.Robotiq2F85] cfg.robot_cfg.q_home = rcs.ROBOTS[RobotType.Panda].q_home return PandaMultiHardwareEnvCreatorConfig( diff --git a/extensions/rcs_panda/src/rcs_panda/hw.py b/extensions/rcs_panda/src/rcs_panda/hw.py index e25a68aec..b988f947b 100644 --- a/extensions/rcs_panda/src/rcs_panda/hw.py +++ b/extensions/rcs_panda/src/rcs_panda/hw.py @@ -36,8 +36,6 @@ def __init__(self, ip: str, **kwargs: Any): super().__init__() rcs.ROBOTS[common.RobotType.Panda].apply(self) self.ip = ip - # Cartesian control uses tcp_offset (identity unless given), as before - self.tcp_offset_explicit = True for key, value in kwargs.items(): if not hasattr(self, key): msg = f"PandaConfig has no field {key}" diff --git a/extensions/rcs_so101/src/rcs_so101/configs.py b/extensions/rcs_so101/src/rcs_so101/configs.py index 747335b64..056357a9b 100644 --- a/extensions/rcs_so101/src/rcs_so101/configs.py +++ b/extensions/rcs_so101/src/rcs_so101/configs.py @@ -22,7 +22,7 @@ def config(self) -> SO101HardwareEnvCreatorConfig: dof=rcs.ROBOTS[RobotType.SO101].dof, joint_limits=rcs.ROBOTS[RobotType.SO101].joint_limits, q_home=rcs.ROBOTS[RobotType.SO101].q_home, - tcp_offset=rcs.common.Pose(), + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.common.Pose()), ) return SO101HardwareEnvCreatorConfig( diff --git a/extensions/rcs_taxim/src/rcs_taxim/creators.py b/extensions/rcs_taxim/src/rcs_taxim/creators.py index 1dc597c57..0007e1219 100644 --- a/extensions/rcs_taxim/src/rcs_taxim/creators.py +++ b/extensions/rcs_taxim/src/rcs_taxim/creators.py @@ -84,7 +84,7 @@ def __call__( scene = EmptyWorldFR3() cfg = scene.config() - cfg.robot_cfgs["right"].tcp_offset = rcs.GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] + cfg.robot_cfgs["right"].end_effector.tcp_offset = rcs.GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] cfg.control_mode = control_mode cfg.headless = render_mode != "human" cfg.sim_cfg.realtime = render_mode == "human" diff --git a/extensions/rcs_ur5e/src/rcs_ur5e/configs.py b/extensions/rcs_ur5e/src/rcs_ur5e/configs.py index 37802922b..86ff08db7 100644 --- a/extensions/rcs_ur5e/src/rcs_ur5e/configs.py +++ b/extensions/rcs_ur5e/src/rcs_ur5e/configs.py @@ -26,7 +26,7 @@ def config(self) -> UR5eHardwareEnvCreatorConfig: dof=rcs.ROBOTS[robot_type].dof, joint_limits=rcs.ROBOTS[robot_type].joint_limits, q_home=rcs.ROBOTS[robot_type].q_home, - tcp_offset=rcs.common.Pose(), + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.common.Pose()), ) gripper_cfg = RobotiQGripperConfig(ip=self.ip) diff --git a/extensions/rcs_xarm7/src/rcs_xarm7/configs.py b/extensions/rcs_xarm7/src/rcs_xarm7/configs.py index 020343c3a..b006a5f0c 100644 --- a/extensions/rcs_xarm7/src/rcs_xarm7/configs.py +++ b/extensions/rcs_xarm7/src/rcs_xarm7/configs.py @@ -23,7 +23,7 @@ def config(self) -> XArm7HardwareEnvCreatorConfig: dof=rcs.ROBOTS[robot_type].dof, joint_limits=rcs.ROBOTS[robot_type].joint_limits, q_home=rcs.ROBOTS[robot_type].q_home, - tcp_offset=rcs.common.Pose(), + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.common.Pose()), ) return XArm7HardwareEnvCreatorConfig( diff --git a/extensions/rcs_xarm7/src/rcs_xarm7/hw.py b/extensions/rcs_xarm7/src/rcs_xarm7/hw.py index 319057bc6..a509e3c25 100644 --- a/extensions/rcs_xarm7/src/rcs_xarm7/hw.py +++ b/extensions/rcs_xarm7/src/rcs_xarm7/hw.py @@ -96,7 +96,9 @@ def reset(self) -> None: def set_cartesian_position(self, pose: common.Pose) -> None: if not self._config.use_internal_ik: - target_joints = self.ik.inverse(pose=pose, q0=self.get_joint_position(), tcp_offset=self._config.tcp_offset) + target_joints = self.ik.inverse( + pose=pose, q0=self.get_joint_position(), tcp_offset=self._config.end_effector.tcp_offset + ) if target_joints is not None: self.set_joint_position(target_joints) return diff --git a/extensions/rcs_yam/src/rcs_yam/configs.py b/extensions/rcs_yam/src/rcs_yam/configs.py index 613ae6de5..61b66d643 100644 --- a/extensions/rcs_yam/src/rcs_yam/configs.py +++ b/extensions/rcs_yam/src/rcs_yam/configs.py @@ -32,7 +32,7 @@ def config(self) -> YamHardwareEnvCreatorConfig: joint_limits=rcs.ROBOTS[robot_type].joint_limits, q_home=rcs.ROBOTS[robot_type].q_home, # The gripper is part of the arm's mjcf, so this is the flange to grasp point offset. - tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type], + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type]), ) gripper_cfg = GripperConfig(gripper_type=gripper_type) diff --git a/extensions/rcs_yam/src/rcs_yam/hw.py b/extensions/rcs_yam/src/rcs_yam/hw.py index ecf414a77..73eb0dec3 100644 --- a/extensions/rcs_yam/src/rcs_yam/hw.py +++ b/extensions/rcs_yam/src/rcs_yam/hw.py @@ -173,13 +173,13 @@ def get_commanded_gripper_width(self) -> float: def get_cartesian_position(self) -> common.Pose: # `Kinematics.forward` applies the inverse of the offset it is handed, so the TCP is composed # here instead, to match the pose `SimRobot::get_cartesian_position` reports in simulation. - return self.get_cartesian_flange_position() * self._config.tcp_offset + return self.get_cartesian_flange_position() * self._config.end_effector.tcp_offset def get_cartesian_flange_position(self) -> common.Pose: return self.ik.forward(self.get_joint_position(), common.Pose()) def set_cartesian_position(self, pose: common.Pose) -> None: - q = self.ik.inverse(pose, self.get_joint_position(), self._config.tcp_offset) + q = self.ik.inverse(pose, self.get_joint_position(), self._config.end_effector.tcp_offset) if q is None: print("IK failed") return diff --git a/extensions/rcs_yam/src/rcs_yam/scripts/test_robot.py b/extensions/rcs_yam/src/rcs_yam/scripts/test_robot.py index 8114eb118..497baf313 100644 --- a/extensions/rcs_yam/src/rcs_yam/scripts/test_robot.py +++ b/extensions/rcs_yam/src/rcs_yam/scripts/test_robot.py @@ -24,7 +24,7 @@ dof=rcs.ROBOTS[robot_type].dof, joint_limits=rcs.ROBOTS[robot_type].joint_limits, q_home=rcs.ROBOTS[robot_type].q_home, - tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type], + end_effector=rcs.common.EndEffectorConfig(tcp_offset=rcs.GRIPPER_TCP_OFFSETS[gripper_type]), ) ik = rcs.common.Pin( robot_config.kinematic_model_path, diff --git a/include/rcs/EndEffector.h b/include/rcs/EndEffector.h new file mode 100644 index 000000000..a763384c0 --- /dev/null +++ b/include/rcs/EndEffector.h @@ -0,0 +1,36 @@ +#ifndef RCS_END_EFFECTOR_H +#define RCS_END_EFFECTOR_H + +#include +#include + +#include "Pose.h" + +namespace rcs { +namespace common { + +// Load fixed to the flange, e.g. a gripper, expressed in the flange frame. +// Same meaning as libfranka's m_total, F_x_Ctotal and I_total. +struct Payload { + double mass = 0.0; + Eigen::Vector3d com = Eigen::Vector3d::Zero(); + Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero(); // about the CoM +}; + +// The tool after the flange (the attachment site): where its TCP is and what +// it weighs. On a Franka, Desk's end effector settings hold the same two +// things (F_T_EE and the mass properties); the backend warns when they differ. +struct EndEffectorConfig { + // TCP relative to the flange, used by Cartesian goals, observations, IK + // and the dynamics + Pose tcp_offset = Pose::Identity(); + // Mass properties for the dynamics of torque control. None: sim uses the + // MJCF bodies after the flange, hardware what the robot reports (Desk). + // Set: sim uses it for the controller model and the gravity compensation + // (as the firmware does with Desk's values), hardware compares it to Desk. + std::optional payload = std::nullopt; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_END_EFFECTOR_H diff --git a/include/rcs/PinocchioDynamics.h b/include/rcs/PinocchioDynamics.h index 98ae65746..71b5d53b7 100644 --- a/include/rcs/PinocchioDynamics.h +++ b/include/rcs/PinocchioDynamics.h @@ -5,6 +5,7 @@ #include #include "Controller.h" +#include "EndEffector.h" #include "Pose.h" #include "pinocchio/multibody/data.hpp" #include "pinocchio/multibody/model.hpp" @@ -13,14 +14,6 @@ namespace rcs { namespace common { -// Load fixed to the flange, e.g. a gripper, expressed in the flange frame. -// Same meaning as libfranka's m_total, F_x_Ctotal and I_total. -struct Payload { - double mass = 0.0; - Eigen::Vector3d com = Eigen::Vector3d::Zero(); - Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero(); // about the CoM -}; - // Rigid-body dynamics of one arm, used by sim and real alike to fill the // ControllerState. Computes the same quantities as libfranka's franka::Model, // which is itself built on Pinocchio. diff --git a/include/rcs/Robot.h b/include/rcs/Robot.h index ac7698eaf..3715b9389 100644 --- a/include/rcs/Robot.h +++ b/include/rcs/Robot.h @@ -9,6 +9,7 @@ #include #include "ControllerConfig.h" +#include "EndEffector.h" #include "Kinematics.h" #include "Pose.h" #include "utils.h" @@ -72,7 +73,8 @@ inline const RobotType RobotType::Rizon4S{"Rizon4S"}; struct RobotConfig { RobotType robot_type; RobotPlatform robot_platform = RobotPlatform::SIMULATION; - rcs::common::Pose tcp_offset = rcs::common::Pose::Identity(); + // the tool after the attachment site: TCP offset and payload + EndEffectorConfig end_effector; std::string attachment_site; std::string kinematic_model_path; std::optional q_home = std::nullopt; diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 226cba70f..7ef123384 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -15,6 +15,7 @@ __all__: list[str] = [ "CartesianInterpolator", "CartesianSetpoint", "ControllerState", + "EndEffectorConfig", "FR3JointController", "FR3JointControllerConfig", "FR3OSC", @@ -102,6 +103,25 @@ class ControllerState: tcp_pose: Pose def __init__(self) -> None: ... +class EndEffectorConfig: + def __init__(self, tcp_offset: Pose = ..., payload: Payload | None = None) -> None: ... + @property + def payload(self) -> Payload | None: + """ + Mass properties after the flange for torque control. None: sim uses the MJCF bodies, hardware what the robot reports (Desk). Set: sim compensates gravity with it, hardware warns if Desk differs. + """ + + @payload.setter + def payload(self, arg0: Payload | None) -> None: ... + @property + def tcp_offset(self) -> Pose: + """ + TCP relative to the flange (attachment site) + """ + + @tcp_offset.setter + def tcp_offset(self, arg0: Pose) -> None: ... + class FR3JointControllerConfig: kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] @@ -401,20 +421,20 @@ class RobotConfig(typing.Generic[M]): attachment_site: str controller: JointPDConfig | OSCConfig | FR3JointControllerConfig | FR3OSCConfig | None dof: int + end_effector: EndEffectorConfig joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]] kinematic_model_path: str q_home: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None robot_platform: RobotPlatform robot_type: RobotType safety: SafetyConfig | None - tcp_offset: Pose def __init__( self, robot_type: RobotType = ..., dof: int = 0, joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]] = ..., robot_platform: RobotPlatform = ..., - tcp_offset: Pose = ..., + end_effector: EndEffectorConfig = ..., attachment_site: str = "", kinematic_model_path: str = "", q_home: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None = None, diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index f192ca4ef..eafb0c1a7 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -207,7 +207,7 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): def __init__( self, robot_type: rcs._core.common.RobotType = ..., - tcp_offset: rcs._core.common.Pose = ..., + end_effector: rcs._core.common.EndEffectorConfig = ..., attachment_site: str = "", kinematic_model_path: str = "", joint_rotational_tolerance: float = 0.0008726646259971648, @@ -240,14 +240,6 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): @kv.setter def kv(self, arg0: list[float] | None) -> None: ... - @property - def payload(self) -> rcs._core.common.Payload | None: - """ - Tool as configured on the real robot, used for gravity compensation under torque control; None uses the MJCF bodies after the flange - """ - - @payload.setter - def payload(self, arg0: rcs._core.common.Payload | None) -> None: ... class SimRobotState(rcs._core.common.RobotState): def __init__(self) -> None: ... diff --git a/python/rcs/common_typing.py b/python/rcs/common_typing.py index 2611b284c..ee76fd86b 100644 --- a/python/rcs/common_typing.py +++ b/python/rcs/common_typing.py @@ -22,7 +22,7 @@ class RobotConfigKwargs(TypedDict, total=False): dof: int joint_limits: numpy.ndarray robot_platform: common.RobotPlatform - tcp_offset: common.Pose + end_effector: common.EndEffectorConfig attachment_site: str kinematic_model_path: str q_home: numpy.ndarray | None diff --git a/python/rcs/envs/configs.py b/python/rcs/envs/configs.py index 52c0c59dd..329b0ca32 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -33,7 +33,9 @@ def config(self) -> SimEnvCreatorConfig: q_home = rcs.ROBOTS[RobotType.FR3].q_home.copy() q_home[-1] = np.pi / 4 robot_cfg: SimRobotConfig[Literal[7]] = SimRobotConfig( - tcp_offset=GRIPPER_TCP_OFFSETS[rcs.common.GripperType.FrankaHand], + end_effector=rcs.common.EndEffectorConfig( + tcp_offset=GRIPPER_TCP_OFFSETS[rcs.common.GripperType.FrankaHand] + ), joint_rotational_tolerance=0.05 * (np.pi / 180.0), seconds_between_callbacks=0.1, trajectory_trace=False, @@ -176,7 +178,7 @@ def config(self) -> SimEnvCreatorConfig: lead_robot_name = self.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[lead_robot_name] - robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] + robot_cfg.end_effector.tcp_offset = GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] robot_cfg.q_home = rcs.ROBOTS[RobotType.FR3].q_home.copy() assert cfg.gripper_cfgs is not None @@ -271,7 +273,9 @@ class EmptyWorldFR3Duo(SimEnvCreator): def config(self) -> SimEnvCreatorConfig: robot_cfg: SimRobotConfig[Literal[7]] = SimRobotConfig( - tcp_offset=GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85], + end_effector=rcs.common.EndEffectorConfig( + tcp_offset=GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] + ), joint_rotational_tolerance=0.05 * (np.pi / 180.0), seconds_between_callbacks=0.1, trajectory_trace=False, @@ -440,7 +444,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfg = cfg.robot_cfgs[lead_robot_name] rcs.ROBOTS[rt].apply(robot_cfg) - robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] + robot_cfg.end_effector.tcp_offset = GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] robot_cfg.arm_collision_geoms = [] robot_cfg.joints = [ "shoulder_pan_joint", @@ -482,7 +486,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfg = cfg.robot_cfgs[lead_robot_name] rcs.ROBOTS[rt].apply(robot_cfg) - robot_cfg.tcp_offset = rcs.common.Pose() + robot_cfg.end_effector.tcp_offset = rcs.common.Pose() robot_cfg.arm_collision_geoms = [] robot_cfg.joints = [ "joint1", @@ -523,7 +527,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfg = cfg.robot_cfgs[lead_robot_name] rcs.ROBOTS[rt].apply(robot_cfg) - robot_cfg.tcp_offset = rcs.common.Pose() + robot_cfg.end_effector.tcp_offset = rcs.common.Pose() robot_cfg.arm_collision_geoms = [] robot_cfg.joints = ["1", "2", "3", "4", "5"] robot_cfg.actuators = ["1", "2", "3", "4", "5"] @@ -559,7 +563,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfg = cfg.robot_cfgs[lead_robot_name] rcs.ROBOTS[rt].apply(robot_cfg) - robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[GripperType.Yam] + robot_cfg.end_effector.tcp_offset = GRIPPER_TCP_OFFSETS[GripperType.Yam] robot_cfg.arm_collision_geoms = [] robot_cfg.joints = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"] robot_cfg.actuators = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"] @@ -595,7 +599,7 @@ def config(self) -> SimEnvCreatorConfig: robot_cfg = cfg.robot_cfgs[lead_robot_name] rcs.ROBOTS[rt].apply(robot_cfg) - robot_cfg.tcp_offset = GRIPPER_TCP_OFFSETS[GripperType.FlexivGrav] + robot_cfg.end_effector.tcp_offset = GRIPPER_TCP_OFFSETS[GripperType.FlexivGrav] robot_cfg.arm_collision_geoms = [] robot_cfg.joints = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"] robot_cfg.actuators = ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6", "joint7"] diff --git a/python/tests/test_robot_config.py b/python/tests/test_robot_config.py index 5e63f3b05..9fdbb2180 100644 --- a/python/tests/test_robot_config.py +++ b/python/tests/test_robot_config.py @@ -1,5 +1,7 @@ """The robot specific fields of RobotConfig come from rcs.ROBOTS, not from C++ defaults.""" +import copy + import numpy as np import pytest from test_sim_torque_control import Setup @@ -72,3 +74,14 @@ def test_apply_sets_the_safety_stage_of_the_franka_robots_only(): assert safety.max_torque_rate == pytest.approx(1000.0 - 1e-3) else: assert safety is None + + +def test_end_effector_holds_the_tcp_offset_and_the_payload(): + cfg = sim.SimRobotConfig() + assert cfg.end_effector.payload is None + np.testing.assert_allclose(cfg.end_effector.tcp_offset.pose_matrix(), np.eye(4)) + cfg.end_effector.tcp_offset = common.Pose(translation=np.array([0.0, 0.0, 0.1493])) + cfg.end_effector.payload = common.Payload(mass=0.9, com=np.array([0.0, 0.0, 0.057]), inertia=np.eye(3) * 1e-3) + copied = copy.deepcopy(cfg) + np.testing.assert_allclose(copied.end_effector.tcp_offset.translation(), [0.0, 0.0, 0.1493]) + assert copied.end_effector.payload.mass == pytest.approx(0.9) diff --git a/python/tests/test_sim_torque_control.py b/python/tests/test_sim_torque_control.py index 43fbb80af..b23c49e3e 100644 --- a/python/tests/test_sim_torque_control.py +++ b/python/tests/test_sim_torque_control.py @@ -19,7 +19,7 @@ def __init__(self, payload: common.Payload | None = None, friction: bool = True, cfg = scene.prefixed_cfg(scene.config()) name = scene.lead_robot_name(cfg) robot_cfg = cfg.robot_cfgs[name] - robot_cfg.payload = payload + robot_cfg.end_effector.payload = payload model = scene.create_model(cfg) if not friction: for joint in model.spec.joints: diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 093c8ae88..d6e328761 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -472,6 +472,22 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("com", &rcs::common::Payload::com) .def_readwrite("inertia", &rcs::common::Payload::inertia); + py::class_(common, "EndEffectorConfig") + .def(py::init([](const rcs::common::Pose& tcp_offset, + std::optional payload) { + return rcs::common::EndEffectorConfig{tcp_offset, payload}; + }), + py::arg("tcp_offset") = rcs::common::Pose::Identity(), + py::arg("payload") = std::nullopt) + .def_readwrite("tcp_offset", &rcs::common::EndEffectorConfig::tcp_offset, + "TCP relative to the flange (attachment site)") + .def_readwrite( + "payload", &rcs::common::EndEffectorConfig::payload, + "Mass properties after the flange for torque control. None: sim " + "uses the MJCF bodies, hardware what the robot reports (Desk). " + "Set: sim compensates gravity with it, hardware warns if Desk " + "differs."); + py::class_>( common, "PinocchioDynamics") @@ -645,14 +661,14 @@ PYBIND11_MODULE(_core, m) { const Eigen::Matrix& joint_limits, rcs::common::RobotPlatform robot_platform, - const rcs::common::Pose& tcp_offset, + const rcs::common::EndEffectorConfig& end_effector, const std::string& attachment_site, const std::string& kinematic_model_path, std::optional q_home) { rcs::common::RobotConfig config; config.robot_type = robot_type; config.robot_platform = robot_platform; - config.tcp_offset = tcp_offset; + config.end_effector = end_effector; config.attachment_site = attachment_site; config.kinematic_model_path = kinematic_model_path; config.q_home = q_home; @@ -664,7 +680,7 @@ PYBIND11_MODULE(_core, m) { py::arg("dof") = default_robot_config.dof, py::arg("joint_limits") = default_robot_config.joint_limits, py::arg("robot_platform") = default_robot_config.robot_platform, - py::arg("tcp_offset") = default_robot_config.tcp_offset, + py::arg("end_effector") = default_robot_config.end_effector, py::arg("attachment_site") = default_robot_config.attachment_site, py::arg("kinematic_model_path") = default_robot_config.kinematic_model_path, @@ -676,7 +692,7 @@ PYBIND11_MODULE(_core, m) { &rcs::common::RobotConfig::kinematic_model_path) .def_readwrite("attachment_site", &rcs::common::RobotConfig::attachment_site) - .def_readwrite("tcp_offset", &rcs::common::RobotConfig::tcp_offset) + .def_readwrite("end_effector", &rcs::common::RobotConfig::end_effector) .def_readwrite("robot_platform", &rcs::common::RobotConfig::robot_platform) .def_readwrite("q_home", &rcs::common::RobotConfig::q_home) @@ -805,60 +821,60 @@ PYBIND11_MODULE(_core, m) { rcs::sim::SimRobotConfig default_simrobot_cfg = rcs::sim::SimRobotConfig(); py::class_( sim, "SimRobotConfig") - .def( - py::init([](rcs::common::RobotType robot_type, - rcs::common::Pose tcp_offset, std::string attachment_site, - std::string kinematic_model_path, - double joint_rotational_tolerance, - double seconds_between_callbacks, bool trajectory_trace, - std::vector arm_collision_geoms, - std::vector joints, - std::optional q_home, - std::vector actuators, - std::optional> kp, - std::optional> kv, std::string base, - size_t dof, - const Eigen::Matrix& joint_limits) { - rcs::sim::SimRobotConfig config; - config.robot_type = robot_type; - config.robot_platform = rcs::common::RobotPlatform::SIMULATION; - config.tcp_offset = tcp_offset; - config.attachment_site = attachment_site; - config.kinematic_model_path = kinematic_model_path; - config.joint_rotational_tolerance = joint_rotational_tolerance; - config.seconds_between_callbacks = seconds_between_callbacks; - config.trajectory_trace = trajectory_trace; - config.arm_collision_geoms = arm_collision_geoms; - config.joints = joints; - config.actuators = actuators; - config.kp = kp; - config.kv = kv; - config.base = base; - config.dof = dof; - config.joint_limits = joint_limits; - config.q_home = q_home; - return config; - }), - py::arg("robot_type") = default_simrobot_cfg.robot_type, - py::arg("tcp_offset") = default_simrobot_cfg.tcp_offset, - py::arg("attachment_site") = default_simrobot_cfg.attachment_site, - py::arg("kinematic_model_path") = - default_simrobot_cfg.kinematic_model_path, - py::arg("joint_rotational_tolerance") = - default_simrobot_cfg.joint_rotational_tolerance, - py::arg("seconds_between_callbacks") = - default_simrobot_cfg.seconds_between_callbacks, - py::arg("trajectory_trace") = default_simrobot_cfg.trajectory_trace, - py::arg("arm_collision_geoms") = - default_simrobot_cfg.arm_collision_geoms, - py::arg("joints") = default_simrobot_cfg.joints, - py::arg("q_home") = default_simrobot_cfg.q_home, - py::arg("actuators") = default_simrobot_cfg.actuators, - py::arg("kp") = std::nullopt, py::arg("kv") = std::nullopt, - py::arg("base") = default_simrobot_cfg.base, - py::arg("dof") = default_simrobot_cfg.dof, - py::arg("joint_limits") = default_simrobot_cfg.joint_limits) + .def(py::init([](rcs::common::RobotType robot_type, + rcs::common::EndEffectorConfig end_effector, + std::string attachment_site, + std::string kinematic_model_path, + double joint_rotational_tolerance, + double seconds_between_callbacks, bool trajectory_trace, + std::vector arm_collision_geoms, + std::vector joints, + std::optional q_home, + std::vector actuators, + std::optional> kp, + std::optional> kv, std::string base, + size_t dof, + const Eigen::Matrix& joint_limits) { + rcs::sim::SimRobotConfig config; + config.robot_type = robot_type; + config.robot_platform = rcs::common::RobotPlatform::SIMULATION; + config.end_effector = end_effector; + config.attachment_site = attachment_site; + config.kinematic_model_path = kinematic_model_path; + config.joint_rotational_tolerance = joint_rotational_tolerance; + config.seconds_between_callbacks = seconds_between_callbacks; + config.trajectory_trace = trajectory_trace; + config.arm_collision_geoms = arm_collision_geoms; + config.joints = joints; + config.actuators = actuators; + config.kp = kp; + config.kv = kv; + config.base = base; + config.dof = dof; + config.joint_limits = joint_limits; + config.q_home = q_home; + return config; + }), + py::arg("robot_type") = default_simrobot_cfg.robot_type, + py::arg("end_effector") = default_simrobot_cfg.end_effector, + py::arg("attachment_site") = default_simrobot_cfg.attachment_site, + py::arg("kinematic_model_path") = + default_simrobot_cfg.kinematic_model_path, + py::arg("joint_rotational_tolerance") = + default_simrobot_cfg.joint_rotational_tolerance, + py::arg("seconds_between_callbacks") = + default_simrobot_cfg.seconds_between_callbacks, + py::arg("trajectory_trace") = default_simrobot_cfg.trajectory_trace, + py::arg("arm_collision_geoms") = + default_simrobot_cfg.arm_collision_geoms, + py::arg("joints") = default_simrobot_cfg.joints, + py::arg("q_home") = default_simrobot_cfg.q_home, + py::arg("actuators") = default_simrobot_cfg.actuators, + py::arg("kp") = std::nullopt, py::arg("kv") = std::nullopt, + py::arg("base") = default_simrobot_cfg.base, + py::arg("dof") = default_simrobot_cfg.dof, + py::arg("joint_limits") = default_simrobot_cfg.joint_limits) .def_readwrite("joint_rotational_tolerance", &rcs::sim::SimRobotConfig::joint_rotational_tolerance) @@ -877,11 +893,6 @@ PYBIND11_MODULE(_core, m) { "kv", &rcs::sim::SimRobotConfig::kv, "Per-joint velocity gains; None uses the MuJoCo XML values") .def_readwrite("base", &rcs::sim::SimRobotConfig::base) - .def_readwrite( - "payload", &rcs::sim::SimRobotConfig::payload, - "Tool as configured on the real robot, used for gravity " - "compensation under torque control; None uses the MJCF bodies " - "after the flange") .def_readwrite("dof", &rcs::sim::SimRobotConfig::dof) .def_readwrite("joint_limits", &rcs::sim::SimRobotConfig::joint_limits) .def("__copy__", diff --git a/src/sim/SimRobot.cpp b/src/sim/SimRobot.cpp index b368af2dc..a90af0e0b 100644 --- a/src/sim/SimRobot.cpp +++ b/src/sim/SimRobot.cpp @@ -117,7 +117,7 @@ bool SimRobot::set_config(const SimRobotConfig& cfg) { throw std::runtime_error("cannot switch back from torque control"); } this->cfg = cfg; - this->state.inverse_tcp_offset = cfg.tcp_offset.inverse(); + this->state.inverse_tcp_offset = cfg.end_effector.tcp_offset.inverse(); if (this->dynamics) { this->configure_dynamics(); if (cfg.controller.has_value()) { @@ -159,7 +159,7 @@ SimRobotState* SimRobot::get_state() { } common::Pose SimRobot::get_cartesian_position() { - return this->get_cartesian_flange_position() * cfg.tcp_offset; + return this->get_cartesian_flange_position() * cfg.end_effector.tcp_offset; } common::Pose SimRobot::get_cartesian_flange_position() { @@ -226,7 +226,7 @@ void SimRobot::set_cartesian_position(const common::Pose& pose) { return; } auto joint_vals = this->m_ik->inverse(pose, this->get_joint_position(), - this->cfg.tcp_offset); + this->cfg.end_effector.tcp_offset); if (joint_vals.has_value()) { this->state.ik_success = true; this->set_joint_position(joint_vals.value()); @@ -353,18 +353,18 @@ void SimRobot::install_configured_controller() { } void SimRobot::configure_dynamics() { - this->dynamics->set_tcp_offset(this->cfg.tcp_offset); + this->dynamics->set_tcp_offset(this->cfg.end_effector.tcp_offset); common::Payload simulated = this->get_simulated_payload(); // runs kinematics // gravity in the robot base frame, for robots that are mounted tilted Eigen::Map gravity_world(this->sim->m->opt.gravity); this->dynamics->set_gravity( this->get_base_pose_in_world_coordinates().rotation_m().transpose() * gravity_world); - if (!this->cfg.payload.has_value()) { + if (!this->cfg.end_effector.payload.has_value()) { this->dynamics->set_payload(simulated); return; } - const common::Payload& configured = this->cfg.payload.value(); + const common::Payload& configured = this->cfg.end_effector.payload.value(); this->dynamics->set_payload(configured); // a gap acts on the arm like a wrong tool configuration on the real robot if (std::abs(configured.mass - simulated.mass) > 0.05 || diff --git a/src/sim/SimRobot.h b/src/sim/SimRobot.h index bc1455b37..fcb5c4863 100644 --- a/src/sim/SimRobot.h +++ b/src/sim/SimRobot.h @@ -30,10 +30,6 @@ struct SimRobotConfig : common::RobotConfig { std::optional> kp; std::optional> kv; std::string base = "base"; - // Tool as configured on the real robot (for Franka: the end effector set in - // Desk), used for gravity compensation and the dynamics in torque control. - // None: the MJCF bodies attached after the flange. - std::optional payload; void add_prefix(const std::string& id) { for (auto& s : this->arm_collision_geoms) { diff --git a/src/sim/test.cpp b/src/sim/test.cpp index 42436a741..8b4c91724 100644 --- a/src/sim/test.cpp +++ b/src/sim/test.cpp @@ -129,7 +129,7 @@ int test_sim() { "attachment_site_" + id, false); auto tcp_offset = rcs::common::Pose(rcs::common::FrankaHandTCPOffset()); rcs::sim::SimRobotConfig fr3_config; - fr3_config.tcp_offset = tcp_offset; + fr3_config.end_effector.tcp_offset = tcp_offset; fr3_config.seconds_between_callbacks = 0.05; // 20hz fr3_config.add_prefix(id); auto fr3 = rcs::sim::SimRobot(sim, ik, fr3_config); From 902708faaa46a90789149c6243f10d7709cb7976 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 17:19:50 -0800 Subject: [PATCH 31/39] feat(pybind): copy and deepcopy for all bound value types rcs/PyCopy.h adds a copy constructor, __copy__ and __deepcopy__ to a bound value type, shared by the core and the rcs_fr3 bindings. The C++ part is copied with the type's copy constructor; for a Python subclass (e.g. rcs_fr3.hw.FR3Config) the copy keeps the subclass and copies its __dict__ shallow or deep. It replaces the hand-written __deepcopy__ of six configs, which returned the C++ base type. All configs and states, the robot, gripper and hand types, payload, end effector, controller and safety configs, setpoints, the linear interpolators and the safety stage are copyable. Pose and RPY keep copying through pickling. Objects that own a simulation, a robot connection or other objects (Sim, robots, grippers, controllers, kinematics, dynamics) are not copyable. --- extensions/rcs_fr3/src/pybind/rcs.cpp | 9 + .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 51 +++++ include/rcs/PyCopy.h | 60 ++++++ python/rcs/_core/common.pyi | 199 +++++++++++++++++- python/rcs/_core/sim.pyi | 93 +++++++- python/tests/test_copy.py | 108 ++++++++++ src/pybind/rcs.cpp | 118 ++++++----- 7 files changed, 576 insertions(+), 62 deletions(-) create mode 100644 include/rcs/PyCopy.h create mode 100644 python/tests/test_copy.py diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index 3374e2a42..390226b65 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -12,6 +12,7 @@ #include "rcs/Kinematics.h" #include "rcs/Pose.h" +#include "rcs/PyCopy.h" #include "rcs/Robot.h" #include "rcs/utils.h" @@ -265,4 +266,12 @@ PYBIND11_MODULE(_core, m) { hw_except, "FrankaRealtimeException", PyExc_RuntimeError); py::register_exception( hw_except, "FrankaInvalidOperationException", PyExc_RuntimeError); + + // copy support for the value types (see rcs/PyCopy.h) + rcs::common::def_copy(hw.attr("RobotState")); + rcs::common::def_copy(hw.attr("FrankaState")); + rcs::common::def_copy(hw.attr("FrankaLoad")); + rcs::common::def_copy(hw.attr("FrankaConfig")); + rcs::common::def_copy(hw.attr("FHConfig")); + rcs::common::def_copy(hw.attr("FHState")); } diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 45b21c38b..7782e5768 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -43,6 +43,9 @@ class FHConfig(rcs._core.common.GripperConfig): grasping_width: float ip: str speed: float + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, ip: str, @@ -53,9 +56,23 @@ class FHConfig(rcs._core.common.GripperConfig): epsilon_outer: float = 0.005, async_control: bool = False, ) -> None: ... + @typing.overload + def __init__(self, other: FHConfig) -> None: + """ + Copy of other. + """ class FHState(rcs._core.common.GripperState): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: FHState) -> None: + """ + Copy of other. + """ + @property def bool_state(self) -> bool: ... @property @@ -116,7 +133,15 @@ class FrankaConfig(rcs._core.common.RobotConfig): speed_factor: float timestep: float world_to_robot: rcs._core.common.Pose | None + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: FrankaConfig) -> None: + """ + Copy of other. + """ class FrankaHand(rcs._core.common.Gripper): def __init__(self, cfg: FHConfig) -> None: ... @@ -131,7 +156,15 @@ class FrankaLoad: f_x_cload: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] | None load_inertia: numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]] | None load_mass: float + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: FrankaLoad) -> None: + """ + Copy of other. + """ class IKSolver: """ @@ -207,7 +240,16 @@ class RobotMode: def value(self) -> int: ... class RobotState: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: RobotState) -> None: + """ + Copy of other. + """ + @property def EE_T_K(self) -> typing.Annotated[list[float], pybind11_stubgen.typing_ext.FixedSize(16)]: ... @property @@ -298,7 +340,16 @@ class RobotState: def theta(self) -> typing.Annotated[list[float], pybind11_stubgen.typing_ext.FixedSize(7)]: ... class FrankaState(rcs._core.common.RobotState): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: FrankaState) -> None: + """ + Copy of other. + """ + @property def robot_state(self) -> RobotState: ... diff --git a/include/rcs/PyCopy.h b/include/rcs/PyCopy.h new file mode 100644 index 000000000..1ddfe01c4 --- /dev/null +++ b/include/rcs/PyCopy.h @@ -0,0 +1,60 @@ +#ifndef RCS_PY_COPY_H +#define RCS_PY_COPY_H + +// Copy support for value types bound with pybind11 (configs, states, ...), +// shared by the core and the extension bindings. + +#include + +#include + +namespace rcs { +namespace common { + +namespace py = pybind11; + +// Copies self, an instance of the bound C++ type T or of a Python subclass of +// it (e.g. rcs_fr3.hw.FR3Config): the C++ part with T's copy constructor, the +// attributes of a Python subclass (__dict__) shallow or, with a memo, deep. +template +py::object copy_instance(py::handle self, py::object memo) { + py::handle cls = reinterpret_cast(Py_TYPE(self.ptr())); + py::object result; + if (cls.is(py::type::of())) { + result = py::cast(T(self.cast())); + } else { + result = cls.attr("__new__")(cls); + py::type::of().attr("__init__")(result, self); // the copy constructor + } + if (!memo.is_none()) { + memo[py::int_(reinterpret_cast(self.ptr()))] = result; + } + if (py::hasattr(self, "__dict__")) { + py::object attributes = self.attr("__dict__"); + if (!memo.is_none()) { + attributes = + py::module_::import("copy").attr("deepcopy")(attributes, memo); + } + result.attr("__dict__").attr("update")(attributes); + } + return result; +} + +// Adds a copy constructor, __copy__ and __deepcopy__ to the bound value type +// T, registered as py::class_ under the given handle (e.g. +// m.attr("RobotConfig")). The C++ copy is a full copy, so the shallow and the +// deep copy of the C++ part are the same. +template +void def_copy(py::handle registered) { + py::reinterpret_borrow>(registered) + .def(py::init(), py::arg("other"), "Copy of other.") + .def("__copy__", + [](py::handle self) { return copy_instance(self, py::none()); }) + .def("__deepcopy__", [](py::handle self, py::dict memo) { + return copy_instance(self, memo); + }); +} + +} // namespace common +} // namespace rcs +#endif // RCS_PY_COPY_H diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 7ef123384..291fabd75 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -72,9 +72,15 @@ class BaseCameraConfig: identifier: str resolution_height: int resolution_width: int - def __copy__(self) -> BaseCameraConfig: ... - def __deepcopy__(self, arg0: dict) -> BaseCameraConfig: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, identifier: str, frame_rate: int, resolution_width: int, resolution_height: int) -> None: ... + @typing.overload + def __init__(self, other: BaseCameraConfig) -> None: + """ + Copy of other. + """ class CartesianController: def reset(self, state: ControllerState) -> None: ... @@ -87,6 +93,13 @@ class CartesianInterpolator: def step(self, dt: float) -> CartesianSetpoint: ... class CartesianSetpoint: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + def __init__(self, other: CartesianSetpoint) -> None: + """ + Copy of other. + """ + @property def pose(self) -> Pose: ... @property @@ -101,10 +114,27 @@ class ControllerState: mass: numpy.ndarray[tuple[M, M], numpy.dtype[numpy.float64]] q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] tcp_pose: Pose + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: ControllerState) -> None: + """ + Copy of other. + """ class EndEffectorConfig: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, tcp_offset: Pose = ..., payload: Payload | None = None) -> None: ... + @typing.overload + def __init__(self, other: EndEffectorConfig) -> None: + """ + Copy of other. + """ + @property def payload(self) -> Payload | None: """ @@ -125,7 +155,15 @@ class EndEffectorConfig: class FR3JointControllerConfig: kd: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] kp: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: FR3JointControllerConfig) -> None: + """ + Copy of other. + """ class FR3OSCConfig: avoidance_weights: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] @@ -133,7 +171,15 @@ class FR3OSCConfig: kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] nullspace_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] residual_mass: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: FR3OSCConfig) -> None: + """ + Copy of other. + """ class GraspType: """ @@ -185,10 +231,26 @@ class Gripper: class GripperConfig: gripper_type: GripperType + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, gripper_type: GripperType = ...) -> None: ... + @typing.overload + def __init__(self, other: GripperConfig) -> None: + """ + Copy of other. + """ class GripperState: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: GripperState) -> None: + """ + Copy of other. + """ class GripperType: FlexivGrav: typing.ClassVar[GripperType] # value = @@ -201,9 +263,18 @@ class GripperType: Yam: typing.ClassVar[GripperType] # value = @staticmethod def get_all() -> list[GripperType]: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __hash__(self) -> int: ... + @typing.overload def __init__(self, arg0: str) -> None: ... + @typing.overload + def __init__(self, other: GripperType) -> None: + """ + Copy of other. + """ + def __repr__(self) -> str: ... @property def id(self) -> str: ... @@ -223,18 +294,43 @@ class Hand: class HandConfig: hand_type: HandType + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, hand_type: HandType = ...) -> None: ... + @typing.overload + def __init__(self, other: HandConfig) -> None: + """ + Copy of other. + """ class HandState: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: HandState) -> None: + """ + Copy of other. + """ class HandType: TilburgHand: typing.ClassVar[HandType] # value = @staticmethod def get_all() -> list[HandType]: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __hash__(self) -> int: ... + @typing.overload def __init__(self, arg0: str) -> None: ... + @typing.overload + def __init__(self, other: HandType) -> None: + """ + Copy of other. + """ + def __repr__(self) -> str: ... @property def id(self) -> str: ... @@ -256,13 +352,28 @@ class JointInterpolator: class JointPDConfig: kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], ) -> None: ... + @typing.overload + def __init__(self, other: JointPDConfig) -> None: + """ + Copy of other. + """ class JointSetpoint: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + def __init__(self, other: JointSetpoint) -> None: + """ + Copy of other. + """ + @property def dq(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... @property @@ -280,12 +391,22 @@ class OSCConfig: kp_orientation: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] nullspace_q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: OSCConfig) -> None: + """ + Copy of other. + """ class Payload: com: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] inertia: numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]] mass: float + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload @@ -295,6 +416,11 @@ class Payload: com: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]], inertia: numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]], ) -> None: ... + @typing.overload + def __init__(self, other: Payload) -> None: + """ + Copy of other. + """ class PinocchioDynamics: def __init__(self, model_path: str, urdf: bool, flange_frame: str, tcp_offset: Pose = ...) -> None: @@ -428,6 +554,9 @@ class RobotConfig(typing.Generic[M]): robot_platform: RobotPlatform robot_type: RobotType safety: SafetyConfig | None + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, robot_type: RobotType = ..., @@ -439,6 +568,11 @@ class RobotConfig(typing.Generic[M]): kinematic_model_path: str = "", q_home: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] | None = None, ) -> None: ... + @typing.overload + def __init__(self, other: RobotConfig) -> None: + """ + Copy of other. + """ class RobotPlatform: """ @@ -470,7 +604,15 @@ class RobotPlatform: def value(self) -> int: ... class RobotState: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: RobotState) -> None: + """ + Copy of other. + """ class RobotType: FR3: typing.ClassVar[RobotType] # value = @@ -482,15 +624,33 @@ class RobotType: Yam: typing.ClassVar[RobotType] # value = @staticmethod def get_all() -> list[RobotType]: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __hash__(self) -> int: ... + @typing.overload def __init__(self, arg0: str) -> None: ... + @typing.overload + def __init__(self, other: RobotType) -> None: + """ + Copy of other. + """ + def __repr__(self) -> str: ... @property def id(self) -> str: ... class RotVec: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, vec: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]]) -> None: ... + @typing.overload + def __init__(self, other: RotVec) -> None: + """ + Copy of other. + """ + def __str__(self) -> str: ... def as_quaternion_vector(self) -> numpy.ndarray[tuple[typing.Literal[4]], numpy.dtype[numpy.float64]]: ... def as_vector(self) -> numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]]: ... @@ -503,22 +663,37 @@ class SafetyConfig: joint_limit_margin: float max_torque_rate: float torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] - def __copy__(self) -> SafetyConfig: ... - def __deepcopy__(self, arg0: dict) -> SafetyConfig: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., max_torque_rate: float = ..., joint_limit_margin: float = 0.1, ) -> None: ... + @typing.overload + def __init__(self, other: SafetyConfig) -> None: + """ + Copy of other. + """ class SafetyStage: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, config: SafetyConfig, joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], timestep: float, ) -> None: ... + @typing.overload + def __init__(self, other: SafetyStage) -> None: + """ + Copy of other. + """ + def apply( self, tau: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], state: ControllerState ) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... @@ -545,7 +720,15 @@ class SafeCartesianController(CartesianController): ) -> None: ... class LinearCartesianInterpolator(CartesianInterpolator): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, duration: float) -> None: ... + @typing.overload + def __init__(self, other: LinearCartesianInterpolator) -> None: + """ + Copy of other. + """ class FR3JointController(JointController): def __init__(self, config: FR3JointControllerConfig, interpolator: JointInterpolator) -> None: ... @@ -568,7 +751,15 @@ class SafeJointController(JointController): ) -> None: ... class LinearJointInterpolator(JointInterpolator): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self, duration: float) -> None: ... + @typing.overload + def __init__(self, other: LinearJointInterpolator) -> None: + """ + Copy of other. + """ class Pin(Kinematics): def __init__( diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index eafb0c1a7..6a1eea056 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -34,6 +34,13 @@ __all__: list[str] = [ M = typing.TypeVar("M", bound=int) class CapturedState: + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + def __init__(self, other: CapturedState) -> None: + """ + Copy of other. + """ + @property def state(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... @property @@ -44,12 +51,28 @@ class DynamicJointSchema: joint_types: list[int] qpos_sizes: list[int] qvel_sizes: list[int] + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: DynamicJointSchema) -> None: + """ + Copy of other. + """ class DynamicJointState(typing.Generic[M]): qpos: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] qvel: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: DynamicJointState) -> None: + """ + Copy of other. + """ class GuiClient: def __init__(self, id: str) -> None: ... @@ -113,8 +136,9 @@ class SimConfig: realtime: bool renderer: RendererBackend timestep: float - def __copy__(self) -> SimConfig: ... - def __deepcopy__(self, arg0: dict) -> SimConfig: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, async_control: bool = False, @@ -125,6 +149,11 @@ class SimConfig: renderer: RendererBackend = ..., timestep: float = 0.001, ) -> None: ... + @typing.overload + def __init__(self, other: SimConfig) -> None: + """ + Copy of other. + """ class SimGripper(rcs._core.common.Gripper): def __init__(self, sim: Sim, cfg: SimGripperConfig) -> None: ... @@ -147,8 +176,9 @@ class SimGripperConfig(rcs._core.common.GripperConfig): min_actuator_width: float min_joint_width: float seconds_between_callbacks: float - def __copy__(self) -> SimGripperConfig: ... - def __deepcopy__(self, arg0: dict) -> SimGripperConfig: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, epsilon_inner: float = 0.005, @@ -165,10 +195,25 @@ class SimGripperConfig(rcs._core.common.GripperConfig): min_actuator_width: float = 0.0, gripper_type: rcs._core.common.GripperType = ..., ) -> None: ... + @typing.overload + def __init__(self, other: SimGripperConfig) -> None: + """ + Copy of other. + """ + def add_prefix(self, id: str) -> None: ... class SimGripperState(rcs._core.common.GripperState): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: SimGripperState) -> None: + """ + Copy of other. + """ + @property def collision(self) -> bool: ... @property @@ -202,8 +247,9 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): joints: list[str] seconds_between_callbacks: float trajectory_trace: bool - def __copy__(self) -> SimRobotConfig: ... - def __deepcopy__(self, arg0: dict) -> SimRobotConfig: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, robot_type: rcs._core.common.RobotType = ..., @@ -223,6 +269,12 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): dof: int = 0, joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]] = ..., ) -> None: ... + @typing.overload + def __init__(self, other: SimRobotConfig) -> None: + """ + Copy of other. + """ + def add_prefix(self, id: str) -> None: ... @property def kp(self) -> list[float] | None: @@ -242,7 +294,16 @@ class SimRobotConfig(rcs._core.common.RobotConfig[M]): def kv(self, arg0: list[float] | None) -> None: ... class SimRobotState(rcs._core.common.RobotState): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: SimRobotState) -> None: + """ + Copy of other. + """ + @property def collision(self) -> bool: ... @property @@ -276,8 +337,9 @@ class SimTilburgHandConfig(rcs._core.common.HandConfig): max_joint_position: numpy.ndarray[tuple[typing.Literal[16]], numpy.dtype[numpy.float64]] min_joint_position: numpy.ndarray[tuple[typing.Literal[16]], numpy.dtype[numpy.float64]] seconds_between_callbacks: float - def __copy__(self) -> SimTilburgHandConfig: ... - def __deepcopy__(self, arg0: dict) -> SimTilburgHandConfig: ... + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, grasp_type: rcs._core.common.GraspType = ..., @@ -324,10 +386,25 @@ class SimTilburgHandConfig(rcs._core.common.HandConfig): max_joint_position: numpy.ndarray[tuple[typing.Literal[16]], numpy.dtype[numpy.float64]] = ..., min_joint_position: numpy.ndarray[tuple[typing.Literal[16]], numpy.dtype[numpy.float64]] = ..., ) -> None: ... + @typing.overload + def __init__(self, other: SimTilburgHandConfig) -> None: + """ + Copy of other. + """ + def add_prefix(self, id: str) -> None: ... class SimTilburgHandState(rcs._core.common.HandState): + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__(self) -> None: ... + @typing.overload + def __init__(self, other: SimTilburgHandState) -> None: + """ + Copy of other. + """ + @property def collision(self) -> bool: ... @property diff --git a/python/tests/test_copy.py b/python/tests/test_copy.py new file mode 100644 index 000000000..18dcf08fa --- /dev/null +++ b/python/tests/test_copy.py @@ -0,0 +1,108 @@ +"""The bound value types (configs, states, ...) can be copied and deep-copied, +also as Python subclasses.""" + +import copy + +import numpy as np +import pytest +from test_sim_torque_control import Setup + +import rcs +from rcs import common, sim + + +def joint_setpoint() -> common.JointSetpoint: + interpolator = common.LinearJointInterpolator(0.05) + interpolator.reset(np.zeros(7)) + return interpolator.step(0.001) + + +def cartesian_setpoint() -> common.CartesianSetpoint: + interpolator = common.LinearCartesianInterpolator(0.05) + interpolator.reset(common.Pose()) + return interpolator.step(0.001) + + +VALUES = { + "BaseCameraConfig": lambda: common.BaseCameraConfig("cam", 30, 640, 480), + "RotVec": lambda: common.RotVec(np.array([0.1, 0.2, 0.3])), + "Pose": lambda: common.Pose(translation=np.array([0.1, 0.2, 0.3])), + "RPY": lambda: common.RPY(0.1, 0.2, 0.3), + "JointSetpoint": lambda: joint_setpoint(), + "CartesianSetpoint": lambda: cartesian_setpoint(), + "ControllerState": common.ControllerState, + "Payload": lambda: common.Payload(mass=0.9, com=np.zeros(3), inertia=np.eye(3)), + "EndEffectorConfig": common.EndEffectorConfig, + "OSCConfig": common.OSCConfig, + "JointPDConfig": lambda: common.JointPDConfig(kp=np.ones(7), kd=np.ones(7)), + "FR3JointControllerConfig": common.FR3JointControllerConfig, + "FR3OSCConfig": common.FR3OSCConfig, + "SafetyConfig": lambda: common.SafetyConfig(torque_limit=np.ones(7)), + "SafetyStage": lambda: common.SafetyStage(common.SafetyConfig(), np.zeros((2, 7)), 0.001), + "LinearJointInterpolator": lambda: common.LinearJointInterpolator(0.05), + "LinearCartesianInterpolator": lambda: common.LinearCartesianInterpolator(0.05), + "RobotType": lambda: common.RobotType.FR3, + "GripperType": lambda: common.GripperType.FrankaHand, + "RobotConfig": lambda: rcs.ROBOTS[common.RobotType.FR3].apply(common.RobotConfig()), + "RobotState": common.RobotState, + "GripperConfig": common.GripperConfig, + "GripperState": common.GripperState, + "HandConfig": common.HandConfig, + "HandState": common.HandState, + "SimRobotConfig": lambda: rcs.ROBOTS[common.RobotType.FR3].apply(sim.SimRobotConfig()), + "SimGripperConfig": sim.SimGripperConfig, + "SimConfig": lambda: sim.SimConfig(frequency=20), + "SimTilburgHandConfig": sim.SimTilburgHandConfig, +} + + +@pytest.mark.parametrize("name", list(VALUES)) +@pytest.mark.parametrize("copier", [copy.copy, copy.deepcopy]) +def test_value_types_can_be_copied(name, copier): + value = VALUES[name]() + copied = copier(value) + assert type(copied) is type(value) + assert copied is not value + + +def test_a_copy_is_independent(): + cfg = rcs.ROBOTS[common.RobotType.FR3].apply(sim.SimRobotConfig()) + cfg.controller = common.FR3OSCConfig() + copied = copy.deepcopy(cfg) + copied.joint_limits = np.zeros((2, 7)) + copied.end_effector.tcp_offset = common.Pose(translation=np.array([0.0, 0.0, 0.2])) + np.testing.assert_allclose(cfg.joint_limits, rcs.ROBOTS[common.RobotType.FR3].joint_limits) + np.testing.assert_allclose(cfg.end_effector.tcp_offset.translation(), 0.0) + assert type(copied.controller) is common.FR3OSCConfig + + +def test_sim_states_can_be_copied(): + setup = Setup() + state = setup.robot.get_state() + assert type(copy.deepcopy(state)) is type(state) + + +def test_a_python_subclass_keeps_its_type_and_attributes(): + class ToolConfig(sim.SimRobotConfig): + def __init__(self): + super().__init__() + rcs.ROBOTS[common.RobotType.FR3].apply(self) + self.note = ["camera on the wrist"] + + cfg = ToolConfig() + deep = copy.deepcopy(cfg) + assert type(deep) is ToolConfig + assert deep.dof == 7 + assert deep.note == cfg.note + assert deep.note is not cfg.note + assert copy.copy(cfg).note is cfg.note + + +def test_fr3_config_can_be_copied(): + hw = pytest.importorskip("rcs_fr3.hw") + cfg = hw.FR3Config(ip="192.168.1.11", async_control=True) + copied = copy.deepcopy(cfg) + assert type(copied) is hw.FR3Config + assert copied.ip == "192.168.1.11" + assert copied.async_control + assert copied.safety is not None diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index d6e328761..66a6f4e4a 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -20,6 +20,7 @@ #include "rcs/LinearInterpolator.h" #include "rcs/PinocchioDynamics.h" #include "rcs/Pose.h" +#include "rcs/PyCopy.h" #include "rcs/Robot.h" #include "rcs/utils.h" @@ -284,15 +285,7 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("resolution_width", &rcs::common::BaseCameraConfig::resolution_width) .def_readwrite("resolution_height", - &rcs::common::BaseCameraConfig::resolution_height) - .def("__copy__", - [](const rcs::common::BaseCameraConfig& self) { - return rcs::common::BaseCameraConfig(self); - }) - .def("__deepcopy__", - [](const rcs::common::BaseCameraConfig& self, py::dict) { - return rcs::common::BaseCameraConfig(self); - }); + &rcs::common::BaseCameraConfig::resolution_height); py::class_(common, "RPY") .def(py::init(), py::arg("roll") = 0.0, py::arg("pitch") = 0.0, py::arg("yaw") = 0.0) @@ -605,14 +598,7 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("max_torque_rate", &rcs::common::SafetyConfig::max_torque_rate) .def_readwrite("joint_limit_margin", - &rcs::common::SafetyConfig::joint_limit_margin) - .def("__copy__", - [](const rcs::common::SafetyConfig& self) { - return rcs::common::SafetyConfig(self); - }) - .def("__deepcopy__", [](const rcs::common::SafetyConfig& self, py::dict) { - return rcs::common::SafetyConfig(self); - }); + &rcs::common::SafetyConfig::joint_limit_margin); py::class_(common, "SafetyStage") .def(py::init(sim, "SimRobotState") @@ -988,14 +966,6 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("min_actuator_width", &rcs::sim::SimGripperConfig::min_actuator_width) .def_readwrite("gripper_type", &rcs::sim::SimGripperConfig::gripper_type) - .def("__copy__", - [](const rcs::sim::SimGripperConfig& self) { - return rcs::sim::SimGripperConfig(self); - }) - .def("__deepcopy__", - [](const rcs::sim::SimGripperConfig& self, py::dict) { - return rcs::sim::SimGripperConfig(self); - }) .def("add_prefix", &rcs::sim::SimGripperConfig::add_prefix, py::arg("id")); py::class_( @@ -1042,14 +1012,7 @@ PYBIND11_MODULE(_core, m) { &rcs::sim::SimConfig::max_convergence_steps) .def_readwrite("memory", &rcs::sim::SimConfig::memory) .def_readwrite("renderer", &rcs::sim::SimConfig::renderer) - .def_readwrite("timestep", &rcs::sim::SimConfig::timestep) - .def("__copy__", - [](const rcs::sim::SimConfig& self) { - return rcs::sim::SimConfig(self); - }) - .def("__deepcopy__", [](const rcs::sim::SimConfig& self, py::dict) { - return rcs::sim::SimConfig(self); - }); + .def_readwrite("timestep", &rcs::sim::SimConfig::timestep); py::class_(sim, "DynamicJointSchema") .def(py::init<>()) @@ -1191,15 +1154,7 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("seconds_between_callbacks", &rcs::sim::SimTilburgHandConfig::seconds_between_callbacks) .def("add_prefix", &rcs::sim::SimTilburgHandConfig::add_prefix, - py::arg("id")) - .def("__copy__", - [](const rcs::sim::SimTilburgHandConfig& self) { - return rcs::sim::SimTilburgHandConfig(self); - }) - .def("__deepcopy__", - [](const rcs::sim::SimTilburgHandConfig& self, py::dict) { - return rcs::sim::SimTilburgHandConfig(self); - }); + py::arg("id")); // SimTilburgHand py::class_>(sim, "SimTilburgHand") @@ -1224,4 +1179,67 @@ PYBIND11_MODULE(_core, m) { self.set_model_and_data((mjModel*)m, (mjData*)d); }) .def("sync", &rcs::sim::GuiClient::sync); + + // copy support (copy constructor, __copy__, __deepcopy__) for the value + // types; Pose and RPY copy through pickling. Objects that own a simulation, + // a robot connection or other objects (Sim, robots, grippers, controllers, + // kinematics, dynamics) are not copyable. + rcs::common::def_copy( + common.attr("BaseCameraConfig")); + rcs::common::def_copy(common.attr("RotVec")); + rcs::common::def_copy( + common.attr("JointSetpoint")); + rcs::common::def_copy( + common.attr("CartesianSetpoint")); + rcs::common::def_copy( + common.attr("ControllerState")); + rcs::common::def_copy(common.attr("Payload")); + rcs::common::def_copy( + common.attr("EndEffectorConfig")); + rcs::common::def_copy(common.attr("OSCConfig")); + rcs::common::def_copy( + common.attr("JointPDConfig")); + rcs::common::def_copy( + common.attr("FR3JointControllerConfig")); + rcs::common::def_copy(common.attr("FR3OSCConfig")); + rcs::common::def_copy(common.attr("SafetyConfig")); + rcs::common::def_copy(common.attr("SafetyStage")); + rcs::common::def_copy(common.attr("RobotType")); + rcs::common::def_copy(common.attr("GripperType")); + rcs::common::def_copy(common.attr("HandType")); + rcs::common::def_copy(common.attr("RobotConfig")); + rcs::common::def_copy(common.attr("RobotState")); + rcs::common::def_copy( + common.attr("GripperConfig")); + rcs::common::def_copy(common.attr("GripperState")); + rcs::common::def_copy(common.attr("HandConfig")); + rcs::common::def_copy(common.attr("HandState")); + rcs::common::def_copy>( + common.attr("LinearJointInterpolator")); + rcs::common::def_copy< + rcs::common::LinearCartesianInterpolator, + rcs::common::CartesianInterpolator, + std::shared_ptr>( + common.attr("LinearCartesianInterpolator")); + rcs::common::def_copy( + sim.attr("SimRobotConfig")); + rcs::common::def_copy( + sim.attr("SimRobotState")); + rcs::common::def_copy( + sim.attr("SimGripperConfig")); + rcs::common::def_copy( + sim.attr("SimGripperState")); + rcs::common::def_copy(sim.attr("SimConfig")); + rcs::common::def_copy( + sim.attr("DynamicJointSchema")); + rcs::common::def_copy( + sim.attr("DynamicJointState")); + rcs::common::def_copy(sim.attr("CapturedState")); + rcs::common::def_copy( + sim.attr("SimTilburgHandState")); + rcs::common::def_copy( + sim.attr("SimTilburgHandConfig")); } From 40aff3222859aa0e047c9f7285755ab689e075d5 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 19:01:33 -0800 Subject: [PATCH 32/39] fix(fr3): rcs_fr3.hw and rcs_panda.hw re-export every class of the C++ module The explicit list missed classes added later (ControlStateBuffer). --- extensions/rcs_fr3/src/rcs_fr3/hw.py | 31 +++--------------------- extensions/rcs_panda/src/rcs_panda/hw.py | 31 +++--------------------- 2 files changed, 8 insertions(+), 54 deletions(-) diff --git a/extensions/rcs_fr3/src/rcs_fr3/hw.py b/extensions/rcs_fr3/src/rcs_fr3/hw.py index 1809efcb1..50ca18208 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/hw.py +++ b/extensions/rcs_fr3/src/rcs_fr3/hw.py @@ -7,19 +7,9 @@ from typing import Any -from rcs_fr3._core.hw import ( - FHConfig, - FHState, - Franka, - FrankaConfig, - FrankaHand, - FrankaLoad, - FrankaState, - IKSolver, - RobotMode, - RobotState, - exceptions, -) +from rcs_fr3._core import hw as _core_hw +from rcs_fr3._core.hw import * # noqa: F403 (all classes of the C++ module) +from rcs_fr3._core.hw import FrankaConfig import rcs from rcs import common @@ -43,17 +33,4 @@ def __init__(self, ip: str, **kwargs: Any): setattr(self, key, value) -__all__ = [ - "FHConfig", - "FHState", - "Franka", - "FrankaConfig", - "FrankaHand", - "FrankaLoad", - "FrankaState", - "FR3Config", - "IKSolver", - "RobotMode", - "RobotState", - "exceptions", -] +__all__ = [name for name in dir(_core_hw) if not name.startswith("_")] + ["FR3Config"] diff --git a/extensions/rcs_panda/src/rcs_panda/hw.py b/extensions/rcs_panda/src/rcs_panda/hw.py index b988f947b..5a77c1969 100644 --- a/extensions/rcs_panda/src/rcs_panda/hw.py +++ b/extensions/rcs_panda/src/rcs_panda/hw.py @@ -7,19 +7,9 @@ from typing import Any -from rcs_panda._core.hw import ( - FHConfig, - FHState, - Franka, - FrankaConfig, - FrankaHand, - FrankaLoad, - FrankaState, - IKSolver, - RobotMode, - RobotState, - exceptions, -) +from rcs_panda._core import hw as _core_hw +from rcs_panda._core.hw import * # noqa: F403 (all classes of the C++ module) +from rcs_panda._core.hw import FrankaConfig import rcs from rcs import common @@ -43,17 +33,4 @@ def __init__(self, ip: str, **kwargs: Any): setattr(self, key, value) -__all__ = [ - "FHConfig", - "FHState", - "Franka", - "FrankaConfig", - "FrankaHand", - "FrankaLoad", - "FrankaState", - "PandaConfig", - "IKSolver", - "RobotMode", - "RobotState", - "exceptions", -] +__all__ = [name for name in dir(_core_hw) if not name.startswith("_")] + ["PandaConfig"] From 59ba0dd1bac7e4fa65832a2c5fe04181d0b69d34 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 19:02:05 -0800 Subject: [PATCH 33/39] docs(fr3): the default controllers have no gains in FrankaConfig anymore --- extensions/rcs_fr3/src/hw/Franka.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index afa8efa84..1dcb160f0 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -89,9 +89,10 @@ class Franka : public common::Robot { double controller_time = 0.0; // The shared torque controllers (core), stepped in the libfranka control // loop: RobotConfig::controller, or without it FR3JointController and - // FR3OSC with the gains below. They are created when a controller thread - // starts, so the gains and the interpolation window (1 / policy_rate) stay - // fixed for its lifetime. + // FR3OSC with their default configs, behind the SafetyStage of + // RobotConfig::safety. They are created when a controller thread starts, so + // the gains and the interpolation window (1 / policy_rate) stay fixed for + // its lifetime. std::shared_ptr dynamics; std::shared_ptr torque_joint_controller; std::shared_ptr torque_cartesian_controller; From 00f7a97272073da8efd91b5e207ea0bf28824382 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 20:12:52 -0800 Subject: [PATCH 34/39] refactor(control): no null-space joint-limit avoidance in the FR3 OSC The FR3 OSC (from deoxys' osc_impedance) pushed a joint away from a limit in the null space within 0.1-0.25 rad of it, with a torque of w*d that starts with a step at 0.25 rad and shrinks towards the limit. Together with the 0.1 rad torque cut it made poses close to the base unreachable under control. Joint limits are handled in joint space by the safety stage instead; FR3OSC no longer takes the joint limits and FR3OSCConfig.avoidance_weights is gone. --- include/rcs/FR3Controllers.h | 11 +++-------- python/rcs/_core/common.pyi | 8 +------- python/tests/test_fr3_controllers.py | 4 ++-- src/pybind/rcs.cpp | 10 ++++------ src/rcs/ControllerConfig.cpp | 2 +- src/rcs/FR3Controllers.cpp | 24 +----------------------- 6 files changed, 12 insertions(+), 47 deletions(-) diff --git a/include/rcs/FR3Controllers.h b/include/rcs/FR3Controllers.h index 5c53a17eb..46603ac3f 100644 --- a/include/rcs/FR3Controllers.h +++ b/include/rcs/FR3Controllers.h @@ -60,21 +60,17 @@ struct FR3OSCConfig { // added to the diagonal of the mass matrix Vector7d residual_mass = (Vector7d() << 0.0, 0.0, 0.0, 0.0, 0.1, 0.5, 0.5).finished(); - // null-space push away from joints that are 0.1 to 0.25 rad from a limit - Vector7d avoidance_weights = - (Vector7d() << 1.0, 1.0, 1.0, 1.0, 1.0, 10.0, 10.0).finished(); }; // Decoupled operational-space control as on the FR3 (deoxys): separate // position and orientation task inertias, damping on the TCP velocity only, // orientation error from the quaternion vector part, small errors cut off, -// posture and joint-limit avoidance in the null space. The joint limits are -// the robot's (RobotConfig::joint_limits), for the avoidance. +// posture in the null space. Unlike deoxys, no joint-limit avoidance in the +// null space: joint limits are the joint-space guard of the SafetyStage. class FR3OSC : public CartesianController { public: FR3OSC(const FR3OSCConfig& config, - std::shared_ptr interpolator, - const JointLimits& joint_limits); + std::shared_ptr interpolator); void reset(const ControllerState& state) override; void set_goal(const Pose& pose_goal, std::optional duration = std::nullopt) override; @@ -83,7 +79,6 @@ class FR3OSC : public CartesianController { private: FR3OSCConfig config; std::shared_ptr interpolator; - Vector7d joint_min, joint_max; }; } // namespace common diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 291fabd75..a2f9cf3b9 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -166,7 +166,6 @@ class FR3JointControllerConfig: """ class FR3OSCConfig: - avoidance_weights: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] kp_orientation: float kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] nullspace_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] @@ -700,12 +699,7 @@ class SafetyStage: def reset(self, state: ControllerState) -> None: ... class FR3OSC(CartesianController): - def __init__( - self, - config: FR3OSCConfig, - interpolator: CartesianInterpolator, - joint_limits: numpy.ndarray[tuple[typing.Literal[2], M], numpy.dtype[numpy.float64]], - ) -> None: ... + def __init__(self, config: FR3OSCConfig, interpolator: CartesianInterpolator) -> None: ... class OSC(CartesianController): def __init__(self, config: OSCConfig, interpolator: CartesianInterpolator) -> None: ... diff --git a/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py index 2092e9bf6..abaf6357e 100644 --- a/python/tests/test_fr3_controllers.py +++ b/python/tests/test_fr3_controllers.py @@ -34,7 +34,7 @@ def osc(state, safety=True, **config) -> common.CartesianController: cfg = common.FR3OSCConfig() for key, value in config.items(): setattr(cfg, key, value) - controller = common.FR3OSC(cfg, common.LinearCartesianInterpolator(0.05), JOINT_LIMITS) + controller = common.FR3OSC(cfg, common.LinearCartesianInterpolator(0.05)) if safety: controller = common.SafeCartesianController(controller, SAFETY, JOINT_LIMITS, DT) controller.reset(state) @@ -138,7 +138,7 @@ def test_fr3_controllers_in_sim(controller): q_home = setup.robot.get_joint_position() setup.robot.set_cartesian_controller( common.SafeCartesianController( - common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05), JOINT_LIMITS), + common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05)), SAFETY, JOINT_LIMITS, DT, diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 66a6f4e4a..64b54961a 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -572,16 +572,14 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("kp_orientation", &rcs::common::FR3OSCConfig::kp_orientation) .def_readwrite("nullspace_q", &rcs::common::FR3OSCConfig::nullspace_q) - .def_readwrite("residual_mass", &rcs::common::FR3OSCConfig::residual_mass) - .def_readwrite("avoidance_weights", - &rcs::common::FR3OSCConfig::avoidance_weights); + .def_readwrite("residual_mass", + &rcs::common::FR3OSCConfig::residual_mass); py::class_>(common, "FR3OSC") .def(py::init, - const rcs::common::JointLimits&>(), - py::arg("config"), py::arg("interpolator"), py::arg("joint_limits")); + std::shared_ptr>(), + py::arg("config"), py::arg("interpolator")); rcs::common::SafetyConfig default_safety_config; py::class_(common, "SafetyConfig") diff --git a/src/rcs/ControllerConfig.cpp b/src/rcs/ControllerConfig.cpp index 6634c7b2d..f70d679a1 100644 --- a/src/rcs/ControllerConfig.cpp +++ b/src/rcs/ControllerConfig.cpp @@ -32,7 +32,7 @@ ControllerPair make_controller(const ControllerConfig& config, std::make_shared(*c, joint_interpolator()); } else if (auto* c = std::get_if(&config)) { controller.cartesian = - std::make_shared(*c, cartesian_interpolator(), joint_limits); + std::make_shared(*c, cartesian_interpolator()); } if (safety.has_value()) { if (controller.joint) { diff --git a/src/rcs/FR3Controllers.cpp b/src/rcs/FR3Controllers.cpp index 0b52af2f6..5ce217b70 100644 --- a/src/rcs/FR3Controllers.cpp +++ b/src/rcs/FR3Controllers.cpp @@ -29,12 +29,6 @@ void check_seven_joints(const ControllerState& state) { } } -void check_joint_limits(const JointLimits& joint_limits) { - if (joint_limits.cols() != 7) { - throw std::invalid_argument("FR3 controllers need the limits of 7 joints"); - } -} - } // namespace FR3JointController::FR3JointController( @@ -69,12 +63,8 @@ VectorXd FR3JointController::step(const ControllerState& state) { } FR3OSC::FR3OSC(const FR3OSCConfig& config, - std::shared_ptr interpolator, - const JointLimits& joint_limits) + std::shared_ptr interpolator) : config(config), interpolator(std::move(interpolator)) { - check_joint_limits(joint_limits); - this->joint_min = joint_limits.row(0).transpose(); - this->joint_max = joint_limits.row(1).transpose(); if (!this->interpolator) { throw std::invalid_argument("interpolator must not be null"); } @@ -146,18 +136,6 @@ VectorXd FR3OSC::step(const ControllerState& state) { // posture in the null space tau += Nullspace * (cfg.nullspace_q - q); - // joint-limit avoidance in the null space - Vector7d avoidance = Vector7d::Zero(); - for (int i = 0; i < 7; i++) { - double to_max = this->joint_max[i] - q[i]; - double to_min = q[i] - this->joint_min[i]; - if (to_max < 0.25 && to_max > 0.1) - avoidance[i] += -cfg.avoidance_weights[i] * to_max; - if (to_min < 0.25 && to_min > 0.1) - avoidance[i] += cfg.avoidance_weights[i] * to_min; - } - tau += Nullspace * avoidance; - tau += state.coriolis; return tau; } From b5493f58b360782cb37144d206782fb0a95002dc Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 20:12:52 -0800 Subject: [PATCH 35/39] feat(control): joint-limit guard from the robot's velocity limits The safety stage's 0.1 rad torque cut is replaced by a guard in joint space, per joint, based on the position based velocity limits v(d) = min(v_max, sqrt(2 a d) - c), which reach zero at d0 = c^2/2a in front of a limit: - a damper on the velocity towards a limit above 80% of v(d); slower motion and motion away from a limit are not affected, - in the last spring_range (0.05 rad) in front of d0 the controller's torque towards the limit fades out and a spring pushes back, like the soft end stop of guiding mode. rcs.ROBOTS holds the parameters: for the FR3 deceleration_limit and velocity_offset from the URDF the robots report (as libfranka's getUpperJointVelocityLimits, d0 = 0.006-0.035 rad), for the Panda the plain sqrt(2 a d); damping 100 / 20 Nm s/rad, spring 10 / 3 Nm. In sim a joint goal 0.15 rad beyond the lower limit of joint 4 stops the joint 0.024-0.033 rad in front of it, also when streamed fast; without the guard it runs into the limit. --- docs/development/controller_interface.md | 4 +- include/rcs/SafetyStage.h | 33 +++++++++++-- python/rcs/__init__.py | 36 +++++++++++++- python/rcs/_core/common.pyi | 16 +++++- python/tests/test_fr3_controllers.py | 40 +++++++++------ python/tests/test_safety_stage.py | 60 +++++++++++++++++++--- src/pybind/rcs.cpp | 35 ++++++++++--- src/rcs/SafetyStage.cpp | 63 +++++++++++++++++++++--- 8 files changed, 240 insertions(+), 47 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 3d110fb47..15c92564d 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -187,8 +187,8 @@ class PinocchioDynamics { | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | | `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | -| `SafetyStage`, `SafeJointController`, `SafeCartesianController` | core | The safety stage of `Franka.cpp` for any robot and controller, configured by `RobotConfig::safety` (`SafetyConfig`: torque limit, torque rate limit, joint-limit margin). In this order: no torque towards a joint limit closer than the margin, the rate limit per step of the nominal control period (as `franka::limitRate`, which limits per command assuming 1 ms, so the measured `dt` is not used), the clip. It keeps its own previous output instead of `tau_J_d`. `make_controller` wraps the configured controller with it, so sim and hardware run the same code. `rcs.ROBOTS` holds the values (FR3 and Panda: 87/12 Nm, 999.999 Nm/s), `apply()` sets them. `Franka` refuses async (torque) control without it; in sim it is used when set, which the FR3 scenes do. | -| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas: Coriolis feed-forward, residual mass, null-space posture, joint-limit avoidance, deadband. The safety stage at the end of both loops (joint-limit guard, torque rate limit, torque clip) is the `SafetyStage` (see below), which applies to any controller. The joint-limit avoidance uses the robot's `RobotConfig::joint_limits`, passed to the constructor, instead of the values hard coded in `Franka.cpp` (which were the Panda limits). `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. `FR3Config` and `PandaConfig` are therefore Python classes (`rcs_fr3.hw`, `rcs_panda.hw`) that subclass the C++ `FrankaConfig` and call `apply()` in their constructor. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | +| `SafetyStage`, `SafeJointController`, `SafeCartesianController` | core | The safety stage of `Franka.cpp` for any robot and controller, configured by `RobotConfig::safety` (`SafetyConfig`: torque limit, torque rate limit, joint-limit guard). In this order: the joint-limit guard, the rate limit per step of the nominal control period (as `franka::limitRate`, which limits per command assuming 1 ms, so the measured `dt` is not used), the clip. It keeps its own previous output instead of `tau_J_d`. `make_controller` wraps the configured controller with it, so sim and hardware run the same code. `rcs.ROBOTS` holds the values (FR3 and Panda: 87/12 Nm, 999.999 Nm/s), `apply()` sets them. `Franka` refuses async (torque) control without it; in sim it is used when set, which the FR3 scenes do. The joint-limit guard works in joint space, per joint, from the robot's position based velocity limits `v(d) = min(v_max, sqrt(2 a d) - c)` (FR3: `deceleration_limit` and `velocity_offset` from the URDF the robot reports, as libfranka's `getUpperJointVelocityLimits`; Panda: `c = 0`), which reach zero at `d0 = c²/2a` in front of the limit (FR3: 0.006-0.035 rad): a damper on the velocity towards a limit above 80% of `v(d)` (100 / 20 Nm s/rad), and in the last 0.05 rad in front of `d0` the controller's torque towards the limit fades out while a spring pushes back (10 / 3 Nm at `d0`), like the soft end stop in guiding mode. Slow motion can reach the limit up to the spring zone, motion away from a limit is never affected. In sim a joint goal 0.15 rad beyond the lower limit of joint 4 stops the joint 0.024-0.033 rad in front of it, also when streamed fast (without the guard it hits the limit). | +| `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas (deoxys): Coriolis feed-forward, residual mass, null-space posture, deadband. Two parts of the original are not in them: the safety stage at the end of both loops (joint-limit cut, torque rate limit, torque clip), which is the `SafetyStage` (see below) for any controller, and deoxys' null-space joint-limit avoidance (a push of `w·d` in the band 0.1-0.25 rad from a limit, which starts with a step and blocked the area close to the base together with the 0.1 rad cut); joint limits are handled in joint space by the `SafetyStage`. `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. `FR3Config` and `PandaConfig` are therefore Python classes (`rcs_fr3.hw`, `rcs_panda.hw`) that subclass the C++ `FrankaConfig` and call `apply()` in their constructor. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | ## Backends diff --git a/include/rcs/SafetyStage.h b/include/rcs/SafetyStage.h index ed9f1aaa2..ed424a42a 100644 --- a/include/rcs/SafetyStage.h +++ b/include/rcs/SafetyStage.h @@ -19,13 +19,36 @@ struct SafetyConfig { VectorXd torque_limit; // per-joint torque rate limit in Nm/s (franka::limitRate on the FR3) double max_torque_rate = std::numeric_limits::infinity(); - // no torque that pushes a joint closer than this to its limit (rad) - double joint_limit_margin = 0.1; + + // Joint-limit guard, in joint space, per joint (an empty vector switches + // that part off). The velocity allowed towards a limit at distance d is + // v(d) = min(max_velocity, max(0, sqrt(2 deceleration d) - + // velocity_offset)) + // as Franka's position based velocity limits (the robot's URDF has the + // parameters); velocity_offset empty means 0, the plain sqrt(2 a d). v is + // zero at d0 = velocity_offset^2 / (2 deceleration), the zero-velocity + // point in front of the limit. + VectorXd max_velocity; + VectorXd deceleration; + VectorXd velocity_offset; + // damper: damping (Nm s/rad) on the velocity towards a limit above + // velocity_margin * v(d); slower motion and motion away from a limit are + // not affected + VectorXd limit_damping; + double velocity_margin = 0.8; + // spring: torque away from a limit, growing from 0 at spring_range (rad) in + // front of the zero-velocity point to spring_torque (Nm) at it; over the + // same zone the controller's torque towards the limit fades out to 0, so + // that no controller can push a joint past the zero-velocity point + VectorXd spring_torque; + double spring_range = 0.05; }; -// The safety stage of Franka.cpp, for any robot and controller. In this order: -// 1. joint-limit guard: a joint closer than joint_limit_margin to a limit gets -// no torque towards it, +// Limits on the torques of any robot and controller. In this order: +// 1. joint-limit guard (see SafetyConfig): the damper slows a joint that +// approaches a limit faster than allowed there; in a small zone in front of +// the limit the controller's torque towards it fades out and a spring +// pushes back, like a soft end stop, // 2. rate limit: each joint torque changes by at most // max_torque_rate * timestep from the previous output per step (starting // from zero after reset). timestep is the nominal period of the control diff --git a/python/rcs/__init__.py b/python/rcs/__init__.py index 7d7e00f76..ae728e0c2 100644 --- a/python/rcs/__init__.py +++ b/python/rcs/__init__.py @@ -139,6 +139,15 @@ class RobotMetaConfig: """joint torque limits in Nm for the safety stage of torque controllers, shape (N,), None: no safety stage""" max_torque_rate: float = float("inf") """joint torque rate limit in Nm/s for the safety stage""" + max_joint_velocity: np.ndarray | None = None + """joint-limit guard of the safety stage (see common.SafetyConfig): allowed velocity towards a limit at distance + d is min(max_joint_velocity, sqrt(2 joint_deceleration d) - joint_velocity_offset), shape (N,)""" + joint_deceleration: np.ndarray | None = None + joint_velocity_offset: np.ndarray | None = None + limit_damping: np.ndarray | None = None + """Nm s/rad on the velocity towards a limit above 80% of the allowed one, None: no damper""" + limit_spring_torque: np.ndarray | None = None + """Nm of the soft end stop at the zero-velocity point in front of each limit, None: no spring""" def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: """Sets the robot specific fields of cfg (type, model, IK site, dof, joint limits, home pose, safety). @@ -151,8 +160,19 @@ def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: cfg.dof = self.dof cfg.joint_limits = self.joint_limits.copy() cfg.q_home = self.q_home.copy() + def array(value: np.ndarray | None) -> np.ndarray: + return np.empty(0) if value is None else np.asarray(value, dtype=np.float64).copy() + cfg.safety = ( - common.SafetyConfig(torque_limit=self.torque_limit.copy(), max_torque_rate=self.max_torque_rate) + common.SafetyConfig( + torque_limit=array(self.torque_limit), + max_torque_rate=self.max_torque_rate, + max_velocity=array(self.max_joint_velocity), + deceleration=array(self.joint_deceleration), + velocity_offset=array(self.joint_velocity_offset), + limit_damping=array(self.limit_damping), + spring_torque=array(self.limit_spring_torque), + ) if self.torque_limit is not None else None ) @@ -174,6 +194,14 @@ def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: # Franka robot specification; the rate limit is franka::limitRate (kMaxTorqueRate - kLimitEps) torque_limit=np.array([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0]), max_torque_rate=1000.0 - 1e-3, + # position based velocity limits from the URDF the FR3s report (velocity, deceleration_limit and + # velocity_offset of position_based_velocity_limits), as libfranka's getUpperJointVelocityLimits + max_joint_velocity=np.array([2.62, 2.62, 2.62, 2.62, 5.26, 4.18, 5.26]), + joint_deceleration=np.array([6.0, 2.585, 3.5, 4.0, 17.0, 5.5, 17.0]), + joint_velocity_offset=np.array([0.652, 0.25, 0.2005, 0.3542, 0.5738, 0.4885, 0.4592]), + # enough to brake a fast approach of the arm before the limit in sim, see test_safety_stage.py + limit_damping=np.array([100.0, 100.0, 100.0, 100.0, 20.0, 20.0, 20.0]), + limit_spring_torque=np.array([10.0, 10.0, 10.0, 10.0, 3.0, 3.0, 3.0]), ), common.RobotType.Panda: RobotMetaConfig( robot_type=common.RobotType.Panda, @@ -205,6 +233,12 @@ def apply(self, cfg: common.RobotConfig) -> common.RobotConfig: # Franka robot specification; the rate limit is franka::limitRate (kMaxTorqueRate - kLimitEps) torque_limit=np.array([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0]), max_torque_rate=1000.0 - 1e-3, + # no position based velocity limits: the plain sqrt(2 a d) with the specified velocity and acceleration + max_joint_velocity=np.array([2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]), + joint_deceleration=np.array([15.0, 7.5, 10.0, 12.5, 15.0, 20.0, 20.0]), + # enough to brake a fast approach of the arm before the limit in sim, see test_safety_stage.py + limit_damping=np.array([100.0, 100.0, 100.0, 100.0, 20.0, 20.0, 20.0]), + limit_spring_torque=np.array([10.0, 10.0, 10.0, 10.0, 3.0, 3.0, 3.0]), ), common.RobotType.XArm7: RobotMetaConfig( robot_type=common.RobotType.XArm7, diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index a2f9cf3b9..4c16174a0 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -659,9 +659,15 @@ class RotVec: ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... class SafetyConfig: - joint_limit_margin: float + deceleration: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + limit_damping: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] max_torque_rate: float + max_velocity: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + spring_range: float + spring_torque: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + velocity_margin: float + velocity_offset: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] def __copy__(self) -> typing.Any: ... def __deepcopy__(self, arg0: dict) -> typing.Any: ... @typing.overload @@ -669,7 +675,13 @@ class SafetyConfig: self, torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., max_torque_rate: float = ..., - joint_limit_margin: float = 0.1, + max_velocity: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + deceleration: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + velocity_offset: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + limit_damping: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + velocity_margin: float = 0.8, + spring_torque: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + spring_range: float = 0.05, ) -> None: ... @typing.overload def __init__(self, other: SafetyConfig) -> None: diff --git a/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py index abaf6357e..cacbab744 100644 --- a/python/tests/test_fr3_controllers.py +++ b/python/tests/test_fr3_controllers.py @@ -73,29 +73,37 @@ def test_torque_is_clipped(dynamics): np.testing.assert_allclose(np.abs(tau), SAFETY.torque_limit) -def test_no_torque_towards_a_close_joint_limit(dynamics): +def test_soft_end_stop_in_front_of_the_fr3_limits(dynamics): + # joint 6 (lower limit 0.44 rad on the FR3, -0.02 rad on the Panda) inside the spring zone in front of its + # zero-velocity point: holding there, the stage pushes the joint away from the limit + d0 = SAFETY.velocity_offset[5] ** 2 / (2 * SAFETY.deceleration[5]) q = Q0.copy() - q[0] = JOINT_LIMITS[1, 0] - 0.05 + q[5] = JOINT_LIMITS[0, 5] + d0 + 0.5 * SAFETY.spring_range state = dynamics.compute(q, np.zeros(7), DT) controller = joint_controller(state) - controller.set_goal(q + 0.3, duration=DT) # pulls joint 1 into the limit - for _ in range(20): + for _ in range(20): # let the rate limit settle tau = controller.step(state) - assert tau[0] == 0.0 - assert tau[1] > 0.0 + np.testing.assert_allclose(tau[5], 0.5 * SAFETY.spring_torque[5], rtol=1e-6) + np.testing.assert_allclose(tau[[0, 1, 2, 3, 4, 6]], 0.0, atol=1e-6) -def test_guard_uses_the_limits_of_the_robot(dynamics): - # the lower limit of joint 6 is 0.44 rad on the FR3 (-0.02 rad on the Panda) +def test_fast_approach_to_an_fr3_limit_is_braked(dynamics): + # joint 1 moving at 1 rad/s towards its upper limit, 0.1 rad away: allowed there are 80% of 0.44 rad/s q = Q0.copy() - q[5] = JOINT_LIMITS[0, 5] + 0.05 - state = dynamics.compute(q, np.zeros(7), DT) - controller = joint_controller(state) - controller.set_goal(q - 0.3, duration=DT) # pulls joint 6 into the limit - for _ in range(20): - tau = controller.step(state) - assert tau[5] == 0.0 - assert tau[4] < 0.0 + q[0] = JOINT_LIMITS[1, 0] - 0.1 + dq = np.zeros(7) + dq[0] = 1.0 + state = dynamics.compute(q, dq, DT) + allowed = 0.8 * (np.sqrt(2 * SAFETY.deceleration[0] * 0.1) - SAFETY.velocity_offset[0]) + stage = common.SafetyStage(SAFETY, JOINT_LIMITS, DT) + stage.reset(state) + for _ in range(100): # let the rate limit (1 Nm per step) settle + tau = stage.apply(np.zeros(7), state) + np.testing.assert_allclose(tau[0], -SAFETY.limit_damping[0] * (1.0 - allowed), rtol=1e-6) + # moving away from the limit is not braked + state = dynamics.compute(q, -dq, DT) + stage.reset(state) + assert np.all(stage.apply(np.zeros(7), state) == 0.0) def test_osc_holds_without_torque_at_its_posture(dynamics): diff --git a/python/tests/test_safety_stage.py b/python/tests/test_safety_stage.py index 000404a51..c5949fa96 100644 --- a/python/tests/test_safety_stage.py +++ b/python/tests/test_safety_stage.py @@ -56,12 +56,39 @@ def test_reset_starts_from_zero_torque(): np.testing.assert_allclose(s.apply(np.full(3, 5.0), state()), 1.0) -def test_no_torque_towards_a_close_joint_limit(): - near = state(q=(0.95, -0.95, 0.0)) # 0.05 rad from the upper and the lower limit - tau = stage().apply(np.array([1.0, -1.0, 1.0]), near) - np.testing.assert_allclose(tau, [0.0, 0.0, 1.0]) - # away from the limit is allowed - np.testing.assert_allclose(stage().apply(np.array([-1.0, 1.0, 1.0]), near), [-1.0, 1.0, 1.0]) +def test_spring_pushes_back_in_front_of_a_limit(): + s = stage(spring_torque=np.full(3, 2.0), spring_range=0.1) + # 0.05 rad from the upper and the lower limit: half way into the spring zone + np.testing.assert_allclose(s.apply(np.zeros(3), state(q=(0.95, -0.95, 0.0))), [-1.0, 1.0, 0.0]) + # outside the zone nothing, at and beyond the limit the full torque + np.testing.assert_allclose( + stage(spring_torque=np.full(3, 2.0), spring_range=0.1).apply(np.zeros(3), state(q=(0.85, 1.0, 1.2))), + [0.0, -2.0, -2.0], + ) + + +def test_spring_sits_in_front_of_the_zero_velocity_point(): + # v(d) = sqrt(2 * 2 * d) - 0.2 is zero at d0 = 0.01 rad + curve = {"max_velocity": np.full(3, 2.0), "deceleration": np.full(3, 2.0), "velocity_offset": np.full(3, 0.2)} + s = stage(spring_torque=np.full(3, 2.0), spring_range=0.1, **curve) + np.testing.assert_allclose(s.apply(np.zeros(3), state(q=(1.0 - 0.01 - 0.05, 0.0, 0.0))), [-1.0, 0.0, 0.0]) + + +def test_damper_brakes_only_a_too_fast_approach(): + curve = {"max_velocity": np.full(3, 2.0), "deceleration": np.full(3, 2.0), "limit_damping": np.full(3, 10.0)} + near = state(q=(0.9, -0.9, 0.0)) # 0.1 rad from the upper / the lower limit: allowed 0.8 * sqrt(0.4) + allowed = 0.8 * np.sqrt(0.4) + near.dq = np.array([1.0, -1.0, 1.0]) # towards both limits, joint 3 far from any limit + np.testing.assert_allclose(stage(**curve).apply(np.zeros(3), near), [-10 * (1 - allowed), 10 * (1 - allowed), 0.0]) + near.dq = np.array([0.3, -0.3, 0.0]) # slow enough + np.testing.assert_allclose(stage(**curve).apply(np.zeros(3), near), 0.0) + near.dq = np.array([-1.0, 1.0, 0.0]) # away from the limits + np.testing.assert_allclose(stage(**curve).apply(np.zeros(3), near), 0.0) + + +def test_damper_needs_the_velocity_curve(): + with pytest.raises(ValueError, match="max_velocity and deceleration"): + common.SafetyStage(common.SafetyConfig(limit_damping=np.ones(3)), LIMITS, DT) def test_torque_limit_needs_one_entry_per_joint(): @@ -100,3 +127,24 @@ def test_robot_config_safety_wraps_the_configured_controller(): setup.robot.set_joint_position(setup.robot.get_joint_position() + 0.5) setup.run(0.1) assert np.max(np.abs(controller_torque(setup))) <= 2.0 + 0.05 + + +@pytest.mark.parametrize("seconds", [4.0, 0.5]) +def test_fr3_guard_stops_joint_4_in_front_of_its_limit(seconds): + # a joint goal 0.15 rad beyond the lower limit of joint 4, streamed slowly or fast at 20 Hz: the joint stops in + # front of the limit (the FR3's zero-velocity point is 0.016 rad in front of it) and never reaches it + setup = configured(common.JointPDConfig(kp=KP, kd=KD)) # the scene sets the FR3 safety stage + lower = setup.robot.get_config().joint_limits[0, 3] + q0 = np.array(setup.robot.get_joint_position()) + goal = q0.copy() + goal[3] = lower - 0.15 + steps = int(seconds / 0.05) + closest = np.inf + for k in range(steps + 40): + setup.robot.set_joint_position(q0 + (goal - q0) * min(1.0, (k + 1) / steps)) + for _ in range(50): + setup.sim.step(1) + closest = min(closest, setup.robot.get_joint_position()[3] - lower) + rest = setup.robot.get_joint_position()[3] - lower + assert closest > 0.01 + assert 0.016 < rest < 0.05 diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 64b54961a..8c123761c 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -584,19 +584,40 @@ PYBIND11_MODULE(_core, m) { rcs::common::SafetyConfig default_safety_config; py::class_(common, "SafetyConfig") .def(py::init([](const rcs::common::VectorXd& torque_limit, - double max_torque_rate, double joint_limit_margin) { - return rcs::common::SafetyConfig{torque_limit, max_torque_rate, - joint_limit_margin}; + double max_torque_rate, + const rcs::common::VectorXd& max_velocity, + const rcs::common::VectorXd& deceleration, + const rcs::common::VectorXd& velocity_offset, + const rcs::common::VectorXd& limit_damping, + double velocity_margin, + const rcs::common::VectorXd& spring_torque, + double spring_range) { + return rcs::common::SafetyConfig{ + torque_limit, max_torque_rate, max_velocity, + deceleration, velocity_offset, limit_damping, + velocity_margin, spring_torque, spring_range}; }), py::arg("torque_limit") = default_safety_config.torque_limit, py::arg("max_torque_rate") = default_safety_config.max_torque_rate, - py::arg("joint_limit_margin") = - default_safety_config.joint_limit_margin) + py::arg("max_velocity") = default_safety_config.max_velocity, + py::arg("deceleration") = default_safety_config.deceleration, + py::arg("velocity_offset") = default_safety_config.velocity_offset, + py::arg("limit_damping") = default_safety_config.limit_damping, + py::arg("velocity_margin") = default_safety_config.velocity_margin, + py::arg("spring_torque") = default_safety_config.spring_torque, + py::arg("spring_range") = default_safety_config.spring_range) .def_readwrite("torque_limit", &rcs::common::SafetyConfig::torque_limit) .def_readwrite("max_torque_rate", &rcs::common::SafetyConfig::max_torque_rate) - .def_readwrite("joint_limit_margin", - &rcs::common::SafetyConfig::joint_limit_margin); + .def_readwrite("max_velocity", &rcs::common::SafetyConfig::max_velocity) + .def_readwrite("deceleration", &rcs::common::SafetyConfig::deceleration) + .def_readwrite("velocity_offset", + &rcs::common::SafetyConfig::velocity_offset) + .def_readwrite("limit_damping", &rcs::common::SafetyConfig::limit_damping) + .def_readwrite("velocity_margin", + &rcs::common::SafetyConfig::velocity_margin) + .def_readwrite("spring_torque", &rcs::common::SafetyConfig::spring_torque) + .def_readwrite("spring_range", &rcs::common::SafetyConfig::spring_range); py::class_(common, "SafetyStage") .def(py::init +#include #include +#include #include namespace rcs { @@ -13,10 +15,26 @@ SafetyStage::SafetyStage(const SafetyConfig& config, if (!(timestep > 0.0)) { throw std::invalid_argument("timestep must be positive"); } - if (config.torque_limit.size() != 0 && - config.torque_limit.size() != joint_limits.cols()) { + const Eigen::Index n = joint_limits.cols(); + for (const auto& [name, v] : {std::pair{ + "torque_limit", config.torque_limit}, + {"max_velocity", config.max_velocity}, + {"deceleration", config.deceleration}, + {"velocity_offset", config.velocity_offset}, + {"limit_damping", config.limit_damping}, + {"spring_torque", config.spring_torque}}) { + if (v.size() != 0 && v.size() != n) { + throw std::invalid_argument(std::string(name) + + " needs one entry per joint of joint_limits"); + } + } + if (config.limit_damping.size() != 0 && + (config.max_velocity.size() == 0 || config.deceleration.size() == 0)) { throw std::invalid_argument( - "torque_limit needs one entry per joint of joint_limits"); + "limit_damping needs max_velocity and deceleration"); + } + if (config.spring_torque.size() != 0 && !(config.spring_range > 0.0)) { + throw std::invalid_argument("spring_range must be positive"); } } @@ -33,13 +51,42 @@ VectorXd SafetyStage::apply(const VectorXd& tau_in, throw std::logic_error("call reset() before apply()"); } VectorXd tau = tau_in; - const double margin = this->config.joint_limit_margin; const double max_step = this->config.max_torque_rate * this->timestep; + const SafetyConfig& c = this->config; for (Eigen::Index i = 0; i < tau.size(); i++) { - if (this->joint_limits(1, i) - state.q[i] < margin && tau[i] > 0.) - tau[i] = 0.; - if (state.q[i] - this->joint_limits(0, i) < margin && tau[i] < 0.) - tau[i] = 0.; + const double offset = c.velocity_offset.size() ? c.velocity_offset[i] : 0.0; + // distances to the upper and the lower limit + const double d_upper = this->joint_limits(1, i) - state.q[i]; + const double d_lower = state.q[i] - this->joint_limits(0, i); + if (c.limit_damping.size()) { + auto allowed = [&](double d) { + return c.velocity_margin * + std::min(c.max_velocity[i], + std::max(0.0, std::sqrt(2.0 * c.deceleration[i] * + std::max(d, 0.0)) - + offset)); + }; + const double towards_upper = state.dq[i] - allowed(d_upper); + const double towards_lower = -state.dq[i] - allowed(d_lower); + if (towards_upper > 0.0) tau[i] -= c.limit_damping[i] * towards_upper; + if (towards_lower > 0.0) tau[i] += c.limit_damping[i] * towards_lower; + } + if (c.spring_torque.size()) { + const double d0 = c.deceleration.size() && c.deceleration[i] > 0.0 + ? offset * offset / (2.0 * c.deceleration[i]) + : 0.0; + // how deep the joint is in the zone in front of the zero-velocity point + auto depth = [&](double d) { + return std::clamp((c.spring_range - (d - d0)) / c.spring_range, 0.0, + 1.0); + }; + // the controller's torque towards the limit fades out over the zone, so + // that the spring always wins at the zero-velocity point + if (tau_in[i] > 0.0) tau[i] -= tau_in[i] * depth(d_upper); + if (tau_in[i] < 0.0) tau[i] -= tau_in[i] * depth(d_lower); + tau[i] -= c.spring_torque[i] * depth(d_upper); + tau[i] += c.spring_torque[i] * depth(d_lower); + } } for (Eigen::Index i = 0; i < tau.size(); i++) { tau[i] = this->last_tau[i] + From 599b5e81006baff576c4e9a9c29f673694722131 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 20:36:29 -0800 Subject: [PATCH 36/39] fix(control): residual mass for the generic OSC On the real FR3 the generic OSC did not rotate about the tool axis at all: the rigid-body model has no motor inertia, joint 7 weighs 0.0007 kg m^2, so the commanded torque for a 30 deg yaw error was 0.045 Nm, below the joint friction. The unrealized yaw error then grew and the coupled task inertia drove joints 1-4 instead (37 Nm peaks), which felt stiff. OSCConfig.residual_mass is added to the diagonal of the mass matrix (empty: none). With the FR3's motor inertia from its MJCF (armature 0.195 / 0.074) the rotation is done by joint 7, as in the sim test; the FR3 OSC's 0.1 / 0.5 / 0.5 on joints 5-7 only makes this OSC turn joints 1, 3 and 5 instead. --- include/rcs/Controllers.h | 10 ++++++++++ python/rcs/_core/common.pyi | 1 + python/tests/test_controller_config.py | 26 ++++++++++++++++++++++++++ src/pybind/rcs.cpp | 3 ++- src/rcs/Controllers.cpp | 14 ++++++++++---- 5 files changed, 49 insertions(+), 5 deletions(-) diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h index 7d7e01d14..cbf461e31 100644 --- a/include/rcs/Controllers.h +++ b/include/rcs/Controllers.h @@ -37,6 +37,16 @@ struct OSCConfig { // the configuration of the last reset(). double kp_nullspace = 10.0; VectorXd nullspace_q; + // Added to the diagonal of the mass matrix (kg m^2 per joint), empty: none. + // The rigid-body model has no motor inertia, so the wrist joints look almost + // weightless (FR3 joint 7: 0.0007 kg m^2) and the OSC commands too little + // torque there to overcome friction: a rotation about the tool axis is not + // realized. The motor inertias keep the joints in proportion (the coupled + // OSC moves the joints with the least inertia): for the FR3 the armature of + // its MJCF, 0.195 on joints 1-4 and 0.074 on joints 5-7. (The FR3 OSC adds + // 0.1 / 0.5 / 0.5 to joints 5-7 only, with which this OSC turns joints 1, 3 + // and 5 for a rotation about the tool axis.) + VectorXd residual_mass; }; // Operational-space control (Khatib), critically damped (kd = 2 sqrt(kp)), diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 4c16174a0..62198ab5b 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -390,6 +390,7 @@ class OSCConfig: kp_orientation: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] nullspace_q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + residual_mass: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] def __copy__(self) -> typing.Any: ... def __deepcopy__(self, arg0: dict) -> typing.Any: ... @typing.overload diff --git a/python/tests/test_controller_config.py b/python/tests/test_controller_config.py index bac4f2472..0aadcd33b 100644 --- a/python/tests/test_controller_config.py +++ b/python/tests/test_controller_config.py @@ -121,3 +121,29 @@ def test_no_way_back_to_native_control(): def test_joint_pd_config_needs_gains(): with pytest.raises(ValueError, match="kp and kd"): configured(common.JointPDConfig(kp=np.array([]), kd=np.array([]))) + + +# motor inertia of the FR3 as the armature of its MJCF +FR3_ARMATURE = np.array([0.195, 0.195, 0.195, 0.195, 0.074, 0.074, 0.074]) + + +@pytest.mark.parametrize("residual_mass", [None, FR3_ARMATURE]) +def test_osc_rotates_about_the_tool_axis_only_with_residual_mass(residual_mass): + # the model has no motor inertia: joint 7 weighs 0.0007 kg m^2, so without residual mass the OSC's torque for a + # rotation about the tool axis stays below the joint friction (as seen on the real FR3); with the motor inertia + # the rotation is done by joint 7, as it should + cfg = common.OSCConfig() + cfg.kp_orientation = np.full(3, 125.0) + if residual_mass is not None: + cfg.residual_mass = residual_mass + setup = configured(cfg) + q0 = np.array(setup.robot.get_joint_position()) + yaw = common.Pose(rpy_vector=np.array([0.0, 0.0, np.radians(30)]), translation=np.zeros(3)) + setup.robot.set_cartesian_position(setup.robot.get_cartesian_position() * yaw) + setup.run(3.0) + turned = np.degrees(np.array(setup.robot.get_joint_position()) - q0) + if residual_mass is None: + assert abs(turned[6]) < 5.0 + else: + assert turned[6] > 25.0 + assert np.max(np.abs(turned[:6])) < 5.0 diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 8c123761c..ba20c6563 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -536,7 +536,8 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("kp_position", &rcs::common::OSCConfig::kp_position) .def_readwrite("kp_orientation", &rcs::common::OSCConfig::kp_orientation) .def_readwrite("kp_nullspace", &rcs::common::OSCConfig::kp_nullspace) - .def_readwrite("nullspace_q", &rcs::common::OSCConfig::nullspace_q); + .def_readwrite("nullspace_q", &rcs::common::OSCConfig::nullspace_q) + .def_readwrite("residual_mass", &rcs::common::OSCConfig::residual_mass); py::class_(common, "JointPDConfig") .def(py::init([](const rcs::common::VectorXd& kp, diff --git a/src/rcs/Controllers.cpp b/src/rcs/Controllers.cpp index 3a752d28d..3f2280efc 100644 --- a/src/rcs/Controllers.cpp +++ b/src/rcs/Controllers.cpp @@ -60,8 +60,14 @@ VectorXd OSC::step(const ControllerState& state) { CartesianSetpoint setpoint = this->interpolator->step(state.dt); const Eigen::Index n = state.q.size(); const auto& J = state.jacobian; - const Eigen::MatrixXd M_inv = - state.mass.ldlt().solve(Eigen::MatrixXd::Identity(n, n)); + Eigen::MatrixXd M = state.mass; + if (this->config.residual_mass.size() != 0) { + if (this->config.residual_mass.size() != n) { + throw std::invalid_argument("residual_mass needs one entry per joint"); + } + M.diagonal() += this->config.residual_mass; + } + const Eigen::MatrixXd M_inv = M.ldlt().solve(Eigen::MatrixXd::Identity(n, n)); // desired TCP acceleration: critically damped spring to the setpoint Vector6d kp; @@ -85,8 +91,8 @@ VectorXd OSC::step(const ControllerState& state) { Eigen::MatrixXd::Identity(n, n) - J.transpose() * J_bar.transpose(); double kd_nullspace = 2.0 * std::sqrt(this->config.kp_nullspace); VectorXd tau_posture = - state.mass * (this->config.kp_nullspace * (this->nullspace_q - state.q) - - kd_nullspace * state.dq); + M * (this->config.kp_nullspace * (this->nullspace_q - state.q) - + kd_nullspace * state.dq); tau += N_transposed * tau_posture; return tau + state.coriolis; From 938a39ddf24d43f66e646cede4855b39706a1586 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 20:50:37 -0800 Subject: [PATCH 37/39] feat(control): optional velocity feed-forward in the generic OSC OSCConfig.velocity_feedforward (default true) damps towards the setpoint velocity of the interpolator; false damps towards zero velocity, as the FR3 OSC. With streamed teleop goals the setpoint velocity jumps with every goal (hand jitter over one period): on the real FR3 the generic OSC's torque changes peaked about 15 ms into every 30 Hz step (when the goal arrives) and ran into the 1000 Nm/s rate limit, which felt stiff. In sim with jittery 30 Hz goals: torque rate p99 1008 Nm/s with, 105 without the feed-forward (FR3 OSC 220), at 12.4 mm tracking error (FR3 OSC 15.8, with feed-forward 4.8). --- include/rcs/Controllers.h | 5 +++++ python/rcs/_core/common.pyi | 1 + python/tests/test_controller_config.py | 25 +++++++++++++++++++++++++ src/pybind/rcs.cpp | 4 +++- src/rcs/Controllers.cpp | 4 +++- 5 files changed, 37 insertions(+), 2 deletions(-) diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h index cbf461e31..c485d865f 100644 --- a/include/rcs/Controllers.h +++ b/include/rcs/Controllers.h @@ -47,6 +47,11 @@ struct OSCConfig { // 0.1 / 0.5 / 0.5 to joints 5-7 only, with which this OSC turns joints 1, 3 // and 5 for a rotation about the tool axis.) VectorXd residual_mass; + // Damp towards the setpoint velocity of the interpolator (true) or towards + // zero velocity (false, as the FR3 OSC). With streamed teleop goals the + // setpoint velocity jumps with every goal (hand jitter over one period), so + // the feed-forward kicks the torques at the goal rate. + bool velocity_feedforward = true; }; // Operational-space control (Khatib), critically damped (kd = 2 sqrt(kp)), diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 62198ab5b..31c7733af 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -391,6 +391,7 @@ class OSCConfig: kp_position: numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]] nullspace_q: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] residual_mass: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + velocity_feedforward: bool def __copy__(self) -> typing.Any: ... def __deepcopy__(self, arg0: dict) -> typing.Any: ... @typing.overload diff --git a/python/tests/test_controller_config.py b/python/tests/test_controller_config.py index 0aadcd33b..2f68b95fc 100644 --- a/python/tests/test_controller_config.py +++ b/python/tests/test_controller_config.py @@ -147,3 +147,28 @@ def test_osc_rotates_about_the_tool_axis_only_with_residual_mass(residual_mass): else: assert turned[6] > 25.0 assert np.max(np.abs(turned[:6])) < 5.0 + + +def test_osc_without_velocity_feedforward_is_smooth_with_jittery_goals(): + # 30 Hz goals with hand jitter: the setpoint velocity jumps with every goal, which the feed-forward turns into + # torque kicks at the goal rate; damping towards zero velocity (as the FR3 OSC) does not + rng = np.random.default_rng(0) + rate_p99 = {} + for feedforward in (True, False): + cfg = common.OSCConfig() + cfg.kp_orientation = np.full(3, 125.0) + cfg.residual_mass = FR3_ARMATURE + cfg.velocity_feedforward = feedforward + setup = configured(cfg) + start = setup.robot.get_cartesian_position() + taus = [] + for _ in range(45): # 1.5 s at 30 Hz + goal = common.Pose( + rotation=start.rotation_m(), translation=start.translation() + 0.001 * rng.normal(size=3) + ) + setup.robot.set_cartesian_position(goal) + for _ in range(33): + setup.sim.step(1) + taus.append(setup.sim.data.actuator_force[:7].copy()) + rate_p99[feedforward] = np.percentile(np.abs(np.diff(np.array(taus)[:, :4], axis=0)) * 1000, 99) + assert rate_p99[False] < 0.3 * rate_p99[True] diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index ba20c6563..5e05803c0 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -537,7 +537,9 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("kp_orientation", &rcs::common::OSCConfig::kp_orientation) .def_readwrite("kp_nullspace", &rcs::common::OSCConfig::kp_nullspace) .def_readwrite("nullspace_q", &rcs::common::OSCConfig::nullspace_q) - .def_readwrite("residual_mass", &rcs::common::OSCConfig::residual_mass); + .def_readwrite("residual_mass", &rcs::common::OSCConfig::residual_mass) + .def_readwrite("velocity_feedforward", + &rcs::common::OSCConfig::velocity_feedforward); py::class_(common, "JointPDConfig") .def(py::init([](const rcs::common::VectorXd& kp, diff --git a/src/rcs/Controllers.cpp b/src/rcs/Controllers.cpp index 3f2280efc..912bbd0a9 100644 --- a/src/rcs/Controllers.cpp +++ b/src/rcs/Controllers.cpp @@ -76,8 +76,10 @@ VectorXd OSC::step(const ControllerState& state) { Vector6d error; error << setpoint.pose.translation() - state.tcp_pose.translation(), rotation_between(state.tcp_pose.quaternion(), setpoint.pose.quaternion()); + const Vector6d v_desired = + this->config.velocity_feedforward ? setpoint.twist : Vector6d::Zero(); Vector6d F = - kp.cwiseProduct(error) + kd.cwiseProduct(setpoint.twist - J * state.dq); + kp.cwiseProduct(error) + kd.cwiseProduct(v_desired - J * state.dq); // task-space inertia Eigen::Matrix L = (J * M_inv * J.transpose()) From 91f2c4f14092dcd3e1586241c8fdf58ae5f6bab6 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sat, 21 Nov 2026 20:53:50 -0800 Subject: [PATCH 38/39] feat(control): no velocity feed-forward in the generic OSC by default OSCConfig.velocity_feedforward defaults to false: with streamed goals (teleop, policies at 15-30 Hz) the setpoint velocity jumps with every goal and the feed-forward kicks the torques at the goal rate. --- docs/development/controller_interface.md | 2 +- include/rcs/Controllers.h | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 15c92564d..42739caef 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -185,7 +185,7 @@ class PinocchioDynamics { |---|---|---| | `LinearJointInterpolator`, `LinearCartesianInterpolator` | core | Straight line (slerp for rotation) from the current setpoint to the goal over a fixed duration, then hold. Generalises the 7-DoF `LinearPoseTrajInterpolator.h`, which is deleted once FR3 has moved over. | | `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | -| `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | +| `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. `v_d` is 0 by default (`velocity_feedforward`: with streamed teleop goals the setpoint velocity jumps with every goal and kicked the torques at the goal rate on the real FR3, see `OSCConfig`). `residual_mass` is added to the mass matrix: the model has no motor inertia, without it (FR3: the MJCF armature) a rotation about the tool axis is not realized. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | | `SafetyStage`, `SafeJointController`, `SafeCartesianController` | core | The safety stage of `Franka.cpp` for any robot and controller, configured by `RobotConfig::safety` (`SafetyConfig`: torque limit, torque rate limit, joint-limit guard). In this order: the joint-limit guard, the rate limit per step of the nominal control period (as `franka::limitRate`, which limits per command assuming 1 ms, so the measured `dt` is not used), the clip. It keeps its own previous output instead of `tau_J_d`. `make_controller` wraps the configured controller with it, so sim and hardware run the same code. `rcs.ROBOTS` holds the values (FR3 and Panda: 87/12 Nm, 999.999 Nm/s), `apply()` sets them. `Franka` refuses async (torque) control without it; in sim it is used when set, which the FR3 scenes do. The joint-limit guard works in joint space, per joint, from the robot's position based velocity limits `v(d) = min(v_max, sqrt(2 a d) - c)` (FR3: `deceleration_limit` and `velocity_offset` from the URDF the robot reports, as libfranka's `getUpperJointVelocityLimits`; Panda: `c = 0`), which reach zero at `d0 = c²/2a` in front of the limit (FR3: 0.006-0.035 rad): a damper on the velocity towards a limit above 80% of `v(d)` (100 / 20 Nm s/rad), and in the last 0.05 rad in front of `d0` the controller's torque towards the limit fades out while a spring pushes back (10 / 3 Nm at `d0`), like the soft end stop in guiding mode. Slow motion can reach the limit up to the spring zone, motion away from a limit is never affected. In sim a joint goal 0.15 rad beyond the lower limit of joint 4 stops the joint 0.024-0.033 rad in front of it, also when streamed fast (without the guard it hits the limit). | | `FR3JointController`, `FR3OSC` | core | The current `Franka::joint_controller` / `Franka::osc` maths, ported one to one out of the libfranka lambdas (deoxys): Coriolis feed-forward, residual mass, null-space posture, deadband. Two parts of the original are not in them: the safety stage at the end of both loops (joint-limit cut, torque rate limit, torque clip), which is the `SafetyStage` (see below) for any controller, and deoxys' null-space joint-limit avoidance (a push of `w·d` in the band 0.1-0.25 rad from a limit, which starts with a step and blocked the area close to the base together with the 0.1 rad cut); joint limits are handled in joint space by the `SafetyStage`. `RobotConfig` has no robot specific defaults (empty type, `dof` 0, 2×0 limits); they are set from `rcs.ROBOTS` with `rcs.ROBOTS[robot_type].apply(cfg)`, and `SimRobot` and `Franka` reject a config without them. `FR3Config` and `PandaConfig` are therefore Python classes (`rcs_fr3.hw`, `rcs_panda.hw`) that subclass the C++ `FrankaConfig` and call `apply()` in their constructor. Being in core, the sim can use them without `rcs_fr3` installed. They are separate classes rather than options on `JointPD`/`OSC`, so that `JointPD`/`OSC` stay minimal and the port can be reviewed line by line against the old code. | diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h index c485d865f..e420f7b0d 100644 --- a/include/rcs/Controllers.h +++ b/include/rcs/Controllers.h @@ -47,16 +47,18 @@ struct OSCConfig { // 0.1 / 0.5 / 0.5 to joints 5-7 only, with which this OSC turns joints 1, 3 // and 5 for a rotation about the tool axis.) VectorXd residual_mass; - // Damp towards the setpoint velocity of the interpolator (true) or towards - // zero velocity (false, as the FR3 OSC). With streamed teleop goals the - // setpoint velocity jumps with every goal (hand jitter over one period), so - // the feed-forward kicks the torques at the goal rate. - bool velocity_feedforward = true; + // Damp towards zero velocity (false, as the FR3 OSC) or towards the setpoint + // velocity of the interpolator (true: tighter tracking of smooth goals). + // With streamed teleop goals the setpoint velocity jumps with every goal + // (hand jitter over one period), so the feed-forward kicks the torques at + // the goal rate. + bool velocity_feedforward = false; }; // Operational-space control (Khatib), critically damped (kd = 2 sqrt(kp)), // with a posture task in the null space: -// F = kp e + kd (v_d - v) e: position and rotation error +// F = kp e + kd (v_d - v) e: position and rotation error, +// v_d: 0 or the setpoint velocity // tau = J' L F + N' tau_posture + coriolis // with the task-space inertia L = (J M^-1 J')^-1 and N the dynamically // consistent null-space projector. Position and orientation are coupled From b7f5e4940a0656ea6156f95ba37450e35f2d68a1 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 22 Nov 2026 09:41:18 -0800 Subject: [PATCH 39/39] feat(control): no velocity feed-forward in JointPD by default JointPD damped towards the setpoint velocity of the interpolator. With streamed goals (30 Hz policies, IK-labelled targets) that velocity jumps with every goal and kicks the torques at the goal rate: in sim with jittery 30 Hz joint goals the torque rate sat at the 1000 Nm/s limit (p99 1000 Nm/s, 10% of steps at the limit), without the feed-forward p99 21 Nm/s. As for the OSC (91f2c4f1), JointPD and JointPDConfig get velocity_feedforward, default false, which is the law of the FR3 joint controller and libfranka's joint impedance example. --- docs/development/controller_interface.md | 2 +- include/rcs/ControllerConfig.h | 2 ++ include/rcs/Controllers.h | 8 +++++++- python/rcs/_core/common.pyi | 3 +++ python/tests/test_controller_config.py | 17 +++++++++++++++++ python/tests/test_controllers.py | 15 ++++++++++----- src/pybind/rcs.cpp | 17 +++++++++++------ src/rcs/ControllerConfig.cpp | 4 ++-- src/rcs/Controllers.cpp | 12 +++++++++--- 9 files changed, 62 insertions(+), 18 deletions(-) diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md index 42739caef..dc4d9634e 100644 --- a/docs/development/controller_interface.md +++ b/docs/development/controller_interface.md @@ -184,7 +184,7 @@ class PinocchioDynamics { | Implementation | Package | Notes | |---|---|---| | `LinearJointInterpolator`, `LinearCartesianInterpolator` | core | Straight line (slerp for rotation) from the current setpoint to the goal over a fixed duration, then hold. Generalises the 7-DoF `LinearPoseTrajInterpolator.h`, which is deleted once FR3 has moved over. | -| `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis` | +| `JointPD` | core | `tau = Kp (q_d - q) + Kd (dq_d - dq) + coriolis`, `dq_d` is 0 by default (`velocity_feedforward`, as the FR3 joint controller and libfranka's joint impedance example): with 30 Hz goals the setpoint velocity jumps with every goal and the feed-forward pins the torque rate limit (sim: p99 1000 vs 21 Nm/s). | | `OSC` | core | Operational-space control with null-space posture: `tau = Jᵀ Λ (Kp e + Kd (v_d - v)) + Nᵀ (posture term) + coriolis`, critically damped. `v_d` is 0 by default (`velocity_feedforward`: with streamed teleop goals the setpoint velocity jumps with every goal and kicked the torques at the goal rate on the real FR3, see `OSCConfig`). `residual_mass` is added to the mass matrix: the model has no motor inertia, without it (FR3: the MJCF armature) a rotation about the tool axis is not realized. Position and orientation are coupled through the full 6×6 task inertia `Λ`, so the TCP follows the setpoint as a clean second-order system when the model is exact. The decoupled form (separate `Λp`, `Λo`, as in the FR3 OSC and robosuite) has cross terms that slow convergence noticeably for combined translation and rotation: on an exact plant it needed 4 s instead of 1 s for a 11 cm / 13° move. | | `PinocchioDynamics` | core | See above. | | `SafetyStage`, `SafeJointController`, `SafeCartesianController` | core | The safety stage of `Franka.cpp` for any robot and controller, configured by `RobotConfig::safety` (`SafetyConfig`: torque limit, torque rate limit, joint-limit guard). In this order: the joint-limit guard, the rate limit per step of the nominal control period (as `franka::limitRate`, which limits per command assuming 1 ms, so the measured `dt` is not used), the clip. It keeps its own previous output instead of `tau_J_d`. `make_controller` wraps the configured controller with it, so sim and hardware run the same code. `rcs.ROBOTS` holds the values (FR3 and Panda: 87/12 Nm, 999.999 Nm/s), `apply()` sets them. `Franka` refuses async (torque) control without it; in sim it is used when set, which the FR3 scenes do. The joint-limit guard works in joint space, per joint, from the robot's position based velocity limits `v(d) = min(v_max, sqrt(2 a d) - c)` (FR3: `deceleration_limit` and `velocity_offset` from the URDF the robot reports, as libfranka's `getUpperJointVelocityLimits`; Panda: `c = 0`), which reach zero at `d0 = c²/2a` in front of the limit (FR3: 0.006-0.035 rad): a damper on the velocity towards a limit above 80% of `v(d)` (100 / 20 Nm s/rad), and in the last 0.05 rad in front of `d0` the controller's torque towards the limit fades out while a spring pushes back (10 / 3 Nm at `d0`), like the soft end stop in guiding mode. Slow motion can reach the limit up to the spring zone, motion away from a limit is never affected. In sim a joint goal 0.15 rad beyond the lower limit of joint 4 stops the joint 0.024-0.033 rad in front of it, also when streamed fast (without the guard it hits the limit). | diff --git a/include/rcs/ControllerConfig.h b/include/rcs/ControllerConfig.h index 65ab7b730..bec947346 100644 --- a/include/rcs/ControllerConfig.h +++ b/include/rcs/ControllerConfig.h @@ -17,6 +17,8 @@ struct JointPDConfig { // one gain per joint, no defaults as they depend on the robot VectorXd kp; VectorXd kd; + // damp towards the setpoint velocity instead of zero, see JointPD + bool velocity_feedforward = false; }; // A controller, identified by its config. RobotConfig::controller holds one; diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h index e420f7b0d..8c4f486ee 100644 --- a/include/rcs/Controllers.h +++ b/include/rcs/Controllers.h @@ -15,10 +15,15 @@ namespace common { // Joint-space PD around the interpolated setpoint: // tau = kp (q_d - q) + kd (dq_d - dq) + coriolis +// dq_d is 0 by default (velocity_feedforward false, as the FR3 joint +// controller and libfranka's joint impedance example): with streamed goals +// the setpoint velocity of the interpolator jumps with every goal and the +// feed-forward kicks the torques at the goal rate. class JointPD : public JointController { public: JointPD(const VectorXd& kp, const VectorXd& kd, - std::shared_ptr interpolator); + std::shared_ptr interpolator, + bool velocity_feedforward = false); void reset(const ControllerState& state) override; void set_goal(const VectorXd& q_goal, std::optional duration = std::nullopt) override; @@ -28,6 +33,7 @@ class JointPD : public JointController { VectorXd kp; VectorXd kd; std::shared_ptr interpolator; + bool velocity_feedforward; }; struct OSCConfig { diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index 31c7733af..db4e2498c 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -351,6 +351,7 @@ class JointInterpolator: class JointPDConfig: kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + velocity_feedforward: bool def __copy__(self) -> typing.Any: ... def __deepcopy__(self, arg0: dict) -> typing.Any: ... @typing.overload @@ -358,6 +359,7 @@ class JointPDConfig: self, kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], + velocity_feedforward: bool = False, ) -> None: ... @typing.overload def __init__(self, other: JointPDConfig) -> None: @@ -747,6 +749,7 @@ class JointPD(JointController): kp: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], kd: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], interpolator: JointInterpolator, + velocity_feedforward: bool = False, ) -> None: ... class SafeJointController(JointController): diff --git a/python/tests/test_controller_config.py b/python/tests/test_controller_config.py index 2f68b95fc..2620670e5 100644 --- a/python/tests/test_controller_config.py +++ b/python/tests/test_controller_config.py @@ -172,3 +172,20 @@ def test_osc_without_velocity_feedforward_is_smooth_with_jittery_goals(): taus.append(setup.sim.data.actuator_force[:7].copy()) rate_p99[feedforward] = np.percentile(np.abs(np.diff(np.array(taus)[:, :4], axis=0)) * 1000, 99) assert rate_p99[False] < 0.3 * rate_p99[True] + + +def test_joint_pd_without_velocity_feedforward_is_smooth_with_jittery_goals(): + # 30 Hz joint goals with jitter: as for the OSC, the feed-forward of the setpoint velocity kicks the torques + rng = np.random.default_rng(0) + rate_p99 = {} + for feedforward in (True, False): + setup = configured(common.JointPDConfig(kp=KP, kd=KD, velocity_feedforward=feedforward)) + q0 = np.array(setup.robot.get_joint_position()) + taus = [] + for _ in range(45): # 1.5 s at 30 Hz + setup.robot.set_joint_position(q0 + 0.002 * rng.normal(size=7)) + for _ in range(33): + setup.sim.step(1) + taus.append(setup.sim.data.actuator_force[:7].copy()) + rate_p99[feedforward] = np.percentile(np.abs(np.diff(np.array(taus)[:, :4], axis=0)) * 1000, 99) + assert rate_p99[False] < 0.3 * rate_p99[True] diff --git a/python/tests/test_controllers.py b/python/tests/test_controllers.py index 9ff8f939e..2e3b6207a 100644 --- a/python/tests/test_controllers.py +++ b/python/tests/test_controllers.py @@ -25,8 +25,10 @@ class TestJointPD: kp = np.full(7, 100.0) kd = np.full(7, 20.0) - def make(self, state) -> common.JointPD: - controller = common.JointPD(self.kp, self.kd, common.LinearJointInterpolator(0.05)) + def make(self, state, velocity_feedforward=False) -> common.JointPD: + controller = common.JointPD( + self.kp, self.kd, common.LinearJointInterpolator(0.05), velocity_feedforward=velocity_feedforward + ) controller.reset(state) return controller @@ -34,14 +36,17 @@ def test_holds_without_torque_at_rest(self, dynamics): state = dynamics.compute(Q0, np.zeros(7), DT) np.testing.assert_allclose(self.make(state).step(state), 0.0, atol=1e-12) - def test_pd_law_with_setpoint_velocity_and_coriolis(self, dynamics): - controller = self.make(dynamics.compute(Q0, np.zeros(7), DT)) + @pytest.mark.parametrize("feedforward", [False, True]) + def test_pd_law_with_coriolis(self, dynamics, feedforward): + # by default the damping is towards zero velocity, with velocity_feedforward towards the setpoint velocity + controller = self.make(dynamics.compute(Q0, np.zeros(7), DT), velocity_feedforward=feedforward) goal = Q0 + 0.1 controller.set_goal(goal) dq = np.full(7, 0.3) state = dynamics.compute(Q0, dq, DT) velocity = (goal - Q0) / 0.05 - expected = self.kp * (Q0 + velocity * DT - Q0) + self.kd * (velocity - dq) + state.coriolis + dq_desired = velocity if feedforward else 0.0 + expected = self.kp * (Q0 + velocity * DT - Q0) + self.kd * (dq_desired - dq) + state.coriolis np.testing.assert_allclose(controller.step(state), expected, atol=1e-10) def test_rejects_mismatched_gains(self): diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 5e05803c0..c67fa63c6 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -528,8 +528,9 @@ PYBIND11_MODULE(_core, m) { py::class_>(common, "JointPD") .def(py::init>(), - py::arg("kp"), py::arg("kd"), py::arg("interpolator")); + std::shared_ptr, bool>(), + py::arg("kp"), py::arg("kd"), py::arg("interpolator"), + py::arg("velocity_feedforward") = false); py::class_(common, "OSCConfig") .def(py::init<>()) @@ -543,12 +544,16 @@ PYBIND11_MODULE(_core, m) { py::class_(common, "JointPDConfig") .def(py::init([](const rcs::common::VectorXd& kp, - const rcs::common::VectorXd& kd) { - return rcs::common::JointPDConfig{kp, kd}; + const rcs::common::VectorXd& kd, + bool velocity_feedforward) { + return rcs::common::JointPDConfig{kp, kd, velocity_feedforward}; }), - py::arg("kp"), py::arg("kd")) + py::arg("kp"), py::arg("kd"), + py::arg("velocity_feedforward") = false) .def_readwrite("kp", &rcs::common::JointPDConfig::kp) - .def_readwrite("kd", &rcs::common::JointPDConfig::kd); + .def_readwrite("kd", &rcs::common::JointPDConfig::kd) + .def_readwrite("velocity_feedforward", + &rcs::common::JointPDConfig::velocity_feedforward); py::class_>(common, "OSC") diff --git a/src/rcs/ControllerConfig.cpp b/src/rcs/ControllerConfig.cpp index f70d679a1..f1fb3f526 100644 --- a/src/rcs/ControllerConfig.cpp +++ b/src/rcs/ControllerConfig.cpp @@ -23,8 +23,8 @@ ControllerPair make_controller(const ControllerConfig& config, if (c->kp.size() == 0 || c->kd.size() == 0) { throw std::invalid_argument("JointPDConfig needs kp and kd"); } - controller.joint = - std::make_shared(c->kp, c->kd, joint_interpolator()); + controller.joint = std::make_shared( + c->kp, c->kd, joint_interpolator(), c->velocity_feedforward); } else if (auto* c = std::get_if(&config)) { controller.cartesian = std::make_shared(*c, cartesian_interpolator()); } else if (auto* c = std::get_if(&config)) { diff --git a/src/rcs/Controllers.cpp b/src/rcs/Controllers.cpp index 912bbd0a9..71962490b 100644 --- a/src/rcs/Controllers.cpp +++ b/src/rcs/Controllers.cpp @@ -8,8 +8,12 @@ namespace rcs { namespace common { JointPD::JointPD(const VectorXd& kp, const VectorXd& kd, - std::shared_ptr interpolator) - : kp(kp), kd(kd), interpolator(std::move(interpolator)) { + std::shared_ptr interpolator, + bool velocity_feedforward) + : kp(kp), + kd(kd), + interpolator(std::move(interpolator)), + velocity_feedforward(velocity_feedforward) { if (kp.size() != kd.size()) { throw std::invalid_argument("kp and kd must have the same size"); } @@ -31,8 +35,10 @@ VectorXd JointPD::step(const ControllerState& state) { throw std::invalid_argument("state has the wrong number of joints"); } JointSetpoint setpoint = this->interpolator->step(state.dt); + const VectorXd dq_desired = + this->velocity_feedforward ? setpoint.dq : VectorXd::Zero(state.q.size()); return this->kp.cwiseProduct(setpoint.q - state.q) + - this->kd.cwiseProduct(setpoint.dq - state.dq) + state.coriolis; + this->kd.cwiseProduct(dq_desired - state.dq) + state.coriolis; } OSC::OSC(const OSCConfig& config,