forked from deib-polimi/renoir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
car_accidents.rs
348 lines (320 loc) · 10.4 KB
/
car_accidents.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Instant;
use itertools::Itertools;
use renoir::operator::Operator;
use renoir::{prelude::*, Stream};
use serde::{Deserialize, Serialize};
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
const DAYS_BEFORE: [u16; 13] = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
type Week = (u16, u16);
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Accident {
#[serde(rename = "DATE")]
date: String,
#[serde(rename = "BOROUGH")]
borough: String,
#[serde(rename = "NUMBER OF PERSONS KILLED")]
killed: u32,
#[serde(rename = "CONTRIBUTING FACTOR VEHICLE 1")]
factor1: String,
#[serde(rename = "CONTRIBUTING FACTOR VEHICLE 2")]
factor2: String,
#[serde(rename = "CONTRIBUTING FACTOR VEHICLE 3")]
factor3: String,
#[serde(rename = "CONTRIBUTING FACTOR VEHICLE 4")]
factor4: String,
#[serde(rename = "CONTRIBUTING FACTOR VEHICLE 5")]
factor5: String,
}
impl Accident {
fn week(&self) -> Week {
let mut day = u16::from_str(&self.date[3..5]).unwrap();
let month = u16::from_str(&self.date[0..2]).unwrap();
let year = u16::from_str(&self.date[6..10]).unwrap();
day += DAYS_BEFORE[month as usize];
if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) && month >= 3 {
day += 1;
}
(year, day / 7)
}
}
fn query1_with_source(
source: Stream<impl Operator<Out = Accident> + 'static>,
) -> StreamOutput<Vec<(Week, u32)>> {
source
// map to the week with 1 if it was lethal, 0 otherwise
.map(|a| (a.week(), (a.killed > 0) as u32))
.group_by_sum(|(week, _killed)| *week, |(_week, killed)| killed)
.collect_vec()
}
fn query1<P: Into<PathBuf>>(env: &StreamContext, path: P) -> StreamOutput<Vec<(Week, u32)>> {
let source = CsvSource::<Accident>::new(path).has_headers(true);
let source = env.stream(source).batch_mode(BatchMode::fixed(1000));
query1_with_source(source)
}
#[allow(clippy::print_literal)]
fn print_query1(res: Vec<(Week, u32)>) {
println!(
"\x1b[1m\x1b[38;5;10m{}\x1b[0m",
"Number of lethal accidents per week"
);
let res_map: HashMap<(u16, u16), u32> = res.clone().into_iter().collect();
let (min_year, max_year) = res
.iter()
.map(|((y, _), _)| *y)
.minmax()
.into_option()
.unwrap();
print!("\t\x1b[1m");
for year in min_year..=max_year {
print!("{year}\t");
}
println!("\x1b[0m");
for week in 0..=52 {
print!("\x1b[1m{week}\x1b[0m\t");
for year in min_year..=max_year {
if let Some(r) = res_map.get(&(year, week)) {
if *r > 0 {
print!("{r}\t");
} else {
print!("\t");
}
} else {
print!("\t");
}
}
println!();
}
}
fn query2_with_source(
source: Stream<impl Operator<Out = Accident> + 'static>,
) -> StreamOutput<Vec<(String, i32, u32)>> {
source
// extract (factor, num accidents, num kills)
.flat_map(|a| {
vec![
(a.factor1, 1, (a.killed > 0) as u32),
(a.factor2, 1, (a.killed > 0) as u32),
(a.factor3, 1, (a.killed > 0) as u32),
(a.factor4, 1, (a.killed > 0) as u32),
(a.factor5, 1, (a.killed > 0) as u32),
]
.into_iter()
.unique()
.collect_vec()
})
// ignore empty factors
.filter(|(f, _, _)| !f.is_empty())
// group by factors
.group_by_fold(
|(f, _, _)| f.clone(),
(0, 0),
|(a1, k1), (_f, a2, k2)| {
*a1 += a2;
*k1 += k2
},
|(a1, k1), (a2, k2)| {
*a1 += a2;
*k1 += k2
},
)
.unkey()
.map(|(f, (a, k))| (f, a, k))
.collect_vec()
}
fn query2<P: Into<PathBuf>>(env: &StreamContext, path: P) -> StreamOutput<Vec<(String, i32, u32)>> {
let source = CsvSource::<Accident>::new(path).has_headers(true);
let source = env.stream(source).batch_mode(BatchMode::fixed(1000));
query2_with_source(source)
}
#[allow(clippy::print_literal)]
fn print_query2(res: Vec<(String, i32, u32)>) {
println!(
"\x1b[1m\x1b[38;5;10m{}\x1b[0m",
"Accident statistics per contributing factor"
);
let max_len = res.iter().map(|(f, _, _)| f.len()).max().unwrap();
println!(
"\x1b[1m{:<width$}\t#Accidents\t%lethal\x1b[0m",
"Contributing factor",
width = max_len
);
for (factor, accidents, kills) in res.iter().sorted() {
println!(
"{:<width$}\t{}\t\t{:.2}%",
factor,
accidents,
(*kills as f64) / (*accidents as f64) * 100.0,
width = max_len
);
}
}
#[allow(clippy::type_complexity)]
fn query3_with_source(
source: Stream<impl Operator<Out = Accident> + 'static>,
) -> (
StreamOutput<Vec<(String, Week, i32, u32)>>,
StreamOutput<Vec<((String, u16), (i32, u32, f64))>>,
) {
let mut splitted = source
.batch_mode(BatchMode::fixed(1000))
// extract borough, week, num accidents, num lethal
.map(|a| (a.borough.clone(), a.week(), 1, (a.killed > 0) as u32))
// group by (borough, week) and sum accidents and lethal
.group_by_fold(
|(borough, week, _, _)| (borough.clone(), *week),
(0, 0),
|(a1, k1), (_, _, a2, k2)| {
*a1 += a2;
*k1 += k2;
},
|(a1, k1), (a2, k2)| {
*a1 += a2;
*k1 += k2
},
)
.unkey()
.map(|((borough, week), (accidents, killed))| (borough, week, accidents, killed))
.split(2);
let res = splitted.pop().unwrap().collect_vec();
let avg_per_week = splitted
.pop()
.unwrap()
// map into (borough, week number, accidents, lethal accidents)
.map(|(b, (_, w), a, k)| (b, w, a, k))
// group by (borough, week number)
.group_by_fold(
|(b, w, _, _)| (b.clone(), *w),
(0, 0),
|(a1, k1), (_, _, a2, k2)| {
*a1 += a2;
*k1 += k2;
},
|(a1, k1), (a2, k2)| {
*a1 += a2;
*k1 += k2
},
)
.unkey()
// compute the average
.map(|((b, w), (a, k))| ((b, w), (a, k, 100.0 * (k as f64) / (a as f64))))
.collect_vec();
(res, avg_per_week)
}
#[allow(clippy::type_complexity)]
fn query3<P: Into<PathBuf>>(
env: &StreamContext,
path: P,
) -> (
StreamOutput<Vec<(String, Week, i32, u32)>>,
StreamOutput<Vec<((String, u16), (i32, u32, f64))>>,
) {
let source = CsvSource::<Accident>::new(path).has_headers(true);
let source = env.stream(source).batch_mode(BatchMode::fixed(1000));
query3_with_source(source)
}
#[allow(clippy::print_literal, clippy::type_complexity)]
fn print_query3(
res: Vec<(String, Week, i32, u32)>,
avg_per_week: Vec<((String, u16), (i32, u32, f64))>,
) {
println!(
"\x1b[1m\x1b[38;5;10m{}\x1b[0m",
"Accidents and lethal per borough"
);
let max_len = res.iter().map(|(b, _, _, _)| b.len()).max().unwrap();
let avg_per_week: HashMap<(String, u16), (i32, u32, f64)> = avg_per_week.into_iter().collect();
let groups = res
.iter()
.sorted_by_key(|(b, yw, _, _)| (b, yw))
.chunk_by(|(b, _, _, _)| b);
for (borough, data) in groups.into_iter() {
print!("\n\x1b[1m{borough:<max_len$}\t");
let data = data.into_iter().collect_vec();
let grouped: HashMap<_, _> = data.iter().map(|(_, yw, a, k)| (yw, (a, k))).collect();
let (min_year, max_year) = data
.iter()
.map(|(_, (y, _), _, _)| *y)
.minmax()
.into_option()
.unwrap();
for year in min_year..=max_year {
print!("{year}\t\t");
}
println!("average");
print!("{:>width$}\t", "week", width = max_len);
for _ in min_year..=max_year + 1 {
print!("#acc\t#let\t");
}
println!("%let\x1b[0m");
for week in 0..=52 {
print!("\x1b[1m{week:>max_len$}\x1b[0m\t");
for year in min_year..=max_year {
if let Some((a, k)) = grouped.get(&(year, week)) {
print!("{a}\t{k}\t");
} else {
print!("\t\t");
}
}
if let Some((a, k, perc)) = avg_per_week.get(&(borough.clone(), week)) {
print!("{a}\t{k}\t{perc:.4}%");
}
println!();
}
}
}
fn main() {
let (config, args) = RuntimeConfig::from_args();
if args.len() != 3 {
panic!(
"Usage: {} dataset share_source",
std::env::args().next().unwrap()
);
}
let path = &args[1];
let share_source = &args[2];
let share_source = match share_source.as_str() {
"true" => true,
"false" => false,
_ => panic!("share_source must be either `true` or `false`, not `{share_source}`"),
};
config.spawn_remote_workers();
let env = StreamContext::new(config);
let (query1, query2, query3) = if share_source {
let source = CsvSource::<Accident>::new(path).has_headers(true);
let mut splits = env
.stream(source)
.batch_mode(BatchMode::fixed(1000))
.split(3)
.into_iter();
(
query1_with_source(splits.next().unwrap()),
query2_with_source(splits.next().unwrap()),
query3_with_source(splits.next().unwrap()),
)
} else {
(query1(&env, path), query2(&env, path), query3(&env, path))
};
let start = Instant::now();
env.execute_blocking();
let elapsed = start.elapsed();
eprintln!("Elapsed: {elapsed:?}");
// print only in debug mode
if !cfg!(debug_assertions) {
return;
}
if let Some(query1) = query1.get() {
print_query1(query1);
}
if let Some(query2) = query2.get() {
print_query2(query2);
}
if let Some(res) = query3.0.get() {
if let Some(avg_per_week) = query3.1.get() {
print_query3(res, avg_per_week);
}
}
}