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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::collections::HashSet;

use abstutil::{prettyprint_usize, Counter, Timer};
use geom::{Distance, Duration, Polygon, UnitFmt};
use map_gui::load::FileLoader;
use map_gui::tools::{open_browser, ColorNetwork};
use map_gui::ID;
use map_model::{PathRequest, PathStepV2, RoadID};
use sim::{Scenario, TripEndpoint, TripMode};
use widgetry::mapspace::ToggleZoomed;
use widgetry::{
    Color, EventCtx, GeomBatch, GfxCtx, Line, Outcome, Panel, Spinner, State, Text, TextExt, Widget,
};

use crate::app::{App, Transition};
use crate::ungap::{Layers, Tab, TakeLayers};

pub struct ShowGaps {
    top_panel: Panel,
    layers: Layers,
    tooltip: Option<Text>,
}

impl TakeLayers for ShowGaps {
    fn take_layers(self) -> Layers {
        self.layers
    }
}

impl ShowGaps {
    pub fn new_state(ctx: &mut EventCtx, app: &mut App, layers: Layers) -> Box<dyn State<App>> {
        let map_name = app.primary.map.get_name().clone();
        let change_key = app.primary.map.get_edits_change_key();
        if app.session.mode_shift.key().as_ref() == Some(&(map_name.clone(), change_key)) {
            return Box::new(ShowGaps {
                top_panel: make_top_panel(ctx, app),
                layers,
                tooltip: None,
            });
        }

        let scenario_name = crate::pregame::default_scenario_for_map(&map_name);
        if scenario_name == "home_to_work" {
            // TODO Should we generate and use this scenario? Or maybe just disable this mode
            // entirely?
            app.session
                .mode_shift
                .set((map_name, change_key), ModeShiftData::empty(ctx));
            ShowGaps::new_state(ctx, app, layers)
        } else {
            FileLoader::<App, Scenario>::new_state(
                ctx,
                abstio::path_scenario(&map_name, &scenario_name),
                Box::new(move |ctx, app, _, maybe_scenario| {
                    // TODO Handle corrupt files
                    let scenario = maybe_scenario.unwrap();
                    let data = ctx.loading_screen("predict mode shift", |ctx, timer| {
                        ModeShiftData::from_scenario(ctx, app, scenario, timer)
                    });
                    app.session.mode_shift.set((map_name, change_key), data);
                    Transition::Replace(ShowGaps::new_state(ctx, app, layers))
                }),
            )
        }
    }
}

impl State<App> for ShowGaps {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        ctx.canvas_movement();
        if ctx.redo_mouseover() {
            self.tooltip = None;
            if let Some(r) = match app.mouseover_unzoomed_roads_and_intersections(ctx) {
                Some(ID::Road(r)) => Some(r),
                Some(ID::Lane(l)) => Some(l.road),
                _ => None,
            } {
                let data = app.session.mode_shift.value().unwrap();
                let count = data.gaps.count_per_road.get(r);
                if count > 0 {
                    // TODO Word more precisely... or less verbosely.
                    self.tooltip = Some(Text::from(Line(format!(
                        "{} trips might cross this high-stress road",
                        prettyprint_usize(count)
                    ))));
                }
            }
        }

        match self.top_panel.event(ctx) {
            Outcome::Clicked(x) => {
                if x == "read about how this prediction works" {
                    open_browser("https://a-b-street.github.io/docs/software/bike_network/tech_details.html#predict-impact");
                    return Transition::Keep;
                }

                return Tab::PredictImpact
                    .handle_action::<ShowGaps>(ctx, app, &x)
                    .unwrap();
            }
            Outcome::Changed(_) => {
                let (map_name, mut data) = app.session.mode_shift.take().unwrap();
                data.filters = Filters::from_controls(&self.top_panel);
                ctx.loading_screen("update mode shift", |ctx, timer| {
                    data.recalculate_gaps(ctx, app, timer)
                });
                app.session.mode_shift.set(map_name, data);
                // TODO This is heavy-handed for just updating the counters
                self.top_panel = make_top_panel(ctx, app);
            }
            _ => {}
        }

