"""CS-4: A messy watch export to a clean table -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs04-messy-watch-export/
Data:     https://apopt.com/data/tutorials/cs04-messy-watch-export/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### Step 1 · Gather: the export as the watch wrote it
#
# An adult male athlete in his mid-40s asked his watch maker's website for his data and got back
# one FIT file per activity. The course case file keeps one row per file: the watch's own
# **session** fields (the summary the watch writes when you press stop), with the watch's own names
# and units, from one watch over two and a half years. GPS positions and per-second records were
# removed. A coach wants one thing from it: a quarter-by-quarter summary of the running that can be
# trusted.

# %%
# Step 1 · Open the export
import os
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/sessions_fit.csv")
print(f"{len(raw)} activities, {raw.shape[1]} fields, {raw['start_time'].min()[:10]} to {raw['start_time'].max()[:10]}")
print(raw.groupby(["sport", raw["sub_sport"].fillna("-")]).size().to_string())
filled = raw.notna().sum().sort_values()
print("activities with each field (fewest first):", filled.head(9).to_dict())
print(raw.iloc[0].dropna().to_dict())

# %% [markdown]
# Eight sports, and fields that come and go with them: running cadence only on runs, pool length
# only on some swims, a distance on 603 of 693 activities. The first run has
# `avg_running_cadence` 86 and `avg_step_length` 980. Eighty-six steps a minute is a slow walk,
# and 980 m is not a step. Nothing in the file says what the units are.
#
# ### Step 2 · Statistics: a unit audit
#
# Do not guess units from one value. Use **identities** that must hold whatever the units: speed ×
# time = distance; distance ÷ steps = step length; strides ÷ minutes = cadence; cadence × step
# length = speed. Each one tests a unit hypothesis against the whole file at once. A **stride** is
# one full cycle of one foot, so one stride is two steps.

# %%
# Step 2 · Test each unit against an identity
run = raw[(raw["sport"] == "running") & (raw["total_distance"] > 200)]
v, d = run["enhanced_avg_speed"], run["total_distance"]
checks = {
    "speed x timer / distance": v * run["total_timer_time"] / d,
    "speed x elapsed / distance": v * run["total_elapsed_time"] / d,
    "distance (mm) / (2 x strides) / step_length": 1000 * d / (2 * run["total_strides"]) / run["avg_step_length"],
    "strides per timer minute / running_cadence": run["total_strides"] / (run["total_timer_time"] / 60) / run["avg_running_cadence"],
    "2 x cadence x step (mm) / 60000 / speed": 2 * run["avg_running_cadence"] * run["avg_step_length"] / 60000 / v,
}
for name, ratio in checks.items():
    near = (ratio / ratio.median() - 1).abs() < 0.02
    print(f"{name:45s} median {ratio.median():.3f}; within 2% of it: {near.mean():.0%}")
ok = run["avg_vertical_ratio"] > 0
vr = run["avg_vertical_oscillation"] / run["avg_step_length"] * 100 / run["avg_vertical_ratio"]
print(f"{'oscillation / step x 100 / vertical_ratio':45s} median {vr[ok].median():.2f} ({ok.sum()} runs with a value)")

# %% [markdown]
# Speed × **timer** time gives the distance for every run; speed × **elapsed** time overshoots by
# about 31%. The timer stops when the watch pauses (traffic lights, a water stop) and elapsed time
# does not, so pace and moving time must come from the timer. Distance in millimeters ÷ twice the
# strides matches `avg_step_length` (median ratio 0.998), so step length is in **millimeters** (980
# is 0.98 m). Strides per timer minute match `avg_running_cadence` (1.005), so that cadence counts
# **one foot**: double it for steps a minute (86 is 172). Twice the cadence times the step length
# gives the speed for 99% of runs, which ties the three together. Vertical oscillation ÷ step length
# comes out at 0.96 of the vertical ratio, so oscillation is in millimeters too.
#
# Not every ratio sits within 2% for every run, and it does not need to. The file rounds step length
# to 10 mm and cadence to whole strides. The wrong units would miss by far more: centimeters by a
# factor of 10, steps instead of strides by a factor of 2. A median of 0.998 rules them out.
#
# Three more traps do not show up in a runner's identities: a field whose meaning changes with the
# sport, zeros that mean "no value", and a clock.

# %%
# Step 2 · One name, many meanings; zeros; the clock
kind = raw["sub_sport"].fillna(raw["sport"])
print("median avg_cadence by kind:", raw.groupby(kind)["avg_cadence"].median().dropna().to_dict())
print("distance blank or 0:", kind[raw["total_distance"].fillna(0) == 0].value_counts().to_dict())
runs_all = raw[raw["sport"] == "running"]
zero = runs_all[["avg_stance_time", "avg_vertical_oscillation", "avg_vertical_ratio", "avg_power"]] == 0
print(f"running activities with 0 (of {len(runs_all)}):", zero.sum().to_dict())
lag = runs_all["total_elapsed_time"] / runs_all["total_timer_time"]
print(f"elapsed / timer on runs: median {lag.median():.2f}; over 1.05 in {(lag > 1.05).sum()} runs")
utc = pd.to_datetime(raw["start_time"]).dt.tz_localize(None)
local = utc + pd.to_timedelta(raw["utc_offset_h"], unit="h")
print("utc_offset_h:", raw["utc_offset_h"].value_counts().to_dict())
away = ~raw["utc_offset_h"].isin([-6, -7])
print("away from -6/-7, by month:", local[away].dt.strftime("%Y-%m").value_counts().sort_index().to_dict())
print(f"activities whose UTC date is not the local date: {(utc.dt.date != local.dt.date).sum()}")

# %% [markdown]
# `avg_cadence` is one column with at least four meanings: pedal revolutions a minute on a bike
# (where 0 means no cadence sensor), strokes a minute in the pool, most likely strides of one foot on
# a walk or a hike, and a rhythm the file does not define on the elliptical. It must never be
# averaged across sports. The elliptical and indoor-bike sessions have no distance at all: a sum of
# distance that treats them as 0 km is right, and a mean that does is wrong.
#
# On 316 of 497 running activities the ground-contact time (stance time), vertical oscillation and
# vertical ratio are **0**, and power is 0 on 23. Nobody runs with zero bounce: 0 is the watch's code
# for "not estimated", and a mean that keeps those zeros lands far below the true value. Elapsed time
# is a median 1.30 times the timer on runs, and more than 5% longer on 376 of them.
#
# The start is in UTC (the "Z"), and `utc_offset_h` says how far the wall clock was from it. Most
# rows are −6 or −7 (US Mountain time, summer and winter), but the watch also logged trips at −5,
# −4 and +3. A date taken from UTC puts 72 activities on the wrong date, and one fixed home
# time zone would put every trip in the wrong hour. The local start is UTC plus the row's own offset.
#
# ### Step 3 · Visualize: what is labelled running?
#
# Convert every field with the units the audit found, then plot each running activity's pace
# against its cadence. Runs should cluster; anything else will stand apart.

# %%
# Step 3 · Convert every field with the audited units
import matplotlib.pyplot as plt

is_bike, is_swim = raw["sport"] == "cycling", raw["sport"] == "swimming"
conv = pd.DataFrame({
    "activity_id": raw["activity_id"], "start_local": local, "utc_offset_h": raw["utc_offset_h"],
    "sport": raw["sport"], "sub_sport": raw["sub_sport"], "distance_km": raw["total_distance"] / 1000,
    "moving_min": raw["total_timer_time"] / 60, "elapsed_min": raw["total_elapsed_time"] / 60,
    "cadence_spm": 2 * raw["avg_running_cadence"], "step_m": raw["avg_step_length"] / 1000,
    "stance_ms": raw["avg_stance_time"], "vert_osc_mm": raw["avg_vertical_oscillation"],
    "vert_ratio_pct": raw["avg_vertical_ratio"], "power_w": raw["avg_power"],
    "pedal_rpm": raw["avg_cadence"].where(is_bike), "strokes_per_min": raw["avg_cadence"].where(is_swim),
    "max_speed_mps": raw["enhanced_max_speed"], "avg_hr_bpm": raw["avg_heart_rate"],
    "max_hr_bpm": raw["max_heart_rate"], "ascent_m": raw["total_ascent"], "energy_kcal": raw["total_calories"]})
conv["pace_min_km"] = conv["moving_min"] / conv["distance_km"].where(conv["distance_km"] > 0.2)
print(conv.loc[conv["sport"] == "running", ["distance_km", "moving_min", "pace_min_km", "cadence_spm", "step_m", "max_speed_mps"]].describe().loc[["50%", "min", "max"]].round(2).to_string())

# %%
# Step 3 · Pace against cadence, every running activity
fig, ax = plt.subplots(figsize=(6.4, 4))
for sub, mk, lab in [(None, "o", "outdoor"), ("indoor_running", "^", "indoor"), ("track", "s", "track")]:
    m = (conv["sport"] == "running") & (conv["sub_sport"].isna() if sub is None else conv["sub_sport"] == sub)
    ax.plot(conv.loc[m, "cadence_spm"], conv.loc[m, "pace_min_km"], mk, ms=4 if sub is None else 7,
            color="k", mfc="k" if sub is None else "white", alpha=0.5 if sub is None else 1, label=lab)
ax.set(xlabel="cadence (steps/min)", ylabel="pace (min/km, log scale)", yscale="log")
ax.set_yticks([3, 4, 5, 7, 10, 15, 20, 30, 50], labels=["3", "4", "5", "7", "10", "15", "20", "30", "50"])
ax.minorticks_off()
ax.legend(loc="upper right")
plt.tight_layout()
groups = conv[conv["sport"] == "running"].groupby(conv["sub_sport"].fillna("outdoor"))
print(groups[["cadence_spm", "pace_min_km", "avg_hr_bpm"]].median().round(1).to_string())
print("indoor runs with cadence of 150 or more:", (groups.get_group("indoor_running")["cadence_spm"] >= 150).sum())

# %% [markdown]
# Most running activities form one tight cluster: about 176 steps a minute at 4.5 to 6 minutes a
# kilometer. Two groups stand apart. A few outdoor activities move at 84 to 140 steps a minute and 7
# to 14 minutes a kilometer: that is walking cadence, so these are walks saved as runs. Pace alone
# would not find them, because a run up a mountain can be just as slow; cadence can. And 15
# of the 21 **indoor** runs scatter far from the rest, at 36 to 132 steps a minute and paces as slow
# as 37 minutes a kilometer. Indoors there is no GPS, and the watch takes distance and cadence from
# its wrist accelerometer. Their median heart rate (153 beats a minute) says the work was real; their
# distances and cadences cannot be trusted. The other 6 indoor runs land in the cluster, but their
# distance still comes from the wrist, not from GPS. Last, the table's extremes: a run of 0 m and a
# few seconds (an aborted start), a step of 2.49 m (an indoor run), and a maximum speed of 23.81 m/s
# (86 km/h, one bad GPS sample).
#
# ### Step 4 · Cleanse: rules first, a change log, a clean copy
#
# The rules, written before they are applied (Section 4.3). None deletes a row; each assigns a
# category or marks a value, and the log counts what each one did:
#
# 1. Not labelled running: category `cross-training` (swims, elliptical, bike, hikes, walks).
# 2. Running with less than 200 m: category `aborted`.
# 3. Indoor running: category `indoor run`; it counts as training time, not toward distance or pace.
# 4. Cadence of 140 steps a minute or less **and** slower than 7 min/km: category `walk`; training
#    time, not running pace.
# 5. Everything else: category `run`.
# 6. A run with a cadence of 140 or less at a running pace: cadence and step length set missing.
#    The wrist missed steps; the distance and time are kept.
# 7. On foot, a maximum speed above 10 m/s (36 km/h): the maximum speed is set missing; the rest of
#    the row is kept.
# 8. A 0 in distance, cadence, step length, stance time, vertical oscillation, vertical ratio, power
#    or pedal cadence: set missing. It means "not measured".

# %%
# Step 4 · Eight rules, a change log and a clean copy
clean = conv.copy()
clean["category"] = "run"
RULES = [("cross-training", clean["sport"] != "running"),
         ("aborted", clean["distance_km"].fillna(0) < 0.2),
         ("indoor run", clean["sub_sport"] == "indoor_running"),
         ("walk", (clean["cadence_spm"] <= 140) & (clean["pace_min_km"] > 7))]
log = []
for name, hit in RULES:
    hit = hit & (clean["category"] == "run")              # first matching rule wins
    clean.loc[hit, "category"] = name
    log.append({"rule": f"category = {name}", "values": int(hit.sum())})
missed = (clean["category"] == "run") & (clean["cadence_spm"] <= 140)
clean.loc[missed, ["cadence_spm", "step_m"]] = np.nan
log.append({"rule": "run cadence and step set missing (missed steps)", "values": int(missed.sum())})
spike = (clean["max_speed_mps"] > 10) & (clean["sport"] != "cycling")   # 36 km/h on foot
clean.loc[spike, "max_speed_mps"] = np.nan
log.append({"rule": "max speed set missing (spike)", "values": int(spike.sum())})
ZERO = ["distance_km", "cadence_spm", "step_m", "stance_ms", "vert_osc_mm", "vert_ratio_pct", "power_w", "pedal_rpm"]
log.append({"rule": "0 set missing (not measured)", "values": int((clean[ZERO] == 0).sum().sum())})
clean[ZERO] = clean[ZERO].mask(clean[ZERO] == 0)
os.makedirs("clean", exist_ok=True)
clean.to_csv("clean/activities_categorized.csv", index=False)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))
print(clean["category"].value_counts().to_dict())

# %%
# Step 4 · Check the conversion against the case file's own
ref = pd.read_csv("raw/activities_clean.csv")              # the case file's own SI copy
assert (ref["activity_id"] == clean["activity_id"]).all()
assert (ref["start_local"] == clean["start_local"].dt.strftime("%Y-%m-%dT%H:%M")).all()
assert np.allclose(ref["distance_km"], clean["distance_km"], atol=0.0006, equal_nan=True)   # to the meter
assert np.allclose(ref["moving_time_min"], clean["moving_min"], atol=0.006)          # to the second
has = ref["avg_cadence_spm"].notna()                        # the case file leaves 0 cadence blank
assert np.allclose(ref.loc[has, "avg_cadence_spm"], conv.loc[has, "cadence_spm"])
print(f"all {len(ref)} rows match the case file's SI table: local start, distance, moving time;")
print(f"running cadence matches on all {has.sum()} rows where the case file has one")

# %% [markdown]
# 457 runs remain, and nothing was thrown away: the 196 cross-training sessions, the 21 indoor
# runs, the 15 walks and the 4 aborted starts are all still in the table with their category. Three
# runs keep their distance and time but lose a cadence the wrist undercounted, 6 maximum speeds that
# were single spikes are marked missing, and so are 1,451 zeros that meant "not measured". The case
# file's own conversion agrees with yours on every local start, distance and moving time, and on all
# 495 running cadences it gives, which checks the unit audit a second way. Notice what an "outlier"
# rule would have done: the walks and the indoor runs look like outliers in pace, and they are real
# sessions.
#
# ### The quarter-by-quarter summary
#
# Now the table the coach asked for, one row per calendar quarter, with the runs summarized and
# everything else counted as hours so that no training disappears. The first and last quarters are
# partial, so the summary also gives kilometers per week of the span each quarter covers.

# %%
# A quarterly running summary a coach can trust
clean["quarter"] = clean["start_local"].dt.to_period("Q")
runs = clean[clean["category"] == "run"]
summary = runs.groupby("quarter").agg(runs=("distance_km", "size"), km=("distance_km", "sum"),
                                      long_km=("distance_km", "max"), median_pace=("pace_min_km", "median"),
                                      cadence=("cadence_spm", "median"), hr=("avg_hr_bpm", "median"))
other = clean[clean["category"] != "run"].groupby("quarter")["moving_min"].sum() / 60
summary["other_h"] = other.reindex(summary.index).fillna(0)
first, last = clean["start_local"].min().normalize(), clean["start_local"].max().normalize()
start = summary.index.start_time.where(summary.index.start_time > first, first)
end = summary.index.end_time.normalize().where(summary.index.end_time < last, last)
summary["weeks"] = ((end - start).days + 1) / 7
summary["km_per_week"] = summary["km"] / summary["weeks"]
summary["median_pace"] = summary["median_pace"].map(lambda p: f"{int(p)}:{60 * (p % 1):02.0f}")
summary.round(1).to_csv("clean/quarter_summary.csv")
print(summary.round(1).to_string())
ref_km = ref.loc[runs.index].groupby(runs["quarter"])["distance_km"].sum()   # same rows, case file's units
print(f"largest quarterly difference from activities_clean.csv: {(ref_km - summary['km']).abs().max():.3f} km")

# %% [markdown]
# Read the weeks column before the totals. The first "quarter" is three days in June 2024 with one
# run, and the last stops on 28 November 2026 (8.4 weeks), so compare kilometers per week, not
# totals. Per week, the running grew from about 19 to 21 km in the second half of 2024 to 28 to 39 km
# in 2025 and 26 to 32 km in most of 2026; the last quarter of 2026 is the biggest by far, at about 57
# km a week. Pace changed once: the median was 6:05 a kilometer at 169 steps a minute in the summer of
# 2024, and 5:06 to 5:18 at 176 steps a minute in every quarter since, at about the same median heart
# rate (155 to 161). The quarterly totals agree with `activities_clean.csv` to 5 m.
#
# Two dips are questions for the athlete, not for the file. The first quarter of 2026 holds a trip
# (the +3 h offset in February) and only 36 runs; and in May 2026 a second watch recorded
# most of the runs, so they are not in this export at all (the challenge).

# %%
# Monthly distance, as exported against clean
labelled = conv[conv["sport"] == "running"]
month_raw = labelled.set_index("start_local")["distance_km"].resample("MS").sum()
month_run = runs.set_index("start_local")["distance_km"].resample("MS").sum().reindex(month_raw.index, fill_value=0)
fig, ax = plt.subplots(figsize=(9, 3.4))
ax.bar(month_raw.index, month_raw, width=25, color="0.8", label="labelled running, as exported")
ax.bar(month_run.index, month_run, width=12, color="k", label="runs after the rules")
ax.set(ylabel="distance per month (km)")
ax.legend(loc="upper left")
plt.tight_layout()
diff = (month_raw - month_run).sort_values(ascending=False)
print("largest exported-minus-clean months (km):", {d.strftime("%Y-%m"): round(v, 1) for d, v in diff.head(4).items()})
