<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Appendix A: Python and AI Assistant Quick Start. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 459–464). IRSRI Sports Research Institute. CC BY 4.0.

# A Python and AI Assistant Quick Start

This appendix is a reference card for the Python and the AI-assistant habits the
book uses. It does not teach programming; Chapter 4 does that. It
gives the setup, the dozen commands that do most of the work, how to read the
apps' results files, and three forms to copy: a prompt template, a prompt log and
a de-identification checklist. The listings and their data are in this
appendix's `code` and `data` folders, and each printed output below
is the real output of the listing above it.

## A.1 A Hosted Notebook

A *hosted notebook* is a web page that runs Python on someone else's
computer and keeps code, output and notes together in *cells*. Nothing is
installed on your laptop, and NumPy, pandas, SciPy and Matplotlib come
preinstalled on the common free services. The routine is the same on all of them:

- Sign in and create a new notebook.

- Upload the folder of data the listing needs (a `data` folder beside
  the notebook), or mount your own storage. Uploaded files usually disappear when
  the session ends; download anything you make.

- Paste a listing into a code cell and run it (Shift+Enter).

- Compare the last printed number with the one the book gives. If they
  differ, stop and find out why before you go on.

A library the service lacks is installed in a cell with
`!pip install` followed by its name, for example
`!pip install ultralytics` for the pose listings of Chapter 8 or
`!pip install fitdecode` for activity files. The notebook forgets these
installs when the session ends, so keep the install line at the top.

Listing A.1 is the setup check. It prints the
Python, NumPy, pandas and Matplotlib versions and the size of a small table of
twelve jumps.

**Listing A.1.** The setup check (`appA-python/code/a01_setup.py`)

```python
# the setup check: versions, and one file read
import sys, numpy as np, pandas as pd, matplotlib
print(sys.version.split()[0], np.__version__, pd.__version__, matplotlib.__version__)
df = pd.read_csv("data/jumps.csv")
print(df.shape)                       # rows, columns: must be (12, 5)
```

```text
3.12.3 2.5.5 3.1.1 3.11.2
(12, 5)
```

Your versions may be newer. The last line must be `(12, 5)`: twelve rows
and five columns. If it is not, the file did not upload whole, or the notebook
is looking in another folder.

> **Limits and cautions: Someone else's computer.**
> 
> A hosted notebook runs on a company's server. Upload only data you may share,
> and de-identify it first (Section A.6). The same rule
> applies, more strongly, to anything you paste into an AI assistant.

### A.1.1 A notebook someone else can run

A notebook is finished when someone else can open it and get your numbers.
Chapter 4 gives the full routine (Sections 4.1 and 4.1.1);
here it is as a checklist.

- **Restart and run all.** Cells can be run in any order, and a
  notebook that works only in the order you happened to run it is broken.
  Before you hand it in, restart the kernel and run every cell from the top.

- **State the versions.** Print the Python and library versions in the
  first cell, and put any `!pip install` lines above it.

- **Fix the seed.** Anything random (synthetic data, a resample, a
  train–test split) takes a fixed seed, so a rerun gives the same numbers.

- \textbf{Check with `assert`.} Test each function you write on
  three cases whose answers you know, including one awkward case, so a wrong
  result stops the notebook instead of flowing into a chart.

Listing A.2 does all four for pace from distance
and time. Run it twice: the output must be identical.

**Listing A.2.** Versions, a seed and three known cases (`appA-python/code/a04_rerun.py`)

```python
import sys, numpy as np, pandas as pd
print("python", sys.version.split()[0], "numpy", np.__version__, "pandas", pd.__version__)
rng = np.random.default_rng(42)                # fixed seed: same numbers every run

def pace_s_per_km(dist_m, time_s):
    """Pace in seconds per km; None if the runner did not move."""
    return None if dist_m <= 0 else 1000 * time_s / dist_m

assert pace_s_per_km(1000, 300) == 300         # 5:00 per km
assert pace_s_per_km(5000, 1200) == 240        # 4:00 per km
assert pace_s_per_km(0, 30) is None            # standing still: no pace
print("checks passed; noise sample", rng.normal(0, 3, 3).round(2))
```

