# Q-16: Open an activity file and list its fields

Data-Driven Athletics tutorial · Week 6 · Chapter 6 · about 15 min · workflow steps: Gather, Statistics, Visualize

Web page: https://apopt.com/course/tutorials/q16-activity-fields/ · Data: https://apopt.com/data/tutorials/q16-activity-fields/

## The decision

A runner sends a watch file and asks for a pace. Before any pace, find out what the file
holds, in which units, and whether the watch was paused.

## The raw data

- `raw/2026-05-14_0726_running_nogps.fit`: the instructor's FIT file of a 5.9 km run on 14 May 2026, as the watch wrote it except that every position value is blanked (FIT's "no value" code), 76,615 bytes The instructor's own watch, published under his name. `prepare.py` blanks the 3,604 position values, recomputes the file's checksum, and checks that no coordinate is left.

A running watch saves each run as a FIT file: compact, binary, and unreadable in a text
editor. This one is the instructor's run of 14 May 2026, the example run of Chapter 6, as his
watch wrote it, except that every position value has been blanked (set to FIT's "no value"
code) so the file shows no route. You will open it, list what it holds, and save it as plain
tables.

### Read the binary file

The first cell needs the `fitdecode` package, which does not run in a web page, so it runs on
your computer or in Colab (`pip install fitdecode`). It writes three CSV files under `clean/`;
the cells after it run here, in the page, from those files.

*Predict first:* The run took about 30 minutes of running. If the watch writes one record a second, how many records do you expect?

```python
# Needs fitdecode (pip install fitdecode); runs on your computer or in Colab.
import os
import warnings
import fitdecode
import pandas as pd

warnings.simplefilter("ignore")                       # the watch writes one odd field definition
rows, fields, session = [], {}, {}
with fitdecode.FitReader("raw/2026-05-14_0726_running_nogps.fit") as fit:
    for m in fit:
        if not isinstance(m, fitdecode.FitDataMessage):
            continue                                  # skip headers and definitions
        for f in m.fields:
            key = (m.name, f.name)
            n, unit, ex = fields.get(key, (0, f.units, None))
            fields[key] = (n + (f.value is not None), unit, ex if ex is not None else f.value)
        if m.name == "record":
            rows.append({f.name: f.value for f in m.fields})
        elif m.name == "session":
            session = {f.name: f.value for f in m.fields}
os.makedirs("clean", exist_ok=True)
table = pd.DataFrame([(a, b, n, u, ex) for (a, b), (n, u, ex) in fields.items()],
                     columns=["message", "field", "values", "units", "example"])
table.to_csv("clean/fields.csv", index=False)
pd.DataFrame(rows).dropna(axis=1, how="all").to_csv("clean/records.csv", index=False)
pd.Series(session).to_csv("clean/session.csv", header=["value"])
print(table.groupby("message")["field"].count().to_string())
```

Output:

```
message
activity              7
developer_data_id     3
device_info           3
event                 5
field_description     5
file_id               5
lap                  27
record               18
session              27
```

Nine kinds of message. Most of the file is `record` messages, one per sample; `lap` and
`session` messages are the watch's own summaries; `event` messages mark the timer starting
and stopping. The position fields come out empty, so `dropna` leaves them out of the records
table.

### List the fields of a record

```python
import pandas as pd

fields = pd.read_csv("clean/fields.csv")
rec = fields[fields["message"] == "record"].drop(columns="message")
print(rec.to_string(index=False))
```

Output:

```
               field  values       units                   example
       activity_type    1803         NaN                   running
           timestamp    1803         NaN 2026-05-14 13:26:48+00:00
            distance    1803           m                       0.0
        position_lat       0 semicircles                       NaN
       position_long       0 semicircles                       NaN
          heart_rate    1802         bpm                        81
      enhanced_speed    1796         m/s                     1.547
               speed    1796         m/s                     1.547
         stance_time    1796          ms                       0.0
vertical_oscillation    1796          mm                       0.0
      vertical_ratio    1796     percent                       0.0
         step_length    1796          mm                     810.0
         Effort Pace    1796         m/s        1.5470000505447388
             cadence    1794         rpm                        75
               power    1794       watts                       115
   accumulated_power    1794       watts                       115
   enhanced_altitude    1783           m                    1445.0
            altitude    1783           m                    1445.0
```

