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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use abstutil::{prettyprint_usize, Counter, Parallelism, Timer};
use map_gui::colors::ColorSchemeChoice;
use map_gui::tools::ColorNetwork;
use map_gui::{AppLike, ID};
use map_model::{PathRequest, RoadID, RoutingParams, Traversable, NORMAL_LANE_THICKNESS};
use sim::{TripEndpoint, TripMode};
use widgetry::{
    Color, Drawable, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel,
    Spinner, State, Text, TextExt, TextSpan, VerticalAlignment, Widget,
};

use crate::app::{App, Transition};
use crate::common::CommonState;

/// See how live-tuned routing parameters affect a single request.
pub struct RouteExplorer {
    panel: Panel,
    start: TripEndpoint,
    // (endpoint, confirmed, render the paths to it)
    goal: Option<(TripEndpoint, bool, Drawable)>,
}

impl RouteExplorer {
    pub fn new(ctx: &mut EventCtx, app: &App, start: TripEndpoint) -> Box<dyn State<App>> {
        Box::new(RouteExplorer {
            start,
            goal: None,
            panel: Panel::new(Widget::col(vec![
                Widget::row(vec![
                    Line("Route explorer").small_heading().draw(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                ctx.style()
                    .btn_outline
                    .text("All routes")
                    .hotkey(Key::A)
                    .build_def(ctx),
                params_to_controls(ctx, TripMode::Bike, &app.primary.map.routing_params())
                    .named("params"),
            ]))
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx),
        })
    }

    fn recalc_paths(&mut self, ctx: &mut EventCtx, app: &App) {
        let (mode, params) = controls_to_params(&self.panel);

        if let Some((ref goal, _, ref mut preview)) = self.goal {
            *preview = Drawable::empty(ctx);
            if let Some(polygon) =
                TripEndpoint::path_req(self.start.clone(), goal.clone(), mode, &app.primary.map)
                    .and_then(|req| app.primary.map.pathfind_with_params(req, &params).ok())
                    .and_then(|path| path.trace(&app.primary.map))
                    .map(|pl| pl.make_polygons(NORMAL_LANE_THICKNESS))
            {
                *preview = GeomBatch::from(vec![(Color::PURPLE, polygon)]).upload(ctx);
            }
        }
    }
}

impl State<App> for RouteExplorer {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        ctx.canvas_movement();

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                "bikes" => {
                    let controls =
                        params_to_controls(ctx, TripMode::Bike, app.primary.map.routing_params());
                    self.panel.replace(ctx, "params", controls);
                    self.recalc_paths(ctx, app);
                }
                "cars" => {
                    let controls =
                        params_to_controls(ctx, TripMode::Drive, app.primary.map.routing_params());
                    self.panel.replace(ctx, "params", controls);
                    self.recalc_paths(ctx, app);
                }
                "pedestrians" => {
                    let controls =
                        params_to_controls(ctx, TripMode::Walk, app.primary.map.routing_params());
                    self.panel.replace(ctx, "params", controls);
                    self.recalc_paths(ctx, app);
                }
                "All routes" => {
                    return Transition::Replace(AllRoutesExplorer::new(ctx, app));
                }
                _ => unreachable!(),
            },
            Outcome::Changed => {
                self.recalc_paths(ctx, app);
            }
            _ => {}
        }

        if self
            .goal
            .as_ref()
            .map(|(_, confirmed, _)| *confirmed)
            .unwrap_or(false)
        {
            return Transition::Keep;
        }