        if let Some(t) = self.layers.event(ctx, app) {
            return t;
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.top_panel.draw(g);
        self.layers.draw(g, app);

        let data = app.session.mode_shift.value().unwrap();
        data.gaps.draw.draw(g);
        if let Some(ref txt) = self.tooltip {
            g.draw_mouse_tooltip(txt.clone());
        }
    }
}

fn make_top_panel(ctx: &mut EventCtx, app: &App) -> Panel {
    let data = app.session.mode_shift.value().unwrap();

    if data.all_candidate_trips.is_empty() {
        return Tab::PredictImpact.make_left_panel(
            ctx,
            app,
            Widget::col(vec![
                "This city doesn't have travel demand model data available".text_widget(ctx),
            ]),
        );
    }

    let col = vec![
        ctx.style()
            .btn_plain
            .icon_text(
                "system/assets/tools/info.svg",
                "How many drivers might switch to biking?",
            )
            .build_widget(ctx, "read about how this prediction works"),
        percentage_bar(
            ctx,
            Text::from(Line(format!(
                "{} total driving trips in this area",
                prettyprint_usize(data.all_candidate_trips.len())
            ))),
            0.0,
        ),
        Widget::col(vec![
            "Who might cycle if it was safer?".text_widget(ctx),
            data.filters.to_controls(ctx),
            percentage_bar(
                ctx,
                Text::from(Line(format!(
                    "{} / {} trips, based on these thresholds",
                    data.filtered_trips.len(),
                    data.all_candidate_trips.len()
                ))),
                pct(data.filtered_trips.len(), data.all_candidate_trips.len()),
            ),
        ])
        .section(ctx),
        Widget::col(vec![
            "How many would switch based on your proposal?".text_widget(ctx),
            percentage_bar(
                ctx,
                Text::from(Line(format!(
                    "{} / {} trips would switch",
                    data.results.num_trips,
                    data.all_candidate_trips.len()
                ))),
                pct(data.results.num_trips, data.all_candidate_trips.len()),
            ),
            data.results.describe().into_widget(ctx),
        ])
        .section(ctx),
    ];

    Tab::PredictImpact.make_left_panel(ctx, app, Widget::col(col))
}

// TODO For now, it's easier to just copy pieces from sandbox/dashboards/mode_shift.rs. I'm not
// sure how these two tools will interact yet, so not worth trying to refactor anything. One works
// off Scenario files directly, the other off an instantiated Scenario.

pub struct ModeShiftData {
    // Calculated from the unedited map, not yet filtered.
    all_candidate_trips: Vec<CandidateTrip>,
    filters: Filters,
    // From the unedited map, filtered
    gaps: NetworkGaps,
    // Indices into all_candidate_trips
    filtered_trips: Vec<usize>,
    results: Results,
}

struct CandidateTrip {
    bike_req: PathRequest,
    estimated_biking_time: Duration,
    driving_distance: Distance,
    total_elevation_gain: Distance,
}

struct Filters {
    max_biking_time: Duration,
    max_elevation_gain: Distance,
}

struct NetworkGaps {
    draw: ToggleZoomed,
    count_per_road: Counter<RoadID>,
}

// Of the filtered trips, which cross at least 1 edited road?
// TODO Many ways of defining this... maybe the edits need to plug the gap on at least 50% of
// stressful roads encountered by this trip?
struct Results {
    num_trips: usize,
    total_driving_distance: Distance,
    annual_co2_emissions_tons: f64,
}

impl Filters {
    fn default() -> Self {
        Self {
            max_biking_time: Duration::minutes(30),
            max_elevation_gain: Distance::feet(100.0),
        }
    }

