"""CS-5: Phone in a pocket: walk, jog, or run? -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/cs05-walk-jog-run/
Data:     https://apopt.com/data/tutorials/cs05-walk-jog-run/ (keep raw/ next to this file)
"""

# %% [markdown]
# ## Part 1 (Week 4): from a phone log to labelled windows
#
# Eight people each carried a phone in a trouser pocket through a three-minute session of standing,
# walking, jogging and running, and wrote down in a diary the second each part began. The phone
# logged its accelerometer about 50 times a second. The people and their logs are **synthetic**,
# made by `prepare.py` from the same step model as the book's activity windows (Section 11.6), so
# the right answers are known; the faults in them are the ones real logs have (Chapter 4).
#
# ### Step 1 · Gather

# %%
# Step 1 · One log and the diary
import numpy as np
import pandas as pd

diary = pd.read_csv("raw/diary.csv")
p1 = pd.read_csv("raw/phone_P1.csv")
print(p1.shape)
print(p1.head(3).to_string(index=False))
print(diary[diary["person"] == "P1"].to_string(index=False))

# %% [markdown]
# The log holds a time stamp in nanoseconds and three accelerations in m/s² along the **phone's**
# axes. The diary holds only start times, in whole seconds, written by the person: each part ends
# where the next begins.
#
# ### Step 2 · Statistics: profile every log before using any

# %%
# Step 2 · Rate, gaps, repeats and extremes for all eight logs
PEOPLE = [f"P{k}" for k in range(1, 9)]
logs, rows = {}, []
for p in PEOPLE:
    d = pd.read_csv(f"raw/phone_{p}.csv")
    d["t_s"] = (d["time"] - d["time"].iloc[0]) / 1e9
    d["mag"] = np.sqrt(d["x"] ** 2 + d["y"] ** 2 + d["z"] ** 2)          # independent of how the phone sits
    dt = d["t_s"].diff().dropna()
    logs[p] = d
    rows.append({"person": p, "rows": len(d), "seconds": round(d["t_s"].iloc[-1], 1),
                 "rate_Hz": round(1 / dt.median(), 1), "longest_gap_ms": round(1000 * dt.max()),
                 "not_forward": int((dt <= 0).sum()), "max_mag": round(d["mag"].max(), 1)})
profile = pd.DataFrame(rows)
print(profile.to_string(index=False))

# %% [markdown]
# Every log runs at about 50 samples a second, but three are not clean. P2 has 30 rows whose time does
# not move forward: a block the phone wrote twice. P5 has a gap of about a second with no rows. P7 has a
# total acceleration of 78 m/s², eight times gravity, in one sample: a spike, since the next sample is
# back to normal. None of these was visible in the first three rows.
#
# ### Step 3 · Visualize: one session against its diary

# %%
# Step 3 · P1's session, with the diary
import matplotlib.pyplot as plt

d = logs["P1"]
parts = diary[diary["person"] == "P1"].reset_index(drop=True)
ends = list(parts["start_s"][1:]) + [d["t_s"].iloc[-1]]
fig, ax = plt.subplots(figsize=(9, 3.4))
shade = {"stand": "1.0", "walk": "0.92", "jog": "0.82", "run": "0.7"}
for (s, a), e in zip(parts[["start_s", "activity"]].values, ends):
    ax.axvspan(s, e, color=shade[a], lw=0)
    ax.text((s + e) / 2, 33, a, ha="center")
ax.plot(d["t_s"], d["mag"], "k-", lw=0.5)
ax.set(xlabel="time (s)", ylabel="total acceleration (m/s²)", ylim=(0, 36))
plt.tight_layout()
print({a: round(d.loc[(d["t_s"] > s + 2) & (d["t_s"] < e - 2), "mag"].std(), 2)
       for (s, a), e in zip(parts[["start_s", "activity"]].values, ends)})

# %% [markdown]
# The diary and the signal agree: the swing grows from walking to jogging to running and vanishes when
# P1 stands. The edges are not sharp, and the diary's whole seconds will not fall exactly on them.
#
# ### Step 4 · Cleanse: rules first
#
# 1. Sort by time; a row whose time stamp repeats an earlier one is a copy and is dropped (logged).
# 2. A total acceleration above 6 g (58.9 m/s²) is a spike: that sample is set missing (logged).
# 3. A gap is not filled. A window that contains a gap longer than 0.2 s is flagged.
# 4. A window gets a label only if it lies wholly inside one diary part with 2 s to spare at each end,
#    because the diary's times are rounded and written by hand. Other windows are kept, unlabelled.

# %%
# Step 4 · Clean the logs and log every change
import os