```text
python 3.12.3 numpy 2.5.5 pandas 3.1.1
checks passed; noise sample [ 0.91 -3.12  2.25]
```

## A.2 The Dozen Commands

The book's listings use about a hundred distinct library calls, but a dozen do most of
the work. Counted over every listing in the chapters, the most frequent are
`pd.read_csv`, `np.array`, `np.sqrt`, `np.diff`,
`np.mean` and `np.median`, `np.linalg.norm`,
`np.percentile`, `np.polyfit`, `.groupby`,
`.rolling` and `plt.subplots`. Table A.1
lists them by job, and Listing A.3 runs twelve of them
on the jump table. Chapter 4 lists the pandas commands for time series
(time zones, resampling, interpolation) in its own table.

*Table A.1. The commands that do most of the book's work.*

| Command | What it does |  |
|---|---|---|
| `df = pd.read_csv("f.csv")` | Read a comma-separated file into a table (a DataFrame). |  |
| `df.head()`, `df.shape`, `df.describe()` | First rows; rows and columns; count, mean, SD and percentiles of each column. |  |
| `df.dropna()` | Drop rows with a missing value. |  |
| `df["h"] = ` | Make a new column from others, row by row. |  |
| `df[df.week == 3]` | Keep the rows that pass a test; join tests with  | and `|`, each in parentheses. |
| `df.groupby("week").h.mean()` | One summary per group; `.agg(["mean", "std"])` for several. |  |
| `s.diff()`, `np.diff(x)` | Change from the previous value. |  |
| `s.rolling(5, center=True).mean()` | A moving average (or `.median()`) over five samples. |  |
| `np.mean`, `np.median`, `np.percentile(x, 75)` | Summaries of an array. |  |
| `np.sqrt`, `np.linalg.norm`, `np.degrees`, `np.arccos` | The geometry of keypoints (Appendix B). |  |
| `b, a = np.polyfit(x, y, 1)` | Straight-line fit; the slope comes first. |  |
| `fig, ax = plt.subplots()`; `ax.plot(x, y)`; `fig.savefig("f.png")` | One chart, saved to a file. |  |
| `df.to_csv("out.csv", index=False)` | Write a table to a CSV file. |  |

**Listing A.3.** Twelve commands on twelve jumps (`appA-python/code/a02_dozen.py`)

```python
# the dozen commands, on twelve jumps
import numpy as np, pandas as pd
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt

df = pd.read_csv("data/jumps.csv")                 # 1 read a CSV file
print(df.head(3))                                  # 2 look at the first rows
df = df.dropna()                                   # 3 drop rows with a gap
df["t_s"] = df.flight_frames / df.fps              # 4 a new column from others
df["h_cm"] = 100 * 9.81 * df.t_s**2 / 8            #   flight-time height
wk3 = df[(df.week == 3) & (df.athlete == "A01")]  # 5 keep the rows you want
print(df.groupby(["athlete", "week"]).h_cm.agg(["mean", "std"]).round(1))  # 6
h = wk3.h_cm.to_numpy()                            # 7 a column as a NumPy array
print(np.median(h).round(1), np.percentile(h, 75).round(1))   # 8 summaries
print(np.diff(h).round(1))                         # 9 change from trial to trial
b, a = np.polyfit(wk3.trial, wk3.h_cm, 1)          # 10 straight-line fit
print(round(b, 2))
fig, ax = plt.subplots(figsize=(4, 3))             # 11 one chart
ax.plot(df.week, df.h_cm, "o"); ax.set_xlabel("Week"); ax.set_ylabel("Height (cm)")
fig.savefig("jumps.png", dpi=150)
df.to_csv("jumps_heights.csv", index=False)        # 12 write a CSV file
print(len(df))
```

