From 1eedf0c8e7f3f067ee17a73ba585c250075e716d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Cab=C3=A9?= Date: Sat, 31 Oct 2026 00:49:42 +0100 Subject: [PATCH] perf(ekf2): cut covariance kernel cost without changing the estimate (#29242) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf(ekf2): skip the zero entries of H in P * H Most observation Jacobians depend on a handful of states only, yet the Kalman gain and both P * H products of the Joseph update ran a dense 24x24 matrix-vector product. Accumulating only the non-zero entries of H, in the same order, leaves every partial sum unchanged, so P and the gains stay bit-identical while the products drop from 576 multiply-adds to 24 per non-zero entry. Add Ekf::computeKalmanGain() and use it at the aid sources that built K as P * H / innov_var. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Benjamin Cabé * perf(ekf2): evaluate the Joseph update in a single pass Step 1 of the Joseph covariance update stored the whole 24x24 P_temp = P - K * PH^T, and step 2 read it back for P_temp * H and the stabilized update of the lower triangle, overwriting the rest. Evaluate each P_temp entry where it is used instead: its columns selected by H for P_temp * H first, then in a single pass over the lower triangle, mirrored to the upper one. The arithmetic of every entry is unchanged, so P stays bit-identical, while the temporary is never written or read back. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Benjamin Cabé * perf(ekf2): only derive the covariance prediction of the kinematic states The gyro bias, accel bias, mag, wind and terrain states have an identity process model, so 120 of the 300 outputs of the generated PredictCovariance() were plain copies of P, which predictCovariance() then copied back into P and mirrored in full. Return only the rows of the quaternion, velocity and position states and update P in place. Regenerated with symforce 0.9.0, the version that reproduces the committed headers byte-for-byte: the intermediate terms and the 180 remaining outputs are unchanged, so P stays bit-identical. The function is 2.8 KB smaller (15.5 to 12.8 KB on Cortex-M7), which matters on boards executing from external flash, and its stack temporary drops from 2304 to 864 bytes. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Benjamin Cabé * refactor(ekf2): take the predicted covariance row count from its type sizeof(P_pred) gives the row count only while matrix::Matrix holds nothing but its data. The predict_covariance return annotation still described the full 24x24 matrix; symforce 0.9.0 regenerates the committed headers unchanged. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Jacob Dahl * perf(ekf2): run computeKalmanGain from ITCM Every fusion now calls it, and on the boards that keep measurementUpdate and controlGravityFusion in ITCM it sat in flash, reached through a veneer. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Jacob Dahl --------- Signed-off-by: Benjamin Cabé Signed-off-by: Jacob Dahl Co-authored-by: Jacob Dahl --- .../scripts/itcm_functions_includes.ld | 1 + .../scripts/itcm_functions_includes.ld | 1 + .../scripts/itcm_functions_includes.ld | 1 + .../scripts/itcm_functions_includes.ld | 1 + .../scripts/itcm_gen_functions.ld | 1 + .../scripts/itcm_functions_includes.ld | 1 + .../aid_sources/airspeed/airspeed_fusion.cpp | 2 +- .../ekf2/EKF/aid_sources/drag/drag_fusion.cpp | 2 +- .../external_vision/ev_vel_control.cpp | 2 +- .../EKF/aid_sources/gnss/gnss_yaw_control.cpp | 2 +- .../aid_sources/gravity/gravity_fusion.cpp | 2 +- .../aid_sources/magnetometer/mag_fusion.cpp | 4 +- .../optical_flow/optical_flow_fusion.cpp | 2 +- .../range_finder/range_height_fusion.cpp | 2 +- .../ranging_beacon/ranging_beacon_control.cpp | 2 +- .../aid_sources/sideslip/sideslip_fusion.cpp | 2 +- src/modules/ekf2/EKF/covariance.cpp | 37 +++-- src/modules/ekf2/EKF/ekf.h | 5 +- src/modules/ekf2/EKF/ekf_helper.cpp | 96 ++++++++++--- .../EKF/python/ekf_derivation/derivation.py | 11 +- .../generated/predict_covariance.h | 136 ++---------------- 21 files changed, 137 insertions(+), 176 deletions(-) diff --git a/boards/agam/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld b/boards/agam/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld index 1b51bb7043e..58a96d058ab 100644 --- a/boards/agam/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/agam/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld @@ -433,6 +433,7 @@ *(.text.nxsig_timeout) *(.text._ZN11RateControl19setSaturationStatusERKN6matrix7Vector3IbEES4_) *(.text._ZN3Ekf17measurementUpdateERN6matrix6VectorIfLj24EEERKS2_ff) +*(.text._ZNK3Ekf17computeKalmanGainERKN6matrix6VectorIfLj24EEEf) *(.text._ZN19MavlinkStreamVFRHUD4sendEv) *(.text.hrt_call_reschedule) *(.text.nxsem_boost_priority) diff --git a/boards/ark/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld b/boards/ark/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld index 6468bdc8c8e..bbcfab71dc0 100644 --- a/boards/ark/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/ark/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld @@ -421,6 +421,7 @@ *(.text.nxsig_timeout) *(.text._ZN11RateControl19setSaturationStatusERKN6matrix7Vector3IbEES4_) *(.text._ZN3Ekf17measurementUpdateERN6matrix6VectorIfLj24EEERKS2_ff) +*(.text._ZNK3Ekf17computeKalmanGainERKN6matrix6VectorIfLj24EEEf) *(.text._ZN19MavlinkStreamVFRHUD4sendEv) *(.text.hrt_call_reschedule) *(.text.nxsem_boost_priority) diff --git a/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld b/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld index e6dc1e6a3a0..148327d06bc 100644 --- a/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld @@ -426,6 +426,7 @@ *(.text.nxsig_timeout) *(.text._ZN11RateControl19setSaturationStatusERKN6matrix7Vector3IbEES4_) *(.text._ZN3Ekf17measurementUpdateERN6matrix6VectorIfLj24EEERKS2_ff) +*(.text._ZNK3Ekf17computeKalmanGainERKN6matrix6VectorIfLj24EEEf) *(.text._ZN19MavlinkStreamVFRHUD4sendEv) *(.text.hrt_call_reschedule) *(.text.nxsem_boost_priority) diff --git a/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld b/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld index 491065eafa3..e39df739da0 100644 --- a/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld @@ -426,6 +426,7 @@ *(.text.nxsig_timeout) *(.text._ZN11RateControl19setSaturationStatusERKN6matrix7Vector3IbEES4_) *(.text._ZN3Ekf17measurementUpdateERN6matrix6VectorIfLj24EEERKS2_ff) +*(.text._ZNK3Ekf17computeKalmanGainERKN6matrix6VectorIfLj24EEEf) *(.text._ZN19MavlinkStreamVFRHUD4sendEv) *(.text.hrt_call_reschedule) *(.text.nxsem_boost_priority) diff --git a/boards/px4/fmu-v5x/nuttx-config/scripts/itcm_gen_functions.ld b/boards/px4/fmu-v5x/nuttx-config/scripts/itcm_gen_functions.ld index e0e9b5cda54..c64636414db 100644 --- a/boards/px4/fmu-v5x/nuttx-config/scripts/itcm_gen_functions.ld +++ b/boards/px4/fmu-v5x/nuttx-config/scripts/itcm_gen_functions.ld @@ -13,3 +13,4 @@ *(.text.param_get_default_value) *(.text._Z12get_orb_meta6ORB_ID) *(.text._ZN3Ekf17measurementUpdateERN6matrix6VectorIfLj24EEERKS2_ff) +*(.text._ZNK3Ekf17computeKalmanGainERKN6matrix6VectorIfLj24EEEf) diff --git a/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld b/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld index 1b51bb7043e..58a96d058ab 100644 --- a/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld @@ -433,6 +433,7 @@ *(.text.nxsig_timeout) *(.text._ZN11RateControl19setSaturationStatusERKN6matrix7Vector3IbEES4_) *(.text._ZN3Ekf17measurementUpdateERN6matrix6VectorIfLj24EEERKS2_ff) +*(.text._ZNK3Ekf17computeKalmanGainERKN6matrix6VectorIfLj24EEEf) *(.text._ZN19MavlinkStreamVFRHUD4sendEv) *(.text.hrt_call_reschedule) *(.text.nxsem_boost_priority) diff --git a/src/modules/ekf2/EKF/aid_sources/airspeed/airspeed_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/airspeed/airspeed_fusion.cpp index 97f7c32fe39..d85123a63ad 100644 --- a/src/modules/ekf2/EKF/aid_sources/airspeed/airspeed_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/airspeed/airspeed_fusion.cpp @@ -222,7 +222,7 @@ void Ekf::fuseAirspeed(const airspeedSample &airspeed_sample, estimator_aid_sour _fault_status.flags.bad_airspeed = false; const VectorState H = sym::ComputeAirspeedH(_state.vector(), FLT_EPSILON); - VectorState K = P * H / aid_src.innovation_variance; + VectorState K = computeKalmanGain(H, aid_src.innovation_variance); if (update_wind_only) { const Vector2f K_wind = K.slice(State::wind_vel.idx, 0); diff --git a/src/modules/ekf2/EKF/aid_sources/drag/drag_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/drag/drag_fusion.cpp index a5a81db319f..59c6552e442 100644 --- a/src/modules/ekf2/EKF/aid_sources/drag/drag_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/drag/drag_fusion.cpp @@ -171,7 +171,7 @@ void Ekf::fuseDrag(const dragSample &drag_sample) && (test_ratio < 1.f) ) { - VectorState K = P * H / innovation_variance(axis_index); + VectorState K = computeKalmanGain(H, innovation_variance(axis_index)); measurementUpdate(K, H, R_ACC, innovation(axis_index)); } diff --git a/src/modules/ekf2/EKF/aid_sources/external_vision/ev_vel_control.cpp b/src/modules/ekf2/EKF/aid_sources/external_vision/ev_vel_control.cpp index 31b82dc3575..3e319ba62e7 100644 --- a/src/modules/ekf2/EKF/aid_sources/external_vision/ev_vel_control.cpp +++ b/src/modules/ekf2/EKF/aid_sources/external_vision/ev_vel_control.cpp @@ -193,7 +193,7 @@ void Ekf::fuseBodyFrameVelocity(estimator_aid_source3d_s &aid_src, const uint64_ aid_src.innovation[index] = Vector3f(_R_to_earth.transpose().row(index)) * _state.vel - measurement(index); - VectorState Kfusion = P * H[index] / aid_src.innovation_variance[index]; + VectorState Kfusion = computeKalmanGain(H[index], aid_src.innovation_variance[index]); measurementUpdate(Kfusion, H[index], aid_src.observation_variance[index], aid_src.innovation[index]); } diff --git a/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp b/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp index 1e102ff748c..839186c8852 100644 --- a/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp +++ b/src/modules/ekf2/EKF/aid_sources/gnss/gnss_yaw_control.cpp @@ -229,7 +229,7 @@ void Ekf::fuseGnssYaw(float antenna_yaw_offset) // calculate the Kalman gains // only calculate gains for states we are using - VectorState Kfusion = P * H / aid_src.innovation_variance; + VectorState Kfusion = computeKalmanGain(H, aid_src.innovation_variance); measurementUpdate(Kfusion, H, aid_src.observation_variance, aid_src.innovation); diff --git a/src/modules/ekf2/EKF/aid_sources/gravity/gravity_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/gravity/gravity_fusion.cpp index 91b5b4b6a76..90a63f52b00 100644 --- a/src/modules/ekf2/EKF/aid_sources/gravity/gravity_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/gravity/gravity_fusion.cpp @@ -108,7 +108,7 @@ void Ekf::controlGravityFusion(const imuSample &imu) const bool accel_clipping = imu.delta_vel_clipping[0] || imu.delta_vel_clipping[1] || imu.delta_vel_clipping[2]; if (_control_status.flags.gravity_vector && !_aid_src_gravity.innovation_rejected && !accel_clipping) { - VectorState K = P * H / _aid_src_gravity.innovation_variance[index]; + VectorState K = computeKalmanGain(H, _aid_src_gravity.innovation_variance[index]); fused[index] = measurementUpdate(K, H, _aid_src_gravity.observation_variance[index], _aid_src_gravity.innovation[index]); diff --git a/src/modules/ekf2/EKF/aid_sources/magnetometer/mag_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/magnetometer/mag_fusion.cpp index 6d388f76bd8..c40fe65f5e0 100644 --- a/src/modules/ekf2/EKF/aid_sources/magnetometer/mag_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/magnetometer/mag_fusion.cpp @@ -107,7 +107,7 @@ bool Ekf::fuseMag(const Vector3f &mag, const float R_MAG, VectorState &H, estima return false; } - VectorState Kfusion = P * H / aid_src.innovation_variance[index]; + VectorState Kfusion = computeKalmanGain(H, aid_src.innovation_variance[index]); if (update_all_states) { if (!update_tilt) { @@ -179,7 +179,7 @@ bool Ekf::fuseDeclination(float decl_measurement_rad, float R, bool update_all_s } // Calculate the Kalman gains - VectorState Kfusion = P * H / innovation_variance; + VectorState Kfusion = computeKalmanGain(H, innovation_variance); if (update_all_states) { if (!update_tilt) { diff --git a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp index e2c72be9be1..745c4097ff6 100644 --- a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp @@ -85,7 +85,7 @@ bool Ekf::fuseOptFlow(VectorState &H, const bool update_terrain) return false; } - VectorState Kfusion = P * H / _aid_src_optical_flow.innovation_variance[index]; + VectorState Kfusion = computeKalmanGain(H, _aid_src_optical_flow.innovation_variance[index]); if (!update_terrain) { Kfusion(State::terrain.idx) = 0.f; diff --git a/src/modules/ekf2/EKF/aid_sources/range_finder/range_height_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/range_finder/range_height_fusion.cpp index 695ecb38752..6b08d122bee 100644 --- a/src/modules/ekf2/EKF/aid_sources/range_finder/range_height_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/range_finder/range_height_fusion.cpp @@ -45,7 +45,7 @@ bool Ekf::fuseHaglRng(estimator_aid_source1d_s &aid_src, bool update_height, boo sym::ComputeHaglH(&H); // calculate the Kalman gain - VectorState K = P * H / aid_src.innovation_variance; + VectorState K = computeKalmanGain(H, aid_src.innovation_variance); if (!update_terrain) { K(State::terrain.idx) = 0.f; diff --git a/src/modules/ekf2/EKF/aid_sources/ranging_beacon/ranging_beacon_control.cpp b/src/modules/ekf2/EKF/aid_sources/ranging_beacon/ranging_beacon_control.cpp index 4412988968d..af2967a699f 100644 --- a/src/modules/ekf2/EKF/aid_sources/ranging_beacon/ranging_beacon_control.cpp +++ b/src/modules/ekf2/EKF/aid_sources/ranging_beacon/ranging_beacon_control.cpp @@ -117,7 +117,7 @@ void Ekf::fuseRangingBeacon(const rangingBeaconSample &sample) return; } - VectorState K = P * H / innov_var; + VectorState K = computeKalmanGain(H, innov_var); K(State::pos.idx + 2) = 0.f; // altitude is handled by height reference measurementUpdate(K, H, R, innovation); diff --git a/src/modules/ekf2/EKF/aid_sources/sideslip/sideslip_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/sideslip/sideslip_fusion.cpp index 48e5cb76709..9f72754e4f3 100644 --- a/src/modules/ekf2/EKF/aid_sources/sideslip/sideslip_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/sideslip/sideslip_fusion.cpp @@ -128,7 +128,7 @@ bool Ekf::fuseSideslip(estimator_aid_source1d_s &sideslip) const float epsilon = 1e-3f; const VectorState H = sym::ComputeSideslipH(_state.vector(), epsilon); - VectorState K = P * H / sideslip.innovation_variance; + VectorState K = computeKalmanGain(H, sideslip.innovation_variance); if (update_wind_only) { const Vector2f K_wind = K.slice(State::wind_vel.idx, 0); diff --git a/src/modules/ekf2/EKF/covariance.cpp b/src/modules/ekf2/EKF/covariance.cpp index 5820fc74d73..4975c8729f5 100644 --- a/src/modules/ekf2/EKF/covariance.cpp +++ b/src/modules/ekf2/EKF/covariance.cpp @@ -47,6 +47,15 @@ #include #include +namespace +{ +template +constexpr size_t numRows(const matrix::Matrix &) +{ + return M; +} +} // namespace + // Sets initial values for the covariance matrix // Do not call before quaternion states have been initialised void Ekf::initialiseCovariance() @@ -133,11 +142,22 @@ void Ekf::predictCovariance(const imuSample &imu_delayed) } } - // calculate variances and upper diagonal covariances for quaternion, velocity, position and gyro bias states - P = sym::PredictCovariance(_state.vector(), P, - imu_delayed.delta_vel / imu_delayed.delta_vel_dt, accel_var, - imu_delayed.delta_ang / imu_delayed.delta_ang_dt, gyro_var, - dt); + // calculate variances and upper diagonal covariances for the quaternion, velocity and position states. + // The other states have an identity process model: their rows of the upper triangle are unchanged. + const auto P_pred = sym::PredictCovariance(_state.vector(), P, + imu_delayed.delta_vel / imu_delayed.delta_vel_dt, accel_var, + imu_delayed.delta_ang / imu_delayed.delta_ang_dt, gyro_var, + dt); + + constexpr unsigned predicted_rows = numRows(P_pred); + + // covariance matrix is symmetrical, so copy upper half to lower half + for (unsigned row = 0; row < predicted_rows; row++) { + for (unsigned column = row; column < State::size; column++) { + P(row, column) = P_pred(row, column); + P(column, row) = P_pred(row, column); + } + } if (!_control_status.flags.heading_observable) { // Zero heading correlations to prevent unintended heading corrections when heading is not observable @@ -236,13 +256,6 @@ void Ekf::predictCovariance(const imuSample &imu_delayed) #endif // CONFIG_EKF2_TERRAIN - // covariance matrix is symmetrical, so copy upper half to lower half - for (unsigned row = 0; row < State::size; row++) { - for (unsigned column = 0; column < row; column++) { - P(row, column) = P(column, row); - } - } - constrainStateVariances(); } diff --git a/src/modules/ekf2/EKF/ekf.h b/src/modules/ekf2/EKF/ekf.h index 164bb16a7ce..648068191a6 100644 --- a/src/modules/ekf2/EKF/ekf.h +++ b/src/modules/ekf2/EKF/ekf.h @@ -284,6 +284,9 @@ public: void fuseDirectStateMeasurement(const float innov, const float innov_var, const float R, const int state_index, bool constrain_variances = true); + // Kalman gain P * H / innov_var for a scalar observation with Jacobian H + VectorState computeKalmanGain(const VectorState &H, const float innov_var) const; + bool measurementUpdate(VectorState &K, const VectorState &H, const float R, const float innovation); // gyro bias @@ -926,7 +929,7 @@ private: bool fuseEvVelocity(estimator_aid_source3d_s &aid_src, const extVisionSample &ev_sample); void fuseBodyVelocity(estimator_aid_source1d_s &aid_src, float &innov_var, VectorState &H) { - VectorState Kfusion = P * H / innov_var; + VectorState Kfusion = computeKalmanGain(H, innov_var); measurementUpdate(Kfusion, H, aid_src.observation_variance, aid_src.innovation); aid_src.fused = true; } diff --git a/src/modules/ekf2/EKF/ekf_helper.cpp b/src/modules/ekf2/EKF/ekf_helper.cpp index 7d9a2c75b67..5e677f30ea5 100644 --- a/src/modules/ekf2/EKF/ekf_helper.cpp +++ b/src/modules/ekf2/EKF/ekf_helper.cpp @@ -45,6 +45,46 @@ #include #include +namespace +{ +// Indices of the non-zero entries of an observation Jacobian, in increasing order. +// Most observations depend on a handful of states only. Skipping the zero terms +// of P * H while keeping the summation order leaves every partial sum unchanged +// (s + P(i, j) * 0 == s for finite P), so the sparse product is bit-identical +// to the dense one. +struct NonZeroIndices { + explicit NonZeroIndices(const Ekf::VectorState &v) + { + for (unsigned i = 0; i < State::size; i++) { + // excludes +0 and -0 only: NaN entries are kept, as in the dense product + if (!(fabsf(v(i)) <= 0.f)) { + idx[count++] = i; + } + } + } + + uint8_t idx[State::size]; + uint8_t count{0}; +}; + +Ekf::VectorState multiplySparse(const Ekf::SquareMatrixState &P, const Ekf::VectorState &H, const NonZeroIndices &nz) +{ + Ekf::VectorState PH; + + for (unsigned i = 0; i < State::size; i++) { + float sum = 0.f; + + for (unsigned k = 0; k < nz.count; k++) { + sum += P(i, nz.idx[k]) * H(nz.idx[k]); + } + + PH(i) = sum; + } + + return PH; +} +} // namespace + bool Ekf::isHeightResetRequired() const { // check if height is continuously failing because of accel errors @@ -1065,24 +1105,22 @@ void Ekf::fuseDirectStateMeasurement(const float innov, const float innov_var, c // = P_temp * (I - H.T * K.T) + K * R * K.T // = P_temp - P_temp * H.T * K.T + K * R * K.T - // Step 1: conventional update - // Compute P_temp and store it in P to avoid allocating more memory + // P_temp = P - K * PH^T is never stored: each entry is evaluated where it is used, first in + // P_temp * H (its column state_index), then in the stabilized update of the lower triangle, + // which is mirrored to the upper one. This is the same arithmetic as storing P_temp first. // P is symmetric, so PH == H.T * P.T == H.T * P. Taking the row is faster as matrices are row-major - VectorState PH = P.row(state_index); + const VectorState PH = P.row(state_index); + VectorState P_temp_H; for (unsigned i = 0; i < State::size; i++) { - for (unsigned j = 0; j < State::size; j++) { - P(i, j) -= K(i) * PH(j); // P is now not symmetric if K is not optimal (e.g.: some gains have been zeroed) - } + P_temp_H(i) = P(i, state_index) - K(i) * PH(state_index); } - // Step 2: stabilized update - // P (or "P_temp") is not symmetric so we must take the column - PH = P.col(state_index); - for (unsigned i = 0; i < State::size; i++) { for (unsigned j = 0; j <= i; j++) { - P(i, j) = P(i, j) - PH(i) * K(j) + K(i) * R * K(j); + // P_temp is not symmetric if K is not optimal (e.g.: some gains have been zeroed) + const float P_temp = P(i, j) - K(i) * PH(j); + P(i, j) = P_temp - P_temp_H(i) * K(j) + K(i) * R * K(j); P(j, i) = P(i, j); } } @@ -1097,6 +1135,12 @@ void Ekf::fuseDirectStateMeasurement(const float innov, const float innov_var, c fuse(K, innov); } +Ekf::VectorState Ekf::computeKalmanGain(const VectorState &H, const float innov_var) const +{ + // K = P * H / innov_var + return multiplySparse(P, H, NonZeroIndices(H)) / innov_var; +} + bool Ekf::measurementUpdate(VectorState &K, const VectorState &H, const float R, const float innovation) { clearInhibitedStateKalmanGains(K); @@ -1118,23 +1162,31 @@ bool Ekf::measurementUpdate(VectorState &K, const VectorState &H, const float R, // = P_temp * (I - H.T * K.T) + K * R * K.T // = P_temp - P_temp * H.T * K.T + K * R * K.T - // Step 1: conventional update - // Compute P_temp and store it in P to avoid allocating more memory - // P is symmetric, so PH == H.T * P.T == H.T * P. Taking the row is faster as matrices are row-major - VectorState PH = P * H; // H is stored as a column vector. H is in fact H.T + // P_temp = P - K * PH^T is never stored: each entry is evaluated where it is used, first in + // P_temp * H (only its columns selected by H), then in the stabilized update of the lower + // triangle, which is mirrored to the upper one. This is the same arithmetic as storing P_temp first. + const VectorState K_local = K; // stores to P cannot alias the gain + const NonZeroIndices H_nz(H); + const VectorState PH = multiplySparse(P, H, H_nz); // H is stored as a column vector. H is in fact H.T + VectorState P_temp_H; for (unsigned i = 0; i < State::size; i++) { - for (unsigned j = 0; j < State::size; j++) { - P(i, j) -= K(i) * PH(j); // P is now not symmetrical if K is not optimal (e.g.: some gains have been zeroed) - } - } + float sum = 0.f; - // Step 2: stabilized update - PH = P * H; // H is stored as a column vector. H is in fact H.T + for (unsigned k = 0; k < H_nz.count; k++) { + const unsigned j = H_nz.idx[k]; + const float P_temp = P(i, j) - K_local(i) * PH(j); + sum += P_temp * H(j); + } + + P_temp_H(i) = sum; + } for (unsigned i = 0; i < State::size; i++) { for (unsigned j = 0; j <= i; j++) { - P(i, j) = P(i, j) - PH(i) * K(j) + K(i) * R * K(j); + // P_temp is not symmetrical if K is not optimal (e.g.: some gains have been zeroed) + const float P_temp = P(i, j) - K_local(i) * PH(j); + P(i, j) = P_temp - P_temp_H(i) * K_local(j) + K_local(i) * R * K_local(j); P(j, i) = P(i, j); } } diff --git a/src/modules/ekf2/EKF/python/ekf_derivation/derivation.py b/src/modules/ekf2/EKF/python/ekf_derivation/derivation.py index 11f500a6a2e..4bb15c74dfe 100755 --- a/src/modules/ekf2/EKF/python/ekf_derivation/derivation.py +++ b/src/modules/ekf2/EKF/python/ekf_derivation/derivation.py @@ -120,7 +120,7 @@ def predict_covariance( gyro: sf.V3, gyro_var: sf.Scalar, dt: sf.Scalar -) -> MTangent: +) -> sf.Matrix: state = vstate_to_state(state) g = sf.Symbol("g") # does not appear in the jacobians @@ -216,7 +216,14 @@ def predict_covariance( if index > j: P_new[index,j] = 0 - return P_new + # The states after the kinematic ones have an identity process model and no process + # noise here, so their rows of the upper triangle are copies of P: only return the rows + # up to the last kinematic state and let the implementation keep the rest of P. + n = state.tangent_dim() + I = sf.Matrix.eye(n) + n_predicted = 1 + max(i for i in range(n) if A[i, :] != I[i, :] or G[i, :] != sf.Matrix.zeros(1, G.shape[1])) + + return P_new[:n_predicted, :] def jacobian_chain_rule(expr: sf.Scalar , state: State): # First compute the jacobian in the parameter space diff --git a/src/modules/ekf2/EKF/python/ekf_derivation/generated/predict_covariance.h b/src/modules/ekf2/EKF/python/ekf_derivation/generated/predict_covariance.h index edf246a6bf6..6f65b166098 100644 --- a/src/modules/ekf2/EKF/python/ekf_derivation/generated/predict_covariance.h +++ b/src/modules/ekf2/EKF/python/ekf_derivation/generated/predict_covariance.h @@ -25,15 +25,15 @@ namespace sym { * dt: Scalar * * Outputs: - * res: Matrix24_24 + * res: Matrix9_24 */ template -matrix::Matrix PredictCovariance(const matrix::Matrix& state, - const matrix::Matrix& P, - const matrix::Matrix& accel, - const matrix::Matrix& accel_var, - const matrix::Matrix& gyro, - const Scalar gyro_var, const Scalar dt) { +matrix::Matrix PredictCovariance(const matrix::Matrix& state, + const matrix::Matrix& P, + const matrix::Matrix& accel, + const matrix::Matrix& accel_var, + const matrix::Matrix& gyro, + const Scalar gyro_var, const Scalar dt) { // Total ops: 1810 // Unused inputs @@ -232,7 +232,7 @@ matrix::Matrix PredictCovariance(const matrix::Matrix _res; + matrix::Matrix _res; _res.setZero(); @@ -357,7 +357,6 @@ matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix PredictCovariance(const matrix::Matrix