Repository navigation
ToleranceCompress
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 ToleranceCompress.java: the production code stays clean and the explanations live in the wiki.
package com.velitask.plugin.official.processing.compress;
import static com.velitask.plugin.official.processing.FormulaParameters.decimal;
import com.velitask.sdk.data.SensorAtom;
import com.velitask.sdk.properties.DoubleSpinnerProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.scenario.CompressStep;
import com.velitask.sdk.scenario.IStepControl;
import com.velitask.sdk.scenario.SegmentView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/* Tolerance compression: a series of points is replaced with straight segments that deviate from the original values by no more than the tolerance. */
public abstract class ToleranceCompress<A extends SensorAtom> extends CompressStep<A> {
/* Parameter name in the import plan and in the step settings JSON. */
public static final String TOLERANCE = "tolerance";
/* Tolerance in units of the sensor value. Created on the first call of parameters(). */
private DoubleSpinnerProperty mTolerance;
/* name and version are passed to CompressStep; atomClass sets the type of atoms. */
protected ToleranceCompress(String name, int version, Class<A> atomClass) {
super(name, version, atomClass);
}
/* How many components the atom has. */
protected abstract int components();
/* Reads component index. */
protected abstract double component(A atom, int index);
/* Period of an angular value; 0 - the value is not angular. */
protected double period() {
return 0;
}
/* Tolerance spinner step; subclasses pick it for the units of their value. */
protected double toleranceStep() {
return 0.1;
}
/* The tolerance parameter, default 0 (lossless). The title and description are taken by the step name. */
@Override
public IProperty[] defineParameters() {
mTolerance = decimal(TOLERANCE, localized(_KEY + "." + getName() + "." + TOLERANCE + ".title"),
localizedOrEmpty(_KEY + "." + getName() + "." + TOLERANCE + ".description"), 0);
/* Step of the value change in the spinner. */
mTolerance.setStep(toleranceStep());
return new IProperty[]{mTolerance};
}
/* Compresses one recording segment; short ones (up to two points) are returned as they are. */
@Override
protected final A[] compress(SegmentView<A> segment, IStepControl control) {
A[] atoms = segment.atoms();
int n = atoms.length;
/* Nothing can be removed from two points. */
if (n <= 2) {
return atoms;
}
parameters();
double tolerance = mTolerance.get();
double period = period();
int count = components();
/* values[c][i] - the value of component c at point i; for angles the series is unwrapped so there are no jumps across the period. */
double[][] values = new double[count][n];
for (int c = 0; c < count; c++) {
for (int i = 0; i < n; i++) {
values[c][i] = component(atoms[i], c);
if (period > 0 && i > 0) {
double step = values[c][i] - values[c][i - 1];
values[c][i] = values[c][i - 1] + step - period * Math.ceil(step / period - 0.5);
}
}
}
/* Indexes of the points that remain. The first point always remains. */
int[] kept = new int[n];
int keptCount = 0;
kept[keptCount++] = 0;
/* anchor - the anchor point of the current link, lo/hi - the "corridor" of allowed slopes for each component. */
int anchor = 0;
double[] lo = new double[count];
double[] hi = new double[count];
resetCorridor(lo, hi);
int k = 1;
/* Go forward while the slope from the anchor to point k fits in the corridor of all components (and, for angles, within 180 degrees). */
while (k < n) {
double dt = atoms[k].timeRaw - atoms[anchor].timeRaw;
boolean fits = true;
for (int c = 0; c < count && fits; c++) {
double delta = values[c][k] - values[c][anchor];
double slope = delta / dt;
if (slope < lo[c] || slope > hi[c] || period > 0 && Math.abs(delta) > period / 2) {
fits = false;
}
}
/* The point fits: the corridor narrows taking the tolerance into account, continue with the next one. */
if (fits) {
for (int c = 0; c < count; c++) {
double delta = values[c][k] - values[c][anchor];
lo[c] = Math.max(lo[c], (delta - tolerance) / dt);
hi[c] = Math.min(hi[c], (delta + tolerance) / dt);
}
k++;
} else {
/* Does not fit: the previous point becomes the new anchor and stays in the result, the corridor is reset. */
anchor = k - 1;
kept[keptCount++] = anchor;
resetCorridor(lo, hi);
}
}
/* The last point of the segment always remains. */
if (kept[keptCount - 1] != n - 1) {
kept[keptCount++] = n - 1;
}
List<A> result = new ArrayList<>(keptCount);
for (int i = 0; i < keptCount; i++) {
A head = atoms[kept[i]];
if (i + 1 < keptCount) {
for (int j = kept[i] + 1; j < kept[i + 1]; j++) {
head.add(atoms[j]);
}
/* The kept point absorbs the duration of the dropped ones; the increment is computed up to the next kept one. */
head.setDeltaTo(atoms[kept[i + 1]]);
}
result.add(head);
}
return result.toArray(Arrays.copyOf(atoms, 0));
}
/* Unbounded corridor: from minus to plus infinity. */
private void resetCorridor(double[] lo, double[] hi) {
Arrays.fill(lo, Double.NEGATIVE_INFINITY);
Arrays.fill(hi, Double.POSITIVE_INFINITY);
}
}ToleranceCompress is the abstract base of the "Tolerance compression" steps for sensors with several components. It replaces a series of points with straight segments that deviate from the original values by no more than the tolerance: the larger the tolerance, the less space the data takes; 0 is lossless compression (the step description is in the strings Plugin.ImportStep.<step name>.description). Subclasses: AccelToleranceCompress, GyroToleranceCompress, OrientToleranceCompress, AttitudeToleranceCompress.
Data. The class extends CompressStep<A>: the base class cuts the input into recording segments, calls compress for each one and checks the outcome (the first and the last atom are kept, the segment duration has not changed, the atom before a pause has zero duration). The subclass describes the atom: components(), component(atom, index), and if needed period() and toleranceStep().
Settings. One parameter tolerance — a DoubleSpinnerProperty with an initial value of 0. The title and description are taken by the step name: Plugin.ImportStep.<name>.tolerance.title and .description, so every subclass has its own units: "Tolerance, mm/s²" (acceleration), "Tolerance, °/s" (rotation), "Tolerance (0.01 ≈ 1°)" (orientation), "Tolerance, °" (angles). The spinner step toleranceStep() is 0.1 by default; the subclasses change it.
Calculation — the "slope corridor" (the "sleeve" curve compression technique):
- If the segment has no more than two points, it is returned unchanged (the parameters are not created in this case).
- A
values[c][i]array is built from the component values; for angular values (period() > 0) every value is unwrapped relative to the previous one: the difference brought to the range of half a period is added to it. - The anchor point
anchoris the first point of the segment. For every next pointkthe slopedelta / dtfrom the anchor is computed (dtis the difference of thetimeRawtimes). The point fits if the slope of every component lies in its corridor[lo; hi], and for angles the deviation from the anchor is no more than a half period. - It fits — the corridor narrows:
lo = max(lo, (delta − tolerance) / dt),hi = min(hi, (delta + tolerance) / dt). - It does not fit — the previous point
k − 1becomes the new anchor, stays in the result, and the corridor is reset. - At the end the last point of the segment is added if it is not there yet.
- Every kept point (the "head") absorbs the duration of the dropped ones after it (
head.add(...)), and its increment is recalculated up to the next kept point (setDeltaTo).
So any dropped value differs from the straight line between the kept points by no more than tolerance in every component. The values of the kept points do not change, only the increments and durations change.
- The tolerance is set for every component separately and in the units of its value; there is no common tolerance for a vector (the vector length).
- With a tolerance of 0 only the points lying exactly on the straight line from the anchor are removed; a noisy series gains nothing.
- The tolerance limits the deviation from the line, not from a "smoothed" curve; data noise is removed separately by the averaging filters (VectorAverageFilter).
- For angles a link cannot cover a change of more than 180° (the check
Math.abs(delta) > period / 2):setDeltaToof the angles interpolates along the shortest arc. - The times are taken from the
timeRawof the kept points; inside a segment they strictly increase, so there is no division by zero indelta / dt. - The segments are processed independently: the links do not cross recording pauses.