diff --git a/docs/en/advanced_features/vision_target_estimator_advanced.md b/docs/en/advanced_features/vision_target_estimator_advanced.md index f6a46508019..b855023832f 100644 --- a/docs/en/advanced_features/vision_target_estimator_advanced.md +++ b/docs/en/advanced_features/vision_target_estimator_advanced.md @@ -110,6 +110,9 @@ Open the box below if you are debugging a bias that fails to converge, jumps une If neither condition fires, the LPF is also accepted when [VTE_BIA_AVG_TOUT](../advanced_config/parameter_reference.md#VTE_BIA_AVG_TOUT) expires. - **Activation after averaging.** Once the LPF is accepted, the state resets via `activateBiasEstimate()`. This sets `r = pos_rel_gnss(t_vision) - b_filtered` and `b = b_filtered`. + Every bias activation resets the position and bias at `t_vision`, keeps a snapshot there so samples still in flight can be replayed, and propagates to now. + This initialisation bridge assumes constant UAV velocity and retains the current target motion estimate; it adds process noise rather than reusing an overconfident capture-time covariance. + A vision sample used to seed the position is reported as `STATUS_INITIALIZED` and is not fused again. #### Fallbacks and Recovery @@ -629,7 +632,7 @@ The `fusion_status` field records which fusion branch the filter. | 6 | `STATUS_REJECT_TOO_NEW` | Sample timestamped 20 ms or more after the latest filter prediction. | Time-sync problem: verify `mavlink_timesync` or the sensor clock. Built-in sources drop these with a warning. | | 7 | `STATUS_REJECT_STALE` | Filter history was reset because no prediction had run for longer than the buffer span. | Expected after long pauses; otherwise investigate scheduler stalls. | | 8 | `STATUS_REJECT_EMPTY` | History buffer not yet populated when the measurement arrived. | Expected after a history reset; position initialisation itself reports `STATUS_INITIALIZED`. | -| 9 | `STATUS_INITIALIZED` | Position observation used once to seed the state and its covariance, then propagated to the current time. | Healthy at position startup or restart. Innovation fields are NaN because no prior prediction exists. | +| 9 | `STATUS_INITIALIZED` | Observation used once to seed the state and its covariance, then propagated to the current time (position and yaw). | Healthy at startup or restart. Innovation fields are NaN because no prior prediction exists. | ::: diff --git a/src/modules/vision_target_estimator/Orientation/VTEOrientation.cpp b/src/modules/vision_target_estimator/Orientation/VTEOrientation.cpp index 90d8b93ccad..e1c2a0eabdd 100644 --- a/src/modules/vision_target_estimator/Orientation/VTEOrientation.cpp +++ b/src/modules/vision_target_estimator/Orientation/VTEOrientation.cpp @@ -42,6 +42,8 @@ #include +#include + #include #include "VTEOrientation.h" @@ -133,18 +135,40 @@ void VTEOrientation::initEstimator(const VisionObs &vision_obs) OrientationStateVec state_init{}; state_init(KF_orientation::kYaw) = vision_obs.yaw; + // The yaw is no better known than the sample that seeds it. OrientationStateVec state_var_init; state_var_init.setAll(fmaxf(_param_vte_yaw_unc_in.get(), kMinVariance)); + state_var_init(KF_orientation::kYaw) = fmaxf(state_var_init(KF_orientation::kYaw), vision_obs.yaw_var); _target_est_yaw.setState(state_init); _target_est_yaw.setStateCovarianceDiag(state_var_init); - _target_est_yaw.resetHistory({vision_obs.timestamp, 0}); PX4_DEBUG("VTE Orientation initialized with yaw: %.2f [rad]", (double)vision_obs.yaw); _estimator_initialized = true; _last_predict = nowUs(); _last_update = vision_obs.timestamp; + + // The sample is the state, so it is not fused. Snapshot it at its capture time for later replays. + _target_est_yaw.resetHistory({vision_obs.timestamp, 0}); + _target_est_yaw.pushHistory(vision_obs.timestamp); + + vte_aid_source1d_s aid{}; + aid.timestamp = _last_predict; + aid.timestamp_sample = vision_obs.timestamp; + aid.time_last_predict = _last_predict; + aid.time_since_meas_ms = (_last_predict - vision_obs.timestamp) * kMicrosecondsToMilliseconds; + aid.observation = vision_obs.yaw; + aid.observation_variance = vision_obs.yaw_var; + aid.innovation = NAN; + aid.innovation_variance = NAN; + aid.test_ratio = NAN; + aid.replay_test_ratio_max = -1.f; + aid.fusion_status = FusionStatus::STATUS_INITIALIZED; + _vte_aid_ev_yaw_pub.publish(aid); + + // Propagate the sample to now with the process noise. + predictionStep((_last_predict - vision_obs.timestamp) * kMicrosecondsToSeconds); } void VTEOrientation::predictionStep(float dt) @@ -163,6 +187,7 @@ void VTEOrientation::performUpdateStep() if (!_estimator_initialized) { initEstimator(vision_obs); + return; } fuseMeas(vision_obs); diff --git a/src/modules/vision_target_estimator/Orientation/VTEOrientation.h b/src/modules/vision_target_estimator/Orientation/VTEOrientation.h index c62c36af22b..182ff274eba 100644 --- a/src/modules/vision_target_estimator/Orientation/VTEOrientation.h +++ b/src/modules/vision_target_estimator/Orientation/VTEOrientation.h @@ -137,9 +137,9 @@ private: float yaw_var{0.f}; }; - /** Seed state and covariance from the first valid yaw sample. */ + /** Seed state and covariance from the first valid yaw sample, which is not fused. */ void initEstimator(const VisionObs &vision_obs); - /** Pull in new observations, initialise on first valid sample, and run fusion. */ + /** Pull in the new observation; initialise on the first valid sample, fuse the later ones. */ void performUpdateStep(); /** Advance the yaw state forward by @p dt using the constant yaw-rate model. */ void predictionStep(float dt); diff --git a/src/modules/vision_target_estimator/Position/KF_position.cpp b/src/modules/vision_target_estimator/Position/KF_position.cpp index 651e7993b12..ae8425dad95 100644 --- a/src/modules/vision_target_estimator/Position/KF_position.cpp +++ b/src/modules/vision_target_estimator/Position/KF_position.cpp @@ -70,6 +70,36 @@ void KF_position::predict(float dt, float acc_uav) _state_covariance = cov_next; } +void KF_position::resetPositionAndBias(float position, float position_var, float bias, float bias_var, float latency) +{ +#if defined(CONFIG_VTEST_MOVING) + // Move the retained motion estimate back to the capture time. Forward prediction must + // restore today's target velocity, not integrate its acceleration for a second time. + _state(vtest::State::vel_target) -= _state(vtest::State::acc_target) * latency; + SquareMatrixState rewind; + rewind.setIdentity(); + rewind(vtest::State::vel_target, vtest::State::acc_target) = -latency; + _state_covariance = rewind * _state_covariance * rewind.transpose(); +#else + (void)latency; +#endif // CONFIG_VTEST_MOVING + + _state(vtest::State::pos_rel) = position; + _state(vtest::State::bias) = bias; + + // Only the replaced states lose their previous correlations. Retain the motion + // covariance; subsequent prediction adds process noise without subtracting past noise. + for (size_t i = 0; i < kStateSize; ++i) { + _state_covariance(vtest::State::pos_rel, i) = 0.f; + _state_covariance(i, vtest::State::pos_rel) = 0.f; + _state_covariance(vtest::State::bias, i) = 0.f; + _state_covariance(i, vtest::State::bias) = 0.f; + } + + _state_covariance(vtest::State::pos_rel, vtest::State::pos_rel) = fmaxf(position_var, kMinVar); + _state_covariance(vtest::State::bias, vtest::State::bias) = fmaxf(bias_var, kMinVar); +} + void KF_position::predictState(float dt, float acc, const VectorState &x_in, const SquareMatrixState &P_in, diff --git a/src/modules/vision_target_estimator/Position/KF_position.h b/src/modules/vision_target_estimator/Position/KF_position.h index ef722701d6a..ca6039f91a1 100644 --- a/src/modules/vision_target_estimator/Position/KF_position.h +++ b/src/modules/vision_target_estimator/Position/KF_position.h @@ -76,6 +76,10 @@ public: void predict(float dt, float acc_uav); + // Seed position/bias at a delayed capture time while retaining the current motion estimate. + // Call predict(latency, 0) afterwards to bridge back to now with constant UAV velocity. + void resetPositionAndBias(float position, float position_var, float bias, float bias_var, float latency); + // Primary Fusion Interface (history-consistent OOSM) // Delayed observations are fused at their timestamp and subsequent stored observations // are replayed in timestamp order, gated again and with recomputed Kalman gains. diff --git a/src/modules/vision_target_estimator/Position/VTEPosition.cpp b/src/modules/vision_target_estimator/Position/VTEPosition.cpp index aad0b67646f..bb38bb45880 100644 --- a/src/modules/vision_target_estimator/Position/VTEPosition.cpp +++ b/src/modules/vision_target_estimator/Position/VTEPosition.cpp @@ -293,8 +293,11 @@ void VTEPosition::performUpdateStep(const Vector3f &vehicle_acc_ned) return; } - if (!_bias.set) { - updateBiasIfObservable(fusion_mask, _obs_buffer); + if (!_bias.set && updateBiasIfObservable(fusion_mask, _obs_buffer)) { + // The vision sample is the state now and is not fused again, as at init. + const TargetObs &vision_obs = _obs_buffer[obsIndex(ObsType::kFiducialMarker)]; + fusion_mask.flags.fuse_vision = false; + publishInitializedAid(vision_obs); } fuseActiveMeasurements(vehicle_acc_ned, fusion_mask, _obs_buffer); @@ -580,18 +583,31 @@ bool VTEPosition::initializeEstimator(const ObsValidMaskU &fusion_mask, _last_relative_meas_fused_time = initial_obs.timestamp; } - vte_aid_source3d_s aid{}; - aid.timestamp = _last_predict; - aid.timestamp_sample = initial_obs.timestamp; - aid.time_last_predict = _last_predict; - aid.time_since_meas_ms = (_last_predict - initial_obs.timestamp) * kMicrosecondsToMilliseconds; - for (int axis = 0; axis < vtest::Axis::size; ++axis) { _target_est_pos[axis].resetHistory({_last_update, _last_relative_meas_fused_time}); _target_est_pos[axis].pushHistory(initial_obs.timestamp); - aid.observation[axis] = initial_obs.meas_xyz(axis); - aid.observation_variance[axis] = initial_obs.meas_unc_xyz(axis); - // There is no prior prediction against which to compute an innovation at startup. + } + + // No acceleration history exists yet. Propagate with constant velocity and grow the + // covariance with the normal process noise instead of labelling the raw sample as current. + predictionStep(Vector3f{}, (_last_predict - initial_obs.timestamp) * kMicrosecondsToSeconds); + publishInitializedAid(initial_obs); + + return true; +} + +void VTEPosition::publishInitializedAid(const TargetObs &obs) +{ + // The sample became the state, so there is no innovation. + vte_aid_source3d_s aid{}; + aid.timestamp = _last_predict; + aid.timestamp_sample = obs.timestamp; + aid.time_last_predict = _last_predict; + aid.time_since_meas_ms = static_cast(signedTimeDiffUs(_last_predict, obs.timestamp)) * kMicrosecondsToMilliseconds; + + for (int axis = 0; axis < vtest::Axis::size; ++axis) { + aid.observation[axis] = obs.meas_xyz(axis); + aid.observation_variance[axis] = obs.meas_unc_xyz(axis); aid.innovation[axis] = NAN; aid.innovation_variance[axis] = NAN; aid.test_ratio[axis] = NAN; @@ -599,12 +615,7 @@ bool VTEPosition::initializeEstimator(const ObsValidMaskU &fusion_mask, aid.fusion_status[axis] = FusionStatus::STATUS_INITIALIZED; } - // No acceleration history exists yet. Propagate with constant velocity and grow the - // covariance with the normal process noise instead of labelling the raw sample as current. - predictionStep(Vector3f{}, (_last_predict - initial_obs.timestamp) * kMicrosecondsToSeconds); - publishInnov(aid, initial_type); - - return true; + publishInnov(aid, obs.type); } void VTEPosition::selectInitialBiasFromGnss(const TargetObs observations[kObsTypeCount], @@ -703,20 +714,15 @@ bool VTEPosition::selectBiasGnssSample(const hrt_abstime sample_time, Vector3f & return true; } -void VTEPosition::updateBiasIfObservable(const ObsValidMaskU &fusion_mask, +bool VTEPosition::updateBiasIfObservable(const ObsValidMaskU &fusion_mask, const TargetObs observations[kObsTypeCount]) { if (!fusion_mask.flags.fuse_vision) { - return; + return false; } const TargetObs &vision_obs = observations[obsIndex(ObsType::kFiducialMarker)]; const hrt_abstime sample_time = vision_obs.timestamp; - - if (sample_time == 0) { - return; - } - const Vector3f &initial_position = vision_obs.meas_xyz; Vector3f gnss_sample{}; @@ -724,18 +730,21 @@ void VTEPosition::updateBiasIfObservable(const ObsValidMaskU &fusion_mask, if (!selectBiasGnssSample(sample_time, gnss_sample)) { if (_bias.averaging_active) { PX4_WARN("GNSS unavailable, ending bias averaging and switching to vision."); - activateBiasEstimate(initial_position, _bias.initial_lpf.getState()); + activateBiasEstimate(initial_position, _bias.initial_lpf.getState(), vision_obs, true); + return true; + } - } else if (_pre_bias_reference == PreBiasReference::kGnss) { + if (_pre_bias_reference == PreBiasReference::kGnss) { // The state was initialized GNSS-referenced, so vision fusion is currently // gated on the GNSS bias being observable. Without an aligned GNSS sample // we would never make progress and vision would be blocked indefinitely. // Activate the bias with a zero offset so the filter unblocks. PX4_WARN("GNSS bias not observable, setting bias to zero."); - activateBiasEstimate(initial_position, Vector3f{}); + activateBiasEstimate(initial_position, Vector3f{}, vision_obs, true); + return true; } - return; + return false; } const Vector3f initial_bias = gnss_sample - initial_position; @@ -743,22 +752,24 @@ void VTEPosition::updateBiasIfObservable(const ObsValidMaskU &fusion_mask, if (!_bias.averaging_active && shouldAverageInitialBias(fusion_mask.flags.fuse_vision)) { PX4_INFO("GNSS/vision bias observable, averaging initial GNSS bias."); startBiasAveraging(initial_bias, sample_time); - return; + return false; } if (_bias.averaging_active) { if (!updateBiasAveraging(initial_bias, sample_time)) { - return; + return false; } + // The averaged bias anchors the position to GNSS, so the vision sample is new information. PX4_INFO("GNSS bias averaging complete, setting position and bias."); const Vector3f filtered_bias = _bias.initial_lpf.getState(); - activateBiasEstimate(gnss_sample - filtered_bias, filtered_bias); - return; + activateBiasEstimate(gnss_sample - filtered_bias, filtered_bias, vision_obs, false); + return false; } PX4_INFO("GNSS/vision bias observable, setting position and bias."); - activateBiasEstimate(initial_position, initial_bias); + activateBiasEstimate(initial_position, initial_bias, vision_obs, true); + return true; } void VTEPosition::startBiasAveraging(const Vector3f &bias_sample, const hrt_abstime sample_time) @@ -825,32 +836,36 @@ void VTEPosition::resetBiasAveraging() _bias.initial_lpf.reset(Vector3f{}); } -void VTEPosition::activateBiasEstimate(const Vector3f &initial_position, const Vector3f &initial_bias) +void VTEPosition::activateBiasEstimate(const Vector3f &position, const Vector3f &bias, + const TargetObs &vision_obs, bool position_from_vision) { const float pos_var = fmaxf(_param_vte_pos_unc_in.get(), kMinVariance); const float bias_var = fmaxf(_param_vte_bias_unc_in.get(), kMinVariance); + const hrt_abstime reset_time = math::min(vision_obs.timestamp, _last_predict); + const float latency = (_last_predict - reset_time) * kMicrosecondsToSeconds; for (int axis = 0; axis < vtest::Axis::size; ++axis) { KF_position &filter = _target_est_pos[axis]; - EstimatorState state = filter.getState(); - state(vtest::State::bias) = initial_bias(axis); - state(vtest::State::pos_rel) = initial_position(axis); - filter.setState(state); + FusionTimes times = filter.getFusionTimes(); - EstimatorState state_var = filter.getStateCovarianceDiag(); - state_var(vtest::State::bias) = bias_var; - state_var(vtest::State::pos_rel) = pos_var; - filter.setStateCovarianceDiag(state_var); + if (position_from_vision) { + times.record(FusionSource::Relative, vision_obs.timestamp); + } - // Bias initialization is a state reset: restart OOSM history to avoid mixing pre/post-reset states. - filter.resetHistory(filter.getFusionTimes()); + filter.resetPositionAndBias(position(axis), fmaxf(pos_var, vision_obs.meas_unc_xyz(axis)), + bias(axis), fmaxf(bias_var, vision_obs.meas_unc_xyz(axis)), latency); + filter.resetHistory(times); + filter.pushHistory(reset_time); } - PX4_DEBUG("Rel pos init %.2f %.2f %.2f", (double)initial_position(vtest::Axis::x), - (double)initial_position(vtest::Axis::y), (double)initial_position(vtest::Axis::z)); + // Reconstruct this one-time initialization bridge with constant UAV velocity and + // the retained target acceleration. Grow covariance with the normal process noise. + predictionStep(Vector3f{}, latency); - PX4_DEBUG("GNSS bias init %.2f %.2f %.2f", (double)initial_bias(vtest::Axis::x), - (double)initial_bias(vtest::Axis::y), (double)initial_bias(vtest::Axis::z)); + PX4_DEBUG("Rel pos init %.2f %.2f %.2f", (double)position(vtest::Axis::x), + (double)position(vtest::Axis::y), (double)position(vtest::Axis::z)); + PX4_DEBUG("GNSS bias init %.2f %.2f %.2f", (double)bias(vtest::Axis::x), + (double)bias(vtest::Axis::y), (double)bias(vtest::Axis::z)); _bias.set = true; _pre_bias_reference = PreBiasReference::kUnknown; diff --git a/src/modules/vision_target_estimator/Position/VTEPosition.h b/src/modules/vision_target_estimator/Position/VTEPosition.h index 30d37044467..1e7278240c9 100644 --- a/src/modules/vision_target_estimator/Position/VTEPosition.h +++ b/src/modules/vision_target_estimator/Position/VTEPosition.h @@ -317,8 +317,9 @@ private: void buildInitialStateArray(const matrix::Vector3f &initial_position, const matrix::Vector3f &initial_uav_velocity, const matrix::Vector3f &initial_bias, AxisEstimatorStates &state_init) const; - /** Track the GNSS/vision bias until it is ready to be activated in the state. */ - void updateBiasIfObservable(const ObsValidMaskU &fusion_mask, + /** Track the GNSS/vision bias until it is ready to be activated in the state. + * Returns true when this cycle's vision sample became the position. */ + bool updateBiasIfObservable(const ObsValidMaskU &fusion_mask, const TargetObs observations[kObsTypeCount]); /** Pick the GNSS-relative sample that best matches the requested timestamp. */ bool selectBiasGnssSample(hrt_abstime sample_time, matrix::Vector3f &gnss_sample); @@ -332,8 +333,9 @@ private: void startBiasAveraging(const matrix::Vector3f &bias_sample, hrt_abstime sample_time); bool updateBiasAveraging(const matrix::Vector3f &bias_sample, hrt_abstime sample_time); void resetBiasAveraging(); - /** Commit the final pre-bias position/bias pair and restart OOSM history. */ - void activateBiasEstimate(const matrix::Vector3f &initial_position, const matrix::Vector3f &initial_bias); + /** Reset the position and bias from a sample: restart the OOSM history at its time and propagate to now. */ + void activateBiasEstimate(const matrix::Vector3f &position, const matrix::Vector3f &bias, + const TargetObs &vision_obs, bool position_from_vision); void publishBiasInitStatus(const matrix::Vector3f &raw_bias, const matrix::Vector3f &filtered_bias, float raw_bias_delta_norm, hrt_abstime sample_time); @@ -360,9 +362,11 @@ private: void updateTargetGpsVelocity(const target_gnss_s &target_gnss); #endif // CONFIG_VTEST_MOVING - /** Publish the per-axis fusion results of one observation. Returns true if any axis fused. */ + /** Publish the per-axis fusion results of one observation. */ void publishAidSource(const TargetObs &target_obs, const FusionResult(&results)[vtest::Axis::size]); void publishTarget(); + /** Report an observation that seeded the state instead of being fused. */ + void publishInitializedAid(const TargetObs &obs); void publishInnov(const vte_aid_source3d_s &target_innov, const ObsType type); void resetObservations(); bool shouldEmitWarning(hrt_abstime &last_warn); diff --git a/src/modules/vision_target_estimator/test/TEST_VTEOrientation.cpp b/src/modules/vision_target_estimator/test/TEST_VTEOrientation.cpp index b762242480e..b8ddae9f651 100644 --- a/src/modules/vision_target_estimator/test/TEST_VTEOrientation.cpp +++ b/src/modules/vision_target_estimator/test/TEST_VTEOrientation.cpp @@ -178,20 +178,62 @@ TEST_F(VTEOrientationTest, InitFromVisionYawPublishesOrientation) const float yaw_meas = 0.5f; pushValidYawSample(yaw_meas); - // THEN: the state initializes from that sample and publishes a fused innovation report. + // THEN: the state is the sample, no better known than the sample itself, and the report says so. ASSERT_TRUE(_state_sub->update()); const auto state = _state_sub->get(); EXPECT_NEAR(state.yaw, yaw_meas, kTolerance); EXPECT_NEAR(state.yaw_rate, 0.f, kTolerance); - // Reported variance is clamped to the configured floor (EVA_NOISE^2) before fusion. - const float meas_var = fmaxf(kMeasVar, kDefaultEvYawVar); - const float expected_cov = (kInitialYawUnc * meas_var) / (kInitialYawUnc + meas_var); - EXPECT_NEAR(state.cov_yaw, expected_cov, kTolerance); + EXPECT_NEAR(state.cov_yaw, fmaxf(kInitialYawUnc, kDefaultEvYawVar), kTolerance); + EXPECT_NEAR(state.cov_yaw_rate, kInitialYawUnc, kTolerance); ASSERT_TRUE(_aid_sub->update()); const auto aid = _aid_sub->get(); + // Reported variance is clamped to the configured floor (EVA_NOISE^2). EXPECT_NEAR(aid.observation_variance, kDefaultEvYawVar, kTolerance); - EXPECT_EQ(aid.fusion_status, static_cast(vte::FusionStatus::STATUS_FUSED_CURRENT)); + EXPECT_EQ(aid.fusion_status, static_cast(vte::FusionStatus::STATUS_INITIALIZED)); + EXPECT_TRUE(std::isnan(aid.innovation)); +} + +// WHY: The init sample is the state, so fusing it again would shrink the covariance without new information. +// WHAT: Initialize, then fuse a second sample and check the covariance of a single update. +TEST_F(VTEOrientationTest, FirstSampleIsNotFusedTwice) +{ + enableVisionFusion(); + pushValidYawSample(0.5f); + ASSERT_TRUE(_state_sub->update()); + ASSERT_TRUE(_aid_sub->update()); + + pushValidYawSample(0.5f); + + ASSERT_TRUE(_aid_sub->update()); + EXPECT_EQ(_aid_sub->get().fusion_status, static_cast(vte::FusionStatus::STATUS_FUSED_CURRENT)); + ASSERT_TRUE(_state_sub->update()); + const float meas_var = fmaxf(kMeasVar, kDefaultEvYawVar); + const float init_var = fmaxf(kInitialYawUnc, meas_var); + const float expected_cov = (init_var * meas_var) / (init_var + meas_var); + EXPECT_NEAR(_state_sub->get().cov_yaw, expected_cov, kTolerance); +} + +// WHY: A delayed init sample must leave a snapshot at its capture time, so later samples from +// between the capture and now can be replayed instead of being dropped as too old. +TEST_F(VTEOrientationTest, DelayedInitSampleSeedsHistoryAtCaptureTime) +{ + enableVisionFusion(); + const hrt_abstime now = vte_test::advanceMicroseconds(kStepUs); + publishVisionYaw(0.5f, kMeasVar, now - 100_ms); + _vte->update(); + ASSERT_TRUE(_aid_sub->update()); + EXPECT_EQ(_aid_sub->get().fusion_status, static_cast(vte::FusionStatus::STATUS_INITIALIZED)); + EXPECT_EQ(_aid_sub->get().timestamp_sample, now - 100_ms); + + vte_test::advanceMicroseconds(20_ms); + publishVisionYaw(0.52f, kMeasVar, now - 50_ms); + _vte->update(); + + ASSERT_TRUE(_aid_sub->update()); + EXPECT_EQ(_aid_sub->get().fusion_status, static_cast(vte::FusionStatus::STATUS_FUSED_OOSM)); + ASSERT_TRUE(_state_sub->update()); + EXPECT_LT(_state_sub->get().cov_yaw, fmaxf(kInitialYawUnc, kDefaultEvYawVar)); } // WHY: Fusion should be disabled when the aid mask is empty. @@ -473,10 +515,10 @@ TEST_F(VTEOrientationTest, ResetsFilterOnStalePredictionGap) pushValidYawSample(-0.25f); - // THEN: the stale state is dropped and the fresh sample initializes a new current fusion. + // THEN: the stale state is dropped and the fresh sample initializes the filter again. ASSERT_TRUE(_aid_sub->update()); EXPECT_EQ(_aid_sub->get().fusion_status, - static_cast(vte::FusionStatus::STATUS_FUSED_CURRENT)); + static_cast(vte::FusionStatus::STATUS_INITIALIZED)); ASSERT_TRUE(_state_sub->update()); const auto state = _state_sub->get(); diff --git a/src/modules/vision_target_estimator/test/TEST_VTEPosition.cpp b/src/modules/vision_target_estimator/test/TEST_VTEPosition.cpp index 06b2c3b020e..93eb4b399c9 100644 --- a/src/modules/vision_target_estimator/test/TEST_VTEPosition.cpp +++ b/src/modules/vision_target_estimator/test/TEST_VTEPosition.cpp @@ -1296,9 +1296,9 @@ TEST_F(VTEPositionTest, BiasAveragingUsesTimeoutWhenSamplesDoNotStabilize) EXPECT_NEAR(state.rel_pos[2], rel_pos_first(2), 0.3f); } -// WHY: If the GNSS-relative sample expires during bias averaging, vision fusion should resume immediately. +// WHY: If the GNSS-relative sample expires during bias averaging, vision must take over immediately. // WHAT: Start averaging from GNSS, let the GNSS-relative sample go stale without refreshing it, -// then verify the estimator switches to the current vision position and fuses that sample. +// then verify the estimator switches to the current vision position. TEST_F(VTEPositionTest, BiasAveragingFallsBackToVisionWhenGnssBecomesStale) { // GIVEN: mission GNSS initializes first and bias averaging is in progress. @@ -1311,6 +1311,7 @@ TEST_F(VTEPositionTest, BiasAveragingFallsBackToVisionWhenGnssBecomesStale) // Shorten the recent-measurement timeout so the 150 ms gap below unambiguously // invalidates _pos_rel_gnss _vte->setMeasRecentTimeout(100_ms); + _vte->setTargetValidTimeout(100_ms); const matrix::Vector3f vel_ned(0.4f, -0.3f, 0.1f); const hrt_abstime vel_time = vte_test::advanceMicroseconds(kStepUs); @@ -1342,12 +1343,13 @@ TEST_F(VTEPositionTest, BiasAveragingFallsBackToVisionWhenGnssBecomesStale) const hrt_abstime stale_vision_time = vte_test::advanceMicroseconds(kStepUs); setLocalVelocity(vel_ned, stale_vision_time); + setLocalPosition(kZeroVec, stale_vision_time); publishVisionPos(rel_pos, vte_test::identityQuat(), kSmallVisionCov, stale_vision_time); // WHEN: vision returns after the GNSS-relative sample has gone stale. _vte->update(matrix::Vector3f{}); - // THEN: the estimator falls back to fusing the current vision measurement immediately. + // THEN: the estimator falls back to the current vision sample as its position immediately. ASSERT_TRUE(_aid_fiducial_sub->update()); const auto aid = _aid_fiducial_sub->get(); ASSERT_TRUE(_vte_state_sub->update()); @@ -1355,9 +1357,15 @@ TEST_F(VTEPositionTest, BiasAveragingFallsBackToVisionWhenGnssBecomesStale) const float altitude_bias = (kUavAltM - kTargetAltM) - rel_pos(2); const matrix::Vector3f expected_bias(-rel_pos(0), -rel_pos(1), altitude_bias); - EXPECT_EQ(aid.fusion_status[0], static_cast(vte::FusionStatus::STATUS_FUSED_CURRENT)); - EXPECT_EQ(aid.fusion_status[1], static_cast(vte::FusionStatus::STATUS_FUSED_CURRENT)); - EXPECT_EQ(aid.fusion_status[2], static_cast(vte::FusionStatus::STATUS_FUSED_CURRENT)); + EXPECT_EQ(aid.fusion_status[0], static_cast(vte::FusionStatus::STATUS_INITIALIZED)); + EXPECT_EQ(aid.fusion_status[1], static_cast(vte::FusionStatus::STATUS_INITIALIZED)); + EXPECT_EQ(aid.fusion_status[2], static_cast(vte::FusionStatus::STATUS_INITIALIZED)); + // No other aid is fused this cycle: initialization alone must refresh validity. + EXPECT_TRUE(state.rel_pos_valid); + ASSERT_TRUE(_target_pose_sub->update()); +#if !defined(CONFIG_VTEST_MOVING) + EXPECT_TRUE(_target_pose_sub->get().rel_vel_ekf2_valid); +#endif EXPECT_NEAR(state.rel_pos[0], rel_pos(0), 0.1f); EXPECT_NEAR(state.rel_pos[1], rel_pos(1), 0.1f); EXPECT_NEAR(state.rel_pos[2], rel_pos(2), 0.1f); @@ -2287,3 +2295,65 @@ TEST_F(VTEPositionTest, TargetVelocityFusionMoving) EXPECT_NEAR(aid.observation_variance[2], kDefaultGpsVelVar, kTolerance); } #endif + +// WHY: The bias is activated from a delayed vision sample, so the position must be moved to now. +// WHAT: Initialize from vision while moving, then let GNSS arrive with an 80 ms old vision sample. +TEST_F(VTEPositionTest, BiasActivationPropagatesDelayedVisionToNow) +{ + enableMask({FusionMaskOption::kVisionPos, FusionMaskOption::kMissionPos}); + static constexpr float kSpeed = 2.f; + static constexpr hrt_abstime kLatencyUs = 80_ms; + const matrix::Vector3f vel(kSpeed, 0.f, 0.f); + const matrix::Vector3f rel_pos_t0(0.f, 0.f, kUavAltM - kTargetAltM); + const hrt_abstime t0 = vte_test::advanceMicroseconds(kStepUs); + const auto north = [t0](hrt_abstime t) { return kSpeed * static_cast(t - t0) * 1e-6f; }; + + setLocalVelocity(vel, t0); + _vte->setMissionPosition(kUavLat, kUavLon, kTargetAltM); + publishVisionPos(rel_pos_t0, vte_test::identityQuat(), kSmallVisionCov, t0); + _vte->update(kZeroVec); + ASSERT_TRUE(_vte_state_sub->update()); + flushVisionAndMissionOutputs(); + + // Vision only, flying north at 2 m/s. + hrt_abstime now = t0; + + for (int i = 0; i < 10; ++i) { + now = vte_test::advanceMicroseconds(20_ms); + setLocalVelocity(vel, now); + _vte->update(kZeroVec); + ASSERT_TRUE(_vte_state_sub->update()); + } + + // GNSS becomes available together with a vision sample captured 80 ms ago. + const hrt_abstime capture = now - kLatencyUs; + publishUavGnss(kUavLat + static_cast(north(now)) / kMetersPerDegLat, kUavLon, kUavAltM, 0.2f, 0.2f, vel, + 0.1f, true, now); + publishVisionPos(rel_pos_t0 - matrix::Vector3f(north(capture), 0.f, 0.f), vte_test::identityQuat(), + kSmallVisionCov, capture); + _vte->update(kZeroVec); + + // THEN: the bias is zero and the position is the sample moved to now, not the sample itself. + ASSERT_TRUE(_vte_state_sub->update()); + const auto state = _vte_state_sub->get(); + expectBiasNear(state, kZeroVec, 0.05f); + EXPECT_NEAR(state.rel_pos[0], -north(now), 0.05f); + // The sample became the state and is reported as such instead of being fused on top of itself. + ASSERT_TRUE(_aid_fiducial_sub->update()); + EXPECT_EQ(_aid_fiducial_sub->get().fusion_status[0], vte::FusionStatus::STATUS_INITIALIZED); + EXPECT_GT(state.cov_rel_pos[0], 0.1f); // reset to VTE_POS_UNC_IN, not shrunk to the sample variance + + // The samples still in flight replay from the activation snapshot instead of being dropped as too old. + for (int i = 0; i < 3; ++i) { + now = vte_test::advanceMicroseconds(20_ms); + const hrt_abstime late = now - kLatencyUs; + setLocalVelocity(vel, now); + publishUavGnss(kUavLat + static_cast(north(now)) / kMetersPerDegLat, kUavLon, kUavAltM, 0.2f, 0.2f, vel, + 0.1f, true, now); + publishVisionPos(rel_pos_t0 - matrix::Vector3f(north(late), 0.f, 0.f), vte_test::identityQuat(), kSmallVisionCov, + late); + _vte->update(kZeroVec); + ASSERT_TRUE(_aid_fiducial_sub->update()); + EXPECT_EQ(_aid_fiducial_sub->get().fusion_status[0], vte::FusionStatus::STATUS_FUSED_OOSM) << "cycle " << i; + } +} diff --git a/src/modules/vision_target_estimator/test/TEST_VTE_KF_position.cpp b/src/modules/vision_target_estimator/test/TEST_VTE_KF_position.cpp index 2feaa3fe8e6..878c5777539 100644 --- a/src/modules/vision_target_estimator/test/TEST_VTE_KF_position.cpp +++ b/src/modules/vision_target_estimator/test/TEST_VTE_KF_position.cpp @@ -773,3 +773,47 @@ TEST(KFPositionTest, PredictMovingTargetAddsUavInputNoise) expectSymmetric(cov); } #endif // defined(CONFIG_VTEST_MOVING) + +// WHY: A delayed position/bias reset must not advance the retained motion estimate twice. +// WHAT: Reset at capture time and bridge back to now, including target acceleration in the moving model. +TEST(KFPositionTest, DelayedPositionBiasResetPreservesCurrentMotion) +{ + vte::KF_position filter; + StateVec initial{}; + initial(vtest::State::vel_uav) = 2.f; +#if defined(CONFIG_VTEST_MOVING) + initial(vtest::State::vel_target) = 3.f; + initial(vtest::State::acc_target) = 2.f; +#endif + StateVec variance; + variance.setAll(0.5f); + setFilterState(filter, initial, variance); + filter.setInputVar(0.2f); + filter.setTargetAccVar(0.2f); + filter.predict(0.2f, 0.f); // Establish the usual motion-state correlations. + const StateVec before = filter.getState(); + const StateCov covariance_before = filter.getStateCovariance(); + constexpr float latency = 0.1f; + constexpr float position = 10.f; + float expected_position = position - before(vtest::State::vel_uav) * latency; +#if defined(CONFIG_VTEST_MOVING) + expected_position += before(vtest::State::vel_target) * latency + - 0.5f * before(vtest::State::acc_target) * latency * latency; +#endif + + filter.resetPositionAndBias(position, 1.f, 0.3f, 0.5f, latency); + filter.predict(latency, 0.f); + + EXPECT_NEAR(filter.getState()(vtest::State::pos_rel), expected_position, kTolerance); + EXPECT_NEAR(filter.getState()(vtest::State::bias), 0.3f, kTolerance); + + for (size_t i = 0; i < vte::KF_position::kStateSize; ++i) { + if ((i != vtest::State::pos_rel) && (i != vtest::State::bias)) { + EXPECT_NEAR(filter.getState()(i), before(i), kTolerance); + EXPECT_GE(filter.getStateCovariance()(i, i), covariance_before(i, i) - kTightTolerance); + } + } + + expectSymmetric(filter.getStateCovariance()); + EXPECT_GE(filter.getStateCovariance()(vtest::State::pos_rel, vtest::State::pos_rel), 1.f); +}