```text
  athlete  week  trial  flight_frames  fps
0     A01     1      1           30.0   60
1     A01     1      2           31.0   60
2     A01     1      3           29.0   60
              mean  std
athlete week
A01     1     30.7  2.0
        3     33.6  0.8
A02     1     25.8  1.3
        3     27.8  0.7
33.8 34.1
[ 1.6 -0.5]
0.53
11
```

Four things in that output are worth a second look. The frame counts print as
`30.0`, not `30`: one row has a gap, and a column with a gap
becomes a column of decimals. The table has 12 rows but the last line says 11,
because `dropna` removed the row with the gap. The week-3 jumps were
filmed at 240 fps, so their frame counts are four times larger, and the
listing divides by each row's own rate; using one rate for the whole table would
make the week-3 heights sixteen times too large. And the slope of 0.53 cm a
trial, from three trials, is not a trend; Appendix B and
Chapter 11 say why.

\paragraph{When a listing fails.} Read the last line of the error
message first. The common ones are FileNotFoundError (the file is in another folder, or
its name differs in capitals), `KeyError` (a column name is spelled
differently, often with a space or a unit in it; print `df.columns`),
ValueError: could not convert string to float (a cell holds text such as
`N/A`) and `ModuleNotFoundError` (the library is not installed in
this notebook).

## A.3 Reading the Apps' Results Files

Every movement app can save its result as text, in Markdown, and the
process-a-folder page of each app writes four files per video:
`results_<video>.mp4`, `.pdf`, `.md` and a `.json`
receipt of the settings used (Chapter 4;
Appendix F gives the layouts). The Markdown file has a
*Metrics* table with the columns *Section, Metric, Value, Rating,
Target*. Listing A.4 reads that table into pandas
and checks the frame rates in the receipt. The two files are the synthetic
week-3 jump of Chapter 4, which was filmed at 120 fps and
analyzed at its 30 fps header on purpose.

**Listing A.4.** A results file into a table, and its receipt (`appA-python/code/a03_results.py`)

```python
# one results file: the Metrics table into pandas, and the receipt's frame rates
import json, pathlib, pandas as pd

def metrics(md_path):
    rows, inside = [], False
    for line in pathlib.Path(md_path).read_text(encoding="utf-8").splitlines():
        if line.startswith("## "):
            inside = line == "## Metrics"
        elif inside and line.startswith("|") and "---" not in line:
            rows.append([c.strip() for c in line.strip("|").split(" | ")])
    return pd.DataFrame(rows[1:], columns=rows[0])     # first row is the header

m = metrics("data/results/results_jump_wk3_t3.md")
print(m.columns.tolist(), len(m))
print(m.loc[m.Metric == "Jump Height", ["Value", "Rating"]].to_string(index=False))
r = json.loads(pathlib.Path("data/results/results_jump_wk3_t3.json").read_text())
print(r["sourceFps"], r["options"]["captureFps"], r["actualCaptureFps"], len(r["warnings"]))
```

```text
['Section', 'Metric', 'Value', 'Rating', 'Target'] 17
            Value    Rating
32.9 cm / 13.0 in Pro (2/3)
30 auto 30 2
```

The Value cell is text with its units, so take the leading number with a regular
expression before you compute with it (Chapter 4 shows how). The last
line is the check that matters: the file's header rate (`sourceFps`) is
30, the capture rate was left on `auto`, the analysis used 30, and there
are two warnings. A clip you know was filmed at 120 that shows
`actualCaptureFps` of 30 must be run again with the capture rate set.

## A.4 Specify, Generate, Verify, Defend

The book uses an AI assistant in four steps: you *specify* what the code
must do and write a test whose answer you computed yourself; the assistant
*generates* the code; you *verify* it by running the test, reading
every line and checking one result a second way; and you *defend* it by
explaining any line a reviewer picks and what the code does on bad input
(Chapter 4). The template below is the specification, written before
you open the assistant. Fill in every line; a blank line is a decision you have
left to the assistant.

