# Q-34: A calculation in a web page

Data-Driven Athletics tutorial · Week 12 · Chapter 12 · about 15 min · workflow steps: Deploy

Web page: https://apopt.com/course/tutorials/q34-calc-web-page/ · Data: https://apopt.com/data/tutorials/q34-calc-web-page/

## The decision

Before a calculation goes into a page an athlete will open, check that the page's JavaScript
gives the same numbers as the Python you trusted, on cases whose answers you know.

## The raw data

- `raw/test_cases.csv`: three typed test cases (contact and flight time in seconds), not a recording: two from the book's running examples and one short sprint contact Typed for this tutorial from Chapter 3 (contact 0.25 s, step 0.349 s) and Chapter 9 (contact 0.200 s, stride 0.700 s).

A calculation reaches an athlete when it runs in a page on their phone. The Python cells on
this page already run in your browser: they use **Pyodide**, a version of Python compiled to
WebAssembly, so nothing is sent to a server. A page an athlete opens, though, is usually
written in **JavaScript**, the browser's own language, and loads in a fraction of a second.
So the same calculation is written twice, and the two must agree.

The calculation is the force of a foot plant from its timing (Section 3.7.2): over a step the
ground's push must average one body weight, and with a half-sine shape the peak is

F_peak / body weight = (π/2) × (1 + flight time / contact time).

### The Python version, on three test cases

The three cases were typed before any code was written, from the book's examples, so each has
a hand answer to check against.

*Predict first:* The book's runner has contact 0.25 s and flight 0.099 s. What peak force do you expect, in body weights?

```python
import math
import pandas as pd

def peak_force_bw(contact_s, flight_s):
    """Peak vertical force in body weights from one contact and the flight after it."""
    return math.pi / 2 * (1 + flight_s / contact_s)

cases = pd.read_csv("raw/test_cases.csv")
cases["python_bw"] = [peak_force_bw(c, f) for c, f in zip(cases["contact_s"], cases["flight_s"])]
print(cases[["case", "contact_s", "flight_s", "python_bw"]].round(4).to_string(index=False))
```

Output:

```
       case  contact_s  flight_s  python_bw
book runner       0.25     0.099     2.1928
course clip       0.20     0.150     2.7489
     sprint       0.10     0.120     3.4558
```

### The same function in JavaScript

This is what goes in the page. Read it line by line against the Python: `Math.PI` is `math.pi`,
and `export` lets the page and a test file import it.

```js
// force.js: peak force of a foot plant, in body weights (Section 3.7.2)
export function peakForceBW(contactS, flightS) {
  return (Math.PI / 2) * (1 + flightS / contactS);
}
```

### Run the JavaScript on the same cases

This cell runs the JavaScript with Node.js, the JavaScript engine for a computer, so it is
marked to run on your computer, not in the page. It writes the answers to a file that the
next cell, back in the browser, compares with Python.

```python
import subprocess, os

JS = """export function peakForceBW(contactS, flightS) {
  return (Math.PI / 2) * (1 + flightS / contactS);
}"""
CHECK = """import { readFileSync, writeFileSync } from 'node:fs';
import { peakForceBW } from './force.mjs';
const rows = readFileSync('raw/test_cases.csv', 'utf8').trim().split('\\n').slice(1);
const out = rows.map((r) => { const [name, c, f] = r.split(',');
  return `${name},${peakForceBW(Number(c), Number(f))}`; });
writeFileSync('clean/force_js.csv', 'case,js_bw\\n' + out.join('\\n') + '\\n');"""
os.makedirs("clean", exist_ok=True)
open("force.mjs", "w").write(JS + "\n")
open("check_force.mjs", "w").write(CHECK + "\n")
run = subprocess.run(["node", "check_force.mjs"], capture_output=True, text=True)
print("node exit code", run.returncode, run.stderr.strip())
print(open("clean/force_js.csv").read().strip())
```

Output:

```
node exit code 0 
case,js_bw
book runner,2.1928316722056755
course clip,2.748893571891069
sprint,3.455751918948773
```

### Do they agree?

*Predict first:* How large do you expect the largest difference between the two languages to be?

```python
import matplotlib.pyplot as plt

js = pd.read_csv("clean/force_js.csv")
both = cases.merge(js, on="case")
both["difference"] = both["js_bw"] - both["python_bw"]
print(both[["case", "python_bw", "js_bw", "difference"]].to_string(index=False))
print("largest difference:", both["difference"].abs().max())

ratio = [r / 100 for r in range(0, 141)]
fig, ax = plt.subplots(figsize=(5.6, 3.2))
ax.plot(ratio, [peak_force_bw(1, r) for r in ratio], "-", color="black", label="Python")
ax.plot(both["flight_s"] / both["contact_s"], both["js_bw"], "s", ms=8, mfc="white", mec="black", label="JavaScript, 3 cases")
ax.set(xlabel="flight time / contact time", ylabel="peak force (body weights)",
       title="Two languages, one answer")
ax.legend()
plt.tight_layout()
```

Output:

```
       case  python_bw    js_bw  difference
book runner   2.192832 2.192832         0.0
course clip   2.748894 2.748894         0.0
     sprint   3.455752 3.455752         0.0
largest difference: 0.0
```

![Peak force in body weights against the ratio of flight to contact time; a solid line for the Python function and open squares for the JavaScript answers on three cases, which sit on the line.](https://apopt.com/course/tutorials/q34-calc-web-page/c05-1.png)

Both languages use the same 64-bit floating-point numbers, so for a formula this simple the
answers agree to every printed digit. For longer calculations they can differ in the last
digit or two, so tests compare with a tolerance, such as 0.0001 body weights, not with `==`.

**For the athlete:** "The page on your phone uses the same formula we checked here: with
a 0.25 s contact and a 0.1 s flight, each foot plant pushes about 2.2 times your body weight."

## References

- Pyodide documentation: [Pyodide](https://pyodide.org/en/stable/), a Python distribution for the browser and Node.js based on WebAssembly.
- 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 sine-wave model of the force–time curve from contact and flight time.)

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