diff --git a/README.md b/README.md index 948db32..9bd1bd3 100644 --- a/README.md +++ b/README.md @@ -52,9 +52,11 @@ Runs and walks are credited by ONE rule, whatever the TCX sport or the `_Walking` file-name suffix (RunnerUp's files and the workout app's alike): a day's activities are summed, and the day counts once their distance reaches 3.5 km (5% GPS tolerance) OR their *moving* time reaches the shared duration -bar (30 min minus the hidden leeway). Moving time is the trackpoint pairs -seen within 30 s of each other and travelled at 0.5 m/s or more, so pauses, -standing still and GPS dropouts earn nothing. The reward is the usual one +bar (30 min minus the hidden leeway). Both are summed over trackpoint pairs +seen within 30 s of each other and travelled at no more than 25 km/h (faster +is a vehicle or a GPS jump: no time, no distance); moving time also needs +0.5 m/s or more. Pauses, standing still, dropouts and files without +trackpoints earn nothing (the lap totals are never used). The reward is the usual one workout credit per day (`runnerup_verified:`); the log's `activity` field is display only. Code: `screen_locker/_walk_tcx.py`. diff --git a/screen_locker/_constants.py b/screen_locker/_constants.py index bc592d0..7eaacb4 100644 --- a/screen_locker/_constants.py +++ b/screen_locker/_constants.py @@ -110,8 +110,11 @@ GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json" # reaches MIN_RUN_DISTANCE_KM OR their summed MOVING time reaches # WORKOUT_DURATION_ACCEPT_MINUTES. Moving = trackpoint pairs seen within # WALK_MAX_GAP_SECONDS and travelled at least this fast (slower is standing -# still). There is no upper speed: a run must count. The Dart app mirrors it. +# still). A pair faster than MAX_MOVING_SPEED_MPS (25 km/h, the app's running +# jump filter) is a vehicle or a GPS jump and counts neither moving time NOR +# distance, for every activity. The Dart app mirrors the bounds. MIN_MOVING_SPEED_MPS = 0.5 +MAX_MOVING_SPEED_MPS = 25 / 3.6 WALK_MAX_GAP_SECONDS = 30 # Workout records this PC must keep deleted in the sync store, pushed as # tombstones on every tick (see _sync_tombstones for why once is not enough). diff --git a/screen_locker/_walk_tcx.py b/screen_locker/_walk_tcx.py index 6ff69ff..fb6fe22 100644 --- a/screen_locker/_walk_tcx.py +++ b/screen_locker/_walk_tcx.py @@ -23,7 +23,13 @@ consecutive trackpoint pairs travelled at least at ``MIN_MOVING_SPEED_MPS``: standing still is too slow. A pair further apart than ``WALK_MAX_GAP_SECONDS`` is a GPS dropout whose motion is unknown and earns nothing -- an activity is never credited for time nobody saw, so a pause cannot buy a run its duration. -There is no upper speed: a run is faster than a walk and must still count. +A pair faster than ``MAX_MOVING_SPEED_MPS`` (25 km/h) is a vehicle or a GPS +jump: it counts neither moving time nor distance, so a bus ride earns nothing. +The day's distance is the sum of the surviving pairs (``track_distance_m``), +never the lap's ``DistanceMeters`` total, and an export with no trackpoints +cannot be speed-checked, so it credits nothing. Only the root-DB fallback, +which has no trackpoints at all, is judged by its recorded distance and +duration. """ from __future__ import annotations @@ -35,6 +41,7 @@ import logging from typing import TYPE_CHECKING, Any from screen_locker._constants import ( + MAX_MOVING_SPEED_MPS, MIN_MOVING_SPEED_MPS, MIN_RUN_DISTANCE_KM, MIN_WORKOUT_DURATION_MINUTES, @@ -94,16 +101,30 @@ def _trackpoints(activity: ET.Element) -> list[tuple[float, float]]: def track_summary(activity: ET.Element) -> dict[str, Any]: - """Moving seconds and end time of one activity, from its trackpoints.""" + """Moving seconds, credited distance and end time, from the trackpoints. + + A pair counts when its points are within ``WALK_MAX_GAP_SECONDS`` and it + was not travelled faster than ``MAX_MOVING_SPEED_MPS``. It then adds its + metres to ``track_distance_m``, and its seconds to ``moving_seconds`` too + when it was travelled at least at ``MIN_MOVING_SPEED_MPS``. + """ points = _trackpoints(activity) moving = 0.0 + metres = 0.0 for (t0, d0), (t1, d1) in itertools.pairwise(points): gap = t1 - t0 - if 0 < gap <= WALK_MAX_GAP_SECONDS and (d1 - d0) / gap >= MIN_MOVING_SPEED_MPS: + if not 0 < gap <= WALK_MAX_GAP_SECONDS: + continue + speed = (d1 - d0) / gap + if speed > MAX_MOVING_SPEED_MPS: + continue + metres += max(d1 - d0, 0.0) + if speed >= MIN_MOVING_SPEED_MPS: moving += gap return { "activity_id": activity.findtext(f"{_TCX_NS}Id") or "", "moving_seconds": moving, + "track_distance_m": metres, "ended_at": points[-1][0] if points else None, } @@ -118,6 +139,11 @@ def moving_qualifies(moving_minutes: float) -> bool: return moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES +def _distance_metres(activity: dict[str, Any]) -> float: + """Credited metres; the root-DB path has no trackpoints, so its total stands in.""" + return float(activity.get("track_distance_m", activity.get("distance_m", 0.0))) + + def _moving_seconds(activity: dict[str, Any]) -> float: """Moving seconds; the root-DB path has no trackpoints, so wall-clock stands in.""" return float(activity.get("moving_seconds", activity.get("duration_seconds", 0.0))) @@ -188,7 +214,7 @@ def activity_day(activities: Iterable[dict[str, Any]]) -> ActivityDay: completed_at: float | None = None for activity in ordered: moving += _moving_seconds(activity) - metres += float(activity.get("distance_m", 0.0)) + metres += _distance_metres(activity) if completed_at is None and ( moving_qualifies(moving / 60) or distance_qualifies(metres / 1000) ): diff --git a/screen_locker/tests/_activity_helpers.py b/screen_locker/tests/_activity_helpers.py index acd236f..fbf1a4c 100644 --- a/screen_locker/tests/_activity_helpers.py +++ b/screen_locker/tests/_activity_helpers.py @@ -76,3 +76,21 @@ def verify(verifier: Verifier) -> tuple[str, str] | None: """The file-based verdict for the test day.""" with patch("screen_locker._runnerup_verification.today_str", return_value=DAY): return verifier._verify_runnerup_via_files() + + +def tcx_points(sport: str, start: str, points: list[tuple[int, float]]) -> str: + """An export whose track is exactly ``(seconds after start, cumulative metres)``.""" + begin = datetime.fromisoformat(f"{DAY}T{start}:00+00:00") + body = "".join( + f"" + f"{m:.1f}" + for s, m in points + ) + return ( + f'' + f'{DAY}T{start}' + f"{points[-1][0]}" + f"{points[-1][1]}" + f"{body}" + "" + ) diff --git a/screen_locker/tests/test_runnerup_webdav_source.py b/screen_locker/tests/test_runnerup_webdav_source.py index 7360c1a..9757c30 100644 --- a/screen_locker/tests/test_runnerup_webdav_source.py +++ b/screen_locker/tests/test_runnerup_webdav_source.py @@ -12,25 +12,14 @@ from __future__ import annotations from typing import TYPE_CHECKING from unittest.mock import MagicMock, patch +from screen_locker.tests._activity_helpers import tcx from screen_locker.tests.conftest import create_locker if TYPE_CHECKING: from pathlib import Path -_TCX = """\ - - - - - - 4200.0 - 5800.0 - - - - -""" +# A 5.8 km / 70 min run WITH its trackpoints: lap totals alone credit nothing. +_TCX = tcx("Running", "18:58", moving_min=70, metres=5800) def _webdav_tree(tmp_path: Path) -> tuple[Path, Path]: diff --git a/screen_locker/tests/test_tcx_unified_day.py b/screen_locker/tests/test_tcx_unified_day.py index 4208e74..8c2048c 100644 --- a/screen_locker/tests/test_tcx_unified_day.py +++ b/screen_locker/tests/test_tcx_unified_day.py @@ -15,7 +15,14 @@ from screen_locker._walk_tcx import ( activity_shortfall, walk_day, ) -from screen_locker.tests._activity_helpers import DAY, Verifier, drop, tcx, verify +from screen_locker.tests._activity_helpers import ( + DAY, + Verifier, + drop, + tcx, + tcx_points, + verify, +) if TYPE_CHECKING: from pathlib import Path @@ -193,3 +200,37 @@ class TestLapOnlyExport: result = verify(verifier) assert result is not None assert result[0] == "too_short" + + +class TestSpeedCap: + """Pairs faster than 25 km/h count neither moving time nor distance.""" + + def test_a_car_trip_credits_nothing(self, verifier: Verifier) -> None: + """10 km at 40 km/h (15 min) is a vehicle, not a workout.""" + drop( + verifier.folder, + "08-00-00", + "_Walking", + tcx("Walking", "08:00", moving_min=15, metres=10000), + ) + result = verify(verifier) + assert result is not None + assert result[0] == "too_short" + + def test_one_gps_jump_drops_only_its_pair(self, verifier: Verifier) -> None: + """A 60 km/h jump inside a 3 m/s run loses that pair and nothing else.""" + points = [(s, s * 3.0 + (83.0 if s > 600 else 0.0)) for s in range(0, 1201, 5)] + drop( + verifier.folder, + "08-00-00", + "_Running", + tcx_points("Running", "08:00", points), + ) + (path,) = verifier._find_runnerup_exports_for_date(DAY) + data = verifier._pull_and_parse_tcx(path) + assert data is not None + assert data["moving_seconds"] == pytest.approx(1195) + assert data["track_distance_m"] == pytest.approx(3585) + result = verify(verifier) + assert result is not None + assert result[0] == "verified" diff --git a/screen_locker/tests/test_walk_tcx.py b/screen_locker/tests/test_walk_tcx.py index 9deb939..b0fcb87 100644 --- a/screen_locker/tests/test_walk_tcx.py +++ b/screen_locker/tests/test_walk_tcx.py @@ -103,7 +103,12 @@ class TestTrackSummary: def test_no_points_has_no_end(self) -> None: """A track with no points has zero moving time and no end.""" summary = track_summary(activity([])) - assert summary == {"activity_id": "A1", "moving_seconds": 0.0, "ended_at": None} + assert summary == { + "activity_id": "A1", + "moving_seconds": 0.0, + "track_distance_m": 0.0, + "ended_at": None, + } def leg( diff --git a/stronglift_replacement/workout_app/DOCS-workout-app-context.md b/stronglift_replacement/workout_app/DOCS-workout-app-context.md index 473e71a..fe2e5f8 100644 --- a/stronglift_replacement/workout_app/DOCS-workout-app-context.md +++ b/stronglift_replacement/workout_app/DOCS-workout-app-context.md @@ -27,7 +27,8 @@ Implementing design_v2.md improvements. - Trackpoints must be <= 30 s apart with cumulative `DistanceMeters`, or the PC credits no moving time (`lib/services/run_math.dart` mirrors that rule). - Thresholds that decide credit live on the PC only, one rule for runs and - walks alike: a day's summed distance >= 3.5 km OR summed moving time >= 25 min + walks alike: a day's summed distance >= 3.5 km OR summed moving time >= 25 min (pairs + faster than 25 km/h count neither) (`screen_locker/_walk_tcx.py`); sport and file-name suffix never matter. - GPS sits behind `PositionSource` (`position_source*.dart`); imported RunnerUp runs are stored with `upload_state='never'` (table CHECK). diff --git a/stronglift_replacement/workout_app/lib/services/run_math.dart b/stronglift_replacement/workout_app/lib/services/run_math.dart index ab81dab..62f5a17 100644 --- a/stronglift_replacement/workout_app/lib/services/run_math.dart +++ b/stronglift_replacement/workout_app/lib/services/run_math.dart @@ -28,8 +28,9 @@ const double kRunningMaxSpeedMps = 25 / 3.6; /// Speed cap above which a fix is a GPS jump, 8 km/h for a walk. const double kWalkingMaxSpeedMps = 8 / 3.6; -/// The jump cap for [sport]. Display only: the PC has no upper speed, so the -/// moving time shown here can be below what the PC credits, never above. +/// The jump cap for [sport]. Display only: the PC's cap is 25 km/h for every +/// sport (`MAX_MOVING_SPEED_MPS`), so the walking cap here can show less than +/// the PC credits, never more. double maxSpeedMps(RunSport sport) => switch (sport) { RunSport.running => kRunningMaxSpeedMps, RunSport.walking => kWalkingMaxSpeedMps,