diff --git a/docs/development/controller_interface.md b/docs/development/controller_interface.md new file mode 100644 index 00000000..dc4d9634 --- /dev/null +++ b/docs/development/controller_interface.md @@ -0,0 +1,365 @@ +# 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) + ▲ + backend (q, dq) ──► PinocchioDynamics +``` + +- **ControllerState**: everything a torque controller needs about one robot, + 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**: reads `q` and `dq`, calls `PinocchioDynamics` and `step()`, + and applies the torque. Only the backend knows the hardware. + +### Gravity convention + +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 + +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, // 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 +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, // 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 */ }; +``` + +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 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 + +| 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`, `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). | +| `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 + +### 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 + `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, + bias 0). The torque is clamped to the actuator's `forcerange`/`ctrlrange`. + MuJoCo gravity compensation (`body_gravcomp`) is switched off for the + robot's bodies, and the backend logs that it did (see the gravity + convention). + - 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()`. 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: `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 + 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. + - `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. 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. + +### FR3 hardware (`Franka`) + +- 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. 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. +- 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 + +`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. `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. 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 + 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 + +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 + +- First run of step 7 on the robot. + +## 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**: `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 + change for FR3. diff --git a/docs/development/index.md b/docs/development/index.md index 42cc9a5f..c18de57e 100644 --- a/docs/development/index.md +++ b/docs/development/index.md @@ -5,5 +5,6 @@ python_extension cpp_extension +controller_interface ../contributing/index ``` diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md index 575d5418..25d49a9a 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 81e67ad6..a44e73ee 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 5c7d443f..15df2df3 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 e16a33c7..bdecb5cc 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 c7882cec..412ee5f7 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 46aa9897..3d357c75 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 a247aac3..e36a28e7 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 91aef19f..1a20221f 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 d9425371..b3eaed0a 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 @@ -11,10 +9,12 @@ #include #include #include +#include #include #include #include "FrankaMotionGenerator.h" +#include "rcs/LinearInterpolator.h" #include "rcs/Pose.h" namespace rcs { @@ -29,12 +29,66 @@ common::Pose GetTCPInBaseFrame(const franka::RobotState& robot_state, return GetFlangeInBaseFrame(robot_state) * tcp_offset; } +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"); + } + 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"); + } +} + +// 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, std::optional> ik) : m_cfg(cfg), m_ik(ik), 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); @@ -54,6 +108,7 @@ Franka::~Franka() { * otherwise the call will fail */ bool Franka::set_config(const FrankaConfig& cfg) { + check_config(cfg); this->m_cfg = cfg; this->m_cfg.speed_factor = std::min(std::max(cfg.speed_factor, 0.0), 1.0); @@ -71,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; } @@ -115,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() { @@ -132,6 +191,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.end_effector.tcp_offset)); + return; + } this->controller_set_joint_position(q); return; } @@ -158,51 +229,18 @@ 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(); + 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 throw std::runtime_error( @@ -229,9 +267,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->torque_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 +322,17 @@ 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(); + 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 " + @@ -306,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; @@ -331,11 +367,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->torque_cartesian_controller->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) { @@ -362,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); @@ -394,11 +428,56 @@ 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) { + config = common::FR3OSCConfig(); + } else { + 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, + this->m_cfg.joint_limits, this->m_cfg.safety, + this->m_cfg.timestep); +} + +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.end_effector.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 +494,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->torque_cartesian_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()); @@ -631,10 +519,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 +534,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->torque_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()); @@ -863,13 +688,20 @@ 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; } 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); @@ -884,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 5834ae95..1dcb160f 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -12,8 +12,11 @@ #include #include +#include "rcs/Controller.h" +#include "rcs/ControllerConfig.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" @@ -33,31 +36,22 @@ 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. // Used to size the interpolation window between successive targets. int policy_rate = 20; - // 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(); + // period of the control loop in seconds; libfranka runs it at 1 kHz, so + // anything else is rejected + double timestep = 0.001; + // 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(); - // 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 @@ -78,31 +72,8 @@ 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(); -}; - -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(); + // robot_type, dof, joint_limits etc. are those of RobotConfig, set them per + // robot (in Python with rcs.ROBOTS[robot_type].apply(cfg)) }; struct FrankaState : common::RobotState { @@ -115,18 +86,27 @@ 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: RobotConfig::controller, or without it FR3JointController and + // 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; + 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; 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/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index fc3ddc18..390226b6 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" @@ -126,28 +127,17 @@ 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) - .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("timestep", &rcs::hw::FrankaConfig::timestep) .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( - "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) @@ -160,109 +150,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"); @@ -379,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/__init__.py b/extensions/rcs_fr3/src/rcs_fr3/__init__.py index 56e60a9b..187ff056 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 5b9ab3eb..7782e576 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", @@ -45,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, @@ -55,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 @@ -113,17 +128,20 @@ 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 - tcp_offset: rcs._core.common.Pose - tcp_offset_explicit: bool - torque_limit: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] + 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: ... @@ -138,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: """ @@ -214,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 @@ -304,50 +339,17 @@ 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 = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", - 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 = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", - 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 __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/extensions/rcs_fr3/src/rcs_fr3/configs.py b/extensions/rcs_fr3/src/rcs_fr3/configs.py index 4727c37e..e2316f5b 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,21 +19,14 @@ 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, speed_factor=0.1, async_control=False, ignore_realtime=False, - tcp_offset=common.Pose(common.FrankaHandTCPOffset()), - attachment_site="attachment_site", - kinematic_model_path=fr3.mjcf_model_path, + end_effector=common.EndEffectorConfig(tcp_offset=common.Pose(common.FrankaHandTCPOffset())), ) - 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 gripper_cfg = hw.FHConfig( ip=self.ip, @@ -118,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( @@ -208,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/creators.py b/extensions/rcs_fr3/src/rcs_fr3/creators.py index 69e25e21..0730dbe0 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/envs.py b/extensions/rcs_fr3/src/rcs_fr3/envs.py index 3bd10c58..511ce8c6 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 00000000..50ca1820 --- /dev/null +++ b/extensions/rcs_fr3/src/rcs_fr3/hw.py @@ -0,0 +1,36 @@ +"""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 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 + + +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 + 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__ = [name for name in dir(_core_hw) if not name.startswith("_")] + ["FR3Config"] diff --git a/extensions/rcs_panda/src/rcs_panda/__init__.py b/extensions/rcs_panda/src/rcs_panda/__init__.py index 4c4e503b..d781e543 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 ba93631e..3edf36bb 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, @@ -20,11 +20,7 @@ class DefaultPandaHardwareEnv(RCSPandaConfigEnvCreator): 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.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.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 @@ -62,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/creators.py b/extensions/rcs_panda/src/rcs_panda/creators.py index fd93ec3e..cacdaf30 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/envs.py b/extensions/rcs_panda/src/rcs_panda/envs.py index 2e83794f..1b332e08 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 00000000..5a77c196 --- /dev/null +++ b/extensions/rcs_panda/src/rcs_panda/hw.py @@ -0,0 +1,36 @@ +"""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 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 + + +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 + 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__ = [name for name in dir(_core_hw) if not name.startswith("_")] + ["PandaConfig"] diff --git a/extensions/rcs_so101/src/rcs_so101/configs.py b/extensions/rcs_so101/src/rcs_so101/configs.py index 747335b6..056357a9 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 1dc597c5..0007e121 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 37802922..86ff08db 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 020343c3..b006a5f0 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 319057bc..a509e3c2 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 613ae6de..61b66d64 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 ecf414a7..73eb0dec 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 8114eb11..497baf31 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/Controller.h b/include/rcs/Controller.h new file mode 100644 index 00000000..62895b10 --- /dev/null +++ b/include/rcs/Controller.h @@ -0,0 +1,58 @@ +#ifndef RCS_CONTROLLER_H +#define RCS_CONTROLLER_H + +#include +#include + +#include "Pose.h" +#include "utils.h" + +namespace rcs { +namespace common { + +// 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; + 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. 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. + +class JointController { + public: + virtual ~JointController() = default; + // Hold the current configuration. + virtual void reset(const ControllerState& state) = 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; +}; + +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, + std::optional duration = std::nullopt) = 0; + virtual VectorXd step(const ControllerState& state) = 0; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_CONTROLLER_H diff --git a/include/rcs/ControllerConfig.h b/include/rcs/ControllerConfig.h new file mode 100644 index 00000000..bec94734 --- /dev/null +++ b/include/rcs/ControllerConfig.h @@ -0,0 +1,56 @@ +#ifndef RCS_CONTROLLER_CONFIG_H +#define RCS_CONTROLLER_CONFIG_H + +#include +#include + +#include "Controller.h" +#include "Controllers.h" +#include "FR3Controllers.h" +#include "SafetyStage.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; + // damp towards the setpoint velocity instead of zero, see JointPD + bool velocity_feedforward = false; +}; + +// 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. 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 std::optional& safety, + double timestep); + +} // namespace common +} // namespace rcs +#endif // RCS_CONTROLLER_CONFIG_H diff --git a/include/rcs/Controllers.h b/include/rcs/Controllers.h new file mode 100644 index 00000000..8c4f486e --- /dev/null +++ b/include/rcs/Controllers.h @@ -0,0 +1,90 @@ +#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 +// 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, + bool velocity_feedforward = false); + 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; + bool velocity_feedforward; +}; + +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; + // 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; + // 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, +// 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 +// 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, + 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/include/rcs/EndEffector.h b/include/rcs/EndEffector.h new file mode 100644 index 00000000..a763384c --- /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/FR3Controllers.h b/include/rcs/FR3Controllers.h new file mode 100644 index 00000000..46603ac3 --- /dev/null +++ b/include/rcs/FR3Controllers.h @@ -0,0 +1,86 @@ +#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. + +// - 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(); +}; + +// 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); + 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; +}; + +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(); +}; + +// 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 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); + 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; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_FR3_CONTROLLERS_H diff --git a/include/rcs/Interpolator.h b/include/rcs/Interpolator.h new file mode 100644 index 00000000..5fc9d062 --- /dev/null +++ b/include/rcs/Interpolator.h @@ -0,0 +1,61 @@ +#ifndef RCS_INTERPOLATOR_H +#define RCS_INTERPOLATOR_H + +#include + +#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). +// +// 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. 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; +}; + +class CartesianInterpolator { + public: + virtual ~CartesianInterpolator() = default; + virtual void reset(const Pose& pose) = 0; + virtual void set_goal(const Pose& pose_goal, + std::optional duration = std::nullopt) = 0; + virtual CartesianSetpoint step(double dt) = 0; +}; + +} // namespace common +} // namespace rcs +#endif // RCS_INTERPOLATOR_H diff --git a/include/rcs/LinearInterpolator.h b/include/rcs/LinearInterpolator.h new file mode 100644 index 00000000..ba3ce215 --- /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/include/rcs/LinearPoseTrajInterpolator.h b/include/rcs/LinearPoseTrajInterpolator.h deleted file mode 100644 index ed126f42..00000000 --- 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 diff --git a/include/rcs/PinocchioDynamics.h b/include/rcs/PinocchioDynamics.h new file mode 100644 index 00000000..71b5d53b --- /dev/null +++ b/include/rcs/PinocchioDynamics.h @@ -0,0 +1,56 @@ +#ifndef RCS_PINOCCHIO_DYNAMICS_H +#define RCS_PINOCCHIO_DYNAMICS_H + +#include +#include + +#include "Controller.h" +#include "EndEffector.h" +#include "Pose.h" +#include "pinocchio/multibody/data.hpp" +#include "pinocchio/multibody/model.hpp" +#include "utils.h" + +namespace rcs { +namespace common { + +// 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/include/rcs/PyCopy.h b/include/rcs/PyCopy.h new file mode 100644 index 00000000..1ddfe01c --- /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/include/rcs/Robot.h b/include/rcs/Robot.h index 25ed354f..3715b938 100644 --- a/include/rcs/Robot.h +++ b/include/rcs/Robot.h @@ -4,9 +4,12 @@ #include #include #include +#include #include #include +#include "ControllerConfig.h" +#include "EndEffector.h" #include "Kinematics.h" #include "Pose.h" #include "utils.h" @@ -26,6 +29,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); } @@ -60,24 +66,39 @@ 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"; + // 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; - 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; + // 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() {}; }; + +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/include/rcs/SafetyStage.h b/include/rcs/SafetyStage.h new file mode 100644 index 00000000..ed424a42 --- /dev/null +++ b/include/rcs/SafetyStage.h @@ -0,0 +1,105 @@ +#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(); + + // 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; +}; + +// 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 +// 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 75ecf41f..244c77c6 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 @@ -118,6 +120,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/python/rcs/__init__.py b/python/rcs/__init__.py index 6db2f7ea..ae728e0c 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 @@ -135,10 +135,53 @@ 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""" + 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). + + 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() + 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=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 + ) + 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]), @@ -148,8 +191,20 @@ class RobotMetaConfig: [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, + # 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, 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]), @@ -175,8 +230,18 @@ class RobotMetaConfig: ], ] ), + # 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, 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 +253,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 +265,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 +284,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 +297,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 307ff9ef..db4e2498 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -11,6 +11,15 @@ import pybind11_stubgen.typing_ext __all__: list[str] = [ "BaseCameraConfig", + "CartesianController", + "CartesianInterpolator", + "CartesianSetpoint", + "ControllerState", + "EndEffectorConfig", + "FR3JointController", + "FR3JointControllerConfig", + "FR3OSC", + "FR3OSCConfig", "FrankaHandTCPOffset", "GraspType", "Gripper", @@ -25,11 +34,22 @@ __all__: list[str] = [ "IdentityRotMatrix", "IdentityRotQuatVec", "IdentityTranslation", + "JointController", + "JointInterpolator", + "JointPD", + "JointPDConfig", + "JointSetpoint", "Kinematics", "LATERAL_GRASP", + "LinearCartesianInterpolator", + "LinearJointInterpolator", + "OSC", + "OSCConfig", "POWER_GRASP", "PRECISION_GRASP", + "Payload", "Pin", + "PinocchioDynamics", "Pose", "RPY", "Robot", @@ -39,6 +59,10 @@ __all__: list[str] = [ "RobotType", "RotVec", "SIMULATION", + "SafeCartesianController", + "SafeJointController", + "SafetyConfig", + "SafetyStage", "TRIPOD_GRASP", ] M = typing.TypeVar("M", bound=int) @@ -48,9 +72,113 @@ 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: ... + 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: ... + 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 + 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 __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: + """ + 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]] + 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: + 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]] + 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: """ @@ -102,10 +230,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 = @@ -118,9 +262,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: ... @@ -140,22 +293,93 @@ 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: ... +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( + self, q_goal: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]], duration: float | None = None + ) -> 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]] + velocity_feedforward: bool + 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]], + velocity_feedforward: bool = False, + ) -> 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 + 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: ... @@ -163,6 +387,69 @@ 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]] + 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 + 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 + 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: ... + @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: + """ + 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 @@ -261,24 +548,34 @@ class Robot: 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 - tcp_offset: Pose + safety: SafetyConfig | None + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload 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", + end_effector: EndEffectorConfig = ..., + attachment_site: str = "", + 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: """ @@ -310,7 +607,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 = @@ -322,15 +627,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]]: ... @@ -339,6 +662,116 @@ class RotVec: self, ) -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... +class SafetyConfig: + 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 + def __init__( + self, + torque_limit: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] = ..., + max_torque_rate: float = ..., + 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: + """ + 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]]: ... + def reset(self, state: ControllerState) -> None: ... + +class FR3OSC(CartesianController): + def __init__(self, config: FR3OSCConfig, interpolator: CartesianInterpolator) -> None: ... + +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 __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: ... + +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, + velocity_feedforward: bool = False, + ) -> 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 __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__( self, diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index ca800634..6a1eea05 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: ... @@ -112,17 +135,25 @@ class SimConfig: memory: int realtime: bool renderer: RendererBackend - def __copy__(self) -> SimConfig: ... - def __deepcopy__(self, arg0: dict) -> SimConfig: ... + timestep: float + def __copy__(self) -> typing.Any: ... + def __deepcopy__(self, arg0: dict) -> typing.Any: ... + @typing.overload def __init__( self, 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: ... + @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: ... @@ -145,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, @@ -163,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 @@ -182,8 +229,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]): @@ -196,52 +247,34 @@ 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 = ..., - tcp_offset: rcs._core.common.Pose = ..., - attachment_site: str = "attachment_site", - kinematic_model_path: str = "assets/scenes/fr3_empty_world/robot.xml", + end_effector: rcs._core.common.EndEffectorConfig = ..., + attachment_site: str = "", + kinematic_model_path: str = "", 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", - dof: int = 7, + 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: @@ -261,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,6 +318,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: ... @@ -293,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 = ..., @@ -341,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/rcs/common_typing.py b/python/rcs/common_typing.py index 2611b284..ee76fd86 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 d79ad936..329b0ca3 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -33,10 +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( - 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, + 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, @@ -69,13 +68,13 @@ 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=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 @@ -179,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 @@ -274,10 +273,9 @@ 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, + 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, @@ -310,15 +308,15 @@ 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"] 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 @@ -445,9 +443,8 @@ 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.attachment_site = rcs.ROBOTS[rt].attachment_site - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path + rcs.ROBOTS[rt].apply(robot_cfg) + robot_cfg.end_effector.tcp_offset = GRIPPER_TCP_OFFSETS[rcs.common.GripperType.Robotiq2F85] robot_cfg.arm_collision_geoms = [] robot_cfg.joints = [ "shoulder_pan_joint", @@ -458,9 +455,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 +485,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 - 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 + rcs.ROBOTS[rt].apply(robot_cfg) + robot_cfg.end_effector.tcp_offset = rcs.common.Pose() robot_cfg.arm_collision_geoms = [] robot_cfg.joints = [ "joint1", @@ -514,9 +506,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 +526,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 - robot_cfg.tcp_offset = rcs.common.Pose() - robot_cfg.attachment_site = "gripper" - robot_cfg.kinematic_model_path = rcs.ROBOTS[rt].mjcf_model_path + rcs.ROBOTS[rt].apply(robot_cfg) + 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"] - 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 +562,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 - 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 + rcs.ROBOTS[rt].apply(robot_cfg) + 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"] - 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 +598,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 - 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 + rcs.ROBOTS[rt].apply(robot_cfg) + 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"] - 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 @@ -810,7 +784,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/rcs/envs/scenes.py b/python/rcs/envs/scenes.py index 6b783266..72962918 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 00000000..2620670e --- /dev/null +++ b/python/tests/test_controller_config.py @@ -0,0 +1,191 @@ +"""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, 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 + + +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] + + +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 new file mode 100644 index 00000000..2e3b6207 --- /dev/null +++ b/python/tests/test_controllers.py @@ -0,0 +1,113 @@ +"""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, 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 + + 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) + + @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 + 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): + with pytest.raises(ValueError, match="same size"): + 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 + 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/python/tests/test_copy.py b/python/tests/test_copy.py new file mode 100644 index 00000000..18dcf08f --- /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/python/tests/test_fr3_controllers.py b/python/tests/test_fr3_controllers.py new file mode 100644 index 00000000..cacbab74 --- /dev/null +++ b/python/tests/test_fr3_controllers.py @@ -0,0 +1,161 @@ +"""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 +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 +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() +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, 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, 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)) + if safety: + controller = common.SafeCartesianController(controller, SAFETY, JOINT_LIMITS, DT) + 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), SAFETY.torque_limit) + + +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[5] = JOINT_LIMITS[0, 5] + d0 + 0.5 * SAFETY.spring_range + state = dynamics.compute(q, np.zeros(7), DT) + controller = joint_controller(state) + for _ in range(20): # let the rate limit settle + tau = controller.step(state) + 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_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[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): + 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.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]) + 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.SafeCartesianController( + common.FR3OSC(common.FR3OSCConfig(), common.LinearCartesianInterpolator(0.05)), + 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])) + 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/python/tests/test_interpolators.py b/python/tests/test_interpolators.py new file mode 100644 index 00000000..488d8401 --- /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, match="duration"): + common.LinearJointInterpolator(0.0) + with pytest.raises(RuntimeError): + common.LinearJointInterpolator(DURATION).set_goal(self.goal) + with pytest.raises(ValueError, match="number of joints"): + 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, 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 new file mode 100644 index 00000000..7c392e8c --- /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, match="q and dq"): + dynamics.compute(np.zeros(6), np.zeros(6)) diff --git a/python/tests/test_robot_config.py b/python/tests/test_robot_config.py new file mode 100644 index 00000000..9fdbb218 --- /dev/null +++ b/python/tests/test_robot_config.py @@ -0,0 +1,87 @@ +"""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 + +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()) + + +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 + + +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 + + +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 + + +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_safety_stage.py b/python/tests/test_safety_stage.py new file mode 100644 index 00000000..c5949fa9 --- /dev/null +++ b/python/tests/test_safety_stage.py @@ -0,0 +1,150 @@ +"""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_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(): + 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 + + +@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/python/tests/test_sim_torque_control.py b/python/tests/test_sim_torque_control.py new file mode 100644 index 00000000..b23c49e3 --- /dev/null +++ b/python/tests/test_sim_torque_control.py @@ -0,0 +1,165 @@ +"""SimRobot under torque control with the shared controllers (1 ms timestep).""" + +import numpy as np +import pytest +from rcs.envs.configs import EmptyWorldFR3 + +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, async_control: bool = True): + scene = EmptyWorldFR3() + cfg = scene.prefixed_cfg(scene.config()) + name = scene.lead_robot_name(cfg) + robot_cfg = cfg.robot_cfgs[name] + robot_cfg.end_effector.payload = payload + model = scene.create_model(cfg) + if not friction: + for joint in model.spec.joints: + joint.frictionloss = 0.0 + 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) + 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_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, match="timestep"): + setup.sim.set_config(sim.SimConfig(timestep=0.0)) + + +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 b36004d8..c67fa63c 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -13,8 +13,14 @@ #include #include "rcs/Camera.h" +#include "rcs/ControllerConfig.h" +#include "rcs/Controllers.h" +#include "rcs/FR3Controllers.h" #include "rcs/Kinematics.h" +#include "rcs/LinearInterpolator.h" +#include "rcs/PinocchioDynamics.h" #include "rcs/Pose.h" +#include "rcs/PyCopy.h" #include "rcs/Robot.h" #include "rcs/utils.h" @@ -279,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) @@ -409,6 +407,253 @@ 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")); + + 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, "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") + .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); + + 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, bool>(), + py::arg("kp"), py::arg("kd"), py::arg("interpolator"), + py::arg("velocity_feedforward") = false); + + 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) + .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, + const rcs::common::VectorXd& kd, + bool velocity_feedforward) { + return rcs::common::JointPDConfig{kp, kd, velocity_feedforward}; + }), + 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("velocity_feedforward", + &rcs::common::JointPDConfig::velocity_feedforward); + + py::class_>(common, "OSC") + .def(py::init>(), + py::arg("config"), py::arg("interpolator")); + + py::class_(common, + "FR3JointControllerConfig") + .def(py::init<>()) + .def_readwrite("kp", &rcs::common::FR3JointControllerConfig::kp) + .def_readwrite("kd", &rcs::common::FR3JointControllerConfig::kd); + + 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); + + py::class_>(common, "FR3OSC") + .def(py::init>(), + py::arg("config"), py::arg("interpolator")); + + rcs::common::SafetyConfig default_safety_config; + py::class_(common, "SafetyConfig") + .def(py::init([](const rcs::common::VectorXd& torque_limit, + 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("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("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(), + 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) @@ -429,14 +674,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; @@ -448,7 +693,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, @@ -460,10 +705,12 @@ 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); + .def_readwrite("q_home", &rcs::common::RobotConfig::q_home) + .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") @@ -587,60 +834,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) @@ -661,14 +908,6 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("base", &rcs::sim::SimRobotConfig::base) .def_readwrite("dof", &rcs::sim::SimRobotConfig::dof) .def_readwrite("joint_limits", &rcs::sim::SimRobotConfig::joint_limits) - .def("__copy__", - [](const rcs::sim::SimRobotConfig& self) { - return rcs::sim::SimRobotConfig(self); - }) - .def("__deepcopy__", - [](const rcs::sim::SimRobotConfig& self, py::dict) { - return rcs::sim::SimRobotConfig(self); - }) .def("add_prefix", &rcs::sim::SimRobotConfig::add_prefix, py::arg("id")); py::class_(sim, "SimRobotState") @@ -676,6 +915,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) @@ -753,14 +993,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_( @@ -781,7 +1013,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; @@ -789,6 +1021,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, @@ -797,7 +1030,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) @@ -805,13 +1039,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("__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<>()) @@ -878,7 +1106,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_( @@ -946,15 +1181,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") @@ -979,4 +1206,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")); } diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index bd1eb07b..2d28c920 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 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 new file mode 100644 index 00000000..f1fb3f52 --- /dev/null +++ b/src/rcs/ControllerConfig.cpp @@ -0,0 +1,50 @@ +#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, + const std::optional& safety, + double timestep) { + 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(), 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)) { + controller.joint = + std::make_shared(*c, joint_interpolator()); + } else if (auto* c = std::get_if(&config)) { + controller.cartesian = + std::make_shared(*c, cartesian_interpolator()); + } + 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; +} + +} // namespace common +} // namespace rcs diff --git a/src/rcs/Controllers.cpp b/src/rcs/Controllers.cpp new file mode 100644 index 00000000..71962490 --- /dev/null +++ b/src/rcs/Controllers.cpp @@ -0,0 +1,110 @@ +#include "rcs/Controllers.h" + +#include +#include +#include + +namespace rcs { +namespace common { + +JointPD::JointPD(const VectorXd& kp, const VectorXd& kd, + 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"); + } + 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); + 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(dq_desired - 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& J = state.jacobian; + 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; + 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()); + const Vector6d v_desired = + this->config.velocity_feedforward ? setpoint.twist : Vector6d::Zero(); + Vector6d F = + kp.cwiseProduct(error) + kd.cwiseProduct(v_desired - J * state.dq); + + // task-space inertia + Eigen::Matrix L = (J * M_inv * J.transpose()) + .completeOrthogonalDecomposition() + .pseudoInverse(); + VectorXd tau = J.transpose() * (L * F); + + // 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 = + M * (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 diff --git a/src/rcs/FR3Controllers.cpp b/src/rcs/FR3Controllers.cpp new file mode 100644 index 00000000..5ce217b7 --- /dev/null +++ b/src/rcs/FR3Controllers.cpp @@ -0,0 +1,144 @@ +#include "rcs/FR3Controllers.h" + +#include +#include +#include + +namespace rcs { +namespace common { + +namespace { + +// 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(); +} + +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); +} + +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 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); +} + +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); + + tau += state.coriolis; + return tau; +} + +} // namespace common +} // namespace rcs diff --git a/src/rcs/LinearInterpolator.cpp b/src/rcs/LinearInterpolator.cpp new file mode 100644 index 00000000..7aa79b3e --- /dev/null +++ b/src/rcs/LinearInterpolator.cpp @@ -0,0 +1,106 @@ +#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); +} + +} // 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 diff --git a/src/rcs/PinocchioDynamics.cpp b/src/rcs/PinocchioDynamics.cpp new file mode 100644 index 00000000..fef31eb8 --- /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 diff --git a/src/rcs/SafetyStage.cpp b/src/rcs/SafetyStage.cpp new file mode 100644 index 00000000..e435089f --- /dev/null +++ b/src/rcs/SafetyStage.cpp @@ -0,0 +1,150 @@ +#include "rcs/SafetyStage.h" + +#include +#include +#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"); + } + 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( + "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"); + } +} + +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 max_step = this->config.max_torque_rate * this->timestep; + const SafetyConfig& c = this->config; + for (Eigen::Index i = 0; i < tau.size(); i++) { + 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] + + 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 6e785cee..a90af0e0 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,8 +111,22 @@ void SimRobot::init_ids() { } bool SimRobot::set_config(const SimRobotConfig& 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"); + } 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()) { + this->install_configured_controller(); + } + } + 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()) { @@ -134,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() { @@ -147,10 +172,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,8 +213,20 @@ 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); + this->cfg.end_effector.tcp_offset); if (joint_vals.has_value()) { this->state.ik_success = true; this->set_joint_position(joint_vals.value()); @@ -193,6 +244,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 +298,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 +318,213 @@ 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(); + 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->cfg.safety, sim_cfg.timestep); + 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() { + 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.end_effector.payload.has_value()) { + this->dynamics->set_payload(simulated); + return; + } + 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 || + (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 56d70111..fcb5c486 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 @@ -13,24 +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 { - common::RobotPlatform robot_platform = common::RobotPlatform::SIMULATION; + 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"; @@ -53,6 +49,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 +79,22 @@ 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. 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); + 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 +107,18 @@ 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 install_configured_controller(); + 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(); diff --git a/src/sim/sim.cpp b/src/sim/sim.cpp index a55221fd..91208120 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 60c50322..5b7ff82c 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -22,13 +22,17 @@ 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 diff --git a/src/sim/test.cpp b/src/sim/test.cpp index 42436a74..8b4c9172 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);