Compute the moving average in a single pass

This commit is contained in:
Roland Geider
2026-07-31 16:54:26 +02:00
parent 7b0f6eeae3
commit abd2959333
2 changed files with 60 additions and 3 deletions

View File

@@ -424,19 +424,25 @@ List<MeasurementChartEntry> moving7dAverage(List<MeasurementChartEntry> vals) {
// first make sure our list is in ascending order
vals.sort((a, b) => a.date.compareTo(b.date));
// The window total is carried along instead of re-summing the window for
// every point: with densely sampled metrics the window holds thousands of
// values, and re-adding them each time makes this quadratic
num sum = 0;
while (end < vals.length) {
sum += vals[end].value;
// since users can log measurements several days, or minutes apart,
// we can't make assumptions. We have to manually advance 'start'
// such that it is always the first point within our desired range.
// posibly start == end (when there is only one point in the range)
final intervalStart = vals[end].date.subtract(const Duration(days: 7));
while (start < end && vals[start].date.isBefore(intervalStart)) {
sum -= vals[start].value;
start++;
}
final sub = vals.sublist(start, end + 1).map((e) => e.value);
final sum = sub.reduce((val, el) => val + el);
out.add(MeasurementChartEntry(sum / sub.length, vals[end].date));
out.add(MeasurementChartEntry(sum / (end - start + 1), vals[end].date));
end++;
}

View File

@@ -234,6 +234,57 @@ void main() {
});
});
group('moving7dAverage', () {
test('returns an empty list for no entries', () {
expect(moving7dAverage([]), isEmpty);
});
test('averages over everything within the preceding 7 days', () {
final result = moving7dAverage([
entry(10, DateTime(2026, 1, 1)),
entry(20, DateTime(2026, 1, 2)),
entry(30, DateTime(2026, 1, 3)),
]);
expect(result.map((e) => e.value), [10, 15, 20]);
expect(result.map((e) => e.date), [
DateTime(2026, 1, 1),
DateTime(2026, 1, 2),
DateTime(2026, 1, 3),
]);
});
test('drops points that fell out of the window', () {
final result = moving7dAverage([
entry(10, DateTime(2026, 1, 1)),
entry(20, DateTime(2026, 1, 20)),
]);
// the january 1st entry is far outside the 7 days before january 20th
expect(result.last.value, 20);
});
test('sorts unordered input by date first', () {
final result = moving7dAverage([
entry(30, DateTime(2026, 1, 3)),
entry(10, DateTime(2026, 1, 1)),
entry(20, DateTime(2026, 1, 2)),
]);
expect(result.map((e) => e.value), [10, 15, 20]);
});
test('stays accurate over a long dense series', () {
// The window total is carried along rather than re-summed, so this
// guards against drift piling up
final result = moving7dAverage([
for (var i = 0; i < 5000; i++) entry(100, DateTime(2026, 1, 1).add(Duration(minutes: i))),
]);
expect(result.every((e) => (e.value - 100).abs() < 0.000001), isTrue);
});
});
group('downsample', () {
/// A day of heart-rate-like sampling: every 5 minutes, alternating between
/// a resting and an exerting value