Skip to content

10. Iterators and generators — Mini-project

You run the monitoring of four sensors in a plant. Every two weeks, the sensor gateway exports its log, data/sensors.csv. Today the file has 8,064 rows. Next year the plant has 400 sensors and the file has 800,000 rows, so the report script must not load the file.

Write a command-line script, sensor_health.py, that reads the log once, as a stream, and answers four questions for each sensor:

  1. How many readings and blank cells are there?
  2. How many temperature spikes are there? Write each one to a CSV file as soon as it is found.
  3. What share of readings has the status warn or fail? A share above 5% suggests wear.
  4. How fast does the daily mean temperature drift? More than 0.2 °C per day suggests a calibration problem.

The project uses the core of the module: a source generator, transform and pass-through stages, a deque rolling window, groupby on a sorted stream, one-pass aggregation and a sink that writes while it streams.

data/sensors.csv: 8,064 rows, 4 sensors (S1–S4) × 2,016 readings, one every 10 minutes from 2024-05-01 00:00 to 2024-05-14 23:50. The file is sorted by timestamp, then sensor_id.

Column Type in the file Notes
timestamp text, YYYY-MM-DDTHH:MM:SS the first 10 characters are the date
sensor_id text S1 to S4
temperature_c number, 22 blank contains injected spikes of +9 to +18 °C
humidity_pct number, 29 blank
vibration_mm_s number, 30 blank
status text ok, warn or fail; never blank

Your script must:

  1. Run as python sensor_health.py data/sensors.csv, with the options --window (readings in the spike baseline, default 6), --jump (spike size in °C, default 6.0) and --out (spike file, default output/spikes.csv). Use argparse (module 08).
  2. Read the file with a source generator. No list, readlines() or list(reader) of the whole file may appear anywhere.
  3. Count the blank numeric cells per sensor in a pass-through generator stage.
  4. Parse each row into a typed record; a blank temperature becomes None.
  5. Detect a spike when a temperature is more than --jump °C above the mean of the sensor’s previous --window normal readings. Keep spikes out of the window and out of the daily means.
  6. Compute the daily mean temperature of each sensor with groupby on the date, and the drift per day from the first daily mean to the last.
  7. Write each spike to the spike CSV (timestamp, sensor_id, temperature_c) while the stream runs.
  8. Read the file exactly once. Every statistic comes from one pass.
  9. Print this report, exactly:
Expected output
Sensor health report: data/sensors.csv
Baseline 6 readings, spike jump 6.0 °C
sensor readings blanks spikes warn fail problem % drift °C/day
S1 2016 27 8 14 0 0.7 +0.00
S2 2016 15 12 17 5 1.1 -0.01
S3 2016 21 11 22 0 1.1 +0.35
S4 2016 18 8 400 19 20.8 -0.01
Rows: 8064. Spikes written to output/spikes.csv: 39
Drifting (> 0.2 °C/day): S3
Wearing (> 5% warn or fail): S4
  1. Write the source. read_rows(path) opens the file inside the generator and yields csv.DictReader rows with yield from. Test it with next().

  2. Count blanks on the way. count_blanks(rows, blanks) adds the number of empty numeric cells of each row to a Counter and yields the row unchanged. It is a pass-through stage: it changes nothing in the stream.

  3. Parse. parse(rows) yields a NamedTuple with the timestamp, the sensor id, the temperature as float | None and the status.

  4. Keep running statistics per sensor. For each sensor, keep a deque(maxlen=window) of recent normal temperatures, a Counter of statuses, a spike count, the temperatures of the current day and the list of daily means. A small class with an add() method keeps this tidy; a dict of dicts also works.

  5. Group by day. Loop over groupby(readings, key=lambda r: r.timestamp[:10]). Inside each day, update the statistics reading by reading. At the end of the day, turn each sensor’s day temperatures into one daily mean.

  6. Write spikes as you go. Open the spike file before the loop with newline="". When add() reports a spike, call writer.writerow(). Create the output/ folder with mkdir(parents=True, exist_ok=True).

  7. Print the report. Use format specs for the columns. Drift is (last daily mean − first daily mean) / (days − 1). The format spec +z.2f shows the sign and prints a tiny negative value as +0.00 instead of -0.00.

  8. Check the result. The blanks must add up to 81 (22 + 29 + 30), the readings to 8,064. Run with --jump 8 --window 12: a robust detector finds the same spikes.

A skeleton to start from:

