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

use std::io::Write;

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

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

fn main() -> Result<()> {
    abstutil::logger::setup();
    test_blockfinding()?;
    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 name = MapName::new("zz", "oneshot", &abstutil::basename(&path));
    let clip = None;
    let raw = convert_osm::convert(
        path,
        name,
        clip,
        convert_osm::Options {
            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),
                turn_on_red: false,
            },
            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,
            skip_local_roads: false,
            filter_crosswalks: false,
            gtfs_url: 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();
        sim.instantiate(&scenario, &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"].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 tr in map.all_transit_routes() {
        writeln!(f, "{} from {} to {:?}", tr.gtfs_id, tr.start, tr.end_border)?;
        for ts in &tr.stops {
            let ts = map.get_ts(*ts);
            writeln!(
                f,
                "  {}: {} driving, {} sidewalk",
                ts.name, ts.driving_pos, ts.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(7);
    let south = IntersectionID(0);
    let east = IntersectionID(1);
    let west = IntersectionID(3);
    // (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();
    sim.instantiate(&scenario, 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(())
}

/// Generate single blocks and merged LTN-style blocks for some maps, counting the number of
/// failures. Store in a goldenfile, so somebody can manually do a visual diff if anything changes.
fn test_blockfinding() -> Result<()> {
    let mut timer = Timer::new("test blockfinding");
    let path = abstio::path("../tests/goldenfiles/blockfinding.txt");
    let mut f = File::create(path)?;

    for name in vec![
        MapName::seattle("montlake"),
        MapName::seattle("downtown"),
        MapName::seattle("lakeslice"),
        MapName::new("us", "phoenix", "tempe"),
        MapName::new("gb", "bristol", "east"),
        MapName::new("gb", "leeds", "north"),
        MapName::new("gb", "london", "camden"),
        MapName::new("gb", "london", "southwark"),
        MapName::new("gb", "manchester", "levenshulme"),
        MapName::new("fr", "lyon", "center"),
        MapName::new("us", "seattle", "north_seattle"),
    ] {
        let map = map_model::Map::load_synchronously(name.path(), &mut timer);
        let mut single_blocks = Perimeter::find_all_single_blocks(&map);
        let num_singles_originally = single_blocks.len();
        // Collapse dead-ends first, so results match the LTN tool and blockfinder
        single_blocks.retain(|x| {
            let mut copy = x.clone();
            copy.collapse_deadends();
            copy.to_block(&map).is_ok()
        });
        let num_singles_blockified = single_blocks.len();

        let partitions = Perimeter::partition_by_predicate(single_blocks, |r| {
            map.get_r(r).get_rank() == map_model::osm::RoadRank::Local
        });
        let mut num_partial_merges = 0;
        let mut merged = Vec::new();
        for perimeters in partitions {
            let stepwise_debug = false;
            let use_expensive_blockfinding = false;
            let newly_merged =
                Perimeter::merge_all(&map, perimeters, stepwise_debug, use_expensive_blockfinding);
            if newly_merged.len() > 1 {
                num_partial_merges += 1;
            }
            merged.extend(newly_merged);
        }

        let mut num_merged_block_failures = 0;
        for perimeter in merged {
            if perimeter.to_block(&map).is_err() {
                // Note this means the LTN UI will fallback to use_expensive_blockfinding = true
                num_merged_block_failures += 1;
            }
        }

        writeln!(f, "{}", name.path())?;
        writeln!(f, "    {} single blocks ({} failures to blockify), {} partial merges, {} failures to blockify partitions", num_singles_originally, num_singles_originally - num_singles_blockified, num_partial_merges, num_merged_block_failures)?;
    }
    Ok(())
}