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
extern crate rand;

use std::collections::BTreeSet;

use rand::Rng;
use rand_xorshift::XorShiftRng;
use serde::{Deserialize, Serialize};

use abstutil::Timer;
use geom::{Duration, Time};
use map_model::Map;

use crate::{Scenario, TripMode};

/// Transforms an existing Scenario before instantiating it.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
pub enum ScenarioModifier {
    RepeatDays(usize),
    RepeatDaysNoise {
        days: usize,
        departure_time_noise: Duration,
    },
    ChangeMode {
        pct_ppl: usize,
        departure_filter: (Time, Time),
        from_modes: BTreeSet<TripMode>,
        /// If `None`, then just cancel the trip.
        to_mode: Option<TripMode>,
    },
    /// Scenario name
    AddExtraTrips(String),
}

impl ScenarioModifier {
    /// If this modifies scenario_name, then that means prebaked results don't match up and
    /// shouldn't be used.
    pub fn apply(&self, map: &Map, mut s: Scenario, rng: &mut XorShiftRng) -> Scenario {
        match self {
            ScenarioModifier::RepeatDays(n) => repeat_days(s, *n, None, rng),
            ScenarioModifier::RepeatDaysNoise {
                days,
                departure_time_noise,
            } => repeat_days(s, *days, Some(*departure_time_noise), rng),
            ScenarioModifier::ChangeMode {
                pct_ppl,
                departure_filter,
                from_modes,
                to_mode,
            } => {
                for (idx, person) in s.people.iter_mut().enumerate() {
                    // This is "stable" as percentage increases. If you modify 10% of people in one
                    // run, then modify 11% in another, the modified people in the 11% run will be
                    // a strict superset of the 10% run.
                    if idx % 100 > *pct_ppl {
                        continue;
                    }
                    let mut cancel_rest = false;
                    for trip in &mut person.trips {
                        if cancel_rest {
                            trip.modified = true;
                            trip.cancelled = true;
                            continue;
                        }

                        if trip.depart < departure_filter.0 || trip.depart > departure_filter.1 {
                            continue;
                        }
                        if !from_modes.contains(&trip.mode) {
                            continue;
                        }
                        if let Some(to_mode) = *to_mode {
                            trip.mode = to_mode;
                            trip.modified = true;
                        } else {
                            trip.modified = true;
                            trip.cancelled = true;
                            // The next trip assumes we're at the destination of this cancelled
                            // trip, and so on. Have to cancel the rest.
                            cancel_rest = true;
                        }
                    }
                }
                s
            }
            // TODO This doesn't work on web!
            ScenarioModifier::AddExtraTrips(name) => {
                let other: Scenario = abstio::must_read_object(
                    abstio::path_scenario(map.get_name(), name),
                    &mut Timer::throwaway(),
                );
                for mut p in other.people {
                    for trip in &mut p.trips {
                        trip.modified = true;
                    }
                    s.people.push(p);
                }
                s
            }
        }
    }

    pub fn describe(&self) -> String {
        match self {
            ScenarioModifier::RepeatDays(n) => format!("repeat the entire day {} times", n),
            ScenarioModifier::RepeatDaysNoise {
                days,
                departure_time_noise,
            } => format!(
                "repeat the entire day {} times with +/- {} noise on each departure",
                days, departure_time_noise
            ),
            ScenarioModifier::ChangeMode {
                pct_ppl,
                to_mode,
                departure_filter,
                from_modes,
            } => format!(
                "change all trips for {}% of people of types {:?} leaving between {} and {} to \
                 {:?}",
                pct_ppl,
                from_modes,
                departure_filter.0.ampm_tostring(),
                departure_filter.1.ampm_tostring(),
                to_mode.map(|m| m.verb())
            ),
            ScenarioModifier::AddExtraTrips(name) => format!("Add extra trips from {}", name),
        }
    }
}

// Utter hack. Blindly repeats all trips taken by each person every day.
//
// What happens if the last place a person winds up in a day isn't the same as where their
// first trip the next starts? Will crash as soon as the scenario is instantiated, through
// check_schedule().
//
// The bigger problem is that any people that seem to require multiple cars... will wind up
// needing LOTS of cars.
fn repeat_days(
    mut s: Scenario,
    days: usize,
    noise: Option<Duration>,
    rng: &mut XorShiftRng,
) -> Scenario {
    s.scenario_name = format!("{} (repeated {} days)", s.scenario_name, days);
    for person in &mut s.people {
        let mut trips = Vec::new();
        let mut offset = Duration::ZERO;
        for _ in 0..days {
            for trip in &person.trips {
                let mut new = trip.clone();
                new.depart += offset;
                if let Some(noise_v) = noise {
                    // + or - noise_v
                    let noise_rnd = Duration::seconds(
                        rng.gen_range((0.0)..=(2.0 * noise_v.inner_seconds() as f64)),
                    ) - noise_v;
                    new.depart = new.depart.clamped_sub(noise_rnd);
                }
                new.modified = true;
                trips.push(new);
            }
            offset += Duration::hours(24);
        }
        person.trips = trips;
    }
    s
}