# CS-17: From a notebook to a page an athlete can open

Data-Driven Athletics tutorial · Week 12 · Chapter 12 · about 60 min · workflow steps: Gather, Deploy

Web page: https://apopt.com/course/tutorials/cs17-notebook-to-page/ · Data: https://apopt.com/data/tutorials/cs17-notebook-to-page/

## The decision

A runner wants to check the force of each foot plant on a phone after a filmed run, without
sending the video or the numbers anywhere. The calculation exists in a notebook. Decide whether
it is ready to go into a page: does the page's version give the same numbers, does it refuse
input it cannot use, and does it need the whole file or can it work step by step?

## Predict first

The same formula is written in Python and in JavaScript and run on 52 inputs: eight test cases, including missing and invalid ones, and 44 foot plants from a real clip. How many will disagree, and where would you expect a disagreement to come from?

## The raw data

- `raw/form1_ankles.csv`: the two ankles' image positions and confidences, frame by frame, for 15.5 s of treadmill running filmed from behind at 30 frames per second (464 frames) Book example data, Chapter 9 (`book/ch09-gait/data/form1_ankles.csv`), made from the course example clip `form1_30fps.mp4` with a YOLO pose model. Keypoints only; no image.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| frame | frame number from 0 | count | 0–463 | none |
| t | time in the clip | s | 0–15.4 | none |
| l_ankle_x, r_ankle_x | horizontal ankle position | pixels from the left edge | 387–703 | none |
| l_ankle_y, r_ankle_y | vertical ankle position; larger is lower in the image | pixels from the top | 1136–1688 | none |
| l_ankle_c, r_ankle_c | the pose model's confidence | 0 to 1 | 0.68–1.00 | none |

What is wrong with it, for this purpose: times come in whole frames (33 ms at 30 frames per
second), so every contact is 0.167, 0.200 or 0.233 s; the first contact begins on frame 0 and
may have started before the clip; and the last foot plant has no flight, because the clip ends
before the next foot lands. The function has to handle a missing value, and the page has to
say how much one frame matters.

Every case study so far ends in a notebook. An athlete will not open a notebook. This one
moves one calculation, the force of each foot plant from its timing (Section 3.7.2, CS-12),
into the form a phone page needs: a JavaScript function that refuses bad input, tested
against the Python version on the same normal, missing and invalid cases (Section 12.4.4).
Then it asks what changes when the same function reads a whole file afterwards (**batch**)
or one step at a time as it happens (**streaming**).

### Step 1 · Gather

The raw file is the book's ankle trace of a runner on a treadmill, filmed from behind at 30
frames per second (Chapter 9): one row per frame, with the image height of each ankle. A
contact is where the ankle sits lowest in the image (largest *y*); Chapter 9's percentile rule
finds it. Each contact is followed by a flight that ends at the other foot's next contact.

*Predict first:* About how many foot plants do you expect in 15.5 s of running at about 170 steps a minute?

```python
import os
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30.0
ank = pd.read_csv("raw/form1_ankles.csv")
rows = []
for side in "lr":
    y = ank[f"{side}_ankle_y"].rolling(3, center=True, min_periods=1).mean().to_numpy()
    hi, lo = np.percentile(y, 85), np.percentile(y, 70)       # bottom 15% and 30% of the foot's range
    for p in find_peaks(y, height=hi, distance=int(0.2 * FPS))[0]:
        i, j = p, p
        while i > 0 and y[i - 1] >= lo: i -= 1
        while j < len(y) - 1 and y[j + 1] >= lo: j += 1
        rows.append({"side": side, "first": i, "last": j})
plants = pd.DataFrame(rows).sort_values("first").reset_index(drop=True)
plants["contact_s"] = (plants["last"] - plants["first"] + 1) / FPS
plants["flight_s"] = (plants["first"].shift(-1) - plants["last"] - 1) / FPS   # to the next contact
plants["t_s"] = plants["first"] / FPS
os.makedirs("clean", exist_ok=True)
plants.to_csv("clean/foot_plants.csv", index=False)
print(f"{len(plants)} foot plants ({(plants['side'] == 'l').sum()} left, {(plants['side'] == 'r').sum()} right)")
print(plants.head(3).round(3).to_string(index=False))
print(plants.tail(2).round(3).to_string(index=False))
print("contact times seen (s):", sorted(float(v) for v in plants["contact_s"].round(3).unique()))
```

Output:

```
44 foot plants (22 left, 22 right)
side  first  last  contact_s  flight_s   t_s
   r      0     5        0.2     0.133 0.000
   l     10    15        0.2     0.133 0.333
   r     20    25        0.2     0.167 0.667
side  first  last  contact_s  flight_s    t_s
   r    444   450      0.233       0.2 14.800
   l    457   463      0.233       NaN 15.233
contact times seen (s): [0.167, 0.2, 0.233]
```

Three facts about this table decide how the function must behave. Times come in whole
frames, so a contact is 0.167, 0.200 or 0.233 s and nothing between. The first contact starts
on frame 0, so it may have begun before the clip did. And the last plant has no flight: the
clip ends before the next foot lands, so that value is **missing**.

### Step 9 · The function, with its rules

The page will receive numbers typed by a person or read from a file, so the function checks
its input before computing. It returns a value and a message, never a wrong number:

* **missing**: a contact or flight time is absent;
* **invalid**: times that look like milliseconds, a contact outside the 0.08 to 0.45 s that the
  running app accepts as a stance (Chapter 9), or a negative flight (feet overlapping, as in
  walking, where the model does not apply).

*Predict first:* The typical plant here is 0.200 s of contact and 0.133 s of flight. What force do you expect?

```python
import math

def foot_force(contact_s, flight_s):
    """Peak vertical force of one foot plant, in body weights, or a message saying why not."""
    if any(v is None or not math.isfinite(v) for v in (contact_s, flight_s)):
        return None, "Missing contact or flight time."
    if contact_s > 2:
        return None, "Times look like milliseconds; enter seconds."
    if not 0.08 <= contact_s <= 0.45:
        return None, "Contact time outside 0.08-0.45 s: not a running step."
    if flight_s < 0:
        return None, "Negative flight: the feet overlap, as in walking."
    return math.pi / 2 * (1 + flight_s / contact_s), None

out = [foot_force(c, f) for c, f in zip(plants["contact_s"], plants["flight_s"])]
plants["force_bw"] = [v for v, _ in out]
plants["message"] = [m for _, m in out]
print(plants.groupby("side")["force_bw"].agg(["count", "mean", "min", "max"]).round(2).to_string())
print("refused:", plants.loc[plants["force_bw"].isna(), ["side", "t_s", "message"]].to_string(index=False))
step = 0.200 + 0.133
print(f"one frame shorter contact, same step: {foot_force(0.200, 0.133)[0]:.2f} -> {foot_force(0.167, step - 0.167)[0]:.2f} BW")
```

Output:

```
      count  mean   min   max
side                         
l        21  2.56  2.24  2.88
r        22  2.76  2.47  3.14
refused: side       t_s                         message
   l 15.233333 Missing contact or flight time.
one frame shorter contact, same step: 2.62 -> 3.13 BW
```

The right foot reads about 0.2 body weights higher than the left on average. Before calling
that an asymmetry, look at what one frame does: the same step with a contact one frame
shorter reads about 20% higher, half a body weight. At 30 frames per second a left–right
difference of 0.2 is inside the frame budget of Chapter 9, and the page must say so (Step 9
below).

The same function in JavaScript, for the page. Each rule has the same words, in the same
order, so the two can be compared message for message:

```js
// force.js: peak force of one foot plant in body weights, or a message (Section 3.7.2)
export function footForce(contactS, flightS) {
  if (!Number.isFinite(contactS) || !Number.isFinite(flightS))
    return { value: null, message: 'Missing contact or flight time.' };
  if (contactS > 2) return { value: null, message: 'Times look like milliseconds; enter seconds.' };
  if (contactS < 0.08 || contactS > 0.45)
    return { value: null, message: 'Contact time outside 0.08-0.45 s: not a running step.' };
  if (flightS < 0) return { value: null, message: 'Negative flight: the feet overlap, as in walking.' };
  return { value: (Math.PI / 2) * (1 + flightS / contactS), message: null };
}
```

### Step 9 · Normal, missing and invalid: the tests

The expected behavior of each case is written down first. The normal case is the book's hand
calculation (contact 0.25 s, flight 0.099 s: 2.19 body weights).

