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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use std::collections::BTreeSet;
use anyhow::Result;
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
use serde::Serialize;
use map_gui::tools::checkbox_per_mode;
use map_model::PathV2;
use synthpop::make::ScenarioGenerator;
use synthpop::{Scenario, TripMode};
use widgetry::tools::{FileLoader, PopupMsg};
use widgetry::{
Color, DrawBaselayer, Drawable, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome,
Panel, Slider, State, Text, TextExt, Toggle, VerticalAlignment, Widget,
};
use crate::impact::{end_of_day, Filters, Impact};
use crate::{colors, App, BrowseNeighbourhoods, Transition};
pub struct ShowResults {
top_panel: Panel,
left_panel: Panel,
}
impl ShowResults {
pub fn new_state(ctx: &mut EventCtx, app: &mut App) -> Box<dyn State<App>> {
let map_name = app.map.get_name().clone();
if app.session.impact.map != map_name {
let scenario_name = Scenario::default_scenario_for_map(&map_name);
if scenario_name != "home_to_work" {
return FileLoader::<App, Scenario>::new_state(
ctx,
abstio::path_scenario(&map_name, &scenario_name),
Box::new(move |ctx, app, timer, maybe_scenario| {
let scenario = maybe_scenario.unwrap();
app.session.impact = Impact::from_scenario(ctx, app, scenario, timer);
Transition::Replace(ShowResults::new_state(ctx, app))
}),
);
}
ctx.loading_screen("synthesize travel demand model", |ctx, timer| {
app.map.keep_pathfinder_despite_edits();
let scenario = ScenarioGenerator::proletariat_robot(
&app.map,
&mut XorShiftRng::seed_from_u64(42),
timer,
);
app.session.impact = Impact::from_scenario(ctx, app, scenario, timer);
});
}
if app.session.impact.change_key != app.session.modal_filters.get_change_key() {
ctx.loading_screen("recalculate impact", |ctx, timer| {
let mut impact = std::mem::replace(&mut app.session.impact, Impact::empty(ctx));
impact.map_edits_changed(ctx, app, timer);
app.session.impact = impact;
});
}
let contents = Widget::col(vec![
BrowseNeighbourhoods::button(ctx, app),
Line("Impact prediction").small_heading().into_widget(ctx),
Text::from(Line("This tool starts with a travel demand model, calculates the route every trip takes before and after changes, and displays volumes along roads")).wrap_to_pct(ctx, 20).into_widget(ctx),
Text::from_all(vec![
Line("Red").fg(Color::RED),
Line(" roads have increased volume, and "),
Line("green").fg(Color::GREEN),
Line(" roads have less. Width of the road shows how much baseline traffic it has."),
]).wrap_to_pct(ctx, 20).into_widget(ctx),
Text::from(Line("Click a road to see changed routes through it.")).wrap_to_pct(ctx, 20).into_widget(ctx),
Text::from(Line("Results may be wrong for various reasons. Interpret carefully.")).wrap_to_pct(ctx, 20).into_widget(ctx),
app.session.impact.filters.to_panel(ctx, app),
app.session
.impact
.compare_counts
.get_panel_widget(ctx)
.named("compare counts"),
ctx.style()
.btn_outline
.text("Save before/after counts to files (JSON)")
.build_def(ctx),
ctx.style()
.btn_outline
.text("Save before/after counts to files (CSV)")
.build_def(ctx),
]);
let top_panel = crate::components::TopPanel::panel(ctx, app);
let left_panel =
crate::components::LeftPanel::builder(ctx, &top_panel, contents).build(ctx);
Box::new(Self {
top_panel,
left_panel,
})
}
}
impl State<App> for ShowResults {
fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
if let Some(t) = crate::components::TopPanel::event(ctx, app, &mut self.top_panel, help) {
return t;
}
match self.left_panel.event(ctx) {
Outcome::Clicked(x) => match x.as_ref() {
"Browse neighbourhoods" => {
return Transition::Replace(BrowseNeighbourhoods::new_state(ctx, app));
}
"Save before/after counts to files (JSON)" => {
let path1 = "counts_a.json";
let path2 = "counts_b.json";
abstio::write_json(
path1.to_string(),
&app.session.impact.compare_counts.counts_a,
);
abstio::write_json(
path2.to_string(),
&app.session.impact.compare_counts.counts_b,
);
return Transition::Push(PopupMsg::new_state(
ctx,
"Saved",
vec![format!("Saved {} and {}", path1, path2)],
));
}
"Save before/after counts to files (CSV)" => {
let path = "before_after_counts.csv";
let msg = match export_csv(app)
.and_then(|contents| abstio::write_file(path.to_string(), contents))
{
Ok(_) => format!("Saved {path}"),
Err(err) => format!("Failed to export: {err}"),
};
return Transition::Push(PopupMsg::new_state(ctx, "CSV export", vec![msg]));
}
x => {
let mut impact = std::mem::replace(&mut app.session.impact, Impact::empty(ctx));
let widget = impact
.compare_counts
.on_click(ctx, app, x)
.expect("button click didn't belong to CompareCounts");
app.session.impact = impact;
self.left_panel.replace(ctx, "compare counts", widget);
return Transition::Keep;
}
},
Outcome::Changed(_) => {
let filters = Filters::from_panel(&self.left_panel);
if filters == app.session.impact.filters {
return Transition::Keep;
}
let mut impact = std::mem::replace(&mut app.session.impact, Impact::empty(ctx));
impact.filters = Filters::from_panel(&self.left_panel);
ctx.loading_screen("update filters", |ctx, timer| {
impact.trips_changed(ctx, app, timer);
});
app.session.impact = impact;
return Transition::Keep;
}
_ => {}
}
if let Some(r) = app.session.impact.compare_counts.other_event(ctx) {
let results = ctx.loading_screen("find changed routes", |_, timer| {
app.session.impact.find_changed_routes(app, r, timer)
});
return Transition::Push(ChangedRoutes::new_state(ctx, app, results));
}
Transition::Keep
}
fn draw_baselayer(&self) -> DrawBaselayer {
DrawBaselayer::Custom
}
fn draw(&self, g: &mut GfxCtx, app: &App) {
g.clear(app.cs.void_background);
g.redraw(&app.draw_map.boundary_polygon);
g.redraw(&app.draw_map.draw_all_areas);
app.session.impact.compare_counts.draw(g, app);
app.session.draw_all_filters.draw(g);
self.top_panel.draw(g);
self.left_panel.draw(g);
}
}
impl Filters {
fn from_panel(panel: &Panel) -> Filters {
let (p1, p2) = (
panel.slider("depart from").get_percent(),
panel.slider("depart until").get_percent(),
);
let departure_time = (end_of_day().percent_of(p1), end_of_day().percent_of(p2));
let modes = TripMode::all()
.into_iter()
.filter(|m| panel.is_checked(m.ongoing_verb()))
.collect::<BTreeSet<_>>();
Filters {
modes,
include_borders: panel.is_checked("include borders"),
departure_time,
}
}
fn to_panel(&self, ctx: &mut EventCtx, app: &App) -> Widget {
Widget::col(vec![
"Filter trips".text_widget(ctx),
Toggle::switch(ctx, "include borders", None, self.include_borders),
Widget::row(vec![
"Departing from:".text_widget(ctx).margin_right(20),
Slider::area(
ctx,
0.15 * ctx.canvas.window_width,
self.departure_time.0.to_percent(end_of_day()),
"depart from",
),
]),
Widget::row(vec![
"Departing until:".text_widget(ctx).margin_right(20),
Slider::area(
ctx,
0.15 * ctx.canvas.window_width,
self.departure_time.1.to_percent(end_of_day()),
"depart until",
),
]),
checkbox_per_mode(ctx, app, &self.modes),
])
.section(ctx)
}
}
fn help() -> Vec<&'static str> {
vec![
"This tool is still experimental.",
"Until better travel demand models are available, we can't predict where most detours will occur,",
"because we don't know where trips begin and end.",
"",
"And note this tool doesn't predict traffic dissipation as people decide to not drive.",
]
}
struct ChangedRoutes {
panel: Panel,
paths: Vec<(PathV2, PathV2)>,
current: usize,
draw_paths: Drawable,
}
impl ChangedRoutes {
fn new_state(
ctx: &mut EventCtx,
app: &App,
paths: Vec<(PathV2, PathV2)>,
) -> Box<dyn State<App>> {
if paths.is_empty() {
return PopupMsg::new_state(
ctx,
"No changes",
vec!["No routes changed near this road"],
);
}
let mut state = ChangedRoutes {
panel: Panel::new_builder(Widget::col(vec![
Widget::row(vec![
Line("Routes that changed near a road")
.small_heading()
.into_widget(ctx),
ctx.style().btn_close_widget(ctx),
]),
Widget::row(vec![
ctx.style()
.btn_prev()
.hotkey(Key::LeftArrow)
.build_widget(ctx, "previous"),
"route X/Y"
.text_widget(ctx)
.named("pointer")
.centered_vert(),
ctx.style()
.btn_next()
.hotkey(Key::RightArrow)
.build_widget(ctx, "next"),
])
.evenly_spaced(),
Line("Route before changes")
.fg(*colors::PLAN_ROUTE_BEFORE)
.into_widget(ctx),
Line("Route after changes")
.fg(*colors::PLAN_ROUTE_AFTER)
.into_widget(ctx),
]))
.aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
.build(ctx),
paths,
current: 0,
draw_paths: Drawable::empty(ctx),
};
state.recalculate(ctx, app);
Box::new(state)
}
fn recalculate(&mut self, ctx: &mut EventCtx, app: &App) {
self.panel.replace(
ctx,
"pointer",
format!("route {}/{}", self.current + 1, self.paths.len()).text_widget(ctx),
);
let mut batch = map_gui::tools::draw_overlapping_paths(
app,
vec![
(
self.paths[self.current].0.clone(),
*colors::PLAN_ROUTE_BEFORE,
),
(
self.paths[self.current].1.clone(),
*colors::PLAN_ROUTE_AFTER,
),
],
)
.unzoomed;
let req = self.paths[self.current].0.get_req();
batch.append(map_gui::tools::start_marker(
ctx,
req.start.pt(&app.map),
2.0,
));
batch.append(map_gui::tools::goal_marker(ctx, req.end.pt(&app.map), 2.0));
self.draw_paths = ctx.upload(batch);
}
}
impl State<App> for ChangedRoutes {
fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
ctx.canvas_movement();
if let Outcome::Clicked(x) = self.panel.event(ctx) {
match x.as_ref() {
"close" => {
return Transition::Pop;
}
"previous" => {
if self.current != 0 {
self.current -= 1;
}
self.recalculate(ctx, app);
}
"next" => {
if self.current != self.paths.len() - 1 {
self.current += 1;
}
self.recalculate(ctx, app);
}
_ => unreachable!(),
}
}
Transition::Keep
}
fn draw(&self, g: &mut GfxCtx, app: &App) {
self.panel.draw(g);
g.redraw(&self.draw_paths);
app.session.draw_all_filters.draw(g);
app.session.draw_poi_icons.draw(g);
}
}
fn export_csv(app: &App) -> Result<String> {
let mut out = Vec::new();
{
let mut writer = csv::Writer::from_writer(&mut out);
for r in app.map.all_roads() {
writer.serialize(ExportRow {
road_name: r.get_name(None),
osm_way_id: r.orig_id.osm_way_id.0,
osm_intersection1: r.orig_id.i1.0,
osm_intersection2: r.orig_id.i2.0,
total_count_before: app
.session
.impact
.compare_counts
.counts_a
.per_road
.get(r.id),
total_count_after: app
.session
.impact
.compare_counts
.counts_b
.per_road
.get(r.id),
})?;
}
writer.flush()?;
}
let out = String::from_utf8(out)?;
Ok(out)
}
#[derive(Serialize)]
struct ExportRow {
road_name: String,
osm_way_id: i64,
osm_intersection1: i64,
osm_intersection2: i64,
total_count_before: usize,
total_count_after: usize,
}