"""Q-29: Median and spread of ten trials -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q29-ten-trials/
Data:     https://apopt.com/data/tutorials/q29-ten-trials/ (keep raw/ next to this file)
"""

# %% [markdown]
# One shot is an anecdote; ten shots are a sample (Section 10.6). The raw files are ten results
# files in the layout the basketball app writes, one per shot, and the made-or-missed log the
# shooter kept by hand. **They are synthetic**: Chapter 10 made them with a fixed random seed so
# that everyone gets the same numbers. They are not measurements of anyone.

# %%
# Read ten results files into one table
import glob
import re
import pandas as pd

rows = []
for f in sorted(glob.glob("raw/results/results_*.md")):
    for line in open(f, encoding="utf-8").read().splitlines():
        cells = [c.strip() for c in line.strip("|").split("|")]
        if len(cells) == 5 and cells[0] not in ("Section", "---"):
            num = re.search(r"[-+]?\d+(\.\d+)?", cells[2])      # "46.3 °" -> 46.3
            rows.append({"file": f.split("/")[-1], "metric": cells[1], "value": float(num.group())})
trials = pd.DataFrame(rows).pivot(index="file", columns="metric", values="value")
trials = trials.join(pd.read_csv("raw/shot_log.csv").set_index("file")["made"])
print(trials.to_string())

# %% [markdown]
# ### Center and spread, two ways
#
# The **mean** and **standard deviation** use every value's size, so one wild value moves them.
# The **median** and the **interquartile range** (IQR, the middle half) or the **median absolute
# deviation** (MAD, the median distance from the median) do not. The disc app scales the MAD by
# 1.4826 (`disc/src/lib/metric-registry.ts`), which turns it into a robust standard deviation:
# for normal scatter the raw MAD is only about two thirds of one.

# %%
# Mean and SD against median, IQR and MAD
import numpy as np

def robust(v):
    med = np.median(v)
    q1, q3 = np.percentile(v, [25, 75])
    mad = np.median(np.abs(v - med))
    return pd.Series({"mean": v.mean(), "SD": v.std(ddof=1), "median": med, "IQR": q3 - q1,
                      "MAD": mad, "1.4826 MAD": 1.4826 * mad})

summary = trials.drop(columns="made").apply(robust).T
print(summary.round(2).to_string())
angle = trials["Ball Release Angle"]
print(f"release angle without its lowest shot: mean {angle.drop(angle.idxmin()).mean():.2f}, "
      f"median {angle.drop(angle.idxmin()).median():.2f}")

# %%
# Ten release angles, with their median and middle half
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 2.6))
q1, q3 = np.percentile(angle, [25, 75])
ax.axvspan(q1, q3, color="gray", alpha=0.25, label="middle half (IQR)")
ax.axvline(angle.median(), color="black", lw=2, label="median")
ax.axvline(angle.mean(), color="black", ls="--", lw=1, label="mean")
made = trials["made"] == 1
ax.plot(angle[made], np.zeros(made.sum()), "o", ms=9, color="black", label="made")
ax.plot(angle[~made], np.zeros((~made).sum()), "o", ms=9, mfc="white", color="black", label="missed")
ax.set(xlabel="ball release angle (degrees, synthetic)", yticks=[])
ax.legend(loc="upper left", fontsize=7, ncol=3)
plt.tight_layout()

# %% [markdown]
# Eight of the ten release angles sit between 46.2° and 48.8°; two missed shots, 40.8° and
# 43.0°, sit well below. Those two pull the mean (46.12°) below the median (46.65°) and more than
# double the standard deviation (2.42°) compared with the robust spread (1.4826 × MAD = 1.11°).
# Drop the lowest shot and the mean jumps by 0.59° while the median moves by 0.15°. That is why
# the apps build a personal baseline from medians and MADs: one bad shot, or one frame where the
# ball was lost, should not move the target. The low shots are not errors to delete, though;
# both were misses, and CS-14 asks whether release angle separates makes from misses.
#
# **For the athlete:** your release angle is about 46.7°, give or take about 1°; judge the next
# session's ten shots against that, not against your best shot.