sensor_health.py (starter)
# sensor_health.py: a one-pass health report for the sensor log.
import argparse
import csv
from collections import Counter, defaultdict, deque
from collections.abc import Iterable, Iterator
from itertools import groupby
from typing import NamedTuple
class Reading(NamedTuple):
timestamp: str
sensor_id: str
temperature_c: float | None
status: str
def read_rows(path: str) -> Iterator[dict[str, str]]:
... # TODO: source
def count_blanks(
rows: Iterable[dict[str, str]], blanks: Counter[str]
) -> Iterator[dict[str, str]]:
... # TODO: pass-through stage
def parse(rows: Iterable[dict[str, str]]) -> Iterator[Reading]:
... # TODO: typed records
def main() -> None:
# TODO: argparse; build the pipeline; one groupby loop over days;
# TODO: write spikes while streaming; print the report
...
if __name__ == "__main__":
main()
Criterion Points Full points when
Runs as a CLI 2 python sensor_health.py data/sensors.csv works; --window, --jump and --out change the run
Streaming 3 No list of all rows anywhere; the source opens the file inside a generator
One pass 2 The file is read once; every statistic comes from the same loop
Pipeline stages 2 Source, pass-through blank counter and parse stage are separate generators with type hints
Spike detection 3 Per-sensor deque windows; spikes excluded from the window; 39 spikes with the defaults
Daily drift 2 groupby on the date; S3 drifts by about +0.35 °C per day
Output 2 The report matches exactly; output/spikes.csv has a header and one row per spike
Readability 2 Small functions with docstrings; names say what they hold
Total 18 15 or more: you are ready for module 11
  1. Add a humidity column to the report: the mean humidity per sensor, skipping blanks, from the same pass.
  2. Write the spikes in chunks: collect them in a list and flush it to the CSV with writer.writerows() every 10 spikes, then once at the end.
  3. Add a --sensor option that reports only one sensor. Filter as early as possible in the pipeline.
  4. Detect vibration spikes too, with a rolling median baseline (see exercise X02).
  5. Generate a 50× larger test file by repeating the rows with shifted timestamps (a generator, of course), and run the script on it with tracemalloc. Show that the peak memory stays the same.

Try the project yourself first. Then compare your script with this one. Your structure can differ; your report must not.

