"""Q-18: Count steps from an accelerometer -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q18-step-count/
Data:     https://apopt.com/data/tutorials/q18-step-count/ (keep raw/ next to this file)
"""

# %% [markdown]
# Each footstrike sends a jolt up the body, and an accelerometer on the chest sees it as a spike
# on the axis along the body. Find the spikes and you have the steps. The file is the
# **synthetic** chest record of Chapter 6 (Section 6.4): it was made by a script with a known
# answer, 30 seconds of running at 172 steps a minute with a little natural variation from step
# to step, then lying still. Because the answer is known, you can check your count exactly.
#
# ### Open the record

# %%
# A chest accelerometer, in g
import numpy as np
import pandas as pd

acc = pd.read_csv("raw/chest-acc-synthetic.csv")          # t_s, vert_g, fwd_g
fs = 1 / acc["t_s"].diff().median()
run = acc[acc["t_s"] < 30]                                # the running part
t, x = run["t_s"].to_numpy(), run["vert_g"].to_numpy()
print(f"{len(acc)} samples at {fs:.0f} samples/s; running part {len(run)} samples")
print(f"vertical axis while running: mean {x.mean():.2f} g, from {x.min():.2f} to {x.max():.2f} g")

# %% [markdown]
# The mean is 1.17 g, not 0: standing or running, the sensor feels 1 g of gravity as well as
# motion (Section 6.4), and the footstrike spikes push it up from there, to almost 3 g.
#
# ### Filter, then find peaks with a minimum gap
#
# The recipe is the one used for R peaks in Q-13. A band-pass from 0.5 to 5 Hz keeps the step
# rhythm and drops gravity and sensor noise; `find_peaks` then refuses any peak closer than
# 0.25 s to the last one, because no runner takes more than 240 steps a minute.

# %%
# Steps and cadence
from scipy.signal import butter, filtfilt, find_peaks

b, a = butter(2, [0.5, 5.0], btype="band", fs=fs)
y = filtfilt(b, a, x)                                    # two passes, so no time lag

def steps(min_gap_s):
    pk, _ = find_peaks(y, distance=max(1, int(min_gap_s * fs)), prominence=0.5 * y.std())
    return pk

pk = steps(0.25)
cadence = 60 * (len(pk) - 1) / (t[pk[-1]] - t[pk[0]])     # from the first to the last step found
print(f"{len(pk)} steps; cadence {cadence:.1f} steps/min")

# %% [markdown]
# The script that made the file put exactly 86 steps in the first 30 seconds, at 171.9 steps a
# minute, so both numbers are right. The cadence comes from the time between the first and last
# step found, not from the count
# divided by 30 s: a step at the very edge of the window cannot be found, and that would bias
# the count but not the spacing.
#
# ### How much does the minimum gap matter?

# %%
# Too short, about right, too long
import matplotlib.pyplot as plt

for gap in [0.0, 0.25, 0.5]:
    print(f"minimum gap {gap:.2f} s: {len(steps(gap))} steps")
f = np.fft.rfftfreq(len(x), 1 / fs)
p = np.abs(np.fft.rfft(x - x.mean())) ** 2
f_step = f[np.argmax(p[f > 0.5]) + np.sum(f <= 0.5)]
print(f"spectrum peak {f_step:.2f} Hz = {60 * f_step:.0f} steps/min")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
w = (t > 10) & (t < 14)
ax[0].plot(t[w], y[w], lw=1)
ax[0].plot(t[pk][(t[pk] > 10) & (t[pk] < 14)], y[pk][(t[pk] > 10) & (t[pk] < 14)], "o", mfc="none")
ax[0].set(xlabel="time (s)", ylabel="band-passed vertical (g)")
ax[1].plot(f, p / p.max(), "k-", lw=1)
ax[1].set(xlim=(0, 8), xlabel="frequency (Hz)", ylabel="relative power")
plt.tight_layout()

# %% [markdown]
# A minimum gap of 0.5 s is longer than one step (0.35 s at 172 steps a minute), so the
# detector skips every other step and counts 43. With no minimum gap the count here barely changes, because the
# band-pass already smoothed each spike into one hump; on a real, noisier recording the small
# wiggles would count. The spectrum gives a second, independent check: one tall peak at the step
# frequency. The smaller peak at twice that frequency is a harmonic: the spikes are sharper than
# a sine wave.
#
# **For the athlete:** "Your chest sensor counted your steps as well as a stopwatch could: about
# 172 a minute, and two different methods agree."
