apopt.comCBE 493R Data-Driven Athletics

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.

  1. 1Gather (used)
  2. 2Statistics
  3. 3Visualize
  4. 4Cleanse
  5. 5Features
  6. 6Balance
  7. 7Scale
  8. 8Split
  9. 9Deploy (used)
  1. Ask
  2. Collect
  3. Check
  4. Interpret (this week)
  5. Coach (this week)
  6. Reassess

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?

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

Data dictionary
FieldMeaningUnitRangeMissing
frameframe number from 0count0–463none
ttime in the clips0–15.4none
l_ankle_x, r_ankle_xhorizontal ankle positionpixels from the left edge387–703none
l_ankle_y, r_ankle_yvertical ankle position; larger is lower in the imagepixels from the top1136–1688none
l_ankle_c, r_ankle_cthe pose model's confidence0 to 10.68–1.00none

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.

PythonStep 1 · From an ankle trace to a table of foot plants

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:

PythonStep 9 · The force function in Python, rules first

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).

PythonStep 9 · Eight cases, expected answers first

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.

PythonStep 9 · Python against JavaScript, cases and plants

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.

PythonStep 9 · The same steps, as a file and as a stream

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)
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.

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:

<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

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 --test after 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.

Open your athlete record

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

  1. Why does the function return a value and a message, instead of only a number?

  2. 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?

  3. 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?

    body weights

  4. Where should the page's files live so an athlete can open it on a phone?

  5. Why is the blank-cell trap found by comparing the two languages and not by the Python tests alone?

0 of 5 answered · 0 right the first time

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).

Hand in

How it is judged

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

    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.