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

> Hedengren, J. (Ed.) (2027). Appendix F: Data Formats. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 491–497). IRSRI Sports Research Institute. CC BY 4.0.

# F Data Formats

This appendix describes the files you will read and write in the course: the
movement apps' text and JSON results, the Heart app's CSV, activity files from
watches, the standard Bluetooth heart-rate message, video files and their frame
rates, and the conventions for CSV files and time stamps. For each it gives the
layout, the units and the conversion that is easiest to get wrong.
Listing F.1 in Section F.6
checks every conversion with one printed number. The last two sections give a
data dictionary template, filled in for the Heart app's CSV, and the addresses
at which the book's own data files are published.

## F.1 The Movement Apps' Results

### F.1.1 File names

An app run on one video, from its own page, offers a PDF report, a highlight
video (MP4) and the text results, which download as
`<video>-results.md`. The process-a-folder page (`automation.html`
in each app's folder) writes four files beside each video, in this order:
`results_<video>.mp4`, `.pdf`, `.md` and, last, the
`.json` receipt. Because the receipt is written last, a folder in which it
exists has a complete set. The page reads MP4, MOV, M4V and WebM files; it skips
files whose names begin with `results_`, refuses two videos with the same
base name, and never overwrites existing results.

### F.1.2 Text results (Markdown)

The `.md` file has one layout for every app, so a person, a spreadsheet
or an AI assistant can read any of them. Its parts, in order:

- A title line, `# <App title> results`.

- A hidden marker,
  `<!– irsri-results app=<app> format=markdown version=1 –>`, naming the
  app (the same word as its folder and web address) and the format version.

- **Analysis**: a two-column table, *Setting | Value*. It always
  starts with *Generated*, in UTC to the minute
  (`2027-01-22 16:09 UTC`), and the video name, then the settings the
  numbers depend on: view, frame rate, athlete height, model.

- **Summary**: a bulleted list of headline lines.

- **Focus areas**: a numbered list; each has a value and, when the app
  has them, *Target*, *Why*, *Cue* and *Drill* lines.

- **Metrics**: a rating legend, then a table with the columns
  *Section | Metric | Value | Rating | Target*, or without *Rating* when
  no metric is rated.

- Optional extra tables (event timelines, per-repetition tables), each under
  its own heading.

- **Metric details**: one block per metric with detail, target and
  coaching notes.

- **Notes**: warnings about this clip.

- A rule (`—`) and the line *“Measured from a single video in
  the browser; treat values as estimates, not clinical measurements.”*

- From the process-a-folder page only, **Batch processing**: the
  analyzed time range in seconds and the warnings of the run.

Three rules make the table cells predictable. A cell's text is on one line, and a
`|` inside it is written `\textbackslash|`. An empty cell is written
`-`. A value carries its unit as text, sometimes in two systems
(`32.9 cm / 13.0 in`), and reads `N/A` when the clip could not
measure it. The rating is one of *Elite (3/3)*, *Pro (2/3)*,
*Good (1/3)* or *N/A*; the legend in the file says what they mean:
Elite is within the target range, Pro close to it, and *Good* furthest from
it. A few apps print their own word (for example *Reported*) instead of a
rating.

### F.1.3 The JSON receipt

The receipt holds no measurements. It records how the analysis was run
(Table F.1); Chapter 4 prints a complete
one.

*Table F.1. Fields of the `results_<video>.json` receipt.*

| Field | Meaning |
|---|---|
| `version`, `savedAt` | format version (1); when the files were saved, ISO 8601 in UTC |
| `id`, `state`, `stage`, `progress` | job identifier; `succeeded`; `Saved`; 1 when finished |
| `input` | the video's file name |
| `options` | the settings used; every app has `captureFps` (`"auto"` or a number from 1 to 2000), the rest are the app's own (height, view, model) |
| `sourceFps` | the rate read from the video file's header, or `null` |
| `actualCaptureFps` | the rate the analysis used for every time and speed |
| `analyzedRange` | `start` and `end` of the analyzed part, in seconds |
| `warnings` | list of warning sentences |
| `outputs` | name and size in bytes of the `mp4`, `pdf` and `md` files |

\paragraph{The same results, for programs.} When an app shows results, the page
also holds the Markdown in the `window.irsriResults` object and marks the
page with `data-results-ready="true"`. Each process-a-folder page publishes
`window.apoptAutomation`, version 1, with the calls
`capabilities()`, `start(options)`, `getJob(id)`,
`markdown(id)`, `download(id, format)` and `cancel(id)`. It
runs one job at a time and keeps only the latest, all in the browser; no file
is sent anywhere.

## F.2 Heart App CSV

The Heart app reads one or more CSV files, or a ZIP of them (Chapter 5),
with the header `time,ecg,hr,rr,marker`. One row is one ECG sample,
about 130 a second:

```text
time,ecg,hr,rr,marker
1800000000000000000,0.154,,,
1800000000007699036,0.220,,,
1800000000015398072,0.392,75,800,
```

- `time` is Unix time in *nanoseconds*, 19 digits for current dates.
  The app measures the sample rate from these stamps rather than assuming it;
  $10^9$ divided by the median spacing of 7699036 ns is 129.9 Hz.

- `ecg` is the voltage in millivolts. The app also accepts a column
  named `ecg_uv` in microvolts, and time columns named
  `timestamp_ns`, `timestamp_ms` or `timestamp_s`.

- `hr` and `rr` are the strap's own heart rate and beat-to-beat
  interval, filled only on the rows where the strap reported them. Both logger
  files and the app's own Live Capture export give `rr` in milliseconds;
  Live Capture keeps the strap's exact value, `799.8046875` for 819 ticks
  of 1/1024 second. An earlier version of Live Capture wrote seconds
  (`0.7998046875`), so check the size of the numbers in an older file:
  about 1000 is milliseconds, about 1 is seconds. The analysis itself ignores
  both columns and finds its own beats in the ECG.

- `marker` is usually empty.

A Live Capture with motion also saves a second file, `<name>_motion.csv`,
whose comment lines begin with `#` (format, rate, range), followed by the
header `time,x_g,y_g,z_g`: acceleration in units of $g$ on each axis.
Pass `comment="#"` to `pd.read_csv` to skip them. The app's
outputs are a PDF report, a Markdown summary written for an AI assistant, with
no raw ECG in it, and a breathing CSV.

## F.3 Activity Files: FIT, GPX and TCX

Watches, bike computers and phone apps export a session in one of three common
formats. All three hold a sequence of time-stamped *records* (position,
distance, heart rate, cadence, power, altitude); they differ in encoding.

- **GPX**  (GPS Exchange Format) is XML text. A track holds segments of
  `<trkpt lat="40.18" lon="-111.65">` points, each with `<ele>` in
  meters and `<time>` in ISO 8601 UTC. Positions are decimal degrees.
  Heart rate and cadence, when present, sit in *extension* elements whose
  names vary by maker. GPX has no distance field: distance is summed from the
  positions.

- **TCX**  (Training Center XML) is XML text organized as activity, laps and
  `<Trackpoint>`s, each with `<Time>`, a `<Position>` in
  decimal degrees, `<AltitudeMeters>`, `<DistanceMeters>`
  (cumulative) and `<HeartRateBpm><Value>`. Laps carry totals.

- **FIT**  (Flexible and Interoperable Data Transfer) is a compact binary format.
  A file is a sequence of messages: a *file_id*, many *record*
  messages (often one a second, or only when something changes), *lap* and
  *session* summaries, and device and event messages. Read it with a
  library (`fitdecode` in Python), not by hand.

Three FIT conventions catch people out.

- **Positions are in semicircles**, a 32-bit integer in which $2^{31}$
  is 180 °: degrees $=$ semicircles $\times180/2^{31}$. A stored
  latitude of 479 409 000 is 40.18 °.

- **Time starts in 1989.** A FIT time stamp counts seconds from
  1989-12-31 00:00:00 UTC, which is 631 065 600 seconds after the Unix epoch
  of 1970-01-01. Add 631 065 600 to get Unix time; a FIT stamp of
  1 100 000 000 is 2024-11-08 11:33:20 UTC.

- **Running cadence is per leg.** FIT stores strides a minute for one
  foot; steps a minute are twice the stored value. The Watch dashboard doubles
  it. Other fields are stored as scaled integers (distance in centimeters, speed
  in millimeters a second), which libraries convert for you; check the units the
  library reports.

The Watch dashboard reads FIT, GPX and TCX. For FIT files it reports the
device's own distance; for GPX files it sums the distance between successive
points with the haversine formula; for TCX files it uses the file's
`DistanceMeters` and sums positions only where that field is missing. Two points 0.0001 ° of latitude
apart are 11.1 m apart.

> **Limits and cautions: A track is a home address.**
> 
> The first and last points of a run are often a home or a dormitory. Trim them
> before sharing a file, and never paste raw positions into an outside service
> (Appendix A).

## F.4 The Bluetooth Heart-Rate Message

Every chest strap and many watches offer the standard Bluetooth
*heart-rate service* (`0x180D`). Its Heart Rate Measurement
characteristic (`0x2A37`) sends a short message with each update
(Chapter 5), shown in Table F.2.

*Table F.2. The heart-rate measurement message (`0x2A37`). Multi-byte values are little-endian: low byte first.*

| Bytes | Content |
|---|---|
| 0 | flags. Bit 0: heart rate is 2 bytes (else 1). Bits 1–2: skin contact detected; contact detection supported. Bit 3: energy-expended field present. Bit 4: RR intervals present. |
| 1, or 1–2 | heart rate, bpm |
| next 2, if bit 3 | energy expended, kilojoules |
| the rest, if bit 4 | one or more RR intervals, 2 bytes each, oldest first, in units of **1/1024 second** |

The message `10 4B 33 03` (hexadecimal) has flags `0x10`: an 8-bit
rate and RR present. The rate is `0x4B`, 75 bpm. The RR value is
`0x0333` $=819$ ticks, which is $819\times1000/1024=\SI{799.8}{\milli\second}$.
Reading 819 as milliseconds overstates every interval by 2.4%.

## F.5 Video Files and Frame Rates

Phone video comes in an *MP4* or *MOV* file. Both are containers built
of nested *boxes*: the pictures, compressed by a codec, sit in one box; the
timing, in others (Chapter 8). The video track's media header
(`mdhd`) gives a *timescale*, clock ticks per second, and its
time-to-sample table (`stts`) gives how many ticks each frame lasts. The
stored frame rate is the number of frames times the timescale divided by the
total ticks; a file with a timescale of 600 and 20 ticks a frame is stored at
$600/20=\SI{30}{\fps}$. Some phones vary the frame length within a clip
(variable frame rate); the formula then gives the average.

Keep the two rates of Chapter 8 apart:

- the *stored frame rate* is the playback clock written in the header;

- the *capture frame rate* is the rate the camera recorded at.

A slow-motion clip filmed at 120 fps is usually stored at
30 fps. Real time is file time $\times f_\text{stored}/f_\text{capture}$.
The apps read the stored rate from an MP4 or MOV header, use 60 fps if
they cannot read one (WebM files, for example), and accept an override of 24, 25,
30, 50, 60, 120, 240, 480, 960 or 1000 fps. The receipt records both
`sourceFps` and `actualCaptureFps`; check them. In Python, OpenCV's
`cv2.VideoCapture(path).get(cv2.CAP_PROP_FPS)` returns the stored rate.

## F.6 CSV Files and Time Stamps

A CSV file you write for this course should follow seven conventions, so that
anyone, and any program, can read it without asking you:

- One header row of short lowercase names with the unit in the name:
  `time_utc`, `hr_bpm`, `height_cm`.

- One row per observation and one column per variable (tidy data,
  Chapter 4).

- Commas between fields, a point as the decimal mark, no thousands
  separators, UTF-8 text.

- Missing values left empty, never `0` or `-999`.

- Numbers without units or symbols in the cells.

- Times in ISO 8601 with the zone: `2027-01-15T23:50:00Z`, where
  `Z` means UTC; or a number of seconds from a stated start.

- A short note beside the file (a README) saying what each column is, how
  the data were collected and what was removed.

Time stamps come in six forms. Table F.3 shows how
to recognize and read each one. A time with no zone is *naive*; decide its
zone once, from the device's settings, and convert to UTC before you join two
files.

*Table F.3. Recognizing a time stamp, and reading it with pandas.*

| Form | Looks like | Read with |
|---|---|---|
| ISO 8601 text | `2027-01-15T23:50:00Z` | `pd.to_datetime(s, utc=True)` |
| Unix seconds | 10 digits, `1800000000` | `pd.to_datetime(s, unit="s", utc=True)` |
| Unix milliseconds | 13 digits | `unit="ms"` |
| Unix nanoseconds | 19 digits (Heart CSV) | `unit="ns"` |
| FIT seconds | 10 digits, about 20 years behind Unix | add 631 065 600, then `unit="s"` |
| Elapsed seconds | `0.000`, `0.0333` | relative to a start you record |

Listing F.1 checks the conversions of this appendix,
one printed number each: semicircles to degrees, the FIT epoch, a FIT time stamp,
the heart-rate message, the Heart CSV sample rate, the distance and time between
two GPX points, and a stored frame rate from the timescale.

**Listing F.1.** The conversions of this appendix (`appF-formats/code/f01_units.py`)

```python
# the unit conversions of Appendix F, each with one number to check
from datetime import datetime, timezone, timedelta
import pandas as pd, gpxpy

print(round(479_409_000 * 180 / 2**31, 2))              # FIT semicircles -> degrees
fit_epoch = datetime(1989, 12, 31, tzinfo=timezone.utc)
print(int(fit_epoch.timestamp()))                        # FIT epoch in Unix seconds
print(fit_epoch + timedelta(seconds=1_100_000_000))      # a FIT timestamp, in UTC

msg = bytes([0x10, 0x4B, 0x33, 0x03])                    # flags, HR, one RR (little-endian)
flags = msg[0]
hr = int.from_bytes(msg[1:3], "little") if flags & 0x01 else msg[1]
rr_raw = int.from_bytes(msg[2:4], "little")              # RR follows an 8-bit HR
print(flags & 0x10 > 0, hr, rr_raw, round(rr_raw * 1000 / 1024, 1))

ecg = pd.read_csv("data/heart_head.csv")
t = (ecg.time - ecg.time.iloc[0]) / 1e9                  # ns -> s from the start
print(round(1 / t.diff().median(), 1))                   # sample rate, Hz

gpx = gpxpy.parse(open("data/track.gpx"))
pts = gpx.tracks[0].segments[0].points
print(round(pts[0].distance_2d(pts[1]), 1), (pts[1].time - pts[0].time).seconds)
print(600 / 20)                                          # timescale / ticks per frame
```

```text
40.18
631065600
2024-11-08 11:33:20+00:00
True 75 819 799.8
129.9
11.1 3
30.0
```

## F.7 A Data Dictionary Template

A *data dictionary* is the table that travels with a data file and says,
for every column, what it means and what values it may hold.
Chapter 4 introduces it (Section 4.2.5) and
turns it into checks a program can run. Every dictionary has the same six
columns:

- **Field**  the column name exactly as it appears in the header.

- **Meaning**  what was measured, in one plain phrase, and by what.

- **Unit**  the physical unit, or “none”.

- **Type**  integer, decimal, text, or a time stamp and its form
  (Table F.3).

- **Allowed range**  the values you accept without question; anything outside
  is flagged, not silently deleted.

- **Missing code**  how a missing value is written. Prefer an empty cell; never
  `0` or `-999`, which a program reads as a number.

Table F.4 fills it in for the Heart app's CSV of
Section F.2. The ranges for `hr` and
`rr` are the checks used in Chapter 4 and Chapter 5;
they are choices for screening training data, not physiological limits.
Copy the table, replace the rows, and keep it in the README beside the file.

*Table F.4. A data dictionary for the Heart app CSV.*

| Field | Meaning | Unit | Type | Allowed range | Missing code |
|---|---|---|---|---|---|
| `time` | time of the ECG sample, UTC | ns since 1970-01-01 | integer, 19 digits | strictly increasing; median spacing about 7.7 ms (130 Hz) | never missing; drop a row without it |
| `ecg` | voltage across the strap's electrodes | mV | decimal | no fixed limit; flag flat stretches (strap off the skin) | empty |
| `hr` | the strap's own heart rate | bpm | integer | 30 to 220 | empty (most rows; a zero is written empty) |
| `rr` | the strap's beat-to-beat interval | ms (older Live Capture files: s) | decimal | 300 to 2000 | empty (most rows) |
| `marker` | a note or event label | none | text | any | empty (usual) |

## F.8 The Book's Data Online

Every data file a listing reads is published at an address built from the
chapter's folder name and the file's name:

`apopt.com/data/book/<chapter-folder>/<file>`

The example run of Chapter 6, which its listings read as
`data/run.csv`, is therefore
`apopt.com/\allowbreak data/\allowbreak book/\allowbreak ch06-gps-motion/\allowbreak run.csv`, and an appendix file
uses the appendix's folder in the same way. pandas reads such an address
directly: put `https://` in front and pass it to `pd.read_csv` in
place of the local path. The de-identified athlete case files are described at
`apopt.com/data/athletes`.

Two files describe the whole collection. The *catalog*,
`apopt.com/data/catalog.json`, lists the published files in a form a
program can read. `apopt.com/data/llms.txt` is a plain-text guide to the
collection written for AI assistants. Start from the catalog when you write
code that loops over files, and from `llms.txt` when you ask an assistant
for help.

\paragraph{Handing a file to an AI assistant.} For a published file, give the
assistant the address, not the contents. A short message such as “Read
`apopt.com/\allowbreak data/\allowbreak book/\allowbreak ch06-gps-motion/\allowbreak run.csv`; the guide is at
`apopt.com/data/llms.txt`; plot speed against time” gives it the file,
its documentation and the task, and you can check its answer against the
book's printed output. An assistant that cannot open web addresses will say
so; then paste the first few rows and the data dictionary instead. Your own
recordings are different: they are not published and should not be. Do not
paste a private file into an assistant. Give it the data dictionary and a
published or synthetic file with the same columns, have it write the code, and
run that code on your own data on your own computer
(Section A.6 lists what to remove first if you must
share any of it).
