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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#[cfg(test)]
#[path = "../../../tests/unit/construction/heuristics/context_test.rs"]
mod context_test;
use crate::construction::features::{TOTAL_DISTANCE_KEY, TOTAL_DURATION_KEY};
use crate::construction::heuristics::factories::*;
use crate::models::common::Cost;
use crate::models::problem::*;
use crate::models::solution::*;
use crate::models::{Extras, Problem, Solution};
use crate::utils::as_mut;
use hashbrown::{HashMap, HashSet};
use nohash_hasher::BuildNoHashHasher;
use rosomaxa::prelude::*;
use rustc_hash::FxHasher;
use std::any::Any;
use std::hash::BuildHasherDefault;
use std::ops::Deref;
use std::sync::Arc;
pub struct InsertionContext {
pub problem: Arc<Problem>,
pub solution: SolutionContext,
pub environment: Arc<Environment>,
}
impl InsertionContext {
pub fn new(problem: Arc<Problem>, environment: Arc<Environment>) -> Self {
create_insertion_context(problem, environment)
}
pub fn new_empty(problem: Arc<Problem>, environment: Arc<Environment>) -> Self {
create_empty_insertion_context(problem, environment)
}
pub fn new_from_solution(
problem: Arc<Problem>,
solution: (Solution, Option<Cost>),
environment: Arc<Environment>,
) -> Self {
let mut ctx = create_insertion_context_from_solution(problem, solution, environment);
ctx.restore();
ctx
}
pub fn restore(&mut self) {
let constraint = self.problem.goal.clone();
constraint.accept_solution_state(&mut self.solution);
self.remove_empty_routes();
self.solution.routes.iter_mut().for_each(|route_ctx| {
constraint.accept_route_state(route_ctx);
});
}
fn remove_empty_routes(&mut self) {
let registry = &mut self.solution.registry;
self.solution.routes.retain(|rc| {
if rc.route.tour.has_jobs() {
true
} else {
registry.free_route(rc);
false
}
});
}
}
impl HeuristicSolution for InsertionContext {
fn fitness<'a>(&'a self) -> Box<dyn Iterator<Item = f64> + 'a> {
self.problem.goal.fitness(self)
}
fn deep_copy(&self) -> Self {
InsertionContext {
problem: self.problem.clone(),
solution: self.solution.deep_copy(),
environment: self.environment.clone(),
}
}
}
pub type StateValue = Arc<dyn Any + Send + Sync>;
#[derive(Clone)]
pub enum UnassignmentInfo {
Unknown,
Simple(i32),
Detailed(Vec<(Arc<Actor>, i32)>),
}
pub struct SolutionContext {
pub required: Vec<Job>,
pub ignored: Vec<Job>,
pub unassigned: HashMap<Job, UnassignmentInfo>,
pub locked: HashSet<Job>,
pub routes: Vec<RouteContext>,
pub registry: RegistryContext,
pub state: HashMap<i32, StateValue>,
}
impl SolutionContext {
pub fn get_total_cost(&self) -> Cost {
self.routes.iter().fold(Cost::default(), |acc, rc| acc + rc.get_route_cost())
}
pub fn get_max_cost(&self) -> Cost {
self.routes.iter().map(|rc| rc.get_route_cost()).max_by(|&a, &b| compare_floats(a, b)).unwrap_or(0.)
}
pub fn to_solution(&self, extras: Arc<Extras>) -> Solution {
Solution {
registry: self.registry.resources().deep_copy(),
routes: self.routes.iter().map(|rc| rc.route.deep_copy()).collect(),
unassigned: self
.unassigned
.iter()
.map(|(job, code)| (job.clone(), code.clone()))
.chain(self.required.iter().map(|job| (job.clone(), UnassignmentInfo::Unknown)))
.collect(),
extras,
}
}
pub fn get_jobs_amount(&self) -> usize {
let assigned = self.routes.iter().map(|route_ctx| route_ctx.route.tour.job_count()).sum::<usize>();
let required = self.required.iter().filter(|job| !self.unassigned.contains_key(job)).count();
self.unassigned.len() + required + self.ignored.len() + assigned
}
pub fn deep_copy(&self) -> Self {
Self {
required: self.required.clone(),
ignored: self.ignored.clone(),
unassigned: self.unassigned.clone(),
locked: self.locked.clone(),
routes: self.routes.iter().map(|rc| rc.deep_copy()).collect(),
registry: self.registry.deep_copy(),
state: self.state.clone(),
}
}
}
#[derive(Clone)]
pub struct RouteContext {
pub route: Arc<Route>,
pub state: Arc<RouteState>,
cache: Arc<RouteCache>,
}
pub struct RouteState {
route_states: HashMap<i32, StateValue, BuildNoHashHasher<i32>>,
activity_states: HashMap<ActivityWithKey, StateValue, BuildHasherDefault<FxHasher>>,
route_keys: HashSet<i32, BuildNoHashHasher<i32>>,
activity_keys: HashSet<i32, BuildNoHashHasher<i32>>,
flags: u8,
}
pub mod state_flags {
pub const NO_FLAGS: u8 = 0x00;
pub const UNASSIGNABLE: u8 = 0x01;
}
impl RouteContext {
pub fn new(actor: Arc<Actor>) -> Self {
let tour = Tour::new(&actor);
Self::new_with_state(Arc::new(Route { actor, tour }), Arc::new(RouteState::default()))
}
pub fn new_with_state(route: Arc<Route>, state: Arc<RouteState>) -> Self {
RouteContext { route, state, cache: Arc::new(RouteCache { is_stale: true }) }
}
pub fn deep_copy(&self) -> Self {
let new_route = Route { actor: self.route.actor.clone(), tour: self.route.tour.deep_copy() };
let new_state = RouteState::from_other_and_tours(self.state.as_ref(), &self.route.tour, &new_route.tour);
RouteContext {
route: Arc::new(new_route),
state: Arc::new(new_state),
cache: Arc::new(RouteCache { is_stale: self.cache.is_stale }),
}
}
pub fn get_route_cost(&self) -> Cost {
let get_cost = |costs: &Costs, distance: f64, duration: f64| {
costs.fixed
+ costs.per_distance * distance
+ costs.per_driving_time.max(costs.per_service_time).max(costs.per_waiting_time) * duration
};
let actor = &self.route.actor;
let distance = self.state.get_route_state::<f64>(TOTAL_DISTANCE_KEY).cloned().unwrap_or(0.);
let duration = self.state.get_route_state::<f64>(TOTAL_DURATION_KEY).cloned().unwrap_or(0.);
get_cost(&actor.vehicle.costs, distance, duration) + get_cost(&actor.driver.costs, distance, duration)
}
pub fn as_mut(&mut self) -> (&mut Route, &mut RouteState) {
self.mark_stale(true);
let route: &mut Route = unsafe { as_mut(&self.route) };
let state: &mut RouteState = unsafe { as_mut(&self.state) };
(route, state)
}
pub fn route_mut(&mut self) -> &mut Route {
self.mark_stale(true);
unsafe { as_mut(&self.route) }
}
pub fn state_mut(&mut self) -> &mut RouteState {
self.mark_stale(true);
unsafe { as_mut(&self.state) }
}
pub fn is_stale(&self) -> bool {
self.cache.is_stale
}
pub(crate) fn mark_stale(&mut self, is_stale: bool) {
let cache: &mut RouteCache = unsafe { as_mut(&self.cache) };
cache.is_stale = is_stale;
}
}
impl PartialEq<RouteContext> for RouteContext {
fn eq(&self, other: &RouteContext) -> bool {
std::ptr::eq(self.route.deref(), other.route.deref())
}
}
impl Eq for RouteContext {}
impl Default for RouteState {
fn default() -> RouteState {
RouteState {
route_states: HashMap::with_capacity_and_hasher(2, BuildNoHashHasher::<i32>::default()),
activity_states: HashMap::with_capacity_and_hasher(4, BuildHasherDefault::<FxHasher>::default()),
route_keys: HashSet::with_capacity_and_hasher(2, BuildNoHashHasher::<i32>::default()),
activity_keys: HashSet::with_capacity_and_hasher(4, BuildNoHashHasher::<i32>::default()),
flags: state_flags::NO_FLAGS,
}
}
}
impl RouteState {
pub(crate) fn from_other_and_tours(other: &Self, old_tour: &Tour, new_tour: &Tour) -> Self {
let route_states = other.route_states.clone();
let route_keys = other.route_keys.clone();
let activity_keys = other.activity_keys.clone();
let mut activity_states =
HashMap::with_capacity_and_hasher(other.activity_states.len(), BuildHasherDefault::<FxHasher>::default());
old_tour.all_activities().enumerate().for_each(|(index, activity)| {
other.all_activity_keys().for_each(|key| {
if let Some(value) = other.get_activity_state_raw(key, activity) {
let activity = new_tour.get(index).unwrap();
activity_states.insert((activity as *const Activity as usize, key), value.clone());
}
});
});
Self { route_states, activity_states, route_keys, activity_keys, flags: other.flags }
}
pub fn get_route_state<T: Send + Sync + 'static>(&self, key: i32) -> Option<&T> {
self.route_states.get(&key).and_then(|s| s.downcast_ref::<T>())
}
pub fn get_route_state_raw(&self, key: i32) -> Option<&StateValue> {
self.route_states.get(&key)
}
pub fn get_activity_state<T: Send + Sync + 'static>(&self, key: i32, activity: &Activity) -> Option<&T> {
self.activity_states.get(&(activity as *const Activity as usize, key)).and_then(|s| s.downcast_ref::<T>())
}
pub fn get_activity_state_raw(&self, key: i32, activity: &Activity) -> Option<&StateValue> {
self.activity_states.get(&(activity as *const Activity as usize, key))
}
pub fn put_route_state<T: Send + Sync + 'static>(&mut self, key: i32, value: T) {
self.route_states.insert(key, Arc::new(value));
self.route_keys.insert(key);
}
pub fn put_route_state_raw(&mut self, key: i32, value: Arc<dyn Any + Send + Sync>) {
self.route_states.insert(key, value);
self.route_keys.insert(key);
}
pub fn put_activity_state<T: Send + Sync + 'static>(&mut self, key: i32, activity: &Activity, value: T) {
self.activity_states.insert((activity as *const Activity as usize, key), Arc::new(value));
self.activity_keys.insert(key);
}
pub fn put_activity_state_raw(&mut self, key: i32, activity: &Activity, value: StateValue) {
self.activity_states.insert((activity as *const Activity as usize, key), value);
self.activity_keys.insert(key);
}
pub fn remove_activity_states(&mut self, activity: &Activity) {
for (_, key) in self.activity_keys.iter().enumerate() {
self.activity_states.remove(&(activity as *const Activity as usize, *key));
}
}
pub fn all_activity_keys(&'_ self) -> impl Iterator<Item = i32> + '_ {
self.activity_keys.iter().cloned()
}
pub fn all_route_keys(&'_ self) -> impl Iterator<Item = i32> + '_ {
self.route_keys.iter().cloned()
}
pub fn sizes(&self) -> (usize, usize) {
(self.route_states.capacity(), self.activity_states.capacity())
}
pub fn set_flag(&mut self, flag: u8) {
self.flags |= flag;
}
pub fn get_flags(&self) -> u8 {
self.flags
}
pub fn has_flag(&self, flag: u8) -> bool {
(self.flags & flag) > 0
}
pub fn reset_flags(&mut self) {
self.flags = state_flags::NO_FLAGS
}
pub fn clear(&mut self) {
self.activity_keys.clear();
self.activity_states.clear();
self.route_keys.clear();
self.route_states.clear();
}
}
struct RouteCache {
is_stale: bool,
}
pub struct RouteModifier {
modifier: Arc<dyn Fn(RouteContext) -> RouteContext + Sync + Send>,
}
impl RouteModifier {
pub fn new<F: 'static + Fn(RouteContext) -> RouteContext + Sync + Send>(modifier: F) -> Self {
Self { modifier: Arc::new(modifier) }
}
pub fn modify(&self, route_ctx: RouteContext) -> RouteContext {
self.modifier.deref()(route_ctx)
}
}
pub struct RegistryContext {
registry: Registry,
index: HashMap<Arc<Actor>, RouteContext>,
}
impl RegistryContext {
pub fn new(goal: Arc<GoalContext>, registry: Registry) -> Self {
Self::new_with_modifier(goal, registry, &RouteModifier::new(move |route_ctx| route_ctx))
}
pub fn new_with_modifier(goal: Arc<GoalContext>, registry: Registry, modifier: &RouteModifier) -> Self {
let index = registry
.all()
.map(|actor| {
let mut route_ctx = RouteContext::new(actor.clone());
goal.accept_route_state(&mut route_ctx);
(actor, modifier.modify(route_ctx))
})
.collect();
Self { registry, index }
}
pub fn resources(&self) -> &Registry {
&self.registry
}
pub fn next(&'_ self) -> impl Iterator<Item = RouteContext> + '_ {
self.registry.next().map(move |actor| self.index[&actor].clone())
}
pub fn next_with_actor(&self, actor: &Actor) -> Option<RouteContext> {
self.registry.available().find(|a| actor == a.as_ref()).and_then(|a| self.index.get(&a).cloned())
}
pub fn use_route(&mut self, route: &RouteContext) -> bool {
self.registry.use_actor(&route.route.actor)
}
pub fn free_route(&mut self, route: &RouteContext) {
self.registry.free_actor(&route.route.actor);
}
pub fn deep_copy(&self) -> Self {
Self { registry: self.registry.deep_copy(), index: self.index.clone() }
}
pub fn deep_slice(&self, filter: impl Fn(&Actor) -> bool) -> Self {
let index = self
.index
.iter()
.filter(|(actor, _)| filter(actor.as_ref()))
.map(|(actor, route_ctx)| (actor.clone(), route_ctx.clone()))
.collect();
Self { registry: self.registry.deep_slice(filter), index }
}
}
pub struct ActivityContext<'a> {
pub index: usize,
pub prev: &'a Activity,
pub target: &'a Activity,
pub next: Option<&'a Activity>,
}
type ActivityWithKey = (usize, i32);
pub enum MoveContext<'a> {
Route {
solution_ctx: &'a SolutionContext,
route_ctx: &'a RouteContext,
job: &'a Job,
},
Activity {
route_ctx: &'a RouteContext,
activity_ctx: &'a ActivityContext<'a>,
},
}
impl<'a> MoveContext<'a> {
pub fn route(solution_ctx: &'a SolutionContext, route_ctx: &'a RouteContext, job: &'a Job) -> MoveContext<'a> {
MoveContext::Route { solution_ctx, route_ctx, job }
}
pub fn activity(route_ctx: &'a RouteContext, activity_ctx: &'a ActivityContext) -> MoveContext<'a> {
MoveContext::Activity { route_ctx, activity_ctx }
}
}