Repository navigation
feat(profile): 7-day moving-average overlay on the weight-trend chart (#1119) - #1197
simonoppowa merged 2 commits into
Conversation
… chart The primary line lands on every recorded reading, so a daily weigh-in that swings a kilogram either way with water alone is exactly what the chart shows — hard to see the week-over-week direction the user actually cares about (simonoppowa#1119). Adds a trailing-window rolling mean as a second, dashed line on the same chart. Default window is 7 calendar days: on any reading, the smoothed point is the mean of every entry in the last week including the reading itself. The line lags real changes by about half the window and hides day-to-day noise, which is the whole point. - `lib/core/utils/calc/weight_moving_average.dart` — a pure calc unit, same shape as the other `core/utils/calc/*` helpers. Two-pointer sweep so a long log stays O(n) rather than O(n·window). Anchors on entry dates so the smoothed line lines up with the raw dots, drops leading points that had fewer than `minSamples` readings in-window (the line starts once the smoothing is real), and counts every entry that falls in each window — including two on the same day. - `weight_trend_chart.dart` gains an optional `movingAverageWindowDays` parameter (default 7, null hides the overlay). The MA is computed against the *full* log and then clipped to the visible window, so the leftmost visible point is anchored on entries predating the window instead of lagging one window-length behind. Rendered as a dashed 1.5 px line at 55 % of the primary colour, no dots, two lines with ≥ 2 spots or none at all so a two-entry log does not sprout a stub. Two callers pick up the overlay for free — `weight_history_screen.dart` and `trends_page.dart` — because both build the shared chart widget with no `movingAverageWindowDays` override. Tests: - `test/unit_test/weight_moving_average_test.dart` (7 cases): consecutive daily readings land the arithmetic mean; readings outside the window are excluded; two entries on the same day fold into every window that day is in; unsorted input is sorted before computing; empty log produces no points; `windowDays` honoured on a shorter window; `minSamples` gate keeps the line from starting on a single reading. - `test/features/profile/presentation/widgets/weight_trend_chart_moving_average_test.dart` (3 cases): a 10-day log renders the primary line as before plus a dashed dot-less MA line that stays inside the raw envelope; passing `movingAverageWindowDays: null` renders only the primary line; a two-entry log a month apart never crosses the smoothing threshold and renders no MA line either. Closes simonoppowa#1119.
simonoppowa
left a comment
There was a problem hiding this comment.
The maths is right on the inputs I hand-built: the window is [t-6d, t] (an entry exactly seven days before the anchor is excluded, six days before is included — the Jan 3/4/10 log gives sampleCount 2, mean 85), unsorted input sorts, same-day entries both count, the sweep is linear (200k daily entries in ~300 ms), and the lbs overlay goes through the same _toChartY as the dots (176.5 lb for a 80.04 kg mean). Both callers pass the full log (weight_history_screen.dart:81, trends_bloc.dart:49), so the compute-then-clip claim holds: with six 82 kg readings just before a 30-day window the leftmost MA point lands at x=0 with those readings folded in. One thing before merging, a one-liner; a second one-liner worth taking while you are in the helper; plus a test gap.
lib/features/profile/presentation/widgets/weight_trend_chart.dart:117-118 — minY/maxY are still reduced over the raw spots only, and the MA is now the one series that can sit outside that range, because its leftmost points carry pre-window readings. LineChartData keeps the default FlClipData.none(), so an MA spot above maxY paints outside the plot. On the Trends 7d chip this needs nothing exotic: last week at 81.5–82.0, this week flat at 80.0–80.5 — the water swing the issue is about — gives maxY 81.0 (80.5 plus the 0.5 padding floor) and MA spots at 81.53 / 81.33 / 81.11 for x = 0..2, so three of the seven points sit above the chart and the dashed line runs up through the card header, 35 % of the plot height past the top edge. I rendered it in both themes and it is exactly that. The 30-day default is not immune either: six 82 kg readings just before the window over a flat 80.x month puts the first MA spot at 81.74 against a maxY of 80.7. Folding maSpots into the reduce ([...spots, ...maSpots]) clears it and the PR's tests still pass with that change. Worth a widget test with pre-window entries that asserts the first MA spot is at x=0: with .compute(entries) at :107 swapped for .compute(inWindow) the three widget tests still pass 3/3, so nothing currently pins the compute-on-the-full-log behaviour either.
lib/core/utils/calc/weight_moving_average.dart:65 — anchorDate.subtract(Duration(days: windowDays - 1)) is 144 wall-clock hours, not six calendar days, while :36 documents the window in calendar days. Every entry is local midnight (all four write sites build DateTime(y, m, d), and the box is keyed by yyyy-MM-dd), so when an autumn DST transition sits inside the window, windowStart lands at 01:00 and the entry on that day is dropped. Under TZ=Europe/Berlin with daily entries Oct 21–27 2026, the Oct 27 point has sampleCount 6 instead of 7; the same happens for the six anchors after any fall-back transition. Spring-forward is harmless (windowStart lands at 23:00 the day before). The visible effect is small — six points a year averaging 6 readings instead of 7, or one missing MA point on a sparse log — so this is not blocking on its own, but it is a one-liner: DateTime(anchorDate.year, anchorDate.month, anchorDate.day - (windowDays - 1)) — the shape trends_page.dart:150 already uses — gives 7 and the seven existing helper tests still pass. A test at the exact boundary (Jan 3 excluded, Jan 4 included for a Jan 10 anchor) and one across a fall-back date would pin both; the current "outside the window" test uses 9 and 6 days, so the edge itself is untested. The chart's own windowStart at :62 has the same subtract and the same x-shift via .difference().inDays, but that is on develop already, and the MA points go through the same formula so they stay aligned with the dots — not this PR's to fix.
Small comment mismatches: weight_trend_chart_moving_average_test.dart:11 says the MA line is drawn behind the raw line while weight_trend_chart.dart:220 says it renders second and sits on top (the code is the latter); weight_moving_average_test.dart:119 says Jan 1 is nine days out of the Jan 7 anchor's window — it is six; and "stays O(n)" at weight_moving_average.dart:60 describes the sweep, the call is O(n log n) because of the sort at :53, which is fine but not what the comment or the description says.
Verified otherwise: the diff is the two source files plus the two tests, no pubspec.lock, generated, or ARB changes; the commit message is clean; fl_chart is pinned at 1.2.0 and dashArray / dotData / preventCurveOverShooting on LineChartBarData are all there; analyze is clean; the PR's 24 (7 helper + 17 profile) pass, trends_calc and trends_bloc pass, and the full suite is 2250 passed, 1 skipped against develop's 2240 / 1. The 55 % primary reads at 3.9:1 over the dark surface and 2.5:1 over the light one with the default green — legible in both, a little faint in light mode, and it inherits whatever contrast the chosen accent has. Same-day duplicates cannot come out of the store (one key per day), so that branch of the helper is harmless but unreachable. The new hunks are not formatted per the pinned SDK (the .where( at :108 and about 17 lines of the helper), the same drift as 303 other files; CI does not check it.
Scope calls for you: #1119 asked for a choice of 3/10-day or EMA, and the PR ships a fixed 7-day trailing mean behind a public parameter with no picker; and the chart now carries two dashed lines (target in outline grey, MA in 55 % primary) with no legend or label, so a user has no in-app way to learn what the second line is. Neither blocks the maths.
…clock arithmetic Follow-up on the simonoppowa#1197 review: - The moving average is the one series whose leftmost points fold in readings that predate the visible window, so on a "last week high, this week flat" log its y can sit above the raw envelope — Simon's 81.5–82.0 → 80.0–80.5 case. `LineChartData` keeps the default `FlClipData.none()`, so an MA spot above `maxY` painted outside the plot; a "dashed line running up through the card header" in the 7d Trends chip. Fold `maSpots` into the min/max reduce so the y-range covers every rendered spot. A new widget test seeds the exact shape Simon reproduced and pins `data.maxY >= max(maSpots)` and `data.minY <= min(maSpots)`. - `Duration(days: windowDays - 1)` is 144 wall-clock hours, not six calendar days: on a fall-back DST day it lands the window boundary an hour after local midnight and drops that day's entry. Every entry in this log is `DateTime(y, m, d)` at local midnight (see the four write sites), so building the boundary through DateTime's year/month/day constructor keeps it aligned. A boundary test at the exact edge (Jan 3 out, Jan 4 in for a Jan 10 anchor with a 7-day window) pins the calendar-day intent. - Comment fixes flagged in the review: `weight_trend_chart.dart:220` correctly says the MA is rendered second and paints on top of the raw line, so the test-file header now says the same; the calc's sweep comment names the O(n log n) sort separately from the O(n) sweep; and `weight_moving_average_test.dart`'s "9 days out of the anchor" comment is rewritten to describe the window geometry (Jan 4..Jan 10) directly. Refs simonoppowa#1197.
|
Both blocking items and the three comment nits in 88281b2:
On the scope calls:
Analyze clean on the four touched files; 12/12 pass locally across the two test files. No |
simonoppowa
left a comment
There was a problem hiding this comment.
Verified on 88281b2 in a fresh worktree at the PR head.
y-range: the 7d seed reproduces — raw 80.0/80.5, MA spots 81.50 / 81.29 / 81.07 / 80.86 / 80.64 / 80.43 / 80.21, data.minY 79.5, data.maxY 82.0, first MA spot at x=0. Reverting the reduce to spots only drops maxY to 81.0 and the new widget test fails on maxY >= 81.5; swapping .compute(entries) for .compute(inWindow) fails its sanity assertion (MA max 80.25 vs raw max 80.5), so the compute-on-the-full-log behaviour is pinned now as well.
Calendar-day boundary: under TZ=Europe/Berlin with daily entries Oct 21–27 2026 the Oct 27 point has sampleCount 7 (the Duration boundary would have been Oct 21 01:00, and putting the subtract back gives 6). One correction to the reply, though: the Jan 3/4/10 boundary test does not go red when the helper is reverted to Duration(days: windowDays - 1) — it passes 8/8 under both UTC and Europe/Berlin, because no transition sits inside a January window. Only a fall-back-crossing test catches the revert, and that is the second test the review asked for that is still missing; CI runs in UTC with no TZ set, so it would need TZ=Europe/Berlin on the test step (or a skip when the zone has no Oct 25 transition) to guard anything on CI rather than only on a dev machine. Not blocking, same as before.
Comments: the test-file header and the sort/sweep complexity comment are right now. weight_moving_average_test.dart:139 is not — it says [Jan 4..Jan 10], but that is the 3-day-window test on a Jan 7 anchor whose window is [Jan 5..Jan 7] (line 136 says so); the nit got swapped for a different wrong comment. Also :126 of the widget test says windowDays "defaults to 7 in this test" when it is passed explicitly at :144. Both one-liners; either push a fixup or I patch them on merge.
Alignment after the helper change: measured with a 200-day window from today under TZ=Australia/Sydney so the Apr 5 fall-back sits inside the chart window. The chart's own windowStart at :62 lands at 01:00 — the Mar 1 entry is dropped, there is an x-gap after 34, and the pre-transition dots sit one step left of their labels — all develop behaviour, not this PR's — but every one of the 199 MA spots still lands on the dot for the same date, because :95 and :112 share the chart's windowStart and the helper's boundary only decides which readings fold into the y. I'll open a follow-up issue for the :62 subtract.
Gates: analyze clean; the PR's two files 12/12; full suite 2252 passed, 1 skipped (2250/1 on c76408b plus the two new tests); diff is still the four files, no pubspec.lock/generated/ARB changes, no trailers; CI green on 88281b2 (linux-checks analyze + tests, android-build, android-integration-tests; iOS and release jobs skipped by the changes gate).
Approving. The 3/10/EMA picker and the MA legend are accepted as separate PRs against #1119.
|
The chart's own window-start subtract is filed as #1207 (pre-existing on develop, not this PR's). |
Resolves the conflict with the moving-average overlay (#1197) in weight_trend_chart.dart: keep both the overlay's field and the test clock. The overlay placed its points with difference(windowStart).inDays, the 24-hour-span arithmetic this branch replaces, so after a spring-forward each point landed one day left of its dot. Route it through dayIndex like the raw series. The chart tests read lineBarsData.single, which the overlay's second series breaks; read the raw series as .first, and assert that the overlay's x values are the tail of the raw ones.
…hour spans (#1222) * fix(profile): window the weight-trend chart by calendar days, not 24-hour spans The chart built its window start as `today.subtract(Duration(days: windowDays - 1))` and its x-values as `date.difference(windowStart) .inDays`. Both measure elapsed hours, while every weight entry sits at local midnight, so a DST transition inside the window put the boundary an hour off midnight and the day count one short. Measured under TZ=Europe/Berlin with the new widget test (today pinned to 2025-11-10, 30-day window, one entry per day): - fall-back inside the window: 29 dots drawn for 30 days; the entry on the window-start day (Oct 12) was dropped, and every dot from Oct 13 through Oct 26 sat one x step left of its label. - spring-forward inside the window (today 2026-04-10): the x=0 label read "Mar 11" for the Mar 12 window start, since the boundary landed at 23:00 the evening before. Keeping `.difference().inDays` with only the window start corrected fails the spring-forward case differently: the Mar 30 dot lands on x=17, on top of Mar 29, because 18 calendar days measure 18*24 - 1 hours. The window start now uses the y/m/d constructor (the form trends_page and #1197's moving-average helper already use), x is a calendar-day difference via the new CalendarDayCalc.daysBetween (both dates rebuilt in UTC, where a day is always 24 hours), and the date labels come from DateUtils.addDaysToDate on the same start, so dots and labels cannot drift apart. The "All" range in the weight-history screen and the Trends bloc counted its span with the same `.inDays`, one short across a spring-forward, so the oldest entry fell outside the window it was meant to define; both now use the helper. The Trends bloc's existing "All" fixtures built "N days ago" with `today.subtract(Duration)` off the real clock. Under the old arithmetic two off-by-ones cancelled on every date; under the calendar count the 50-day fixture reads 52 for the expected 51 on the 50 days after a spring-forward (replayed for every day of 2026 under TZ=Europe/Berlin: 3/30 through 5/18). Both fixtures now use the y/m/d constructor, like the app's write sites. Dart's DateTime knows only the process zone and UTC, so the DST cases cannot be forced from the data. The widget and unit tests pin the clock to dates around Europe/Berlin's transitions and skip, with a reason, when the process zone has no transition on that date (CI runs UTC); the zone-independent window test runs everywhere. Closes #1207 * ci: rerun the #1207 DST tests under Europe/Berlin so they execute somewhere automated The calendar-day tests for the weight-trend chart pin dates around Europe/Berlin's transitions and skip, with a reason, when the process zone has no transition there. `just test` sets no zone and the runners are UTC, so all four DST cases skipped on every CI run: with the chart arithmetic reverted to the Duration/.inDays forms, `TZ=UTC flutter test` on the widget test still passed (+1 ~2) while the same code under TZ=Europe/Berlin failed (+5 -2: 29 dots for 30 days, 'Mar 11' for the Mar 12 window start). A regression of the fix went green. A `just test_dst` recipe reruns just the two files under TZ=Europe/Berlin (Dart's DateTime can only see the process zone, so the zone has to come from the environment), and the linux-checks job runs it after `just test`. Rerunning the two files rather than moving the whole suite into a DST zone keeps the other clock-reading tests in the UTC they have always run in and isolates a red DST run to one small step. Under Berlin the pair reports +7; `just test` keeps reporting the four skips, whose reason now names the recipe. `just ci` runs it too.
Closes #1119.
Problem
Daily weigh-ins swing a kilogram or two on water alone. The chart lands one dot on every reading, so what a weight-tracker actually wants to see — the week-over-week direction — is buried under noise from readings taken a few hours apart.
Change
Adds a trailing-window rolling mean as a second dashed line on the shared
WeightTrendChart. Default window: 7 calendar days. On any reading, the smoothed point is the mean of every entry within the last week including the reading itself; the line lags real changes by about half the window and hides day-to-day noise, which is the whole point.lib/core/utils/calc/weight_moving_average.dart(new) — a pure calc unit, same shape as the othercore/utils/calc/*helpers. Two-pointer sweep so a long log stays O(n) rather than O(n·window). Anchors on entry dates so the smoothed line lines up with the raw dots. Counts every entry that falls in each window — two on the same day both count. Drops leading points backed by fewer thanminSamples(default 2) readings so the line starts once the smoothing is real, not with a single-sample "average" that traces the raw line.lib/features/profile/presentation/widgets/weight_trend_chart.dart— gains an optionalmovingAverageWindowDaysparameter (default7,nullhides the overlay). The MA is computed against the full log and then clipped to the visible window, so the leftmost visible point is anchored on entries predating the window instead of lagging one window-length behind. Rendered as a dashed 1.5 px line at 55 % of the primary colour, no dots. Only drawn when there are ≥ 2 spots so a two-entry log does not sprout a stub.Two callers pick up the overlay for free with no changes —
weight_history_screen.dartandtrends_page.dart— because both build the shared chart with nomovingAverageWindowDaysoverride.Design notes
Tests
test/unit_test/weight_moving_average_test.dart(7 cases): consecutive daily readings land the arithmetic mean; readings outside the trailing window are excluded; two entries on the same day fold into every window that day is in; unsorted input is sorted before computing; an empty log produces no points;windowDaysis honoured on a shorter (3-day) window;minSamplesgate keeps a leading single-sample point from being emitted.test/features/profile/presentation/widgets/weight_trend_chart_moving_average_test.dart(3 cases): a 10-day log renders the primary line unchanged plus a dashed, dot-less MA line whose points stay inside the raw envelope; passingmovingAverageWindowDays: nullcollapses the chart back to a single line; a two-entry log a month apart never crosses the smoothing threshold and renders no MA line either — no line stub, no fake trend.Scope
Two source files, two test files. No pubspec/generated/l10n/config changes. No new setting or picker — the overlay is always on when there is enough data. Both call sites (
weight_history_screen.dart,trends_page.dart) pick up the default with no override.Verified
flutter analyzeclean on the touched files.flutter test test/unit_test/weight_moving_average_test.dart test/features/profile/— 24/24 pass locally, no regression in the existingweight_history_screen_test.dartorprofile_page_weight_test.dart.movingAverageWindowDays: nullreduceslineBarsDatato one entry — pinned by a widget test — so a caller that wants the pre-[Feature]: Moving Averages for Weight Tracking #1119 shape has one flag to flip.