Repository navigation
Expand file tree
/
Copy pathmodel.rs
More file actions
352 lines (328 loc) · 11.8 KB
/
Copy pathmodel.rs
File metadata and controls
352 lines (328 loc) · 11.8 KB
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
use crate::geometry::METRES_PER_UDEG;
use serde::{Deserialize, Serialize};
pub type Cost = u64;
pub const BIKE: u8 = 1;
pub const FOOT: u8 = 2;
pub const PUSH: u8 = 4;
pub const NO_ELEVATION: f32 = f32::MIN;
/// `#[repr(C)]`: the routing bake stores points as 12-byte records.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Point {
pub lat: i32,
pub lon: i32,
pub elevation: f32,
}
impl Point {
pub fn distance(self, other: Self) -> f64 {
let y = (other.lat as f64 - self.lat as f64) * METRES_PER_UDEG;
let x = (other.lon as f64 - self.lon as f64)
* METRES_PER_UDEG
* ((self.lat as f64 + other.lat as f64) * 0.5e-6).to_radians().cos();
x.hypot(y)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Surface {
#[default]
Unknown,
Paved,
Compacted,
Gravel,
Dirt,
Rough,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Road {
pub from: u32,
pub to: u32,
pub way: i64,
pub reversed: bool,
pub length_m: u32,
pub ascent_m: u32,
pub descent_m: u32,
pub surface: Surface,
/// 0: cycleway, 1: quiet road, 2: main road, 3: track, 4: path, 5: steps, 6: ferry.
pub class: u8,
pub access: u8,
/// MTB scale; 255 means that the source has no classification.
pub difficulty: u8,
pub hiking_difficulty: Option<u8>,
/// A bridge or tunnel uses endpoint-interpolated elevation.
pub structure: bool,
pub shape: Vec<Point>,
}
impl Road {
pub fn mtb_scale(&self) -> Option<u8> {
(self.difficulty != 255).then_some(self.difficulty)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Profile {
pub name: String,
pub weighting: Weighting,
pub walking: bool,
/// Moving time follows the mountain-bike pace curve.
pub mtb_pace: bool,
/// The cost discount per level of a signed cycle route, on a road the rider cycles.
pub route_bonus: f64,
/// The highest SAC grade on foot, or MTB grade by bike.
pub max_difficulty: u8,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Weighting {
RoadBike(RoadBike),
Weighted { surface: [f64; 6], road: [f64; 7], climb: f64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum RoadBike {
Balanced,
LessClimbing,
}
impl Profile {
pub fn presets() -> Vec<Self> {
let mut profiles = vec![
Self {
name: "touring".into(),
walking: false,
weighting: Weighting::Weighted {
surface: [1.4, 1.0, 1.15, 1.6, 2.5, 5.0],
road: [1.0, 1.15, 3.0, 1.2, 2.0, 8.0, 2.0],
climb: 10.0,
},
mtb_pace: false,
route_bonus: 0.1,
max_difficulty: 1,
},
Self {
name: "gravel".into(),
walking: false,
weighting: Weighting::Weighted {
surface: [1.3, 1.4, 1.0, 1.0, 1.5, 3.5],
road: [1.1, 1.2, 4.0, 1.0, 1.7, 8.0, 2.0],
climb: 6.0,
},
mtb_pace: false,
route_bonus: 0.04,
max_difficulty: 1,
},
Self {
name: "road".into(),
walking: false,
weighting: Weighting::RoadBike(RoadBike::Balanced),
mtb_pace: false,
route_bonus: 0.04,
max_difficulty: 0,
},
Self {
name: "hiking".into(),
walking: true,
weighting: Weighting::Weighted {
surface: [1.2, 1.3, 1.1, 1.0, 1.0, 1.5],
road: [1.4, 2.0, 8.0, 1.1, 1.0, 1.2, 2.0],
climb: 4.0,
},
mtb_pace: false,
route_bonus: 0.0,
// Up to `mountain_hiking` (T2); `hiking/alpine` goes to T6.
max_difficulty: 2,
},
];
let mut mtb = profiles[1].clone();
mtb.name = "mtb".into();
mtb.weighting = Weighting::Weighted {
surface: [1.4, 1.3, 1.1, 1.0, 1.0, 1.8],
road: [1.2, 1.4, 4.0, 1.0, 1.0, 8.0, 2.0],
climb: 6.0,
};
mtb.max_difficulty = 2;
mtb.mtb_pace = true;
profiles.push(mtb);
let variants: Vec<_> = profiles
.iter()
.filter(|profile| ["touring", "gravel", "road"].contains(&profile.name.as_str()))
.map(|profile| {
let mut p = profile.clone();
p.name = format!("{}/less-climbing", profile.name);
match &mut p.weighting {
Weighting::RoadBike(road) => *road = RoadBike::LessClimbing,
Weighting::Weighted { climb, .. } => *climb *= 3.0,
}
p
})
.collect();
profiles.extend(variants);
// Explicit skill choices up to the highest known grade, so an unknown grade value (255)
// stays refused. Alpine keeps off T5 and T6 paths only through their cost factors.
for (base, name, difficulty) in [("mtb", "mtb/technical", 6), ("hiking", "hiking/alpine", 6)] {
let mut profile = profiles.iter().find(|p| p.name == base).unwrap().clone();
profile.name = name.into();
profile.max_difficulty = difficulty;
profiles.push(profile);
}
profiles
}
pub fn validate(&self) -> Result<(), String> {
if let Weighting::Weighted { surface, road, climb } = &self.weighting {
if surface.iter().chain(road).any(|v| !v.is_finite() || *v < 0.01 || *v > 1000.0)
|| !climb.is_finite()
|| !(0.0..=1000.0).contains(climb)
{
return Err("Weights must be finite, positive and at most 1000; climb may be zero".into());
}
}
// Five route levels at the bonus must leave a positive factor.
if !self.route_bonus.is_finite() || !(0.0..0.2).contains(&self.route_bonus) {
return Err("A route bonus is a fraction below 0.2 per route level".into());
}
Ok(())
}
pub fn permits(&self, road: &Road) -> bool {
let too_difficult = if self.walking {
road.hiking_difficulty.is_some_and(|d| d > self.max_difficulty)
} else {
road.mtb_scale().is_some_and(|d| d > self.max_difficulty) || road.hiking_difficulty.is_some_and(|d| d > 2)
};
// Cycling profiles never carry a bike up steps.
road.access & self.modes() != 0 && !too_difficult && (self.walking || road.class != 5)
}
/// The modes the profile moves in: on foot, or cycling and pushing.
pub fn modes(&self) -> u8 {
if self.walking {
FOOT
} else {
BIKE | PUSH
}
}
/// The mode the rider uses on a permitted road: a cyclist pushes where riding is not allowed.
pub fn mode(&self, road: &Road) -> u8 {
if self.walking {
FOOT
} else if road.access & BIKE != 0 {
BIKE
} else {
PUSH
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Pace {
pub cycling_kmh: f64,
pub walking_kmh: f64,
/// A larger value means more time. This never enters the route cost.
pub personal_multiplier: f64,
}
impl Default for Pace {
fn default() -> Self {
Self { cycling_kmh: 19.0, walking_kmh: 4.5, personal_multiplier: 1.0 }
}
}
impl Pace {
pub fn validate(&self) -> Result<(), String> {
if !(1.0..=80.0).contains(&self.cycling_kmh)
|| !(0.5..=15.0).contains(&self.walking_kmh)
|| !(0.25..=4.0).contains(&self.personal_multiplier)
{
return Err("Pace requires cycling 1–80 km/h, walking 0.5–15 km/h and multiplier 0.25–4".into());
}
Ok(())
}
pub fn segment_seconds(&self, from: Point, to: Point, walk: bool, mtb: bool) -> f64 {
let rise = if from.elevation == NO_ELEVATION || to.elevation == NO_ELEVATION {
0.0
} else {
to.elevation as f64 - from.elevation as f64
};
self.seconds(from.distance(to), rise, walk, mtb)
}
/// The moving time over `distance_m` that rises by `rise_m`, a drop when negative.
pub fn seconds(&self, distance_m: f64, rise_m: f64, walk: bool, mtb: bool) -> f64 {
let gradient = rise_m / distance_m.max(1.0);
let minutes_per_km = if walk {
60.0 / self.walking_kmh * (3.5 * ((gradient.clamp(-0.5, 0.5) + 0.05).abs() - 0.05)).exp()
} else {
60.0 / self.cycling_kmh * cycling_pace(gradient, mtb) / cycling_pace(0.0, false)
};
distance_m / 1000.0 * minutes_per_km * 60.0 * self.personal_multiplier
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Totals {
pub distance_m: u64,
pub ascent_m: u64,
pub descent_m: u64,
pub seconds: f64,
pub surface_m: [u64; 6],
pub unknown_elevation_m: u64,
pub pushing_m: u64,
}
impl Totals {
pub fn add(&mut self, other: &Self) {
self.distance_m += other.distance_m;
self.ascent_m += other.ascent_m;
self.descent_m += other.descent_m;
self.seconds += other.seconds;
for (metres, other) in self.surface_m.iter_mut().zip(other.surface_m) {
*metres += other;
}
self.unknown_elevation_m += other.unknown_elevation_m;
self.pushing_m += other.pushing_m;
}
}
// Frozen log-pace curve and broad bike offsets from the ride-time model. Learning stays with the host.
fn cycling_pace(gradient: f64, mtb: bool) -> f64 {
const GRADES: [f64; 9] = [-0.2, -0.1, -0.05, -0.02, 0.0, 0.02, 0.05, 0.1, 0.2];
const PACE: [f64; 9] = [
3.6678441275,
2.4586028318,
1.8631026063,
2.0623855840,
2.3229872458,
2.7963045324,
3.8723657434,
5.7198863509,
8.7498015838,
];
let grade = gradient.clamp(GRADES[0], GRADES[8]);
let right = GRADES.partition_point(|&g| g < grade).clamp(1, 8);
let t = (grade - GRADES[right - 1]) / (GRADES[right] - GRADES[right - 1]);
(PACE[right - 1].ln() * (1.0 - t) + PACE[right].ln() * t + if mtb { 0.2243923187 } else { 0.0268886981 }).exp()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn skill_choices_set_difficulty_limits_and_bicycles_avoid_steps() {
let path = Road {
from: 0,
to: 1,
way: 1,
reversed: false,
length_m: 100,
ascent_m: 0,
descent_m: 0,
surface: Surface::Dirt,
class: 4,
access: BIKE | FOOT | PUSH,
difficulty: 255,
hiking_difficulty: None,
structure: false,
shape: vec![],
};
for profile in Profile::presets() {
profile.validate().unwrap();
assert_eq!(profile.permits(&Road { class: 5, ..path.clone() }), profile.walking, "{}", profile.name);
let sac = (1..=6).filter(|&t| profile.permits(&Road { hiking_difficulty: Some(t), ..path.clone() }));
let mtb = (0..=6).filter(|&s| profile.permits(&Road { difficulty: s, ..path.clone() }));
let expected = match profile.name.as_str() {
"hiking/alpine" => (6, 6),
"mtb/technical" => (2, 6),
name if name.starts_with("hiking") => (2, 6),
name if name.starts_with("mtb") => (2, 2),
name if name.starts_with("road") => (2, 0),
_ => (2, 1),
};
assert_eq!((sac.max().unwrap(), mtb.max().unwrap()), expected, "{}", profile.name);
}
}
}