    fn apply(&self, x: &CandidateTrip) -> bool {
        x.estimated_biking_time <= self.max_biking_time
            && x.total_elevation_gain <= self.max_elevation_gain
    }

    fn to_controls(&self, ctx: &mut EventCtx) -> Widget {
        Widget::col(vec![
            Widget::row(vec![
                "Max biking time".text_widget(ctx).centered_vert(),
                Spinner::widget(
                    ctx,
                    "max_biking_time",
                    (Duration::ZERO, Duration::hours(12)),
                    self.max_biking_time,
                    Duration::minutes(1),
                ),
            ]),
            Widget::row(vec![
                "Max elevation gain".text_widget(ctx).centered_vert(),
                Spinner::widget_with_custom_rendering(
                    ctx,
                    "max_elevation_gain",
                    (Distance::ZERO, Distance::feet(500.0)),
                    self.max_elevation_gain,
                    Distance::feet(10.0),
                    // Even if the user's settings are set to meters, our step size is in feet, so
                    // just render in feet.
                    Box::new(|x| {
                        x.to_string(&UnitFmt {
                            round_durations: false,
                            metric: false,
                        })
                    }),
                ),
            ]),
        ])
    }

    fn from_controls(panel: &Panel) -> Filters {
        Filters {
            max_biking_time: panel.spinner("max_biking_time"),
            max_elevation_gain: panel.spinner("max_elevation_gain"),
        }
    }
}

impl Results {
    fn default() -> Self {
        Self {
            num_trips: 0,
            total_driving_distance: Distance::ZERO,
            annual_co2_emissions_tons: 0.0,
        }
    }

    fn describe(&self) -> Text {
        let mut txt = Text::new();
        txt.add_line(Line(format!(
            "{} total vehicle miles traveled daily, now eliminated",
            prettyprint_usize(self.total_driving_distance.to_miles() as usize)
        )));
        // Round to 1 decimal place
        let tons = (self.annual_co2_emissions_tons * 10.0).round() / 10.0;
        txt.add_line(Line(format!(
            "{} tons of CO2 emissions saved annually",
            tons
        )));
        txt
    }
}

impl ModeShiftData {
    fn empty(ctx: &mut EventCtx) -> Self {
        Self {
            all_candidate_trips: Vec::new(),
            filters: Filters::default(),
            gaps: NetworkGaps {
                draw: ToggleZoomed::empty(ctx),
                count_per_road: Counter::new(),
            },
            filtered_trips: Vec::new(),
            results: Results::default(),
        }
    }

    fn from_scenario(
        ctx: &mut EventCtx,
        app: &App,
        scenario: Scenario,
        timer: &mut Timer,
    ) -> ModeShiftData {
        let map = app
            .primary
            .unedited_map
            .as_ref()
            .unwrap_or(&app.primary.map);
        let all_candidate_trips = timer
            .parallelize(
                "analyze trips",
                scenario
                    .all_trips()
                    .filter(|trip| {
                        trip.mode == TripMode::Drive
                            && matches!(trip.origin, TripEndpoint::Bldg(_))
                            && matches!(trip.destination, TripEndpoint::Bldg(_))
                    })
                    .collect(),
                |trip| {
                    // TODO Does ? work
                    if let (Some(driving_path), Some(biking_path)) = (
                        TripEndpoint::path_req(trip.origin, trip.destination, TripMode::Drive, map)
                            .and_then(|req| map.pathfind(req).ok()),
                        TripEndpoint::path_req(trip.origin, trip.destination, TripMode::Bike, map)
                            .and_then(|req| map.pathfind(req).ok()),
                    ) {
                        let (total_elevation_gain, _) = biking_path.get_total_elevation_change(map);
                        Some(CandidateTrip {
                            bike_req: biking_path.get_req().clone(),
                            estimated_biking_time: biking_path
                                .estimate_duration(map, Some(map_model::MAX_BIKE_SPEED)),
                            driving_distance: driving_path.total_length(),
                            total_elevation_gain,
                        })
                    } else {
                        None
                    }
                },
            )
            .into_iter()
            .flatten()
            .collect();
        let mut data = ModeShiftData::empty(ctx);
        data.all_candidate_trips = all_candidate_trips;
        data.recalculate_gaps(ctx, app, timer);
        data
    }

