# Files You Can Defend

Class 7, Chapter 4: Athlete Data in Python. 29 slides, about 38 minutes.

## 1. Title

Slide up while people sit down. Every measurement in this course ends up as a file, and none of those files is ready to be believed. A strap slips, a watch writes local time without saying where, a phone freezes for a second and a half, a coach types inches into a column of centimetres. Today: the small amount of Python you need to find each of those, by rule, before any number reaches a chart.

## 2. Listing 4.1: the setup check  (2 min)

Use a hosted notebook: Python on someone else's computer, with pandas, NumPy, SciPy and Matplotlib already there. Upload the chapter's data folder and run this. Your version numbers may be newer. The line that matters is the last one: fifteen hundred, one heart rate a second for twenty-five minutes. If it is not fifteen hundred, the file did not upload whole. That habit runs through the chapter: end every listing with one number you can predict before you run it. You do not need to memorise pandas. Table 4.1 lists nearly every command the book uses; you need to recognise them when an assistant writes them.

## 3. A notebook someone else can run  (3 min)

A notebook lets you run cells in any order and remembers every variable, even from a cell you deleted. That hidden state is why a notebook that worked for you fails for the next person. Reproducibility means someone else, with your files, gets your numbers. Five habits. The last is the one to start today: check each function against three cases you worked out by hand. For pace: three hundred seconds a kilometre for a ten kilometre run in fifty minutes, two twenty-five for a ninety-second lap, and two twenty-three point six nine for a six-minute mile. The mile catches the unit bug. And remember whose computer the notebook runs on.

## 4. Six laps: which speed do you report?  (2 min)

[Thirty seconds, hands up.] B. The session speed is the total distance over the total time: four point five oh one. The mean of the six lap speeds is four point five oh five, slightly different, because each lap counts equally however long it took. Small here, large on a session with a slow recovery lap. While we are here: a NumPy array does arithmetic on every value at once, which is called vectorising. It is shorter than a loop, has no counter to get wrong, and runs tens of times faster. But multiply a plain list by two and Python repeats it.

## 5. A coach's sheet, made tidy  (2 min)

A coach's spreadsheet usually has one row per athlete and one column per week. Easy to type, awkward to analyse, because week is a variable living in the column names. A tidy table has each variable in a column and each observation in a row: one jump, one athlete, one week, one row. Pandas melt does the reshaping. [Ask the room.] Eight athletes, two weeks: how many rows? [Click.] Eighteen. Sixteen was the right prediction, and that is why the eighteen matters: a row typed twice. And the fourth row is in inches. Predicting the count is what caught it.

## 6. Two clocks, one moment  (2 min)

Three questions decide whether two time series can be compared: which zone, are the clocks right, and how often was each sample taken? The strap writes UTC and says so with a Z. The watch writes local time and says nothing. Worn in the Mountain zone in January, sixteen fifty becomes twenty-three fifty UTC, and the session runs past midnight into the sixteenth. Filter on the fifteenth and you lose the last quarter hour of one evening's training. Name the zone, America Denver, rather than typing minus seven, which is wrong for half the year. Localise first, then convert.

## 7. The real sample rate, from the time stamps  (2 min)

A logging app asks for a rate, but the phone delivers samples when it can. So compute the rate from the time stamps. In the walk file the median spacing is twenty milliseconds, about fifty hertz. The minimum of zero means some rows repeat a time stamp; the maximum of eight hundred and twenty is a gap. Use the median: one long gap moves the mean spacing but not the median. And is fifty hertz enough? A signal sampled at f s can hold frequencies up to half that. Walking steps come about twice a second and their sharpest features stay under ten hertz. Fifty is ample.

## 8. The data dictionary says what the file does not  (2 min)

Every problem so far, a zone not stated, inches in a centimetre column, a rate that was not the rate asked for, is a fact about a file that the file did not say. A data dictionary says it: one row per field, with meaning, unit, type, allowed range, and how the file writes no value. Watch the cadence row: a watch counts one foot, so a runner at one seventy steps shows eighty-five. Checking a fifteen-minute run against it found two missing-value codes nobody listed: zeros, and two dashes. Update the dictionary with what you found, then clean by it. And note the checkpoint: the row count adds up.

## 9. Five problems, and rules written before you look  (2 min)

Cleaning means finding values that do not describe the athlete and deciding, by a rule, what to do with each. Five problems cover most athlete data: missing values, spikes, flat lines, duplicates and unit mix-ups. Here is the key idea of the chapter. Write the rules before you look, as numbers with units. A rule chosen after you have seen the data can be bent, without meaning to, toward the answer you hoped for. Science calls the cure preregistration. In a notebook it is a dictionary called RULES at the top of the cell.

## 10. The walk, and what the rules found  (3 min)

Here is the walk. Three rules, written first: walking stays under four g; a reading identical for half a second is a frozen sensor; a sample more than five units from the median of its five neighbours is a spike, because a real step takes many samples to rise and fall. The rules found one spike, the orange mark, a run of one and a half seconds where the sensor repeated itself, shaded, and twenty duplicated rows you cannot see in any plot. Notice the code marks bad samples as missing rather than deleting rows. The time line stays intact, and anyone can count what was removed.