```python
NAN = float("nan")
CASES = [  # name, contact_s, flight_s, expected value (or None), expected message start
    ("normal: book runner", 0.25, 0.099, 2.1928, None),
    ("normal: this clip", 0.200, 0.133, 2.6154, None),
    ("missing: no flight", 0.200, NAN, None, "Missing"),
    ("missing: no contact", NAN, 0.133, None, "Missing"),
    ("invalid: milliseconds", 200, 133, None, "Times look like milliseconds"),
    ("invalid: walking contact", 0.60, 0.10, None, "Contact time outside"),
    ("invalid: zero contact", 0.0, 0.10, None, "Contact time outside"),
    ("invalid: negative flight", 0.20, -0.05, None, "Negative flight"),
]
for name, c, f, want, msg in CASES:
    value, message = foot_force(c, f)
    if want is None:
        assert value is None and message.startswith(msg), name
    else:
        assert message is None and abs(value - want) < 1e-4, name
print(f"all {len(CASES)} Python tests pass")
pd.DataFrame(CASES, columns=["case", "contact_s", "flight_s", "want", "msg"]).to_csv("clean/cases.csv", index=False)
```

Output:

```
all 8 Python tests pass
```

### Step 9 · The same cases in JavaScript

Node.js runs the JavaScript on a computer; the page would run the same file in the phone's
browser. This cell writes `force.js`, feeds it the eight cases and every foot plant, and saves
the answers. One trap had to be handled in the test harness: in JavaScript, `Number("")` is
**0**, not "missing", so a blank cell would have passed as a zero contact. The harness turns a
blank cell into `NaN` first, as the page must.

```python
import subprocess

FORCE_JS = """export function footForce(contactS, flightS) {
  if (!Number.isFinite(contactS) || !Number.isFinite(flightS))
    return { value: null, message: 'Missing contact or flight time.' };
  if (contactS > 2) return { value: null, message: 'Times look like milliseconds; enter seconds.' };
  if (contactS < 0.08 || contactS > 0.45)
    return { value: null, message: 'Contact time outside 0.08-0.45 s: not a running step.' };
  if (flightS < 0) return { value: null, message: 'Negative flight: the feet overlap, as in walking.' };
  return { value: (Math.PI / 2) * (1 + flightS / contactS), message: null };
}"""
HARNESS = """import { readFileSync, writeFileSync } from 'node:fs';
import { footForce } from './force.mjs';
const num = (s) => (s === undefined || s.trim() === '' || s === 'nan' ? NaN : Number(s));  // blank is missing, not 0
const run = (file, a, b, key) => { const [head, ...rows] = readFileSync(file, 'utf8').trim().split('\\n');
  const h = head.split(','); return rows.map((r) => { const c = r.split(','); const o = footForce(num(c[h.indexOf(a)]), num(c[h.indexOf(b)]));
    return [c[h.indexOf(key)], o.value ?? '', JSON.stringify(o.message ?? '')].join(','); }); };
writeFileSync('clean/force_js_cases.csv', 'case,js_value,js_message\\n' + run('clean/cases.csv', 'contact_s', 'flight_s', 'case').join('\\n') + '\\n');
writeFileSync('clean/force_js_plants.csv', 'first,js_value,js_message\\n' + run('clean/foot_plants.csv', 'contact_s', 'flight_s', 'first').join('\\n') + '\\n');"""
open("force.mjs", "w").write(FORCE_JS + "\n")
open("run_force.mjs", "w").write(HARNESS + "\n")
done = subprocess.run(["node", "run_force.mjs"], capture_output=True, text=True)
print("node exit code", done.returncode, done.stderr.strip()[:200])
print(open("clean/force_js_cases.csv").read().strip())
```

Output:

```
node exit code 0 
case,js_value,js_message
normal: book runner,2.1928316722056755,""
normal: this clip,2.6153758841135026,""
missing: no flight,,"Missing contact or flight time."
missing: no contact,,"Missing contact or flight time."
invalid: milliseconds,,"Times look like milliseconds; enter seconds."
invalid: walking contact,,"Contact time outside 0.08-0.45 s: not a running step."
invalid: zero contact,,"Contact time outside 0.08-0.45 s: not a running step."
invalid: negative flight,,"Negative flight: the feet overlap, as in walking."
```

### Step 9 · Do the two languages agree?

Read the JavaScript answers back in the browser and compare them with Python, value by value
and message by message.

*Predict first:* How many of the 52 inputs (8 cases and 44 plants) will disagree?

