-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathsimulation.rs
361 lines (329 loc) · 11.9 KB
/
simulation.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
350
351
352
353
354
355
356
357
358
359
360
361
use std::collections::BTreeMap;
use std::collections::HashMap;
use editoast_schemas::rolling_stock::EffortCurves;
use editoast_schemas::rolling_stock::Gamma;
use editoast_schemas::rolling_stock::RollingResistance;
use editoast_schemas::rolling_stock::RollingStock;
use editoast_schemas::train_schedule::Comfort;
use editoast_schemas::train_schedule::Distribution;
use editoast_schemas::train_schedule::MarginValue;
use editoast_schemas::train_schedule::ReceptionSignal;
use editoast_schemas::train_schedule::TrainScheduleOptions;
use serde::Deserialize;
use serde::Serialize;
use utoipa::ToSchema;
use super::pathfinding::TrackRange;
use crate::core::{AsCoreRequest, Json};
use crate::error::InternalError;
use crate::views::path::pathfinding::PathfindingFailure;
use derivative::Derivative;
use editoast_schemas::primitives::Identifier;
use std::hash::Hash;
editoast_common::schemas! {
CompleteReportTrain,
RoutingRequirement,
SignalSighting,
SpacingRequirement,
RoutingZoneRequirement,
ZoneUpdate,
ReportTrain,
SimulationResponse,
}
#[derive(Debug, Serialize, Derivative)]
#[derivative(Hash)]
pub struct PhysicsRollingStock {
pub effort_curves: EffortCurves,
pub base_power_class: Option<String>,
/// Length of the rolling stock in mm
pub length: u64,
/// Maximum speed of the rolling stock in m/s
#[derivative(Hash(hash_with = "editoast_common::hash_float::<3,_>"))]
pub max_speed: f64,
// Time in ms
pub startup_time: u64,
#[derivative(Hash(hash_with = "editoast_common::hash_float::<5,_>"))]
pub startup_acceleration: f64,
#[derivative(Hash(hash_with = "editoast_common::hash_float::<5,_>"))]
pub comfort_acceleration: f64,
pub gamma: Gamma,
#[derivative(Hash(hash_with = "editoast_common::hash_float::<5,_>"))]
pub inertia_coefficient: f64,
/// Mass of the rolling stock in kg
pub mass: u64,
pub rolling_resistance: RollingResistance,
/// Mapping of power restriction code to power class
#[serde(default)]
pub power_restrictions: BTreeMap<String, String>,
/// The time the train takes before actually using electrical power (in miliseconds).
/// Is null if the train is not electric or the value not specified.
pub electrical_power_startup_time: Option<u64>,
/// The time it takes to raise this train's pantograph in miliseconds.
/// Is null if the train is not electric or the value not specified.
pub raise_pantograph_time: Option<u64>,
}
#[derive(Debug, Default)]
pub struct SimulationParameters {
pub total_mass: Option<f64>,
pub total_length: Option<f64>,
pub max_speed: Option<f64>,
}
impl PhysicsRollingStock {
pub fn new(traction_engine: RollingStock, params: SimulationParameters) -> Self {
let traction_engine_length = traction_engine.length * 1000.0;
let length = params
.total_length
.map(|tl| tl * 1000.0)
.unwrap_or(traction_engine_length)
.round() as u64;
let traction_engine_mass = traction_engine.mass;
let mass = params.total_mass.unwrap_or(traction_engine_mass).round() as u64;
let max_speed = f64::min(
traction_engine.max_speed,
params.max_speed.unwrap_or(traction_engine.max_speed),
);
Self {
effort_curves: traction_engine.effort_curves,
base_power_class: traction_engine.base_power_class,
length,
mass,
max_speed,
startup_time: (traction_engine.startup_time * 1000.0).round() as u64,
startup_acceleration: traction_engine.startup_acceleration,
comfort_acceleration: traction_engine.comfort_acceleration,
gamma: traction_engine.gamma,
inertia_coefficient: traction_engine.inertia_coefficient,
rolling_resistance: traction_engine.rolling_resistance,
power_restrictions: traction_engine.power_restrictions.into_iter().collect(),
electrical_power_startup_time: traction_engine
.electrical_power_startup_time
.map(|v| (v * 1000.0).round() as u64),
raise_pantograph_time: traction_engine
.raise_pantograph_time
.map(|v| (v * 1000.0).round() as u64),
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ZoneUpdate {
pub zone: String,
// Time in ms
pub time: u64,
pub position: u64,
pub is_entry: bool,
}
#[derive(Debug, Serialize, Hash)]
pub struct SimulationScheduleItem {
/// Position on the path in mm
pub path_offset: u64,
/// Time in ms since the departure of the train
pub arrival: Option<u64>,
/// Duration of the stop in ms
pub stop_for: Option<u64>,
/// Whether the next signal is expected to be blocking while stopping
pub reception_signal: ReceptionSignal,
}
#[derive(Debug, Serialize, Hash)]
pub struct SimulationMargins {
/// Path offset separating margin transitions in mm
pub boundaries: Vec<u64>,
pub values: Vec<MarginValue>,
}
#[derive(Debug, Serialize, Hash)]
pub struct SimulationPowerRestrictionItem {
/// Position on the path in mm
pub from: u64,
/// Position on the path in mm
pub to: u64,
pub value: String,
}
/// Path description
#[derive(Debug, Serialize, Hash)]
pub struct SimulationPath {
pub blocks: Vec<Identifier>,
pub routes: Vec<Identifier>,
pub track_section_ranges: Vec<TrackRange>,
/// The path offset in mm of each path item given as input of the pathfinding
pub path_item_positions: Vec<u64>,
}
#[derive(Deserialize, Default, PartialEq, Serialize, Clone, Debug, ToSchema)]
pub struct ReportTrain {
/// List of positions of a train
/// Both positions (in mm) and times (in ms) must have the same length
pub positions: Vec<u64>,
pub times: Vec<u64>,
/// List of speeds associated to a position
pub speeds: Vec<f64>,
/// Total energy consumption
pub energy_consumption: f64,
/// Time in ms of each path item given as input of the pathfinding
/// The first value is always `0` (beginning of the path) and the last one, the total time of the simulation (end of the path)
pub path_item_times: Vec<u64>,
}
#[derive(Deserialize, Default, PartialEq, Serialize, Clone, Debug, ToSchema)]
pub struct CompleteReportTrain {
#[serde(flatten)]
pub report_train: ReportTrain,
pub signal_sightings: Vec<SignalSighting>,
pub zone_updates: Vec<ZoneUpdate>,
pub spacing_requirements: Vec<SpacingRequirement>,
pub routing_requirements: Vec<RoutingRequirement>,
}
#[derive(Debug, Clone, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
pub struct SignalSighting {
pub signal: String,
/// Time in ms
pub time: u64,
/// Position in mm
pub position: u64,
pub state: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct SpacingRequirement {
pub zone: String,
// Time in ms
pub begin_time: u64,
// Time in ms
pub end_time: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct RoutingRequirement {
pub route: String,
/// Time in ms
pub begin_time: u64,
pub zones: Vec<RoutingZoneRequirement>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct RoutingZoneRequirement {
pub zone: String,
pub entry_detector: String,
pub exit_detector: String,
pub switches: HashMap<String, String>,
/// Time in ms
pub end_time: u64,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ElectricalProfiles {
/// List of `n` boundaries of the ranges (block path).
/// A boundary is a distance from the beginning of the path in mm.
pub boundaries: Vec<u64>,
/// List of `n+1` values associated to the ranges
#[schema(inline)]
pub values: Vec<ElectricalProfileValue>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "electrical_profile_type", rename_all = "snake_case")]
pub enum ElectricalProfileValue {
NoProfile,
Profile {
profile: Option<String>,
handled: bool,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "speed_limit_source_type", rename_all = "snake_case")]
#[allow(clippy::enum_variant_names)]
pub enum SpeedLimitSource {
GivenTrainTag { tag: String },
FallbackTag { tag: String },
UnknownTag,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct SpeedLimitProperty {
/// in meters per second
pub speed: f64,
/// source of the speed-limit if relevant (tag used)
#[schema(inline)]
pub source: Option<SpeedLimitSource>,
}
/// A MRSP computation result (Most Restrictive Speed Profile)
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct SpeedLimitProperties {
/// List of `n` boundaries of the ranges (block path).
/// A boundary is a distance from the beginning of the path in mm.
pub boundaries: Vec<u64>,
/// List of `n+1` values associated to the ranges
#[schema(inline)]
pub values: Vec<SpeedLimitProperty>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct SimulationPowerRestrictionRange {
/// Start position in the path in mm
begin: u64,
/// End position in the path in mm
end: u64,
code: String,
/// Is power restriction handled during simulation
handled: bool,
}
#[derive(Debug, Serialize, Derivative)]
#[derivative(Hash)]
pub struct SimulationRequest {
pub infra: i64,
pub expected_version: String,
pub path: SimulationPath,
pub schedule: Vec<SimulationScheduleItem>,
pub margins: SimulationMargins,
#[derivative(Hash(hash_with = "editoast_common::hash_float::<3,_>"))]
pub initial_speed: f64,
pub comfort: Comfort,
pub constraint_distribution: Distribution,
pub speed_limit_tag: Option<String>,
pub power_restrictions: Vec<SimulationPowerRestrictionItem>,
pub options: TrainScheduleOptions,
pub rolling_stock: PhysicsRollingStock,
pub electrical_profile_set_id: Option<i64>,
}
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, ToSchema)]
#[serde(tag = "status", rename_all = "snake_case")]
// We accepted the difference of memory size taken by variants
// Since there is only on success and others are error cases
#[allow(clippy::large_enum_variant)]
pub enum SimulationResponse {
Success {
/// Simulation without any regularity margins
base: ReportTrain,
/// Simulation that takes into account the regularity margins
provisional: ReportTrain,
#[schema(inline)]
/// User-selected simulation: can be base or provisional
final_output: CompleteReportTrain,
#[schema(inline)]
mrsp: SpeedLimitProperties,
#[schema(inline)]
electrical_profiles: ElectricalProfiles,
},
PathfindingFailed {
pathfinding_failed: PathfindingFailure,
},
SimulationFailed {
core_error: InternalError,
},
}
impl Default for SimulationResponse {
fn default() -> Self {
Self::Success {
base: Default::default(),
provisional: Default::default(),
final_output: Default::default(),
mrsp: Default::default(),
electrical_profiles: Default::default(),
}
}
}
impl AsCoreRequest<Json<SimulationResponse>> for SimulationRequest {
const METHOD: reqwest::Method = reqwest::Method::POST;
const URL_PATH: &'static str = "/v2/standalone_simulation";
fn infra_id(&self) -> Option<i64> {
Some(self.infra)
}
}
impl SimulationResponse {
pub fn simulation_run_time(self) -> Result<u64, Box<Self>> {
match self {
SimulationResponse::Success { provisional, .. } => {
Ok(*provisional.times.last().expect("empty simulation result"))
}
err => Err(Box::from(err)),
}
}
}