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
use super::*;
use crate::construction::heuristics::*;
use crate::models::common::SingleDimLoad;
use crate::models::problem::ProblemObjective;
use crate::rosomaxa::get_default_selection_size;
use crate::solver::search::*;
use rosomaxa::algorithms::gsom::Input;
use rosomaxa::hyper::*;
use rosomaxa::population::*;
use rosomaxa::termination::*;
use std::marker::PhantomData;
pub type TargetPopulation =
Box<dyn HeuristicPopulation<Objective = ProblemObjective, Individual = InsertionContext> + Send + Sync>;
pub type TargetHeuristic =
Box<dyn HyperHeuristic<Context = RefinementContext, Objective = ProblemObjective, Solution = InsertionContext>>;
pub type TargetHeuristicOperator = Arc<
dyn HeuristicOperator<Context = RefinementContext, Objective = ProblemObjective, Solution = InsertionContext>
+ Send
+ Sync,
>;
pub type GreedyPopulation = Greedy<ProblemObjective, InsertionContext>;
pub type ElitismPopulation = Elitism<ProblemObjective, InsertionContext>;
pub type RosomaxaPopulation = Rosomaxa<ProblemObjective, InsertionContext>;
pub type DynTermination = dyn Termination<Context = RefinementContext, Objective = ProblemObjective> + Send + Sync;
pub type TargetCompositeTermination = CompositeTermination<RefinementContext, ProblemObjective, InsertionContext>;
pub type MaxTimeTermination = MaxTime<RefinementContext, ProblemObjective, InsertionContext>;
pub type MaxGenerationTermination = MaxGeneration<RefinementContext, ProblemObjective, InsertionContext>;
pub type MinVariationTermination = MinVariation<RefinementContext, ProblemObjective, InsertionContext, String>;
pub type TargetHeuristicProbability = HeuristicProbability<RefinementContext, ProblemObjective, InsertionContext>;
pub type TargetHeuristicGroup = HeuristicGroup<RefinementContext, ProblemObjective, InsertionContext>;
pub type ProblemConfigBuilder = EvolutionConfigBuilder<RefinementContext, ProblemObjective, InsertionContext, String>;
pub fn create_default_config_builder(
problem: Arc<Problem>,
environment: Arc<Environment>,
telemetry_mode: TelemetryMode,
) -> ProblemConfigBuilder {
let selection_size = get_default_selection_size(environment.as_ref());
let population = get_default_population(problem.objective.clone(), environment.clone(), selection_size);
ProblemConfigBuilder::default()
.with_heuristic(get_default_heuristic(problem.clone(), environment.clone()))
.with_context(RefinementContext::new(problem.clone(), population, telemetry_mode, environment.clone()))
.with_initial(4, 0.05, create_default_init_operators(problem, environment))
.with_processing(create_default_processing())
}
pub fn get_default_telemetry_mode(logger: InfoLogger) -> TelemetryMode {
TelemetryMode::OnlyLogging { logger, log_best: 100, log_population: 1000, dump_population: false }
}
pub fn get_default_heuristic(problem: Arc<Problem>, environment: Arc<Environment>) -> TargetHeuristic {
get_dynamic_heuristic(problem, environment)
}
pub fn get_static_heuristic(problem: Arc<Problem>, environment: Arc<Environment>) -> TargetHeuristic {
let default_operator = statik::create_default_heuristic_operator(problem, environment.clone());
let local_search = statik::create_default_local_search(environment.clone());
let heuristic_group: TargetHeuristicGroup = vec![
(
Arc::new(DecomposeSearch::new(default_operator.clone(), (2, 4), 4)),
create_context_operator_probability(
300,
10,
vec![(SelectionPhase::Exploration, 0.05), (SelectionPhase::Exploitation, 0.05)],
environment.random.clone(),
),
),
(local_search.clone(), create_scalar_operator_probability(0.05, environment.random.clone())),
(default_operator.clone(), create_scalar_operator_probability(1., environment.random.clone())),
(local_search, create_scalar_operator_probability(0.05, environment.random.clone())),
(
Arc::new(InfeasibleSearch::new(default_operator, 4, (0.05, 0.2), (0.05, 0.33))),
create_scalar_operator_probability(0.01, environment.random.clone()),
),
];
get_static_heuristic_from_heuristic_group(heuristic_group)
}
pub fn get_static_heuristic_from_heuristic_group(heuristic_group: TargetHeuristicGroup) -> TargetHeuristic {
Box::new(StaticSelective::<RefinementContext, ProblemObjective, InsertionContext>::new(heuristic_group))
}
pub fn get_dynamic_heuristic(problem: Arc<Problem>, environment: Arc<Environment>) -> TargetHeuristic {
let random = environment.random.clone();
let operators = dynamic::get_operators(problem, environment);
Box::new(DynamicSelective::<RefinementContext, ProblemObjective, InsertionContext>::new(operators, random))
}
pub fn create_elitism_population(objective: Arc<ProblemObjective>, environment: Arc<Environment>) -> TargetPopulation {
let selection_size = get_default_selection_size(environment.as_ref());
Box::new(Elitism::new(objective, environment.random.clone(), 4, selection_size))
}
impl RosomaxaWeighted for InsertionContext {
fn init_weights(&mut self) {
let weights = vec![
get_max_load_variance(self),
get_duration_mean(self),
get_distance_mean(self),
get_waiting_mean(self),
get_longest_distance_between_customers_mean(self),
get_average_distance_between_depot_customer_mean(self),
get_distance_gravity_mean(self),
get_customers_deviation(self),
get_longest_distance_between_depot_customer_mean(self),
self.solution.routes.len() as f64,
self.solution.unassigned.len() as f64,
];
self.solution.state.insert(SOLUTION_WEIGHTS_KEY, Arc::new(weights));
}
}
impl Input for InsertionContext {
fn weights(&self) -> &[f64] {
self.solution.state.get(&SOLUTION_WEIGHTS_KEY).and_then(|s| s.downcast_ref::<Vec<f64>>()).unwrap().as_slice()
}
}
impl DominanceOrdered for InsertionContext {
fn get_order(&self) -> &DominanceOrder {
self.solution.state.get(&SOLUTION_ORDER_KEY).and_then(|s| s.downcast_ref::<DominanceOrder>()).unwrap()
}
fn set_order(&mut self, order: DominanceOrder) {
self.solution.state.insert(SOLUTION_ORDER_KEY, Arc::new(order));
}
}
pub fn create_scalar_operator_probability(
scalar_probability: f64,
random: Arc<dyn Random + Send + Sync>,
) -> TargetHeuristicProbability {
(Box::new(move |_, _| random.is_hit(scalar_probability)), PhantomData::default())
}
pub fn create_context_operator_probability(
jobs_threshold: usize,
routes_threshold: usize,
phases: Vec<(SelectionPhase, f64)>,
random: Arc<dyn Random + Send + Sync>,
) -> TargetHeuristicProbability {
let phases = phases.into_iter().collect::<HashMap<_, _>>();
(
Box::new(move |refinement_ctx, insertion_ctx| {
let below_thresholds = insertion_ctx.problem.jobs.size() < jobs_threshold
|| insertion_ctx.solution.routes.len() < routes_threshold;
if below_thresholds {
return false;
}
let phase_probability = phases.get(&refinement_ctx.population().selection_phase()).cloned().unwrap_or(0.);
random.is_hit(phase_probability)
}),
PhantomData::default(),
)
}
pub use self::builder::create_default_init_operators;
pub use self::builder::create_default_processing;
pub use self::statik::create_default_heuristic_operator;
pub use self::statik::create_default_random_ruin;
mod builder {
use super::*;
use crate::models::common::SingleDimLoad;
use crate::rosomaxa::evolution::InitialOperators;
use crate::solver::processing::*;
use crate::solver::RecreateInitialOperator;
pub fn create_default_init_operators(
problem: Arc<Problem>,
environment: Arc<Environment>,
) -> InitialOperators<RefinementContext, ProblemObjective, InsertionContext> {
let random = environment.random.clone();
let wrap = |recreate: Arc<dyn Recreate + Send + Sync>| Box::new(RecreateInitialOperator::new(recreate));
vec![
(wrap(Arc::new(RecreateWithCheapest::new(random.clone()))), 1),
(wrap(Arc::new(RecreateWithFarthest::new(random.clone()))), 1),
(wrap(Arc::new(RecreateWithRegret::new(2, 3, random.clone()))), 1),
(wrap(Arc::new(RecreateWithGaps::new(1, (problem.jobs.size() / 10).max(1), random.clone()))), 1),
(wrap(Arc::new(RecreateWithSkipBest::new(1, 2, random.clone()))), 1),
(wrap(Arc::new(RecreateWithBlinks::<SingleDimLoad>::new_with_defaults(random.clone()))), 1),
(wrap(Arc::new(RecreateWithPerturbation::new_with_defaults(random.clone()))), 1),
(wrap(Arc::new(RecreateWithNearestNeighbor::new(random.clone()))), 1),
]
}
pub fn create_default_processing() -> ProcessingConfig<RefinementContext, ProblemObjective, InsertionContext> {
ProcessingConfig {
context: vec![Box::new(VicinityClustering::default())],
solution: vec![
Box::new(AdvanceDeparture::default()),
Box::new(UnassignmentReason::default()),
Box::new(VicinityClustering::default()),
],
}
}
}
mod statik {
use super::*;
pub fn create_default_heuristic_operator(
problem: Arc<Problem>,
environment: Arc<Environment>,
) -> TargetHeuristicOperator {
let random = environment.random.clone();
let recreate = Arc::new(WeightedRecreate::new(vec![
(Arc::new(RecreateWithSkipBest::new(1, 2, random.clone())), 50),
(Arc::new(RecreateWithRegret::new(2, 3, random.clone())), 20),
(Arc::new(RecreateWithCheapest::new(random.clone())), 20),
(Arc::new(RecreateWithPerturbation::new_with_defaults(random.clone())), 10),
(Arc::new(RecreateWithSkipBest::new(3, 4, random.clone())), 5),
(Arc::new(RecreateWithGaps::new(2, 20, random.clone())), 5),
(Arc::new(RecreateWithBlinks::<SingleDimLoad>::new_with_defaults(random.clone())), 5),
(Arc::new(RecreateWithFarthest::new(random.clone())), 2),
(Arc::new(RecreateWithSkipBest::new(4, 8, random.clone())), 2),
(Arc::new(RecreateWithNearestNeighbor::new(random.clone())), 1),
(Arc::new(RecreateWithSlice::new(random.clone())), 1),
(
Arc::new(RecreateWithSkipRandom::default_explorative_phased(
Arc::new(RecreateWithCheapest::new(random.clone())),
random.clone(),
)),
1,
),
]));
let close_route = Arc::new(CloseRouteRemoval::default());
let worst_route = Arc::new(WorstRouteRemoval::default());
let random_route = Arc::new(RandomRouteRemoval::default());
let random_job = Arc::new(RandomJobRemoval::new(RuinLimits::default()));
let random_ruin = create_default_random_ruin();
let ruin = Arc::new(WeightedRuin::new(vec![
(vec![(Arc::new(AdjustedStringRemoval::default()), 1.), (random_ruin.clone(), 0.1)], 100),
(vec![(Arc::new(NeighbourRemoval::default()), 1.), (random_ruin.clone(), 0.1)], 10),
(vec![(Arc::new(WorstJobRemoval::default()), 1.), (random_ruin.clone(), 0.1)], 10),
(
vec![
(Arc::new(ClusterRemoval::new_with_defaults(problem, environment.clone())), 1.),
(random_ruin, 0.1),
],
5,
),
(vec![(close_route, 1.), (random_job.clone(), 0.1)], 2),
(vec![(worst_route, 1.), (random_job.clone(), 0.1)], 1),
(vec![(random_route, 1.), (random_job, 0.1)], 1),
]));
Arc::new(WeightedHeuristicOperator::new(
vec![Arc::new(RuinAndRecreate::new(ruin, recreate)), create_default_local_search(environment)],
vec![100, 10],
))
}
pub fn create_default_random_ruin() -> Arc<dyn Ruin + Send + Sync> {
Arc::new(WeightedRuin::new(vec![
(vec![(Arc::new(CloseRouteRemoval::default()), 1.)], 100),
(vec![(Arc::new(RandomRouteRemoval::default()), 1.)], 10),
(vec![(Arc::new(WorstRouteRemoval::default()), 1.)], 5),
(vec![(Arc::new(RandomJobRemoval::new(RuinLimits::default())), 1.)], 2),
]))
}
pub fn create_default_local_search(environment: Arc<Environment>) -> TargetHeuristicOperator {
let random = environment.random.clone();
Arc::new(LocalSearch::new(Arc::new(CompositeLocalOperator::new(
vec![
(Arc::new(ExchangeSwapStar::new(random)), 200),
(Arc::new(ExchangeInterRouteBest::default()), 100),
(Arc::new(ExchangeSequence::default()), 100),
(Arc::new(ExchangeInterRouteRandom::default()), 30),
(Arc::new(ExchangeIntraRouteRandom::default()), 30),
(Arc::new(RescheduleDeparture::default()), 20),
],
1,
2,
))))
}
}
mod dynamic {
use super::*;
use crate::models::common::MultiDimLoad;
pub fn get_operators(
problem: Arc<Problem>,
environment: Arc<Environment>,
) -> Vec<(TargetHeuristicOperator, String)> {
let random = environment.random.clone();
let recreates: Vec<(Arc<dyn Recreate + Send + Sync>, String)> = vec![
(Arc::new(RecreateWithSkipBest::new(1, 2, random.clone())), "skip_best_1".to_string()),
(Arc::new(RecreateWithSkipBest::new(1, 4, random.clone())), "skip_best_2".to_string()),
(Arc::new(RecreateWithRegret::new(1, 3, random.clone())), "regret".to_string()),
(Arc::new(RecreateWithCheapest::new(random.clone())), "cheapest".to_string()),
(Arc::new(RecreateWithPerturbation::new_with_defaults(random.clone())), "perturbation".to_string()),
(Arc::new(RecreateWithGaps::new(2, 20, random.clone())), "gaps".to_string()),
(
Arc::new(RecreateWithBlinks::<SingleDimLoad>::new_with_defaults(random.clone())),
"blinks_single".to_string(),
),
(
Arc::new(RecreateWithBlinks::<MultiDimLoad>::new_with_defaults(random.clone())),
"blinks_multi".to_string(),
),
(Arc::new(RecreateWithFarthest::new(random.clone())), "farthest".to_string()),
(Arc::new(RecreateWithNearestNeighbor::new(random.clone())), "nearest".to_string()),
(
Arc::new(RecreateWithSkipRandom::default_explorative_phased(
Arc::new(RecreateWithCheapest::new(random.clone())),
random.clone(),
)),
"skip_random".to_string(),
),
(Arc::new(RecreateWithSlice::new(random.clone())), "slice".to_string()),
];
let primary_ruins: Vec<(Arc<dyn Ruin + Send + Sync>, String)> = vec![
(Arc::new(AdjustedStringRemoval::default()), "asr".to_string()),
(Arc::new(NeighbourRemoval::default()), "neighbour_removal".to_string()),
(
Arc::new(ClusterRemoval::new_with_defaults(problem.clone(), environment.clone())),
"cluster_removal".to_string(),
),
(Arc::new(WorstJobRemoval::default()), "worst_job".to_string()),
(Arc::new(RandomJobRemoval::new(RuinLimits::default())), "random_job_removal_1".to_string()),
(Arc::new(RandomRouteRemoval::default()), "random_route_removal".to_string()),
(Arc::new(CloseRouteRemoval::default()), "close_route_removal".to_string()),
(Arc::new(WorstRouteRemoval::default()), "worst_route_removal".to_string()),
];
let secondary_ruins: Vec<(Arc<dyn Ruin + Send + Sync>, String)> =
vec![(Arc::new(RandomJobRemoval::new(RuinLimits::new(2, 8, 0.1, 2))), "random_job_removal_2".to_string())];
let ruins = primary_ruins
.iter()
.flat_map(|(outer_ruin, outer_name)| {
secondary_ruins.iter().map(move |(inner_ruin, inner_name)| {
(outer_ruin.clone(), inner_ruin.clone(), format!("{}+{}", outer_name, inner_name))
})
})
.map::<(Arc<dyn Ruin + Send + Sync>, String), _>(|(a, b, name)| {
(Arc::new(CompositeRuin::new(vec![(a, 1.), (b, 1.)])), name)
})
.chain(primary_ruins.iter().chain(secondary_ruins.iter()).map::<(Arc<dyn Ruin + Send + Sync>, String), _>(
|(ruin, name)| (Arc::new(CompositeRuin::new(vec![(ruin.clone(), 1.)])), name.clone()),
))
.collect::<Vec<_>>();
let inner_search = statik::create_default_heuristic_operator(problem, environment);
let mutations: Vec<(TargetHeuristicOperator, String)> = vec![
(
Arc::new(LocalSearch::new(Arc::new(ExchangeInterRouteBest::default()))),
"local_exch_inter_route_best".to_string(),
),
(
Arc::new(LocalSearch::new(Arc::new(ExchangeInterRouteRandom::default()))),
"local_exch_inter_route_random".to_string(),
),
(
Arc::new(LocalSearch::new(Arc::new(ExchangeIntraRouteRandom::default()))),
"local_exch_intra_route_random".to_string(),
),
(Arc::new(LocalSearch::new(Arc::new(ExchangeSequence::default()))), "local_exch_sequence".to_string()),
(
Arc::new(LocalSearch::new(Arc::new(RescheduleDeparture::default()))),
"local_reschedule_departure".to_string(),
),
(Arc::new(DecomposeSearch::new(inner_search.clone(), (2, 4), 4)), "decompose_search".to_string()),
(
Arc::new(InfeasibleSearch::new(inner_search, 4, (0.05, 0.2), (0.05, 0.33))),
"infeasible_search".to_string(),
),
(
Arc::new(LocalSearch::new(Arc::new(ExchangeSwapStar::new(random.clone())))),
"local_swap_star".to_string(),
),
];
recreates
.iter()
.flat_map(|(recreate, recreate_name)| {
ruins.iter().map::<(TargetHeuristicOperator, String), _>(move |(ruin, ruin_name)| {
(
Arc::new(RuinAndRecreate::new(ruin.clone(), recreate.clone())),
format!("{}+{}", ruin_name, recreate_name),
)
})
})
.chain(mutations.into_iter())
.collect::<Vec<_>>()
}
}