-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_data.py
More file actions
3397 lines (2966 loc) · 135 KB
/
Copy pathprocess_data.py
File metadata and controls
3397 lines (2966 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Strava Data Processor - Parses activities.csv and GPX/TCX files, computes all metrics."""
import csv
import json
import gzip
import math
import os
import io
import shutil
import fitparse
import h3
import numpy as np
from scipy.ndimage import gaussian_filter
from PIL import Image
import mercantile
import xml.etree.ElementTree as ET
from datetime import datetime, timezone, timedelta
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
# --- Configuration ---
EXPORT_DIR = "strava_export"
OUTPUT_DIR = "data"
ACTIVITIES_CSV = os.path.join(EXPORT_DIR, "activities.csv")
ACTIVITIES_DIR = os.path.join(EXPORT_DIR, "activities")
# Namespaces for GPX parsing
NS = {
"": "http://www.topografix.com/GPX/1/1",
"gpxtpx": "http://www.garmin.com/xmlschemas/TrackPointExtension/v1",
"gpxx": "http://www.garmin.com/xmlschemas/GpxExtensions/v3",
}
# Sport type mapping for our target sports
TARGET_SPORTS = {"Run", "Ride", "Hike", "Swim"}
# HR zones as percentages of max HR
ZONE_RANGES = {
"Z1 (Recovery)": (0, 60),
"Z2 (Endurance)": (60, 70),
"Z3 (Tempo)": (70, 80),
"Z4 (Threshold)": (80, 90),
"Z5 (Max)": (90, 100),
}
os.makedirs(OUTPUT_DIR, exist_ok=True)
def parse_csv_date_utc(date_str):
"""Parse the Strava CSV date string (assumed local time) and return UTC ISO string."""
if not date_str:
return None
try:
# Format: "Apr 29, 2026, 5:31:44 PM"
dt = datetime.strptime(date_str, "%b %d, %Y, %I:%M:%S %p")
# Assume it's local time (guess based on activities being in Australia)
# Try common Australian timezones
for tz_offset in [10, 11, 8, 9.5]: # AEST, AEDT, AWST, ACST
try:
tz = timezone(timedelta(hours=tz_offset))
dt_tz = dt.replace(tzinfo=tz)
return dt_tz.isoformat()
except:
continue
# Fallback: treat as UTC
dt_utc = dt.replace(tzinfo=timezone.utc)
return dt_utc.isoformat()
except (ValueError, TypeError):
return None
# --- Haversine distance calculation ---
def haversine(lat1, lon1, lat2, lon2):
"""Haversine distance in metres between two lat/lon points."""
R = 6371000
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlam = math.radians(lon2 - lon1)
a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlam / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def douglas_peucker(coords, tolerance):
"""Simplify a list of [lng, lat] coordinates using Douglas-Peucker.
Returns simplified list of [lng, lat] pairs.
Tolerance is in metres (approximate). Uses perpendicular distance in degrees
scaled by a rough metres-per-degree factor at the midpoint latitude.
"""
if len(coords) <= 2:
return coords[:]
# Compute average latitude for rough degrees-to-metres conversion
avg_lat = sum(c[1] for c in coords) / len(coords)
m_per_deg_lat = 111320
m_per_deg_lng = 111320 * math.cos(math.radians(avg_lat))
# Convert tolerance in metres to approximate squared distance in degree-space
tol_deg_lat = tolerance / m_per_deg_lat
tol_deg_lng = tolerance / m_per_deg_lng
def point_line_dist_sq(px, py, ax, ay, bx, by):
"""Squared perpendicular distance of point P from line AB."""
dx = bx - ax
dy = by - ay
if dx == 0 and dy == 0:
return ((px - ax) * (0.5)) ** 2 + ((py - ay) * (0.5)) ** 2 # simplified
t = max(0, min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
proj_x = ax + t * dx
proj_y = ay + t * dy
return (px - proj_x) ** 2 + (py - proj_y) ** 2
def max_distance_sq(start, end):
"""Find point with max squared distance from line between start and end indices."""
max_d2 = 0
max_idx = start
ax, ay = coords[start][0], coords[start][1]
bx, by = coords[end][0], coords[end][1]
for i in range(start + 1, end):
px, py = coords[i][0] / 180 * math.pi if False else coords[i][0], coords[i][1] # no transform needed
d2 = point_line_dist_sq(
coords[i][0] * m_per_deg_lng, coords[i][1] * m_per_deg_lat,
ax * m_per_deg_lng, ay * m_per_deg_lat,
bx * m_per_deg_lng, by * m_per_deg_lat
)
if d2 > max_d2:
max_d2 = d2
max_idx = i
return max_d2, max_idx
def recurse(start, end, tol_sq):
"""Recursive DP simplification. Returns list of indices to keep."""
d2, idx = max_distance_sq(start, end)
if d2 <= tol_sq:
return [start, end]
left = recurse(start, idx, tol_sq)
right = recurse(idx, end, tol_sq)
return left[:-1] + right
tol_sq = tolerance * tolerance # square of tolerance in metres
kept = recurse(0, len(coords) - 1, tol_sq)
return [coords[i] for i in kept]
# --- Grade calculation ---
def calc_grade(elev_change, distance):
if distance == 0:
return 0
return (elev_change / distance) * 100
# --- GPX file parsing ---
def parse_gpx(filepath):
"""Parse a GPX file returning list of track points with time, lat, lon, ele, hr, cadence, temp."""
points = []
try:
if filepath.endswith(".gz"):
f = gzip.open(filepath, "r")
content = f.read()
f.close()
root = ET.fromstring(content)
else:
tree = ET.parse(filepath)
root = tree.getroot()
for trkseg in root.iterfind(".//{http://www.topografix.com/GPX/1/1}trkseg"):
for trkpt in trkseg.findall("{http://www.topografix.com/GPX/1/1}trkpt"):
lat = float(trkpt.get("lat"))
lon = float(trkpt.get("lon"))
ele_el = trkpt.find("{http://www.topografix.com/GPX/1/1}ele")
time_el = trkpt.find("{http://www.topografix.com/GPX/1/1}time")
ele = float(ele_el.text) if ele_el is not None else None
time_str = time_el.text if time_el is not None else None
# Extensions (HR, cadence, temp)
hr = None
cadence = None
temp = None
for ext in trkpt.iter():
tag = ext.tag.split("}")[-1] if "}" in ext.tag else ext.tag
if tag == "hr" and ext.text:
try:
hr = int(float(ext.text))
except ValueError:
pass
if tag == "cad" and ext.text:
try:
cadence = int(float(ext.text))
except ValueError:
pass
if tag == "atemp" and ext.text:
try:
temp = float(ext.text)
except ValueError:
pass
points.append({
"lat": lat, "lon": lon, "ele": ele,
"time": time_str, "hr": hr, "cadence": cadence, "temp": temp
})
except Exception as e:
print(f" WARNING: Failed to parse GPX {filepath}: {e}")
return []
return points
# --- TCX file parsing ---
def parse_tcx(filepath):
"""Parse a TCX file returning list of track points."""
points = []
try:
if filepath.endswith(".gz"):
f = gzip.open(filepath, "r")
content = f.read()
f.close()
root = ET.fromstring(content)
else:
tree = ET.parse(filepath)
root = tree.getroot()
tcx_ns = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
for track in root.iter(f"{{{tcx_ns}}}Trackpoint"):
time_el = track.find(f"{{{tcx_ns}}}Time")
dist_el = track.find(f"{{{tcx_ns}}}DistanceMeters")
hr_el = track.find(f"{{{tcx_ns}}}HeartRateBpm")
cad_el = track.find(f"{{{tcx_ns}}}Cadence")
pos_el = track.find(f"{{{tcx_ns}}}Position")
alt_el = track.find(f"{{{tcx_ns}}}AltitudeMeters")
time_str = time_el.text if time_el is not None else None
distance = float(dist_el.text) if dist_el is not None else None
hr = None
if hr_el is not None:
hr_v = hr_el.find(f"{{{tcx_ns}}}Value")
if hr_v is not None:
hr = int(float(hr_v.text))
cadence = int(float(cad_el.text)) if cad_el is not None and cad_el.text else None
lat, lon = None, None
if pos_el is not None:
lat_el = pos_el.find(f"{{{tcx_ns}}}LatitudeDegrees")
lon_el = pos_el.find(f"{{{tcx_ns}}}LongitudeDegrees")
lat = float(lat_el.text) if lat_el is not None else None
lon = float(lon_el.text) if lon_el is not None else None
ele = float(alt_el.text) if alt_el is not None else None
points.append({
"lat": lat, "lon": lon, "ele": ele,
"time": time_str, "hr": hr, "cadence": cadence,
"distance_cum": distance
})
except Exception as e:
print(f" WARNING: Failed to parse TCX {filepath}: {e}")
return []
return points
# --- FIT file parsing ---
SEMICIRCLE_TO_DEG = 180.0 / (2**31)
def parse_fit(filepath):
"""Parse a FIT binary file returning list of track points with time, lat, lon, ele, hr, cadence, speed."""
points = []
try:
if filepath.endswith(".gz"):
f = gzip.open(filepath, "rb")
fit = fitparse.FitFile(f)
else:
fit = fitparse.FitFile(filepath)
for rec in fit:
if rec.name != "record":
continue
vals = {}
for field in rec.fields:
try:
vals[field.name] = rec.get_value(field.name)
except Exception:
pass
ts = vals.get("timestamp")
if ts is None:
continue
lat = vals.get("position_lat")
lon = vals.get("position_long")
if lat is not None:
lat = lat * SEMICIRCLE_TO_DEG
if lon is not None:
lon = lon * SEMICIRCLE_TO_DEG
ele = vals.get("enhanced_altitude") or vals.get("altitude")
hr = vals.get("heart_rate")
cadence = vals.get("cadence")
speed = vals.get("enhanced_speed") or vals.get("speed")
temp = vals.get("temperature")
moving = vals.get("moving") # Strava app FIT includes this boolean
points.append({
"lat": lat,
"lon": lon,
"ele": float(ele) if ele is not None else None,
"time": ts.isoformat() if isinstance(ts, datetime) else str(ts),
"hr": int(hr) if hr is not None else None,
"cadence": int(cadence) if cadence is not None else None,
"temp": float(temp) if temp is not None else None,
"speed_ms": float(speed) if speed is not None else None,
"moving": bool(moving) if moving is not None else None,
})
except Exception as e:
print(f" WARNING: Failed to parse FIT {filepath}: {e}")
return []
return points
# --- Compute time-series metrics from points ---
def compute_stream_metrics(points, is_tcx=False, is_fit=False, sport=""):
"""Compute detailed per-second metrics from track points."""
result = {
"times": [],
"distances": [],
"lats": [],
"lons": [],
"elevations": [],
"speeds": [],
"heartrates": [],
"cadences": [],
"grades": [],
"cumulative_distance": 0,
"total_elevation_gain": 0,
"total_elevation_loss": 0,
"max_speed": 0,
"avg_speed": 0,
"max_hr": None,
"avg_hr": None,
"avg_cadence": 0,
"max_cadence": 0,
"moving_time": 0,
"elapsed_time": 0,
"start_time": None,
"end_time": None,
"start_lat": None,
"start_lon": None,
"end_lat": None,
"end_lon": None,
"avg_temp": None,
"hr_zones": {},
"hr_samples": 0,
"grade_positive_sum": 0,
"grade_negative_sum": 0,
"grade_positive_count": 0,
"grade_negative_count": 0,
"raw_points": [], # simplified points for dashboard
"is_moving": [], # boolean per segment: True = moving, False = stopped
"long_stops": [], # [(start_idx, end_idx, duration_sec), ...]
}
if len(points) < 2:
return result
# --- Stop detection speed thresholds (m/s) ---
threshold = {"Run": 0.5, "Ride": 1.0, "Hike": 0.15, "Swim": 0.2}.get(sport, 0.5)
# Hysteresis: require N consecutive seconds below threshold to trigger stop
STOP_T = 10 # seconds
RESUME_T = 3 # seconds
# For hiking, GPS speed at 1-second intervals is too noisy for hysteresis
use_hysteresis = (sport != "Hike")
cum_dist = 0
prev_point = None
prev_time = None
speeds = []
heart_rates = []
hr_seg_ids = [] # segment index for each HR value (for stop filtering)
cadences = []
temps = []
grades_smooth = []
last_elevation = None
last_grade_distance = 0
rolling_grades = []
seg_speeds = [] # per-segment GPS speed (m/s)
seg_dt = [] # per-segment time delta (s)
seg_fit_moving = [] # per-segment FIT moving flag (None if unavailable)
for i, p in enumerate(points):
cur_time = None
if p["time"]:
try:
if "T" in p["time"]:
cur_time = datetime.fromisoformat(p["time"].replace("Z", "+00:00"))
else:
cur_time = datetime.fromisoformat(p["time"].replace("Z", "+00:00"))
except (ValueError, TypeError):
continue
if result["start_time"] is None and cur_time:
result["start_time"] = cur_time.isoformat()
if cur_time:
result["end_time"] = cur_time.isoformat()
if i == 0 and p["lat"] is not None and p["lon"] is not None:
result["start_lat"] = p["lat"]
result["start_lon"] = p["lon"]
if p["lat"] is not None and p["lon"] is not None:
result["end_lat"] = p["lat"]
result["end_lon"] = p["lon"]
# Distance calculation
if is_tcx and p.get("distance_cum") is not None:
cum_dist = p["distance_cum"]
elif prev_point and p["lat"] is not None and prev_point.get("lat") is not None:
seg_dist = haversine(prev_point["lat"], prev_point["lon"], p["lat"], p["lon"])
cum_dist += seg_dist
else:
seg_dist = 0
result["distances"].append(cum_dist)
# Speed: always use GPS-derived (position delta) for consistency
if prev_point and cur_time and prev_time:
td = (cur_time - prev_time).total_seconds()
if td > 0:
d = cum_dist - result["distances"][-2] if len(result["distances"]) > 1 else 0
spd = d / td
speeds.append(spd)
seg_speeds.append(spd)
seg_dt.append(td)
fit_mv = p.get("moving") # None if not a FIT file or flag absent
seg_fit_moving.append(fit_mv)
result["max_speed"] = max(result["max_speed"], spd)
if spd > 0.3:
result["moving_time"] += td
# Elevation gain/loss
if p["ele"] is not None and last_elevation is not None:
diff = p["ele"] - last_elevation
if diff > 0:
result["total_elevation_gain"] += diff
else:
result["total_elevation_loss"] += abs(diff)
if p["ele"] is not None:
last_elevation = p["ele"]
result["elevations"].append(p["ele"])
else:
result["elevations"].append(None)
# Grade calculation (using rolling 30m distance)
if not is_tcx and prev_point and p["lat"] is not None and prev_point.get("lat") is not None:
seg_dist = haversine(prev_point["lat"], prev_point["lon"], p["lat"], p["lon"])
last_grade_distance += seg_dist
if last_grade_distance >= 30:
if len(result["elevations"]) >= 2:
ele_start = None
for e in reversed(result["elevations"]):
if e is not None:
ele_start = e
break
if ele_start is not None and p["ele"] is not None:
grd = calc_grade(p["ele"] - ele_start, last_grade_distance)
grades_smooth.append(grd)
if grd > 0:
result["grade_positive_sum"] += grd
result["grade_positive_count"] += 1
elif grd < 0:
result["grade_negative_sum"] += abs(grd)
result["grade_negative_count"] += 1
last_grade_distance = 0
result["grades"].append(grades_smooth[-1] if grades_smooth else None)
# HR
if p["hr"] is not None:
heart_rates.append(p["hr"])
hr_seg_ids.append(len(seg_speeds) - 1) # segment index of preceding segment
result["hr_samples"] += 1
# Cadence
if p.get("cadence") is not None:
cadences.append(p["cadence"])
# Temperature
if p.get("temp") is not None:
temps.append(p["temp"])
result["times"].append(cur_time.isoformat() if cur_time else None)
result["lats"].append(p["lat"])
result["lons"].append(p["lon"])
result["heartrates"].append(p["hr"])
result["cadences"].append(p.get("cadence"))
# Store simplified point for dashboard (1 per 10s)
if i % 10 == 0:
result["raw_points"].append({
"t": cur_time.isoformat() if cur_time else None,
"d": round(cum_dist, 1),
"e": round(p["ele"], 1) if p["ele"] else None,
"hr": p["hr"],
"s": round(speeds[-1], 2) if speeds else None,
"lat": p["lat"],
"lon": p["lon"],
"_pi": i, # original point index for stop-detection mapping
})
prev_point = p
prev_time = cur_time
# --- Hysteresis stop detection ---
# Use FIT moving flag if available; otherwise GPS speed threshold + hysteresis
has_fit_moving = any(mv is not None for mv in seg_fit_moving)
is_moving = [True] * len(seg_speeds)
stop_state = False
stop_timer = 0.0
move_timer = 0.0
long_stops = []
current_stop_start = -1
for si in range(len(seg_speeds)):
spd = seg_speeds[si]
dt = seg_dt[si]
fit_mv = seg_fit_moving[si] if si < len(seg_fit_moving) else None
if has_fit_moving and fit_mv is not None:
moving_now = bool(fit_mv)
elif not use_hysteresis:
moving_now = spd >= threshold
else:
if spd < threshold:
stop_timer += dt
move_timer = 0.0
else:
move_timer += dt
stop_timer = 0.0
if not stop_state:
if stop_timer >= STOP_T:
stop_state = True
stop_timer = 0.0
current_stop_start = si
move_timer = 0.0
else:
if move_timer >= RESUME_T:
stop_state = False
move_timer = 0.0
if current_stop_start >= 0:
stop_dur = sum(seg_dt[current_stop_start:si])
if stop_dur > 300:
long_stops.append((current_stop_start, si, round(stop_dur, 1)))
current_stop_start = -1
moving_now = not stop_state
is_moving[si] = moving_now
# Flush any trailing long stop
if stop_state and current_stop_start >= 0:
stop_dur = sum(seg_dt[current_stop_start:])
if stop_dur > 300:
long_stops.append((current_stop_start, len(seg_speeds) - 1, round(stop_dur, 1)))
result["is_moving"] = is_moving
result["long_stops"] = long_stops
# Tag raw_points with moving flag (raw_points stored every 10th original point)
for rp in result["raw_points"]:
pi = rp.get("_pi", 0)
seg_idx = pi - 1
rp["m"] = is_moving[seg_idx] if 0 <= seg_idx < len(is_moving) else True
# Recompute moving_time from hysteresis (more accurate than threshold alone)
result["moving_time"] = sum(seg_dt[i] for i in range(len(seg_speeds)) if is_moving[i])
result["cumulative_distance"] = cum_dist
result["speeds"] = speeds # Store full speeds for decoupling analysis
result["_seg_dt"] = seg_dt # time deltas for moving-filtered analysis
# Compute avg_speed and avg_hr over moving segments only
moving_speeds = [seg_speeds[i] for i in range(len(seg_speeds)) if is_moving[i]]
result["avg_speed"] = sum(moving_speeds) / len(moving_speeds) if moving_speeds else 0
result["avg_cadence"] = round(sum(cadences) / len(cadences), 1) if cadences else 0
result["max_cadence"] = max(cadences) if cadences else 0
result["avg_temp"] = round(sum(temps) / len(temps), 1) if temps else 0
if heart_rates:
# Filter HR to moving segments only
moving_hr = [heart_rates[k] for k in range(len(heart_rates)) if hr_seg_ids[k] < 0 or (0 <= hr_seg_ids[k] < len(is_moving) and is_moving[hr_seg_ids[k]])]
result["avg_hr"] = round(sum(moving_hr) / len(moving_hr), 1) if moving_hr else round(sum(heart_rates) / len(heart_rates), 1)
result["max_hr"] = max(heart_rates)
else:
result["avg_hr"] = 0
result["max_hr"] = 0
if result["start_time"] and result["end_time"]:
try:
st = datetime.fromisoformat(result["start_time"])
et = datetime.fromisoformat(result["end_time"])
result["elapsed_time"] = (et - st).total_seconds()
except:
pass
# HR zone distribution (using max HR from points or estimated) — moving only
max_hr = result["max_hr"] or 190 # fallback
zones = {"Z1": 0, "Z2": 0, "Z3": 0, "Z4": 0, "Z5": 0}
hr_vals = moving_hr if heart_rates else heart_rates
for hr in hr_vals:
pct = (hr / max_hr) * 100 if max_hr > 0 else 0
if pct < 60:
zones["Z1"] += 1
elif pct < 70:
zones["Z2"] += 1
elif pct < 80:
zones["Z3"] += 1
elif pct < 90:
zones["Z4"] += 1
else:
zones["Z5"] += 1
result["hr_zones"] = zones
return result
# --- HR cleaning ---
def clean_hr(hr_values, observed_max_hr):
"""Clean HR stream: cap, rate-of-change filter, trim zeros, sport ceiling."""
if not hr_values:
return hr_values, 0
n = len(hr_values)
cleaned = [min(max(h, 30), 220) for h in hr_values] # Hard cap
# Rate-of-change: HR can't jump >20 bpm between consecutive reads
for i in range(1, n):
if abs(cleaned[i] - cleaned[i - 1]) > 20:
cleaned[i] = cleaned[i - 1]
# Sport-specific ceiling
if observed_max_hr:
cleaned = [min(h, observed_max_hr + 5) for h in cleaned]
# Trim leading/trailing values below 30 (sensor dropout)
start = 0
while start < n and cleaned[start] < 30:
start += 1
end = n
while end > start and cleaned[end - 1] < 30:
end -= 1
cleaned = cleaned[start:end]
dropped = n - len(cleaned)
return cleaned, dropped
# --- Per-sport HR max calibration ---
def compute_sport_max_hr(all_activities, sport, n_months=18):
"""99th percentile of cleaned HR across recent activities for the sport."""
import numpy as np
cutoff = datetime.now(timezone.utc) - timedelta(days=n_months * 30)
all_hr = []
for a in all_activities:
if a.get("sport") != sport:
continue
st = a.get("start_time_utc")
if not st:
continue
try:
dt_str = str(st).replace("Z", "+00:00")
if "+" in dt_str or dt_str.count("-") > 2:
dt = datetime.fromisoformat(dt_str)
else:
dt = datetime.fromisoformat(dt_str).replace(tzinfo=timezone.utc)
except:
continue
if dt < cutoff:
continue
hrs = a.get("_raw_hr_values", [])
if hrs:
all_hr.extend(hrs)
if len(all_hr) < 50:
return None
return float(np.percentile(all_hr, 99))
def compute_karvonen_zones(max_hr, resting_hr=50):
"""5-zone Karvonen model. Returns list of (zone_name, low%, high%, low_bpm, high_bpm)."""
hrr = max_hr - resting_hr
return [
("Z1 Recovery", 50, 60, int(resting_hr + 0.50 * hrr), int(resting_hr + 0.60 * hrr)),
("Z2 Endurance", 60, 70, int(resting_hr + 0.60 * hrr), int(resting_hr + 0.70 * hrr)),
("Z3 Tempo", 70, 80, int(resting_hr + 0.70 * hrr), int(resting_hr + 0.80 * hrr)),
("Z4 Threshold", 80, 90, int(resting_hr + 0.80 * hrr), int(resting_hr + 0.90 * hrr)),
("Z5 VO2max", 90, 100, int(resting_hr + 0.90 * hrr), int(resting_hr + 1.00 * hrr)),
]
def compute_gap_segments(streams, activity_type, grade_points):
"""Compute grade-adjusted pace/speed at per-point level, then aggregate to 1km splits.
Algorithm:
1. Smooth elevation with a rolling-median over 15-point window (~15s at 1Hz)
2. Compute grade per point using ±25m horizontal window (50m total)
3. Clamp grade to [-25%, +25%] to reject residual noise
4. Apply Minetti GAP multiplier per point: gap_speed = actual_speed * factor(grade)
5. Aggregate to 1km splits by distance-weighted average of gap_speed
6. Convert to pace (mm:ss) at the end
Reference: Minetti et al. (2002) J. Applied Physiology
"""
points = streams.get("raw_points", [])
if len(points) < 10:
return []
n = len(points)
# Step 1: Extract arrays (distance, elevation, speed, HR) with valid data
dists = [p.get("d", 0) for p in points]
eles = [p.get("e") for p in points]
speeds = [p.get("s") for p in points]
hrs = [p.get("hr") for p in points]
# Step 1a: Smooth elevation with rolling median (window=15 points)
def rolling_median(values, window):
result = [None] * len(values)
valid = [(i, v) for i, v in enumerate(values) if v is not None]
half = window // 2
for idx in range(len(values)):
start = max(0, idx - half)
end = min(len(values), idx + half + 1)
win = [values[j] for j in range(start, end) if values[j] is not None]
if win:
win.sort()
result[idx] = win[len(win) // 2]
return result
eles_smooth = rolling_median(eles, 15)
speeds_smooth = rolling_median(speeds, 15) # Also smooth GPS speed to remove spikes
# Step 2: Compute grade per point using ±35m horizontal window
grades = [None] * n
for i in range(n):
if eles_smooth[i] is None:
continue
d_cur = dists[i]
# Find point ~35m before
j_before = i
while j_before > 0 and d_cur - dists[j_before] < 35:
j_before -= 1
# Find point ~35m after
j_after = i
while j_after < n - 1 and dists[j_after] - d_cur < 35:
j_after += 1
# Compute grade
ele_before = eles_smooth[j_before]
ele_after = eles_smooth[j_after]
h_dist = dists[j_after] - dists[j_before]
if h_dist > 5 and ele_before is not None and ele_after is not None:
grade_pct = ((ele_after - ele_before) / h_dist) * 100
# Step 3: Clamp to ±25%
grades[i] = max(-25.0, min(25.0, grade_pct))
# Step 4: Apply Minetti multiplier per point
def minetti_factor(grade_pct, is_run):
if is_run:
if grade_pct > 1.0:
return 1.0 + 0.033 * grade_pct
elif grade_pct < -2.0:
return 1.0 - 0.017 * abs(grade_pct)
else:
return 1.0
else:
if grade_pct > 0:
return 1.0 + 0.033 * grade_pct
elif grade_pct < -1.0:
return 1.0 - 0.012 * abs(grade_pct)
else:
return 1.0
is_run = (activity_type == "Run")
gap_speeds = []
for i in range(n):
s = speeds_smooth[i] if speeds_smooth[i] is not None else speeds[i]
if s is not None and s > 0.3 and grades[i] is not None:
factor = minetti_factor(grades[i], is_run)
gap_speeds.append(s * factor)
else:
gap_speeds.append(None)
# Step 5: Aggregate to splits — distance-based for run (1km), moving-time-based for ride (5min)
movings = [p.get("m", True) for p in points] # is_moving flag per point
is_ride = (activity_type == "Ride")
SEGMENT_DIST = 1000 if is_run else 5000 # metres for run path detection only
SEGMENT_TIME = 300 # seconds moving time for cycling (5 min)
MIN_MOVING_DIST = 250 # metres minimum moving distance for a valid split
MIN_MOVING_TIME = 150 # seconds minimum moving time for a valid cycling split
# Compute time deltas between consecutive raw points
time_deltas = [0.0] * n
for i in range(1, n):
try:
t1 = datetime.fromisoformat(points[i - 1]["t"].replace("Z", "+00:00") if points[i - 1].get("t") else "")
t2 = datetime.fromisoformat(points[i]["t"].replace("Z", "+00:00") if points[i].get("t") else "")
time_deltas[i] = (t2 - t1).total_seconds()
if time_deltas[i] < 0:
time_deltas[i] = 0
except:
time_deltas[i] = 10 # fallback ~10s between raw points
segments = []
split_start = 0
split_gap_sum = 0.0
split_weight_sum = 0.0
split_speed_sum = 0.0
split_speed_count = 0
split_hrs = []
split_dist = 0.0 # distance covered in this split (moving only)
split_moving_time = 0.0
split_ele_start = eles_smooth[0]
split_ele_end = split_ele_start
for i in range(n):
d = dists[i]
delta = d - (dists[i - 1] if i > 0 else d)
is_mv = movings[i] if i < len(movings) else True
td = time_deltas[i]
if is_mv and gap_speeds[i] is not None and delta > 0:
split_gap_sum += gap_speeds[i] * delta
split_weight_sum += delta
split_dist += delta
split_moving_time += td
s = speeds_smooth[i] if speeds_smooth[i] is not None else speeds[i]
if s is not None and s > 0.3:
split_speed_sum += s
split_speed_count += 1
if hrs[i] is not None:
split_hrs.append(hrs[i])
if eles_smooth[i] is not None:
split_ele_end = eles_smooth[i]
should_cut = False
if is_ride:
should_cut = split_moving_time >= SEGMENT_TIME and split_dist >= MIN_MOVING_DIST
else:
should_cut = d - dists[split_start] >= SEGMENT_DIST and split_dist >= MIN_MOVING_DIST
if should_cut and split_weight_sum > 0:
gap_speed = split_gap_sum / split_weight_sum
raw_speed = split_speed_sum / split_speed_count if split_speed_count > 0 else 0
avg_grade = grades[i] if i < n and grades[i] is not None else 0
avg_hr = sum(split_hrs) / len(split_hrs) if split_hrs else None
ele_change = (split_ele_end - split_ele_start) if split_ele_start is not None and split_ele_end is not None else 0
segments.append({
"dist_km": round(d / 1000, 2),
"split_dist_km": round(split_dist / 1000, 2),
"split_moving_time_s": round(split_moving_time, 1),
"grade_pct": round(avg_grade, 2),
"speed_ms": round(raw_speed, 2),
"speed_kmh": round(raw_speed * 3.6, 1),
"gap_pace_min_km": round((1000 / gap_speed) / 60, 2) if is_run and gap_speed > 0 else None,
"gap_pace_str": format_pace(gap_speed) if is_run and gap_speed > 0 else None,
"gap_speed_kmh": round(gap_speed * 3.6, 1) if not is_run else None,
"avg_hr": round(avg_hr, 1) if avg_hr else None,
"ele_gain": round(max(0, ele_change), 1),
})
# Reset
split_start = i
split_gap_sum = 0.0
split_weight_sum = 0.0
split_speed_sum = 0.0
split_speed_count = 0
split_hrs = []
split_dist = 0.0
split_moving_time = 0.0
split_ele_start = eles_smooth[i] if eles_smooth[i] is not None else split_ele_start
# Include trailing partial split
include_tail = False
if is_ride:
include_tail = split_moving_time >= MIN_MOVING_TIME and split_dist >= MIN_MOVING_DIST
else:
include_tail = dists[-1] - dists[split_start] >= 500 and split_dist >= MIN_MOVING_DIST
if split_weight_sum > 0 and include_tail:
d_last = dists[-1]
gap_speed = split_gap_sum / split_weight_sum
raw_speed = split_speed_sum / split_speed_count if split_speed_count > 0 else 0
avg_hr = sum(split_hrs) / len(split_hrs) if split_hrs else None
ele_change = (split_ele_end - split_ele_start) if split_ele_start is not None and split_ele_end is not None else 0
tail_grade = grades[n - 1] if grades[n - 1] is not None else 0
segments.append({
"dist_km": round(d_last / 1000, 2),
"split_dist_km": round(split_dist / 1000, 2),
"split_moving_time_s": round(split_moving_time, 1),
"grade_pct": round(tail_grade, 2),
"speed_ms": round(raw_speed, 2),
"speed_kmh": round(raw_speed * 3.6, 1),
"gap_pace_min_km": round((1000 / gap_speed) / 60, 2) if is_run and gap_speed > 0 else None,
"gap_pace_str": format_pace(gap_speed) if is_run and gap_speed > 0 else None,
"gap_speed_kmh": round(gap_speed * 3.6, 1) if not is_run else None,
"avg_hr": round(avg_hr, 1) if avg_hr else None,
"ele_gain": round(max(0, ele_change), 1),
})
return segments
def _compute_point_gap_factors(raw_points):
"""Compute Minetti GAP factor per raw point (same algorithm as compute_gap_segments).
Returns list of (grade_pct, minetti_factor) tuples; None where no valid grade.
"""
n = len(raw_points)
dists = [p.get("d", 0) for p in raw_points]
eles = [p.get("e") for p in raw_points]
def rolling_median(values, window):
result = [None] * len(values)
half = window // 2
for idx in range(len(values)):
start = max(0, idx - half)
end = min(len(values), idx + half + 1)
win = [values[j] for j in range(start, end) if values[j] is not None]
if win:
win.sort()
result[idx] = win[len(win) // 2]
return result
eles_smooth = rolling_median(eles, 15)
grades = [None] * n
for i in range(n):
if eles_smooth[i] is None:
continue
d_cur = dists[i]
j_before = i
while j_before > 0 and d_cur - dists[j_before] < 35:
j_before -= 1
j_after = i
while j_after < n - 1 and dists[j_after] - d_cur < 35:
j_after += 1
ele_before = eles_smooth[j_before]
ele_after = eles_smooth[j_after]
h_dist = dists[j_after] - dists[j_before]
if h_dist > 5 and ele_before is not None and ele_after is not None:
grade_pct = ((ele_after - ele_before) / h_dist) * 100
grades[i] = max(-25.0, min(25.0, grade_pct))
def minetti_factor(grade_pct):
if grade_pct > 1.0:
return 1.0 + 0.033 * grade_pct
elif grade_pct < -2.0:
return 1.0 - 0.017 * abs(grade_pct)
else:
return 1.0
return [(grades[i], minetti_factor(grades[i]) if grades[i] is not None else None) for i in range(n)]
def compute_negative_split(streams, act):
"""Compute negative split metrics for a single running activity.
Uses moving-only raw points, trims first 5 min warmup, finds midpoint
by distance (with interpolation), and computes pace delta for each half
in both raw and GAP-adjusted forms.
Returns a dict or None if insufficient data.
"""
raw_points = streams.get("raw_points", [])
if len(raw_points) < 20:
return None
# Filter to moving points with valid distance/time
moving = [p for p in raw_points if p.get("m", True) and p.get("t") and p.get("d") is not None and p.get("d") >= 0]
if len(moving) < 20:
return None
n = len(moving)
# Compute time deltas between consecutive moving raw points
time_deltas = [0.0] * n
total_moving_time = 0.0
for i in range(1, n):
try:
t1 = datetime.fromisoformat(moving[i - 1]["t"].replace("Z", "+00:00"))
t2 = datetime.fromisoformat(moving[i]["t"].replace("Z", "+00:00"))
dt = (t2 - t1).total_seconds()
if 0 < dt < 3600:
time_deltas[i] = dt
total_moving_time += dt
except Exception:
pass
total_distance = moving[-1]["d"] # cumulative at end of activity
start_distance = moving[0]["d"]
# --- Qualifying criteria ---