Course / Tutorials / Week 12 / CS-17
Case study CS-17 · Week 12 · about 60 min · Core
From a notebook to a page an athlete can open
Move the foot-plant force formula out of a notebook into a JavaScript function that refuses bad input, prove the Python and JavaScript versions agree on normal, missing and invalid cases and on 44 real foot plants, compare a file analysed afterwards with a stream read step by step, and specify the phone page.
- Ask
- Collect
- Check
- Interpret (this week)
- Coach (this week)
- Reassess
Download notebook ·Python file ·Read as Markdown ·Data folder ·Chapter 12 (sections 3.7.2, 12.1, 12.2, 12.4.4, 12.6, 12.9)
5 of 6 cells run in this page. The rest need a model that does not run in the browser: run them in the notebook on your computer or in Colab (File → Upload notebook); their output from the course build is shown, and the files they write are published so the later cells still run here. Helpful first: Q-34 A calculation in a web page, Q-35 Three tests: normal, missing, invalid.
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?
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 clipform1_30fps.mp4with 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.
Step by step
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.
Type a prediction to enable Run.
Show the expected result without running
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).
Type a prediction to enable Run.
Show the expected result without running
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:
// 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).
Show the expected result without running
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.
Step 9 · Run force.js with Node.js on the same inputs
Runs in the notebook (needs a model that does not run in the browser). Output from the course build:
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())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.
Type a prediction to enable Run.
Show the expected result without running
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.
Show the expected result without running
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)

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 anhttpsaddress, and the address is printed as a QR code for the athlete (Section 12.9). The tests inforce.test.jsrun withnode --testbefore every upload.
<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.
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.
- How 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.
- Test again
- Run the eight tests with
node --testafter every change to the page, before it is copied online.
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.
Check the AI
Asked to "turn the force function into JavaScript for a page", an assistant wrote:
> ``js > export function footForce(contactS, flightS) { > if (contactS <= 0) return { value: null, message: 'Contact must be positive.' }; > return { value: (Math.PI / 2) * (1 + flightS / contactS), message: null }; > } > `` > It handles bad input: a zero or negative contact is refused.
What is wrong with it?
A missing flight time is not refused. Number("") is 0 in JavaScript, so a blank flight becomes a flight of zero and the page shows (π/2) = 1.6 body weights, a wrong number in a large font; a missing contact becomes 0 and is refused with the wrong message. The function needs the missing test first (Number.isFinite), and the page must turn a blank box into NaN, not 0.
Check yourself
Why does the function return a value and a message, instead of only a number?
A page reads steps live and shows a running mean of force. What can the batch analysis of the same file do that the stream cannot?
Contact 0.200 s and flight 0.133 s give 2.62 body weights. If the contact is one frame shorter at 30 frames per second and the step time is unchanged, what does the formula give?
Where should the page's files live so an athlete can open it on a phone?
Why is the blank-cell trap found by comparing the two languages and not by the Python tests alone?
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.
- Write the function in Python with its rules for missing and invalid input, and the messages in words a user can act on.
- 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.
- Run both on a real file from your project and report the largest difference and the number of refused rows.
- Say whether the use needs batch or streaming, and what the stream would lose.
- 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).
Hand in
- 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
How it is judged
- Missing and invalid input give a message and no number, in both languages (30%)
- The two versions agree on every case and on real data (30%)
- Batch or streaming chosen and justified (15%)
- A specification an athlete-facing page can be built from (25%)
Hints
The solution unlocks after you make an attempt. Comparing your own attempt with it is where the learning happens.
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.
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).
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 (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.
Built 2026-11-30 with Python packages numpy 2.5.5, pandas 3.1.1, matplotlib 3.11.2, scipy 1.18.1. In the browser the same code runs on Pyodide, so the last digit can differ.