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:
- How many readings and blank cells are there?
- How many temperature spikes are there? Write each one to a CSV file as soon as it is found.
- What share of readings has the status
warnorfail? A share above 5% suggests wear. - 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.
Dataset
Section titled “Dataset”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 |
Requirements
Section titled “Requirements”Your script must:
- 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, defaultoutput/spikes.csv). Useargparse(module 08). - Read the file with a source generator. No list,
readlines()orlist(reader)of the whole file may appear anywhere. - Count the blank numeric cells per sensor in a pass-through generator stage.
- Parse each row into a typed record; a blank temperature becomes
None. - Detect a spike when a temperature is more than
--jump°C above the mean of the sensor’s previous--windownormal readings. Keep spikes out of the window and out of the daily means. - Compute the daily mean temperature of each sensor with
groupbyon the date, and the drift per day from the first daily mean to the last. - Write each spike to the spike CSV (
timestamp,sensor_id,temperature_c) while the stream runs. - Read the file exactly once. Every statistic comes from one pass.
- Print this report, exactly:
Sensor health report: data/sensors.csvBaseline 6 readings, spike jump 6.0 °Csensor readings blanks spikes warn fail problem % drift °C/dayS1 2016 27 8 14 0 0.7 +0.00S2 2016 15 12 17 5 1.1 -0.01S3 2016 21 11 22 0 1.1 +0.35S4 2016 18 8 400 19 20.8 -0.01Rows: 8064. Spikes written to output/spikes.csv: 39Drifting (> 0.2 °C/day): S3Wearing (> 5% warn or fail): S4Step plan
Section titled “Step plan”-
Write the source.
read_rows(path)opens the file inside the generator and yieldscsv.DictReaderrows withyield from. Test it withnext(). -
Count blanks on the way.
count_blanks(rows, blanks)adds the number of empty numeric cells of each row to aCounterand yields the row unchanged. It is a pass-through stage: it changes nothing in the stream. -
Parse.
parse(rows)yields aNamedTuplewith the timestamp, the sensor id, the temperature asfloat | Noneand the status. -
Keep running statistics per sensor. For each sensor, keep a
deque(maxlen=window)of recent normal temperatures, aCounterof statuses, a spike count, the temperatures of the current day and the list of daily means. A small class with anadd()method keeps this tidy; a dict of dicts also works. -
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. -
Write spikes as you go. Open the spike file before the loop with
newline="". Whenadd()reports a spike, callwriter.writerow(). Create theoutput/folder withmkdir(parents=True, exist_ok=True). -
Print the report. Use format specs for the columns. Drift is (last daily mean − first daily mean) / (days − 1). The format spec
+z.2fshows the sign and prints a tiny negative value as+0.00instead of-0.00. -
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: a one-pass health report for the sensor log.import argparseimport csvfrom collections import Counter, defaultdict, dequefrom collections.abc import Iterable, Iteratorfrom itertools import groupbyfrom 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()Rubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Add a humidity column to the report: the mean humidity per sensor, skipping blanks, from the same pass.
- 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. - Add a
--sensoroption that reports only one sensor. Filter as early as possible in the pipeline. - Detect vibration spikes too, with a rolling median baseline (see exercise X02).
- 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.
Reference solution
Section titled “Reference solution”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: a one-pass health report for the sensor log.# It streams data/sensors.csv row by row and never stores the whole file.import argparseimport csvfrom collections import Counter, defaultdict, dequefrom collections.abc import Iterable, Iteratorfrom itertools import groupbyfrom pathlib import Pathfrom statistics import fmeanfrom 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()Sensor health report: data/sensors.csvBaseline 6 readings, spike jump 6.0 °Csensor readings blanks spikes warn fail problem % drift °C/dayS1 2016 27 8 14 0 0.7 +0.00S2 2016 15 12 17 5 1.1 -0.01S3 2016 21 11 22 0 1.1 +0.35S4 2016 18 8 400 19 20.8 -0.01Rows: 8064. Spikes written to output/spikes.csv: 39Drifting (> 0.2 °C/day): S3Wearing (> 5% warn or fail): S4Run it from the project folder, here with a longer baseline and a higher spike threshold:
python sensor_health.py data/sensors.csv --window 12 --jump 8head -4 output/spikes.csvSensor health report: data/sensors.csvBaseline 12 readings, spike jump 8.0 °Csensor readings blanks spikes warn fail problem % drift °C/dayS1 2016 27 8 14 0 0.7 +0.00S2 2016 15 12 17 5 1.1 -0.01S3 2016 21 11 22 0 1.1 +0.35S4 2016 18 8 400 19 20.8 -0.01Rows: 8064. Spikes written to output/spikes.csv: 39Drifting (> 0.2 °C/day): S3Wearing (> 5% warn or fail): S4timestamp,sensor_id,temperature_c2024-05-01T10:40:00,S3,33.512024-05-02T12:30:00,S1,36.032024-05-02T13:20:00,S2,44.89How it works:
- Pipeline.
parse(count_blanks(read_rows(path), blanks))builds three lazy stages. Nothing is read until thegroupbyloop asks for the first reading. - Pass-through stage.
count_blanksupdates theblanksCounter and yields each row unchanged, so the blank count costs no extra pass. - Running statistics. Each
SensorStatsobject 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. - Spikes.
add()compares a reading with the mean of the window. A spike is counted, returned asTrueand kept out of both the window and the daily mean, so it cannot hide the next spike or bend the drift. - Days.
groupbyon 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. - 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.
- Results. S3 drifts by +0.35 °C per day, the calibration drift of the data dictionary. S4 has 20.8%
warnorfailreadings: 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.