**Listing A.5.** A prompt template for the specify step

```text
TASK      Write a Python function <name>(<inputs>) that returns <output>.
INPUT     File or object, its columns and units, e.g. "CSV: time (s), y_px (pixels,
          y grows downward), fps given separately". Paste the header and 5 INVENTED
          rows, never the athlete's data.
OUTPUT    Type and units, e.g. "a float, centimeters, rounded to 0.1".
RULES     The formula or method in words, with the source (book section, app file).
          What to do with gaps, duplicates, text in number columns, an empty file.
LIBRARIES Only numpy and pandas (or name them). No new installs.
TEST      For <these exact inputs> the answer is <value>, computed by hand:
          <one line of working>. Also: <an edge case> must give <NaN / an error>.
STYLE     Under 25 lines; comments say why, not what; print one number at the end.
ASK       Before writing code, restate the task in two sentences and list any
          assumption you had to make.
```

A filled-in *TEST* line for a flight-time height function reads: “For 30
frames at 60 fps the answer is 30.7 cm: $t=0.5$ s, $9.81\times0.5^2/8=0.307$ m.
A frame rate of 0 must raise an error.” The last instruction, *ASK*, is
worth its line: an assistant that restates the task wrongly has told you, before
any code exists, that the specification was unclear.

\paragraph{Verify, in order.} Run your test. Read the code line by line and say
what each line does to the data. Feed it the edge case. Check one real result a
second way: by hand, with the app, or with a different library. Only then use it
on the athlete's file.

## A.5 The Prompt Log

Keep a prompt log with every notebook and hand it in with the work. It shows a
reviewer, and you a month later, which choices were yours. One row per exchange
is enough (Table A.2).

*Table A.2. A prompt log, with one filled row.*

| Date, cell | What I asked (or the spec I gave) | What came back | What I checked and changed | Kept? |
|---|---|---|---|---|
| 2027-01-16, cell 3 | Spec for a centered 5-point moving average with NaN at the ends; my hand test | Used `np.convolve(, mode="same")` | Test failed at sample 1 (73.4, expected NaN); asked for NaN edges; test passes | Yes, v2 |

Record also which assistant and which data you gave it (“column names and five
invented rows”), and any source it named. A source an assistant cites is a lead,
not a reference: open it before you cite it, and drop it if it does not exist or
does not say what was claimed.

## A.6 Before You Paste: De-identification

An outside AI service, a hosted notebook and a shared drive all put data on
someone else's computer, where you cannot delete it later. Before any athlete's
data goes there, run this checklist. If you are unsure about a line, leave the
data out; the assistant rarely needs real values to write code.

- **Do you need real data at all?** For writing or fixing code, paste the
  column names and five invented rows instead.

- **Consent.** The athlete agreed to this use, including an outside
  service (Appendix E). If not, stop here.

- **Names and codes.** Replace names, initials, jersey numbers and
  student numbers with a study code (A01, A02\ldots). Keep the key that links
  codes to people offline, apart from the data.

- **File names and headers.** Rename files that carry a name or a
  date, such as jordan_2027-01-15.csv; check the Markdown results' *Analysis*
  table and any report text for a name, height, age or body mass.

- **Dates and times.** Shift every time stamp by one fixed offset, or keep
  only elapsed time. Exact dates with a sport and a team can identify a person.

- **Places.** Delete or trim route start and end points from GPS tracks;
  never paste a home address or a training location.

- **Faces and bodies.** No photographs or video frames of an identifiable
  person. Keypoint coordinates are much safer than images.

- **Health and body data.** Leave out heart rhythm, body mass, glucose,
  injury and medical notes unless the task cannot be done without them, and then
  only with the athlete's specific agreement.

- **Small groups.** A summary of three athletes can still point to one of
  them. Report groups of five or more, or ask.

- **The service's terms.** Know whether the service keeps or trains on what
  you paste, and follow your institution's rules on approved tools.

- **Log it.** Note in the prompt log what you shared and why.