```python
js = pd.read_csv("clean/force_js_cases.csv").fillna({"js_message": ""})   # no message: empty
py = [foot_force(c, f) for _, c, f, _, _ in CASES]
cmp = pd.DataFrame({"case": [c[0] for c in CASES], "py_value": [v for v, _ in py],
                    "py_message": [m or "" for _, m in py]}).merge(js, on="case")
same_msg = (cmp["py_message"] == cmp["js_message"]).sum()
dv = (cmp["py_value"].astype(float) - cmp["js_value"]).abs().max()
jp = pd.read_csv("clean/force_js_plants.csv").merge(plants, on="first")
dp = (jp["force_bw"] - jp["js_value"]).abs().max()
print(f"cases: {same_msg} of {len(cmp)} messages identical; largest value difference {dv:.1e} BW")
print(f"plants: {len(jp)} compared; largest difference {dp:.1e} BW; "
      f"refused by both: {int((jp['force_bw'].isna() & jp['js_value'].isna()).sum())}")
```

Output:

```
cases: 8 of 8 messages identical; largest value difference 0.0e+00 BW
plants: 44 compared; largest difference 0.0e+00 BW; refused by both: 1
```

Every value and every message agrees. That is what lets you put the JavaScript in the page and
keep the Python as the reference.

### Step 9 · Batch or streaming?

