"""Q-38: Say how sure you are in one sentence -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q38-how-sure/
Data:     https://apopt.com/data/tutorials/q38-how-sure/ (keep raw/ next to this file)
"""

# %% [markdown]
# Every number in a report has two parts: the value and how sure you are of it (Section 13.3).
# The athlete needs both in one sentence, in words, with a range in their own units and a
# likelihood word from a named scale. This tutorial builds that sentence from Chapter 13's
# **teaching set** of a runner's step rate, before and after three weeks of running to a
# metronome.
#
# ### The change and its 90% range
#
# The typical error (TE) of one clip is the spread of the six baseline clips. The standard
# error of the change between a mean of n₁ clips and a mean of n₂ clips is
# TE × √(1/n₁ + 1/n₂), and the 90% range is the change ± 1.645 standard errors.

# %%
# Typical error, change and range
import pandas as pd
from scipy.stats import norm

df = pd.read_csv("raw/cadence_sessions_synthetic.csv")
base = df[df["phase"] == "baseline"]["cadence_spm"]
te = base.std()
rows = []
for day in (22, 29):
    now = df[df["day"] == day]["cadence_spm"]
    change = now.mean() - base.mean()
    se = te * (1 / len(base) + 1 / len(now)) ** 0.5
    rows.append({"day": day, "change": change, "se": se,
                 "lo": change - 1.645 * se, "hi": change + 1.645 * se,
                 "p_above_3": 1 - norm.cdf((3 - change) / se)})       # 3 spm agreed beforehand
res = pd.DataFrame(rows)
print(f"typical error {te:.2f} spm")
print(res.round(4).to_string(index=False))

# %% [markdown]
# ### From numbers to one sentence
#
# The words come from the calibrated scale of Table 13.4 (after the climate assessments):
# virtually certain 99–100%, very likely 90–100%, likely 66–100%, about as likely as not
# 33–66%, unlikely 0–33%, very unlikely 0–10%. Round the values to the first digit of their
# uncertainty (Section 13.3.3): whole steps a minute.

# %%
# One sentence, two tests
WORDS = [(0.99, "virtually certain"), (0.90, "very likely"), (0.66, "likely"),
         (0.33, "about as likely as not"), (0.10, "unlikely"), (0.0, "very unlikely")]

def how_sure(base_mean, now_mean, se, worthwhile=3, unit="steps a minute"):
    change = now_mean - base_mean
    p = 1 - norm.cdf((worthwhile - abs(change)) / se)
    word = next(w for cut, w in WORDS if p >= cut)
    lo, hi = round(abs(change) - 1.645 * se), round(abs(change) + 1.645 * se)
    return (f"Your step rate {'rose' if change >= 0 else 'fell'} from about {base_mean:.0f} to about "
            f"{now_mean:.0f} {unit} (a change of {lo} to {hi}). It is {word} that this is a real "
            f"change of more than {worthwhile}.")

se29 = res.loc[res["day"] == 29, "se"].iloc[0]
print(how_sure(base.mean(), base.mean() + res.loc[1, "change"], se29))
print(how_sure(base.mean(), 158.0, se29))                 # the book's second test

# %% [markdown]
# The second line matters as much as the first. A function that only ever says "real change"
# is not a summary; it is a cheerleader (Section 13.14).
#
# ### The range, drawn

# %%
# The change and its 90% range against the worthwhile change
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.0, 2.2))
for i, r in res.iterrows():
    ax.plot([r["lo"], r["hi"]], [i, i], "-", color="black", lw=2)
    ax.plot(r["change"], i, "o", color="black", ms=7)
ax.axvline(0, color="0.5", lw=1)
ax.axvline(3, color="0.3", ls="--", lw=1)
ax.text(3.05, 1.35, "worthwhile: 3", fontsize=8)
ax.set(yticks=[0, 1], yticklabels=["day 22", "day 29"], ylim=(-0.6, 1.6), xlim=(-1, 9),
       xlabel="change from baseline (steps per minute)", title="Both ranges clear the worthwhile change")
plt.tight_layout()

# %% [markdown]
# The sentence carries a condition the arithmetic cannot see: it holds *on this treadmill at
# this speed*. Step rate rises with speed, so a change of conditions belongs in the sentence too.
#
# **For the athlete:** "Your step rate on easy runs rose from about 157 to about 163 a minute,
# somewhere between 4 and 7, and on this treadmill at this speed it is almost certainly real."