Read the units column before anything else. Distance is in metres and speed in metres per
second, but `cadence` is in "rpm", one leg's steps a minute, so a runner's cadence is twice
it. `position_lat` and `position_long` have no values here; in a file straight from a watch they
are in semicircles (2³¹ of them make 180°), not degrees.

### Three facts before any analysis

*Predict first:* Will the time between the first and last record equal the watch's timer time?

```python
import matplotlib.pyplot as plt

rec = pd.read_csv("clean/records.csv", parse_dates=["timestamp"])
ses = pd.read_csv("clean/session.csv", index_col=0)["value"]
gaps = rec["timestamp"].diff().dt.total_seconds()
print(f"{len(rec)} records; gaps over 1 s: {gaps[gaps > 1].tolist()}")
print(f"first to last record {(rec['timestamp'].iloc[-1] - rec['timestamp'].iloc[0]).total_seconds():.0f} s; "
      f"watch timer {float(ses['total_timer_time']):.1f} s; distance {float(ses['total_distance']):.1f} m")
print(f"cadence field {float(ses['avg_running_cadence']):.0f} per leg -> {2 * float(ses['avg_running_cadence']):.0f} steps/min")

minutes = (rec["timestamp"] - rec["timestamp"].iloc[0]).dt.total_seconds() / 60
fig, ax = plt.subplots(figsize=(9, 3.2))
ax.plot(minutes, rec["enhanced_speed"], ".", ms=1.5, label="speed (m/s)")
ax2 = ax.twinx()
broken = rec["heart_rate"].where(gaps.shift(-1).fillna(1) <= 1)   # no line across a pause
ax2.plot(minutes, broken, "k-", lw=0.6, label="heart rate")
ax.set(xlabel="time from the first record (min)", ylabel="speed (m/s), dots")
ax2.set_ylabel("heart rate (beats/min), line")
plt.tight_layout()
```

Output:

```
1803 records; gaps over 1 s: [3787.0, 23.0]
first to last record 5610 s; watch timer 1801.7 s; distance 5880.5 m
cadence field 88 per leg -> 176 steps/min
```

![Speed in metres per second (dots) and heart rate in beats per minute (line) against minutes from the first record. A gap of about an hour, from minute 17 to minute 80, splits the run in two; speed sits near 3.3 to 3.6 m/s before and after it.](https://apopt.com/course/tutorials/q16-activity-fields/c05-1.png)

The watch was paused twice, once for more than an hour and once for 23 seconds, so the first
and last records are over 90 minutes apart while the watch ran for 30. Any pace computed from
the clock instead of the timer would be three times too slow. Chapter 6 (Section 6.3) reads
the same file and finds the same facts.

**For the athlete:** "Your watch file holds 1803 one-second records of speed, heart rate,
cadence and running dynamics; we saved them as plain tables and checked the pauses before
measuring anything."

## With your own data

Export the FIT file of one of your own runs from your watch's app, put it in `raw/`, change the
file name in the first cell and run it on your computer. Do not share a file that still has
positions in it: the `clean/records.csv` the cell writes keeps them if your watch recorded them,
so drop the `position_lat` and `position_long` columns before you share it.

## Action card

- **Finding:** The file holds 1803 one-second records in nine kinds of message; the watch was paused twice.
- **Evidence:** Gaps of 3787 s and 23 s between records; timer 1801.7 s against 5610 s from first to last record.
- **Sure:** High; these are the watch's own fields and timestamps.
- **Action:** Compute pace from timer time and the watch's distance, and double the cadence field.
- **Retest:** Run the same three checks on every new file before analysing it.

## References

- *Data-Driven Athletics*, Chapter 6, Activity Files (Section 6.3): what a record holds, reading a FIT file, splits and pauses.
- fitdecode, a FIT file reader for Python: [github.com/polyvertex/fitdecode](https://github.com/polyvertex/fitdecode).

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