fix(ekf2): keep the output predictor attitude correction in earth frame (#29062)

* fix(ekf2): keep the output predictor attitude correction in earth frame

The attitude correction is the error between the EKF and the output
predictor at the delayed fusion time horizon, expressed in the body
frame at that time. It was added unchanged to the delta angle at the
current time horizon, where the body has turned by yaw rate x delay.
Above about 61 deg (7 rad/s with a 150 ms delay) this feedback loop is
unstable and vehicle_attitude diverges while the EKF state stays right,
e.g. when a quadrotor spins after losing a motor.

Hold the correction in earth frame and express it in the current body
frame when it is applied. This is the same as correcting at the delayed
horizon and integrating the gyro forward. Attitude resets rotate the
earth frame, so they rotate the held correction too.

Signed-off-by: Isak Åslund <isak.aslund@airolit.com>

* test(ekf2): check output predictor attitude tracking while spinning

Drive the output predictor with a constant body rate about roll, pitch
or yaw and a perfect but delayed EKF attitude: an attitude error must
be removed at 0 to 25 rad/s. The old body-frame correction fails at
7 rad/s and above on every axis.

Also check that a yaw reset commutes with a pending attitude correction.

Signed-off-by: Isak Åslund <isak.aslund@airolit.com>

* refactor(ekf2): compute output predictor attitude error in earth frame

Form the attitude tracking error directly as an earth-frame rotation
instead of computing it in the delayed body frame and rotating it out;
the result is identical and saves a vector rotation per EKF update.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: bresch <brescianimathieu@gmail.com>

---------

Signed-off-by: Isak Åslund <isak.aslund@airolit.com>
Signed-off-by: bresch <brescianimathieu@gmail.com>
Co-authored-by: bresch <brescianimathieu@gmail.com>
(cherry picked from commit 004f014719)
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Ramon Roche <mrpollo@gmail.com>
This commit is contained in:
Isak Åslund authored and Ramon Roche committed 2026-11-16 12:37:55 -08:00
1 parent 727f5f5b5f
commit 9d8cfcfc91
4 files changed
+203 -11

No files matched your search

@@ -93,6 +93,9 @@ void OutputPredictor::alignOutputFilter(const Quatf &quat_state, const Vector3f
_output_buffer[i].pos += pos_delta;
}
// the attitude correction is held in earth frame, which has just been rotated
_delta_angle_corr_earth = q_delta.rotateVector(_delta_angle_corr_earth);
_output_new = _output_buffer.get_newest();
}
@@ -116,7 +119,7 @@ void OutputPredictor::reset()
_delta_angle_sum.setIdentity();
_delta_angle_sum_dt = 0.f;
_delta_angle_corr.setZero();
_delta_angle_corr_earth.setZero();
_vel_err_integ.setZero();
_pos_err_integ.setZero();
@@ -142,6 +145,9 @@ void OutputPredictor::resetQuaternion(const Quatf &quat_change)
// apply the change in attitude quaternion to our newest quaternion estimate
// which was already taken out from the output buffer
_output_new.quat_nominal = quat_change * _output_new.quat_nominal;
// the attitude correction is held in earth frame, which has just been rotated
_delta_angle_corr_earth = quat_change.rotateVector(_delta_angle_corr_earth);
}
void OutputPredictor::resetHorizontalVelocityTo(const Vector2f &delta_horz_vel)
@@ -189,7 +195,8 @@ void OutputPredictor::calculateOutputStates(const uint64_t time_us, const Vector
// correct delta angle and delta velocity for bias offsets
// Apply corrections to the delta angle required to track the quaternion states at the EKF fusion time horizon
const Vector3f delta_angle_bias_scaled = _gyro_bias * delta_angle_dt;
const Vector3f delta_angle_corrected(delta_angle - delta_angle_bias_scaled + _delta_angle_corr);
const Vector3f delta_angle_corr = _output_new.quat_nominal.rotateVectorInverse(_delta_angle_corr_earth);
const Vector3f delta_angle_corrected(delta_angle - delta_angle_bias_scaled + delta_angle_corr);
const Vector3f delta_vel_bias_scaled = _accel_bias * delta_velocity_dt;
const Vector3f delta_velocity_corrected(delta_velocity - delta_vel_bias_scaled);
@@ -291,13 +298,11 @@ void OutputPredictor::correctOutputStates(const uint64_t time_delayed_us,
const outputSample &output_delayed = _output_buffer.get_oldest();
const outputVert &output_vert_delayed = _output_vert_buffer.get_oldest();
// calculate the quaternion delta between the INS and EKF quaternions at the EKF fusion time horizon
const Quatf q_error((quat_state.inversed() * output_delayed.quat_nominal).normalized());
// convert the quaternion delta to a delta angle
const float scalar = (q_error(0) >= 0.0f) ? -2.f : 2.f;
const Vector3f delta_ang_error{scalar * q_error(1), scalar * q_error(2), scalar * q_error(3)};
// Earth frame rotation from the INS to the EKF quaternion at the EKF fusion time horizon. Two attitudes
// integrated from the same gyro keep a constant error in earth frame, so the correction stays valid at the
// current time horizon however far the vehicle has turned since.
const Quatf q_error((quat_state * output_delayed.quat_nominal.inversed()).canonical().normalized());
const Vector3f delta_ang_error = 2.f * q_error.imag();
// calculate a gain that provides tight tracking of the estimator attitude states and
// adjust for changes in time delay to maintain consistent damping ratio of ~0.7
@@ -307,7 +312,7 @@ void OutputPredictor::correctOutputStates(const uint64_t time_delayed_us,
// calculate a corrrection to the delta angle
// that will cause the INS to track the EKF quaternions
_delta_angle_corr = delta_ang_error * att_gain;
_delta_angle_corr_earth = delta_ang_error * att_gain;
_output_tracking_error(0) = delta_ang_error.norm();
/*
@@ -187,7 +187,7 @@ private:
float _delta_vel_dt{}; // duration of delta velocity integration (s)
// output predictor states
matrix::Vector3f _delta_angle_corr{}; ///< delta angle correction vector (rad)
matrix::Vector3f _delta_angle_corr_earth{}; ///< delta angle correction vector, earth frame (rad)
matrix::Vector3f _vel_err_integ{}; ///< integral of velocity tracking error (m)
matrix::Vector3f _pos_err_integ{}; ///< integral of position tracking error (m.s)
+1
View File
@@ -55,6 +55,7 @@ px4_add_unit_gtest(SRC test_EKF_initialization.cpp LINKLIBS ecl_EKF ecl_sensor_s
px4_add_unit_gtest(SRC test_EKF_mag.cpp LINKLIBS ecl_EKF ecl_sensor_sim)
px4_add_unit_gtest(SRC test_EKF_mag_declination_generated.cpp LINKLIBS ecl_EKF ecl_test_helper)
px4_add_unit_gtest(SRC test_EKF_measurementSampling.cpp LINKLIBS ecl_EKF ecl_sensor_sim)
px4_add_unit_gtest(SRC test_EKF_output_predictor.cpp LINKLIBS output_predictor lat_lon_alt geo)
px4_add_unit_gtest(SRC test_EKF_terrain.cpp LINKLIBS ecl_EKF ecl_sensor_sim ecl_test_helper)
px4_add_unit_gtest(SRC test_EKF_utils.cpp LINKLIBS ecl_EKF ecl_sensor_sim)
px4_add_unit_gtest(SRC test_EKF_withReplayData.cpp LINKLIBS ecl_EKF ecl_sensor_sim)
@@ -0,0 +1,186 @@
/****************************************************************************
*
* Copyright (c) 2026 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file test_EKF_output_predictor.cpp
*
* @brief Unit tests for the output predictor attitude tracking
*
* The output predictor integrates the gyro at the current time horizon and is pulled towards the EKF
* attitude, which is known at the delayed fusion time horizon. These tests drive it directly with a
* known rotation and a perfect (but delayed) EKF attitude.
*/
#include <gtest/gtest.h>
#include <cmath>
#include <tuple>
#include "EKF/output_predictor/output_predictor.h"
using namespace matrix;
namespace
{
constexpr uint64_t kImuDtUs = 4000; // 250 Hz IMU
constexpr float kImuDt = kImuDtUs * 1e-6f;
constexpr int kImuPerUpdate = 2; // EKF update every 8 ms
constexpr uint8_t kBufferLength = 20; // delay = (length - 1) * 8 ms = 152 ms
constexpr float kGravity = 9.80665f;
float angleBetween(const Quatf &a, const Quatf &b)
{
const Quatf q_err = (a.inversed() * b).normalized();
return 2.f * asinf(math::min(Vector3f(q_err(1), q_err(2), q_err(3)).norm(), 1.f));
}
// Vehicle spinning at a constant body rate, an output predictor and a perfect EKF that lags by the buffer delay
class OutputPredictorSim
{
public:
OutputPredictorSim()
{
_op.allocate(kBufferLength);
_op.set_gravity(kGravity);
}
void setBodyRate(const Vector3f &body_rate)
{
_body_rate = body_rate;
_tick_spin_start = _tick;
}
// attitude of the vehicle at IMU tick n, spinning at a constant body rate since setBodyRate()
Quatf truth(int tick) const
{
const float spin_time = static_cast<float>(math::max(tick - _tick_spin_start, 0)) * kImuDt;
return Quatf(AxisAnglef(_body_rate * spin_time));
}
Quatf truthNow() const { return truth(_tick); }
void run(float duration, const Quatf &ekf_frame = Quatf())
{
const int steps = static_cast<int>(lroundf(duration / kImuDt));
const int delay_ticks = (kBufferLength - 1) * kImuPerUpdate;
for (int i = 0; i < steps; i++) {
_tick++;
const uint64_t time_us = static_cast<uint64_t>(_tick) * kImuDtUs;
const Vector3f delta_angle = _body_rate * kImuDt;
const Vector3f delta_velocity = truth(_tick).rotateVectorInverse(Vector3f(0.f, 0.f, -kGravity)) * kImuDt;
_op.calculateOutputStates(time_us, delta_angle, kImuDt, delta_velocity, kImuDt);
if (_tick % kImuPerUpdate == 0) {
const uint64_t time_delayed_us = time_us - static_cast<uint64_t>(delay_ticks) * kImuDtUs;
_op.correctOutputStates(time_delayed_us, ekf_frame * truth(_tick - delay_ticks), Vector3f(), _gpos,
Vector3f(), Vector3f());
}
}
}
OutputPredictor _op;
private:
Vector3f _body_rate{};
int _tick{0};
int _tick_spin_start{0};
LatLonAlt _gpos{47.3977, 8.5456, 400.f};
};
}
class OutputPredictorSpin : public ::testing::TestWithParam<std::tuple<int, float>> {};
// An attitude error must be removed whatever the rotation rate, about roll, pitch or yaw. Before the correction
// was held in earth frame, it was applied about axes that had turned by rate x delay, and the error grew above
// about 7 rad/s.
TEST_P(OutputPredictorSpin, attitudeErrorConvergesWhileSpinning)
{
const int axis = std::get<0>(GetParam());
const float rate = std::get<1>(GetParam());
Vector3f body_rate{};
body_rate(axis) = rate;
// an error about an axis perpendicular to the spin; an error along it is not affected
Vector3f error_axis{};
error_axis(axis == 0 ? 1 : 0) = 1.f;
OutputPredictorSim sim;
sim.run(1.f); // settle at rest
sim.setBodyRate(body_rate);
sim.run(0.5f);
// rotate the output 2 degrees away from the EKF (and from the truth)
sim._op.resetQuaternion(Quatf(AxisAnglef(error_axis * math::radians(2.f))));
EXPECT_NEAR(math::degrees(angleBetween(sim._op.getQuaternion(), sim.truthNow())), 2.f, 0.01f);
sim.run(4.f);
EXPECT_LT(math::degrees(angleBetween(sim._op.getQuaternion(), sim.truthNow())), 0.05f)
<< "axis " << axis << ", rate " << rate << " rad/s";
}
INSTANTIATE_TEST_SUITE_P(RollPitchYaw, OutputPredictorSpin,
::testing::Combine(::testing::Values(0, 1, 2), ::testing::Values(0.f, 3.f, 7.f, 15.f, 25.f)));
// Rotating the earth frame (e.g. a yaw reset) must commute with the output predictor:
// resetting and then running must give the same result as running and then resetting.
TEST(OutputPredictor, yawResetCommutesWithAttitudeCorrection)
{
OutputPredictorSim a;
OutputPredictorSim b;
for (OutputPredictorSim *sim : {&a, &b}) {
sim->run(1.f);
sim->setBodyRate(Vector3f(0.f, 0.f, 10.f));
sim->run(0.5f);
// a large pending attitude correction
sim->_op.resetQuaternion(Quatf(AxisAnglef(Vector3f(math::radians(5.f), 0.f, 0.f))));
sim->run(0.02f);
}
const Quatf yaw_reset(AxisAnglef(Vector3f(0.f, 0.f, math::radians(30.f))));
a._op.resetQuaternion(yaw_reset);
float max_diff = 0.f;
for (int i = 0; i < 50; i++) {
a.run(kImuDt, yaw_reset);
b.run(kImuDt);
max_diff = math::max(max_diff, angleBetween(a._op.getQuaternion(), yaw_reset * b._op.getQuaternion()));
}
EXPECT_LT(max_diff, 5e-5f);
}