-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathpathfinding.rs
349 lines (325 loc) · 12.1 KB
/
pathfinding.rs
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//! Provides the [Pathfinding] model
use std::collections::HashSet;
use crate::models::Identifiable;
use crate::schema::Direction;
use crate::schema::DirectionalTrackRange;
use crate::schema::TrackLocation;
use crate::tables::pathfinding;
use chrono::{NaiveDateTime, Utc};
use derivative::Derivative;
use diesel::{result::Error as DieselError, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl;
use editoast_derive::Model;
use geos::geojson;
use postgis_diesel::types::*;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
crate::schemas! {
Slope,
Curve,
PathfindingPayload,
RoutePath,
PathWaypoint,
}
/// Describes a pathfinding that resulted from a simulation and stored in the DB
///
/// It differs from infra/pathfinding that performs a topological pathfinding
/// meant to be used with the infra editor.
#[derive(
Debug,
Clone,
PartialEq,
Serialize,
Deserialize,
Derivative,
Queryable,
QueryableByName,
Model,
Insertable,
)]
#[derivative(Default(new = "true"))]
#[model(table = "pathfinding")]
#[model(retrieve, delete)]
#[diesel(table_name = pathfinding)]
pub struct Pathfinding {
// TODO: we probably want to use ModelV2 and avoid default 0 (test isolation, the DB assigns a value anyway)
// See https://github.com/osrd-project/osrd/pull/5033
pub id: i64,
pub owner: uuid::Uuid,
#[derivative(Default(value = "Utc::now().naive_utc()"))]
pub created: NaiveDateTime,
#[derivative(Default(value = "diesel_json::Json::new(Default::default())"))]
pub payload: diesel_json::Json<PathfindingPayload>,
#[derivative(Default(value = "diesel_json::Json::new(Default::default())"))]
pub slopes: diesel_json::Json<SlopeGraph>,
#[derivative(Default(value = "diesel_json::Json::new(Default::default())"))]
pub curves: diesel_json::Json<CurveGraph>,
#[derivative(Default(value = "LineString { points: vec![], srid: None }"))]
pub geographic: LineString<Point>,
#[derivative(Default(value = "LineString { points: vec![], srid: None }"))]
pub schematic: LineString<Point>,
pub infra_id: i64,
pub length: f64,
}
#[derive(Clone, Debug, Serialize, Queryable, Insertable, Derivative, AsChangeset, Model)]
#[derivative(Default(new = "true"))]
#[model(table = "pathfinding")]
#[model(create, update)]
#[diesel(table_name = pathfinding)]
pub struct PathfindingChangeset {
#[diesel(deserialize_as=i64)]
pub id: Option<i64>,
#[diesel(deserialize_as=uuid::Uuid)]
pub owner: Option<uuid::Uuid>,
#[diesel(deserialize_as=NaiveDateTime)]
pub created: Option<NaiveDateTime>,
#[diesel(deserialize_as=diesel_json::Json<PathfindingPayload>)]
pub payload: Option<diesel_json::Json<PathfindingPayload>>,
#[diesel(deserialize_as=diesel_json::Json<SlopeGraph>)]
pub slopes: Option<diesel_json::Json<SlopeGraph>>,
#[diesel(deserialize_as=diesel_json::Json<CurveGraph>)]
pub curves: Option<diesel_json::Json<CurveGraph>>,
#[diesel(deserialize_as=LineString<Point>)]
pub geographic: Option<LineString<Point>>,
#[diesel(deserialize_as=LineString<Point>)]
pub schematic: Option<LineString<Point>>,
#[diesel(deserialize_as=i64)]
pub infra_id: Option<i64>,
#[diesel(deserialize_as=f64)]
pub length: Option<f64>,
}
impl From<Pathfinding> for PathfindingChangeset {
fn from(value: Pathfinding) -> Self {
Self {
id: Some(value.id),
owner: Some(value.owner),
length: Some(value.length),
created: Some(value.created),
payload: Some(value.payload),
slopes: Some(value.slopes),
curves: Some(value.curves),
geographic: Some(value.geographic),
schematic: Some(value.schematic),
infra_id: Some(value.infra_id),
}
}
}
impl From<PathfindingChangeset> for Pathfinding {
fn from(value: PathfindingChangeset) -> Self {
Self {
id: value.id.expect("invalid changeset result"),
owner: value.owner.expect("invalid changeset result"),
created: value.created.expect("invalid changeset result"),
length: value.length.expect("invalid changeset result"),
payload: value.payload.expect("invalid changeset result"),
slopes: value.slopes.expect("invalid changeset result"),
curves: value.curves.expect("invalid changeset result"),
geographic: value.geographic.expect("invalid changeset result"),
schematic: value.schematic.expect("invalid changeset result"),
infra_id: value.infra_id.expect("invalid changeset result"),
}
}
}
pub type SlopeGraph = Vec<Slope>;
pub type CurveGraph = Vec<Curve>;
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct Slope {
pub gradient: f64,
pub position: f64,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct Curve {
radius: f64,
position: f64,
}
/// The "payload" of a path
///
/// It contains the route paths and the path waypoints that the simulation returned,
/// but enhanced using data from the infra. Notably, path waypoints are reprojected
/// onto their track section to obtain their geographic and schematic representations
/// back.
#[derive(Debug, Clone, PartialEq, Derivative, Deserialize, Serialize, ToSchema)]
#[derivative(Default)]
pub struct PathfindingPayload {
pub route_paths: Vec<RoutePath>,
pub path_waypoints: Vec<PathWaypoint>,
}
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct RoutePath {
pub route: String,
pub signaling_type: String,
#[serde(rename = "track_sections")]
pub track_ranges: Vec<DirectionalTrackRange>,
}
#[derive(Debug, Clone, PartialEq, Derivative, Deserialize, Serialize, ToSchema)]
#[derivative(Default)]
pub struct PathWaypoint {
#[schema(required)]
pub id: Option<String>,
#[schema(required)]
pub name: Option<String>,
pub location: TrackLocation,
pub duration: f64,
pub path_offset: f64,
pub suggestion: bool,
#[derivative(Default(
value = "geojson::Geometry::new(geojson::Value::Point(Default::default()))"
))]
#[schema(value_type = GeoJsonPoint)]
pub geo: geojson::Geometry,
#[derivative(Default(
value = "geojson::Geometry::new(geojson::Value::Point(Default::default()))"
))]
#[schema(value_type = GeoJsonPoint)]
pub sch: geojson::Geometry,
#[schema(required)]
pub uic: Option<i64>,
#[schema(required)]
pub ch: Option<String>,
}
impl Pathfinding {
/// Returns the track sections ids used in this pathfinding
pub fn track_section_ids(&self) -> HashSet<String> {
self.payload
.route_paths
.iter()
.flat_map(|route_path| &route_path.track_ranges)
.map(|track_range| track_range.track.to_string())
.collect::<HashSet<_>>()
}
/// Returns the track ranges covered by this pathfinding's route paths.
/// Contiguous track ranges on the same track are merged.
pub fn merged_track_ranges(&self) -> Vec<DirectionalTrackRange> {
let mut res = Vec::new();
let mut track_ranges = self
.payload
.route_paths
.iter()
.flat_map(|route_path| &route_path.track_ranges)
.filter(|track_range| track_range.begin != track_range.end);
let mut current_range = track_ranges.next().unwrap().clone();
for track_range in track_ranges {
assert!(track_range.begin < track_range.end);
if track_range.track == current_range.track {
assert!(track_range.direction == current_range.direction);
match current_range.direction {
Direction::StartToStop => {
assert!(current_range.end == track_range.begin);
current_range.end = track_range.end;
}
Direction::StopToStart => {
assert!(current_range.begin == track_range.end);
current_range.begin = track_range.begin;
}
}
} else {
res.push(current_range.clone());
current_range = track_range.clone();
}
}
res.push(current_range);
res
}
}
impl Identifiable for Pathfinding {
fn get_id(&self) -> i64 {
self.id
}
}
#[cfg(test)]
pub mod tests {
use crate::fixtures::tests::TestFixture;
use crate::models::Create;
use crate::DbPool;
use actix_web::web::Data;
use super::*;
pub fn simple_pathfinding(infra_id: i64) -> Pathfinding {
// T1 T2 T3 T4 T5
// |------> < ------| |------> |------> |------>
let route_paths = vec![
RoutePath {
route: "route_1".into(),
track_ranges: vec![
DirectionalTrackRange::new("track_1", 0.0, 10.0, Direction::StartToStop),
DirectionalTrackRange::new("track_2", 7.0, 10.0, Direction::StopToStart),
DirectionalTrackRange::new("track_2", 7.0, 7.0, Direction::StartToStop),
],
signaling_type: "BAL3".into(),
},
RoutePath {
route: "route_2".into(),
track_ranges: vec![DirectionalTrackRange::new(
"track_2",
3.0,
7.0,
Direction::StopToStart,
)],
signaling_type: "BAL3".into(),
},
RoutePath {
route: "route_3".into(),
track_ranges: vec![
DirectionalTrackRange::new("track_2", 0.0, 3.0, Direction::StopToStart),
DirectionalTrackRange::new("track_3", 0.0, 10.0, Direction::StartToStop),
DirectionalTrackRange::new("track_4", 0.0, 2.0, Direction::StartToStop),
],
signaling_type: "BAL3".into(),
},
RoutePath {
route: "route_4".into(),
track_ranges: vec![
DirectionalTrackRange::new("track_4", 2.0, 10.0, Direction::StartToStop),
DirectionalTrackRange::new("track_5", 0.0, 8.0, Direction::StartToStop),
],
signaling_type: "BAL3".into(),
},
];
Pathfinding {
infra_id,
payload: diesel_json::Json(PathfindingPayload {
route_paths,
..Default::default()
}),
..Default::default()
}
}
pub async fn simple_pathfinding_fixture(
infra_id: i64,
db_pool: Data<DbPool>,
) -> TestFixture<Pathfinding> {
let pathfinding = simple_pathfinding(infra_id);
let pathfinding: Pathfinding = PathfindingChangeset::from(pathfinding)
.create(db_pool.clone())
.await
.unwrap()
.into();
TestFixture::new(pathfinding, db_pool)
}
#[test]
fn test_path_track_section_ids() {
let pathfinding = simple_pathfinding(0);
let track_section_ids = pathfinding.track_section_ids();
assert_eq!(
track_section_ids,
vec!["track_1", "track_2", "track_3", "track_4", "track_5"]
.into_iter()
.map(|s| s.to_string())
.collect::<HashSet<_>>()
);
}
#[test]
fn test_path_merged_track_ranges() {
let pathfinding = simple_pathfinding(0);
let merged_track_ranges = pathfinding.merged_track_ranges();
assert_eq!(
merged_track_ranges,
vec![
DirectionalTrackRange::new("track_1", 0.0, 10.0, Direction::StartToStop),
DirectionalTrackRange::new("track_2", 0.0, 10.0, Direction::StopToStart),
DirectionalTrackRange::new("track_3", 0.0, 10.0, Direction::StartToStop),
DirectionalTrackRange::new("track_4", 0.0, 10.0, Direction::StartToStop),
DirectionalTrackRange::new("track_5", 0.0, 8.0, Direction::StartToStop),
]
);
}
}