Reference solution
sensor_health.py
# sensor_health.py: a one-pass health report for the sensor log.
# It streams data/sensors.csv row by row and never stores the whole file.
import argparse
import csv
from collections import Counter, defaultdict, deque
from collections.abc import Iterable, Iterator
from itertools import groupby
from pathlib import Path
from statistics import fmean
from typing import NamedTuple
NUMERIC = ("temperature_c", "humidity_pct", "vibration_mm_s")
class Reading(NamedTuple):
timestamp: str
sensor_id: str
temperature_c: float | None
status: str
def read_rows(path: str) -> Iterator[dict[str, str]]:
"""Source: yield each CSV row as a dict of strings."""
with open(path, encoding="utf-8", newline="") as f:
yield from csv.DictReader(f)
def count_blanks(
rows: Iterable[dict[str, str]], blanks: Counter[str]
) -> Iterator[dict[str, str]]:
"""Pass-through: count blank numeric cells per sensor."""
for row in rows:
blanks[row["sensor_id"]] += sum(1 for col in NUMERIC if not row[col])
yield row
def parse(rows: Iterable[dict[str, str]]) -> Iterator[Reading]:
"""Transform: typed readings; a blank temperature becomes None."""
for row in rows:
temp = row["temperature_c"]
value = float(temp) if temp else None
yield Reading(row["timestamp"], row["sensor_id"], value, row["status"])
class SensorStats:
"""Running statistics of one sensor; updated one reading at a time."""
def __init__(self, window: int) -> None:
self.recent: deque[float] = deque(maxlen=window)
self.readings = 0
self.status: Counter[str] = Counter()
self.spikes = 0
self.day_temps: list[float] = [] # normal readings of the current day
self.daily_means: list[float] = []
def add(self, r: Reading, jump: float) -> bool:
"""Update the statistics; return True if the reading is a spike."""
self.readings += 1
self.status[r.status] += 1
if r.temperature_c is None:
return False
full = len(self.recent) == self.recent.maxlen
if full and r.temperature_c - fmean(self.recent) > jump:
self.spikes += 1
return True # keep the spike out of the window and the daily mean
self.recent.append(r.temperature_c)
self.day_temps.append(r.temperature_c)
return False
def end_day(self) -> None:
if self.day_temps:
self.daily_means.append(fmean(self.day_temps))
self.day_temps = []
def problem_share(self) -> float:
"""Share of readings with status warn or fail."""
return (self.status["warn"] + self.status["fail"]) / self.readings
def drift(self) -> float:
"""Change of the daily mean per day, from the first day to the last."""
days = len(self.daily_means)
return (self.daily_means[-1] - self.daily_means[0]) / (days - 1)
def main() -> None:
parser = argparse.ArgumentParser(description="Stream a sensor health report.")
parser.add_argument("path", help="sensor CSV file, e.g. data/sensors.csv")
parser.add_argument("--window", type=int, default=6, help="readings per baseline")
parser.add_argument("--jump", type=float, default=6.0, help="spike size in °C")
parser.add_argument("--out", default="output/spikes.csv", help="spike CSV file")
args = parser.parse_args()
blanks: Counter[str] = Counter()
stats: defaultdict[str, SensorStats] = defaultdict(lambda: SensorStats(args.window))
readings = parse(count_blanks(read_rows(args.path), blanks))
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
with open(out, "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["timestamp", "sensor_id", "temperature_c"])
# The file is sorted by timestamp: groupby on the date gives one group per day.
for _day, day_readings in groupby(readings, key=lambda r: r.timestamp[:10]):
for r in day_readings:
if stats[r.sensor_id].add(r, args.jump):
writer.writerow([r.timestamp, r.sensor_id, r.temperature_c])
for sensor in stats.values():
sensor.end_day()
print(f"Sensor health report: {args.path}")
print(f"Baseline {args.window} readings, spike jump {args.jump} °C")
print("sensor readings blanks spikes warn fail problem % drift °C/day")
for sensor_id in sorted(stats):
s = stats[sensor_id]
print(
f"{sensor_id:<6} {s.readings:>8} {blanks[sensor_id]:>6} {s.spikes:>6}"
f" {s.status['warn']:>4} {s.status['fail']:>4}"
f" {100 * s.problem_share():>9.1f}"
f" {s.drift():>+z12.2f}" # z: show -0.00 as +0.00
)
rows = sum(s.readings for s in stats.values())
spikes = sum(s.spikes for s in stats.values())
drifting = [k for k in sorted(stats) if abs(stats[k].drift()) > 0.2]
wearing = [k for k in sorted(stats) if stats[k].problem_share() > 0.05]
print(f"Rows: {rows}. Spikes written to {out.as_posix()}: {spikes}")
print("Drifting (> 0.2 °C/day):", ", ".join(drifting) or "none")
print("Wearing (> 5% warn or fail):", ", ".join(wearing) or "none")
if __name__ == "__main__":
main()
Output
Sensor health report: data/sensors.csv
Baseline 6 readings, spike jump 6.0 °C
sensor readings blanks spikes warn fail problem % drift °C/day
S1 2016 27 8 14 0 0.7 +0.00
S2 2016 15 12 17 5 1.1 -0.01
S3 2016 21 11 22 0 1.1 +0.35
S4 2016 18 8 400 19 20.8 -0.01
Rows: 8064. Spikes written to output/spikes.csv: 39
Drifting (> 0.2 °C/day): S3
Wearing (> 5% warn or fail): S4

Run it from the project folder, here with a longer baseline and a higher spike threshold:

Terminal
python sensor_health.py data/sensors.csv --window 12 --jump 8
head -4 output/spikes.csv
Output
Sensor health report: data/sensors.csv
Baseline 12 readings, spike jump 8.0 °C
sensor readings blanks spikes warn fail problem % drift °C/day
S1 2016 27 8 14 0 0.7 +0.00
S2 2016 15 12 17 5 1.1 -0.01
S3 2016 21 11 22 0 1.1 +0.35
S4 2016 18 8 400 19 20.8 -0.01
Rows: 8064. Spikes written to output/spikes.csv: 39
Drifting (> 0.2 °C/day): S3
Wearing (> 5% warn or fail): S4
timestamp,sensor_id,temperature_c
2024-05-01T10:40:00,S3,33.51
2024-05-02T12:30:00,S1,36.03
2024-05-02T13:20:00,S2,44.89

How it works:

  1. Pipeline. parse(count_blanks(read_rows(path), blanks)) builds three lazy stages. Nothing is read until the groupby loop asks for the first reading.
  2. Pass-through stage. count_blanks updates the blanks Counter and yields each row unchanged, so the blank count costs no extra pass.
  3. Running statistics. Each SensorStats object holds a 6-value window, a status Counter, a spike count, the current day’s temperatures and the list of 14 daily means. Memory does not grow with the number of rows, only with the number of sensors and days.
  4. Spikes. add() compares a reading with the mean of the window. A spike is counted, returned as True and kept out of both the window and the daily mean, so it cannot hide the next spike or bend the drift.
  5. Days. groupby on the date yields one group per day, because the file is sorted by timestamp. After each group, end_day() turns the day’s temperatures into one daily mean.
  6. Sink. The spike file is written inside the loop, so the first spike is on disk before the last row is read. The report itself is printed after the stream is used up, because only then are the counts final.
  7. Results. S3 drifts by +0.35 °C per day, the calibration drift of the data dictionary. S4 has 20.8% warn or fail readings: its vibration rises from May 12. The other sensors are healthy. The spike count does not change between the two runs, so the detector is not sensitive to its settings.

Alternative: replace SensorStats with a defaultdict of plain dicts, or with pandas: pd.read_csv(path, chunksize=2_000) and per-chunk aggregates. The pandas version is shorter, but the rolling window must then carry the last readings from one chunk to the next, which is easy to get wrong. A generator pipeline handles chunk borders for free, because it never has any.