"""Q-10: Open a phone sensor log and plot it -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q10-phone-log/
Data:     https://apopt.com/data/tutorials/q10-phone-log/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### What a phone writes
#
# A free sensor-logging app on a phone writes the accelerometer as a table: a time stamp and three
# accelerations, x, y and z, along the phone's own axes, in m/s². The file here is the book's
# **synthetic** 60-second walk (Chapter 4), made by a script so that its faults are known: the
# phone was in a pocket, the walker stood still for about 5 seconds, walked, and stood again.
# Open it and look before you compute anything.

# %%
# Open the log
import numpy as np
import pandas as pd

walk = pd.read_csv("raw/walk_accel.csv")
print(walk.shape)
print(walk.head(3).to_string(index=False))
print(walk.isna().sum().to_string())

# %% [markdown]
# The `time` column is in **nanoseconds** since 1 January 1970, the form many logging apps use;
# `seconds_elapsed` counts from the start of the log. Six cells of `x` are empty. Now the clock.
# Never take the sample rate from the app's settings screen; compute it from the time stamps
# (Section 4.2.4).

# %%
# The real sample rate
t = (walk["time"] - walk["time"].iloc[0]) / 1e9               # ns -> s since the start
dt = t.diff().dropna()
print(f"median spacing {1000 * dt.median():.1f} ms -> {1 / dt.median():.1f} Hz")
print(f"largest gap {1000 * dt.max():.0f} ms; steps that do not move forward: {int((dt <= 0).sum())}")
walk["t_s"] = t
walk["mag"] = np.sqrt(walk["x"]**2 + walk["y"]**2 + walk["z"]**2)   # total acceleration
print(f"total acceleration: median {walk['mag'].median():.2f} m/s², largest {walk['mag'].max():.1f}")

# %% [markdown]
# About 50 samples a second, with one gap of 820 ms and 20 rows that do not move forward in time:
# a block the phone wrote twice. The **magnitude** of the three axes, √(x² + y² + z²), does not
# care how the phone sits in the pocket. Standing still it reads gravity, 9.81 m/s²; walking makes
# it swing around that. The largest value, 78 m/s², is eight times gravity: a spike to check.
#
# ### One chart

# %%
# The walk at two zoom levels
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 1, figsize=(8, 4.6))
ax[0].plot(walk["t_s"], walk["mag"], "-", color="k", lw=0.6)
ax[0].axhline(9.81, color="0.5", ls="--", lw=1, label="gravity")
ax[0].set(xlabel="time (s)", ylabel="acceleration (m/s²)", ylim=(0, 25))
ax[0].legend(loc="upper right")
win = walk[(walk["t_s"] > 10) & (walk["t_s"] < 14)]
ax[1].plot(win["t_s"], win["mag"], "o-", ms=2, color="k", lw=0.8)
ax[1].set(xlabel="time (s)", ylabel="acceleration (m/s²)")
plt.tight_layout()
print(f"samples between 10 and 14 s: {len(win)} (expected about {4 / dt.median():.0f})")

# %% [markdown]
# The top panel shows the shape of the session: still, walking, still, and two faults, the spike
# near 21 s (drawn off the scale here) and a stretch near 33 s where the line goes flat because the
# sensor froze. The zoom shows the steps themselves, about two a second. The zoom window also
# holds about 20 more samples than 4 seconds should: that is the block written twice, near 12 s.
# Nothing has been cleaned yet; Q-12 marks what is wrong without deleting it.
#
# **For the athlete:** "Your phone logged about 50 readings a second and caught your walking
# rhythm clearly; before we count steps we'll fix one spike, one frozen second and one repeated
# block in the file."