## 11. The hardest error: right shape, wrong size  (1.5 min)

The coach's sheet needs different rules. The duplicate row goes. One athlete's heights are in inches, so multiply by two point five four, which is exact. One athlete missed week one, and that value stays missing rather than being guessed. Without the unit fix, A04 improved by under a centimetre and looked like the weakest jumper on the team by a factor of two. A value that is the right shape but the wrong size is the hardest error to see, which is why the range check comes first. And never edit the original: keep the raw file, write a cleaned copy, and log every rule with how many rows it touched.

## 12. Two devices, one clock: cross-correlation  (3 min)

Once both devices are in UTC, are the clocks right? Put both on a one-second grid, filling only short gaps. Then slide the watch against the strap a second at a time and compute the correlation at each shift. The peak, on the right, is the offset: the watch clock is seven seconds fast, the offset the data generator put in. Two things make it trustworthy: the peak is high, and it is one clear peak, not a flat top. And check it by eye: pick one sharp edge. The strap reaches one forty at three sixty-nine seconds, the watch at three seventy-seven. Eight, within the watch's noise.

## 13. A flat correlation curve  (2 min)

[One minute in pairs.] The code runs without an error. The correlation curve is flat. The assistant might even tell you the clocks agree. What went wrong? [Click.] utc equals True does not convert anything; it declares the local times to be UTC. So the watch's sixteen fifty becomes sixteen fifty UTC, seven hours before the strap. The true shift is about twenty-five thousand seconds, far outside the thirty-second search, and the two series barely overlap. The fix is the two-step line from Example 4.3. The general lesson: a flat cross-correlation means your search or your alignment is wrong.

## 14. Predict the rows before you join  (2 min)

Aligning puts two series on one clock. A join matches rows by what they describe, here a session ID. Three things go wrong, and none raises an error by default: a duplicate key, unmatched rows, and row growth. [Two minutes, by hand.] [Click.] S01, S02 and S04 give sixty each; S03 matches both copies and gives a hundred and twenty; S06 keeps forty-five rows with an empty type. Three hundred and forty-five, sixty more than you started with. Pandas will not warn you. validate equals many to one turns the duplicate into an error, and indicator equals True labels the unmatched rows.

## 15. Average or median? One bad beat  (2.5 min)

Every sensor adds noise, and smoothing replaces each sample by a combination of its neighbours. A five-point moving average at sample three: six nineteen over five, one twenty-three point eight. [Two minutes.] Now the strap slips and sample six reads one ninety. [Click.] The average there is one forty point eight, against a true value near one twenty-nine, and every window that holds the bad beat rises by twelve: one slip corrupts five seconds. The median filter takes the middle value instead: one twenty-nine, and the spike is gone. So the order is: median or a rule first, then average. A single beat of one ninety is almost always the device, not the heart.

## 16. The price of smoothing is lag  (1 min)

Smoothing has a price, and it is lag. A centred window uses future samples, so a live display must use a trailing window, and a trailing average is late: on a steady rise, N minus one over two samples. Five points at one a second: two seconds late. A low-pass Butterworth filter run once is eighty milliseconds late on the step rhythm. Run forward and then backward over a recorded file, the two delays cancel. For a recorded file, use two passes. For a live display, accept the lag and report it.

## 17. Two devices: describe the difference  (2 min)

When two devices measure the same thing, describe their difference. Plot watch minus strap against the mean of the two, and draw the bias and the limits of agreement. After the seven-second correction, the watch reads about one beat high on average, and ninety-five percent of its seconds fall within minus four to plus six of the strap. A correlation is the wrong tool: two devices can correlate at zero point nine nine and disagree by ten beats at every second. And without the clock correction the limits are far wider, because every rise is compared with a value seven seconds away.

## 18. A chart that makes one point  (2.5 min)

A chart for a coach has one job: to make one point the coach can see in five seconds. On the left, what a spreadsheet does by default: the axis starts at twenty-nine, so a four centimetre range looks fivefold; Series one to seven say nothing; seven shades suggest seven categories; and an invalid clip is included. On the right, the same jumps: weeks as categories, every jump shown, means labelled, zero on the axis, and the finding as the title: week three jumps two point eight centimetres higher. About nine percent. Worth reporting, and within reach of noise for three jumps a week. The honest chart shows both.

## 19. Before Class 8  (1.5 min)

Homework eight is due at the start of next class. The concept checks and hand calculations: a naive time stamp, the lag of a trailing average, and a moving average with one bad speed. Then record yourself with a sensor-logging app: stand still, move, stand still. Find the real sample rate from the time stamps, clean by rules you wrote first, and find your cadence; compare with twice a thirty-second hand count from a partner. Walk on a clear path. Run your week one and week three jump clips through the jump app's process-a-folder page. Read sections 4.8 to 4.13 before Thursday: the app results files and coding with an assistant.
