Project: A CSV Report for the Wind Farm
Build a Rust program that parses CSV text with error handling, groups readings by turbine with a BTreeMap, computes per-turbine statistics and writes a report file, then verify the file with Python.
In this lesson you will
- Parse CSV text safely
- Group data with BTreeMap
- Write and read a file
- Verify the report in Python
About 28 minutes
From raw lines to a report file
The second project joins the ideas of the intermediate lessons. The farm’s data logger produces a CSV file with the columns turbine, hour and speed, and some of its lines are damaged. Ines wants a program that parses every line, keeps the good ones, counts and reports the bad ones with their line numbers, groups the speeds by turbine and writes a summary file with one row per turbine. The standard library has no CSV parser, and for this simple format splitting on commas is enough, though real CSV with quoted fields deserves a proper crate.
The design has three parts. A Row struct and a parse function return a Result with a descriptive error string, a BTreeMap<String, Vec> groups the speeds and keeps the turbines in sorted order, which makes the output deterministic, and a function writes the summary with std::fs::write. The program then reads its own output back to prove that the file really contains what was printed. Using BTreeMap instead of HashMap, the lesson from lesson 6, makes the report identical on every run.
use std::collections::BTreeMap;
use std::fs;
struct Row { turbine: String, hour: u32, speed: f64 }
fn parse_row(line: &str) -> Result<Row, String> {
let f: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
if f.len() != 3 { return Err(format!("expected 3 fields, found {}", f.len())); }
let hour: u32 = f[1].parse().map_err(|e| format!("bad hour {:?}: {}", f[1], e))?;
let speed: f64 = f[2].parse().map_err(|e| format!("bad speed {:?}: {}", f[2], e))?;
if hour > 23 { return Err(format!("hour {} is not 0-23", hour)); }
if speed < 0.0 { return Err(format!("speed {} is negative", speed)); }
Ok(Row { turbine: f[0].to_string(), hour, speed })
}
fn main() {
let csv = "turbine,hour,speed
T1,0,8.5
T2,0,12.0
T1,1,9.5
T3,0,4.0
T2,1,abc
T1,2,14.0
T3,1
T2,2,15.5
T1,25,6.0
T3,2,4.5
T2,3,-1.0
T3,3,11.0
T2,4,11.0";
let mut groups: BTreeMap<String, Vec<f64>> = BTreeMap::new();
let mut bad = Vec::new();
let mut hours = 0;
for (i, line) in csv.lines().enumerate().skip(1) {
match parse_row(line) {
Ok(r) => { hours += r.hour; groups.entry(r.turbine).or_default().push(r.speed); }
Err(e) => bad.push(format!("line {}: {}", i + 1, e)),
}
}
let mut report = String::from("turbine,count,mean,max\n");
for (name, v) in &groups {
let mean = v.iter().sum::<f64>() / v.len() as f64;
let max = v.iter().cloned().fold(f64::MIN, f64::max);
report.push_str(&format!("{},{},{:.3},{}\n", name, v.len(), mean, max));
}
let path = std::env::temp_dir().join("farm_report_demo.csv");
fs::write(&path, &report).unwrap();
let back = fs::read_to_string(&path).unwrap();
print!("{}", back);
println!("rejected {} lines:", bad.len());
for b in &bad { println!(" {}", b); }
println!("file round trip identical: {} | bytes written: {} | hour sum {}", back == report, back.len(), hours);
fs::remove_file(&path).unwrap();
}
turbine,count,mean,max
T1,3,10.667,14
T2,3,12.833,15.5
T3,3,6.500,11
rejected 4 lines:
line 6: bad speed "abc": invalid float literal
line 8: expected 3 fields, found 2
line 10: hour 25 is not 0-23
line 12: speed -1 is negative
file round trip identical: true | bytes written: 69 | hour sum 14
The program parsed twelve data lines under a header. Eight were valid and four were rejected, and the rejected ones were reported with their real line numbers in the file, where line 1 is the header: line 6: bad speed “abc”: invalid float literal; line 8: expected 3 fields, found 2; line 10: hour 25 is not 0-23; line 12: speed -1 is negative. Each message says what was wrong and quotes the value, so that Ines can find the damaged record in the logger’s file.
The report written to the file, and read back and printed, has one row per turbine in sorted order, thanks to the BTreeMap:
turbine,count,mean,max
T1,3,10.667,14
T2,3,12.833,15.5
T3,3,6.500,11
The round trip check confirmed that the text read back from the file was identical to the text written (true), and its size, 69 bytes, equals the length that Python computed for the same text. The hours of the accepted rows add up to 14, a simple checksum that Python reproduced. The file was created in the system’s temporary directory and removed at the end, so the program leaves nothing behind.
Independent check: a Python script parsed the same twelve lines with its own int and float conversions, rejected the same four, and computed the per-turbine count, mean and maximum. Every row of the table, the list of rejected line numbers and the hour sum match the Rust output exactly. Where the Rust output prints a whole-number maximum such as 14, Python prints 14.0, which is only a difference in formatting, since Rust’s Display for f64 leaves off a trailing .0.
Check by hand: T1 has three good readings, 8.5, 9.5 and 14.0, whose mean is 32 / 3 = 10.667. T2 has 12.0, 15.5 and 11.0 with mean 38.5 / 3 = 12.833. T3 has 4.0, 4.5 and 11.0 with mean 19.5 / 3 = 6.5. Of the four rejected lines, one has a text speed, one has two fields instead of three, one has the hour 25 and one a negative speed.
This parser breaks on quoted fields that contain commas or line breaks. For real-world CSV, use a tested CSV crate and check its documentation on crates.io.
Counting and listing rejected lines, with their numbers, lets a person fix the source. Silently skipping them makes the totals look right and wrong at the same time.
Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording.
Practice
Add a column with the direction in degrees and reject values above 360. Write a second report that lists the hour of each turbine’s maximum. Read the CSV from a file given on the command line using std::env::args, and print a usage message if it is missing.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why use BTreeMap instead of HashMap here?
- Sorted, repeatable output
- It is always faster
- It uses less memory
- It allows duplicates
Deterministic order.
How were rejected lines reported?
- Silently skipped
- As a panic
- Only counted
- With their line numbers and the reason
So the source can be fixed.
What does map_err do?
- Maps over a list
- Prints an error
- Ignores errors
- Converts the error type of a Result
Used with ?.
How was the file verified?
- By trusting it
- By screenshot
- Read back and compared, and recomputed in Python
- Not verified
Round trip plus an independent implementation.
When is splitting on commas not enough?
- Never
- For numbers
- Quoted fields containing commas
- For short files
Use a proper CSV crate.
Summary
- Parse each line into a Result and report the failures with line numbers.
- BTreeMap groups and keeps a stable order.
- std::fs writes and reads files.
- Independent verification in Python confirms every figure.
Questions
How do I read a file passed on the command line?
Take the path from std::env::args().nth(1), read it with std::fs::read_to_string, and match the Result to print a clear message if it fails.
What does or_default do?
It inserts the default value of the type, here an empty Vec, if the key is missing, and returns a mutable reference to it.
Is writing to the temp directory safe?
It is fine for demonstrations. Real programs should use a unique name or a tempfile crate to avoid collisions. Check the documentation of the one you choose.
