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
use crate::app::App;
use crate::common::Tab;
use crate::game::{DrawBaselayer, State, Transition};
use crate::sandbox::dashboards::DashTab;
use crate::sandbox::SandboxMode;
use abstutil::{prettyprint_usize, Counter};
use geom::Time;
use map_model::BusRouteID;
use widgetry::{
    Autocomplete, Btn, EventCtx, GfxCtx, Line, LinePlot, Outcome, Panel, PlotOptions, Series,
    TextExt, Widget,
};

pub struct ActiveTraffic {
    panel: Panel,
}

impl ActiveTraffic {
    pub fn new(ctx: &mut EventCtx, app: &App) -> Box<dyn State> {
        // TODO Downsampling in the middle of the day and comparing to the downsampled entire day
        // doesn't work. For the same simulation, by end of day, the plots will be identical, but
        // until then, they'll differ. See https://github.com/dabreegster/abstreet/issues/85 for
        // more details on the "downsampling subset" problem.
        let mut active_agents = vec![Series {
            label: format!("After \"{}\"", app.primary.map.get_edits().edits_name),
            color: app.cs.after_changes,
            pts: downsample(
                app.primary
                    .sim
                    .get_analytics()
                    .active_agents(app.primary.sim.time()),
            ),
        }];
        if app.has_prebaked().is_some() {
            active_agents.push(Series {
                label: format!("Before \"{}\"", app.primary.map.get_edits().edits_name),
                color: app.cs.before_changes.alpha(0.5),
                pts: downsample(
                    app.prebaked()
                        .active_agents(app.primary.sim.get_end_of_day()),
                ),
            });
        }

        Box::new(ActiveTraffic {
            panel: Panel::new(Widget::col(vec![
                DashTab::ActiveTraffic.picker(ctx, app),
                LinePlot::new(ctx, active_agents, PlotOptions::fixed()),
            ]))
            .exact_size_percent(90, 90)
            .build(ctx),
        })
    }
}

impl State for ActiveTraffic {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => DashTab::TripSummaries.transition(ctx, app, &x),
            _ => Transition::Keep,
        }
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::Custom
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        g.clear(app.cs.dialog_bg);
        self.panel.draw(g);
    }
}

fn downsample(raw: Vec<(Time, usize)>) -> Vec<(Time, usize)> {
    if raw.is_empty() {
        return raw;
    }

    let min_x = Time::START_OF_DAY;
    let min_y = 0;
    let max_x = raw.last().unwrap().0;
    let max_y = raw.iter().max_by_key(|(_, cnt)| *cnt).unwrap().1;

    let mut pts = Vec::new();
    for (t, cnt) in raw {
        pts.push(lttb::DataPoint::new(
            (t - min_x) / (max_x - min_x),
            ((cnt - min_y) as f64) / ((max_y - min_y) as f64),
        ));
    }
    let mut downsampled = Vec::new();
    for pt in lttb::lttb(pts, 100) {
        downsampled.push((
            max_x.percent_of(pt.x),
            min_y + (pt.y * (max_y - min_y) as f64) as usize,
        ));
    }
    downsampled
}

pub struct TransitRoutes {
    panel: Panel,
}

impl TransitRoutes {
    pub fn new(ctx: &mut EventCtx, app: &App) -> Box<dyn State> {
        // Count totals per route
        let mut boardings = Counter::new();
        for list in app.primary.sim.get_analytics().passengers_boarding.values() {
            for (_, r, _) in list {
                boardings.inc(*r);
            }
        }
        let mut alightings = Counter::new();
        for list in app
            .primary
            .sim
            .get_analytics()
            .passengers_alighting
            .values()
        {
            for (_, r) in list {
                alightings.inc(*r);
            }
        }
        let mut waiting = Counter::new();
        for bs in app.primary.map.all_bus_stops().keys() {
            for (_, r, _, _) in app.primary.sim.get_people_waiting_at_stop(*bs) {
                waiting.inc(*r);
            }
        }

        // Sort descending by count, but ascending by name. Hence the funny negation.
        let mut routes: Vec<(isize, isize, isize, String, BusRouteID)> = Vec::new();
        for r in app.primary.map.all_bus_routes() {
            routes.push((
                -1 * (boardings.get(r.id) as isize),
                -1 * (alightings.get(r.id) as isize),
                -1 * (waiting.get(r.id) as isize),
                r.full_name.clone(),
                r.id,
            ));
        }
        routes.sort();

        let col = vec![
            DashTab::TransitRoutes.picker(ctx, app),
            Line(format!("{} Transit routes", routes.len()))
                .small_heading()
                .draw(ctx),
            Widget::row(vec![
                Widget::draw_svg(ctx, "system/assets/tools/search.svg"),
                Autocomplete::new(
                    ctx,
                    routes
                        .iter()
                        .map(|(_, _, _, r, id)| (r.clone(), *id))
                        .collect(),
                )
                .named("search"),
            ])
            .padding(8),
            // TODO Maybe a table instead
            Widget::col(
                routes
                    .into_iter()
                    .map(|(boardings, alightings, waiting, name, id)| {
                        Widget::row(vec![
                            Btn::text_fg(name).build(ctx, id.to_string(), None),
                            format!(
                                "{} boardings, {} alightings, {} currently waiting",
                                prettyprint_usize(-boardings as usize),
                                prettyprint_usize(-alightings as usize),
                                prettyprint_usize(-waiting as usize)
                            )
                            .draw_text(ctx),
                        ])
                    })
                    .collect(),
            ),
        ];

        Box::new(TransitRoutes {
            panel: Panel::new(Widget::col(col))
                .exact_size_percent(90, 90)
                .build(ctx),
        })
    }
}

impl State for TransitRoutes {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        let route = match self.panel.event(ctx) {
            Outcome::Clicked(x) => {
                if let Some(x) = x.strip_prefix("BusRoute #") {
                    BusRouteID(x.parse::<usize>().unwrap())
                } else {
                    return DashTab::TransitRoutes.transition(ctx, app, &x);
                }
            }
            _ => {
                if let Some(routes) = self.panel.autocomplete_done("search") {
                    if !routes.is_empty() {
                        routes[0]
                    } else {
                        return Transition::Keep;
                    }
                } else {
                    return Transition::Keep;
                }
            }
        };

        Transition::Multi(vec![
            Transition::Pop,
            Transition::ModifyState(Box::new(move |state, ctx, app| {
                let sandbox = state.downcast_mut::<SandboxMode>().unwrap();
                let mut actions = sandbox.contextual_actions();
                sandbox.controls.common.as_mut().unwrap().launch_info_panel(
                    ctx,
                    app,
                    Tab::BusRoute(route),
                    &mut actions,
                )
            })),
        ])
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::Custom
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        g.clear(app.cs.dialog_bg);
        self.panel.draw(g);
    }
}