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
use anyhow::Result;
use serde::Deserialize;
use geom::{Distance, FindClosest, LonLat, Time};
use map_model::Map;
use crate::{IndividTrip, MapBorders, PersonSpec, TripEndpoint, TripMode, TripPurpose};
#[derive(Deserialize)]
pub struct ExternalPerson {
pub trips: Vec<ExternalTrip>,
}
#[derive(Deserialize)]
pub struct ExternalTrip {
pub departure: Time,
pub origin: ExternalTripEndpoint,
pub destination: ExternalTripEndpoint,
pub mode: TripMode,
pub purpose: TripPurpose,
}
#[derive(Deserialize)]
pub enum ExternalTripEndpoint {
TripEndpoint(TripEndpoint),
Position(LonLat),
}
impl ExternalPerson {
pub fn import(
map: &Map,
input: Vec<ExternalPerson>,
skip_problems: bool,
) -> Result<Vec<PersonSpec>> {
let mut closest: FindClosest<TripEndpoint> = FindClosest::new(map.get_bounds());
for b in map.all_buildings() {
closest.add(TripEndpoint::Building(b.id), b.polygon.points());
}
let borders = MapBorders::new(map);
let lookup_pt = |endpt, is_origin, mode| match endpt {
ExternalTripEndpoint::TripEndpoint(endpt) => Ok(endpt),
ExternalTripEndpoint::Position(gps) => {
let pt = gps.to_pt(map.get_gps_bounds());
if map.get_boundary_polygon().contains_pt(pt) {
match closest.closest_pt(pt, Distance::meters(100.0)) {
Some((x, _)) => Ok(x),
None => Err(anyhow!("No building within 100m of {}", gps)),
}
} else {
let (incoming, outgoing) = borders.for_mode(mode);
let candidates = if is_origin { incoming } else { outgoing };
Ok(TripEndpoint::Border(
candidates
.iter()
.min_by_key(|border| border.gps_pos.fast_dist(gps))
.ok_or_else(|| anyhow!("No border for {}", mode.ongoing_verb()))?
.i,
))
}
}
};
let mut results = Vec::new();
for person in input {
let mut spec = PersonSpec {
orig_id: None,
trips: Vec::new(),
};
for trip in person.trips {
spec.trips.push(IndividTrip::new(
trip.departure,
trip.purpose,
match lookup_pt(trip.origin, true, trip.mode) {
Ok(endpt) => endpt,
Err(err) => {
if skip_problems {
warn!("Skipping person: {}", err);
continue;
} else {
return Err(err);
}
}
},
match lookup_pt(trip.destination, false, trip.mode) {
Ok(endpt) => endpt,
Err(err) => {
if skip_problems {
warn!("Skipping person: {}", err);
continue;
} else {
return Err(err);
}
}
},
trip.mode,
));
}
results.push(spec);
}
Ok(results)
}
}