# Q-41: Drag and rolling resistance from a cycling-simulator export

Data-Driven Athletics tutorial · Week 6 · Chapter 3 · about 20 min · workflow steps: Gather, Visualize, Features

Web page: https://apopt.com/course/tutorials/q41-cycling-sim-export/ · Data: https://apopt.com/data/tutorials/q41-cycling-sim-export/

## The decision

A rider wants to know whether a lower position is worth learning. That needs their drag area,
which a power meter and a speed sensor can estimate on a level road. The simulator lets you
check the estimate against the value it used.

## The raw data

- `raw/cycling-rider_20261202_221900.csv`: SIMULATED: the cycling simulator's CSV export of scenario 2 (Exertion steps, and the step that fades), one row a second for 25 minutes, 134 columns, exactly as the Export CSV button writes it [Cycling simulator](https://apmonitor.com/apps/cycling-rider/), recreational preset, scenario 2 · Exertion steps, and the step that fades (seeded, so every run of the scenario gives the same file).

### A road you can ride in a browser

The [cycling simulator](https://apmonitor.com/apps/cycling-rider/) puts a modeled rider on a
road bicycle. You set the exertion; the model answers with crank power, cadence, gear, speed,
heart rate, lactate and an anaerobic reserve, once a second. Its **Export CSV** button writes
every logged second to a file.

This file comes from scenario **2 · Exertion steps, and the step that fades**: on a level road
with no wind, exertion steps to 30, 55, 70 and 85% and back to 30%. It runs for 25 minutes.
Every number is **simulated**.

Section 3.8 says the road and the air take back the power the rider supplies. At the wheel,
force = power / speed, and on level ground that force goes to three places:

F = Crr·m·g + ½·ρ·CdA·v² + m·a

rolling resistance (coefficient Crr), air drag (drag area CdA, air density ρ) and speeding up
(mass m times acceleration a). Your job: estimate Crr and CdA from power and speed alone, as
you would from a real power meter, then compare them with the values the simulator used.
The export carries those too, in its `param_…` columns, which no real ride gives you.

To make the file yourself: open the simulator, choose that scenario, press **Run**, let it
pass 25 minutes, and press **Export CSV**.

*Predict first:* Which column would you trust for power, power_W or power_meas_W?

```python
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/cycling-rider_20261202_221900.csv", comment="#")
tcol = raw.columns[0]
scale = {"Time (s)": 1, "Time (min)": 60, "Time (h)": 3600}[tcol]
ride = pd.DataFrame({
    "t_s": (raw[tcol] * scale).round(2),
    "power_W": raw["power_meas_W"],     # the power meter: noisy and smoothed
    "speed_mps": raw["speed_mps"],
    "grade_pct": raw["grade_pct"],
})
m = raw["param_mass_kg"].iloc[0] + raw["param_bike_mass_kg"].iloc[0]
print(f"{raw.shape[0]} rows, {raw.shape[1]} columns; rider and bicycle {m} kg")
print(f"grade {ride.grade_pct.min()} to {ride.grade_pct.max()} %, headwind "
      f"{raw['headwind_mps'].max()} m/s")
print(f"the truth to check against: CdA {raw['param_cda_m2'].iloc[0]} m2, "
      f"Crr {raw['param_crr'].iloc[0]}")
```

Output:

```
1501 rows, 134 columns; rider and bicycle 83.5 kg
grade 0 to 0 %, headwind 0 m/s
the truth to check against: CdA 0.32 m2, Crr 0.0045
```

The road is level and still, so the grade and wind terms drop out. Some numbers the force
balance needs are not in the file. The simulator's **Show Model** dialog lists them on its
**Parameters** tab: the drivetrain passes 97.5% of the crank power to the wheel, air density
is 1.20 kg/m³, and the wheels (0.335 m radius, 0.14 kg·m² of rotational inertia) add a little
to the mass that has to be sped up. Write such constants down when you export; a file that
leaves them out is a common fault in real data too.

```python
import matplotlib.pyplot as plt

mins = ride.t_s / 60
fig, ax = plt.subplots(2, 1, figsize=(6.4, 4.2), sharex=True)
ax[0].plot(mins, ride.power_W, "k-", lw=0.8)
ax[1].plot(mins, ride.speed_mps * 3.6, "k-")
ax[0].set_ylabel("crank power (W)")
ax[1].set_ylabel("speed (km/h)")
ax[1].set_xlabel("time (min)")
plt.tight_layout()
for a, b in [(240, 300), (540, 600), (840, 900), (1440, 1500)]:
    w = ride[ride.t_s.between(a, b)]
    print(f"{a / 60:4.0f}-{b / 60:.0f} min: {w.power_W.mean():5.0f} W, "
          f"{3.6 * w.speed_mps.mean():5.1f} km/h")
```

Output:

```
   4-5 min:    89 W,  24.5 km/h
   9-10 min:   164 W,  31.2 km/h
  14-15 min:   206 W,  34.2 km/h
  24-25 min:    85 W,  24.1 km/h
```

![Two stacked panels against minutes, 0 to 25. Top, measured crank power steps to about 89, 164 and 206 watts, spikes to about 465 at 15 minutes and fades to about 215, then drops to about 85 at 19 minutes. Bottom, speed rises in steps to about 24, 31 and 34 km/h, peaks near 44 km/h after the 85% step, eases to about 35 and falls back to about 24.](https://apopt.com/course/tutorials/q41-cycling-sim-export/c03-1.png)

Speed takes a minute or more to catch up with each change in power, and at 85% power fades
while the anaerobic reserve drains, so the bicycle is speeding up or slowing down for a good
part of the ride. If you
fit only the force at the wheel, the force that went into speeding up would be blamed on drag
and rolling. So the acceleration term stays in. With F, v and a in hand, the balance is a
straight-line model with two unknowns and no intercept, which least squares solves.

*Predict first:* Leave out the acceleration term. Will the fitted CdA go up or down?

```python
G, RHO, ETA = 9.81, 1.20, 0.975
m_eff = m + 0.14 / 0.335**2          # spinning wheels: inertia / radius^2 of extra mass

def fit(df, with_accel=True):
    t, v, P = df.t_s.to_numpy(), df.speed_mps.to_numpy(), df.power_W.to_numpy()
    a = np.gradient(v, t)
    ok = (v > 4) & (P > 20)             # rolling and pedaling: no start, no coasting
    F = ETA * P[ok] / v[ok] - (m_eff * a[ok] if with_accel else 0)
    X = np.column_stack([np.full(ok.sum(), m * G), 0.5 * RHO * v[ok] ** 2])
    (crr, cda), *_ = np.linalg.lstsq(X, F, rcond=None)
    return crr, cda, ok.sum()

for label, kw in [("with acceleration", {}), ("without acceleration", {"with_accel": False})]:
    crr, cda, n = fit(ride, **kw)
    print(f"{label:21s} Crr {crr:.5f}, CdA {cda:.3f} m2 ({n} s)")
crr, cda, n = fit(ride.assign(power_W=raw["power_W"]))
print(f"{'true power, with a':21s} Crr {crr:.5f}, CdA {cda:.3f} m2")
```

Output:

```
with acceleration     Crr 0.00435, CdA 0.324 m2 (1459 s)
without acceleration  Crr 0.00532, CdA 0.309 m2 (1459 s)
true power, with a    Crr 0.00449, CdA 0.320 m2
```

With the acceleration term the fit gives CdA 0.324 m² and Crr 0.00435, against the simulator's
0.32 and 0.0045. Without it, CdA comes out 0.309 and Crr 0.00532: rolling resistance is
overestimated by 18%, because the force that sped the bicycle up during each step lands on the
only constant term in the model. Fitting the model's true power instead of the power meter
gives 0.320 and 0.0045 almost exactly, so the small remaining miss is the meter's noise and
smoothing, not the method.

### What the athlete can use

```python
from scipy.optimize import brentq

crr, cda, _ = fit(ride)
def speed_at(P, cda):                 # level road, steady speed: power in = power out
    return brentq(lambda v: ETA * P - (crr * m * G + 0.5 * RHO * cda * v**2) * v, 1, 30)

v_hoods, v_drops = speed_at(200, cda), speed_at(200, 0.25)
print(f"200 W on the hoods (CdA {cda:.3f}): {3.6 * v_hoods:.1f} km/h")
print(f"200 W in the drops (CdA 0.25):   {3.6 * v_drops:.1f} km/h, "
      f"+{3.6 * (v_drops - v_hoods):.1f} km/h")
print(f"40 km at 200 W: {40e3 / v_hoods / 60:.1f} min on the hoods, "
      f"{40e3 / v_drops / 60:.1f} min in the drops")
```

Output:

```
200 W on the hoods (CdA 0.324): 33.8 km/h
200 W in the drops (CdA 0.25):   36.7 km/h, +2.8 km/h
40 km at 200 W: 70.9 min on the hoods, 65.4 min in the drops
```

At 200 W the fitted rider holds 33.8 km/h on the brake hoods. The simulator's hint for the
drops is a CdA of 0.25 m²; at the same 200 W that is 36.7 km/h, 2.8 km/h faster for no extra
work, and 40 km takes 5.5 minutes less. The prediction assumes the fitted Crr and that only
the position changes. Set the simulator's drag area to 0.25, ride the same scenario, and check
it: "With your own data" below says how.

**For the athlete:** "In the drops you would ride about 2.8 km/h faster at the same 200 W; over
40 km that saves about five and a half minutes without training any harder."

## With your own data

Test the prediction. In the cycling simulator choose the same scenario, press **Show Model**,
and on its **Parameters** tab set **Aerodynamic drag area, CdA** to 0.25 m² before you press
Run. Ride to 25 minutes, export, and run this page on your file.
Does the fit find 0.25, and is the rider about 2.8 km/h faster at 200 W? Then try scenario
**4 · A climb at constant exertion**: the grade is no longer zero, so add the gravity term
m·g·sin(θ) to the force balance before you fit.

## The same method in another field

Road-vehicle engineers fit the same two numbers, a drag area and a rolling coefficient, to a
car's coast-down test, where the force is the car's own deceleration times its mass. The same least
squares on a physics-based feature set appears in the
[Dynamic Data Engineering course](https://apmonitor.com/dde).

## Acknowledgements

Data made with the cycling simulator at apmonitor.com/apps/cycling-rider.

## References

- Chapter 3 of *Data-Driven Athletics*: Science of the Sports (cycling power).
- Chapter 11 of *Data-Driven Athletics*: Regression.

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