    fn recalculate_gaps(&mut self, ctx: &mut EventCtx, app: &App, timer: &mut Timer) {
        let map = app
            .primary
            .unedited_map
            .as_ref()
            .unwrap_or(&app.primary.map);

        // Find all high-stress roads, since we'll filter by them next
        let high_stress: HashSet<RoadID> = map
            .all_roads()
            .iter()
            .filter_map(|r| {
                if r.high_stress_for_bikes(map) {
                    Some(r.id)
                } else {
                    None
                }
            })
            .collect();

        self.filtered_trips.clear();
        let mut filtered_requests = Vec::new();
        for (idx, trip) in self.all_candidate_trips.iter().enumerate() {
            if self.filters.apply(trip) {
                self.filtered_trips.push(idx);
                filtered_requests.push((idx, trip.bike_req.clone()));
            }
        }

        self.results = Results::default();

        let mut count_per_road = Counter::new();
        for (idx, path) in timer
            .parallelize("calculate routes", filtered_requests, |(idx, req)| {
                map.pathfind_v2(req).map(|path| (idx, path))
            })
            .into_iter()
            .flatten()
        {
            let mut crosses_edited_road = false;
            for step in path.get_steps() {
                // No Contraflow steps for bike paths
                if let PathStepV2::Along(dr) = step {
                    if high_stress.contains(&dr.id) {
                        count_per_road.inc(dr.id);

                        // TODO Assumes the edits have made the road stop being high stress!
                        if !crosses_edited_road
                            && app.primary.map.get_edits().changed_roads.contains(&dr.id)
                        {
                            crosses_edited_road = true;
                        }
                    }
                }
            }
            if crosses_edited_road {
                self.results.num_trips += 1;
                self.results.total_driving_distance +=
                    self.all_candidate_trips[idx].driving_distance;
            }
        }

        // Assume this trip happens 5 times a week, 52 weeks a year.
        let annual_mileage = 5.0 * 52.0 * self.results.total_driving_distance.to_miles();
        // https://www.epa.gov/greenvehicles/greenhouse-gas-emissions-typical-passenger-vehicle#driving
        // says 404 grams per mile.
        // And convert grams to tons
        self.results.annual_co2_emissions_tons = 404.0 * annual_mileage / 907185.0;

        let mut colorer = ColorNetwork::no_fading(app);
        colorer.ranked_roads(count_per_road.clone(), &app.cs.good_to_bad_red);
        self.gaps = NetworkGaps {
            draw: colorer.build(ctx),
            count_per_road,
        };
    }
}

fn percentage_bar(ctx: &mut EventCtx, txt: Text, pct_green: f64) -> Widget {
    let car_color = Color::RED;
    let bike_color = Color::GREEN;

    let total_width = 450.0;
    let height = 32.0;
    let radius = 4.0;

    let mut batch = GeomBatch::new();
    // Background
    batch.push(
        car_color,
        Polygon::rounded_rectangle(total_width, height, radius),
    );
    // Foreground
    if let Some(poly) = Polygon::maybe_rounded_rectangle(pct_green * total_width, height, radius) {
        batch.push(bike_color, poly);
    }
    // Text
    let label = txt.render_autocropped(ctx);
    let dims = label.get_dims();
    batch.append(label.translate(10.0, height / 2.0 - dims.height / 2.0));
    batch.into_widget(ctx)
}

fn pct(value: usize, total: usize) -> f64 {
    if total == 0 {
        1.0
    } else {
        value as f64 / total as f64
    }
}