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
//! Integration tests

use std::fs::File;
use std::io::Write;

use anyhow::Result;
use rand::seq::SliceRandom;

use abstio::{CityName, MapName};
use abstutil::Timer;
use geom::{Distance, Duration, Time};
use map_model::{IntersectionID, Map};
use sim::{IndividTrip, PersonSpec, Scenario, TripEndpoint, TripMode, TripPurpose};

fn main() -> Result<()> {
    test_lane_changing(&import_map(abstio::path(
        "../tests/input/lane_selection.osm",
    )))?;
    test_map_importer()?;
    check_proposals()?;
    smoke_test()?;
    Ok(())
}

/// Test the map pipeline by importing simple, handcrafted .osm files, then emitting goldenfiles
/// that summarize part of the generated map. Keep the goldenfiles under version control to notice
/// when they change. The goldenfiles (and changes to them) themselves aren't easy to understand,
/// but the test maps are.
fn test_map_importer() -> Result<()> {
    for &name in &[
        "divided_highway_split",
        "left_turn_and_bike_lane",
        "multiple_left_turn_lanes",
    ] {
        // TODO It's kind of a hack to reference the crate's directory relative to the data dir.
        let map = import_map(abstio::path(format!("../tests/input/{}.osm", name)));
        // Enable to debug the result wih the normal GUI
        if false {
            map.save();
        }
        println!("Producing goldenfiles for {}", map.get_name().describe());
        dump_turn_goldenfile(&map)?;
    }
    Ok(())
}

/// Run the contents of a .osm through the full map importer with default options.
fn import_map(path: String) -> Map {
    let mut timer = Timer::new("convert synthetic map");
    let raw = convert_osm::convert(
        convert_osm::Options {
            name: MapName::new("zz", "oneshot", &abstutil::basename(&path)),
            osm_input: path,
            clip: None,
            map_config: map_model::MapConfig {
                driving_side: map_model::DrivingSide::Right,
                bikes_can_use_bus_lanes: true,
                inferred_sidewalks: true,
                street_parking_spot_length: Distance::meters(8.0),
            },
            onstreet_parking: convert_osm::OnstreetParking::JustOSM,
            public_offstreet_parking: convert_osm::PublicOffstreetParking::None,
            private_offstreet_parking: convert_osm::PrivateOffstreetParking::FixedPerBldg(0),
            include_railroads: true,
            extra_buildings: None,
        },
        &mut timer,
    );
    Map::create_from_raw(raw, map_model::RawToMapOptions::default(), &mut timer)
}

/// Verify what turns are generated by writing (from lane, to lane, turn type).
fn dump_turn_goldenfile(map: &Map) -> Result<()> {
    let path = abstio::path(format!("../tests/goldenfiles/{}.txt", map.get_name().map));
    let mut f = File::create(path)?;
    for t in map.all_turns() {
        writeln!(f, "{} is a {:?}", t.id, t.turn_type)?;
    }
    Ok(())
}

/// Simulate an hour on every map.
fn smoke_test() -> Result<()> {
    let mut timer = Timer::new("run a smoke-test for all maps");
    for name in MapName::list_all_maps_locally() {
        let map = map_model::Map::load_synchronously(name.path(), &mut timer);
        let scenario = if map.get_city_name() == &CityName::seattle() {
            abstio::read_binary(abstio::path_scenario(&name, "weekday"), &mut timer)
        } else {
            let mut rng = sim::SimFlags::for_test("smoke_test").make_rng();
            sim::ScenarioGenerator::proletariat_robot(&map, &mut rng, &mut timer)
        };

        let mut opts = sim::SimOptions::new("smoke_test");
        opts.alerts = sim::AlertHandler::Silence;
        let mut sim = sim::Sim::new(&map, opts);
        // Bit of an abuse of this, but just need to fix the rng seed.
        let mut rng = sim::SimFlags::for_test("smoke_test").make_rng();
        scenario.instantiate(&mut sim, &map, &mut rng, &mut timer);
        sim.timed_step(&map, Duration::hours(1), &mut None, &mut timer);

        #[allow(clippy::collapsible_if)]
        if (name.city == CityName::seattle()
            && vec!["downtown", "lakeslice", "montlake", "udistrict"].contains(&name.map.as_str()))
            || name == MapName::new("pl", "krakow", "center")
        {
            if false {
                dump_route_goldenfile(&map)?;
            }
        }
    }
    Ok(())
}

