"""Q-21: Sweat rate from two weighings -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q21-sweat-rate/
Data:     https://apopt.com/data/tutorials/q21-sweat-rate/ (keep raw/ next to this file)
"""

# %% [markdown]
# You do not need a sweat patch to know how much you sweat. Weigh yourself before and after a
# run, note what you drank and any urine you passed, and almost all of the mass lost is water
# (Section 7.6):
#
# sweat rate = (mass before − mass after + drink − urine) / time, with 1 L of water = 1 kg.
#
# The log here is **synthetic**: ten runs by an invented 70 kg runner, made by `prepare.py` to
# look like a real log, including one mistake a real log would have.
#
# ### Open the log and check it

# %%
# Ten weighings, one range check
import numpy as np
import pandas as pd

log = pd.read_csv("raw/weighings_synthetic.csv")
print(log.to_string(index=False))
change = (log["mass_after_kg"] - log["mass_before_kg"]) / log["mass_before_kg"]
print("rows where the mass changed by more than 10%:", log.index[change.abs() > 0.10].tolist())

# %% [markdown]
# Row 6 shows 153.0 kg after a one-hour run that started at 70.4 kg. Nobody gains 83 kg on a
# run: 153.0 is the after-weight typed in pounds (153.0 / 2.20462 = 69.4 kg). Fix it with a rule
# you can state, and keep a note of the change.
#
# ### Sweat rate and mass loss

# %%
# Convert the pounds, then compute
LB = 2.20462
fix = change.abs() > 0.10
log.loc[fix, "mass_after_kg"] = (log.loc[fix, "mass_after_kg"] / LB).round(1)
log["note"] = np.where(fix, "after-weight was in lb; divided by 2.20462", "")
loss = log["mass_before_kg"] - log["mass_after_kg"]
log["sweat_l_per_h"] = (loss + log["drink_l"] - log["urine_l"]) / (log["minutes"] / 60)
log["mass_loss_pct"] = 100 * loss / log["mass_before_kg"]
print(log[["date", "air_temp_c", "minutes", "sweat_l_per_h", "mass_loss_pct", "note"]].round(2).to_string(index=False))

# %% [markdown]
# Only the hottest run, at 31 °C, lost more than 2% of body mass (2.7%), the level the American
# College of Sports Medicine advises drinking to stay under (Sawka and others, 2007). Sweat rate
# more than triples from the coolest run to the hottest.
#
# ### Sweat rate against temperature

# %%
# A line through the log, with the scale's resolution
import matplotlib.pyplot as plt

slope, icpt = np.polyfit(log["air_temp_c"], log["sweat_l_per_h"], 1)
err = 0.1 / (log["minutes"] / 60)                        # up to 0.1 kg from two 0.1 kg readings
print(f"sweat rate ≈ {icpt:.2f} + {slope:.3f} × temperature (L/h, °C)")
hot = icpt + slope * 30
print(f"at 30 °C: {hot:.2f} L/h; scale resolution adds up to ±{err.min():.2f} to ±{err.max():.2f} L/h")
need = (hot * 1.5 - 0.02 * 70) / 1.5                     # 90 min at 30 °C, loss held to 2% of 70 kg
print(f"90 min at 30 °C: drink at least {need:.2f} L/h to keep the loss under 2%")

fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.errorbar(log["air_temp_c"], log["sweat_l_per_h"], yerr=err, fmt="o", color="k", capsize=3)
tt = np.array([5, 33])
ax.plot(tt, icpt + slope * tt, "--")
ax.set(xlabel="air temperature (°C)", ylabel="sweat rate (L/h)")
plt.tight_layout()

# %% [markdown]
# On a scale that reads to 0.1 kg, each weighing can be off by up to 0.05 kg, so the mass change
# can be off by up to 0.1 kg; over a one-hour run that is up to 0.1 L/h, and over 45 minutes
# up to 0.13 L/h. Longer runs and a finer scale give a better number. The line is this runner's own: sweat
# rates differ a great deal between people (Sawka and others, 2007).
#
# **For the athlete:** "At 30 °C you sweat about 1.5 litres an hour; on a 90-minute run in that
# heat, drink at least 0.6 litres an hour to keep the loss under 2% of your weight."
