feat(vision_target_estimator): recheck observations during replay (#29394)

Co-authored-by: jonas <jonas.perolini@rigi.tech>
This commit is contained in:
Jonas Peroliniandjonas authored and GitHub committed 2026-10-25 10:08:22 -05:00
1 parent fcc55e4f54
commit cafa463630
16 files changed
+574 -115

No files matched your search

@@ -462,7 +462,7 @@ For deeper inspection, the following uORB topics are the most useful entry point
- `vte_orientation` provides yaw, yaw-rate, and their variances.
- `vte_input` records the downsampled NED acceleration and attitude quaternion actually fed to the position prediction step.
- `vte_bias_init_status` shows raw and filtered GNSS/vision bias while the initial averaging phase is active.
- Innovations published on `vte_aid_*` topics include the raw measurement, innovation, innovation variance, chi-squared test ratio, the `fusion_status` enum (per-axis on the 3D variant), and Out-of-Sequence Measurements ([OOSM](../advanced_features/vision_target_estimator_advanced.md#oosm-implementation)) diagnostics (`time_since_meas_ms`, `history_steps`, `replayed_count`, `replay_test_ratio_max`).
- Innovations published on `vte_aid_*` topics include the raw measurement, innovation, innovation variance, chi-squared test ratio, the `fusion_status` enum (per-axis on the 3D variant), and Out-of-Sequence Measurements ([OOSM](../advanced_features/vision_target_estimator_advanced.md#oosm-implementation)) diagnostics (`time_since_meas_ms`, `history_steps`, `replayed_count`, `replay_revised_count`, `replay_test_ratio_max`).
See [aid-source diagnostics](../advanced_features/vision_target_estimator_advanced.md#aid-source-diagnostics) for the full status table.
## Operational Notes
@@ -412,7 +412,7 @@ If the yaw state ends up oscillating, the [Orientation Filter case study](#orien
## Time Alignment
Vision and GNSS observations can arrive delayed due to transport and processing latency.
The position and orientation filters handle out-of-sequence measurements (OOSM) by replaying subsequent accepted observations in timestamp order.
The position and orientation filters handle out-of-sequence measurements (OOSM) by replaying subsequent observations in timestamp order.
For example, at 200 ms the filter fuses vision captured at 160 ms.
In the next cycle, at 220 ms, GNSS captured at 100 ms arrives.
The filter restores the state and covariance from history at or before 100 ms.
@@ -427,16 +427,16 @@ Validity and reset timeouts count from the capture time of the newest fused posi
Each filter retains up to 25 post-update snapshots of the time, state, covariance and prediction input.
At 50 Hz, 25 snapshots span 480 ms from oldest to newest.
A separate fixed-size buffer stores the accepted scalar observations, including their measurement matrix and variance.
A separate fixed-size buffer stores the gated scalar observations, accepted or rejected, with their measurement matrix, variance and latest gate decision.
It is sized for one observation per aid source and cycle: 100 per position axis (up to four sources in moving-target mode) and 25 for yaw.
For a delayed observation:
1. Find the newest snapshot at or before its capture time.
2. Predict to the capture time using the recorded control input, replaying any accepted observations along the way.
2. Predict to the capture time using the recorded control input, replaying the stored observations along the way.
3. Compute the innovation, innovation variance and NIS gate at that time.
4. If accepted, apply the ordinary scalar Kalman update.
5. Replay later predictions and accepted observations in time order, recalculating every gain from the updated covariance.
5. Replay later predictions and stored observations in time order, gating each one again and recalculating every gain from the updated covariance.
6. Replace the snapshots at or after the capture time and the live state with the replayed posteriors.
Each prediction advances the state and covariance using the transition matrix $\Phi$, control input $u$, input matrix $G$, and process noise $Q$:
@@ -459,31 +459,31 @@ $$
Replaying subsequent updates preserves their information, including their effect on position/bias cross-covariance.
Previously accepted observations remain accepted during replay: their innovation and gain are recalculated, but their original gate decisions and published diagnostic messages are not revised.
Their recalculated test ratios are logged on the delayed observations that triggered the replay (`replay_test_ratio_max`), so logs show when the revised trajectory contradicts an observation that was already fused.
Rejected observations are not retained or reconsidered.
Stored observations are gated again during replay against the replayed prior, so a decision can change in either direction.
Their published diagnostic messages are not revised.
Instead, the delayed observations that triggered the replay log how many stored observations were gated again (`replayed_count`), how many changed decision (`replay_revised_count`), and the highest test ratio among those accepted before the replay (`replay_test_ratio_max`).
If a stored observation fails during replay (invalid innovation variance), the delayed batch is discarded and history is cleared, so the failing observation cannot block later replays.
The live state is unchanged; pending and provisionally accepted delayed observations report `STATUS_REJECT_COV`, while earlier rejections keep their original status.
Fresh observations can still fuse afterwards.
The result therefore matches chronological fusion of the accepted observations at their effective fusion times; it does not promise arrival-order-independent outlier decisions.
On successful replay within the observation-log capacity, the result matches chronological fusion with the same gate, effective fusion times and equal-time order, up to float rounding, provided the required history is retained.
Prediction uses the stored piecewise-constant control inputs and current process-noise settings.
Observations less than 20 ms from the current time take the direct-update path and are recorded at the effective fusion time (now).
Within each cycle, observations are fused in effective timestamp order, preserving source priority for equal times.
Once a delayed observation is accepted, the remaining delayed observations of that cycle share its replay per axis: it stops at each of them to gate and apply it, and rewrites the later snapshots once.
Once a delayed observation is accepted or a stored gate decision changes, the remaining delayed observations of that cycle share its replay per axis: it stops at each of them to gate and apply it, and rewrites the later snapshots once.
For example, target GNSS position and velocity share a capture time, so they cost one replay instead of two.
On successful replay within the observation-log capacity, the final state and covariance match fusing them one at a time, oldest first, up to float rounding.
Replay diagnostics use this shared trajectory, so an older observation's `replay_test_ratio_max` can include the influence of later observations accepted in the same batch.
Other new batch observations are not included in `replayed_count`; it counts only previously stored observations.
Observations outside the available history or the 500 ms maximum delay are rejected.
Accepted observations older than the oldest retained posterior can be discarded because that posterior already contains their information.
Stored observations older than the oldest retained posterior are discarded: that posterior already contains the accepted ones, and their decisions can no longer change.
The buffer cannot overflow while each aid source contributes at most one observation per cycle.
If adding an observation would exceed its capacity, history restarts from the live posterior: the state is preserved, but older delayed observations are rejected until history accumulates again.
When all `B` delayed observations in a cycle are accepted, each axis requires at most `N_snapshots + N_observations + B + 1` predictions and `N_observations + B` measurement updates.
Here, `N_snapshots` counts snapshots after the floor of the oldest one (at most 24), and `N_observations` counts stored observations replayed from that floor to now.
The extra predictions advance to each delayed observation and then to now; predictions with no elapsed time are skipped.
Candidates rejected before the first acceptance are checked independently from their own floor snapshots and may replay stored observations more than once.
Until a delayed observation is accepted or a stored gate decision changes, rejected candidates are checked independently from their own floor snapshots and may replay stored observations more than once.
## Moving-target Mode (experimental)
@@ -603,7 +603,7 @@ For example plots of what a healthy and a degraded filter look like, see [Expect
- `vte_input`: downsampled acceleration in NED and the quaternion fed to each prediction step.
Can be used to correlate estimator behaviour with vehicle attitude changes.
- `vte_aid_*`: one topic per fused source (`vte_aid_gps_pos_target`, `vte_aid_gps_pos_mission`, `vte_aid_gps_vel_uav`, `vte_aid_gps_vel_target`, `vte_aid_fiducial_marker`, `vte_aid_ev_yaw`).
Each publishes the observation, observation variance, innovation, innovation variance, chi-squared `test_ratio`, the `fusion_status` outcome code (per-axis on the 3D variant), and OOSM diagnostics (`time_since_meas_ms`, `history_steps`, `replayed_count`, `replay_test_ratio_max`, `time_last_predict`).
Each publishes the observation, observation variance, innovation, innovation variance, chi-squared `test_ratio`, the `fusion_status` outcome code (per-axis on the 3D variant), and OOSM diagnostics (`time_since_meas_ms`, `history_steps`, `replayed_count`, `replay_revised_count`, `replay_test_ratio_max`, `time_last_predict`).
See [Aid-source diagnostics](#aid-source-diagnostics) for the meaning of each `fusion_status` value.
### Aid-Source Diagnostics
@@ -634,9 +634,10 @@ Additional fields make latency and replay tractable without manual timestamp ari
Negative values mean the measurement is timestamped after the latest prediction (i.e. the filter has not caught up yet).
- `history_steps` counts the retained snapshots after the capture time that were recomputed during replay (at most 24).
It is 0 for every other status, and also for `STATUS_FUSED_OOSM` when no snapshot is newer than the sample.
- `replayed_count` counts the stored observations re-applied after a delayed one, and `replay_test_ratio_max` is the highest `test_ratio` among them (-1 if none).
A value above 1 means the revised trajectory contradicts an observation that was already fused; replay keeps that observation fused.
With batching, later accepted observations in the same cycle can also influence this ratio (see [OOSM Implementation](#oosm-implementation)).
- `replayed_count` counts the stored observations gated again after a delayed one, and `replay_revised_count` how many of them changed decision.
`replay_test_ratio_max` is the highest `test_ratio` among those accepted before the replay (-1 if none).
A value above 1 means the replay rejected an observation accepted before (see [OOSM Implementation](#oosm-implementation)).
The delayed observations of one cycle share a replay, so their values can also reflect each other.
### Main Input Feeds
@@ -1175,7 +1176,7 @@ perf | grep "VTE"
These counters overlap; do not add their elapsed times to estimate CPU usage.
Reset them with `perf reset` after warmup, and use `top` to measure the `wq:vte` CPU share.
Replay cost increases with measurement delay and the number of later accepted observations (see [OOSM Implementation](#oosm-implementation)).
Replay cost increases with measurement delay and the number of later stored observations (see [OOSM Implementation](#oosm-implementation)).
Check the aid-source `fusion_status` fields alongside timing to confirm that observations are being fused.
<a id="pixhawk-6c-reference-measurements"></a>
+3 -2
View File
@@ -31,7 +31,8 @@ uint8 STATUS_INITIALIZED = 9 # Accepted as initial state; no prior innovation or
# OOSM Diagnostics
float32 time_since_meas_ms # [ms] (now - timestamp_sample)
uint8 history_steps # [-] Number of steps replayed in OOSM (0 if current or failed)
uint8 replayed_count # [-] Stored observations replayed after this one (0 if none)
float32 replay_test_ratio_max # [-] Highest test_ratio among those replayed observations (-1 if none)
uint8 replayed_count # [-] Stored observations gated again after this one (0 if none)
uint8 replay_revised_count # [-] Those whose gate decision changed (0 if none)
float32 replay_test_ratio_max # [-] Highest test_ratio among those accepted before the replay (-1 if none)
# TOPICS vte_aid_ev_yaw
+3 -2
View File
@@ -31,8 +31,9 @@ uint8 STATUS_INITIALIZED = 9 # Accepted as initial state; no prior innovation or
# OOSM Diagnostics (scalars are shared across axes)
float32 time_since_meas_ms # [ms] (now - timestamp_sample)
uint8 history_steps # [-] Number of steps replayed in OOSM (0 if current or failed)
uint8 replayed_count # [-] Stored observations replayed after this one, most on any axis (0 if none)
float32[3] replay_test_ratio_max # [-] Highest test_ratio among those replayed observations (-1 if none)
uint8 replayed_count # [-] Stored observations gated again after this one, most on any axis (0 if none)
uint8 replay_revised_count # [-] Those whose gate decision changed, most on any axis (0 if none)
float32[3] replay_test_ratio_max # [-] Highest test_ratio among those accepted before the replay (-1 if none)
# TOPICS vte_aid_gps_pos_target vte_aid_gps_pos_mission vte_aid_gps_vel_target vte_aid_gps_vel_uav
# TOPICS vte_aid_fiducial_marker
@@ -107,9 +107,9 @@ void KF_orientation::pushHistory(const uint64_t time_us)
_oosm.push(time_us, _state, _state_covariance, EmptyInput{});
}
void KF_orientation::resetHistory()
void KF_orientation::resetHistory(FusionTimes times)
{
_oosm.reset();
_oosm.reset(times);
}
FusionResult KF_orientation::fuseScalarAtTime(const ScalarMeas &meas, uint64_t now_us, float nis_threshold)
@@ -73,19 +73,21 @@ public:
float val;
float unc;
VectorState H;
FusionSource source{FusionSource::Primary};
};
void predict(float dt);
// Primary Fusion Interface (history-consistent OOSM)
// Delayed observations are fused at their timestamp and subsequent accepted observations
// are replayed in timestamp order, recomputing their Kalman gains.
// Delayed observations are fused at their timestamp and subsequent stored observations
// are replayed in timestamp order, gated again and with recomputed Kalman gains.
// Returns FusionResult describing the result for logging.
FusionResult fuseScalarAtTime(const ScalarMeas &meas, uint64_t now_us, float nis_threshold);
// History Management
void pushHistory(const uint64_t time_us);
void resetHistory();
void resetHistory(FusionTimes times = {});
FusionTimes getFusionTimes() const { return _oosm.getFusionTimes(); }
// State
void setState(const VectorState &state) { _state = state; }
@@ -138,7 +138,7 @@ void VTEOrientation::initEstimator(const VisionObs &vision_obs)
_target_est_yaw.setState(state_init);
_target_est_yaw.setStateCovarianceDiag(state_var_init);
_target_est_yaw.resetHistory();
_target_est_yaw.resetHistory({vision_obs.timestamp, 0});
PX4_DEBUG("VTE Orientation initialized with yaw: %.2f [rad]", (double)vision_obs.yaw);
@@ -259,14 +259,13 @@ void VTEOrientation::fuseMeas(const VisionObs &vision_obs)
target_innov.fusion_status = static_cast<uint8_t>(result.status);
target_innov.history_steps = result.history_steps;
target_innov.replayed_count = result.replayed_count;
target_innov.replay_revised_count = result.replay_revised_count;
target_innov.replay_test_ratio_max = result.replay_test_ratio_max;
_vte_aid_ev_yaw_pub.publish(target_innov);
// Freshness follows the capture time, so a late sample does not extend validity.
if (result.status == FusionStatus::STATUS_FUSED_CURRENT || result.status == FusionStatus::STATUS_FUSED_OOSM) {
_last_update = math::max(_last_update, vision_obs.timestamp);
}
// Replay can revise a stored sample even when the newly arrived sample is rejected.
_last_update = _target_est_yaw.getFusionTimes().last_fused;
}
void VTEOrientation::publishTarget()
@@ -94,9 +94,9 @@ void KF_position::pushHistory(const uint64_t time_us)
_oosm.push(time_us, _state, _state_covariance, _last_acc);
}
void KF_position::resetHistory()
void KF_position::resetHistory(FusionTimes times)
{
_oosm.reset();
_oosm.reset(times);
}
FusionResult KF_position::fuseScalarAtTime(const ScalarMeas &meas, uint64_t now_us, float nis_threshold)
@@ -71,13 +71,14 @@ public:
float val;
float unc;
VectorState H;
FusionSource source{FusionSource::Primary};
};
void predict(float dt, float acc_uav);
// Primary Fusion Interface (history-consistent OOSM)
// Delayed observations are fused at their timestamp and subsequent accepted observations
// are replayed in timestamp order, recomputing their Kalman gains.
// Delayed observations are fused at their timestamp and subsequent stored observations
// are replayed in timestamp order, gated again and with recomputed Kalman gains.
// Returns FusionResult describing the result for logging.
FusionResult fuseScalarAtTime(const ScalarMeas &meas, uint64_t now_us, float nis_threshold);
@@ -87,7 +88,8 @@ public:
// History Management
void pushHistory(const uint64_t time_us);
void resetHistory();
void resetHistory(FusionTimes times = {});
FusionTimes getFusionTimes() const { return _oosm.getFusionTimes(); }
// Setters / Getters
void setState(const VectorState &state) { _state = state; }
@@ -587,7 +587,7 @@ bool VTEPosition::initializeEstimator(const ObsValidMaskU &fusion_mask,
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();
_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);
@@ -843,7 +843,7 @@ void VTEPosition::activateBiasEstimate(const Vector3f &initial_position, const V
filter.setStateCovarianceDiag(state_var);
// Bias initialization is a state reset: restart OOSM history to avoid mixing pre/post-reset states.
filter.resetHistory();
filter.resetHistory(filter.getFusionTimes());
}
PX4_DEBUG("Rel pos init %.2f %.2f %.2f", (double)initial_position(vtest::Axis::x),
@@ -946,6 +946,13 @@ void VTEPosition::fuseActiveMeasurements(const matrix::Vector3f &vehicle_acc_ned
KF_position::ScalarMeas &meas_input = meas[axis_count];
meas_input = {obs.timestamp, obs.meas_xyz(axis), obs.meas_unc_xyz(axis), obs.meas_h_xyz.row(axis)};
if (obs.type == ObsType::kFiducialMarker) {
meas_input.source = FusionSource::Relative;
} else if ((obs.type == ObsType::kUavGpsVel) || (obs.type == ObsType::kTargetGpsVel)) {
meas_input.source = FusionSource::Untracked;
}
// Bias can become observable after observations were collected in this update.
// Build the GNSS model from the state being fused, including on that first cycle.
if (_bias.set && (obs.type == ObsType::kTargetGpsPos || obs.type == ObsType::kMissionGpsPos)) {
@@ -973,18 +980,19 @@ void VTEPosition::fuseActiveMeasurements(const matrix::Vector3f &vehicle_acc_ned
for (unsigned i = 0; i < count; ++i) {
const TargetObs &obs = *order[i];
if (obs.timestamp == 0 || !publishAidSource(obs, results[i])) {
continue;
if (obs.timestamp != 0) {
publishAidSource(obs, results[i]);
}
}
// Freshness follows the capture time, so a late sample does not extend validity.
if (obs.type == ObsType::kFiducialMarker) {
_last_relative_meas_fused_time = math::max(_last_relative_meas_fused_time, obs.timestamp);
}
// Replay can accept or reject older observations, so freshness can move in either direction.
_last_update = 0;
_last_relative_meas_fused_time = 0;
if ((obs.type != ObsType::kUavGpsVel) && (obs.type != ObsType::kTargetGpsVel)) {
_last_update = math::max(_last_update, obs.timestamp);
}
for (const KF_position &filter : _target_est_pos) {
const FusionTimes times = filter.getFusionTimes();
_last_update = math::max(_last_update, times.last_fused);
_last_relative_meas_fused_time = math::max(_last_relative_meas_fused_time, times.last_relative_fused);
}
}
@@ -1294,7 +1302,7 @@ bool VTEPosition::processObsGNSSPosTarget(const target_gnss_s &target_gnss, Targ
return true;
}
bool VTEPosition::publishAidSource(const TargetObs &target_obs, const FusionResult(&results)[vtest::Axis::size])
void VTEPosition::publishAidSource(const TargetObs &target_obs, const FusionResult(&results)[vtest::Axis::size])
{
vte_aid_source3d_s target_innov = {};
target_innov.timestamp_sample = target_obs.timestamp;
@@ -1303,9 +1311,9 @@ bool VTEPosition::publishAidSource(const TargetObs &target_obs, const FusionResu
target_innov.time_since_meas_ms = static_cast<float>(signedTimeDiffUs(_last_predict, target_obs.timestamp))
* kMicrosecondsToMilliseconds;
bool any_axis_fused = false;
uint8_t history_steps = 0;
uint8_t replayed_count = 0;
uint8_t replay_revised_count = 0;
for (int j = 0; j < vtest::Axis::size; j++) {
target_innov.replay_test_ratio_max[j] = -1.f;
@@ -1323,21 +1331,19 @@ bool VTEPosition::publishAidSource(const TargetObs &target_obs, const FusionResu
target_innov.test_ratio[j] = result.test_ratio;
target_innov.fusion_status[j] = static_cast<uint8_t>(result.status);
target_innov.replay_test_ratio_max[j] = result.replay_test_ratio_max;
any_axis_fused |= (result.status == FusionStatus::STATUS_FUSED_CURRENT ||
result.status == FusionStatus::STATUS_FUSED_OOSM);
if (result.status == FusionStatus::STATUS_FUSED_OOSM) {
history_steps = math::max(result.history_steps, history_steps);
replayed_count = math::max(result.replayed_count, replayed_count);
replay_revised_count = math::max(result.replay_revised_count, replay_revised_count);
}
}
target_innov.history_steps = history_steps;
target_innov.replayed_count = replayed_count;
target_innov.replay_revised_count = replay_revised_count;
publishInnov(target_innov, target_obs.type);
return any_axis_fused;
}
void VTEPosition::publishInnov(const vte_aid_source3d_s &target_innov, const ObsType type)
@@ -361,7 +361,7 @@ private:
#endif // CONFIG_VTEST_MOVING
/** Publish the per-axis fusion results of one observation. Returns true if any axis fused. */
bool publishAidSource(const TargetObs &target_obs, const FusionResult(&results)[vtest::Axis::size]);
void publishAidSource(const TargetObs &target_obs, const FusionResult(&results)[vtest::Axis::size]);
void publishTarget();
void publishInnov(const vte_aid_source3d_s &target_innov, const ObsType type);
void resetObservations();
+111 -43
View File
@@ -35,21 +35,22 @@
* @file VTEOosm.h
* @brief Generic Out-Of-Sequence Measurement (OOSM) manager for VTE filters.
*
* Keeps post-update snapshots and accepted scalar observations in fixed-size buffers.
* Keeps post-update snapshots and gated scalar observations in fixed-size buffers.
* A delayed observation is fused at its capture time, then subsequent predictions and
* accepted observations are replayed in time order with recomputed Kalman gains.
* stored observations are replayed in time order with recomputed Kalman gains.
* This preserves the information from newer observations when arrivals cross in time.
*
* For a delayed scalar observation:
* 1. Find the newest snapshot at or before its timestamp.
* 2. Predict to that time, replaying any accepted observations between the snapshot and it.
* 2. Predict to that time, replaying the stored observations between the snapshot and it.
* 3. Compute the innovation and gain, and reject the new observation if it fails the NIS gate.
* 4. Apply the ordinary Kalman correction at the observation time.
* 5. Replay later predictions and accepted observations, recomputing gains without re-gating.
* Their test ratios are only reported, as diagnostics of the new observation.
* 5. Replay later predictions and stored observations, recomputing gains and gating each one
* again, so a stored observation can change from accepted to rejected or back.
* 6. Rewrite the later snapshots in place and replace the live state. Retain the new
* observation for future replay; no extra prediction snapshot is needed. If a stored
* observation fails during replay, clear the history so it cannot block later replays.
* observation, accepted or rejected, for future replays; no extra prediction snapshot is
* needed. If a stored observation fails during replay, clear the history so it cannot
* block later replays.
*
* Delayed observations from the same cycle share one replay: it stops at each of them in turn,
* oldest first, so the window is replayed once per cycle rather than once per observation.
@@ -100,7 +101,7 @@ struct EmptyInput {};
* - void applyCorrection:
* Update (x, P) with an already-computed gain vector K.
*
* ScalarMeasT concept: default-constructible with members time_us, val, unc and H.
* ScalarMeasT concept: default-constructible with members time_us, val, unc, H and source.
*/
template <typename FilterT, int StateDim, typename InputT, int HistorySize = 25, int MaxObsPerSnapshot = 4>
class OOSMManager
@@ -121,19 +122,25 @@ public:
static_assert(MaxObsPerSnapshot > 0, "MaxObsPerSnapshot must be > 0");
static constexpr uint8_t kHistorySize = static_cast<uint8_t>(HistorySize);
// Retained observations were fused within the last HistorySize cycles, so the log
// only fills if the filter fuses more than MaxObsPerSnapshot per cycle.
// Retained observations were gated within the last HistorySize cycles, so the log
// only fills if the filter gates more than MaxObsPerSnapshot per cycle.
static constexpr size_t kMeasurementCapacity = static_cast<size_t>(MaxObsPerSnapshot) * HistorySize;
static constexpr uint64_t kOosmMinTimeUs = vision_target_estimator::kOosmMinTimeUs;
static constexpr uint64_t kOosmMaxTimeUs = vision_target_estimator::kOosmMaxTimeUs;
static_assert(kOosmMinTimeUs <= INT16_MAX, "Fast-path capture-time offset must fit in int16_t");
// Most measurements fused in one pass; a larger batch is fused in chunks of this size.
static constexpr size_t kMaxBatchSize = 8;
OOSMManager() = default;
void reset()
FusionTimes getFusionTimes() const { return _fusion_times; }
// A state reset clears freshness by default. History-only recovery passes the committed times.
void reset(FusionTimes times = {})
{
_measurement_count = 0;
_baseline_times = times;
_fusion_times = times;
if (_history.valid()) {
_history.reset();
@@ -264,9 +271,21 @@ private:
float val;
float unc;
StateVec H;
FusionSource source;
bool accepted; // Latest gate decision
// Only the fast path retimes observations: the offset is strictly less than 20 ms.
int16_t capture_offset_us;
uint64_t captureTime() const
{
return (capture_offset_us >= 0) ? time_us + static_cast<uint64_t>(capture_offset_us)
: time_us - static_cast<uint64_t>(-capture_offset_us);
}
};
StoredMeasurement _measurements[kMeasurementCapacity] {};
size_t _measurement_count{0};
FusionTimes _baseline_times{}; // Accepted observations already incorporated in the oldest snapshot.
FusionTimes _fusion_times{}; // Committed live posterior, unchanged while replay is speculative.
void pruneMeasurements()
{
@@ -277,6 +296,12 @@ private:
size_t obsolete = 0;
while (obsolete < _measurement_count && _measurements[obsolete].time_us <= _history.get_oldest().time_us) {
const StoredMeasurement &stored = _measurements[obsolete];
if (stored.accepted) {
_baseline_times.record(stored.source, stored.captureTime());
}
++obsolete;
}
@@ -293,13 +318,13 @@ private:
template <typename ScalarMeasT>
void rememberMeasurement(const ScalarMeasT &meas, uint64_t effective_time, uint64_t now_us,
const StateVec &state, const StateCov &cov, const InputT &input)
const StateVec &state, const StateCov &cov, const InputT &input, bool accepted)
{
pruneMeasurements();
if (_measurement_count == kMeasurementCapacity) {
// Restart from the live posterior rather than drop an update a later replay needs.
reset();
reset(_fusion_times);
push(now_us, state, cov, input);
return;
}
@@ -311,17 +336,20 @@ private:
--pos;
}
_measurements[pos] = {effective_time, meas.val, meas.unc, meas.H};
_measurements[pos] = {effective_time, meas.val, meas.unc, meas.H, meas.source, accepted,
static_cast<int16_t>(signedTimeDiffUs(meas.time_us, effective_time))
};
++_measurement_count;
}
// Replay position: the posterior at time_us, with the stored observations before
// measurement_pos either applied or already contained in the starting snapshot.
// Replay position: posterior at time_us, with stored observations before measurement_pos replayed
// or in the starting snapshot. changed marks a replay that differs from history and must be committed.
struct ReplayCursor {
StateVec state;
StateCov cov;
uint64_t time_us;
size_t measurement_pos;
bool changed;
};
// Fast path: the measurement is effectively current.
@@ -344,7 +372,7 @@ private:
// Live time moved backwards or jumped too far forward relative to history: wipe and recover.
if (now_us < newest_time_us || (now_us - newest_time_us) > kOosmMaxTimeUs) {
reset();
reset(_fusion_times);
res.status = FusionStatus::STATUS_REJECT_STALE;
return false;
}
@@ -370,11 +398,16 @@ private:
{
StateVec K;
// The fast path treats near-current samples as observations at now. Rejected ones are kept
// too, so a later replay can gate them again.
if (processMeasurement(filter, curr_state, curr_cov, meas, nis_threshold, res, K)) {
filter.applyCorrection(curr_state, curr_cov, K, res.innov, res.innov_var);
res.status = FusionStatus::STATUS_FUSED_CURRENT;
// The fast path treats near-current samples as observations at now.
rememberMeasurement(meas, now_us, now_us, curr_state, curr_cov, curr_input);
_fusion_times.record(meas.source, meas.time_us);
rememberMeasurement(meas, now_us, now_us, curr_state, curr_cov, curr_input, true);
} else if (res.status == FusionStatus::STATUS_REJECT_NIS) {
rememberMeasurement(meas, now_us, now_us, curr_state, curr_cov, curr_input, false);
}
}
@@ -398,8 +431,8 @@ private:
return (idx != _history.get_newest_index()) ? _history[_history.next(idx)].input : curr_input;
}
// Fuse the sorted delayed measurements in one replay. Until one is accepted, each starts from its
// own floor and history stays untouched; after that, history is rewritten in place.
// Fuse the sorted delayed measurements in one replay. Until something changes (an accepted measurement
// or a revised decision), each starts from its own floor; after that, history is rewritten in place.
template <typename ScalarMeasT>
void replayBatch(FilterT &filter, const ScalarMeasT *meas, const uint8_t *order, size_t count, uint64_t now_us,
float nis_threshold, StateVec &curr_state, StateCov &curr_cov, const InputT &curr_input,
@@ -409,13 +442,12 @@ private:
ReplayCursor cursor{};
uint8_t idx = 0;
size_t k = 0;
bool accepted = false;
bool ok = true;
while (ok && ((k < count) || (accepted && (idx != newest_idx)))) {
while (ok && ((k < count) || (cursor.changed && (idx != newest_idx)))) {
// Recompute later posteriors rather than subtract an old correction from a newer one.
// A snapshot at a measurement's time is rewritten after that measurement.
if (accepted && (idx != newest_idx)
if (cursor.changed && (idx != newest_idx)
&& ((k == count) || (_history[_history.next(idx)].time_us < meas[order[k]].time_us))) {
idx = _history.next(idx);
Sample &sample = _history[idx];
@@ -440,20 +472,19 @@ private:
continue;
}
if (!accepted) {
if (!cursor.changed) {
idx = floorIndex(meas[order[k]].time_us);
cursor = {_history[idx].state, _history[idx].cov, _history[idx].time_us, 0};
cursor = {_history[idx].state, _history[idx].cov, _history[idx].time_us, 0, false};
}
ok = fuseDelayed(filter, meas, order, k, inputAfter(idx, curr_input), nis_threshold, idx, cursor, results);
if (ok) {
accepted = accepted || (results[order[k]].status == FusionStatus::STATUS_FUSED_OOSM);
++k;
}
}
if (ok && accepted) {
if (ok && cursor.changed) {
ok = replayStored<ScalarMeasT>(filter, now_us, curr_input, nis_threshold, cursor, order, count, results);
}
@@ -462,17 +493,37 @@ private:
return;
}
if (!accepted) {
return;
if (cursor.changed) {
predictTo(filter, now_us, curr_input, cursor);
curr_state = cursor.state;
curr_cov = cursor.cov;
}
predictTo(filter, now_us, curr_input, cursor);
curr_state = cursor.state;
curr_cov = cursor.cov;
// Rebuild freshness from the decisions that survived replay, including rejected-to-accepted
// transitions. Capture times are distinct from the fast path's effective fusion time.
_fusion_times = _baseline_times;
for (size_t j = 0; j < _measurement_count; ++j) {
const StoredMeasurement &stored = _measurements[j];
if (stored.accepted) {
_fusion_times.record(stored.source, stored.captureTime());
}
}
// Commit all new timestamps before insertion can restart a full observation log.
for (size_t j = 0; j < count; ++j) {
if (results[order[j]].status == FusionStatus::STATUS_FUSED_OOSM) {
rememberMeasurement(meas[order[j]], meas[order[j]].time_us, now_us, curr_state, curr_cov, curr_input);
_fusion_times.record(meas[order[j]].source, meas[order[j]].time_us);
}
}
for (size_t j = 0; j < count; ++j) {
const uint8_t status = results[order[j]].status;
if ((status == FusionStatus::STATUS_FUSED_OOSM) || (status == FusionStatus::STATUS_REJECT_NIS)) {
rememberMeasurement(meas[order[j]], meas[order[j]].time_us, now_us, curr_state, curr_cov, curr_input,
status == FusionStatus::STATUS_FUSED_OOSM);
}
}
}
@@ -498,6 +549,7 @@ private:
filter.applyCorrection(at_meas.state, at_meas.cov, K, res.innov, res.innov_var);
res.status = FusionStatus::STATUS_FUSED_OOSM;
cursor = at_meas;
cursor.changed = true;
// Update an existing snapshot at this time. Between snapshots, the observation log
// retains this correction for future replays without consuming a history slot.
@@ -514,7 +566,7 @@ private:
// Delayed measurements not already rejected on their own report the failure.
void failBatch(const uint8_t *order, size_t count, size_t processed, FusionResult *results)
{
reset();
reset(_fusion_times);
for (size_t j = 0; j < count; ++j) {
FusionResult &res = results[order[j]];
@@ -523,13 +575,14 @@ private:
res.status = FusionStatus::STATUS_REJECT_COV;
res.history_steps = 0;
res.replayed_count = 0;
res.replay_revised_count = 0;
res.replay_test_ratio_max = -1.f;
}
}
}
// Apply the stored observations up to end_time with their original decisions and fresh gains, without
// the final prediction. Each counts for the diagnostics of the fused delayed order[0..fused_count).
// Gate and apply the stored observations up to end_time, without the final prediction. A revised
// decision marks the replay as changed; each counts for the fused delayed order[0..fused_count).
template <typename ScalarMeasT>
bool replayStored(FilterT &filter, uint64_t end_time, const InputT &input, float nis_threshold,
ReplayCursor &cursor, const uint8_t *order, size_t fused_count, FusionResult *results)
@@ -537,7 +590,7 @@ private:
const uint64_t start_time = cursor.time_us;
while (cursor.measurement_pos < _measurement_count) {
const StoredMeasurement &stored = _measurements[cursor.measurement_pos];
StoredMeasurement &stored = _measurements[cursor.measurement_pos];
if (stored.time_us <= start_time) {
++cursor.measurement_pos;
@@ -556,13 +609,13 @@ private:
meas.H = stored.H;
StateVec K;
FusionResult result{};
const bool accepted = processMeasurement(filter, cursor.state, cursor.cov, meas, nis_threshold, result, K);
if (!processMeasurement(filter, cursor.state, cursor.cov, meas, 0.f, result, K)) {
if (!accepted && (result.status != FusionStatus::STATUS_REJECT_NIS)) {
return false;
}
const float test_ratio = (nis_threshold > 0.f)
? (result.innov * result.innov) / (result.innov_var * nis_threshold) : -1.f;
const bool revised = (accepted != stored.accepted);
for (size_t j = 0; j < fused_count; ++j) {
FusionResult &res = results[order[j]];
@@ -572,11 +625,26 @@ private:
++res.replayed_count;
}
res.replay_test_ratio_max = fmaxf(res.replay_test_ratio_max, test_ratio);
if (revised && (res.replay_revised_count < UINT8_MAX)) {
++res.replay_revised_count;
}
// Only previously accepted observations: above 1 means one was rejected now.
if (stored.accepted) {
res.replay_test_ratio_max = fmaxf(res.replay_test_ratio_max, result.test_ratio);
}
}
}
filter.applyCorrection(cursor.state, cursor.cov, K, result.innov, result.innov_var);
if (revised) {
stored.accepted = accepted;
cursor.changed = true;
}
if (accepted) {
filter.applyCorrection(cursor.state, cursor.cov, K, result.innov, result.innov_var);
}
++cursor.measurement_pos;
}
+22 -2
View File
@@ -116,14 +116,34 @@ inline hrt_abstime nowUs()
return TimeSourceProvider::nowUs();
}
// Velocity aiding must not refresh position validity; relative position also backs EKF2 aiding.
enum class FusionSource : uint8_t { Primary, Relative, Untracked };
struct FusionTimes {
uint64_t last_fused{0};
uint64_t last_relative_fused{0};
void record(FusionSource source, uint64_t capture_time)
{
if (source != FusionSource::Untracked && capture_time > last_fused) {
last_fused = capture_time;
}
if (source == FusionSource::Relative && capture_time > last_relative_fused) {
last_relative_fused = capture_time;
}
}
};
struct FusionResult {
uint8_t status{FusionStatus::STATUS_IDLE};
float innov{0.f};
float innov_var{0.f};
float test_ratio{-1.f}; // Normalized NIS (beta / threshold)
uint8_t history_steps{0};
uint8_t replayed_count{0}; // Stored observations replayed after this one
float replay_test_ratio_max{-1.f}; // Highest test ratio among them, -1 if none
uint8_t replayed_count{0}; // Stored observations gated again after this one
uint8_t replay_revised_count{0}; // Those whose gate decision changed
float replay_test_ratio_max{-1.f}; // Highest test ratio among those accepted before, -1 if none
};
static inline bool hasTimedOutAt(const hrt_abstime now, const hrt_abstime ts, const hrt_abstime timeout_us)
@@ -43,6 +43,7 @@
#include <algorithm>
#include <cmath>
#include <random>
#include <vector>
#include "VTEOosm.h"
@@ -90,6 +91,7 @@ struct ScalarMeas {
float val{0.f};
float unc{0.f};
matrix::Vector<float, kStateDim> H{};
vte::FusionSource source{vte::FusionSource::Primary};
};
struct ScalarMeas2 {
@@ -97,6 +99,7 @@ struct ScalarMeas2 {
float val{0.f};
float unc{0.f};
StateVec2 H{};
vte::FusionSource source{vte::FusionSource::Primary};
};
class TestFilter
@@ -381,10 +384,12 @@ TEST_F(VTEOosmTest, MeasurementCapacityRestartsHistoryFromLivePosterior)
EXPECT_NEAR(cov, 4.f / (1.f + 4.f * measurement_count), kTolerance);
EXPECT_EQ(Access::historyEntries(oosm), 1);
EXPECT_EQ(Access::historyOldestTime(oosm), now);
EXPECT_EQ(oosm.getFusionTimes().last_fused, now);
EXPECT_EQ(fuseMeas(makeMeas(1020_ms, 0.f, 1.f), now, 0.f).status,
vte::FusionStatus::STATUS_REJECT_TOO_OLD);
oosm.reset();
EXPECT_EQ(oosm.getFusionTimes().last_fused, 0u);
pushSample(now, state, cov, curr_input);
const float variance_before = cov;
ASSERT_EQ(fuseMeas(makeMeas(now, 0.f, 1.f), now + 30_ms, 0.f).status,
@@ -392,6 +397,41 @@ TEST_F(VTEOosmTest, MeasurementCapacityRestartsHistoryFromLivePosterior)
EXPECT_NEAR(cov, variance_before / (variance_before + 1.f) + 0.003f, kTolerance);
}
// Once an accepted observation leaves the replay window, its capture time remains the
// freshness baseline; an unrelated velocity update must not replace it.
TEST_F(VTEOosmTest, RetainsFreshnessAfterObservationIsPruned)
{
using Access = vte::OOSMManagerTestAccess<Manager>;
constexpr uint64_t start = 1_s;
constexpr uint64_t step = 20_ms;
pushSample(start, state, cov, curr_input);
for (int cycle = 1; cycle <= Manager::kHistorySize; ++cycle) {
const uint64_t now = start + cycle * step;
cov += 0.002f;
if (cycle == 1) {
ScalarMeas relative = makeMeas(now - 5_ms, 0.f, 0.1f);
relative.source = vte::FusionSource::Relative;
ASSERT_EQ(fuseMeas(relative, now, 10.f).status, vte::FusionStatus::STATUS_FUSED_CURRENT);
}
pushSample(now, state, cov, curr_input);
}
ASSERT_EQ(Access::historyOldestTime(oosm), start + step);
ScalarMeas velocity = makeMeas(start + step + 10_ms, 0.f, 0.1f);
velocity.source = vte::FusionSource::Untracked;
ASSERT_EQ(fuseMeas(velocity, start + Manager::kHistorySize * step, 10.f).status,
vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(oosm.getFusionTimes().last_fused, start + step - 5_ms);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, start + step - 5_ms);
oosm.reset();
EXPECT_EQ(oosm.getFusionTimes().last_fused, 0u);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, 0u);
}
// A log sized for one observation per snapshot must hold one fused observation per cycle
// indefinitely, so the orientation filter never restarts its history in steady state.
TEST_F(VTEOosmTest, OneObservationPerCycleFitsMeasurementCapacity)
@@ -1120,8 +1160,9 @@ TEST_F(VTEOosmTest, RejectsNisDuringOosmPrediction)
EXPECT_EQ(filter.applied_k.size(), 0u);
}
// Replay keeps earlier decisions, but the late observation reports how strongly the stored ones now disagree.
TEST_F(VTEOosmTest, ReportsReplayedObservationsAfterDelayedSample)
// A late observation that contradicts stored ones gets them rejected on replay, as if all had arrived
// in time order, and reports how many decisions changed and how strongly the stored ones now disagree.
TEST_F(VTEOosmTest, RegatesStoredObservationsAfterDelayedSample)
{
constexpr uint64_t start = 1_s;
constexpr uint64_t step = 20_ms;
@@ -1136,13 +1177,18 @@ TEST_F(VTEOosmTest, ReportsReplayedObservationsAfterDelayedSample)
filter.predictState(step * 1e-6f, curr_input, x, P, x, P);
state = x(0);
cov = P(0, 0);
ASSERT_EQ(fuseMeas(makeMeas(now - 5_ms, 0.f, 0.01f), now, kThreshold).status,
ScalarMeas relative = makeMeas(now - 5_ms, 0.f, 0.01f);
relative.source = vte::FusionSource::Relative;
ASSERT_EQ(fuseMeas(relative, now, kThreshold).status,
vte::FusionStatus::STATUS_FUSED_CURRENT);
x = makeVec(state);
P = makeCov(cov);
oosm.push(now, x, P, curr_input);
}
EXPECT_EQ(oosm.getFusionTimes().last_fused, start + 2 * step - 5_ms);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, start + 2 * step - 5_ms);
// A late observation passes its own gate but contradicts both stored ones.
const uint64_t now = start + 3 * step;
filter.predictState(step * 1e-6f, curr_input, x, P, x, P);
@@ -1154,38 +1200,184 @@ TEST_F(VTEOosmTest, ReportsReplayedObservationsAfterDelayedSample)
ASSERT_EQ(res.status, vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(res.replayed_count, 2);
EXPECT_EQ(filter.applied_k.size() - corrections_before, 3u);
EXPECT_EQ(res.replay_revised_count, 2);
EXPECT_EQ(filter.applied_k.size() - corrections_before, 1u);
EXPECT_EQ(oosm.getFusionTimes().last_fused, late.time_us);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, 0u);
// Chronological fusion with the same gate.
TestFilter truth_filter;
auto x_truth = makeVec(0.f);
auto P_truth = makeCov(4.f);
float max_ratio = -1.f;
const auto fuse_truth = [&](const ScalarMeas & m, bool replayed) {
const auto gate_truth = [&](const ScalarMeas & m) {
float innov = 0.f;
float innov_var = 0.f;
truth_filter.computeInnovation(x_truth, P_truth, m, innov, innov_var);
const float ratio = innov * innov / (innov_var * kThreshold);
if (replayed) {
max_ratio = fmaxf(max_ratio, innov * innov / (innov_var * kThreshold));
if (ratio <= 1.f) {
truth_filter.applyCorrection(x_truth, P_truth, (P_truth * m.H) / innov_var, innov, innov_var);
}
const auto K = (P_truth * m.H) / innov_var;
truth_filter.applyCorrection(x_truth, P_truth, K, innov, innov_var);
return ratio;
};
truth_filter.predictState(0.01f, curr_input, x_truth, P_truth, x_truth, P_truth);
fuse_truth(late, false);
gate_truth(late);
truth_filter.predictState(0.01f, curr_input, x_truth, P_truth, x_truth, P_truth);
fuse_truth(makeMeas(start + step, 0.f, 0.01f), true);
const float ratio_1 = gate_truth(makeMeas(start + step, 0.f, 0.01f));
truth_filter.predictState(0.02f, curr_input, x_truth, P_truth, x_truth, P_truth);
fuse_truth(makeMeas(start + 2 * step, 0.f, 0.01f), true);
const float ratio_2 = gate_truth(makeMeas(start + 2 * step, 0.f, 0.01f));
truth_filter.predictState(0.02f, curr_input, x_truth, P_truth, x_truth, P_truth);
EXPECT_GT(max_ratio, 1.f);
EXPECT_GT(ratio_1, 1.f);
EXPECT_GT(ratio_2, 1.f);
const float max_ratio = fmaxf(ratio_1, ratio_2);
EXPECT_NEAR(res.replay_test_ratio_max, max_ratio, 1e-3f * max_ratio);
EXPECT_NEAR(state, x_truth(0), kTolerance);
EXPECT_NEAR(cov, P_truth(0, 0), kTolerance);
}
// With the gate repeated on replay, the arrival order does not matter: delayed observations,
// outliers included, give the same state as fusing them in time order with the same gate.
TEST_F(VTEOosmTest, ResultDoesNotDependOnArrivalOrder)
{
using LongManager = vte::OOSMManager<TestFilter, kStateDim, float, 25>;
constexpr uint64_t t0 = 1_s;
constexpr uint64_t step = 20_ms;
constexpr float input = 0.5f;
constexpr float kThreshold = 10.f;
constexpr int kObsCount = 10;
constexpr int kCycles = 22;
std::mt19937 rng(1234);
const auto uniform = [&rng](float lo, float hi) { return lo + (hi - lo) * static_cast<float>(rng() / 4294967296.0); };
int revised_total = 0;
struct Arrival {
ScalarMeas meas;
uint64_t time_us;
};
for (int trial = 0; trial < 200; ++trial) {
Arrival arrivals[kObsCount];
// Capture within 20-200 ms after t0, arrival 20-200 ms later; every fifth one is an outlier.
for (int i = 0; i < kObsCount; ++i) {
const uint64_t capture = t0 + 20_ms + static_cast<uint64_t>(uniform(0.f, 180000.f));
const float value = (i % 5 == 0) ? ((uniform(0.f, 1.f) < 0.5f) ? 3.f : -3.f) : uniform(-0.15f, 0.15f);
arrivals[i] = {makeMeas(capture, value, 0.05f), capture + 20_ms + static_cast<uint64_t>(uniform(0.f, 180000.f))};
}
LongManager run{};
TestFilter run_filter{};
auto x = makeVec(0.f);
auto P = makeCov(1.f);
run.push(t0, x, P, input);
uint64_t now = t0;
for (int cycle = 1; cycle <= kCycles; ++cycle) {
now = t0 + cycle * step;
run_filter.predictState(step * 1e-6f, input, x, P, x, P);
ScalarMeas batch[kObsCount];
vte::FusionResult res[kObsCount];
size_t count = 0;
for (const Arrival &arrival : arrivals) {
if ((arrival.time_us > now - step) && (arrival.time_us <= now)) {
batch[count++] = arrival.meas;
}
}
run.fuseBatch(run_filter, batch, count, now, kThreshold, x, P, input, res);
for (size_t i = 0; i < count; ++i) {
ASSERT_TRUE((res[i].status == vte::FusionStatus::STATUS_FUSED_OOSM)
|| (res[i].status == vte::FusionStatus::STATUS_REJECT_NIS)) << "trial " << trial;
revised_total += res[i].replay_revised_count;
}
run.push(now, x, P, input);
}
std::sort(arrivals, arrivals + kObsCount, [](const Arrival & a, const Arrival & b) { return a.meas.time_us < b.meas.time_us; });
TestFilter truth_filter;
auto x_truth = makeVec(0.f);
auto P_truth = makeCov(1.f);
uint64_t truth_time = t0;
for (const Arrival &arrival : arrivals) {
truth_filter.predictState((arrival.meas.time_us - truth_time) * 1e-6f, input, x_truth, P_truth, x_truth, P_truth);
truth_time = arrival.meas.time_us;
float innov = 0.f;
float innov_var = 0.f;
truth_filter.computeInnovation(x_truth, P_truth, arrival.meas, innov, innov_var);
if (innov * innov <= kThreshold * innov_var) {
truth_filter.applyCorrection(x_truth, P_truth, (P_truth * arrival.meas.H) / innov_var, innov, innov_var);
}
}
truth_filter.predictState((now - truth_time) * 1e-6f, input, x_truth, P_truth, x_truth, P_truth);
EXPECT_NEAR(x(0), x_truth(0), kTolerance) << "trial " << trial;
EXPECT_NEAR(P(0, 0), P_truth(0, 0), kTolerance) << "trial " << trial;
}
// Some arrival orders changed decisions that a gate frozen at arrival would have kept.
EXPECT_GT(revised_total, 0);
}
// A decision revised on the way to a rejected late sample still reaches the live state.
TEST_F(VTEOosmTest, CommitsRevisedDecisionBeforeRejectedSample)
{
constexpr uint64_t t0 = 1_s;
constexpr uint64_t now = t0 + 40_ms;
pushSample(t0, 0.f, 1.f, 0.f);
pushSample(t0 + 20_ms, 0.f, 1.002f, 0.f);
cov = 1.004f;
// Accepted with a wide gate (test ratio about 0.03).
ASSERT_EQ(fuseMeas(makeMeas(t0 + 5_ms, 0.6f, 0.05f), now, 10.f).status, vte::FusionStatus::STATUS_FUSED_OOSM);
ASSERT_GT(state, 0.5f);
// With a narrower gate, the stored observation is rejected on the way to the late outlier.
const vte::FusionResult res = fuseMeas(makeMeas(t0 + 10_ms, 50.f, 0.05f), now, 0.1f);
EXPECT_EQ(res.status, vte::FusionStatus::STATUS_REJECT_NIS);
EXPECT_NEAR(state, 0.f, kTolerance);
EXPECT_NEAR(cov, 1.004f, kTolerance);
}
// A fast-path observation rejected on arrival is kept, so a later replay can accept it.
TEST_F(VTEOosmTest, RegatesRejectedFastPathObservation)
{
constexpr uint64_t t0 = 1_s;
constexpr uint64_t t1 = t0 + 20_ms;
constexpr uint64_t now = t1 + 20_ms;
pushSample(t0, 0.f, 0.01f, 0.f);
cov = 0.012f;
ScalarMeas relative = makeMeas(t1 - 5_ms, 1.f, 0.01f);
relative.source = vte::FusionSource::Relative;
ASSERT_EQ(fuseMeas(relative, t1, 10.f).status, vte::FusionStatus::STATUS_REJECT_NIS);
EXPECT_EQ(oosm.getFusionTimes().last_fused, 0u);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, 0u);
pushSample(t1, state, cov, 0.f);
cov += 0.002f;
// A wider gate on the next replay accepts it.
const vte::FusionResult res = fuseMeas(makeMeas(t0 + 5_ms, 0.f, 0.01f), now, 100.f);
ASSERT_EQ(res.status, vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(res.replayed_count, 1);
EXPECT_EQ(res.replay_revised_count, 1);
EXPECT_FLOAT_EQ(res.replay_test_ratio_max, -1.f);
EXPECT_GT(state, 0.3f);
EXPECT_EQ(oosm.getFusionTimes().last_fused, relative.time_us);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, relative.time_us);
ScalarMeas velocity = makeMeas(now, state, 0.1f);
velocity.source = vte::FusionSource::Untracked;
ASSERT_EQ(fuseMeas(velocity, now, 100.f).status, vte::FusionStatus::STATUS_FUSED_CURRENT);
EXPECT_EQ(oosm.getFusionTimes().last_fused, relative.time_us);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, relative.time_us);
}
// A stored observation that fails during replay must not stay in the log and block every later replay.
TEST_F(VTEOosmTest, ClearsHistoryWhenReplayFails)
{
@@ -1288,10 +1480,12 @@ TEST_F(VTEOosmTest, RewritesWrappedHistoryInPlace)
EXPECT_FLOAT_EQ(sample.input, before[i].input);
}
// Same gate as the outlier, which is stored and stays rejected on replay.
const ScalarMeas meas = makeMeas(t_meas, 0.5f, 0.1f);
const vte::FusionResult res = fuseMeas(meas, now, 0.f);
const vte::FusionResult res = fuseMeas(meas, now, 1.f);
ASSERT_EQ(res.status, vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(res.history_steps, Manager::kHistorySize - 3);
EXPECT_EQ(res.replay_revised_count, 0);
TestFilter truth_filter;
auto x_truth = makeVec(before[2].state(0));
@@ -1426,6 +1620,64 @@ TEST_F(VTEOosmTest, BatchMatchesSequentialFusion)
EXPECT_FLOAT_EQ(batch.P(0, 0), seq.P(0, 0));
}
// Sequential fusion stores the rejected outlier, so the later sample's replay splits its prediction
// there while the batch does not: the two then match up to float rounding.
TEST_F(VTEOosmTest, BatchMatchesSequentialFusionAcrossRejectedSample)
{
using Access = vte::OOSMManagerTestAccess<Manager>;
constexpr uint64_t t0 = 1_s;
constexpr uint64_t step = 20_ms;
constexpr uint64_t now = t0 + 4 * step;
constexpr float input = 0.5f;
constexpr float kThreshold = 10.f;
Manager seq{};
auto x = makeVec(0.f);
auto P = makeCov(1.f);
oosm.push(t0, x, P, input);
seq.push(t0, x, P, input);
for (int i = 1; i < 4; ++i) {
filter.predictState(step * 1e-6f, input, x, P, x, P);
oosm.push(t0 + i * step, x, P, input);
seq.push(t0 + i * step, x, P, input);
}
filter.predictState(step * 1e-6f, input, x, P, x, P);
auto x_seq = x;
auto P_seq = P;
// The outlier lies between the second sample and its floor at t0 + step.
const ScalarMeas batch_meas[] {makeMeas(t0 + step + 11_ms, 0.03f, 0.05f), makeMeas(t0 + step + 3_ms, 50.f, 0.05f),
makeMeas(t0 + 7_ms, 0.01f, 0.05f)
};
vte::FusionResult batch_res[3];
oosm.fuseBatch(filter, batch_meas, 3, now, kThreshold, x, P, input, batch_res);
vte::FusionResult seq_res[3];
for (int i : {2, 1, 0}) {
seq_res[i] = seq.fuse(filter, batch_meas[i], now, kThreshold, x_seq, P_seq, input);
}
const uint8_t expected_status[] {vte::FusionStatus::STATUS_FUSED_OOSM, vte::FusionStatus::STATUS_REJECT_NIS,
vte::FusionStatus::STATUS_FUSED_OOSM
};
for (int i = 0; i < 3; ++i) {
EXPECT_EQ(batch_res[i].status, expected_status[i]) << "measurement " << i;
EXPECT_EQ(seq_res[i].status, expected_status[i]) << "measurement " << i;
EXPECT_NEAR(batch_res[i].innov, seq_res[i].innov, 1e-5f) << "measurement " << i;
}
EXPECT_NEAR(x(0), x_seq(0), 1e-5f);
EXPECT_NEAR(P(0, 0), P_seq(0, 0), 1e-5f);
for (int i = 0; i < 4; ++i) {
EXPECT_NEAR(Access::historySample(oosm, i).state(0), Access::historySample(seq, i).state(0), 1e-5f);
EXPECT_NEAR(Access::historySample(oosm, i).cov(0, 0), Access::historySample(seq, i).cov(0, 0), 1e-5f);
}
}
// A stored observation that fails during a batch replay rejects the delayed samples and clears
// history, while fresh samples of the same cycle still fuse.
TEST_F(VTEOosmTest, BatchReplayFailureKeepsFreshSamples)
@@ -1462,9 +1714,14 @@ TEST_F(VTEOosmTest, BatchReplayFailureBeforeGate)
cov = 1.004f;
const uint64_t now = 1040_ms;
ASSERT_EQ(fuseMeas(makeMeas(1005_ms, 0.f, 0.1f), now, 0.f).status, vte::FusionStatus::STATUS_FUSED_OOSM);
ScalarMeas relative = makeMeas(1003_ms, 0.5f, 0.1f);
relative.source = vte::FusionSource::Relative;
ASSERT_EQ(fuseMeas(relative, now, 0.01f).status, vte::FusionStatus::STATUS_REJECT_NIS);
ASSERT_EQ(oosm.getFusionTimes().last_relative_fused, 0u);
// Replaying the stored observation now fails.
// Replay provisionally accepts the relative observation, then fails on the next one.
filter.fail_time = 1005_ms;
const size_t corrections_before = filter.applied_k.size();
auto x = makeVec(state);
auto P = makeCov(cov);
const ScalarMeas meas[] {makeMeas(1002_ms, 50.f, 0.01f), makeMeas(1010_ms, 0.f, 0.1f)};
@@ -1474,8 +1731,11 @@ TEST_F(VTEOosmTest, BatchReplayFailureBeforeGate)
EXPECT_EQ(res[0].status, vte::FusionStatus::STATUS_REJECT_NIS);
EXPECT_EQ(res[1].status, vte::FusionStatus::STATUS_REJECT_COV);
EXPECT_EQ(Access::historyEntries(oosm), 0);
EXPECT_EQ(filter.applied_k.size() - corrections_before, 1u);
EXPECT_FLOAT_EQ(x(0), state);
EXPECT_FLOAT_EQ(P(0, 0), cov);
EXPECT_EQ(oosm.getFusionTimes().last_fused, 1005_ms);
EXPECT_EQ(oosm.getFusionTimes().last_relative_fused, 0u);
}
// More measurements than one pass handles are fused in chunks, and delayed ones still land at their
@@ -384,6 +384,49 @@ TEST_F(VTEOrientationTest, FusesOosmYawMeasurement)
EXPECT_GT(aid.history_steps, 0u);
}
// Validity follows the newest observation still accepted after replay, in either direction.
TEST_F(VTEOrientationTest, RevisedYawDecisionsUpdateFreshness)
{
enableVisionFusion();
setParamFloat("VTE_YAW_NIS_THRE", kPermissiveNis);
_vte->updateParamsPublic();
const hrt_abstime t0 = pushValidYawSample(0.f);
const hrt_abstime recent_time = vte_test::advanceMicroseconds(20_ms);
publishVisionYaw(0.6f, kMeasVar, recent_time);
_vte->update();
ASSERT_TRUE(_aid_sub->update());
ASSERT_EQ(_aid_sub->get().fusion_status, vte::FusionStatus::STATUS_FUSED_CURRENT);
// Replaying from an older sample with a narrower gate removes the recent yaw update.
setParamFloat("VTE_YAW_NIS_THRE", kRestrictiveNis);
_vte->updateParamsPublic();
_vte->setTargetValidTimeout(30_ms);
vte_test::advanceMicroseconds(20_ms);
publishVisionYaw(0.f, kMeasVar, t0 + 5_ms);
_vte->update();
ASSERT_TRUE(_aid_sub->update());
ASSERT_EQ(_aid_sub->get().fusion_status, vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(_aid_sub->get().replay_revised_count, 1);
ASSERT_TRUE(_state_sub->update());
EXPECT_FALSE(_state_sub->get().orientation_valid);
// A subsequent replay accepts that same stored observation, restoring its capture-time credit.
setParamFloat("VTE_YAW_NIS_THRE", kPermissiveNis);
_vte->updateParamsPublic();
_vte->setTargetValidTimeout(45_ms);
_vte->setVteTimeout(45_ms);
vte_test::advanceMicroseconds(20_ms);
publishVisionYaw(0.f, kMeasVar, t0 + 10_ms);
_vte->update();
ASSERT_TRUE(_aid_sub->update());
ASSERT_EQ(_aid_sub->get().fusion_status, vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_EQ(_aid_sub->get().replay_revised_count, 1);
ASSERT_TRUE(_state_sub->update());
EXPECT_TRUE(_state_sub->get().orientation_valid);
EXPECT_FALSE(_vte->timedOut());
}
// Clock-sync jitter can stamp yaw slightly in the future: such samples are fused as current,
// while samples further ahead are dropped.
TEST_F(VTEOrientationTest, AlignsYawStampedSlightlyInTheFuture)
@@ -1991,6 +1991,62 @@ TEST_F(VTEPositionTest, GpsOnlyRelativeVelocityDoesNotEnableEkf2Aiding)
EXPECT_FALSE(pose.rel_vel_ekf2_valid);
}
// Removing the latest vision correction during GNSS replay must also remove its freshness credit.
TEST_F(VTEPositionTest, RevisedVisionDecisionUpdatesFreshness)
{
enableMask({FusionMaskOption::kVisionPos, FusionMaskOption::kMissionPos});
setParamFloat("VTE_BIA_AVG_TOUT", 0.f);
setParamFloat("VTE_POS_NIS_THRE", kPermissiveNisThreshold);
_vte->updateParamsPublic();
_vte->setMeasRecentTimeout(35_ms);
_vte->setVteTimeout(25_ms);
const hrt_abstime t0 = vte_test::advanceMicroseconds(kStepUs);
const matrix::Vector3f initial_pos(0.f, 0.f, kUavAltM - kTargetAltM);
setLocalVelocity(kZeroVec, t0);
setLocalPosition(kZeroVec, t0);
_vte->setMissionPosition(kUavLat, kUavLon, kTargetAltM);
publishNominalUavGnss(kZeroVec, t0);
publishVisionPos(initial_pos, vte_test::identityQuat(), kSmallVisionCov, t0);
_vte->update(kZeroVec);
ASSERT_TRUE(_target_pose_sub->update());
const hrt_abstime vision_time = vte_test::advanceMicroseconds(20_ms);
publishVisionPos(initial_pos + matrix::Vector3f(0.6f, 0.6f, 0.6f), vte_test::identityQuat(), kSmallVisionCov,
vision_time);
_vte->update(kZeroVec);
ASSERT_TRUE(_aid_fiducial_sub->update());
ASSERT_TRUE(_target_pose_sub->update());
for (int axis = 0; axis < 3; ++axis) {
ASSERT_EQ(_aid_fiducial_sub->get().fusion_status[axis], vte::FusionStatus::STATUS_FUSED_CURRENT);
}
#if !defined(CONFIG_VTEST_MOVING)
EXPECT_TRUE(_target_pose_sub->get().rel_vel_ekf2_valid);
#endif
// The older GNSS sample is accepted, but the narrower gate removes the stored vision update.
setParamFloat("VTE_POS_NIS_THRE", kRestrictiveNisThreshold);
_vte->updateParamsPublic();
vte_test::advanceMicroseconds(20_ms);
publishNominalUavGnss(kZeroVec, t0 + 10_ms);
_vte->update(kZeroVec);
ASSERT_TRUE(_aid_gps_mission_sub->update());
ASSERT_TRUE(_target_pose_sub->update());
for (int axis = 0; axis < 3; ++axis) {
EXPECT_EQ(_aid_gps_mission_sub->get().fusion_status[axis], vte::FusionStatus::STATUS_FUSED_OOSM);
EXPECT_GT(_aid_gps_mission_sub->get().replay_test_ratio_max[axis], 1.f);
}
EXPECT_EQ(_aid_gps_mission_sub->get().replay_revised_count, 1);
EXPECT_TRUE(_target_pose_sub->get().rel_pos_valid);
EXPECT_FALSE(_target_pose_sub->get().rel_vel_ekf2_valid);
// The newest accepted position sample is now GNSS at t0 + 10 ms, not vision at t0 + 20 ms.
EXPECT_TRUE(_vte->timedOut());
}
// WHY: GNSS time misalignment should increase measurement variance.
// WHAT: Publish delayed UAV GPS and verify propagation uncertainty is included.
TEST_F(VTEPositionTest, TargetGpsInterpolationVariance)