The notebook read the whole file afterwards: a **batch** analysis. It knew the clip's first
and last frames, could compute the median contact of the whole run, and could wait for the
next foot to land before computing a flight. A page that reads steps **as they happen**, from
a live camera or a sensor (the way the Heart app's live capture reads a chest strap), sees one
step at a time and never the future. Replay the plants in order to see the difference.

```python
import matplotlib.pyplot as plt

ok = plants.dropna(subset=["force_bw"])
batch_mean = ok["force_bw"].mean()
stream = ok["force_bw"].expanding().mean()            # what a live page could show at each step
median_batch = ok["contact_s"].median()
median_live = ok["contact_s"].shift(1).rolling(6, min_periods=6).median()   # past steps only
print(f"batch: {len(ok)} plants, mean {batch_mean:.2f} BW, median contact {median_batch:.3f} s")
print(f"stream: after 6 plants {stream.iloc[5]:.2f}, after 20 {stream.iloc[19]:.2f}, at the end {stream.iloc[-1]:.2f} BW")
print(f"stream has no contact baseline for the first {int(median_live.isna().sum())} plants; "
      f"each force is known one step late (it needs the next landing)")

fig, ax = plt.subplots(figsize=(6.6, 3.2))
for side, mk, fill in [("l", "o", "white"), ("r", "s", "black")]:
    d = ok[ok["side"] == side]
    ax.plot(d["t_s"], d["force_bw"], mk, mfc=fill, mec="black", ms=5, label="left" if side == "l" else "right")
ax.axhline(batch_mean, color="0.4", ls="--", label="batch mean (whole file)")
ax.plot(ok["t_s"], stream, "-", color="black", lw=1.5, label="streaming running mean")
ax.set(xlabel="time in the clip (s)", ylabel="peak force (body weights)",
       title="A stream settles on the file's answer; it cannot see ahead", ylim=(2.1, 3.45))
ax.legend(fontsize=8, ncol=2, loc="upper right")
plt.tight_layout()
```

Output:

```
batch: 43 plants, mean 2.66 BW, median contact 0.200 s
stream: after 6 plants 2.71, after 20 2.68, at the end 2.66 BW
stream has no contact baseline for the first 6 plants; each force is known one step late (it needs the next landing)
```

![Force of each foot plant in body weights against time, left as open circles and right as filled squares; a horizontal dashed line for the batch mean of the whole file and a solid line for the streaming running mean, which wanders at first and settles near the batch value.](https://apopt.com/course/tutorials/cs17-notebook-to-page/c11-1.png)

The two end at the same number, as they must. The stream's early answers wander, it cannot
judge a contact against a baseline until it has seen a few, and every force arrives one step
late. Choose by the question: a report after a session is a batch job; a cue
while running needs a stream, and a stream needs rules that use the past only.

### Step 9 · The page, described

Nothing here is put online; this is the specification of the page the athlete would open
(Section 12.1), built from the tested `force.js`:

* **One screen, Basic first** (Section 12.6). Two boxes, contact and flight time in seconds,
  or a dropped foot-plant table. Below them, one large number per foot, for example
  "Left 2.6, right 2.8 body weights", and one line: "A one-frame error at 30 fps changes this
  by about 20%."
* **Messages, never wrong numbers.** The three rules above, word for word.
* **Privacy.** The page is static files; the numbers never leave the phone. The footer says
  "Training information, not a medical assessment. Nothing is uploaded."
* **A link.** The folder (`index.html`, `force.js`, a stylesheet) is copied to any static host
  with an `https` address, and the address is printed as a QR code for the athlete (Section
  12.9). The tests in `force.test.js` run with `node --test` before every upload.

```html
<label>Contact time (s) <input id="contact" inputmode="decimal"></label>
<label>Flight time (s) <input id="flight" inputmode="decimal"></label>
<p id="result" role="status"></p>
<script type="module">
  import { footForce } from './force.js';
  const show = () => { const num = (id) => { const s = document.getElementById(id).value.trim(); return s ? Number(s) : NaN; };
    const r = footForce(num('contact'), num('flight'));
    document.getElementById('result').textContent = r.message ?? `${r.value.toFixed(1)} body weights`; };
  document.querySelectorAll('input').forEach((i) => i.addEventListener('input', show));
</script>
```

## How good is the number?

The two versions agree to every digit on all eight cases and all 44 foot plants, and give the
same eight messages; that checks the code, not the number. The number itself is modeled, not
measured (Section 3.7.2): vertical force only, no impact peak, and every error in the times
carried through. At 30 frames per second one frame is most of the error: the same step with a
contact one frame shorter reads 3.13 instead of 2.62 body weights, about 20% higher. So the
0.2 body-weight difference between the right foot (2.76) and the left (2.56) is inside what
one frame can do, and is not reported as an asymmetry.

## Track it

The page can add rows to the athlete record: `test=run-form-3.5, metric=peak_force_bw,
value, unit=BW, trial` (one row per foot plant or the session mean), with `device` (phone and
frame rate) and `note=modeled from contact and flight time`. Contact and flight time are
better kept as their own rows (`contact_time_s`, `flight_time_s`), because the force follows
from them.

## With your own data

Film your own run from behind or the side at the highest frame rate your phone offers, build
an ankle table with the pose step of Chapter 8 (or Q-24), and replace `raw/form1_ankles.csv`.
At 120 frames per second one frame is 8 ms, a quarter of the error here, and a left–right
comparison starts to mean something.

## The same method in another field

Moving a model from an analysis notebook into an application that people or machines call is
the deploy step of every data project, and the data can arrive in batches or as a continuous
stream. See the Machine Learning for Engineers page
[Deploy Machine Learning](https://apmonitor.com/pds/index.php/Main/DeployMachineLearning).

## Acknowledgements

The ankle table and the clip it came from are the book's Chapter 9 example data. The force model is the sine-wave model of Morin and colleagues (Section 3.7.2).

## Action card

- **Finding:** The force calculation is ready for a phone page; it agrees with the notebook and refuses what it cannot use.
- **Evidence:** Python and JavaScript agree on 8 test cases and 44 foot plants; the clip averages about 2.7 body weights per plant.
- **Sure:** High for the code; low for any left–right difference at 30 frames per second, where one frame moves the force by about 20%.
- **Action:** Open the page from the link on your phone after a filmed run; film at 120 frames per second if you want to compare your feet.
- **Retest:** Run the eight tests with `node --test` after every change to the page, before it is copied online.

## Challenge: Your calculation, on a phone

Choose one calculation from your own project or an earlier case study (a jump height from
flight time, an RMSSD, a typical error) and take it from the notebook to a page specification
the way this case study did.

1. Write the function in Python with its rules for missing and invalid input, and the messages in words a user can act on.
2. Write the same function in JavaScript, and run both on the same set of normal, missing and invalid cases, with the expected answers written first.
3. Run both on a real file from your project and report the largest difference and the number of refused rows.
4. Say whether the use needs batch or streaming, and what the stream would lose.
5. Write the one-screen specification of Section 12.1 for the page, including the "will not do" line, and test it with five users (homework P25).

Deliverables:

- a notebook that runs top to bottom, with the Node.js cell
- the JavaScript function and its test file
- a one-page specification of the page

## References

- Morin, J.-B., Dalleau, G., Kyröläinen, H., Jeannin, T., and Belli, A. (2005). A simple method for measuring stiffness during running. *Journal of Applied Biomechanics*, 21(2), 167–180. (The force–time curve modeled as a sine function from contact and flight time.)
- Machine Learning for Engineers: [Deploy Machine Learning](https://apmonitor.com/pds/index.php/Main/DeployMachineLearning) (data flow in batches or as a continuous stream).
- Chapter 12 of *Data-Driven Athletics*: Start from One Decision; Three Inputs Every App Must Survive; Basic First; Putting It Online.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
