From c8ecd7e7b089878efe2ca746c9580e5632c94c8b Mon Sep 17 00:00:00 2001 From: Bulban <147950706+Bulban@users.noreply.github.com> Date: Mon, 20 Jul 2026 20:47:12 +0200 Subject: [PATCH 1/5] Add ldlt based torque allocation --- CMakeLists.txt | 25 +- include/config.hpp | 87 +++++-- include/orchestrator.hpp | 116 ++++++++-- include/ros_interface.hpp | 276 +++++++++++++++++++++-- include/tv/kinematic_force_estimator.hpp | 116 ++++++---- include/tv/ldlt_torque_allocator.hpp | 178 +++++++++++++++ include/tv/pid_yaw_controller.hpp | 187 ++++++++------- include/tv/qp_torque_allocator.hpp | 208 ++++++++++++----- include/types.hpp | 24 +- launch/launch.py | 17 +- package.xml | 4 +- src/main.cpp | 24 +- 12 files changed, 999 insertions(+), 263 deletions(-) create mode 100644 include/tv/ldlt_torque_allocator.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 72d3b60..1a1bd1c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,14 +2,12 @@ cmake_minimum_required(VERSION 3.8) project(torque_vectoring_pkg) -# Default to C++17 -if(NOT CMAKE_CXX_STANDARD) - set(CMAKE_CXX_STANDARD 20) - set(CMAKE_CXX_STANDARD_REQUIRED ON) -endif() +# C++20 — required for the concepts in interfaces.hpp +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) + add_compile_options(-Wall -Wextra -Wpedantic -DDEBUG) endif() set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -19,30 +17,29 @@ find_package(ament_cmake REQUIRED) find_package(rclcpp REQUIRED) find_package(std_msgs REQUIRED) find_package(sensor_msgs REQUIRED) +find_package(nav_msgs REQUIRED) find_package(Eigen3 REQUIRED) -find_package(OsqpEigen REQUIRED) find_package(vehicle_params_cpp REQUIRED) find_package(ros2can_msgs REQUIRED) find_package(fs_msgs REQUIRED) -# Include directories -include_directories(include) - # C++ executable add_executable(torque_vectoring_node src/main.cpp) +target_include_directories(torque_vectoring_node PRIVATE include) + ament_target_dependencies(torque_vectoring_node rclcpp std_msgs sensor_msgs + nav_msgs fs_msgs ros2can_msgs ) -target_link_libraries(torque_vectoring_node - Eigen3::Eigen - OsqpEigen::OsqpEigen - vehicle_params_cpp::vehicle_params_cpp +target_link_libraries(torque_vectoring_node + Eigen3::Eigen + vehicle_params_cpp::vehicle_params_cpp ) # Install C++ executables diff --git a/include/config.hpp b/include/config.hpp index 8743439..ca5cf62 100644 --- a/include/config.hpp +++ b/include/config.hpp @@ -10,6 +10,9 @@ namespace tv { +// Standard gravity [m/s²] — shared by the load-transfer model and grip clamps. +inline constexpr double kGravity{9.81}; + // ----------------------------------------------------------------------------- // Vehicle physical properties — shared across all three layers // ----------------------------------------------------------------------------- @@ -19,68 +22,104 @@ struct VehicleConfig { kthfs::vehicle::dev19::cg_height_m}; // centre-of-gravity height [m] static constexpr double wheelbase{ kthfs::vehicle::dev19::wheelbase_m}; // front-to-rear axle distance [m] - static constexpr double l_r{0.82}; // rear axle to CG [m] → l_f = wheelbase - l_r + static constexpr double l_r{0.705}; // rear axle to CG [m] → l_f = wheelbase - l_r static constexpr double trackwidth_front{ kthfs::vehicle::dev19::track_width_m}; // front track width [m] static constexpr double trackwidth_rear{ kthfs::vehicle::dev19::track_width_m}; // rear track width [m] static constexpr double front_tlltd{ - 0.45}; // front TLLTD fraction (0 = all rear, 1 = all front) + 0.40}; // front TLLTD fraction (0 = all rear, 1 = all front) static constexpr double wheel_radius{ kthfs::vehicle::dev19::tire_radius_m}; // effective wheel radius [m] static constexpr double mu{1.6}; // tyre-road friction coefficient - static constexpr double t_max{21.0 * 14}; // per-wheel motor torque limit [Nm] + static constexpr double gear_ratio{13.5}; // motor → wheel gear ratio + static constexpr double motor_t_max{21.0}; // per-wheel motor peak torque [Nm] + static constexpr double t_max{motor_t_max * + gear_ratio}; // per-wheel wheel-side torque cap [Nm] }; // ----------------------------------------------------------------------------- -// Aerodynamic and rolling-resistance losses — SmcYawController Fx feedforward +// Aerodynamic and rolling-resistance losses — reserved for a future Fx loss +// feedforward in the longitudinal tracker (currently unused) // ----------------------------------------------------------------------------- struct AeroConfig { static constexpr double rho{1.225}; // air density [kg/m³] (1.225 at sea level, 15 °C) static constexpr double c_d{kthfs::vehicle::dev19::drag_coefficient}; // drag coefficient static constexpr double frontal_area{ kthfs::vehicle::dev19::frontal_area}; // frontal reference area [m²] - static constexpr double c_rr = - 0.0 {kthfs::vehicle::dev19::rolling_resistance}; // rolling resistance coefficient + static constexpr double c_rr{ + kthfs::vehicle::dev19::rolling_resistance}; // rolling resistance coefficient }; // ----------------------------------------------------------------------------- // Driving Force Observer — KinematicForceEstimator // ----------------------------------------------------------------------------- struct ForceEstimatorConfig { - static constexpr double j_w{0.5}; // wheel + motor rotational inertia [kg·m²] - static constexpr double lpf_tau{0.02}; // DFO low-pass filter time constant [s] + static constexpr double j_w{0.5}; // rotational inertia referred to the wheel [kg·m²] + // (includes motor inertia reflected as J_motor·N²) + static constexpr double eta{1.0}; // drivetrain efficiency (motor → wheel), (0, 1] + static constexpr double lpf_tau{0.10}; // DFO low-pass filter time constant [s] // smaller → faster but noisier Fx estimate }; // ----------------------------------------------------------------------------- -// Bicycle model — SmcYawController feedforward (steady-state yaw moment) +// Bicycle model — reserved for a future steady-state yaw-moment feedforward +// (currently unused) // ----------------------------------------------------------------------------- struct BicycleModelConfig { - static constexpr double c_f{ - kthfs::vehicle::dev19::cornerings_stiffness_n_rad}; // front axle cornering stiffness - // [N/rad] - static constexpr double c_r{ - kthfs::vehicle::dev19::cornerings_stiffness_n_rad}; // rear axle cornering stiffness - // [N/rad] typical FS values: 40 000–70 - // 000 N/rad + // dev19::cornerings_stiffness_n_rad is a per-TIRE value; the bicycle model needs + // per-AXLE stiffness, so multiply by 2 (two tires per axle). + static constexpr double c_f{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * + 2.0}; // front axle cornering stiffness [N/rad] + static constexpr double c_r{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * + 2.0}; // rear axle cornering stiffness [N/rad] + // typical FS values: 40 000–70 000 N/rad }; struct PIDYawControllerConfig { - static constexpr double kp{0.5}; // Proportional term for yaw rate error tracking - static constexpr double ki{0.1}; // Integral term for yaw rate error tracking + static constexpr double kp{250}; // Proportional term for yaw rate error tracking + static constexpr double ki{50}; // Integral term for yaw rate error tracking + static constexpr double kd{20}; // Derivative term on the yaw-rate error + static constexpr double i_max{ + 1000.0}; // yaw integral-term saturation [Nm] — symmetric anti-windup clamp. + // Tune to the yaw-moment authority the allocator can realise. + static constexpr double d_tau{ + 0.02}; // low-pass time constant on the derivative term [s]. The yaw-rate + // error comes straight from the gyro, so the raw derivative is + // noise-dominated; this filters it before applying kd. }; struct LongitudinalPiConfig { - static constexpr double k_p{2.0}; // proportional gain [1/s] - static constexpr double k_i{0.0}; // integral gain [1/s²] - static constexpr double eta{0.0}; // drivetrain efficiency + static constexpr double k_p{2.0}; // proportional gain [1/s] — velocity-loop bandwidth. + // Full Fx (grip clamp μg≈15.7 m/s²) is reached at a + // velocity error of μg/k_p; keep k_p low (~1–3) so + // tracking noise doesn't slam the demand to saturation. + static constexpr double k_i{1.0}; // integral gain [1/s²] + static constexpr double b{0.8}; // setpoint weight on the proportional term (2-DoF PI), + // [0, 1]. 1 → classic PI; <1 softens the proportional + // kick on reference steps without changing disturbance + // rejection (the integral still sees the full error). + static constexpr double eta{1.0}; // drivetrain efficiency + static constexpr double vx_ref_rate{ + 5.0}; // max rate of change of the velocity reference [m/s²]. Ramps vx_ref so a + // step target (e.g. launch from rest) doesn't slam Fx to saturation. + // Keep below the grip limit μ·g ≈ 15.7 m/s². }; struct AllocatorConfig { - static constexpr double w_fx{1.0}; // Fx tracking weight - static constexpr double w_mz{10.0}; // Mz tracking weight - static constexpr double w_reg{0.001}; // torque magnitude regularisation + static constexpr double w_fx{4.0}; // Fx tracking weight + static constexpr double w_mz{10.0}; // Mz tracking weight + static constexpr double w_reg{0.01}; // torque magnitude regularisation +}; + +// ----------------------------------------------------------------------------- +// ROS node behaviour +// ----------------------------------------------------------------------------- +struct NodeConfig { + static constexpr double input_timeout{ + 0.3}; // max age of the latest cmd_in / odom message [s]. If either input + // is older (or was never received), the node commands zero torque + // instead of acting on stale references. }; struct Config { diff --git a/include/orchestrator.hpp b/include/orchestrator.hpp index 69ac087..4c5700b 100644 --- a/include/orchestrator.hpp +++ b/include/orchestrator.hpp @@ -1,7 +1,9 @@ #pragma once +#include #include -#include +#include +#include #include #include "interfaces.hpp" @@ -9,6 +11,27 @@ namespace tv { +// Online mean / sample standard deviation (Welford's algorithm) — numerically +// stable, O(1) memory. Used for the per-stage timing statistics. +class RunningStat { + public: + void add(double x) noexcept { + ++n_; + const double delta = x - mean_; + mean_ += delta / static_cast(n_); + m2_ += delta * (x - mean_); + } + [[nodiscard]] double mean() const noexcept { return mean_; } + [[nodiscard]] double stddev() const noexcept { + return n_ > 1 ? std::sqrt(m2_ / static_cast(n_ - 1)) : 0.0; + } + + private: + std::uint64_t n_{0}; + double mean_{0.0}; + double m2_{0.0}; // sum of squared deviations from the running mean +}; + /// Runs the full torque vectoring pipeline: /// VehicleState -> ForceEstimator -> YawMomentGenerator -> TorqueAllocator -> WheelTorques template @@ -20,27 +43,78 @@ class Orchestrator { torque_allocator_(std::move(torque_allocator)) {} /// Execute the full pipeline for the given vehicle state and driver inputs. - [[nodiscard]] WheelTorques run(const VehicleState& state, const SteeringCommand& cmd) { - auto start = std::chrono::high_resolution_clock::now(); + /// `dt` is the elapsed time since the previous call [s]; it is forwarded to + /// any stage that needs a control period (e.g. the yaw controller's + /// integrators). Stages that do not expose setDt() are left untouched. + /// Returns the final wheel torques together with every intermediate signal + /// (tyre forces, yaw moment command) and per-stage execution times — this + /// cycle plus running mean / standard deviation since startup — so callers + /// can publish them for debug. Timing is measured with steady_clock and + /// returned rather than printed — no blocking I/O in the control loop. + /// `alloc_ok` is false when the allocator reported a failed solve (it holds + /// its previous solution), so callers can warn. + [[nodiscard]] PipelineResult run(const VehicleState& state, const SteeringCommand& cmd, + double dt) { + // Forward the control period to stages that track one. Kept optional via + // `requires` so the generic concepts don't have to mandate setDt(). + if constexpr (requires(Y& y) { y.setDt(dt); }) { + yaw_generator_.setDt(dt); + } + + using Clock = std::chrono::steady_clock; + const auto start = Clock::now(); const ForceVector forces = force_estimator_.estimateForces(state); - auto forces_time = std::chrono::high_resolution_clock::now(); + const auto t_forces = Clock::now(); const YawMomentCommand yaw_cmd = yaw_generator_.compute(state, forces, cmd); - auto yaw_moment = std::chrono::high_resolution_clock::now(); + const auto t_yaw = Clock::now(); const auto allocated_torques = torque_allocator_.allocate(state, yaw_cmd, forces); - auto allocator = std::chrono::high_resolution_clock::now(); - auto forces_duration = - std::chrono::duration_cast(forces_time - start); - std::cout << &"Force calculation duration: "[forces_duration.count()] << std::endl; - auto yaw_duration = - std::chrono::duration_cast(yaw_moment - forces_time); - std::cout << &"yaw calculation duration: "[yaw_duration.count()] << std::endl; - auto allocator_duration = - std::chrono::duration_cast(allocator - yaw_moment); - std::cout << &"allocator calculation duration: "[allocator_duration.count()] << std::endl; - auto total_duration = - std::chrono::duration_cast(allocator - start); - std::cout << &"total calculation duration: "[total_duration.count()] << std::endl; - return allocated_torques; + const auto t_alloc = Clock::now(); + + const auto us = [](Clock::time_point a, Clock::time_point b) { + return std::chrono::duration(b - a).count(); + }; + const StageTimings timings{.forces_us = us(start, t_forces), + .yaw_us = us(t_forces, t_yaw), + .alloc_us = us(t_yaw, t_alloc), + .total_us = us(start, t_alloc)}; + timing_stats_[0].add(timings.forces_us); + timing_stats_[1].add(timings.yaw_us); + timing_stats_[2].add(timings.alloc_us); + timing_stats_[3].add(timings.total_us); + + // Surface a failed allocation when the stage reports one. Kept optional + // via `requires` so the generic concepts don't have to mandate it. + bool alloc_ok = true; + if constexpr (requires(const A& a) { + { a.lastSolveOk() } -> std::convertible_to; + }) { + alloc_ok = torque_allocator_.lastSolveOk(); + } + + return PipelineResult{.forces = forces, + .yaw_cmd = yaw_cmd, + .torques = allocated_torques, + .timings = timings, + .timings_avg = StageTimings{.forces_us = timing_stats_[0].mean(), + .yaw_us = timing_stats_[1].mean(), + .alloc_us = timing_stats_[2].mean(), + .total_us = timing_stats_[3].mean()}, + .timings_std = StageTimings{.forces_us = timing_stats_[0].stddev(), + .yaw_us = timing_stats_[1].stddev(), + .alloc_us = timing_stats_[2].stddev(), + .total_us = timing_stats_[3].stddev()}, + .alloc_ok = alloc_ok}; + } + + /// Forward per-wheel feedback (motor torque, wheel angular velocity, and the + /// sample period between wheel-speed messages) to the force-estimation stage, + /// when that stage consumes it. No-op for stages that don't expose it, so the + /// generic concepts don't have to mandate updateWheelState(). + void updateWheelState(const WheelTorques& motor_torques, const WheelOmegas& wheel_omegas, + double dt) { + if constexpr (requires(F& f) { f.updateWheelState(motor_torques, wheel_omegas, dt); }) { + force_estimator_.updateWheelState(motor_torques, wheel_omegas, dt); + } } [[nodiscard]] const F& forceEstimator() const noexcept { return force_estimator_; } @@ -51,6 +125,10 @@ class Orchestrator { F force_estimator_; Y yaw_generator_; A torque_allocator_; + + // Per-stage timing statistics [forces, yaw, alloc, total], accumulated over + // the whole run. + std::array timing_stats_{}; }; // CTAD: Orchestrator{f, y, a} deduces template args without explicit spelling diff --git a/include/ros_interface.hpp b/include/ros_interface.hpp index a53d3f9..1572228 100644 --- a/include/ros_interface.hpp +++ b/include/ros_interface.hpp @@ -2,13 +2,21 @@ #include +#include +#include + +#include #include #include +#include #include +#include "config.hpp" #include "fs_msgs/msg/car_command.hpp" +#include "fs_msgs/msg/wheelspeeds.hpp" #include "orchestrator.hpp" #include "ros2can_msgs/msg/dv_control_target_tv.hpp" +#include "ros2can_msgs/msg/vehicle_status_motor_torques.hpp" #include "types.hpp" namespace tv { @@ -16,19 +24,19 @@ namespace tv { /// ROS2 node that wraps the full torque-vectoring pipeline. /// /// Subscriptions: -/// ~/imu/data sensor_msgs/Imu — yaw_rate, ax, ay -/// ~/steering_command std_msgs/Float64MultiArray[3] — [steering_angle (rad), vx_ref (m/s), -/// r_ref (rad/s)] +/// imu sensor_msgs/Imu — yaw_rate, ax, ay +/// odom nav_msgs/Odometry — body velocities vx, vy +/// wheel_speeds fs_msgs/Wheelspeeds — per-wheel ω [FL,FR,RL,RR] (rad/s) +/// motor_torques ros2can_msgs/VehicleStatusMotorTorques — per-wheel motor torque (Nm) +/// cmd_in fs_msgs/CarCommand — steering_angle [deg], vx_ref, r_ref /// /// Publication: -/// ~/wheel_torques std_msgs/Float64MultiArray[4] — [T_FL, T_FR, T_RL, T_RR] (Nm) -/// -/// NOTE: VehicleState fields vx and vy (indices 0 and 1) are initialised to zero and -/// never updated by this node. Add an odometry subscriber if the controllers -/// require actual body velocities. +/// cmd_out ros2can_msgs/DvControlTargetTv — per-wheel targets + steering /// -/// The pipeline is triggered on every IMU message. Steering updates are applied -/// immediately on receipt and will take effect on the next IMU tick. +/// The pipeline is triggered on every IMU message. Odometry, wheel-speed, +/// motor-torque and steering updates are cached on receipt and take effect on +/// the next IMU tick. Wheel-speed messages carry their own sample period, used +/// by the DFO force estimator. template class TVNode : public rclcpp::Node { public: @@ -39,12 +47,48 @@ class TVNode : public rclcpp::Node { "imu", rclcpp::SensorDataQoS(), [this](sensor_msgs::msg::Imu::SharedPtr msg) { imuCallback(msg); }); + odom_sub_ = create_subscription( + "odom", rclcpp::SensorDataQoS(), + [this](nav_msgs::msg::Odometry::SharedPtr msg) { odomCallback(msg); }); + + wheel_speeds_sub_ = create_subscription( + "wheel_speeds", rclcpp::SensorDataQoS(), + [this](fs_msgs::msg::Wheelspeeds::SharedPtr msg) { wheelSpeedsCallback(msg); }); + + motor_torques_sub_ = create_subscription( + "motor_torques", 10, + [this](ros2can_msgs::msg::VehicleStatusMotorTorques::SharedPtr msg) { + motorTorquesCallback(msg); + }); + steering_sub_ = create_subscription( - "/navigation/dv_control_target_tv", 10, + "cmd_in", 10, [this](fs_msgs::msg::CarCommand::SharedPtr msg) { steeringCallback(msg); }); - torque_pub_ = create_publisher( - "ros2can/send/dv_control_target_tv", 10); + torque_pub_ = create_publisher("cmd_out", 10); + + // Debug publishers for every intermediate pipeline signal. These carry no + // control meaning — they exist for telemetry/plotting (rqt_plot, PlotJuggler). + // Wheel order for the array topics is [FL, FR, RL, RR]. + tire_fx_pub_ = create_publisher("debug/tire_fx", 10); + tire_fy_pub_ = create_publisher("debug/tire_fy", 10); + tire_fz_pub_ = create_publisher("debug/tire_fz", 10); + yaw_moment_pub_ = + create_publisher("debug/yaw_moment", 10); + wheel_torques_pub_ = + create_publisher("debug/wheel_torques", 10); + timing_pub_ = create_publisher("debug/timing", 10); + tracking_pub_ = create_publisher("debug/tracking", 10); + +#ifdef DEBUG + // Achieved virtual demand *after* the QP allocation, reconstructed from the + // allocated wheel torques. Divergence from debug/yaw_moment (the requested + // demand) shows how far the box/friction constraints pushed the solution off + // the request. + alloc_yaw_moment_pub_ = + create_publisher("debug/alloc_yaw_moment", 10); + alloc_fx_total_pub_ = create_publisher("debug/alloc_fx_total", 10); +#endif } private: @@ -53,31 +97,225 @@ class TVNode : public rclcpp::Node { state_.ax_ = msg->linear_acceleration.x; // ax [m/s²] state_.ay_ = msg->linear_acceleration.y; // ay [m/s²] - const WheelTorques torques = orchestrator_.run(state_, steering_cmd_); + // Control period since the previous IMU tick, used by the stage + // integrators. Guarded so the first tick (and any out-of-order or + // duplicate stamps) yields dt = 0 rather than a bogus/negative step. + const rclcpp::Time stamp(msg->header.stamp); + double dt = 0.0; + if (have_last_stamp_ && stamp > last_stamp_) { + dt = (stamp - last_stamp_).seconds(); + } + last_stamp_ = stamp; + have_last_stamp_ = true; + + // Input watchdog: if driver commands or odometry are stale (or were never + // received), command zero torque instead of acting on old references. + const rclcpp::Time now_time = now(); + const auto is_stale = [&](bool received, const rclcpp::Time& last_rx) { + return !received || (now_time - last_rx).seconds() > NodeConfig::input_timeout; + }; + if (is_stale(have_cmd_, last_cmd_rx_) || is_stale(have_odom_, last_odom_rx_)) { + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 1000, + "cmd_in/odom stale or missing — commanding zero torque"); + ros2can_msgs::msg::DvControlTargetTv out; // torque targets default to zero + out.dv_steering_angle_target_tv = + steering_cmd_.steering_angle_ * (180.0 / std::numbers::pi); + torque_pub_->publish(out); + return; + } + + const PipelineResult result = orchestrator_.run(state_, steering_cmd_, dt); + const WheelTorques& torques = result.torques; + + // The allocator holds its previous solution on a failed solve — surface it. + if (!result.alloc_ok) { + ++alloc_failures_; + RCLCPP_WARN_THROTTLE( + get_logger(), *get_clock(), 1000, + "torque allocation failed (%lu total) — holding previous solution", + static_cast(alloc_failures_)); + } ros2can_msgs::msg::DvControlTargetTv out; - out.dv_steering_angle_target_tv = steering_cmd_.steering_angle_; + // steering_angle_ is stored in radians internally; the CAN target expects degrees. + out.dv_steering_angle_target_tv = steering_cmd_.steering_angle_ * (180.0 / std::numbers::pi); out.dv_fl_speedd_target = torques[0]; out.dv_fr_speed_target = torques[1]; out.dv_rl_speed_target = torques[2]; out.dv_rr_speed_target = torques[3]; torque_pub_->publish(out); + + publishDebug(result); + } + + // Publishes each intermediate pipeline stage on its own debug topic. + void publishDebug(const PipelineResult& result) { + const auto to_msg = [](const std::array& src) { + std_msgs::msg::Float64MultiArray msg; + msg.data.assign(src.begin(), src.end()); + return msg; + }; + + // Stage 1 — tyre force estimate (per wheel). + tire_fx_pub_->publish(to_msg(result.forces.fx_)); + tire_fy_pub_->publish(to_msg(result.forces.fy_)); + tire_fz_pub_->publish(to_msg(result.forces.fz_)); + + // Stage 2 — high-level yaw moment command: [mz (Nm), fx_total (N)]. + std_msgs::msg::Float64MultiArray yaw_msg; + yaw_msg.data = {result.yaw_cmd.mz_, result.yaw_cmd.fx_total_}; + yaw_moment_pub_->publish(yaw_msg); + + // Stage 3 — allocated wheel torques [FL, FR, RL, RR] (Nm). + std_msgs::msg::Float64MultiArray torque_msg; + torque_msg.data = {result.torques[0], result.torques[1], result.torques[2], + result.torques[3]}; + wheel_torques_pub_->publish(torque_msg); + + // Per-stage pipeline execution times (µs), three blocks of + // [forces, yaw, alloc, total]: this cycle, running mean, and running + // standard deviation since startup. + std_msgs::msg::Float64MultiArray timing_msg; + timing_msg.data = {result.timings.forces_us, result.timings.yaw_us, + result.timings.alloc_us, result.timings.total_us, + result.timings_avg.forces_us, result.timings_avg.yaw_us, + result.timings_avg.alloc_us, result.timings_avg.total_us, + result.timings_std.forces_us, result.timings_std.yaw_us, + result.timings_std.alloc_us, result.timings_std.total_us}; + timing_pub_->publish(timing_msg); + + // Controller tracking: [r_ref, r, r_ref − r, vx_ref, vx, vx_ref − vx]. + // A yaw-rate error that never changes sign (or r_ref/r with opposite + // signs in a corner) points at a reference sign/unit mismatch or the + // yaw integral riding its clamp — the usual causes of a standing + // left/right torque split. + std_msgs::msg::Float64MultiArray tracking_msg; + tracking_msg.data = {steering_cmd_.r_ref_, + state_.yaw_rate_, + steering_cmd_.r_ref_ - state_.yaw_rate_, + steering_cmd_.vx_ref_, + state_.vx_, + steering_cmd_.vx_ref_ - state_.vx_}; + tracking_pub_->publish(tracking_msg); + +#ifdef DEBUG + // Achieved [Mz, Fx_total] after allocation. Undo the allocator's output map + // (T_motor = F·R / gear_ratio) to recover the per-wheel driving force + // F = T·gear_ratio / R, then apply the dependency matrix G (wheel order + // [FL, FR, RL, RR]): + // Fx_total = F_FL + F_FR + F_RL + F_RR + // Mz = -sf·F_FL + sf·F_FR - sr·F_RL + sr·F_RR + const double sf = VehicleConfig::trackwidth_front / 2.0; + const double sr = VehicleConfig::trackwidth_rear / 2.0; + std::array f{}; // per-wheel driving force [N], [FL, FR, RL, RR] + for (int i = 0; i < 4; ++i) { + f[i] = result.torques[i] * VehicleConfig::gear_ratio / VehicleConfig::wheel_radius; + } + + std_msgs::msg::Float64 alloc_fx_msg; + alloc_fx_msg.data = f[0] + f[1] + f[2] + f[3]; + alloc_fx_total_pub_->publish(alloc_fx_msg); + + std_msgs::msg::Float64 alloc_mz_msg; + alloc_mz_msg.data = (-sf * f[0]) + (sf * f[1]) + (-sr * f[2]) + (sr * f[3]); + alloc_yaw_moment_pub_->publish(alloc_mz_msg); +#endif } void steeringCallback(const fs_msgs::msg::CarCommand::SharedPtr& msg) { - steering_cmd_.steering_angle_ = msg->steering; // steering_angle [rad] - steering_cmd_.vx_ref_ = msg->velocity; // vx_ref [m/s] - steering_cmd_.r_ref_ = msg->yaw_rate; // r_ref [rad/s] - state_.steering_angle_ = msg->steering; // mirror into VehicleState + // CarCommand.steering is a road-wheel angle in degrees; the pipeline works + // in radians throughout, so convert on ingress. + const double steering_rad = msg->steering * (std::numbers::pi / 180.0); + + steering_cmd_.steering_angle_ = steering_rad; // steering_angle [rad] + steering_cmd_.vx_ref_ = msg->velocity; // vx_ref [m/s] + steering_cmd_.r_ref_ = msg->yaw_rate; // r_ref [rad/s] + state_.steering_angle_ = steering_rad; // mirror into VehicleState + + last_cmd_rx_ = now(); + have_cmd_ = true; + } + + // Body-frame velocities from odometry; consumed on the next IMU tick. + void odomCallback(const nav_msgs::msg::Odometry::SharedPtr& msg) { + state_.vx_ = msg->twist.twist.linear.x; // vx [m/s] + state_.vy_ = msg->twist.twist.linear.y; // vy [m/s] + + last_odom_rx_ = now(); + have_odom_ = true; + } + + // Per-wheel angular velocities [FL, FR, RL, RR] (rad/s) for the DFO. The + // sample period is derived from consecutive wheel-speed stamps and forwarded + // to the force estimator together with the latest motor-torque feedback. + void wheelSpeedsCallback(const fs_msgs::msg::Wheelspeeds::SharedPtr& msg) { + WheelOmegas omegas; + omegas << msg->front_left, msg->front_right, msg->rear_left, msg->rear_right; + + const rclcpp::Time stamp(msg->header.stamp); + double dt = 0.0; + if (have_last_wheel_stamp_ && stamp > last_wheel_stamp_) { + dt = (stamp - last_wheel_stamp_).seconds(); + } + last_wheel_stamp_ = stamp; + have_last_wheel_stamp_ = true; + + orchestrator_.updateWheelState(motor_torques_, omegas, dt); + } + + // Latest per-wheel motor-torque feedback [FL, FR, RL, RR] (Nm), cached for + // the DFO (published at a slower rate than the wheel speeds). + void motorTorquesCallback(const ros2can_msgs::msg::VehicleStatusMotorTorques::SharedPtr& msg) { + motor_torques_ << msg->torque_fl, msg->torque_fr, msg->torque_rl, msg->torque_rr; } rclcpp::Subscription::SharedPtr imu_sub_; + rclcpp::Subscription::SharedPtr odom_sub_; + rclcpp::Subscription::SharedPtr wheel_speeds_sub_; + rclcpp::Subscription::SharedPtr motor_torques_sub_; rclcpp::Subscription::SharedPtr steering_sub_; rclcpp::Publisher::SharedPtr torque_pub_; + // Debug publishers for intermediate pipeline stages. + rclcpp::Publisher::SharedPtr tire_fx_pub_; + rclcpp::Publisher::SharedPtr tire_fy_pub_; + rclcpp::Publisher::SharedPtr tire_fz_pub_; + rclcpp::Publisher::SharedPtr yaw_moment_pub_; + rclcpp::Publisher::SharedPtr wheel_torques_pub_; + rclcpp::Publisher::SharedPtr timing_pub_; + rclcpp::Publisher::SharedPtr tracking_pub_; + +#ifdef DEBUG + // Achieved yaw moment / total Fx reconstructed from the allocated torques. + rclcpp::Publisher::SharedPtr alloc_yaw_moment_pub_; + rclcpp::Publisher::SharedPtr alloc_fx_total_pub_; +#endif + Orchestrator orchestrator_; VehicleState state_{}; // vx_, vy_, yaw_rate_, steering_angle_, ax_, ay_ SteeringCommand steering_cmd_{}; // steering_angle_, vx_ref_, r_ref_ + + // Latest per-wheel motor-torque feedback [FL, FR, RL, RR] (Nm) for the DFO. + WheelTorques motor_torques_{WheelTorques::Zero()}; + + // Timestamp of the previous IMU message, used to derive the control period. + rclcpp::Time last_stamp_{0, 0, RCL_ROS_TIME}; + bool have_last_stamp_{false}; + + // Timestamp of the previous wheel-speed message, used to derive the DFO + // sample period. + rclcpp::Time last_wheel_stamp_{0, 0, RCL_ROS_TIME}; + bool have_last_wheel_stamp_{false}; + + // Receive times of the latest cmd_in / odom messages (node clock), for the + // input watchdog — stale inputs make the node command zero torque. + rclcpp::Time last_cmd_rx_{0, 0, RCL_ROS_TIME}; + bool have_cmd_{false}; + rclcpp::Time last_odom_rx_{0, 0, RCL_ROS_TIME}; + bool have_odom_{false}; + + // Count of control cycles where the allocator fell back to zero torque. + std::size_t alloc_failures_{0}; }; // CTAD deduction guides diff --git a/include/tv/kinematic_force_estimator.hpp b/include/tv/kinematic_force_estimator.hpp index 2bf9cc9..4fef485 100644 --- a/include/tv/kinematic_force_estimator.hpp +++ b/include/tv/kinematic_force_estimator.hpp @@ -1,7 +1,10 @@ #pragma once +#include + #include +#include "config.hpp" #include "interfaces.hpp" #include "types.hpp" @@ -20,29 +23,57 @@ class KinematicForceEstimator : public IForceEstimator // j_w wheel + motor rotational inertia [kg·m²] // r_eff effective wheel radius [m] // lpf_tau low-pass filter time constant [s] - KinematicForceEstimator(double mass, double cg_height, double wheelbase, double l_r, - double trackwidth, double front_tlltd, double j_w, double r_eff, - double lpf_tau) - : mass_(mass), - cg_height_(cg_height), - wheelbase_(wheelbase), - l_r_(l_r), - trackwidth_(trackwidth), - front_tlltd_(front_tlltd), - j_w_(j_w), - r_eff_(r_eff), - lpf_tau_(lpf_tau) {} - - // Feed per-wheel sensor data before each call to estimateForcesImpl. + KinematicForceEstimator() + : mass_(VehicleConfig::mass), + cg_height_(VehicleConfig::cg_height), + wheelbase_(VehicleConfig::wheelbase), + l_r_(VehicleConfig::l_r), + trackwidth_(VehicleConfig::trackwidth_front), + front_tlltd_(VehicleConfig::front_tlltd), + j_w_(ForceEstimatorConfig::j_w), + r_eff_(VehicleConfig::wheel_radius), + gear_ratio_(VehicleConfig::gear_ratio), + eta_(ForceEstimatorConfig::eta), + lpf_tau_(ForceEstimatorConfig::lpf_tau) {} + + // Feed per-wheel sensor data as it arrives. // motor_torques inverter torque demand [FL, FR, RL, RR] (Nm) // wheel_omegas wheel angular velocities [FL, FR, RL, RR] (rad/s) // dt time since last update (s) + // + // --- Fx: Driving Force Observer (DFO) --- + // Wheel-axle torque balance: J_w·dω/dt = T_wheel − F_x·R_eff, so + // F̂_x = (1/R_eff) * [T_wheel − J_w·dω/dt], smoothed by first-order LPF. + // The inverter reports motor-side torque, so convert to the wheel axle + // (T_wheel = N·η·T_motor) to keep it consistent with the wheel-side ω, + // wheel-referred inertia J_w, and wheel radius R_eff. + // Reference: Hori (2004), adopted by FS Team Tallinn (world #1 FSE 2024). + // + // The DFO and its LPF run here — at the wheel-speed sample rate — rather + // than in estimateForcesImpl (control rate), so the filter honours lpf_tau + // regardless of how the IMU and wheel-speed rates relate. void updateWheelState(const WheelTorques& motor_torques, const WheelOmegas& wheel_omegas, double dt) { + // Seed on the first sample so dω/dt doesn't spike when the node starts + // while the car is already moving. + if (!wheel_init_) { + current_omegas_ = wheel_omegas; + wheel_init_ = true; + } prev_omegas_ = current_omegas_; current_omegas_ = wheel_omegas; motor_torques_ = motor_torques; - dt_ = dt; + + if (dt <= 0.0) { + return; + } + const double alpha = lpf_tau_ / (lpf_tau_ + dt); + for (int i = 0; i < 4; ++i) { + const double d_omega_dt = (current_omegas_[i] - prev_omegas_[i]) / dt; + const double t_wheel = gear_ratio_ * eta_ * motor_torques_[i]; + const double fx_raw = (t_wheel - j_w_ * d_omega_dt) / r_eff_; + fx_filtered_[i] = alpha * fx_filtered_[i] + (1.0 - alpha) * fx_raw; + } } [[nodiscard]] ForceVector estimateForcesImpl(const VehicleState& s) { @@ -52,24 +83,14 @@ class KinematicForceEstimator : public IForceEstimator ForceVector forces{}; - // --- Fx: Driving Force Observer (DFO) --- - // F̂_x = (1/R_eff) * [T_motor − J_w·dω/dt], smoothed by first-order LPF. - // Reference: Hori (2004), adopted by FS Team Tallinn (world #1 FSE 2024). - if (dt_ > 0.0) { - const double alpha = lpf_tau_ / (lpf_tau_ + dt_); - for (int i = 0; i < 4; ++i) { - const double d_omega_dt = (current_omegas_[i] - prev_omegas_[i]) / dt_; - const double fx_raw = (motor_torques_[i] - j_w_ * d_omega_dt) / r_eff_; - fx_filtered_[i] = alpha * fx_filtered_[i] + (1.0 - alpha) * fx_raw; - } - } + // --- Fx: latest DFO estimate (filtered in updateWheelState) --- for (int i = 0; i < 4; ++i) forces.fx_[i] = fx_filtered_[i]; // --- Fz: quasi-static load transfer (AMZ acceleration-based method) --- // Uses IMU ax, ay directly — no kinematic approximation. // Reference: AMZ Racing (ETH Zurich), docs/tire_forces.md §1. - const double fz_front_static = 0.5 * mass_ * 9.81 * l_r_ / wheelbase_; - const double fz_rear_static = 0.5 * mass_ * 9.81 * l_f / wheelbase_; + const double fz_front_static = 0.5 * mass_ * kGravity * l_r_ / wheelbase_; + const double fz_rear_static = 0.5 * mass_ * kGravity * l_f / wheelbase_; const double delta_fz_lat = mass_ * ay * cg_height_ / trackwidth_; const double delta_fz_lat_front = front_tlltd_ * delta_fz_lat; @@ -82,13 +103,28 @@ class KinematicForceEstimator : public IForceEstimator forces.fz_[3] = fz_rear_static + delta_fz_long + delta_fz_lat_rear; // RR // --- Fy: steady-state bicycle model (using IMU ay) --- - const double fy_f = 0.5 * (l_r_ / wheelbase_) * mass_ * ay; - const double fy_r = 0.5 * (l_f / wheelbase_) * mass_ * ay; - - forces.fy_[0] = fy_f; // FL - forces.fy_[1] = fy_f; // FR - forces.fy_[2] = fy_r; // RL - forces.fy_[3] = fy_r; // RR + // The axle force is split per wheel by its share of the axle load, not + // 50/50: tyre lateral force scales roughly with normal load, so during + // cornering the unloaded inner wheel carries proportionally less Fy. + // An even split overstated the inner wheel's Fy, which collapsed its + // friction-circle budget √((μ·Fz)² − Fy²) in the allocator to zero and + // pinned that wheel's torque at 0 through every corner. + const double fy_front_axle = (l_r_ / wheelbase_) * mass_ * ay; + const double fy_rear_axle = (l_f / wheelbase_) * mass_ * ay; + + // Left wheel's share of the axle load; 0.5 when the axle is unloaded. + const auto left_share = [](double fz_left, double fz_right) { + const double left = std::max(0.0, fz_left); + const double sum = left + std::max(0.0, fz_right); + return sum > 1e-6 ? left / sum : 0.5; + }; + const double front_left_share = left_share(forces.fz_[0], forces.fz_[1]); + const double rear_left_share = left_share(forces.fz_[2], forces.fz_[3]); + + forces.fy_[0] = fy_front_axle * front_left_share; // FL + forces.fy_[1] = fy_front_axle * (1.0 - front_left_share); // FR + forces.fy_[2] = fy_rear_axle * rear_left_share; // RL + forces.fy_[3] = fy_rear_axle * (1.0 - rear_left_share); // RR return forces; } @@ -103,16 +139,18 @@ class KinematicForceEstimator : public IForceEstimator double front_tlltd_; // front TLLTD fraction, e.g. 0.52 // DFO parameters - double j_w_; // wheel + motor inertia [kg·m²] - double r_eff_; // effective wheel radius [m] - double lpf_tau_; // LPF time constant [s] + double j_w_; // rotational inertia referred to the wheel [kg·m²] + double r_eff_; // effective wheel radius [m] + double gear_ratio_; // motor → wheel gear ratio + double eta_; // drivetrain efficiency (motor → wheel) + double lpf_tau_; // LPF time constant [s] // DFO state WheelOmegas prev_omegas_{WheelOmegas::Zero()}; WheelOmegas current_omegas_{WheelOmegas::Zero()}; WheelTorques motor_torques_{WheelTorques::Zero()}; Eigen::Vector4d fx_filtered_{Eigen::Vector4d::Zero()}; - double dt_{0.0}; + bool wheel_init_{false}; // seed prev/current omegas from the first sample }; } // namespace tv diff --git a/include/tv/ldlt_torque_allocator.hpp b/include/tv/ldlt_torque_allocator.hpp new file mode 100644 index 0000000..00471b7 --- /dev/null +++ b/include/tv/ldlt_torque_allocator.hpp @@ -0,0 +1,178 @@ +#pragma once + +#include +#include + +#include "interfaces.hpp" +#include "types.hpp" + +namespace tv { + +// Torque allocator solving the distribution problem in closed form via an +// LDLᵀ (Cholesky-with-pivoting) factorisation (docs/tv.md §optimal allocation). +// +// Unconstrained weighted least-squares formulation (driving-force decision +// variable — radius-independent G): +// min (Gu − v)ᵀ W₁ (Gu − v) + uᵀ W₂ u +// u +// +// u = [F_FL, F_FR, F_RL, F_RR]ᵀ per-wheel driving forces [N] +// v = [Fx_total, Mz]ᵀ virtual demand +// +// Dependency matrix G (2×4) — depends only on the half-track widths: +// Fx row: [ 1, 1, 1, 1 ] +// Mz row: [-sf, sf, -sr, sr ] sf = tf/2, sr = tr/2 +// +// W₁ = diag(w_fx, w_mz) demand tracking weights +// W₂ = diag(w_reg · Fz_avg / Fz_i) load-inverse regularisation — each wheel is +// penalised inversely to its load, so the +// lowest-grip tyre is used least (normalised by +// the mean load Fz_avg so w_reg keeps its scale) +// +// Because there are no inequality constraints, the optimum is the solution of the +// normal equations (setting ∇J = 0; the factor of 2 cancels): +// (GᵀW₁G + W₂) u = GᵀW₁ v +// +// G is 2×4, so GᵀW₁G is rank-2 (singular) on its own: infinitely many force splits +// realise the same [Fx, Mz]. The load-inverse W₂ ≻ 0 makes the Hessian symmetric +// positive definite, picking the unique physically-meaningful split and letting us +// factor with LDLᵀ. On a 4×4 system this is essentially free — factor once per +// cycle, then forward/back-substitute. +// +// The wheel radius enters only at the output: T_motor = F · R / gear_ratio. +// +// NOTE: this layer enforces NO actuator or friction-circle limits. Motor-torque and +// tyre-grip bounds are assumed to be handled upstream (or by downstream clipping); +// adding them here would make the problem a genuinely constrained QP for which the +// closed form no longer holds. +// +// Reference: De Novellis et al. (SAE 2013-01-0673) +class LdltTorqueAllocator : public ITorqueAllocator { + public: + // Vehicle geometry / powertrain: + // r_w wheel radius [m] + // gear_ratio motor → wheel gear ratio (output: T_motor = F·R / gear_ratio) + // t_f front track width [m] + // t_r rear track width [m] + // + // QP weights: + // w_fx weight on Fx tracking error + // w_mz weight on Mz tracking error (typically >> w_fx for racing) + // w_reg load-inverse regularisation weight on driving-force magnitude + LdltTorqueAllocator(double r_w, double gear_ratio, double t_f, double t_r, double w_fx, + double w_mz, double w_reg) + : r_w_(r_w), gear_ratio_(gear_ratio), w_reg_(w_reg) { + // --- Dependency matrix G (2×4): driving forces → [Fx, Mz] --- + // Radius-independent — depends only on the half-track widths. + const double sf = t_f / 2.0; + const double sr = t_r / 2.0; + + // clang-format off + g_mat_ << 1.0, 1.0, 1.0, 1.0, + -sf, sf, -sr, sr; + // clang-format on + + // --- W1 = diag(w_fx, w_mz) --- + Eigen::Matrix2d w1_mat = Eigen::Matrix2d::Zero(); + w1_mat(0, 0) = w_fx; + w1_mat(1, 1) = w_mz; + + // Precompute GᵀW₁ (4×2) — reused each cycle for the rhs GᵀW₁·v and the + // constant tracking part of the Hessian GᵀW₁G. + gt_w1_ = g_mat_.transpose() * w1_mat; + + // Constant tracking part of the Hessian, GᵀW₁G (rank-2; the per-cycle + // load-inverse W₂ diagonal added on top makes the full H positive definite). + h_track_ = gt_w1_ * g_mat_; + } + + // VehicleState: [vx, vy, yaw_rate, steering_angle, ax, ay] + // YawMomentCommand: {mz_, fx_total_} + // ForceVector: [Fx×4, Fy×4, Fz×4] + [[nodiscard]] WheelTorques allocateImpl(const VehicleState& state, const YawMomentCommand& cmd, + const ForceVector& forces) { + (void)state; // reserved for speed-dependent torque maps + + // Pessimistically mark the solve as failed; set true only on a clean solve. + // Queried by the orchestrator via lastSolveOk() so the ROS node can warn + // when the fallback (previous solution) was used. + last_solve_ok_ = false; + + // --- rhs: GᵀW₁·v --- + const Eigen::Vector2d v_demand{cmd.fx_total_, cmd.mz_}; + const Eigen::Vector4d rhs = gt_w1_ * v_demand; + + // --- Load-inverse regularisation: W₂ = diag(w_reg · Fz_avg / Fz_i) --- + // Penalise each wheel inversely to its load so the lowest-grip tyre is used + // least. Normalised by the mean load so w_reg keeps its scale and H stays + // well-conditioned. + double fz_sum = 0.0; + for (int i = 0; i < 4; ++i) fz_sum += std::max(0.0, forces.fz_[i]); + const double fz_avg = std::max(kFzFloor, fz_sum / 4.0); + + Eigen::Matrix4d h = h_track_; + for (int i = 0; i < 4; ++i) { + const double fz = std::max(kFzFloor, forces.fz_[i]); + h(i, i) += w_reg_ * (fz_avg / fz); + } + + // --- LDLᵀ factorisation + solve of (GᵀW₁G + W₂) u = GᵀW₁ v --- + // H is SPD while w_reg > 0, so LLT would also be valid; LDLᵀ's symmetric + // pivoting is preferred because the tracking part GᵀW₁G is rank-2 and the + // two null-space directions are lifted only by the small load-inverse W₂, + // leaving H weakly conditioned there. LDLᵀ degrades gracefully (and still + // factors) if w_reg is ever set to 0, where the matrix becomes singular. + Eigen::LDLT ldlt(h); + if (ldlt.info() != Eigen::Success) { + return last_torques_; // hold previous solution on numerical breakdown + } + Eigen::Vector4d u = ldlt.solve(rhs); + + // Convert per-wheel driving force to motor torque: T_motor = F·R / gear_ratio. + for (int i = 0; i < 4; ++i) { + u[i] = (u[i] * r_w_) / gear_ratio_; + } + + // Guard against NaN/Inf — hold the previous solution. + if (!u.allFinite()) { + return last_torques_; + } + + last_solve_ok_ = true; + last_torques_ = u; + return u; + } + + // False when the most recent allocate() fell back to the previous solution + // (numerical breakdown or a non-finite solution). + [[nodiscard]] bool lastSolveOk() const noexcept { return last_solve_ok_; } + + private: + // Vehicle geometry / powertrain + double r_w_; // wheel radius [m] + double gear_ratio_; // motor → wheel gear ratio + double w_reg_; // load-inverse regularisation weight + + // Dependency matrix G (2×4), constant across cycles. + Eigen::Matrix g_mat_; + + // Precomputed GᵀW₁ (4×2, constant across cycles). + Eigen::Matrix gt_w1_; + + // Constant tracking part of the Hessian, GᵀW₁G (4×4). The load-inverse + // regularisation diagonal is added on top each cycle. + Eigen::Matrix4d h_track_; + + // Whether the most recent allocate() produced a clean solution. + bool last_solve_ok_{true}; + + // Most recent clean solution (motor torques), returned when a solve fails. + // Zero until the first successful solve. + WheelTorques last_torques_{WheelTorques::Zero()}; + + // Lower bound on wheel load [N] used in the 1/Fz weighting to avoid a + // divide-by-zero / unbounded penalty when a wheel is unloaded. + static constexpr double kFzFloor = 1.0; +}; + +} // namespace tv diff --git a/include/tv/pid_yaw_controller.hpp b/include/tv/pid_yaw_controller.hpp index 883b917..a0d4090 100644 --- a/include/tv/pid_yaw_controller.hpp +++ b/include/tv/pid_yaw_controller.hpp @@ -1,7 +1,9 @@ #pragma once +#include #include +#include "config.hpp" #include "interfaces.hpp" #include "types.hpp" @@ -9,51 +11,57 @@ namespace tv { // High-level yaw moment controller — docs/tv.md §layer 2 // -// Feedforward (yaw moment): bicycle model steady-state yaw moment -// Feedback (yaw moment): super-twisting Sliding Mode Control (Goggia et al. 2015) -// Fx demand : PI velocity tracker (TU Munich / KIT FSG approach) +// Yaw moment: PID on the yaw-rate error (derivative low-pass filtered) +// Fx demand : 2-DoF PI velocity tracker (TU Munich / KIT FSG approach) // // SteeringCommand layout: [delta (rad), vx_ref (m/s), r_ref (rad/s)] // Call setDt(dt) once per control cycle before computeImpl. class PIDYawController : public IYawController { public: - // Bicycle model params (yaw moment feedforward): - // c_f front axle cornering stiffness [N/rad] - // c_r rear axle cornering stiffness [N/rad] - // l_f front axle to CG [m] - // l_r rear axle to CG [m] + // Yaw PID params: + // kp_yaw proportional gain on yaw-rate error + // ki_yaw integral gain on yaw-rate error + // kd_yaw derivative gain on the yaw-rate error + // i_max_yaw symmetric saturation on the integral term |ki·∫e_r dt| [Nm] + // d_tau_yaw low-pass time constant on the derivative term [s] // - // Loss feedforward params: - // rho air density [kg/m³] - // c_d drag coefficient - // frontal_area frontal reference area [m²] - // c_rr rolling resistance coefficient - // - // Longitudinal PI params: + // Longitudinal 2-DoF PI params: // mass vehicle mass [kg] // k_p proportional gain [1/s] // k_i integral gain [1/s²] + // b setpoint weight on the proportional term [0, 1] (2-DoF PI) // eta drivetrain efficiency (0, 1] + // mu tyre-road friction coefficient (for the Fx grip clamp) + // vx_ref_rate max slew of the velocity reference [m/s²] // - // Fx_total = (k_p·ev + k_i·∫ev dt) · mass / eta + f_loss - // f_loss = f_aero + f_roll (only when accelerating, zero when braking) - PIDYawController(double c_f, double c_r, double l_f, double l_r, double rho, double c_d, - double frontal_area, double c_rr, double kp_yaw, double ki_yaw, double mass, - double k_p, double k_i, double eta) - : c_f_(c_f), - c_r_(c_r), - l_f_(l_f), - l_r_(l_r), - rho_(rho), - c_d_(c_d), - frontal_area_(frontal_area), - c_rr_(c_rr), - kp_yaw_(kp_yaw), + // ep = b·vx_ref − vx (setpoint-weighted proportional error) + // ev = vx_ref − vx (integral error — sees the full error) + // Fx_total = clamp((k_p·ep + k_i·∫ev dt) · mass / eta, ±μ·m·g) + // Errors are formed against a rate-limited vx_ref (slew ≤ vx_ref_rate). + PIDYawController(double kp_yaw, double ki_yaw, double kd_yaw, double i_max_yaw, + double d_tau_yaw, double mass, double k_p, double k_i, double b, double eta, + double mu, double vx_ref_rate) + : kp_yaw_(kp_yaw), ki_yaw_(ki_yaw), + kd_yaw_(kd_yaw), + i_max_yaw_(i_max_yaw), + d_tau_yaw_(d_tau_yaw), mass_(mass), kp_longi_(k_p), ki_longi_(k_i), - eta_(eta) {} + b_sp_(b), + eta_(eta), + mu_(mu), + vx_ref_rate_(vx_ref_rate) {} + + // Default: all parameters from config.hpp. + PIDYawController() + : PIDYawController(PIDYawControllerConfig::kp, PIDYawControllerConfig::ki, + PIDYawControllerConfig::kd, PIDYawControllerConfig::i_max, + PIDYawControllerConfig::d_tau, VehicleConfig::mass, + LongitudinalPiConfig::k_p, LongitudinalPiConfig::k_i, + LongitudinalPiConfig::b, LongitudinalPiConfig::eta, VehicleConfig::mu, + LongitudinalPiConfig::vx_ref_rate) {} // Must be called once per control cycle before computeImpl. void setDt(double dt) { dt_ = dt; } @@ -65,79 +73,104 @@ class PIDYawController : public IYawController { (void)forces; // reserved for future combined-slip feedforward const double vx = s.vx_; - const double vy = s.vy_; const double r = s.yaw_rate_; - const double delta = cmd.steering_angle_; const double vx_ref = cmd.vx_ref_; const double r_ref = cmd.r_ref_; - // ----------------------------------------------------------------------- - // Yaw moment feedforward — bicycle model steady-state - // ----------------------------------------------------------------------- - double mz_ff = 0.0; - if (std::abs(vx) > 0.5) { - const double alpha_f = delta - ((vy + (l_f_ * r_ref)) / vx); - const double alpha_r = -((vy - (l_r_ * r_ref)) / vx); - mz_ff = ((l_r_ * c_r_) * alpha_r) - ((l_f_ * c_f_) * alpha_f); - } - - // PID for yaw rate tracking, no D term right now + // PID for yaw rate tracking. + // Yaw-rate error is bidirectional (r_ref < 0 in right-hand turns), so the + // integrator must accumulate in both directions. Anti-windup is a symmetric + // clamp on the integral term rather than a one-sided reset — the previous + // `if (e_r < 0) reset` dumped the integral on every right turn. const double e_r = r_ref - r; - e_r_integral_ += e_r * dt_; // TODO: maybe need some anti windup + e_r_integral_ += e_r * dt_; + if (ki_yaw_ > 0.0) { + const double integral_limit = i_max_yaw_ / ki_yaw_; + e_r_integral_ = std::clamp(e_r_integral_, -integral_limit, integral_limit); + } - const double mz_pid = (kp_yaw_ * e_r) + (ki_yaw_ * e_r_integral_); + // Derivative term on the yaw-rate error, low-pass filtered (time constant + // d_tau_yaw). The error comes straight from the gyro, so the raw finite + // difference is noise-dominated — kd on it would inject noise into Mz. + double mz_d = 0.0; + if (yaw_d_init_ && dt_ > 0.0) { + const double de_r_raw = (e_r - e_r_prev_) / dt_; + const double beta = dt_ / (d_tau_yaw_ + dt_); + de_r_filt_ += beta * (de_r_raw - de_r_filt_); + mz_d = kd_yaw_ * de_r_filt_; + } + e_r_prev_ = e_r; + yaw_d_init_ = true; - const double mz = mz_ff + mz_pid; + const double mz = (kp_yaw_ * e_r) + (ki_yaw_ * e_r_integral_) + mz_d; // ----------------------------------------------------------------------- - // Fx demand — PI velocity tracker + loss feedforward (TU Munich / KIT FSG approach) - // - // Fx_total = (k_p·ev + k_i·∫ev dt) · m / η + f_loss + // Fx demand — 2-DoF PI velocity tracker (no feedforward). // - // Loss feedforward reduces integral windup by compensating known disturbances. - // Applied only during acceleration — during braking the losses already assist - // deceleration so adding them would oppose the braking demand. + // Fx_total = (k_p·ep + k_i·∫ev dt) · m / η // ----------------------------------------------------------------------- - const double e_vx = vx_ref - vx; + // Rate-limit the velocity reference so a stepped target (e.g. launch from + // rest) can't produce a huge instantaneous error that slams Fx to + // saturation. Seed the ramp from the current speed on the first tick. + if (!vx_ref_init_) { + vx_ref_ramped_ = vx; + vx_ref_init_ = true; + } + const double max_step = vx_ref_rate_ * dt_; + vx_ref_ramped_ = std::clamp(vx_ref, vx_ref_ramped_ - max_step, vx_ref_ramped_ + max_step); + + // 2-DoF PI: the integral acts on the full error (drives steady-state to + // zero), while the proportional acts on a setpoint-weighted error so a + // reference step doesn't produce a full proportional kick. + // Anti-windup is a symmetric clamp sized so the integral term alone stays + // within the grip limit — the error is bidirectional (overspeed needs a + // negative Fx), so a one-sided reset would dump the integral on every + // overshoot of the ramped reference and preclude integral action while + // decelerating. + const double e_vx = vx_ref_ramped_ - vx; // integral error + const double e_vx_p = (b_sp_ * vx_ref_ramped_) - vx; // proportional error e_vx_integral_ += e_vx * dt_; - const double f_aero = (0.5 * rho_ * c_d_ * frontal_area_) * (vx * vx); - const double f_roll = c_rr_ * mass_ * 9.81; - const double f_loss = (e_vx > 0.0) ? (f_aero + f_roll) : 0.0; - const double fx_total = - (((kp_longi_ * e_vx) + (ki_longi_ * e_vx_integral_)) * (mass_ / eta_)) + - f_loss; // limiting currently happens in torque allocator + if (ki_longi_ > 0.0) { + const double integral_limit = (mu_ * kGravity * eta_) / ki_longi_; + e_vx_integral_ = std::clamp(e_vx_integral_, -integral_limit, integral_limit); + } + const double fx_raw = + ((kp_longi_ * e_vx_p) + (ki_longi_ * e_vx_integral_)) * (mass_ / eta_); + // Clamp to the longitudinal grip limit ±μ·m·g so the demand stays within + // what the tyres can deliver (the allocator would otherwise ride saturation). + const double fx_max = mu_ * mass_ * kGravity; + const double fx_total = std::clamp(fx_raw, -fx_max, fx_max); return YawMomentCommand{.mz_ = mz, .fx_total_ = fx_total}; } private: - // Bicycle model parameters (yaw moment feedforward) - const double c_f_; // front cornering stiffness [N/rad] - const double c_r_; // rear cornering stiffness [N/rad] - const double l_f_; // front axle to CG [m] - const double l_r_; // rear axle to CG [m] - - // Loss feedforward parameters - const double rho_; // air density [kg/m³] - const double c_d_; // drag coefficient - const double frontal_area_; // frontal reference area [m²] - const double c_rr_; // rolling resistance coefficient - // PID Yaw parameters const double kp_yaw_; const double ki_yaw_; - - // Longitudinal PI parameters - const double mass_; // vehicle mass [kg] - const double kp_longi_; // proportional gain [1/s] - const double ki_longi_; // integral gain [1/s²] - const double eta_; // drivetrain efficiency + const double kd_yaw_; // derivative gain (on yaw-rate error) + const double i_max_yaw_; // symmetric integral-term clamp [Nm] + const double d_tau_yaw_; // derivative low-pass time constant [s] + + // Longitudinal 2-DoF PI parameters + const double mass_; // vehicle mass [kg] + const double kp_longi_; // proportional gain [1/s] + const double ki_longi_; // integral gain [1/s²] + const double b_sp_; // setpoint weight on the proportional term [0, 1] + const double eta_; // drivetrain efficiency + const double mu_; // tyre-road friction coefficient (Fx grip clamp) + const double vx_ref_rate_; // max velocity-reference slew [m/s²] // Yaw PID state double e_r_integral_{0.0}; // integral of yaw rate error [rad] + double e_r_prev_{0.0}; // previous yaw-rate error [rad/s] (for the derivative term) + double de_r_filt_{0.0}; // low-pass-filtered error derivative [rad/s²] + bool yaw_d_init_{false}; // seed e_r_prev_ on the first tick to avoid a spike // PI state double e_vx_integral_{0.0}; // integral of velocity error [m] + double vx_ref_ramped_{0.0}; // rate-limited velocity reference [m/s] + bool vx_ref_init_{false}; // seed the ramp from measured vx on first tick // Time step — updated each cycle via setDt() double dt_{0.0}; diff --git a/include/tv/qp_torque_allocator.hpp b/include/tv/qp_torque_allocator.hpp index 6444fda..3310606 100644 --- a/include/tv/qp_torque_allocator.hpp +++ b/include/tv/qp_torque_allocator.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "interfaces.hpp" #include "types.hpp" @@ -15,36 +16,43 @@ namespace tv { // Torque allocator solving the distribution problem via OSQP (docs/tv.md §optimal allocation). // -// QP formulation: -// min (Bu − v)ᵀ W₁ (Bu − v) + uᵀ W₂ u +// QP formulation (driving-force decision variable — radius-independent G): +// min (Gu − v)ᵀ W₁ (Gu − v) + uᵀ W₂ u // u // -// u = [T_FL, T_FR, T_RL, T_RR]ᵀ wheel torques [Nm] +// u = [F_FL, F_FR, F_RL, F_RR]ᵀ per-wheel driving forces [N] // v = [Fx_total, Mz]ᵀ virtual demand // -// Effectiveness matrix B (2×4): -// Fx row: [ 1/R, 1/R, 1/R, 1/R ] -// Mz row: [-tf/2R, tf/2R, -tr/2R, tr/2R ] +// Dependency matrix G (2×4) — depends only on the half-track widths: +// Fx row: [ 1, 1, 1, 1 ] +// Mz row: [-sf, sf, -sr, sr ] sf = tf/2, sr = tr/2 // -// W₁ = diag(w_fx, w_mz) demand tracking weights -// W₂ = w_reg · I₄ regularisation (equalises tyre utilisation) +// W₁ = diag(w_fx, w_mz) demand tracking weights +// W₂ = diag(w_reg · Fz_avg / Fz_i) load-inverse regularisation — each wheel is +// penalised inversely to its load, so the +// lowest-grip tyre is used least (normalised by +// the mean load Fz_avg so w_reg keeps its scale) // // Rewritten in standard OSQP form min 0.5 uᵀPu + qᵀu, s.t. lb ≤ Iu ≤ ub: -// P = 2(BᵀW₁B + W₂) (upper triangular, constant — computed once in constructor) -// q = −2BᵀW₁v (updated each cycle from current demand) +// P = 2(GᵀW₁G + W₂) (GᵀW₁G constant; the W₂ diagonal is refreshed each cycle +// from the current wheel loads via updateHessianMatrix) +// q = −2GᵀW₁v (updated each cycle from current demand) // -// Box constraints per wheel (updated each cycle): -// Motor: |T_i| ≤ T_max -// Friction circle:|T_i| ≤ R·√(max(0, (μ·Fz_i)² − Fy_i²)) +// Box constraints per wheel (updated each cycle), as forces: +// Motor: |F_i| ≤ T_max / R +// Friction circle:|F_i| ≤ √(max(0, (μ·Fz_i)² − Fy_i²)) +// +// The wheel radius enters only at the output: T_motor = F · R / gear_ratio. // // OSQP warm-starts from the previous solution, giving fast convergence in practice. // Reference: De Novellis et al. (SAE 2013-01-0673) class QpTorqueAllocator : public ITorqueAllocator { public: - // Vehicle geometry: - // r_w wheel radius [m] - // t_f front track width [m] - // t_r rear track width [m] + // Vehicle geometry / powertrain: + // r_w wheel radius [m] + // gear_ratio motor → wheel gear ratio (output: T_motor = F·R / gear_ratio) + // t_f front track width [m] + // t_r rear track width [m] // // Limits: // t_max per-wheel motor torque limit [Nm] @@ -53,19 +61,19 @@ class QpTorqueAllocator : public ITorqueAllocator { // QP weights: // w_fx weight on Fx tracking error // w_mz weight on Mz tracking error (typically >> w_fx for racing) - // w_reg regularisation weight on torque magnitude - QpTorqueAllocator(double r_w, double t_f, double t_r, double t_max, double mu, double w_fx, - double w_mz, double w_reg) - : r_w_(r_w), t_max_(t_max), mu_(mu) { - // --- Effectiveness matrix B (2×4) --- - const double inv_r = 1.0 / r_w; - const double tf_term = t_f / (2.0 * r_w); - const double tr_term = t_r / (2.0 * r_w); - - Eigen::Matrix b_mat; + // w_reg regularisation weight on driving-force magnitude + QpTorqueAllocator(double r_w, double gear_ratio, double t_f, double t_r, double t_max, double mu, + double w_fx, double w_mz, double w_reg) + : r_w_(r_w), gear_ratio_(gear_ratio), t_max_(t_max), mu_(mu) { + // --- Dependency matrix G (2×4): driving forces → [Fx, Mz] --- + // Radius-independent — depends only on the half-track widths. + const double sf = t_f / 2.0; + const double sr = t_r / 2.0; + + Eigen::Matrix g_mat; // clang-format off - b_mat << inv_r, inv_r, inv_r, inv_r, - -tf_term, tf_term, -tr_term, tr_term; + g_mat << 1.0, 1.0, 1.0, 1.0, + -sf, sf, -sr, sr; // clang-format on // --- W1 = diag(w_fx, w_mz) --- @@ -73,20 +81,30 @@ class QpTorqueAllocator : public ITorqueAllocator { w1_mat(0, 0) = w_fx; w1_mat(1, 1) = w_mz; - // Precompute BᵀW₁ — reused each cycle for gradient q = −2·BᵀW₁·v - bt_w1_ = b_mat.transpose() * w1_mat; + // Precompute GᵀW₁ — reused each cycle for gradient q = −2·GᵀW₁·v + gt_w1_ = g_mat.transpose() * w1_mat; + + // Constant tracking part of the Hessian: 2·GᵀW₁G (rank-2; the load-inverse + // regularisation added each cycle makes the full P positive definite). + p_track_ = 2.0 * (gt_w1_ * g_mat); + w_reg_ = w_reg; // --- P = 2(BᵀW₁B + W₂), upper triangular sparse (OSQP convention) --- + // Initial Hessian uses an equal-load W₂ = w_reg·I just to establish the + // (full upper-triangular) sparsity pattern; the diagonal is refreshed with + // the load-inverse weights every cycle via updateHessianMatrix(). The + // sparse matrix is a member so the per-cycle update touches values only — + // no allocation in the control loop. const Eigen::Matrix p_dense = - 2.0 * ((bt_w1_ * b_mat) + (w_reg * Eigen::Matrix::Identity())); + p_track_ + (2.0 * w_reg_ * Eigen::Matrix::Identity()); - Eigen::SparseMatrix p_upper(4, 4); + p_upper_.resize(4, 4); for (int i = 0; i < 4; ++i) { for (int j = i; j < 4; ++j) { - p_upper.insert(i, j) = p_dense(i, j); + p_upper_.insert(i, j) = p_dense(i, j); } } - p_upper.makeCompressed(); + p_upper_.makeCompressed(); // --- Constraint matrix A = I₄ (encodes box constraints) --- Eigen::SparseMatrix a_sparse(4, 4); @@ -95,25 +113,32 @@ class QpTorqueAllocator : public ITorqueAllocator { // --- Configure OSQP --- solver_.settings()->setWarmStart(true); solver_.settings()->setVerbosity(false); - solver_.settings()->setPolish(true); + // Polishing is an optional high-accuracy refinement step; disabled here. + // It adds latency in the control loop and prints "Polishing not needed — + // no active set detected at optimal point" (not gated by verbosity) on + // every cycle where it's skipped. Warm-start + 1e-5 tolerances suffice. + solver_.settings()->setPolish(false); solver_.settings()->setMaxIteration(500); solver_.settings()->setAbsoluteTolerance(1e-5); solver_.settings()->setRelativeTolerance(1e-5); solver_.data()->setNumberOfVariables(4); solver_.data()->setNumberOfConstraints(4); - solver_.data()->setHessianMatrix(p_upper); + solver_.data()->setHessianMatrix(p_upper_); Eigen::VectorXd q_init = Eigen::VectorXd::Zero(4); solver_.data()->setGradient(q_init); solver_.data()->setLinearConstraintsMatrix(a_sparse); - Eigen::VectorXd lb_init = Eigen::VectorXd::Constant(4, -t_max); - Eigen::VectorXd ub_init = Eigen::VectorXd::Constant(4, t_max); + const double f_motor_max = t_max / r_w; // wheel-torque cap expressed as a force + Eigen::VectorXd lb_init = Eigen::VectorXd::Constant(4, -f_motor_max); + Eigen::VectorXd ub_init = Eigen::VectorXd::Constant(4, f_motor_max); solver_.data()->setLowerBound(lb_init); solver_.data()->setUpperBound(ub_init); - solver_.initSolver(); + if (!solver_.initSolver()) { + throw std::runtime_error("QpTorqueAllocator: OSQP solver initialisation failed"); + } } // VehicleState: [vx, vy, yaw_rate, steering_angle, ax, ay] @@ -123,43 +148,116 @@ class QpTorqueAllocator : public ITorqueAllocator { const ForceVector& forces) { (void)state; // reserved for speed-dependent torque maps - // --- Gradient: q = −2·BᵀW₁·v --- + // Pessimistically mark the solve as failed; set true only on a clean + // solve. Queried by the orchestrator via lastSolveOk() so the ROS node + // can warn when the fallback was used. + last_solve_ok_ = false; + + // Any failed solver update leaves OSQP with inconsistent data — hold the + // previous solution for this cycle rather than solving the wrong problem + // (zero before the first successful solve). A transient failure then + // doesn't step the torque to zero mid-manoeuvre; persistent failures + // keep reporting via lastSolveOk(). + + // --- Gradient: q = −2·GᵀW₁·v --- const Eigen::Vector2d v_demand{cmd.fx_total_, cmd.mz_}; - const Eigen::VectorXd q_vec = -2.0 * (bt_w1_ * v_demand); - solver_.updateGradient(q_vec); + const Eigen::VectorXd q_vec = -2.0 * (gt_w1_ * v_demand); + if (!solver_.updateGradient(q_vec)) { + return last_torques_; + } - // --- Per-wheel bounds: motor cap ∩ friction circle --- - // ForceVector: Fy = indices [4..7], Fz = indices [8..11] + // --- Per-wheel bounds (driving force): motor cap ∩ friction circle --- + // The friction circle already gives a force cap; the motor wheel-torque cap + // t_max is expressed as a force via t_max / R. + const double f_motor_max = t_max_ / r_w_; Eigen::VectorXd ub(4); Eigen::VectorXd lb(4); for (int i = 0; i < 4; ++i) { const double fz = std::max(0.0, forces.fz_[i]); const double fy = forces.fy_[i]; const double fx_cap = std::sqrt(std::max(0.0, ((mu_ * fz) * (mu_ * fz)) - (fy * fy))); - ub[i] = std::min(t_max_, r_w_ * fx_cap); + ub[i] = std::min(f_motor_max, fx_cap); lb[i] = -ub[i]; } - solver_.updateBounds(lb, ub); + if (!solver_.updateBounds(lb, ub)) { + return last_torques_; + } + + // --- Load-inverse regularisation: W₂ = diag(w_reg · Fz_avg / Fz_i) --- + // Penalise each wheel inversely to its load so the lowest-grip tyre is used + // least. Normalised by the mean load so w_reg keeps its scale and P stays + // well-conditioned. Only the diagonal of P = 2·GᵀW₁G + 2·W₂ changes, so + // refresh those values in the persistent sparse matrix (pattern is fixed). + double fz_sum = 0.0; + for (int i = 0; i < 4; ++i) fz_sum += std::max(0.0, forces.fz_[i]); + const double fz_avg = std::max(kFzFloor, fz_sum / 4.0); + + for (int i = 0; i < 4; ++i) { + const double fz = std::max(kFzFloor, forces.fz_[i]); + p_upper_.coeffRef(i, i) = p_track_(i, i) + 2.0 * w_reg_ * (fz_avg / fz); + } + if (!solver_.updateHessianMatrix(p_upper_)) { + return last_torques_; + } switch (solver_.solveProblem()) { - case OsqpEigen::ErrorExitFlag::NoError: - return solver_.getSolution().head<4>(); - break; + case OsqpEigen::ErrorExitFlag::NoError: { + // Solution is the per-wheel driving force. Convert to motor torque: + // T_motor = F · R_wheel / gear_ratio. + WheelTorques u = solver_.getSolution().head<4>(); + for (int i = 0; i < 4; ++i) { + u[i] = (u[i] * r_w_) / gear_ratio_; + } + // Guard against NaN/Inf in the solution (e.g. non-convergence or + // numerical breakdown reported as NoError) — hold the previous + // solution. + if (!u.allFinite()) { + return last_torques_; + } + last_solve_ok_ = true; + last_torques_ = u; + return u; + } default: - return WheelTorques::Zero(); + return last_torques_; } } + // False when the most recent allocate() fell back to the previous solution + // (failed OSQP update/solve or a non-finite solution). + [[nodiscard]] bool lastSolveOk() const noexcept { return last_solve_ok_; } + private: - // Vehicle geometry - double r_w_; // wheel radius [m] + // Vehicle geometry / powertrain + double r_w_; // wheel radius [m] + double gear_ratio_; // motor → wheel gear ratio // Limits double t_max_; // per-wheel motor torque cap [Nm] double mu_; // tyre-road friction coefficient - // Precomputed BᵀW₁ (4×2, constant across cycles) - Eigen::Matrix bt_w1_; + // Precomputed GᵀW₁ (4×2, constant across cycles) + Eigen::Matrix gt_w1_; + + // Constant tracking part of the Hessian, 2·GᵀW₁G (4×4). The load-inverse + // regularisation diagonal is added on top each cycle. + Eigen::Matrix p_track_; + double w_reg_; // regularisation weight (load-inverse cost) + + // Persistent upper-triangular Hessian passed to OSQP. The sparsity pattern + // is fixed in the constructor; only the diagonal values change per cycle. + Eigen::SparseMatrix p_upper_; + + // Whether the most recent allocate() produced a clean solution. + bool last_solve_ok_{true}; + + // Most recent clean solution (motor torques), returned when a solve fails. + // Zero until the first successful solve. + WheelTorques last_torques_{WheelTorques::Zero()}; + + // Lower bound on wheel load [N] used in the 1/Fz weighting to avoid a + // divide-by-zero / unbounded penalty when a wheel is unloaded. + static constexpr double kFzFloor = 1.0; // OSQP solver — maintains warm-start state between control cycles OsqpEigen::Solver solver_; diff --git a/include/types.hpp b/include/types.hpp index a319f9e..6ba9139 100644 --- a/include/types.hpp +++ b/include/types.hpp @@ -37,11 +37,33 @@ struct SteeringCommand { }; // Per-wheel torque commands [FL, FR, RL, RR] (Nm). -// Kept as Eigen — returned directly from the OSQP solver and used in DFO loops. +// Kept as Eigen — returned directly from the allocator solve and used in DFO loops. using WheelTorques = Eigen::Vector4d; // Per-wheel angular velocities [FL, FR, RL, RR] (rad/s). // Kept as Eigen — used in element-wise DFO loops. using WheelOmegas = Eigen::Vector4d; +// Per-stage pipeline execution times [µs] — published on debug/timing for +// telemetry; carries no control meaning. +struct StageTimings { + double forces_us{0.0}; // force estimator (stage 1) + double yaw_us{0.0}; // yaw moment generator (stage 2) + double alloc_us{0.0}; // torque allocator (stage 3) + double total_us{0.0}; // full pipeline +}; + +// Full pipeline output: final wheel torques plus every intermediate signal. +// The intermediates carry no control meaning here — they exist so the ROS node +// can publish them on debug topics for telemetry/plotting. +struct PipelineResult { + ForceVector forces{}; // tyre force estimate (stage 1) + YawMomentCommand yaw_cmd{}; // yaw moment + Fx demand (stage 2) + WheelTorques torques{WheelTorques::Zero()}; // allocated wheel torques (stage 3) + StageTimings timings{}; // per-stage execution times, this cycle + StageTimings timings_avg{}; // running mean since startup + StageTimings timings_std{}; // running sample standard deviation since startup + bool alloc_ok{true}; // false when the allocator failed and held its previous solution +}; + } // namespace tv diff --git a/launch/launch.py b/launch/launch.py index 714a6a2..2aa1634 100644 --- a/launch/launch.py +++ b/launch/launch.py @@ -2,12 +2,10 @@ """ Launch file for torque_vectoring_pkg. -This launch file starts the time_publisher and time_subscriber nodes -with parameters loaded from the config file. +Starts the torque-vectoring node with its topics remapped onto the +vehicle bus / navigation stack. """ -import os - from launch import LaunchDescription from launch_ros.actions import Node @@ -23,15 +21,18 @@ def generate_launch_description(): return LaunchDescription( [ - # Time Publisher Node (C++) Node( package="torque_vectoring_pkg", - executable="torque_vectoring_pkg", + executable="torque_vectoring_node", name="torque_vectoring_node", output="screen", remappings=[ - ("steering_cmd", "navigation/dv_control_target"), - ("imu", "dlio/odom"), + ("cmd_in", "navigation/dv_control_target"), + ("odom", "/odom"), + ("imu", "/imu"), + ("wheel_speeds", "vehicle/wheel_speeds"), + ("motor_torques", "ros2can/receive/vehicle_status_motor_torques"), + ("cmd_out", "ros2can/send/dv_control_target_tv"), ], ), ] diff --git a/package.xml b/package.xml index 55f30a2..0f9b4c4 100644 --- a/package.xml +++ b/package.xml @@ -16,9 +16,11 @@ rclpy std_msgs sensor_msgs + nav_msgs eigen - osqp-eigen vehicle_params_cpp + fs_msgs + ros2can_msgs ament_lint_auto ament_lint_common diff --git a/src/main.cpp b/src/main.cpp index cbdeb51..27421cf 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,6 @@ #include +#include #include "config.hpp" #include "orchestrator.hpp" @@ -7,17 +8,28 @@ #include "ros_interface.hpp" #include "tv/kinematic_force_estimator.hpp" #include "tv/pid_yaw_controller.hpp" -#include "tv/qp_torque_allocator.hpp" +#include "tv/ldlt_torque_allocator.hpp" #include "types.hpp" -namespace tv { - int main(int argc, char* argv[]) { - KinematicForceEstimator kfe(tv::Config::force_estimator); + using namespace tv; rclcpp::init(argc, argv); + + KinematicForceEstimator force_estimator; + + PIDYawController yaw_controller; // all parameters from config.hpp + + LdltTorqueAllocator torque_allocator(VehicleConfig::wheel_radius, VehicleConfig::gear_ratio, + VehicleConfig::trackwidth_front, + VehicleConfig::trackwidth_rear, AllocatorConfig::w_fx, + AllocatorConfig::w_mz, AllocatorConfig::w_reg); + + Orchestrator orchestrator(std::move(force_estimator), std::move(yaw_controller), + std::move(torque_allocator)); + rclcpp::spin( - std::make_unique>()); + std::make_unique>( + std::move(orchestrator))); rclcpp::shutdown(); return 0; } -} // namespace tv From 3872a4b3ff6c861f75db70592576e1cecda16e5b Mon Sep 17 00:00:00 2001 From: Bulban <147950706+Bulban@users.noreply.github.com> Date: Tue, 28 Jul 2026 22:07:05 +0200 Subject: [PATCH 2/5] Don't really know what changed --- include/config.hpp | 22 +++++++++++----------- include/tv/ldlt_torque_allocator.hpp | 24 ++++++++++++++++-------- src/main.cpp | 3 ++- 3 files changed, 29 insertions(+), 20 deletions(-) diff --git a/include/config.hpp b/include/config.hpp index ca5cf62..1303e33 100644 --- a/include/config.hpp +++ b/include/config.hpp @@ -22,7 +22,7 @@ struct VehicleConfig { kthfs::vehicle::dev19::cg_height_m}; // centre-of-gravity height [m] static constexpr double wheelbase{ kthfs::vehicle::dev19::wheelbase_m}; // front-to-rear axle distance [m] - static constexpr double l_r{0.705}; // rear axle to CG [m] → l_f = wheelbase - l_r + static constexpr double l_r{0.612}; // rear axle to CG [m] → l_f = wheelbase - l_r static constexpr double trackwidth_front{ kthfs::vehicle::dev19::track_width_m}; // front track width [m] static constexpr double trackwidth_rear{ @@ -77,12 +77,12 @@ struct BicycleModelConfig { }; struct PIDYawControllerConfig { - static constexpr double kp{250}; // Proportional term for yaw rate error tracking - static constexpr double ki{50}; // Integral term for yaw rate error tracking - static constexpr double kd{20}; // Derivative term on the yaw-rate error + static constexpr double kp{600}; // Proportional term for yaw rate error tracking + static constexpr double ki{1}; // Integral term for yaw rate error tracking + static constexpr double kd{0}; // Derivative term on the yaw-rate error static constexpr double i_max{ - 1000.0}; // yaw integral-term saturation [Nm] — symmetric anti-windup clamp. - // Tune to the yaw-moment authority the allocator can realise. + 250.0}; // yaw integral-term saturation [Nm] — symmetric anti-windup clamp. + // Tune to the yaw-moment authority the allocator can realise. static constexpr double d_tau{ 0.02}; // low-pass time constant on the derivative term [s]. The yaw-rate // error comes straight from the gyro, so the raw derivative is @@ -90,20 +90,20 @@ struct PIDYawControllerConfig { }; struct LongitudinalPiConfig { - static constexpr double k_p{2.0}; // proportional gain [1/s] — velocity-loop bandwidth. + static constexpr double k_p{6.0}; // proportional gain [1/s] — velocity-loop bandwidth. // Full Fx (grip clamp μg≈15.7 m/s²) is reached at a // velocity error of μg/k_p; keep k_p low (~1–3) so // tracking noise doesn't slam the demand to saturation. - static constexpr double k_i{1.0}; // integral gain [1/s²] + static constexpr double k_i{0.5}; // integral gain [1/s²] static constexpr double b{0.8}; // setpoint weight on the proportional term (2-DoF PI), // [0, 1]. 1 → classic PI; <1 softens the proportional // kick on reference steps without changing disturbance // rejection (the integral still sees the full error). static constexpr double eta{1.0}; // drivetrain efficiency static constexpr double vx_ref_rate{ - 5.0}; // max rate of change of the velocity reference [m/s²]. Ramps vx_ref so a - // step target (e.g. launch from rest) doesn't slam Fx to saturation. - // Keep below the grip limit μ·g ≈ 15.7 m/s². + 20.0}; // max rate of change of the velocity reference [m/s²]. Ramps vx_ref so a + // step target (e.g. launch from rest) doesn't slam Fx to saturation. + // Keep below the grip limit μ·g ≈ 15.7 m/s². }; struct AllocatorConfig { diff --git a/include/tv/ldlt_torque_allocator.hpp b/include/tv/ldlt_torque_allocator.hpp index 00471b7..003426b 100644 --- a/include/tv/ldlt_torque_allocator.hpp +++ b/include/tv/ldlt_torque_allocator.hpp @@ -41,10 +41,13 @@ namespace tv { // // The wheel radius enters only at the output: T_motor = F · R / gear_ratio. // -// NOTE: this layer enforces NO actuator or friction-circle limits. Motor-torque and -// tyre-grip bounds are assumed to be handled upstream (or by downstream clipping); -// adding them here would make the problem a genuinely constrained QP for which the -// closed form no longer holds. +// NOTE: the closed form enforces no friction-circle limits — those are assumed to be +// handled upstream, since adding them would make this a genuinely constrained QP for +// which the closed form no longer holds. The one exception is a hard per-wheel motor- +// torque saturation applied to the output (see t_max): a simple symmetric clip that +// keeps every command within actuator authority. Clipping a wheel independently +// distorts the realised [Fx, Mz], but this is the standard downstream saturation and +// keeps the solver from ever commanding an unachievable torque. // // Reference: De Novellis et al. (SAE 2013-01-0673) class LdltTorqueAllocator : public ITorqueAllocator { @@ -54,14 +57,16 @@ class LdltTorqueAllocator : public ITorqueAllocator { // gear_ratio motor → wheel gear ratio (output: T_motor = F·R / gear_ratio) // t_f front track width [m] // t_r rear track width [m] + // t_max per-wheel motor-torque limit [Nm]; each output is clipped to + // [-t_max, t_max]. Use a large value to effectively disable. // // QP weights: // w_fx weight on Fx tracking error // w_mz weight on Mz tracking error (typically >> w_fx for racing) // w_reg load-inverse regularisation weight on driving-force magnitude LdltTorqueAllocator(double r_w, double gear_ratio, double t_f, double t_r, double w_fx, - double w_mz, double w_reg) - : r_w_(r_w), gear_ratio_(gear_ratio), w_reg_(w_reg) { + double w_mz, double w_reg, double t_max) + : r_w_(r_w), gear_ratio_(gear_ratio), w_reg_(w_reg), t_max_(t_max) { // --- Dependency matrix G (2×4): driving forces → [Fx, Mz] --- // Radius-independent — depends only on the half-track widths. const double sf = t_f / 2.0; @@ -128,9 +133,11 @@ class LdltTorqueAllocator : public ITorqueAllocator { } Eigen::Vector4d u = ldlt.solve(rhs); - // Convert per-wheel driving force to motor torque: T_motor = F·R / gear_ratio. + // Convert per-wheel driving force to motor torque: T_motor = F·R / gear_ratio, + // then clip to the per-wheel actuator limit so no wheel is ever commanded + // beyond motor authority (see NOTE above on the resulting [Fx, Mz] distortion). for (int i = 0; i < 4; ++i) { - u[i] = (u[i] * r_w_) / gear_ratio_; + u[i] = std::clamp((u[i] * r_w_) / gear_ratio_, -t_max_, t_max_); } // Guard against NaN/Inf — hold the previous solution. @@ -152,6 +159,7 @@ class LdltTorqueAllocator : public ITorqueAllocator { double r_w_; // wheel radius [m] double gear_ratio_; // motor → wheel gear ratio double w_reg_; // load-inverse regularisation weight + double t_max_; // per-wheel motor-torque saturation limit [Nm] // Dependency matrix G (2×4), constant across cycles. Eigen::Matrix g_mat_; diff --git a/src/main.cpp b/src/main.cpp index 27421cf..559bbdd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -22,7 +22,8 @@ int main(int argc, char* argv[]) { LdltTorqueAllocator torque_allocator(VehicleConfig::wheel_radius, VehicleConfig::gear_ratio, VehicleConfig::trackwidth_front, VehicleConfig::trackwidth_rear, AllocatorConfig::w_fx, - AllocatorConfig::w_mz, AllocatorConfig::w_reg); + AllocatorConfig::w_mz, AllocatorConfig::w_reg, + VehicleConfig::motor_t_max); Orchestrator orchestrator(std::move(force_estimator), std::move(yaw_controller), std::move(torque_allocator)); From 64327c5fc9d273d91f82f40915e1de1dcb5e039e Mon Sep 17 00:00:00 2001 From: Bulban <147950706+Bulban@users.noreply.github.com> Date: Fri, 2 Oct 2026 20:18:51 +0200 Subject: [PATCH 3/5] Removed unnecessary comments and added filtering --- include/config.hpp | 88 ++++--------- include/interfaces.hpp | 5 - include/orchestrator.hpp | 33 ++--- include/ros_interface.hpp | 155 +++++++++++------------ include/tv/kinematic_force_estimator.hpp | 55 ++------ include/tv/ldlt_torque_allocator.hpp | 109 +++------------- include/tv/pid_yaw_controller.hpp | 91 ++++--------- include/tv/qp_torque_allocator.hpp | 128 ++++--------------- include/types.hpp | 13 +- 9 files changed, 191 insertions(+), 486 deletions(-) diff --git a/include/config.hpp b/include/config.hpp index 1303e33..1a6dc7f 100644 --- a/include/config.hpp +++ b/include/config.hpp @@ -1,21 +1,10 @@ #pragma once #include -// ============================================================================= -// config.hpp — edit all tunable parameters here. -// -// Each struct maps to one pipeline component. Pass the values to the -// component constructors as shown in the usage example at the bottom. -// ============================================================================= - namespace tv { -// Standard gravity [m/s²] — shared by the load-transfer model and grip clamps. -inline constexpr double kGravity{9.81}; +inline constexpr double kGravity{9.81}; // [m/s²] -// ----------------------------------------------------------------------------- -// Vehicle physical properties — shared across all three layers -// ----------------------------------------------------------------------------- struct VehicleConfig { static constexpr double mass{kthfs::vehicle::dev19::weight_kg}; // total vehicle mass [kg] static constexpr double cg_height{ @@ -38,10 +27,7 @@ struct VehicleConfig { gear_ratio}; // per-wheel wheel-side torque cap [Nm] }; -// ----------------------------------------------------------------------------- -// Aerodynamic and rolling-resistance losses — reserved for a future Fx loss -// feedforward in the longitudinal tracker (currently unused) -// ----------------------------------------------------------------------------- +// Reserved for a future Fx loss feedforward in the longitudinal tracker (unused). struct AeroConfig { static constexpr double rho{1.225}; // air density [kg/m³] (1.225 at sea level, 15 °C) static constexpr double c_d{kthfs::vehicle::dev19::drag_coefficient}; // drag coefficient @@ -51,59 +37,36 @@ struct AeroConfig { kthfs::vehicle::dev19::rolling_resistance}; // rolling resistance coefficient }; -// ----------------------------------------------------------------------------- -// Driving Force Observer — KinematicForceEstimator -// ----------------------------------------------------------------------------- struct ForceEstimatorConfig { - static constexpr double j_w{0.5}; // rotational inertia referred to the wheel [kg·m²] - // (includes motor inertia reflected as J_motor·N²) + static constexpr double j_w{0.5}; // inertia referred to the wheel [kg·m²], incl. J_m·N² static constexpr double eta{1.0}; // drivetrain efficiency (motor → wheel), (0, 1] - static constexpr double lpf_tau{0.10}; // DFO low-pass filter time constant [s] - // smaller → faster but noisier Fx estimate + static constexpr double lpf_tau{0.10}; // DFO LPF time constant [s]; smaller → noisier }; -// ----------------------------------------------------------------------------- -// Bicycle model — reserved for a future steady-state yaw-moment feedforward -// (currently unused) -// ----------------------------------------------------------------------------- +// Reserved for a future steady-state yaw-moment feedforward (unused). struct BicycleModelConfig { - // dev19::cornerings_stiffness_n_rad is a per-TIRE value; the bicycle model needs - // per-AXLE stiffness, so multiply by 2 (two tires per axle). - static constexpr double c_f{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * - 2.0}; // front axle cornering stiffness [N/rad] - static constexpr double c_r{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * - 2.0}; // rear axle cornering stiffness [N/rad] - // typical FS values: 40 000–70 000 N/rad + // dev19::cornerings_stiffness_n_rad is per-TIRE; the bicycle model needs per-AXLE. + static constexpr double c_f{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * 2.0}; + static constexpr double c_r{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * 2.0}; }; struct PIDYawControllerConfig { - static constexpr double kp{600}; // Proportional term for yaw rate error tracking - static constexpr double ki{1}; // Integral term for yaw rate error tracking - static constexpr double kd{0}; // Derivative term on the yaw-rate error - static constexpr double i_max{ - 250.0}; // yaw integral-term saturation [Nm] — symmetric anti-windup clamp. - // Tune to the yaw-moment authority the allocator can realise. - static constexpr double d_tau{ - 0.02}; // low-pass time constant on the derivative term [s]. The yaw-rate - // error comes straight from the gyro, so the raw derivative is - // noise-dominated; this filters it before applying kd. + static constexpr double kp{600}; + static constexpr double ki{1}; + static constexpr double kd{0}; + static constexpr double i_max{250.0}; // yaw integral-term clamp [Nm] — size to the yaw + // authority the allocator can realise + static constexpr double d_tau{0.02}; // derivative low-pass time constant [s] }; struct LongitudinalPiConfig { - static constexpr double k_p{6.0}; // proportional gain [1/s] — velocity-loop bandwidth. - // Full Fx (grip clamp μg≈15.7 m/s²) is reached at a - // velocity error of μg/k_p; keep k_p low (~1–3) so - // tracking noise doesn't slam the demand to saturation. - static constexpr double k_i{0.5}; // integral gain [1/s²] - static constexpr double b{0.8}; // setpoint weight on the proportional term (2-DoF PI), - // [0, 1]. 1 → classic PI; <1 softens the proportional - // kick on reference steps without changing disturbance - // rejection (the integral still sees the full error). - static constexpr double eta{1.0}; // drivetrain efficiency - static constexpr double vx_ref_rate{ - 20.0}; // max rate of change of the velocity reference [m/s²]. Ramps vx_ref so a - // step target (e.g. launch from rest) doesn't slam Fx to saturation. - // Keep below the grip limit μ·g ≈ 15.7 m/s². + static constexpr double k_p{6.0}; // [1/s] — full Fx (grip clamp μg) is reached at a + // velocity error of μg/k_p; keep low so tracking + // noise doesn't slam the demand to saturation + static constexpr double k_i{0.5}; // [1/s²] + static constexpr double b{0.8}; // setpoint weight on the proportional term, [0, 1] + static constexpr double eta{1.0}; // drivetrain efficiency + static constexpr double vx_ref_rate{20.0}; // velocity-reference slew limit [m/s²] }; struct AllocatorConfig { @@ -112,14 +75,9 @@ struct AllocatorConfig { static constexpr double w_reg{0.01}; // torque magnitude regularisation }; -// ----------------------------------------------------------------------------- -// ROS node behaviour -// ----------------------------------------------------------------------------- struct NodeConfig { - static constexpr double input_timeout{ - 0.3}; // max age of the latest cmd_in / odom message [s]. If either input - // is older (or was never received), the node commands zero torque - // instead of acting on stale references. + static constexpr double input_timeout{0.3}; // max age of cmd_in / odom [s]; stale or + // missing inputs command zero torque }; struct Config { diff --git a/include/interfaces.hpp b/include/interfaces.hpp index 6c72f90..c12e894 100644 --- a/include/interfaces.hpp +++ b/include/interfaces.hpp @@ -6,22 +6,17 @@ namespace tv { -/// Type must provide: ForceVector estimate(const VehicleState&) template concept ForceEstimator = requires(T estimator, const VehicleState& state) { { estimator.estimateForcesImpl(state) } -> std::same_as; }; -/// Type must provide: YawMomentCommand computeImpl(const VehicleState&, const ForceVector&, const -/// SteeringCommand&) template concept YawMomentGenerator = requires(T generator, const VehicleState& state, const ForceVector& forces, const SteeringCommand& cmd) { { generator.computeImpl(state, forces, cmd) } -> std::same_as; }; -/// Type must provide: WheelTorques allocateImpl(const VehicleState&, const YawMomentCommand&, const -/// ForceVector&) template concept TorqueAllocator = requires(T allocator, const VehicleState& state, const YawMomentCommand& cmd, const ForceVector& forces) { diff --git a/include/orchestrator.hpp b/include/orchestrator.hpp index 4c5700b..e299e1b 100644 --- a/include/orchestrator.hpp +++ b/include/orchestrator.hpp @@ -11,8 +11,7 @@ namespace tv { -// Online mean / sample standard deviation (Welford's algorithm) — numerically -// stable, O(1) memory. Used for the per-stage timing statistics. +// Online mean / sample standard deviation (Welford's algorithm). class RunningStat { public: void add(double x) noexcept { @@ -42,21 +41,13 @@ class Orchestrator { yaw_generator_(std::move(yaw_generator)), torque_allocator_(std::move(torque_allocator)) {} - /// Execute the full pipeline for the given vehicle state and driver inputs. - /// `dt` is the elapsed time since the previous call [s]; it is forwarded to - /// any stage that needs a control period (e.g. the yaw controller's - /// integrators). Stages that do not expose setDt() are left untouched. - /// Returns the final wheel torques together with every intermediate signal - /// (tyre forces, yaw moment command) and per-stage execution times — this - /// cycle plus running mean / standard deviation since startup — so callers - /// can publish them for debug. Timing is measured with steady_clock and - /// returned rather than printed — no blocking I/O in the control loop. - /// `alloc_ok` is false when the allocator reported a failed solve (it holds - /// its previous solution), so callers can warn. + /// Runs the pipeline and returns the wheel torques together with every + /// intermediate signal and per-stage timing, for debug publication. `dt` is the + /// elapsed time since the previous call [s]. `alloc_ok` is false when the + /// allocator held its previous solution after a failed solve. [[nodiscard]] PipelineResult run(const VehicleState& state, const SteeringCommand& cmd, double dt) { - // Forward the control period to stages that track one. Kept optional via - // `requires` so the generic concepts don't have to mandate setDt(). + // Optional so the concepts don't have to mandate setDt(). if constexpr (requires(Y& y) { y.setDt(dt); }) { yaw_generator_.setDt(dt); } @@ -82,8 +73,6 @@ class Orchestrator { timing_stats_[2].add(timings.alloc_us); timing_stats_[3].add(timings.total_us); - // Surface a failed allocation when the stage reports one. Kept optional - // via `requires` so the generic concepts don't have to mandate it. bool alloc_ok = true; if constexpr (requires(const A& a) { { a.lastSolveOk() } -> std::convertible_to; @@ -106,10 +95,8 @@ class Orchestrator { .alloc_ok = alloc_ok}; } - /// Forward per-wheel feedback (motor torque, wheel angular velocity, and the - /// sample period between wheel-speed messages) to the force-estimation stage, - /// when that stage consumes it. No-op for stages that don't expose it, so the - /// generic concepts don't have to mandate updateWheelState(). + /// Forwards per-wheel feedback to the force-estimation stage, when that stage + /// consumes it. No-op otherwise, so the concepts needn't mandate it. void updateWheelState(const WheelTorques& motor_torques, const WheelOmegas& wheel_omegas, double dt) { if constexpr (requires(F& f) { f.updateWheelState(motor_torques, wheel_omegas, dt); }) { @@ -126,12 +113,10 @@ class Orchestrator { Y yaw_generator_; A torque_allocator_; - // Per-stage timing statistics [forces, yaw, alloc, total], accumulated over - // the whole run. + // [forces, yaw, alloc, total] std::array timing_stats_{}; }; -// CTAD: Orchestrator{f, y, a} deduces template args without explicit spelling template Orchestrator(F, Y, A) -> Orchestrator; diff --git a/include/ros_interface.hpp b/include/ros_interface.hpp index 1572228..f89c1b5 100644 --- a/include/ros_interface.hpp +++ b/include/ros_interface.hpp @@ -3,9 +3,8 @@ #include #include -#include - #include +#include #include #include #include @@ -33,10 +32,8 @@ namespace tv { /// Publication: /// cmd_out ros2can_msgs/DvControlTargetTv — per-wheel targets + steering /// -/// The pipeline is triggered on every IMU message. Odometry, wheel-speed, -/// motor-torque and steering updates are cached on receipt and take effect on -/// the next IMU tick. Wheel-speed messages carry their own sample period, used -/// by the DFO force estimator. +/// The pipeline runs on every IMU message; the other inputs are cached on receipt +/// and take effect on the next IMU tick. template class TVNode : public rclcpp::Node { public: @@ -67,9 +64,7 @@ class TVNode : public rclcpp::Node { torque_pub_ = create_publisher("cmd_out", 10); - // Debug publishers for every intermediate pipeline signal. These carry no - // control meaning — they exist for telemetry/plotting (rqt_plot, PlotJuggler). - // Wheel order for the array topics is [FL, FR, RL, RR]. + // Debug topics — telemetry only; wheel order [FL, FR, RL, RR]. tire_fx_pub_ = create_publisher("debug/tire_fx", 10); tire_fy_pub_ = create_publisher("debug/tire_fy", 10); tire_fz_pub_ = create_publisher("debug/tire_fz", 10); @@ -81,10 +76,9 @@ class TVNode : public rclcpp::Node { tracking_pub_ = create_publisher("debug/tracking", 10); #ifdef DEBUG - // Achieved virtual demand *after* the QP allocation, reconstructed from the - // allocated wheel torques. Divergence from debug/yaw_moment (the requested - // demand) shows how far the box/friction constraints pushed the solution off - // the request. + // Achieved virtual demand after allocation, reconstructed from the allocated + // torques. Divergence from debug/yaw_moment shows how far the box/friction + // constraints pushed the solution off the request. alloc_yaw_moment_pub_ = create_publisher("debug/alloc_yaw_moment", 10); alloc_fx_total_pub_ = create_publisher("debug/alloc_fx_total", 10); @@ -93,13 +87,21 @@ class TVNode : public rclcpp::Node { private: void imuCallback(const sensor_msgs::msg::Imu::SharedPtr& msg) { - state_.yaw_rate_ = msg->angular_velocity.z; // yaw_rate [rad/s] - state_.ax_ = msg->linear_acceleration.x; // ax [m/s²] - state_.ay_ = msg->linear_acceleration.y; // ay [m/s²] + if (first_imu_recieved_) { + // 200 ms imu filter, assumes imu at 100 hz + state_.yaw_rate_ = msg->angular_velocity.z; + state_.ax_ -= state_.ax_ / 20; + state_.ax_ += msg->linear_acceleration.x / 20; + state_.ay_ -= state_.ay_ / 20; + state_.ay_ += msg->linear_acceleration.y / 20; + } else { + first_imu_recieved_ = true; + state_.yaw_rate_ = msg->angular_velocity.z; + state_.ax_ = msg->linear_acceleration.x; + state_.ay_ = msg->linear_acceleration.y; + } - // Control period since the previous IMU tick, used by the stage - // integrators. Guarded so the first tick (and any out-of-order or - // duplicate stamps) yields dt = 0 rather than a bogus/negative step. + // dt = 0 on the first tick and on out-of-order or duplicate stamps. const rclcpp::Time stamp(msg->header.stamp); double dt = 0.0; if (have_last_stamp_ && stamp > last_stamp_) { @@ -108,8 +110,7 @@ class TVNode : public rclcpp::Node { last_stamp_ = stamp; have_last_stamp_ = true; - // Input watchdog: if driver commands or odometry are stale (or were never - // received), command zero torque instead of acting on old references. + // Stale or missing driver commands / odometry — command zero torque. const rclcpp::Time now_time = now(); const auto is_stale = [&](bool received, const rclcpp::Time& last_rx) { return !received || (now_time - last_rx).seconds() > NodeConfig::input_timeout; @@ -130,15 +131,15 @@ class TVNode : public rclcpp::Node { // The allocator holds its previous solution on a failed solve — surface it. if (!result.alloc_ok) { ++alloc_failures_; - RCLCPP_WARN_THROTTLE( - get_logger(), *get_clock(), 1000, - "torque allocation failed (%lu total) — holding previous solution", - static_cast(alloc_failures_)); + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 1000, + "torque allocation failed (%lu total) — holding previous solution", + static_cast(alloc_failures_)); } ros2can_msgs::msg::DvControlTargetTv out; // steering_angle_ is stored in radians internally; the CAN target expects degrees. - out.dv_steering_angle_target_tv = steering_cmd_.steering_angle_ * (180.0 / std::numbers::pi); + out.dv_steering_angle_target_tv = + steering_cmd_.steering_angle_ * (180.0 / std::numbers::pi); out.dv_fl_speedd_target = torques[0]; out.dv_fr_speed_target = torques[1]; out.dv_rl_speed_target = torques[2]; @@ -148,7 +149,6 @@ class TVNode : public rclcpp::Node { publishDebug(result); } - // Publishes each intermediate pipeline stage on its own debug topic. void publishDebug(const PipelineResult& result) { const auto to_msg = [](const std::array& src) { std_msgs::msg::Float64MultiArray msg; @@ -156,55 +156,40 @@ class TVNode : public rclcpp::Node { return msg; }; - // Stage 1 — tyre force estimate (per wheel). tire_fx_pub_->publish(to_msg(result.forces.fx_)); tire_fy_pub_->publish(to_msg(result.forces.fy_)); tire_fz_pub_->publish(to_msg(result.forces.fz_)); - // Stage 2 — high-level yaw moment command: [mz (Nm), fx_total (N)]. + // [mz (Nm), fx_total (N)] std_msgs::msg::Float64MultiArray yaw_msg; yaw_msg.data = {result.yaw_cmd.mz_, result.yaw_cmd.fx_total_}; yaw_moment_pub_->publish(yaw_msg); - // Stage 3 — allocated wheel torques [FL, FR, RL, RR] (Nm). + // [FL, FR, RL, RR] (Nm) std_msgs::msg::Float64MultiArray torque_msg; torque_msg.data = {result.torques[0], result.torques[1], result.torques[2], result.torques[3]}; wheel_torques_pub_->publish(torque_msg); - // Per-stage pipeline execution times (µs), three blocks of - // [forces, yaw, alloc, total]: this cycle, running mean, and running - // standard deviation since startup. + // Three blocks of [forces, yaw, alloc, total] in µs: this cycle, mean, stddev. std_msgs::msg::Float64MultiArray timing_msg; - timing_msg.data = {result.timings.forces_us, result.timings.yaw_us, - result.timings.alloc_us, result.timings.total_us, - result.timings_avg.forces_us, result.timings_avg.yaw_us, - result.timings_avg.alloc_us, result.timings_avg.total_us, - result.timings_std.forces_us, result.timings_std.yaw_us, - result.timings_std.alloc_us, result.timings_std.total_us}; + timing_msg.data = { + result.timings.forces_us, result.timings.yaw_us, result.timings.alloc_us, + result.timings.total_us, result.timings_avg.forces_us, result.timings_avg.yaw_us, + result.timings_avg.alloc_us, result.timings_avg.total_us, result.timings_std.forces_us, + result.timings_std.yaw_us, result.timings_std.alloc_us, result.timings_std.total_us}; timing_pub_->publish(timing_msg); - // Controller tracking: [r_ref, r, r_ref − r, vx_ref, vx, vx_ref − vx]. - // A yaw-rate error that never changes sign (or r_ref/r with opposite - // signs in a corner) points at a reference sign/unit mismatch or the - // yaw integral riding its clamp — the usual causes of a standing - // left/right torque split. + // [r_ref, r, r_ref − r, vx_ref, vx, vx_ref − vx] std_msgs::msg::Float64MultiArray tracking_msg; - tracking_msg.data = {steering_cmd_.r_ref_, - state_.yaw_rate_, - steering_cmd_.r_ref_ - state_.yaw_rate_, - steering_cmd_.vx_ref_, - state_.vx_, - steering_cmd_.vx_ref_ - state_.vx_}; + tracking_msg.data = { + steering_cmd_.r_ref_, state_.yaw_rate_, steering_cmd_.r_ref_ - state_.yaw_rate_, + steering_cmd_.vx_ref_, state_.vx_, steering_cmd_.vx_ref_ - state_.vx_}; tracking_pub_->publish(tracking_msg); #ifdef DEBUG - // Achieved [Mz, Fx_total] after allocation. Undo the allocator's output map - // (T_motor = F·R / gear_ratio) to recover the per-wheel driving force - // F = T·gear_ratio / R, then apply the dependency matrix G (wheel order - // [FL, FR, RL, RR]): - // Fx_total = F_FL + F_FR + F_RL + F_RR - // Mz = -sf·F_FL + sf·F_FR - sr·F_RL + sr·F_RR + // Achieved [Mz, Fx_total]: undo the allocator's output map + // (F = T·gear_ratio / R), then apply G. const double sf = VehicleConfig::trackwidth_front / 2.0; const double sr = VehicleConfig::trackwidth_rear / 2.0; std::array f{}; // per-wheel driving force [N], [FL, FR, RL, RR] @@ -223,14 +208,13 @@ class TVNode : public rclcpp::Node { } void steeringCallback(const fs_msgs::msg::CarCommand::SharedPtr& msg) { - // CarCommand.steering is a road-wheel angle in degrees; the pipeline works - // in radians throughout, so convert on ingress. + // CarCommand.steering is in degrees; the pipeline works in radians throughout. const double steering_rad = msg->steering * (std::numbers::pi / 180.0); - steering_cmd_.steering_angle_ = steering_rad; // steering_angle [rad] - steering_cmd_.vx_ref_ = msg->velocity; // vx_ref [m/s] - steering_cmd_.r_ref_ = msg->yaw_rate; // r_ref [rad/s] - state_.steering_angle_ = steering_rad; // mirror into VehicleState + steering_cmd_.steering_angle_ = steering_rad; + steering_cmd_.vx_ref_ = msg->velocity; + steering_cmd_.r_ref_ = msg->yaw_rate; + state_.steering_angle_ = steering_rad; // mirror into VehicleState last_cmd_rx_ = now(); have_cmd_ = true; @@ -238,16 +222,23 @@ class TVNode : public rclcpp::Node { // Body-frame velocities from odometry; consumed on the next IMU tick. void odomCallback(const nav_msgs::msg::Odometry::SharedPtr& msg) { - state_.vx_ = msg->twist.twist.linear.x; // vx [m/s] - state_.vy_ = msg->twist.twist.linear.y; // vy [m/s] - - last_odom_rx_ = now(); - have_odom_ = true; + if (first_odom_recieved_) { + // 200 ms odometry filter, assumes odometry at 100 hz + state_.vx_ -= state.vx_ / 20; + state_.vy_ -= state.vy_ / 20; + state_.vx_ += msg->twist.twist.linear.x / 20; + state_.vy_ += msg->twist.twist.linear.y / 20; + } else { + first_odom_recieved_ = true; + state_.vx_ = msg->twist.twist.linear.x; + state_.vy_ = msg->twist.twist.linear.y; + } + last_odom_rx_ = now(); + have_odom_ = true; } - // Per-wheel angular velocities [FL, FR, RL, RR] (rad/s) for the DFO. The - // sample period is derived from consecutive wheel-speed stamps and forwarded - // to the force estimator together with the latest motor-torque feedback. + // Per-wheel ω [FL, FR, RL, RR] (rad/s) for the DFO; the sample period comes from + // consecutive wheel-speed stamps. void wheelSpeedsCallback(const fs_msgs::msg::Wheelspeeds::SharedPtr& msg) { WheelOmegas omegas; omegas << msg->front_left, msg->front_right, msg->rear_left, msg->rear_right; @@ -263,8 +254,7 @@ class TVNode : public rclcpp::Node { orchestrator_.updateWheelState(motor_torques_, omegas, dt); } - // Latest per-wheel motor-torque feedback [FL, FR, RL, RR] (Nm), cached for - // the DFO (published at a slower rate than the wheel speeds). + // Cached for the DFO — published at a slower rate than the wheel speeds. void motorTorquesCallback(const ros2can_msgs::msg::VehicleStatusMotorTorques::SharedPtr& msg) { motor_torques_ << msg->torque_fl, msg->torque_fr, msg->torque_rl, msg->torque_rr; } @@ -272,11 +262,11 @@ class TVNode : public rclcpp::Node { rclcpp::Subscription::SharedPtr imu_sub_; rclcpp::Subscription::SharedPtr odom_sub_; rclcpp::Subscription::SharedPtr wheel_speeds_sub_; - rclcpp::Subscription::SharedPtr motor_torques_sub_; + rclcpp::Subscription::SharedPtr + motor_torques_sub_; rclcpp::Subscription::SharedPtr steering_sub_; rclcpp::Publisher::SharedPtr torque_pub_; - // Debug publishers for intermediate pipeline stages. rclcpp::Publisher::SharedPtr tire_fx_pub_; rclcpp::Publisher::SharedPtr tire_fy_pub_; rclcpp::Publisher::SharedPtr tire_fz_pub_; @@ -292,33 +282,32 @@ class TVNode : public rclcpp::Node { #endif Orchestrator orchestrator_; - VehicleState state_{}; // vx_, vy_, yaw_rate_, steering_angle_, ax_, ay_ - SteeringCommand steering_cmd_{}; // steering_angle_, vx_ref_, r_ref_ + VehicleState state_{}; + SteeringCommand steering_cmd_{}; // Latest per-wheel motor-torque feedback [FL, FR, RL, RR] (Nm) for the DFO. WheelTorques motor_torques_{WheelTorques::Zero()}; - // Timestamp of the previous IMU message, used to derive the control period. + // Previous IMU stamp — derives the control period. rclcpp::Time last_stamp_{0, 0, RCL_ROS_TIME}; bool have_last_stamp_{false}; - // Timestamp of the previous wheel-speed message, used to derive the DFO - // sample period. + // Previous wheel-speed stamp — derives the DFO sample period. rclcpp::Time last_wheel_stamp_{0, 0, RCL_ROS_TIME}; bool have_last_wheel_stamp_{false}; - // Receive times of the latest cmd_in / odom messages (node clock), for the - // input watchdog — stale inputs make the node command zero torque. + // Receive times for the input watchdog (node clock). rclcpp::Time last_cmd_rx_{0, 0, RCL_ROS_TIME}; bool have_cmd_{false}; rclcpp::Time last_odom_rx_{0, 0, RCL_ROS_TIME}; bool have_odom_{false}; - // Count of control cycles where the allocator fell back to zero torque. + bool first_imu_recieved_{false}; + bool first_odom_recieved_{false}; + std::size_t alloc_failures_{0}; }; -// CTAD deduction guides template TVNode(Orchestrator) -> TVNode; diff --git a/include/tv/kinematic_force_estimator.hpp b/include/tv/kinematic_force_estimator.hpp index 4fef485..3f7a37d 100644 --- a/include/tv/kinematic_force_estimator.hpp +++ b/include/tv/kinematic_force_estimator.hpp @@ -12,17 +12,6 @@ namespace tv { class KinematicForceEstimator : public IForceEstimator { public: - // Vehicle params: - // mass [kg] - // cg_height [m] - // wheelbase [m] - // l_r distance from rear axle to CG [m] - // trackwidth [m] - // front_tlltd front total lateral load transfer distribution fraction (0–1) - // DFO params: - // j_w wheel + motor rotational inertia [kg·m²] - // r_eff effective wheel radius [m] - // lpf_tau low-pass filter time constant [s] KinematicForceEstimator() : mass_(VehicleConfig::mass), cg_height_(VehicleConfig::cg_height), @@ -36,26 +25,17 @@ class KinematicForceEstimator : public IForceEstimator eta_(ForceEstimatorConfig::eta), lpf_tau_(ForceEstimatorConfig::lpf_tau) {} - // Feed per-wheel sensor data as it arrives. - // motor_torques inverter torque demand [FL, FR, RL, RR] (Nm) - // wheel_omegas wheel angular velocities [FL, FR, RL, RR] (rad/s) - // dt time since last update (s) - // - // --- Fx: Driving Force Observer (DFO) --- - // Wheel-axle torque balance: J_w·dω/dt = T_wheel − F_x·R_eff, so - // F̂_x = (1/R_eff) * [T_wheel − J_w·dω/dt], smoothed by first-order LPF. - // The inverter reports motor-side torque, so convert to the wheel axle - // (T_wheel = N·η·T_motor) to keep it consistent with the wheel-side ω, - // wheel-referred inertia J_w, and wheel radius R_eff. + // Driving Force Observer, from the wheel-axle torque balance + // J_w·dω/dt = T_wheel − F_x·R_eff: + // F̂_x = (T_wheel − J_w·dω/dt) / R_eff, T_wheel = N·η·T_motor + // The inverter reports motor-side torque, hence the conversion to the wheel + // axle, where ω, J_w and R_eff live. Wheel order [FL, FR, RL, RR]; dt is the + // wheel-speed sample period [s] — the DFO runs here rather than at control + // rate so the LPF honours lpf_tau whatever the IMU rate is. // Reference: Hori (2004), adopted by FS Team Tallinn (world #1 FSE 2024). - // - // The DFO and its LPF run here — at the wheel-speed sample rate — rather - // than in estimateForcesImpl (control rate), so the filter honours lpf_tau - // regardless of how the IMU and wheel-speed rates relate. void updateWheelState(const WheelTorques& motor_torques, const WheelOmegas& wheel_omegas, double dt) { - // Seed on the first sample so dω/dt doesn't spike when the node starts - // while the car is already moving. + // Seed on the first sample so dω/dt doesn't spike at startup. if (!wheel_init_) { current_omegas_ = wheel_omegas; wheel_init_ = true; @@ -83,11 +63,9 @@ class KinematicForceEstimator : public IForceEstimator ForceVector forces{}; - // --- Fx: latest DFO estimate (filtered in updateWheelState) --- for (int i = 0; i < 4; ++i) forces.fx_[i] = fx_filtered_[i]; - // --- Fz: quasi-static load transfer (AMZ acceleration-based method) --- - // Uses IMU ax, ay directly — no kinematic approximation. + // Quasi-static load transfer from IMU ax, ay — no kinematic approximation. // Reference: AMZ Racing (ETH Zurich), docs/tire_forces.md §1. const double fz_front_static = 0.5 * mass_ * kGravity * l_r_ / wheelbase_; const double fz_rear_static = 0.5 * mass_ * kGravity * l_f / wheelbase_; @@ -102,13 +80,9 @@ class KinematicForceEstimator : public IForceEstimator forces.fz_[2] = fz_rear_static + delta_fz_long - delta_fz_lat_rear; // RL forces.fz_[3] = fz_rear_static + delta_fz_long + delta_fz_lat_rear; // RR - // --- Fy: steady-state bicycle model (using IMU ay) --- - // The axle force is split per wheel by its share of the axle load, not - // 50/50: tyre lateral force scales roughly with normal load, so during - // cornering the unloaded inner wheel carries proportionally less Fy. - // An even split overstated the inner wheel's Fy, which collapsed its - // friction-circle budget √((μ·Fz)² − Fy²) in the allocator to zero and - // pinned that wheel's torque at 0 through every corner. + // Steady-state bicycle model. The axle force is split by each wheel's share of + // the axle load, not 50/50: an even split overstates the unloaded inner wheel's + // Fy, collapsing its friction-circle budget in the allocator to zero. const double fy_front_axle = (l_r_ / wheelbase_) * mass_ * ay; const double fy_rear_axle = (l_f / wheelbase_) * mass_ * ay; @@ -130,7 +104,6 @@ class KinematicForceEstimator : public IForceEstimator } private: - // Vehicle parameters double mass_; double cg_height_; double wheelbase_; @@ -138,19 +111,17 @@ class KinematicForceEstimator : public IForceEstimator double trackwidth_; double front_tlltd_; // front TLLTD fraction, e.g. 0.52 - // DFO parameters double j_w_; // rotational inertia referred to the wheel [kg·m²] double r_eff_; // effective wheel radius [m] double gear_ratio_; // motor → wheel gear ratio double eta_; // drivetrain efficiency (motor → wheel) double lpf_tau_; // LPF time constant [s] - // DFO state WheelOmegas prev_omegas_{WheelOmegas::Zero()}; WheelOmegas current_omegas_{WheelOmegas::Zero()}; WheelTorques motor_torques_{WheelTorques::Zero()}; Eigen::Vector4d fx_filtered_{Eigen::Vector4d::Zero()}; - bool wheel_init_{false}; // seed prev/current omegas from the first sample + bool wheel_init_{false}; }; } // namespace tv diff --git a/include/tv/ldlt_torque_allocator.hpp b/include/tv/ldlt_torque_allocator.hpp index 003426b..defea49 100644 --- a/include/tv/ldlt_torque_allocator.hpp +++ b/include/tv/ldlt_torque_allocator.hpp @@ -9,66 +9,33 @@ namespace tv { // Torque allocator solving the distribution problem in closed form via an -// LDLᵀ (Cholesky-with-pivoting) factorisation (docs/tv.md §optimal allocation). +// LDLᵀ factorisation (docs/tv.md §optimal allocation). // -// Unconstrained weighted least-squares formulation (driving-force decision -// variable — radius-independent G): -// min (Gu − v)ᵀ W₁ (Gu − v) + uᵀ W₂ u +// min (Gu − v)ᵀ W₁ (Gu − v) + uᵀ W₂ u → (GᵀW₁G + W₂) u = GᵀW₁ v // u // // u = [F_FL, F_FR, F_RL, F_RR]ᵀ per-wheel driving forces [N] // v = [Fx_total, Mz]ᵀ virtual demand +// G = [[1, 1, 1, 1], [-sf, sf, -sr, sr]] sf = tf/2, sr = tr/2 +// W₁ = diag(w_fx, w_mz) +// W₂ = diag(w_reg · Fz_avg / Fz_i) load-inverse, so the lowest-grip tyre is +// used least; the Fz_avg normalisation keeps w_reg's scale // -// Dependency matrix G (2×4) — depends only on the half-track widths: -// Fx row: [ 1, 1, 1, 1 ] -// Mz row: [-sf, sf, -sr, sr ] sf = tf/2, sr = tr/2 +// GᵀW₁G alone is rank-2 — infinitely many splits realise the same [Fx, Mz]; the +// load-inverse W₂ ≻ 0 makes the Hessian SPD and picks the unique physical split. // -// W₁ = diag(w_fx, w_mz) demand tracking weights -// W₂ = diag(w_reg · Fz_avg / Fz_i) load-inverse regularisation — each wheel is -// penalised inversely to its load, so the -// lowest-grip tyre is used least (normalised by -// the mean load Fz_avg so w_reg keeps its scale) -// -// Because there are no inequality constraints, the optimum is the solution of the -// normal equations (setting ∇J = 0; the factor of 2 cancels): -// (GᵀW₁G + W₂) u = GᵀW₁ v -// -// G is 2×4, so GᵀW₁G is rank-2 (singular) on its own: infinitely many force splits -// realise the same [Fx, Mz]. The load-inverse W₂ ≻ 0 makes the Hessian symmetric -// positive definite, picking the unique physically-meaningful split and letting us -// factor with LDLᵀ. On a 4×4 system this is essentially free — factor once per -// cycle, then forward/back-substitute. +// No friction-circle limits: adding them would make this a genuinely constrained +// QP for which the closed form no longer holds. Only the per-wheel motor +// saturation t_max is applied, on the output — clipping a wheel independently +// distorts the realised [Fx, Mz]. // // The wheel radius enters only at the output: T_motor = F · R / gear_ratio. -// -// NOTE: the closed form enforces no friction-circle limits — those are assumed to be -// handled upstream, since adding them would make this a genuinely constrained QP for -// which the closed form no longer holds. The one exception is a hard per-wheel motor- -// torque saturation applied to the output (see t_max): a simple symmetric clip that -// keeps every command within actuator authority. Clipping a wheel independently -// distorts the realised [Fx, Mz], but this is the standard downstream saturation and -// keeps the solver from ever commanding an unachievable torque. -// // Reference: De Novellis et al. (SAE 2013-01-0673) class LdltTorqueAllocator : public ITorqueAllocator { public: - // Vehicle geometry / powertrain: - // r_w wheel radius [m] - // gear_ratio motor → wheel gear ratio (output: T_motor = F·R / gear_ratio) - // t_f front track width [m] - // t_r rear track width [m] - // t_max per-wheel motor-torque limit [Nm]; each output is clipped to - // [-t_max, t_max]. Use a large value to effectively disable. - // - // QP weights: - // w_fx weight on Fx tracking error - // w_mz weight on Mz tracking error (typically >> w_fx for racing) - // w_reg load-inverse regularisation weight on driving-force magnitude LdltTorqueAllocator(double r_w, double gear_ratio, double t_f, double t_r, double w_fx, double w_mz, double w_reg, double t_max) : r_w_(r_w), gear_ratio_(gear_ratio), w_reg_(w_reg), t_max_(t_max) { - // --- Dependency matrix G (2×4): driving forces → [Fx, Mz] --- - // Radius-independent — depends only on the half-track widths. const double sf = t_f / 2.0; const double sr = t_r / 2.0; @@ -77,40 +44,23 @@ class LdltTorqueAllocator : public ITorqueAllocator { -sf, sf, -sr, sr; // clang-format on - // --- W1 = diag(w_fx, w_mz) --- Eigen::Matrix2d w1_mat = Eigen::Matrix2d::Zero(); w1_mat(0, 0) = w_fx; w1_mat(1, 1) = w_mz; - // Precompute GᵀW₁ (4×2) — reused each cycle for the rhs GᵀW₁·v and the - // constant tracking part of the Hessian GᵀW₁G. gt_w1_ = g_mat_.transpose() * w1_mat; - - // Constant tracking part of the Hessian, GᵀW₁G (rank-2; the per-cycle - // load-inverse W₂ diagonal added on top makes the full H positive definite). h_track_ = gt_w1_ * g_mat_; } - // VehicleState: [vx, vy, yaw_rate, steering_angle, ax, ay] - // YawMomentCommand: {mz_, fx_total_} - // ForceVector: [Fx×4, Fy×4, Fz×4] [[nodiscard]] WheelTorques allocateImpl(const VehicleState& state, const YawMomentCommand& cmd, const ForceVector& forces) { (void)state; // reserved for speed-dependent torque maps - // Pessimistically mark the solve as failed; set true only on a clean solve. - // Queried by the orchestrator via lastSolveOk() so the ROS node can warn - // when the fallback (previous solution) was used. last_solve_ok_ = false; - // --- rhs: GᵀW₁·v --- const Eigen::Vector2d v_demand{cmd.fx_total_, cmd.mz_}; const Eigen::Vector4d rhs = gt_w1_ * v_demand; - // --- Load-inverse regularisation: W₂ = diag(w_reg · Fz_avg / Fz_i) --- - // Penalise each wheel inversely to its load so the lowest-grip tyre is used - // least. Normalised by the mean load so w_reg keeps its scale and H stays - // well-conditioned. double fz_sum = 0.0; for (int i = 0; i < 4; ++i) fz_sum += std::max(0.0, forces.fz_[i]); const double fz_avg = std::max(kFzFloor, fz_sum / 4.0); @@ -121,26 +71,20 @@ class LdltTorqueAllocator : public ITorqueAllocator { h(i, i) += w_reg_ * (fz_avg / fz); } - // --- LDLᵀ factorisation + solve of (GᵀW₁G + W₂) u = GᵀW₁ v --- - // H is SPD while w_reg > 0, so LLT would also be valid; LDLᵀ's symmetric - // pivoting is preferred because the tracking part GᵀW₁G is rank-2 and the - // two null-space directions are lifted only by the small load-inverse W₂, - // leaving H weakly conditioned there. LDLᵀ degrades gracefully (and still - // factors) if w_reg is ever set to 0, where the matrix becomes singular. + // LDLᵀ rather than LLT: GᵀW₁G is rank-2 and those null-space directions are + // lifted only by the small W₂, leaving H weakly conditioned there. LDLᵀ's + // symmetric pivoting degrades gracefully, and still factors at w_reg = 0. Eigen::LDLT ldlt(h); if (ldlt.info() != Eigen::Success) { return last_torques_; // hold previous solution on numerical breakdown } Eigen::Vector4d u = ldlt.solve(rhs); - // Convert per-wheel driving force to motor torque: T_motor = F·R / gear_ratio, - // then clip to the per-wheel actuator limit so no wheel is ever commanded - // beyond motor authority (see NOTE above on the resulting [Fx, Mz] distortion). + // Driving force → motor torque, clipped to actuator authority. for (int i = 0; i < 4; ++i) { u[i] = std::clamp((u[i] * r_w_) / gear_ratio_, -t_max_, t_max_); } - // Guard against NaN/Inf — hold the previous solution. if (!u.allFinite()) { return last_torques_; } @@ -150,36 +94,25 @@ class LdltTorqueAllocator : public ITorqueAllocator { return u; } - // False when the most recent allocate() fell back to the previous solution - // (numerical breakdown or a non-finite solution). + // False when the last allocate() fell back to the previous solution. [[nodiscard]] bool lastSolveOk() const noexcept { return last_solve_ok_; } private: - // Vehicle geometry / powertrain double r_w_; // wheel radius [m] double gear_ratio_; // motor → wheel gear ratio double w_reg_; // load-inverse regularisation weight double t_max_; // per-wheel motor-torque saturation limit [Nm] - // Dependency matrix G (2×4), constant across cycles. Eigen::Matrix g_mat_; + Eigen::Matrix gt_w1_; // GᵀW₁ + Eigen::Matrix4d h_track_; // GᵀW₁G; the W₂ diagonal is added each cycle - // Precomputed GᵀW₁ (4×2, constant across cycles). - Eigen::Matrix gt_w1_; - - // Constant tracking part of the Hessian, GᵀW₁G (4×4). The load-inverse - // regularisation diagonal is added on top each cycle. - Eigen::Matrix4d h_track_; - - // Whether the most recent allocate() produced a clean solution. bool last_solve_ok_{true}; - // Most recent clean solution (motor torques), returned when a solve fails. - // Zero until the first successful solve. + // Held and re-returned when a solve fails; zero until the first success. WheelTorques last_torques_{WheelTorques::Zero()}; - // Lower bound on wheel load [N] used in the 1/Fz weighting to avoid a - // divide-by-zero / unbounded penalty when a wheel is unloaded. + // Floor on Fz [N] so the 1/Fz weighting stays bounded for an unloaded wheel. static constexpr double kFzFloor = 1.0; }; diff --git a/include/tv/pid_yaw_controller.hpp b/include/tv/pid_yaw_controller.hpp index a0d4090..98aa8ce 100644 --- a/include/tv/pid_yaw_controller.hpp +++ b/include/tv/pid_yaw_controller.hpp @@ -13,31 +13,8 @@ namespace tv { // // Yaw moment: PID on the yaw-rate error (derivative low-pass filtered) // Fx demand : 2-DoF PI velocity tracker (TU Munich / KIT FSG approach) -// -// SteeringCommand layout: [delta (rad), vx_ref (m/s), r_ref (rad/s)] -// Call setDt(dt) once per control cycle before computeImpl. class PIDYawController : public IYawController { public: - // Yaw PID params: - // kp_yaw proportional gain on yaw-rate error - // ki_yaw integral gain on yaw-rate error - // kd_yaw derivative gain on the yaw-rate error - // i_max_yaw symmetric saturation on the integral term |ki·∫e_r dt| [Nm] - // d_tau_yaw low-pass time constant on the derivative term [s] - // - // Longitudinal 2-DoF PI params: - // mass vehicle mass [kg] - // k_p proportional gain [1/s] - // k_i integral gain [1/s²] - // b setpoint weight on the proportional term [0, 1] (2-DoF PI) - // eta drivetrain efficiency (0, 1] - // mu tyre-road friction coefficient (for the Fx grip clamp) - // vx_ref_rate max slew of the velocity reference [m/s²] - // - // ep = b·vx_ref − vx (setpoint-weighted proportional error) - // ev = vx_ref − vx (integral error — sees the full error) - // Fx_total = clamp((k_p·ep + k_i·∫ev dt) · mass / eta, ±μ·m·g) - // Errors are formed against a rate-limited vx_ref (slew ≤ vx_ref_rate). PIDYawController(double kp_yaw, double ki_yaw, double kd_yaw, double i_max_yaw, double d_tau_yaw, double mass, double k_p, double k_i, double b, double eta, double mu, double vx_ref_rate) @@ -54,7 +31,6 @@ class PIDYawController : public IYawController { mu_(mu), vx_ref_rate_(vx_ref_rate) {} - // Default: all parameters from config.hpp. PIDYawController() : PIDYawController(PIDYawControllerConfig::kp, PIDYawControllerConfig::ki, PIDYawControllerConfig::kd, PIDYawControllerConfig::i_max, @@ -66,8 +42,6 @@ class PIDYawController : public IYawController { // Must be called once per control cycle before computeImpl. void setDt(double dt) { dt_ = dt; } - // VehicleState: [vx, vy, yaw_rate, steering_angle, ax, ay] - // SteeringCommand: uses steering_angle_, vx_ref_, r_ref_ [[nodiscard]] YawMomentCommand computeImpl(const VehicleState& s, const ForceVector& forces, const SteeringCommand& cmd) { (void)forces; // reserved for future combined-slip feedforward @@ -77,11 +51,8 @@ class PIDYawController : public IYawController { const double vx_ref = cmd.vx_ref_; const double r_ref = cmd.r_ref_; - // PID for yaw rate tracking. - // Yaw-rate error is bidirectional (r_ref < 0 in right-hand turns), so the - // integrator must accumulate in both directions. Anti-windup is a symmetric - // clamp on the integral term rather than a one-sided reset — the previous - // `if (e_r < 0) reset` dumped the integral on every right turn. + // The yaw-rate error is bidirectional (r_ref < 0 in right-hand turns), so + // anti-windup must be a symmetric clamp, not a one-sided reset. const double e_r = r_ref - r; e_r_integral_ += e_r * dt_; if (ki_yaw_ > 0.0) { @@ -89,9 +60,8 @@ class PIDYawController : public IYawController { e_r_integral_ = std::clamp(e_r_integral_, -integral_limit, integral_limit); } - // Derivative term on the yaw-rate error, low-pass filtered (time constant - // d_tau_yaw). The error comes straight from the gyro, so the raw finite - // difference is noise-dominated — kd on it would inject noise into Mz. + // The error comes straight from the gyro, so the raw finite difference is + // noise-dominated — low-pass it before applying kd. double mz_d = 0.0; if (yaw_d_init_ && dt_ > 0.0) { const double de_r_raw = (e_r - e_r_prev_) / dt_; @@ -104,14 +74,8 @@ class PIDYawController : public IYawController { const double mz = (kp_yaw_ * e_r) + (ki_yaw_ * e_r_integral_) + mz_d; - // ----------------------------------------------------------------------- - // Fx demand — 2-DoF PI velocity tracker (no feedforward). - // - // Fx_total = (k_p·ep + k_i·∫ev dt) · m / η - // ----------------------------------------------------------------------- // Rate-limit the velocity reference so a stepped target (e.g. launch from - // rest) can't produce a huge instantaneous error that slams Fx to - // saturation. Seed the ramp from the current speed on the first tick. + // rest) can't slam Fx to saturation; seed the ramp from the current speed. if (!vx_ref_init_) { vx_ref_ramped_ = vx; vx_ref_init_ = true; @@ -119,14 +83,11 @@ class PIDYawController : public IYawController { const double max_step = vx_ref_rate_ * dt_; vx_ref_ramped_ = std::clamp(vx_ref, vx_ref_ramped_ - max_step, vx_ref_ramped_ + max_step); - // 2-DoF PI: the integral acts on the full error (drives steady-state to - // zero), while the proportional acts on a setpoint-weighted error so a - // reference step doesn't produce a full proportional kick. - // Anti-windup is a symmetric clamp sized so the integral term alone stays - // within the grip limit — the error is bidirectional (overspeed needs a - // negative Fx), so a one-sided reset would dump the integral on every - // overshoot of the ramped reference and preclude integral action while - // decelerating. + // 2-DoF PI: Fx_total = (k_p·ep + k_i·∫ev dt)·m/η. The integral sees the full + // error; the proportional a setpoint-weighted one, so a reference step doesn't + // produce a full proportional kick. The clamp is sized so the integral term + // alone stays within the grip limit, and is symmetric because the error is + // bidirectional (overspeed needs a negative Fx). const double e_vx = vx_ref_ramped_ - vx; // integral error const double e_vx_p = (b_sp_ * vx_ref_ramped_) - vx; // proportional error e_vx_integral_ += e_vx * dt_; @@ -137,43 +98,37 @@ class PIDYawController : public IYawController { const double fx_raw = ((kp_longi_ * e_vx_p) + (ki_longi_ * e_vx_integral_)) * (mass_ / eta_); - // Clamp to the longitudinal grip limit ±μ·m·g so the demand stays within - // what the tyres can deliver (the allocator would otherwise ride saturation). + // Keep the demand inside the longitudinal grip limit ±μ·m·g. const double fx_max = mu_ * mass_ * kGravity; const double fx_total = std::clamp(fx_raw, -fx_max, fx_max); return YawMomentCommand{.mz_ = mz, .fx_total_ = fx_total}; } private: - // PID Yaw parameters const double kp_yaw_; const double ki_yaw_; - const double kd_yaw_; // derivative gain (on yaw-rate error) + const double kd_yaw_; const double i_max_yaw_; // symmetric integral-term clamp [Nm] const double d_tau_yaw_; // derivative low-pass time constant [s] - // Longitudinal 2-DoF PI parameters const double mass_; // vehicle mass [kg] - const double kp_longi_; // proportional gain [1/s] - const double ki_longi_; // integral gain [1/s²] + const double kp_longi_; // [1/s] + const double ki_longi_; // [1/s²] const double b_sp_; // setpoint weight on the proportional term [0, 1] const double eta_; // drivetrain efficiency - const double mu_; // tyre-road friction coefficient (Fx grip clamp) + const double mu_; // tyre-road friction coefficient const double vx_ref_rate_; // max velocity-reference slew [m/s²] - // Yaw PID state - double e_r_integral_{0.0}; // integral of yaw rate error [rad] - double e_r_prev_{0.0}; // previous yaw-rate error [rad/s] (for the derivative term) - double de_r_filt_{0.0}; // low-pass-filtered error derivative [rad/s²] - bool yaw_d_init_{false}; // seed e_r_prev_ on the first tick to avoid a spike + double e_r_integral_{0.0}; // [rad] + double e_r_prev_{0.0}; // [rad/s] + double de_r_filt_{0.0}; // [rad/s²] + bool yaw_d_init_{false}; - // PI state - double e_vx_integral_{0.0}; // integral of velocity error [m] - double vx_ref_ramped_{0.0}; // rate-limited velocity reference [m/s] - bool vx_ref_init_{false}; // seed the ramp from measured vx on first tick + double e_vx_integral_{0.0}; // [m] + double vx_ref_ramped_{0.0}; // [m/s] + bool vx_ref_init_{false}; - // Time step — updated each cycle via setDt() - double dt_{0.0}; + double dt_{0.0}; // control period [s], set each cycle via setDt() }; } // namespace tv diff --git a/include/tv/qp_torque_allocator.hpp b/include/tv/qp_torque_allocator.hpp index 3310606..07735f8 100644 --- a/include/tv/qp_torque_allocator.hpp +++ b/include/tv/qp_torque_allocator.hpp @@ -16,57 +16,28 @@ namespace tv { // Torque allocator solving the distribution problem via OSQP (docs/tv.md §optimal allocation). // -// QP formulation (driving-force decision variable — radius-independent G): // min (Gu − v)ᵀ W₁ (Gu − v) + uᵀ W₂ u // u // // u = [F_FL, F_FR, F_RL, F_RR]ᵀ per-wheel driving forces [N] // v = [Fx_total, Mz]ᵀ virtual demand +// G = [[1, 1, 1, 1], [-sf, sf, -sr, sr]] sf = tf/2, sr = tr/2 +// W₁ = diag(w_fx, w_mz) +// W₂ = diag(w_reg · Fz_avg / Fz_i) load-inverse, so the lowest-grip tyre is +// used least; the Fz_avg normalisation keeps w_reg's scale // -// Dependency matrix G (2×4) — depends only on the half-track widths: -// Fx row: [ 1, 1, 1, 1 ] -// Mz row: [-sf, sf, -sr, sr ] sf = tf/2, sr = tr/2 -// -// W₁ = diag(w_fx, w_mz) demand tracking weights -// W₂ = diag(w_reg · Fz_avg / Fz_i) load-inverse regularisation — each wheel is -// penalised inversely to its load, so the -// lowest-grip tyre is used least (normalised by -// the mean load Fz_avg so w_reg keeps its scale) -// -// Rewritten in standard OSQP form min 0.5 uᵀPu + qᵀu, s.t. lb ≤ Iu ≤ ub: -// P = 2(GᵀW₁G + W₂) (GᵀW₁G constant; the W₂ diagonal is refreshed each cycle -// from the current wheel loads via updateHessianMatrix) -// q = −2GᵀW₁v (updated each cycle from current demand) -// -// Box constraints per wheel (updated each cycle), as forces: -// Motor: |F_i| ≤ T_max / R -// Friction circle:|F_i| ≤ √(max(0, (μ·Fz_i)² − Fy_i²)) +// In OSQP form min 0.5 uᵀPu + qᵀu, s.t. lb ≤ Iu ≤ ub: +// P = 2(GᵀW₁G + W₂) (the W₂ diagonal is refreshed each cycle from wheel loads) +// q = −2GᵀW₁v +// |F_i| ≤ min(T_max / R, √(max(0, (μ·Fz_i)² − Fy_i²))) motor cap ∩ friction circle // // The wheel radius enters only at the output: T_motor = F · R / gear_ratio. -// -// OSQP warm-starts from the previous solution, giving fast convergence in practice. // Reference: De Novellis et al. (SAE 2013-01-0673) class QpTorqueAllocator : public ITorqueAllocator { public: - // Vehicle geometry / powertrain: - // r_w wheel radius [m] - // gear_ratio motor → wheel gear ratio (output: T_motor = F·R / gear_ratio) - // t_f front track width [m] - // t_r rear track width [m] - // - // Limits: - // t_max per-wheel motor torque limit [Nm] - // mu tyre-road friction coefficient - // - // QP weights: - // w_fx weight on Fx tracking error - // w_mz weight on Mz tracking error (typically >> w_fx for racing) - // w_reg regularisation weight on driving-force magnitude QpTorqueAllocator(double r_w, double gear_ratio, double t_f, double t_r, double t_max, double mu, double w_fx, double w_mz, double w_reg) : r_w_(r_w), gear_ratio_(gear_ratio), t_max_(t_max), mu_(mu) { - // --- Dependency matrix G (2×4): driving forces → [Fx, Mz] --- - // Radius-independent — depends only on the half-track widths. const double sf = t_f / 2.0; const double sr = t_r / 2.0; @@ -76,25 +47,16 @@ class QpTorqueAllocator : public ITorqueAllocator { -sf, sf, -sr, sr; // clang-format on - // --- W1 = diag(w_fx, w_mz) --- Eigen::Matrix w1_mat = Eigen::Matrix::Zero(); w1_mat(0, 0) = w_fx; w1_mat(1, 1) = w_mz; - // Precompute GᵀW₁ — reused each cycle for gradient q = −2·GᵀW₁·v gt_w1_ = g_mat.transpose() * w1_mat; - - // Constant tracking part of the Hessian: 2·GᵀW₁G (rank-2; the load-inverse - // regularisation added each cycle makes the full P positive definite). p_track_ = 2.0 * (gt_w1_ * g_mat); w_reg_ = w_reg; - // --- P = 2(BᵀW₁B + W₂), upper triangular sparse (OSQP convention) --- - // Initial Hessian uses an equal-load W₂ = w_reg·I just to establish the - // (full upper-triangular) sparsity pattern; the diagonal is refreshed with - // the load-inverse weights every cycle via updateHessianMatrix(). The - // sparse matrix is a member so the per-cycle update touches values only — - // no allocation in the control loop. + // Upper triangular (OSQP convention). The equal-load W₂ = w_reg·I here only + // establishes the sparsity pattern; the diagonal is refreshed every cycle. const Eigen::Matrix p_dense = p_track_ + (2.0 * w_reg_ * Eigen::Matrix::Identity()); @@ -106,17 +68,14 @@ class QpTorqueAllocator : public ITorqueAllocator { } p_upper_.makeCompressed(); - // --- Constraint matrix A = I₄ (encodes box constraints) --- + // A = I₄ — the constraints are per-wheel boxes. Eigen::SparseMatrix a_sparse(4, 4); a_sparse.setIdentity(); - // --- Configure OSQP --- solver_.settings()->setWarmStart(true); solver_.settings()->setVerbosity(false); - // Polishing is an optional high-accuracy refinement step; disabled here. - // It adds latency in the control loop and prints "Polishing not needed — - // no active set detected at optimal point" (not gated by verbosity) on - // every cycle where it's skipped. Warm-start + 1e-5 tolerances suffice. + // Polish adds loop latency and prints an ungated message on every cycle it is + // skipped; warm-start plus 1e-5 tolerances suffice. solver_.settings()->setPolish(false); solver_.settings()->setMaxIteration(500); solver_.settings()->setAbsoluteTolerance(1e-5); @@ -141,34 +100,19 @@ class QpTorqueAllocator : public ITorqueAllocator { } } - // VehicleState: [vx, vy, yaw_rate, steering_angle, ax, ay] - // YawMomentCommand: {mz_, fx_total_} - // ForceVector: [Fx×4, Fy×4, Fz×4] [[nodiscard]] WheelTorques allocateImpl(const VehicleState& state, const YawMomentCommand& cmd, const ForceVector& forces) { (void)state; // reserved for speed-dependent torque maps - // Pessimistically mark the solve as failed; set true only on a clean - // solve. Queried by the orchestrator via lastSolveOk() so the ROS node - // can warn when the fallback was used. last_solve_ok_ = false; - // Any failed solver update leaves OSQP with inconsistent data — hold the - // previous solution for this cycle rather than solving the wrong problem - // (zero before the first successful solve). A transient failure then - // doesn't step the torque to zero mid-manoeuvre; persistent failures - // keep reporting via lastSolveOk(). - - // --- Gradient: q = −2·GᵀW₁·v --- const Eigen::Vector2d v_demand{cmd.fx_total_, cmd.mz_}; const Eigen::VectorXd q_vec = -2.0 * (gt_w1_ * v_demand); if (!solver_.updateGradient(q_vec)) { - return last_torques_; + return last_torques_; // a failed update leaves OSQP inconsistent } - // --- Per-wheel bounds (driving force): motor cap ∩ friction circle --- - // The friction circle already gives a force cap; the motor wheel-torque cap - // t_max is expressed as a force via t_max / R. + // Per-wheel force bounds: motor cap (t_max / R) ∩ friction circle. const double f_motor_max = t_max_ / r_w_; Eigen::VectorXd ub(4); Eigen::VectorXd lb(4); @@ -183,11 +127,7 @@ class QpTorqueAllocator : public ITorqueAllocator { return last_torques_; } - // --- Load-inverse regularisation: W₂ = diag(w_reg · Fz_avg / Fz_i) --- - // Penalise each wheel inversely to its load so the lowest-grip tyre is used - // least. Normalised by the mean load so w_reg keeps its scale and P stays - // well-conditioned. Only the diagonal of P = 2·GᵀW₁G + 2·W₂ changes, so - // refresh those values in the persistent sparse matrix (pattern is fixed). + // Only P's diagonal changes with load, so refresh those values in place. double fz_sum = 0.0; for (int i = 0; i < 4; ++i) fz_sum += std::max(0.0, forces.fz_[i]); const double fz_avg = std::max(kFzFloor, fz_sum / 4.0); @@ -202,15 +142,11 @@ class QpTorqueAllocator : public ITorqueAllocator { switch (solver_.solveProblem()) { case OsqpEigen::ErrorExitFlag::NoError: { - // Solution is the per-wheel driving force. Convert to motor torque: - // T_motor = F · R_wheel / gear_ratio. + // Driving force → motor torque. WheelTorques u = solver_.getSolution().head<4>(); for (int i = 0; i < 4; ++i) { u[i] = (u[i] * r_w_) / gear_ratio_; } - // Guard against NaN/Inf in the solution (e.g. non-convergence or - // numerical breakdown reported as NoError) — hold the previous - // solution. if (!u.allFinite()) { return last_torques_; } @@ -223,40 +159,28 @@ class QpTorqueAllocator : public ITorqueAllocator { } } - // False when the most recent allocate() fell back to the previous solution - // (failed OSQP update/solve or a non-finite solution). + // False when the last allocate() fell back to the previous solution. [[nodiscard]] bool lastSolveOk() const noexcept { return last_solve_ok_; } private: - // Vehicle geometry / powertrain double r_w_; // wheel radius [m] double gear_ratio_; // motor → wheel gear ratio + double t_max_; // per-wheel motor torque cap [Nm] + double mu_; // tyre-road friction coefficient - // Limits - double t_max_; // per-wheel motor torque cap [Nm] - double mu_; // tyre-road friction coefficient - - // Precomputed GᵀW₁ (4×2, constant across cycles) - Eigen::Matrix gt_w1_; - - // Constant tracking part of the Hessian, 2·GᵀW₁G (4×4). The load-inverse - // regularisation diagonal is added on top each cycle. - Eigen::Matrix p_track_; - double w_reg_; // regularisation weight (load-inverse cost) + Eigen::Matrix gt_w1_; // GᵀW₁ + Eigen::Matrix p_track_; // 2·GᵀW₁G; the W₂ diagonal is added each cycle + double w_reg_; - // Persistent upper-triangular Hessian passed to OSQP. The sparsity pattern - // is fixed in the constructor; only the diagonal values change per cycle. + // Sparsity pattern is fixed in the constructor; only the diagonal changes. Eigen::SparseMatrix p_upper_; - // Whether the most recent allocate() produced a clean solution. bool last_solve_ok_{true}; - // Most recent clean solution (motor torques), returned when a solve fails. - // Zero until the first successful solve. + // Held and re-returned when a solve fails; zero until the first success. WheelTorques last_torques_{WheelTorques::Zero()}; - // Lower bound on wheel load [N] used in the 1/Fz weighting to avoid a - // divide-by-zero / unbounded penalty when a wheel is unloaded. + // Floor on Fz [N] so the 1/Fz weighting stays bounded for an unloaded wheel. static constexpr double kFzFloor = 1.0; // OSQP solver — maintains warm-start state between control cycles diff --git a/include/types.hpp b/include/types.hpp index 6ba9139..f27ac25 100644 --- a/include/types.hpp +++ b/include/types.hpp @@ -6,7 +6,7 @@ namespace tv { -// Full vehicle state — populated from IMU, odometry, and steering sensor. +// Populated from the IMU, odometry, and the steering sensor. struct VehicleState { double vx_{0.0}; // longitudinal velocity [m/s] double vy_{0.0}; // lateral velocity [m/s] @@ -23,7 +23,6 @@ struct ForceVector { std::array fz_{}; // normal forces [N] }; -// High-level controller output: yaw moment + total longitudinal force demand. struct YawMomentCommand { double mz_{0.0}; // corrective yaw moment [Nm] double fx_total_{0.0}; // total longitudinal force demand [N] @@ -37,15 +36,12 @@ struct SteeringCommand { }; // Per-wheel torque commands [FL, FR, RL, RR] (Nm). -// Kept as Eigen — returned directly from the allocator solve and used in DFO loops. using WheelTorques = Eigen::Vector4d; // Per-wheel angular velocities [FL, FR, RL, RR] (rad/s). -// Kept as Eigen — used in element-wise DFO loops. using WheelOmegas = Eigen::Vector4d; -// Per-stage pipeline execution times [µs] — published on debug/timing for -// telemetry; carries no control meaning. +// Per-stage pipeline execution times [µs] — telemetry only, no control meaning. struct StageTimings { double forces_us{0.0}; // force estimator (stage 1) double yaw_us{0.0}; // yaw moment generator (stage 2) @@ -53,9 +49,8 @@ struct StageTimings { double total_us{0.0}; // full pipeline }; -// Full pipeline output: final wheel torques plus every intermediate signal. -// The intermediates carry no control meaning here — they exist so the ROS node -// can publish them on debug topics for telemetry/plotting. +// Full pipeline output. The intermediates exist so the ROS node can publish them +// on debug topics. struct PipelineResult { ForceVector forces{}; // tyre force estimate (stage 1) YawMomentCommand yaw_cmd{}; // yaw moment + Fx demand (stage 2) From 50afa588c2eb0f032dce2a7a666829389b84cc3c Mon Sep 17 00:00:00 2001 From: Bulban <147950706+Bulban@users.noreply.github.com> Date: Fri, 2 Oct 2026 20:41:01 +0200 Subject: [PATCH 4/5] Fixed docker setup and clean template --- .github/workflows/docker-ci.yml | 2 +- CMakeLists.txt | 10 - Dockerfile | 31 +--- README.md | 281 +++-------------------------- config/parameters.yaml | 7 - docs/ros_messages.md | 56 +++--- launch/launch.py | 6 - package.xml | 6 +- pre-commit_copy.sh | 4 +- scripts/example_time_subscriber.py | 55 ------ test/test_hello_world.py | 2 - 11 files changed, 61 insertions(+), 399 deletions(-) delete mode 100644 config/parameters.yaml delete mode 100755 scripts/example_time_subscriber.py delete mode 100644 test/test_hello_world.py diff --git a/.github/workflows/docker-ci.yml b/.github/workflows/docker-ci.yml index 061c2d5..40b12ff 100644 --- a/.github/workflows/docker-ci.yml +++ b/.github/workflows/docker-ci.yml @@ -145,7 +145,7 @@ jobs: sleep 5 # Check if ROS2 nodes are running - if ! docker exec $CONTAINER_NAME bash -c "source /ws/install/setup.bash && ros2 node list" | grep -E "time_publisher|time_subscriber"; then + if ! docker exec $CONTAINER_NAME bash -c "source /ws/install/setup.bash && ros2 node list" | grep -E "torque_vectoring_node"; then echo "Health check failed!" echo "Expected nodes not found. Current nodes:" docker exec $CONTAINER_NAME bash -c "source /ws/install/setup.bash && ros2 node list" diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a1bd1c..99fc056 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,22 +48,12 @@ install(TARGETS DESTINATION lib/${PROJECT_NAME} ) -# Install Python modules (for importable Python code) - -# Install Python executables - # Install launch files install(DIRECTORY launch DESTINATION share/${PROJECT_NAME} ) -# Install config files -install(DIRECTORY - config - DESTINATION share/${PROJECT_NAME} -) - # Install include directory install(DIRECTORY include/ diff --git a/Dockerfile b/Dockerfile index 8a3b987..494357d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,44 +1,17 @@ -# This is a template for a Dockerfile to build a docker image for your ROS2 package. -# The main purpose of this file is to install dependencies for your package. - FROM ros:jazzy-ros-base-noble ENV ROS_DISTRO=jazzy - ENV ROS_ROOT=/opt/ros/${ROS_DISTRO} +ENV DEBIAN_FRONTEND=noninteractive -# Set up workspace RUN mkdir -p /ws/src -# Set noninteractive installation -ENV DEBIAN_FRONTEND=noninteractive - -# Package apt dependencies RUN apt-get update && \ apt-get install --no-install-recommends -y \ python3-colcon-common-extensions \ python3-rosdep \ - # EXAMPLE: \ - # libssl-dev \ - # libffi-dev \ + libeigen3-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* WORKDIR /ws - - -# Installing of pip dependencies -#RUN pip3 install \ -# # EXAMPLE: \ -# # torch \ -# # torchvision \ -# # tensorboardX \ -# # opencv-python \ -# # scikit-image \ -# # scikit-learn \ - - -# Build dependencies from source -#RUN git clone https://github.com/your-github-username/your-repo.git -#WORKDIR your-repo -#RUN make diff --git a/README.md b/README.md index 38ca822..d2c944f 100644 --- a/README.md +++ b/README.md @@ -1,278 +1,45 @@ -# DV-TEMPLATE-PACKAGE (ROS2 Jazzy) +# torque_vectoring_pkg (ROS2 Jazzy) -Example of generic package development of DV pipeline packages for ROS2 Jazzy. You should create a new repository from this template (by clicking `Use this template` → `Create a new repository`) and replace the content with your own package, source code, and documentation. +Torque vectoring for a four-wheel-drive electric Formula Student car. Each control cycle runs three stages: -## Table of Contents +1. **Force estimation** (`KinematicForceEstimator`): estimates tire forces from the vehicle state. +2. **Yaw control** (`PIDYawController`): computes a corrective yaw moment from the yaw rate error. +3. **Torque allocation** (`LdltTorqueAllocator`): distributes the total force and yaw moment demand across the four motors. -- [Guidelines](#guidelines) - - [Overview](#overview) - - [Enforced](#enforced) - - [Encouraged](#encouraged) -- [Development](#development) - - [Creating a package](#creating-a-package) - - [Graphical User Interface (GUI) Support](#graphical-user-interface-gui-support) -- [Deployment](#deployment) - - [Prerequisites](#prerequisites) - - [Building and Running](#building-and-running) - - [Stopping and Cleanup](#stopping-and-cleanup) -- [Validation and Testing](#validation-and-testing) -- [Troubleshooting](#troubleshooting) -- [Resources](#resources) -- [Codebase Diagram](#codebase-diagram) +The stages are wired together in [src/main.cpp](src/main.cpp) and tuned in [include/config.hpp](include/config.hpp). Topics are listed in [docs/ros_messages.md](docs/ros_messages.md), and background on the algorithms is in [docs/tv.md](docs/tv.md) and [docs/tire_forces.md](docs/tire_forces.md). -## Guidelines +## Dependencies -For this new CI Branch for pre-commits +- `fs_msgs`, `ros2can_msgs` and `vehicle_params_cpp` must be in the colcon workspace. +- Eigen 3 (`libeigen3-dev`), which the [Dockerfile](Dockerfile) installs. + +## Running with Docker ```bash -./setupenv.sh +docker compose up --build ``` -If you just want to check C++ Code Correctness for modified C++ files before adding to commit => +The entrypoint runs `colcon build` on the first startup and then launches [launch/launch.py](launch/launch.py). To check that the node is running: ```bash -./tidy-code.sh +docker exec -it bash -c "source /ws/install/setup.bash && ros2 node list" ``` -### Overview - -- Our final pipeline will be constructed using Docker-compose to launch all individual packages. This will be based on the Dockerfiles from each package repo. -- ROS2 uses a decentralized architecture with DDS (Data Distribution Service), so no separate ROS master is needed. -- All packages will firstly be built through an entrypoint script using `colcon build` and then launched with a launch file using the command (CMD) instruction in the Docker-compose file. - -### Enforced - -- Repository name ending with "_pkg". - -- Main branch always in a deployable state. - -- ROS2 package must be runnable standalone from other ROS nodes without the package nodes crashing. - -- Document what messages and message types are used in the package in the [ROS messages](./docs/ros_messages.md) markdown file. This is to make it easier to understand the inputs and outputs of the package and to make it easier to integrate with other packages. - -- [Dockerfile](Dockerfile) installs all package dependencies and sets up the workspace directory in a Docker container. - -- Working ROS2 package that can be built with `colcon build` using [docker-entrypoint.sh](docker-entrypoint.sh), this requires having both [package.xml](package.xml), [CMakeLists.txt](CMakeLists.txt), as well as a working [launch.py](launch/launch.py) file in the launch directory (of course, rename this to a suitable name of your package). - -- [Docker-compose file](docker-compose.yml) builds and launches the package with a launch file specified in the [launch](./launch/) directory. The compose uses `network_mode: host` for ROS2 DDS communication. - -- Read more about our Software Development Guidelines on the [KTHFS wiki](https://wiki.kthformulastudent.se/index.php/Driverless_Software_Development_Guidelines). - -### Encouraged - -- Avoid hard-coding variables and instead utilize configuration files defined in the [configuration](./config/) folder. - -- Incorporating unit testing with github actions to automatically run tests on pull requests. - -- [Visualize codebase](https://githubnext.com/projects/repo-visualization/) by adding `![Visualization of the codebase](./diagram.svg)` in the README. Note: this diagram is automatically generated on push to the main branch as defined in the [Github Action file](./.github/workflows/codebase-diagram.yml). - -## Development - -This section provides step-by-step instructions on how to create a new ROS2 package and integrate it with Docker using this template. - -### Creating a package - -1. Choose a suitable Docker base image based on your package's requirements. In many cases, the 'ros-base' image is sufficient. For ROS2 Jazzy, use [ros:jazzy-ros-base-noble](https://hub.docker.com/_/ros). For packages related to machine learning, consider the [dustynv jetpack containers](https://github.com/dusty-nv/jetson-containers). Ensure that all the package dependencies are installed and set up in the [Dockerfile](Dockerfile). Also, remember to adjust the `ROS_DISTRO` variables in accordance with the ROS distribution you're using. - -2. Ensure that the ROS2 package is complete and can be built using `colcon build`. This entails adding source code, primarily in C++, to the `src` directory and incorporating Python scripts in the `scripts` directory. Additionally, modifications should be made to [package.xml](package.xml), [CMakeLists.txt](CMakeLists.txt), [docker-entrypoint.sh](docker-entrypoint.sh), and [launch.py](launch/launch.py) (rename this launch file to a suitable name for your package). Refer to the provided files and the [ROS2 documentation](https://docs.ros.org/en/jazzy/) for guidance. - -3. Update the Docker-compose file. Ensure that the service name aligns with the package's name and modify the launch command to the correct package and launch file name. Also, set the `ROS_DOMAIN_ID` appropriately for your environment. Additionally, if required, include extra mounted volumes in the `src` directory or adjust other arguments as appropriate. - -4. Test the package compose file using `docker compose up`. Make sure that the package is launched correctly, for example with `docker exec ros_container bash -c "source /ws/install/setup.bash && ros2 node list"`. See Usage for further guidance. This testing is incorporated in the CI workflow. - -5. Add a GitHub token to the repository's GitHub secrets. This token should come from an account with access to all submodules utilized in the package build. - -### Graphical User Interface (GUI) Support - -The `docker-compose.yml` includes a `noVNC` service that enables GUI support through X11 forwarding. The service is based on the [theasp/novnc](https://hub.docker.com/r/theasp/novnc) image. The service allows graphical applications to be run in your web browser by connecting to the container's VNC server (default `http://localhost:8080/vnc.html`). - -For example, you might want to run `rviz2` in your ROS2 container, this solution allows you to do so. To do this, you need to: - -1. Enter the container: - - ```bash - docker exec -it /bin/bash - ``` - -2. Run `rviz2` (or any other GUI application): - - ```bash - rviz2 - ``` - -3. Open a web browser and navigate to `http://localhost:8080/vnc.html`. - -You can now interact with the GUI application in your browser for development or for other purposes. - -## Deployment - -This section provides step-by-step instructions on how to test and deploy the `torque_vectoring_pkg` using Docker. - -### Prerequisites - -1. Ensure that the Dockerfile, docker-compose, launch files configuration and environment variables are set up as per the [package requirements](#creating-a-package). - -2. Make sure you have Docker, or another container runtime, along with Docker Compose, installed on your machine. If not, you can get them from [here](https://docs.docker.com/compose/install/). - -### Building and Running - -1. **Clone the Repository**: - - ```bash - git clone - cd - ``` - -2. **Build the Docker Image**: - - ```bash - docker compose build - ``` - -3. **Run the Package**: +`ros2 node list` should show `/torque_vectoring_node`. The compose file also starts a noVNC service at `http://localhost:8080/vnc.html` for GUI tools like `rviz2`. - ```bash - docker compose up - ``` +## Running natively - This will run your package and necessary docker containers as described in the `docker-compose.yml` file. Your ROS2 package should now be up and running within the Docker environment. If this command is run before `docker compose build`, it will automatically perform the building process as well. +From the workspace root: -4. To interact or debug within the running container: - - ```bash - docker exec -it /bin/bash - ``` - - To get the name and id of all containers, run: - - ```bash - docker ps - ``` - - To list all containers, including those that have exited, run: - - ```bash - docker ps -a - ``` - -#### Stopping and Cleanup - -1. To stop the running services: - - ```bash - docker compose stop - ``` - -2. To stop and remove the containers: - - ```bash - docker compose down - ``` - -3. If you wish to remove the built images to free up space: - - ```bash - docker rmi - ``` - -## Validation and Testing - -### Testing manually - -After launching the package, it's essential to validate its functionality: - -1. **Check Package Health**: - - ```bash - docker exec container_name bash -c "source /ws/install/setup.bash && ros2 node list" - ``` - - This should list the nodes exposed by your ROS2 package, indicating they're running correctly. - -2. **Check Topics**: - - ```bash - docker exec container_name bash -c "source /ws/install/setup.bash && ros2 topic list" - ``` - -3. If unit tests have been integrated, run them to ensure package integrity: - - ```bash - docker exec container_name bash -c "source /ws/install/setup.bash && colcon test" - ``` - -### GitHub CI Workflow - -To ensure that the package is functional and can be built successfully, a GitHub CI workflow is included in the repository. This workflow is triggered whenever a pull request is opened, updated, or reopened. The workflow is defined in the [`.github/workflows/docker-ci.yml`](.github/workflows/docker-ci.yml) file. Below is a brief description of the workflow. - -**Trigger:** - -- The CI workflow gets initiated whenever a pull request (PR) is: - - Opened - - Updated (synchronized) - - Reopened - -**Jobs:** - -1. **Check for Essential Files**: - - Ensure the presence of `Dockerfile`, `docker-compose.yml`, and `docker-entrypoint.sh` in the repository. - -2. **Docker Operations**: - - After verifying essential files, execute Docker Compose. - -3. **Container Health Check**: - - Wait and check if the Docker container is running, with a maximum wait time defined by `COMPOSE_UP_TIMEOUT_SECONDS`. - -4. **Build Validation**: - - After a short initial wait (5 seconds), inspect the Docker container for a sentinel file named `.CONTAINER_INITIALIZED_PLACEHOLDER` indicating build completion. The maximum wait time for this operation is `COLCON_BUILD_TIMEOUT_SECONDS`. - -5. **ROS2 Node Verification**: - - Confirm the health and operation of ROS2 nodes by checking for expected nodes using: - - ```bash - docker exec container_name bash -c "source /ws/install/setup.bash && ros2 node list" - ``` - -## Troubleshooting - -If you encounter difficulties, the logs generated during the Docker-compose build and execution phases are your best first reference. These logs can provide insights into issues such as missing dependencies or other common errors. - -Frequently observed challenges include: - -- Launch command in Docker compose not set up correctly to match package name and launch file name. -- Failure to update the `CMakeLists.txt` with the appropriate package name. -- Discrepancies between the package name specified in the launch command and those in `package.xml` or the launch file. -- Not updating the variables for the relevant ROS distribution in both the `Dockerfile` and `docker-entrypoint.sh`. -- DDS communication issues. Check the `ROS_DOMAIN_ID` environment variable and network configuration. -- FS_msgs or other submodule not initialized. `git submodule update --init --recursive`. - -## Resources - -1. **ROS2 (Robot Operating System 2)**: - - [ROS2 Documentation](https://docs.ros.org/en/jazzy/) - - [ROS2 Tutorials](https://docs.ros.org/en/jazzy/Tutorials.html) - - [ROS2 Launch](https://docs.ros.org/en/jazzy/Tutorials/Intermediate/Launch/Launch-Main.html) - - [Creating a ROS2 Package](https://docs.ros.org/en/jazzy/Tutorials/Beginner-Client-Libraries/Creating-Your-First-ROS2-Package.html) - -2. **Colcon Build System**: - - [Colcon Documentation](https://colcon.readthedocs.io/en/released/) - - [Building ROS2 Packages](https://docs.ros.org/en/jazzy/Tutorials/Beginner-Client-Libraries/Colcon-Tutorial.html) - -3. **Docker**: - - [Docker Get Started Guide](https://docs.docker.com/get-started/) - - [Dockerfile Reference](https://docs.docker.com/engine/reference/builder/) - - [Best Practices for Writing Dockerfiles](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - -4. **Docker Compose**: - - [Overview of Docker Compose](https://docs.docker.com/compose/) - - [Docker Compose CLI Reference](https://docs.docker.com/compose/reference/overview/) - -5. **Github Actions**: +```bash +colcon build --packages-up-to torque_vectoring_pkg +source install/setup.bash +ros2 launch torque_vectoring_pkg launch.py +``` - - [Understanding Github Actions](https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions) +## CI -6. **CI guide** - -[Wiki Page Regarding CI](https://wiki.kthformulastudent.se/index.php/Continuous_Integration) +[docker-ci.yml](.github/workflows/docker-ci.yml) starts the compose stack, waits for `colcon build` to finish, and checks that `torque_vectoring_node` is running. ## Codebase Diagram diff --git a/config/parameters.yaml b/config/parameters.yaml deleted file mode 100644 index 0b0c5b4..0000000 --- a/config/parameters.yaml +++ /dev/null @@ -1,7 +0,0 @@ -# Parameters for torque_vectoring_pkg nodes -# This file is loaded by the launch file and passed to the nodes. - -# Time Publisher Node Parameters -time_publisher: - ros__parameters: - publish_rate: 1.0 # Publishing rate in Hz (messages per second) diff --git a/docs/ros_messages.md b/docs/ros_messages.md index 1a2b9bc..dc9e655 100644 --- a/docs/ros_messages.md +++ b/docs/ros_messages.md @@ -1,46 +1,50 @@ # ROS2 Messages -Messages used in this package and the purpose for each message. +Topic names are as remapped in [launch.py](../launch/launch.py). Wheel order in all arrays is `[FL, FR, RL, RR]`. ## Input -### `/my_input/path` +### `/navigation/dv_control_target` -- **Type**: `my_msgs/msg/Type` +- **Type**: `fs_msgs/msg/CarCommand` +- **Purpose**: Steering angle (deg), target velocity and target yaw rate from the control stack. -- **Purpose**: Brief description of the purpose of this message +### `/odom` -... +- **Type**: `nav_msgs/msg/Odometry` +- **Purpose**: Longitudinal and lateral velocity. SensorData QoS. -## Output +### `/imu` -### `/current_time` +- **Type**: `sensor_msgs/msg/Imu` +- **Purpose**: Yaw rate and accelerations. Each IMU message triggers one control cycle, so the output rate follows the IMU rate. SensorData QoS. -- **Type**: `std_msgs/msg/String` +### `/vehicle/wheel_speeds` -- **Purpose**: Publishes the current ROS2 time as a formatted string +- **Type**: `fs_msgs/msg/Wheelspeeds` +- **Purpose**: Per-wheel angular speeds. SensorData QoS. -### `/my_output/steering_angle` +### `/ros2can/receive/vehicle_status_motor_torques` -- **Type**: `my_msgs/msg/Type` +- **Type**: `ros2can_msgs/msg/VehicleStatusMotorTorques` +- **Purpose**: Measured motor torques. -- **Purpose**: Brief description of the purpose of this message +## Output -... +### `/ros2can/send/dv_control_target_tv` -## Example Topic Commands +- **Type**: `ros2can_msgs/msg/DvControlTargetTv` +- **Purpose**: Per-wheel torque targets and steering angle target (deg) sent to the car over CAN. Zero torque is commanded if `cmd_in` or `odom` goes stale. -List topics: -```bash -ros2 topic list -``` +### Debug topics -Echo a topic: -```bash -ros2 topic echo /current_time -``` +All `std_msgs/msg/Float64MultiArray` unless noted. -Get topic info: -```bash -ros2 topic info /current_time -``` +| Topic | Content | +| --- | --- | +| `/debug/tire_fx`, `/debug/tire_fy`, `/debug/tire_fz` | Estimated tire forces per wheel | +| `/debug/yaw_moment` | `[Mz, Fx_total]` demand from the yaw controller | +| `/debug/wheel_torques` | Allocated wheel torques | +| `/debug/timing` | Pipeline timing | +| `/debug/tracking` | Yaw rate tracking | +| `/debug/alloc_yaw_moment`, `/debug/alloc_fx_total` | `std_msgs/msg/Float64`, achieved demand after allocation (only built with `-DDEBUG`) | diff --git a/launch/launch.py b/launch/launch.py index 2aa1634..16b79e4 100644 --- a/launch/launch.py +++ b/launch/launch.py @@ -13,12 +13,6 @@ def generate_launch_description(): """Generate launch description for torque_vectoring_pkg.""" - # Get the package share directory - # pkg_share = get_package_share_directory("torque_vectoring_pkg") - - # Path to the parameters file - # params_file = os.path.join(pkg_share, "config", "parameters.yaml") - return LaunchDescription( [ Node( diff --git a/package.xml b/package.xml index 0f9b4c4..620b5a0 100644 --- a/package.xml +++ b/package.xml @@ -3,17 +3,15 @@ torque_vectoring_pkg 0.0.1 - Template package for ROS2 Jazzy + Torque vectoring controller for a 4WD electric race car: yaw moment control and per-wheel torque allocation - Your Name + Bulban TODO: License declaration ament_cmake - ament_cmake_python rclcpp - rclpy std_msgs sensor_msgs nav_msgs diff --git a/pre-commit_copy.sh b/pre-commit_copy.sh index 317ade7..1a46893 100755 --- a/pre-commit_copy.sh +++ b/pre-commit_copy.sh @@ -39,14 +39,14 @@ if [ $? -ne 0 ]; then fi echo " Running ament_flake8" -ament_flake8 scripts/ torque_vectoring_pkg/ +ament_flake8 launch/ if [ $? -ne 0 ]; then echo "ament_flake8 failed" exit 1 fi echo " Running ament_pep257" -ament_pep257 scripts/ torque_vectoring_pkg/ +ament_pep257 launch/ if [ $? -ne 0 ]; then echo "ament_pep257 failed" exit 1 diff --git a/scripts/example_time_subscriber.py b/scripts/example_time_subscriber.py deleted file mode 100755 index f95c2a1..0000000 --- a/scripts/example_time_subscriber.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python3 - -import rclpy -from rclpy.node import Node -from std_msgs.msg import String - - -class TimeSubscriber(Node): - """ - A ROS2 node that subscribes to the 'current_time' topic and logs received messages. - """ - - def __init__(self): - super().__init__("time_subscriber") - - # Create a subscription to the 'current_time' topic - self.subscription = self.create_subscription( - String, - "current_time", - self.listener_callback, - 10, # QoS history depth - ) - self.subscription # prevent unused variable warning - - self.get_logger().info("Time subscriber node started") - - def listener_callback(self, msg: String) -> None: - """ - Callback function to log the received time from the 'current_time' topic. - - Args: - msg (String): Message received from the topic. - """ - self.get_logger().info(f"Received time: {msg.data}") - - -def main(args=None) -> None: - """ - Main function to initialize the subscriber node and subscribe to the 'current_time' topic. - """ - rclpy.init(args=args) - - time_subscriber = TimeSubscriber() - - try: - rclpy.spin(time_subscriber) - except KeyboardInterrupt: - pass - finally: - time_subscriber.destroy_node() - rclpy.shutdown() - - -if __name__ == "__main__": - main() diff --git a/test/test_hello_world.py b/test/test_hello_world.py deleted file mode 100644 index 0d6dea1..0000000 --- a/test/test_hello_world.py +++ /dev/null @@ -1,2 +0,0 @@ -def test_hello_world(): - assert True From e4defcf8d175a201106624cd92aaeb42da05ffb7 Mon Sep 17 00:00:00 2001 From: kthfsdv-admin Date: Fri, 13 Nov 2026 19:17:02 +0100 Subject: [PATCH 5/5] Updated car params and topic names --- CMakeLists.txt | 4 + Dockerfile | 1 + docs/ros_messages.md | 10 +-- include/config.hpp | 34 ++++----- include/ros_interface.hpp | 149 ++++++++++++++++++++++++++++++-------- launch/launch.py | 11 +-- package.xml | 2 + 7 files changed, 152 insertions(+), 59 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 99fc056..c890c7e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,6 +22,8 @@ find_package(Eigen3 REQUIRED) find_package(vehicle_params_cpp REQUIRED) find_package(ros2can_msgs REQUIRED) find_package(fs_msgs REQUIRED) +find_package(tf2 REQUIRED) +find_package(tf2_ros REQUIRED) # C++ executable add_executable(torque_vectoring_node src/main.cpp) @@ -35,6 +37,8 @@ ament_target_dependencies(torque_vectoring_node nav_msgs fs_msgs ros2can_msgs + tf2 + tf2_ros ) target_link_libraries(torque_vectoring_node diff --git a/Dockerfile b/Dockerfile index 494357d..5140944 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,6 +9,7 @@ RUN mkdir -p /ws/src RUN apt-get update && \ apt-get install --no-install-recommends -y \ python3-colcon-common-extensions \ + ros-jazzy-rmw-cyclonedds-cpp \ python3-rosdep \ libeigen3-dev \ && apt-get clean \ diff --git a/docs/ros_messages.md b/docs/ros_messages.md index dc9e655..d9eb2f4 100644 --- a/docs/ros_messages.md +++ b/docs/ros_messages.md @@ -17,14 +17,14 @@ Topic names are as remapped in [launch.py](../launch/launch.py). Wheel order in ### `/imu` - **Type**: `sensor_msgs/msg/Imu` -- **Purpose**: Yaw rate and accelerations. Each IMU message triggers one control cycle, so the output rate follows the IMU rate. SensorData QoS. +- **Purpose**: Yaw rate and accelerations. Each IMU message triggers one control cycle, so the output rate follows the IMU rate. Transformed from `header.frame_id` into `base_frame` (parameter, default `base_link`) via TF, including a lever-arm correction for the IMU's offset; zero torque is commanded until that transform is available. SensorData QoS. -### `/vehicle/wheel_speeds` +### `/ros2can/recv/vehicle_status_wheel_speed` -- **Type**: `fs_msgs/msg/Wheelspeeds` -- **Purpose**: Per-wheel angular speeds. SensorData QoS. +- **Type**: `ros2can_msgs/msg/VehicleStatusWheelSpeed` +- **Purpose**: Per-wheel motor speeds in rpm, converted to wheel-side rad/s (divided by the gear ratio) for the force estimator. The message has no header, so the sample period is taken from receive times. -### `/ros2can/receive/vehicle_status_motor_torques` +### `/ros2can/recv/vehicle_status_motor_torques` - **Type**: `ros2can_msgs/msg/VehicleStatusMotorTorques` - **Purpose**: Measured motor torques. diff --git a/include/config.hpp b/include/config.hpp index 1a6dc7f..0e59bb4 100644 --- a/include/config.hpp +++ b/include/config.hpp @@ -1,28 +1,28 @@ #pragma once -#include +#include namespace tv { inline constexpr double kGravity{9.81}; // [m/s²] struct VehicleConfig { - static constexpr double mass{kthfs::vehicle::dev19::weight_kg}; // total vehicle mass [kg] + static constexpr double mass{kthfs::vehicle::dev20::weight_kg}; // total vehicle mass [kg] static constexpr double cg_height{ - kthfs::vehicle::dev19::cg_height_m}; // centre-of-gravity height [m] + kthfs::vehicle::dev20::cg_height_m}; // centre-of-gravity height [m] static constexpr double wheelbase{ - kthfs::vehicle::dev19::wheelbase_m}; // front-to-rear axle distance [m] + kthfs::vehicle::dev20::wheelbase_m}; // front-to-rear axle distance [m] static constexpr double l_r{0.612}; // rear axle to CG [m] → l_f = wheelbase - l_r static constexpr double trackwidth_front{ - kthfs::vehicle::dev19::track_width_m}; // front track width [m] + kthfs::vehicle::dev20::track_width_m}; // front track width [m] static constexpr double trackwidth_rear{ - kthfs::vehicle::dev19::track_width_m}; // rear track width [m] + kthfs::vehicle::dev20::track_width_m}; // rear track width [m] static constexpr double front_tlltd{ 0.40}; // front TLLTD fraction (0 = all rear, 1 = all front) static constexpr double wheel_radius{ - kthfs::vehicle::dev19::tire_radius_m}; // effective wheel radius [m] + kthfs::vehicle::dev20::tire_radius_m}; // effective wheel radius [m] static constexpr double mu{1.6}; // tyre-road friction coefficient static constexpr double gear_ratio{13.5}; // motor → wheel gear ratio - static constexpr double motor_t_max{21.0}; // per-wheel motor peak torque [Nm] + static constexpr double motor_t_max{18.0}; // per-wheel motor peak torque [Nm] static constexpr double t_max{motor_t_max * gear_ratio}; // per-wheel wheel-side torque cap [Nm] }; @@ -30,11 +30,11 @@ struct VehicleConfig { // Reserved for a future Fx loss feedforward in the longitudinal tracker (unused). struct AeroConfig { static constexpr double rho{1.225}; // air density [kg/m³] (1.225 at sea level, 15 °C) - static constexpr double c_d{kthfs::vehicle::dev19::drag_coefficient}; // drag coefficient + static constexpr double c_d{kthfs::vehicle::dev20::drag_coefficient}; // drag coefficient static constexpr double frontal_area{ - kthfs::vehicle::dev19::frontal_area}; // frontal reference area [m²] + kthfs::vehicle::dev20::frontal_area}; // frontal reference area [m²] static constexpr double c_rr{ - kthfs::vehicle::dev19::rolling_resistance}; // rolling resistance coefficient + kthfs::vehicle::dev20::rolling_resistance}; // rolling resistance coefficient }; struct ForceEstimatorConfig { @@ -45,9 +45,9 @@ struct ForceEstimatorConfig { // Reserved for a future steady-state yaw-moment feedforward (unused). struct BicycleModelConfig { - // dev19::cornerings_stiffness_n_rad is per-TIRE; the bicycle model needs per-AXLE. - static constexpr double c_f{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * 2.0}; - static constexpr double c_r{kthfs::vehicle::dev19::cornerings_stiffness_n_rad * 2.0}; + // dev20::cornerings_stiffness_n_rad is per-TIRE; the bicycle model needs per-AXLE. + static constexpr double c_f{kthfs::vehicle::dev20::cornerings_stiffness_n_rad * 2.0}; + static constexpr double c_r{kthfs::vehicle::dev20::cornerings_stiffness_n_rad * 2.0}; }; struct PIDYawControllerConfig { @@ -60,12 +60,12 @@ struct PIDYawControllerConfig { }; struct LongitudinalPiConfig { - static constexpr double k_p{6.0}; // [1/s] — full Fx (grip clamp μg) is reached at a + static constexpr double k_p{5.0}; // [1/s] — full Fx (grip clamp μg) is reached at a // velocity error of μg/k_p; keep low so tracking // noise doesn't slam the demand to saturation - static constexpr double k_i{0.5}; // [1/s²] + static constexpr double k_i{0.7}; // [1/s²] static constexpr double b{0.8}; // setpoint weight on the proportional term, [0, 1] - static constexpr double eta{1.0}; // drivetrain efficiency + static constexpr double eta{0.9}; // drivetrain efficiency static constexpr double vx_ref_rate{20.0}; // velocity-reference slew limit [m/s²] }; diff --git a/include/ros_interface.hpp b/include/ros_interface.hpp index f89c1b5..353d544 100644 --- a/include/ros_interface.hpp +++ b/include/ros_interface.hpp @@ -2,20 +2,27 @@ #include +#include #include +#include +#include #include #include #include #include #include #include +#include +#include +#include +#include #include "config.hpp" #include "fs_msgs/msg/car_command.hpp" -#include "fs_msgs/msg/wheelspeeds.hpp" #include "orchestrator.hpp" #include "ros2can_msgs/msg/dv_control_target_tv.hpp" #include "ros2can_msgs/msg/vehicle_status_motor_torques.hpp" +#include "ros2can_msgs/msg/vehicle_status_wheel_speed.hpp" #include "types.hpp" namespace tv { @@ -23,9 +30,9 @@ namespace tv { /// ROS2 node that wraps the full torque-vectoring pipeline. /// /// Subscriptions: -/// imu sensor_msgs/Imu — yaw_rate, ax, ay +/// imu sensor_msgs/Imu — yaw_rate, ax, ay (→ base_frame) /// odom nav_msgs/Odometry — body velocities vx, vy -/// wheel_speeds fs_msgs/Wheelspeeds — per-wheel ω [FL,FR,RL,RR] (rad/s) +/// wheel_speeds ros2can_msgs/VehicleStatusWheelSpeed — per-wheel motor rpm [FL,FR,RL,RR] /// motor_torques ros2can_msgs/VehicleStatusMotorTorques — per-wheel motor torque (Nm) /// cmd_in fs_msgs/CarCommand — steering_angle [deg], vx_ref, r_ref /// @@ -33,13 +40,18 @@ namespace tv { /// cmd_out ros2can_msgs/DvControlTargetTv — per-wheel targets + steering /// /// The pipeline runs on every IMU message; the other inputs are cached on receipt -/// and take effect on the next IMU tick. +/// and take effect on the next IMU tick. Zero torque is commanded until the IMU → +/// base_frame transform is available. template class TVNode : public rclcpp::Node { public: explicit TVNode(Orchestrator orchestrator, const std::string& node_name = "torque_vectoring") : Node(node_name), orchestrator_(std::move(orchestrator)) { + base_frame_ = declare_parameter("base_frame", "base_link"); + tf_buffer_ = std::make_unique(get_clock()); + tf_listener_ = std::make_unique(*tf_buffer_); + imu_sub_ = create_subscription( "imu", rclcpp::SensorDataQoS(), [this](sensor_msgs::msg::Imu::SharedPtr msg) { imuCallback(msg); }); @@ -48,9 +60,11 @@ class TVNode : public rclcpp::Node { "odom", rclcpp::SensorDataQoS(), [this](nav_msgs::msg::Odometry::SharedPtr msg) { odomCallback(msg); }); - wheel_speeds_sub_ = create_subscription( - "wheel_speeds", rclcpp::SensorDataQoS(), - [this](fs_msgs::msg::Wheelspeeds::SharedPtr msg) { wheelSpeedsCallback(msg); }); + wheel_speeds_sub_ = create_subscription( + "wheel_speeds", 10, + [this](ros2can_msgs::msg::VehicleStatusWheelSpeed::SharedPtr msg) { + wheelSpeedsCallback(msg); + }); motor_torques_sub_ = create_subscription( "motor_torques", 10, @@ -87,18 +101,11 @@ class TVNode : public rclcpp::Node { private: void imuCallback(const sensor_msgs::msg::Imu::SharedPtr& msg) { - if (first_imu_recieved_) { - // 200 ms imu filter, assumes imu at 100 hz - state_.yaw_rate_ = msg->angular_velocity.z; - state_.ax_ -= state_.ax_ / 20; - state_.ax_ += msg->linear_acceleration.x / 20; - state_.ay_ -= state_.ay_ / 20; - state_.ay_ += msg->linear_acceleration.y / 20; - } else { - first_imu_recieved_ = true; - state_.yaw_rate_ = msg->angular_velocity.z; - state_.ax_ = msg->linear_acceleration.x; - state_.ay_ = msg->linear_acceleration.y; + const std::optional imu_to_base = + lookupImuTransform(msg->header.frame_id); + if (!imu_to_base) { + publishZeroTorque(); + return; } // dt = 0 on the first tick and on out-of-order or duplicate stamps. @@ -110,6 +117,38 @@ class TVNode : public rclcpp::Node { last_stamp_ = stamp; have_last_stamp_ = true; + const Eigen::Matrix3d rot = imu_to_base->rotation(); + const Eigen::Vector3d omega = + rot * Eigen::Vector3d(msg->angular_velocity.x, msg->angular_velocity.y, + msg->angular_velocity.z); + const Eigen::Vector3d accel_imu = + rot * Eigen::Vector3d(msg->linear_acceleration.x, msg->linear_acceleration.y, + msg->linear_acceleration.z); + + // Lever-arm correction: a_base = a_imu - alpha x r - omega x (omega x r), with r the IMU + // position in base_frame. alpha is a finite difference of omega; zero when dt is unknown. + const Eigen::Vector3d alpha = + (dt > 0.0 && have_last_omega_) ? Eigen::Vector3d((omega - last_omega_) / dt) + : Eigen::Vector3d::Zero(); + last_omega_ = omega; + have_last_omega_ = true; + const Eigen::Vector3d r = imu_to_base->translation(); + const Eigen::Vector3d accel = accel_imu - alpha.cross(r) - omega.cross(omega.cross(r)); + + if (first_imu_recieved_) { + // 200 ms imu filter, assumes imu at 100 hz + state_.yaw_rate_ = omega.z(); + state_.ax_ -= state_.ax_ / 20; + state_.ax_ += accel.x() / 20; + state_.ay_ -= state_.ay_ / 20; + state_.ay_ += accel.y() / 20; + } else { + first_imu_recieved_ = true; + state_.yaw_rate_ = omega.z(); + state_.ax_ = accel.x(); + state_.ay_ = accel.y(); + } + // Stale or missing driver commands / odometry — command zero torque. const rclcpp::Time now_time = now(); const auto is_stale = [&](bool received, const rclcpp::Time& last_rx) { @@ -118,10 +157,7 @@ class TVNode : public rclcpp::Node { if (is_stale(have_cmd_, last_cmd_rx_) || is_stale(have_odom_, last_odom_rx_)) { RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 1000, "cmd_in/odom stale or missing — commanding zero torque"); - ros2can_msgs::msg::DvControlTargetTv out; // torque targets default to zero - out.dv_steering_angle_target_tv = - steering_cmd_.steering_angle_ * (180.0 / std::numbers::pi); - torque_pub_->publish(out); + publishZeroTorque(); return; } @@ -149,6 +185,39 @@ class TVNode : public rclcpp::Node { publishDebug(result); } + // The IMU mount is static, so the transform is looked up once per frame and cached. + std::optional lookupImuTransform(const std::string& imu_frame) { + if (imu_to_base_ && imu_frame == imu_frame_) { + return imu_to_base_; + } + try { + const auto tf = + tf_buffer_->lookupTransform(base_frame_, imu_frame, tf2::TimePointZero); + const auto& q = tf.transform.rotation; + const auto& t = tf.transform.translation; + Eigen::Isometry3d iso = Eigen::Isometry3d::Identity(); + iso.linear() = Eigen::Quaterniond(q.w, q.x, q.y, q.z).normalized().toRotationMatrix(); + iso.translation() = Eigen::Vector3d(t.x, t.y, t.z); + imu_to_base_ = iso; + imu_frame_ = imu_frame; + RCLCPP_INFO(get_logger(), "IMU transform %s -> %s acquired", imu_frame.c_str(), + base_frame_.c_str()); + return imu_to_base_; + } catch (const tf2::TransformException& ex) { + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 1000, + "no transform %s -> %s (%s) — commanding zero torque", + imu_frame.c_str(), base_frame_.c_str(), ex.what()); + return std::nullopt; + } + } + + void publishZeroTorque() { + ros2can_msgs::msg::DvControlTargetTv out; // torque targets default to zero + out.dv_steering_angle_target_tv = + steering_cmd_.steering_angle_ * (180.0 / std::numbers::pi); + torque_pub_->publish(out); + } + void publishDebug(const PipelineResult& result) { const auto to_msg = [](const std::array& src) { std_msgs::msg::Float64MultiArray msg; @@ -224,8 +293,8 @@ class TVNode : public rclcpp::Node { void odomCallback(const nav_msgs::msg::Odometry::SharedPtr& msg) { if (first_odom_recieved_) { // 200 ms odometry filter, assumes odometry at 100 hz - state_.vx_ -= state.vx_ / 20; - state_.vy_ -= state.vy_ / 20; + state_.vx_ -= state_.vx_ / 20; + state_.vy_ -= state_.vy_ / 20; state_.vx_ += msg->twist.twist.linear.x / 20; state_.vy_ += msg->twist.twist.linear.y / 20; } else { @@ -237,13 +306,17 @@ class TVNode : public rclcpp::Node { have_odom_ = true; } - // Per-wheel ω [FL, FR, RL, RR] (rad/s) for the DFO; the sample period comes from - // consecutive wheel-speed stamps. - void wheelSpeedsCallback(const fs_msgs::msg::Wheelspeeds::SharedPtr& msg) { + // Per-wheel ω [FL, FR, RL, RR] (rad/s) for the DFO, converted from motor rpm. The CAN + // message carries no header, so the sample period comes from consecutive receive times. + void wheelSpeedsCallback(const ros2can_msgs::msg::VehicleStatusWheelSpeed::SharedPtr& msg) { + constexpr double motor_rpm_to_wheel_rad_s = + 2.0 * std::numbers::pi / 60.0 / VehicleConfig::gear_ratio; WheelOmegas omegas; - omegas << msg->front_left, msg->front_right, msg->rear_left, msg->rear_right; + omegas << msg->wheel_speed_fl, msg->wheel_speed_fr, msg->wheel_speed_rl, + msg->wheel_speed_rr; + omegas *= motor_rpm_to_wheel_rad_s; - const rclcpp::Time stamp(msg->header.stamp); + const rclcpp::Time stamp = now(); double dt = 0.0; if (have_last_wheel_stamp_ && stamp > last_wheel_stamp_) { dt = (stamp - last_wheel_stamp_).seconds(); @@ -261,7 +334,8 @@ class TVNode : public rclcpp::Node { rclcpp::Subscription::SharedPtr imu_sub_; rclcpp::Subscription::SharedPtr odom_sub_; - rclcpp::Subscription::SharedPtr wheel_speeds_sub_; + rclcpp::Subscription::SharedPtr + wheel_speeds_sub_; rclcpp::Subscription::SharedPtr motor_torques_sub_; rclcpp::Subscription::SharedPtr steering_sub_; @@ -292,7 +366,7 @@ class TVNode : public rclcpp::Node { rclcpp::Time last_stamp_{0, 0, RCL_ROS_TIME}; bool have_last_stamp_{false}; - // Previous wheel-speed stamp — derives the DFO sample period. + // Previous wheel-speed receive time (node clock) — derives the DFO sample period. rclcpp::Time last_wheel_stamp_{0, 0, RCL_ROS_TIME}; bool have_last_wheel_stamp_{false}; @@ -306,6 +380,17 @@ class TVNode : public rclcpp::Node { bool first_odom_recieved_{false}; std::size_t alloc_failures_{0}; + + // IMU → base_frame transform, cached once the static transform is available. + std::string base_frame_; + std::unique_ptr tf_buffer_; + std::unique_ptr tf_listener_; + std::string imu_frame_; + std::optional imu_to_base_; + + // Previous base-frame ω — differentiated for the lever-arm angular acceleration. + Eigen::Vector3d last_omega_{Eigen::Vector3d::Zero()}; + bool have_last_omega_{false}; }; template diff --git a/launch/launch.py b/launch/launch.py index 16b79e4..7bcb52d 100644 --- a/launch/launch.py +++ b/launch/launch.py @@ -20,13 +20,14 @@ def generate_launch_description(): executable="torque_vectoring_node", name="torque_vectoring_node", output="screen", + parameters=[{"base_frame": "base_link"}], remappings=[ ("cmd_in", "navigation/dv_control_target"), - ("odom", "/odom"), - ("imu", "/imu"), - ("wheel_speeds", "vehicle/wheel_speeds"), - ("motor_torques", "ros2can/receive/vehicle_status_motor_torques"), - ("cmd_out", "ros2can/send/dv_control_target_tv"), + ("odom", "/slam/output/odom"), + ("imu", "/ouster/imu"), + ("wheel_speeds", "/ros2can/recv/vehicle_status_wheel_speed"), + ("motor_torques", "/ros2can/recv/vehicle_status_motor_torques"), + ("cmd_out", "/navigation/dv_control_target_tv"), ], ), ] diff --git a/package.xml b/package.xml index 620b5a0..b5183cc 100644 --- a/package.xml +++ b/package.xml @@ -19,6 +19,8 @@ vehicle_params_cpp fs_msgs ros2can_msgs + tf2 + tf2_ros ament_lint_auto ament_lint_common