log, clean = [], []
for p, d in logs.items():
    d = d.sort_values("time", kind="stable")
    copy = d["time"].duplicated()
    d = d[~copy].copy()
    spike = d["mag"] > 6 * 9.81
    d.loc[spike, "mag"] = np.nan
    log += [{"person": p, "rule": "repeated time stamp dropped", "rows": int(copy.sum())},
            {"person": p, "rule": "spike over 6 g set missing", "rows": int(spike.sum())}]
    d["t_s"] = (d["time"] - d["time"].iloc[0]) / 1e9
    clean.append(d.assign(person=p)[["person", "t_s", "mag"]])
clean = pd.concat(clean)
os.makedirs("clean", exist_ok=True)
clean.round(3).to_csv("clean/samples_clean.csv", index=False)
changes = pd.DataFrame(log)
changes[changes["rows"] > 0].to_csv("clean/change_log.csv", index=False)
print(changes[changes["rows"] > 0].to_string(index=False))
print(f"{len(clean)} clean samples from {sum(len(d) for d in logs.values())} raw rows")

# %% [markdown]
# ### Cut the session into windows
#
# A **window** is a short stretch of the signal treated as one example: here 5 seconds, long enough
# for at least seven steps even when walking. Each window gets its person, its start time, a label
# from the diary (rule 4), and a flag if it contains a gap (rule 3).

# %%
# Five-second windows with diary labels
WIN, MARGIN = 5.0, 2.0
rows = []
for p, d in clean.groupby("person"):
    parts = diary[diary["person"] == p].reset_index(drop=True)
    ends = list(parts["start_s"][1:]) + [d["t_s"].max()]
    for t0 in np.arange(0, d["t_s"].max() - WIN, WIN):
        w = d[(d["t_s"] >= t0) & (d["t_s"] < t0 + WIN)]
        inside = [a for (s, a), e in zip(parts[["start_s", "activity"]].values, ends)
                  if t0 >= s + MARGIN and t0 + WIN <= e - MARGIN]
        rows.append({"person": p, "t0_s": t0, "label": inside[0] if inside else "unlabelled",
                     "gap": bool(w["t_s"].diff().max() > 0.2)})
windows = pd.DataFrame(rows)
windows.to_csv("clean/windows.csv", index=False)
print(windows["label"].value_counts().to_string())
lab = windows[windows["label"] != "unlabelled"]
print("share of labelled windows:", (lab["label"].value_counts(normalize=True) * 100).round(0).to_dict())
print("windows with a gap:", int(windows["gap"].sum()))

# %% [markdown]
# 289 windows, 196 of them labelled. About three quarters of the labelled windows are walking and
# only about one in eleven is running, as in a real day: the class you most want to find is the rarest.
# The unlabelled windows sit on the diary's boundaries; they stay in the table for Part 2's last step.
#
# ## Part 2 (Week 6): walk, jog or run, for a person the model has never seen
#
# ### Step 5 · Features
#
# Two numbers per window describe a gait (Section 6.4): the **cadence**, the strongest rhythm between
# 0.5 and 4 steps a second, found from the window's spectrum; and the **bounce**, the standard
# deviation of the total acceleration, in units of g. This cell starts from the clean files, so Part 2
# runs on its own.

# %%
# Step 5 · Cadence and bounce for every window
samples = pd.read_csv("clean/samples_clean.csv")
windows = pd.read_csv("clean/windows.csv")

def features(m):
    m = m.dropna().to_numpy()
    spec = np.abs(np.fft.rfft(m - m.mean(), n=1024))         # zero-padded for a finer frequency grid
    f = np.fft.rfftfreq(1024, d=WIN / len(m))
    band = (f >= 0.5) & (f <= 4.0)
    return f[band][np.argmax(spec[band])], m.std() / 9.81

feats = [features(samples.loc[(samples["person"] == r.person) & (samples["t_s"] >= r.t0_s)
                              & (samples["t_s"] < r.t0_s + WIN), "mag"]) for r in windows.itertuples()]
windows[["cadence_hz", "bounce_g"]] = np.round(feats, 3)
windows.to_csv("clean/windows_features.csv", index=False)
print(windows[windows["label"] != "unlabelled"].groupby("label")[["cadence_hz", "bounce_g"]].median().round(2).to_string())

# %%
# Step 5 · The two features by class
lab = windows[windows["label"] != "unlabelled"]
fig, ax = plt.subplots(figsize=(6.4, 4))
for name, m in [("stand", "s"), ("walk", "o"), ("jog", "^"), ("run", "X")]:
    s = lab[lab["label"] == name]
    ax.plot(s["cadence_hz"], s["bounce_g"], m, ms=6, mfc="white" if name in ("walk", "jog") else "k",
            color="k", label=f"{name} ({len(s)})")