        if ctx.redo_mouseover() {
            app.primary.current_selection = app.mouseover_unzoomed_everything(ctx);
            if match app.primary.current_selection {
                Some(ID::Intersection(i)) => !app.primary.map.get_i(i).is_border(),
                Some(ID::Building(_)) => false,
                _ => true,
            } {
                app.primary.current_selection = None;
            }
        }
        if let Some(hovering) = match app.primary.current_selection {
            Some(ID::Intersection(i)) => Some(TripEndpoint::Border(i)),
            Some(ID::Building(b)) => Some(TripEndpoint::Bldg(b)),
            None => None,
            _ => unreachable!(),
        } {
            if self.start != hovering {
                if self
                    .goal
                    .as_ref()
                    .map(|(to, _, _)| to != &hovering)
                    .unwrap_or(true)
                {
                    self.goal = Some((hovering, false, Drawable::empty(ctx)));
                    self.recalc_paths(ctx, app);
                }
            } else {
                self.goal = None;
            }
        } else {
            self.goal = None;
        }

        if let Some((_, ref mut confirmed, _)) = self.goal {
            if app.per_obj.left_click(ctx, "end here") {
                app.primary.current_selection = None;
                *confirmed = true;
            }
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.panel.draw(g);
        CommonState::draw_osd(g, app);

        g.draw_polygon(
            Color::BLUE.alpha(0.8),
            match self.start {
                TripEndpoint::Border(i) => app.primary.map.get_i(i).polygon.clone(),
                TripEndpoint::Bldg(b) => app.primary.map.get_b(b).polygon.clone(),
                TripEndpoint::SuddenlyAppear(_) => unreachable!(),
            },
        );
        if let Some((ref endpt, _, ref draw)) = self.goal {
            g.draw_polygon(
                Color::GREEN.alpha(0.8),
                match endpt {
                    TripEndpoint::Border(i) => app.primary.map.get_i(*i).polygon.clone(),
                    TripEndpoint::Bldg(b) => app.primary.map.get_b(*b).polygon.clone(),
                    TripEndpoint::SuddenlyAppear(_) => unreachable!(),
                },
            );
            g.redraw(draw);
        }
    }
}

fn params_to_controls(ctx: &mut EventCtx, mode: TripMode, params: &RoutingParams) -> Widget {
    let mut rows = vec![Widget::custom_row(vec![
        ctx.style()
            .btn_plain
            .icon("system/assets/meters/bike.svg")
            .disabled(mode == TripMode::Bike)
            .build_widget(ctx, "bikes"),
        ctx.style()
            .btn_plain
            .icon("system/assets/meters/car.svg")
            .disabled(mode == TripMode::Drive)
            .build_widget(ctx, "cars"),
        ctx.style()
            .btn_plain
            .icon("system/assets/meters/pedestrian.svg")
            .disabled(mode == TripMode::Walk)
            .build_widget(ctx, "pedestrians"),
    ])
    .evenly_spaced()];
    if mode == TripMode::Drive || mode == TripMode::Bike {
        rows.push(Widget::row(vec![
            "Unprotected turn penalty:".draw_text(ctx).margin_right(20),
            Spinner::widget(
                ctx,
                (1, 100),
                (params.unprotected_turn_penalty * 10.0) as isize,
            )
            .named("unprotected turn penalty"),
        ]));
    }
    if mode == TripMode::Bike {
        // TODO Spinners that natively understand a floating point range with a given precision
        rows.push(Widget::row(vec![
            "Bike lane penalty:".draw_text(ctx).margin_right(20),
            Spinner::widget(ctx, (0, 20), (params.bike_lane_penalty * 10.0) as isize)
                .named("bike lane penalty"),
        ]));
        rows.push(Widget::row(vec![
            "Bus lane penalty:".draw_text(ctx).margin_right(20),
            Spinner::widget(ctx, (0, 20), (params.bus_lane_penalty * 10.0) as isize)
                .named("bus lane penalty"),
        ]));
        rows.push(Widget::row(vec![
            "Driving lane penalty:".draw_text(ctx).margin_right(20),
            Spinner::widget(ctx, (0, 20), (params.driving_lane_penalty * 10.0) as isize)
                .named("driving lane penalty"),
        ]));
    }
    Widget::col(rows)
}

