Repository navigation
BadPointFilter
Up | Previous | Next | Русский
Below is the full source of the class in documentation form. The comments inside the block explain the purpose of the parts of the class, but they are not stored in the working file BadPointFilter.java: the production code stays clean and the explanations live in the wiki.
package com.velitask.plugin.official.processing.filters;
import static com.velitask.plugin.official.processing.FormulaParameters.decimal;
import static com.velitask.plugin.official.processing.FormulaParameters.flag;
import static com.velitask.plugin.official.processing.FormulaParameters.signed;
import com.velitask.sdk.data.SensorAtom;
import com.velitask.sdk.data.SensorGap;
import com.velitask.sdk.data.SensorGapReason;
import com.velitask.sdk.properties.BooleanProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DoubleSpinnerProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.Property;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.scenario.FilterStep;
import com.velitask.sdk.scenario.ImportStepKind;
import com.velitask.sdk.scenario.IStepControl;
import com.velitask.sdk.scenario.StepException;
import com.velitask.sdk.scenario.StepInput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/* Rejection of bad points: removes atoms that cannot be trusted. The concrete sensor is set by the subclasses. */
public abstract class BadPointFilter<A extends SensorAtom> extends FilterStep<A> {
/* Parameter names: they are also the keys in import plans and in the saved step settings. */
public static final String SETTLE_SEC = "settleSec";
public static final String USE_RANGE = "useRange";
public static final String MIN = "min";
public static final String MAX = "max";
public static final String USE_MARKER = "useMarker";
public static final String MAX_RATE = "maxRate";
public static final String RATE_RESET_SEC = "rateResetSec";
public static final String WINDOW_SEC = "windowSec";
public static final String DEVIATION = "deviation";
public static final String FLOOR = "floor";
/* Localization key prefix: Plugin.ImportStep.badPoint. */
private static final String KEY = _KEY + ".badPoint";
private static final String GROUP_SETTLE = "settle";
private static final String GROUP_RANGE = "range";
private static final String GROUP_RATE = "rate";
private static final String GROUP_SPIKE = "spike";
private static final double MS_PER_HOUR = 3_600_000d;
/* Cancellation is checked once per 4096 atoms, so as not to slow the loop down. */
private static final int CANCEL_CHECK_MASK = 0xFFF;
/* The parameters are created in defineParameters(); ten in total. */
private DoubleSpinnerProperty mSettleSec;
private BooleanProperty mUseRange;
private DoubleSpinnerProperty mMin;
private DoubleSpinnerProperty mMax;
private BooleanProperty mUseMarker;
private DoubleSpinnerProperty mMaxRate;
private DoubleSpinnerProperty mRateResetSec;
private DoubleSpinnerProperty mWindowSec;
private DoubleSpinnerProperty mDeviation;
private DoubleSpinnerProperty mFloor;
protected BadPointFilter(String name, int version, Class<A> atomClass) {
super(name, version, atomClass);
}
/* The sensor value in the units of the parameters (km/h, m, bpm, W, %). */
protected abstract double value(A atom);
/* The size of the change between two atoms for the jump check; by default the difference of the values. */
protected double delta(A from, A to) {
return Math.abs(value(to) - value(from));
}
/* The limits check; by default the value is outside [min, max]. Subclasses may override it. */
protected boolean outOfRange(A atom, A previous) {
double value = value(atom);
return value < mMin.get() || value > mMax.get();
}
/* The device's "no data" marker; by default there is no marker. */
protected boolean isMarker(A atom) {
return false;
}
@Override
/* The filter does not require a pause step before it and usually comes first in the scenario of a sensor. */
public ImportStepKind[] requiresBefore() {
return new ImportStepKind[0];
}
@Override
/* Ten parameters; by default all are off (0 or false). */
public IProperty[] defineParameters() {
mSettleSec = decimal(SETTLE_SEC, title(SETTLE_SEC), description(SETTLE_SEC), 0);
mUseRange = flag(USE_RANGE, title(USE_RANGE), description(USE_RANGE), false);
mMin = signed(MIN, title(MIN), description(MIN), 0);
mMax = signed(MAX, title(MAX), description(MAX), 0);
mUseMarker = flag(USE_MARKER, title(USE_MARKER), description(USE_MARKER), false);
mMaxRate = decimal(MAX_RATE, title(MAX_RATE), description(MAX_RATE), 0);
mRateResetSec = decimal(RATE_RESET_SEC, title(RATE_RESET_SEC), description(RATE_RESET_SEC), 0);
mWindowSec = decimal(WINDOW_SEC, title(WINDOW_SEC), description(WINDOW_SEC), 0);
mDeviation = decimal(DEVIATION, title(DEVIATION), description(DEVIATION), 0);
mFloor = signed(FLOOR, title(FLOOR), description(FLOOR), 0);
return new IProperty[]{mSettleSec, mUseRange, mMin, mMax, mUseMarker, mMaxRate, mRateResetSec, mWindowSec,
mDeviation, mFloor};
}
@Override
/* Distributes the parameters over four groups with the weights 10, 20, 30, 40. */
public void configureDisplay(DisplayConfig config) {
parameters();
group(config, GROUP_SETTLE, 10, mSettleSec);
group(config, GROUP_RANGE, 20, mUseRange, mMin, mMax, mUseMarker);
group(config, GROUP_RATE, 30, mMaxRate, mRateResetSec);
group(config, GROUP_SPIKE, 40, mWindowSec, mDeviation, mFloor);
}
@Override
/* One pass over the atoms: we keep only those that passed all the checks. */
protected A[] filter(StepInput<A> input, IStepControl control) throws StepException {
parameters();
A[] atoms = input.atoms();
long[] pauseEnds = pauseEnds(input.gaps());
boolean[] spikes = spikes(atoms, control);
List<A> kept = new ArrayList<>();
A last = null;
for (int i = 0; i < atoms.length; i++) {
if ((i & CANCEL_CHECK_MASK) == 0) {
control.throwIfCancelled();
}
A atom = atoms[i];
/* Any of the checks rejects the atom; the order: pause, marker, limits, jump, spike. */
if (isSettling(pauseEnds, atom.timeRaw)
|| mUseMarker.get() && isMarker(atom)
|| mUseRange.get() && outOfRange(atom, i == 0 ? null : atoms[i - 1])
|| isJump(last, atom)
|| spikes[i]) {
continue;
}
kept.add(atom);
last = atom;
}
return kept.toArray(Arrays.copyOf(atoms, 0));
}
/* The parameter title is taken from the plugin strings by the key badPoint.<name>.title. */
private String title(String name) {
return localized(KEY + "." + name + ".title");
}
private String description(String name) {
return localizedOrEmpty(KEY + "." + name + ".description");
}
/* A group is created only if the strings have its title. */
private void group(DisplayConfig config, String id, int weight, Property<?>... parameters) {
if (localizedOrEmpty(KEY + ".group." + id + ".title").isEmpty()) {
return;
}
PropertyGroup group = new PropertyGroup(id, KEY + ".group." + id + ".title", weight);
for (Property<?> parameter : parameters) {
config.set(parameter, group);
}
}
/* Ends of the pauses from the file: interval pauses and manual ones do not count. */
private long[] pauseEnds(List<SensorGap<A>> gaps) {
return gaps.stream()
.filter((gap) -> !gap.isManual()
&& gap.getReason() != SensorGapReason.INTERVAL
&& gap.getReason() != SensorGapReason.MANUAL)
.mapToLong(SensorGap::getEndTimeRaw)
.sorted()
.toArray();
}
/* Binary search for the last pause that ended no later than the atom time. */
private boolean isSettling(long[] pauseEnds, long time) {
long settleMs = (long) (mSettleSec.get() * 1000);
if (settleMs <= 0) {
return false;
}
int position = Arrays.binarySearch(pauseEnds, time);
int index = position >= 0 ? position : -position - 2;
return index >= 0 && time - pauseEnds[index] < settleMs;
}
/* Rate of change relative to the last accepted point, in units per hour. */
private boolean isJump(A last, A atom) {
double maxRate = mMaxRate.get();
if (maxRate <= 0 || last == null) {
return false;
}
long elapsedMs = atom.timeRaw - last.timeRaw;
if (elapsedMs <= 0) {
return false;
}
long resetMs = (long) (mRateResetSec.get() * 1000);
if (resetMs > 0 && elapsedMs > resetMs) {
return false;
}
return delta(last, atom) / (elapsedMs / MS_PER_HOUR) > maxRate;
}
/* A spike: the deviation from the window median is not less than the threshold; the window slides over time. */
private boolean[] spikes(A[] atoms, IStepControl control) throws StepException {
boolean[] spikes = new boolean[atoms.length];
long halfMs = (long) (mWindowSec.get() * 500);
double deviation = mDeviation.get();
if (halfMs <= 0 || deviation <= 0) {
return spikes;
}
double floor = mFloor.get();
double[] values = new double[atoms.length];
for (int i = 0; i < atoms.length; i++) {
values[i] = value(atoms[i]);
}
int low = 0;
int high = 0;
for (int i = 0; i < atoms.length; i++) {
if ((i & CANCEL_CHECK_MASK) == 0) {
control.throwIfCancelled();
}
long time = atoms[i].timeRaw;
while (atoms[low].timeRaw < time - halfMs) {
low++;
}
while (high < atoms.length && atoms[high].timeRaw <= time + halfMs) {
high++;
}
if (values[i] >= floor) {
double[] window = Arrays.copyOfRange(values, low, high);
Arrays.sort(window);
spikes[i] = Math.abs(values[i] - window[window.length / 2]) >= deviation;
}
}
return spikes;
}
}BadPointFilter<A> is the base of the "Bad ... points" family of filters: it removes from the sensor data the values that cannot be trusted: those recorded right after a pause, outside the limits, changed too sharply, or single spikes. Which checks are applied is determined by the parameters; by default all are off and the filter removes nothing.
The subclasses bind the class to a sensor atom and units: GeoBadPointFilter, HeartBadPointFilter, SpeedBadPointFilter, CyclingPowerBadPointFilter, PowerBalanceBadPointFilter, ElevationBadPointFilter, SlopeBadPointFilter. Each of them is registered in BuiltinScenarios as a separate step, and the import plans (FitImportPlan, GoproImportPlan, DjiImportPlan, DjiSrtImportPlan) put it first among the steps of the sensor and set the parameter values.
Data. The step receives the sensor atoms input.atoms() and the pauses input.gaps(). The filter declares that it needs no pause step before it (requiresBefore() returns an empty array), so in the plans it stands before the pause-by-gap step, on raw atoms. From input.gaps() only the pauses recorded in the file are taken: not manual ones and with a reason other than INTERVAL and MANUAL (that is, TIMER, SEGMENT, SIGNAL). The end of each is taken (getEndTimeRaw), the array is sorted.
Parameters. All ten are created in defineParameters() by the FormulaParameters factories: decimal (a number not less than zero, default 0), signed (a signed number, range ±10^9, default 0) and flag (a checkbox, off by default). The names come from the plugin strings (Plugin.ImportStep.badPoint.*).
| Parameter (key) | Name in the interface | Type | Group |
|---|---|---|---|
settleSec |
Settling time, s | number ≥ 0 | After a pause |
useRange |
Check the limits | checkbox | Limits |
min |
Lower limit | signed number | Limits |
max |
Upper limit | signed number | Limits |
useMarker |
Reject the "no data" marker | checkbox | Limits |
maxRate |
Rate of change limit | number ≥ 0 | Jumps |
rateResetSec |
Reset after a break, s | number ≥ 0 | Jumps |
windowSec |
Spike search window, s | number ≥ 0 | Spikes |
deviation |
Spike deviation | number ≥ 0 | Spikes |
floor |
Spike lower threshold | signed number | Spikes |
configureDisplay attaches the parameters to four PropertyGroups with the weights 10 ("After a pause"), 20 ("Limits"), 30 ("Jumps"), 40 ("Spikes"). A group is created only if the strings have its title; otherwise the parameters stay without a group.
Checks. filter goes over the atoms in order and rejects an atom if any check fires (evaluated left to right):
-
After a pause (
settleSec). An atom is rejected if it was recorded less thansettleSecseconds after the end of the nearest previous pause of the file. WithsettleSec = 0the check is off. -
Marker (
useMarker). With the checkbox on, an atom for whichisMarkeris true is rejected. The base class has no marker: only GPS overrides it. -
Limits (
useRange). With the checkbox on, an atom for whichoutOfRangeis true is rejected: by default the value is less thanminor greater thanmax. -
Jump (
maxRate). The atom is compared with the last accepted one (not with the neighbour in the original data). The rate of change isdelta(last, current) / (elapsed time in hours); if it is greater thanmaxRate, the atom is rejected. The check is skipped whenmaxRate <= 0, for the first atom, with a non-positive time interval and, ifrateResetSecis set and the interval is greater than it, after a long break. -
Spike (
windowSec,deviation,floor). Computed beforehand for all atoms: a window of±windowSec / 2seconds is taken around the value (sliding, two pointers over time), the window values are sorted, and the element with the indexsize / 2is taken (the median; for an even size, the upper of the two middle ones). An atom is a spike if its value is not less thanfloorand|value − median| >= deviation. The check is off ifwindowSecordeviationis zero.
The accepted atoms are collected into a new array, last is updated only by an accepted atom. The result is an array, as a rule, of smaller length. If the input is already laid out over segments (the filter stands after a pause), FilterStep restores the segment layout by itself.
Hooks for subclasses. value(atom) (required), delta(from, to) (by default |value(to) − value(from)|), outOfRange(atom, previous) (the value is outside [min, max]), isMarker(atom) (false by default).
- By default the filter is "empty": the parameters are off, nothing is removed. The values are set by the import plans; the user can change them in the step settings.
- The
useRangecheckbox without set limits is dangerous:min = max = 0by default, and the check will reject all values except zero. The exceptions are GPS, whose limits are hard-coded (latitude and longitude), and slope with its own condition. - The default value of
flooris 0, and the spike check is applied only to values>= floor; negative values withfloor = 0are not checked for spikes. - The units of
maxRateare "sensor units per hour", for GPS km/h; the units ofmin,max,deviation,floorare the same as in the subclassvalue(). - Spikes are searched in the original values of all atoms, including those that will be rejected by another check: the window may contain bad values.
- A jump is compared with the last accepted atom: after a real jump of position, the following points are rejected until the rate of change relative to the last accepted one falls below the threshold or
rateResetSecpasses. - The spike window assumes that the input is ordered by time (
timeRawis used). - Every window is sorted anew: large
windowSecvalues slow the import down on long recordings. Cancellation is checked once per 4096 atoms.