ax.set(xlabel="cadence (steps per second)", ylabel="bounce (g)")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# Walking stands apart. Jogging and running overlap at their edges: some people jog with as much
# bounce as others run. Standing has no rhythm, so its "cadence" is just the largest wobble in the noise.
#
# ### Steps 7 and 8 · Scale inside the model, split by person, and beat the baseline
#
# Standing needs no model: its bounce is under 0.1 g. The question is walk, jog or run, and what the
# model will do on **someone new**, so every test holds out one whole person: train on seven, test on the eighth, eight times (`LeaveOneGroupOut`). The scaler is fitted
# inside each training set (a pipeline). And every score is set beside the **majority-class
# baseline**, a "model" that always says "walk" (Section 11.6.3).

# %%
# Steps 7–8 · Leave one person out, against the majority class
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import LeaveOneGroupOut
from sklearn.metrics import accuracy_score, recall_score

moving = lab[lab["label"] != "stand"]                      # standing: bounce under 0.1 g, no model needed
X, y, who = moving[["cadence_hz", "bounce_g"]].to_numpy(), moving["label"].to_numpy(), moving["person"].to_numpy()
CLASSES = ["walk", "jog", "run"]

def held_out(fit_rows):
    pred = np.empty(len(y), dtype=object)
    for tr, te in LeaveOneGroupOut().split(X, y, who):
        Xt, yt = fit_rows(X[tr], y[tr])
        pred[te] = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(Xt, yt).predict(X[te])
    return pred

plain = held_out(lambda a, b: (a, b))
print(f"majority class ('walk'): accuracy {np.mean(y == 'walk'):.2f}")
print(f"model, one person out:   accuracy {accuracy_score(y, plain):.2f}")
print("recall by class:", dict(zip(CLASSES, recall_score(y, plain, labels=CLASSES, average=None).round(2))))

# %% [markdown]
# Always saying "walk" is right about three times in four. The model does much better, 0.94, but
# look at the recall for each class, the share of that class's windows it found. Walking is found
# every time; jogging and running, the rare classes, only about seven times in ten, because a model
# trained on mostly walking can afford to be careless with them and still score well.
#
# ### Step 6 · Balance: the training rows only
#
# One fix is to **oversample**: inside each training set, repeat the windows of the rarer classes at
# random until every class has as many as walking. The test person is never touched; the test set must
# look like the data the model will meet (Section 11.6.3).

# %%
# Step 6 · Oversample the training rows, never the test person
rng = np.random.default_rng(0)

def oversample(Xt, yt):
    n = max(np.sum(yt == c) for c in CLASSES)
    idx = np.concatenate([rng.choice(np.flatnonzero(yt == c), n, replace=True) for c in CLASSES])
    return Xt[idx], yt[idx]

balanced = held_out(oversample)
table = pd.DataFrame({"plain": recall_score(y, plain, labels=CLASSES, average=None),
                      "balanced training": recall_score(y, balanced, labels=CLASSES, average=None)},
                     index=CLASSES).round(2)
print(table.to_string())
print(f"accuracy: plain {accuracy_score(y, plain):.2f}, balanced training {accuracy_score(y, balanced):.2f}")
print(pd.crosstab(pd.Series(y, name="diary"), pd.Series(balanced, name="model")).reindex(index=CLASSES, columns=CLASSES).to_string())

# %% [markdown]
# Balancing the training rows raises the recall for running from 0.72 to 0.78 and leaves the test
# person exactly as recorded; overall accuracy does not move, which is the point of Section 11.6.3:
# accuracy is mostly a score on the common class. The table of diary against model shows where the
# remaining mistakes are: all between jogging and running, the two classes that overlap. Balancing
# cannot fix that; only a better feature or more people can.
#
# ### Minutes at each intensity in a session
#
# The athlete does not want windows; she wants minutes. For each person, using the model trained on
# the other seven with balanced training rows, add up the predicted windows (5 s each) and set them
# beside the diary.

# %%
# Minutes of walking, jogging and running, model against diary
moving = moving.assign(model=balanced)
mins = moving.groupby("person").apply(lambda g: pd.Series(
    {f"{c} diary": (g["label"] == c).sum() * WIN / 60 for c in ["walk", "jog", "run"]} |
    {f"{c} model": (g["model"] == c).sum() * WIN / 60 for c in ["walk", "jog", "run"]}), include_groups=False)
print(mins.round(2).to_string())
err = {c: (mins[f"{c} model"] - mins[f"{c} diary"]).abs().mean() * 60 for c in ["walk", "jog", "run"]}
print("mean absolute error per session (s):", {c: round(v) for c, v in err.items()})

# %% [markdown]
# For a person it has never seen, the model gets the walking minutes right in every session and the
# jogging and running minutes within 7 seconds on average. The misses are whole people, not scattered
# windows: P1 runs in a way the model reads as jogging, and P7 jogs in a way it reads as running. Each
# person's style shifts both features, which is exactly why the test holds out whole people. Two
# limits to say out loud. These minutes cover only the labelled windows; the windows on the diary's
# boundaries would add some time to each part. And the people are synthetic: a real pocket, real
# shoes and real hills will spread the features more, so test the model on a recording of your own
# before trusting its minutes.