fn controls_to_params(panel: &Panel) -> (TripMode, RoutingParams) {
    let mut params = RoutingParams::default();
    if !panel.is_button_enabled("cars") {
        params.unprotected_turn_penalty = panel.spinner("unprotected turn penalty") as f64 / 10.0;
        return (TripMode::Drive, params);
    }
    if !panel.is_button_enabled("pedestrians") {
        return (TripMode::Walk, params);
    }
    params.unprotected_turn_penalty = panel.spinner("unprotected turn penalty") as f64 / 10.0;
    params.bike_lane_penalty = panel.spinner("bike lane penalty") as f64 / 10.0;
    params.bus_lane_penalty = panel.spinner("bus lane penalty") as f64 / 10.0;
    params.driving_lane_penalty = panel.spinner("driving lane penalty") as f64 / 10.0;
    (TripMode::Bike, params)
}

/// See how live-tuned routing parameters affect all requests for the current scenario.
struct AllRoutesExplorer {
    panel: Panel,
    requests: Vec<PathRequest>,
    baseline_counts: Counter<RoadID>,

    current_counts: Counter<RoadID>,
    unzoomed: Drawable,
    zoomed: Drawable,
    tooltip: Option<Text>,
}

impl AllRoutesExplorer {
    fn new(ctx: &mut EventCtx, app: &mut App) -> Box<dyn State<App>> {
        // Tuning the differential scale is hard enough; always use day mode.
        app.change_color_scheme(ctx, ColorSchemeChoice::DayMode);

        let (requests, baseline_counts) =
            ctx.loading_screen("calculate baseline paths", |_, mut timer| {
                let map = &app.primary.map;
                let requests = timer
                    .parallelize(
                        "predict route requests",
                        Parallelism::Fastest,
                        app.primary.sim.all_trip_info(),
                        |(_, trip)| TripEndpoint::path_req(trip.start, trip.end, trip.mode, map),
                    )
                    .into_iter()
                    .flatten()
                    .collect::<Vec<_>>();
                let baseline_counts = calculate_demand(app, &requests, &mut timer);
                (requests, baseline_counts)
            });
        let current_counts = baseline_counts.clone();

        // Start by showing the original counts, not relative to anything
        let mut colorer = ColorNetwork::new(app);
        colorer.ranked_roads(current_counts.clone(), &app.cs.good_to_bad_red);
        let (unzoomed, zoomed) = colorer.build(ctx);

        Box::new(AllRoutesExplorer {
            panel: Panel::new(Widget::col(vec![
                Widget::row(vec![
                    Line("All routes explorer").small_heading().draw(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                format!("{} total requests", prettyprint_usize(requests.len())).draw_text(ctx),
                params_to_controls(ctx, TripMode::Bike, app.primary.map.routing_params())
                    .named("params"),
                ctx.style()
                    .btn_outline
                    .text("Calculate differential demand")
                    .build_def(ctx),
                ctx.style()
                    .btn_solid_destructive
                    .text("keep changed params")
                    .build_def(ctx),
            ]))
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx),
            requests,
            baseline_counts,
            current_counts,
            unzoomed,
            zoomed,
            tooltip: None,
        })
    }
}

impl State<App> for AllRoutesExplorer {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        ctx.canvas_movement();

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    ctx.loading_screen("revert routing params to defaults", |_, mut timer| {
                        app.primary
                            .map
                            .hack_override_routing_params(RoutingParams::default(), &mut timer);
                    });
                    return Transition::Pop;
                }
                "keep changed params" => {
                    // This is handy for seeing the effects on a real simulation without rebuilding
                    // the map.
                    ctx.loading_screen("update routing params", |_, mut timer| {
                        let (_, params) = controls_to_params(&self.panel);
                        app.primary
                            .map
                            .hack_override_routing_params(params, &mut timer);
                    });
                    return Transition::Pop;
                }
                "bikes" => {
                    let controls =
                        params_to_controls(ctx, TripMode::Bike, app.primary.map.routing_params());
                    self.panel.replace(ctx, "params", controls);
                }
                "cars" => {
                    let controls =
                        params_to_controls(ctx, TripMode::Drive, app.primary.map.routing_params());
                    self.panel.replace(ctx, "params", controls);
                }
                "pedestrians" => {
                    let controls =
                        params_to_controls(ctx, TripMode::Walk, app.primary.map.routing_params());
                    self.panel.replace(ctx, "params", controls);
                }
                "Calculate differential demand" => {
                    ctx.loading_screen(
                        "calculate differential demand due to routing params",
                        |ctx, mut timer| {
                            let (_, params) = controls_to_params(&self.panel);
                            app.primary
                                .map
                                .hack_override_routing_params(params, &mut timer);
                            self.current_counts = calculate_demand(app, &self.requests, &mut timer);

                            // Calculate the difference
                            let mut colorer = ColorNetwork::new(app);
                            // TODO If this works well, promote it alongside DivergingScale
                            let more = &app.cs.good_to_bad_red;
                            let less = &app.cs.good_to_bad_green;
                            let comparisons = self
                                .baseline_counts
                                .clone()
                                .compare(self.current_counts.clone());
                            // Find the biggest gain/loss
                            let diff = comparisons
                                .iter()
                                .map(|(_, after, before)| {
                                    ((*after as isize) - (*before as isize)).abs() as usize
                                })
                                .max()
                                .unwrap() as f64;
                            for (r, before, after) in comparisons {
                                if after < before {
                                    colorer.add_r(r, less.eval((before - after) as f64 / diff));
                                } else if before < after {
                                    colorer.add_r(r, more.eval((after - before) as f64 / diff));
                                }
                            }
                            let (unzoomed, zoomed) = colorer.build(ctx);
                            self.unzoomed = unzoomed;
                            self.zoomed = zoomed;
                        },
                    );
                }
                _ => unreachable!(),
            },
            _ => {}
        }

        if ctx.redo_mouseover() {
            self.tooltip = None;
            if let Some(ID::Road(r)) = app.mouseover_unzoomed_roads_and_intersections(ctx) {
                let baseline = self.baseline_counts.get(r);
                let current = self.current_counts.get(r);
                let mut txt = Text::new();
                txt.append_all(cmp_count(current, baseline));
                txt.add(Line(format!("{} baseline", prettyprint_usize(baseline))));
                txt.add(Line(format!("{} now", prettyprint_usize(current))));
                self.tooltip = Some(txt);
            }
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.panel.draw(g);
        CommonState::draw_osd(g, app);
        if g.canvas.cam_zoom < app.opts.min_zoom_for_detail {
            g.redraw(&self.unzoomed);
        } else {
            g.redraw(&self.zoomed);
        }
        if let Some(ref txt) = self.tooltip {
            g.draw_mouse_tooltip(txt.clone());
        }
    }
}

fn calculate_demand(app: &App, requests: &Vec<PathRequest>, timer: &mut Timer) -> Counter<RoadID> {
    let map = &app.primary.map;
    let paths = timer
        .parallelize("pathfind", Parallelism::Fastest, requests.clone(), |req| {
            map.pathfind(req)
        })
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();
    let mut counter = Counter::new();
    timer.start_iter("compute demand", paths.len());
    for path in paths {
        timer.next();
        for step in path.get_steps() {
            if let Traversable::Lane(l) = step.as_traversable() {
                counter.inc(app.primary.map.get_l(l).parent);
            }
        }
    }
    counter
}

fn cmp_count(after: usize, before: usize) -> Vec<TextSpan> {
    if after == before {
        vec![Line("same")]
    } else if after < before {
        vec![
            Line(prettyprint_usize(before - after)).fg(Color::GREEN),
            Line(" less"),
        ]
    } else if after > before {
        vec![
            Line(prettyprint_usize(after - before)).fg(Color::RED),
            Line(" more"),
        ]
    } else {
        unreachable!()
    }
}