/// Describe all public transit routes and keep under version control to spot diffs easily.
fn dump_route_goldenfile(map: &map_model::Map) -> Result<()> {
    let path = abstio::path(format!(
        "route_goldenfiles/{}.txt",
        map.get_name().as_filename()
    ));
    let mut f = File::create(path)?;
    for br in map.all_bus_routes() {
        writeln!(
            f,
            "{} from {} to {:?}",
            br.osm_rel_id, br.start, br.end_border
        )?;
        for bs in &br.stops {
            let bs = map.get_bs(*bs);
            writeln!(
                f,
                "  {}: {} driving, {} sidewalk",
                bs.name, bs.driving_pos, bs.sidewalk_pos
            )?;
        }
    }
    Ok(())
}

/// Verify all edits under version control can be correctly apply to their map.
fn check_proposals() -> Result<()> {
    let mut timer = Timer::new("check all proposals");
    for name in abstio::list_all_objects(abstio::path("system/proposals")) {
        match abstio::maybe_read_json::<map_model::PermanentMapEdits>(
            abstio::path(format!("system/proposals/{}.json", name)),
            &mut timer,
        ) {
            Ok(perma) => {
                let map = map_model::Map::load_synchronously(perma.map_name.path(), &mut timer);
                if let Err(err) = perma.clone().into_edits(&map) {
                    abstio::write_json(
                        "repair_attempt.json".to_string(),
                        &perma.into_edits_permissive(&map).to_permanent(&map),
                    );
                    anyhow::bail!("{} is out-of-date: {}", name, err);
                }
            }
            Err(err) => {
                anyhow::bail!("{} JSON is broken: {}", name, err);
            }
        }
    }
    Ok(())
}

/// Verify lane-chaging behavior is overall reasonable, by asserting all cars and bikes can
/// complete their trip under a time limit.
fn test_lane_changing(map: &Map) -> Result<()> {
    // This uses a fixed RNG seed
    let mut rng = sim::SimFlags::for_test("smoke_test").make_rng();

    // Bit brittle to hardcode IDs here, but it's fast to update
    let north = IntersectionID(8);
    let south = IntersectionID(0);
    let east = IntersectionID(2);
    let west = IntersectionID(4);
    // (origin, destination) pairs
    let mut od = Vec::new();
    for _ in 0..100 {
        od.push((north, south));
        od.push((east, south));
    }
    for _ in 0..100 {
        od.push((north, west));
        od.push((east, west));
    }
    // Shuffling here is critical, since the loop below creates a car/bike and chooses spawn time
    // based on index.
    od.shuffle(&mut rng);

    let mut scenario = Scenario::empty(map, "lane_changing");
    for (idx, (from, to)) in od.into_iter().enumerate() {
        scenario.people.push(PersonSpec {
            orig_id: None,
            trips: vec![IndividTrip::new(
                // Space out the spawn times a bit. If a vehicle tries to spawn and something's in
                // the way, there's a fixed retry time in the simulation that we'll hit.
                Time::START_OF_DAY + Duration::seconds(idx as f64 - 0.5).max(Duration::ZERO),
                TripPurpose::Shopping,
                TripEndpoint::Border(from),
                TripEndpoint::Border(to),
                // About half cars, half bikes
                if idx % 2 == 0 {
                    TripMode::Drive
                } else {
                    TripMode::Bike
                },
            )],
        });
    }
    // Enable to manually watch the scenario
    if false {
        map.save();
        scenario.save();
    }

    let mut opts = sim::SimOptions::new("test_lane_changing");
    opts.alerts = sim::AlertHandler::Silence;
    let mut sim = sim::Sim::new(&map, opts);
    let mut rng = sim::SimFlags::for_test("test_lane_changing").make_rng();
    scenario.instantiate(&mut sim, &map, &mut rng, &mut Timer::throwaway());
    while !sim.is_done() {
        sim.tiny_step(&map, &mut None);
    }
    // This time limit was determined by watching the scenario manually. This test prevents the
    // time from regressing, which would probably indicate something breaking related to lane
    // selection.
    let limit = Duration::minutes(8) + Duration::seconds(40.0);
    if sim.time() > Time::START_OF_DAY + limit {
        panic!(
            "Lane-changing scenario took {} to complete; it should be under {}",
            sim.time(),
            limit
        );
    }

    Ok(())
}