forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouting_search.cc
4521 lines (4173 loc) · 177 KB
/
routing_search.cc
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Implementation of all classes related to routing and search.
// This includes decision builders, local search neighborhood operators
// and local search filters.
// TODO(user): Move all existing routing search code here.
#include "ortools/constraint_solver/routing_search.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <deque>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/flags/flag.h"
#include "absl/memory/memory.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "ortools/base/adjustable_priority_queue-inl.h"
#include "ortools/base/adjustable_priority_queue.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/macros.h"
#include "ortools/base/map_util.h"
#include "ortools/base/stl_util.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_index_manager.h"
#include "ortools/constraint_solver/routing_types.h"
#include "ortools/graph/christofides.h"
#include "ortools/util/bitset.h"
#include "ortools/util/range_query_function.h"
#include "ortools/util/saturated_arithmetic.h"
namespace operations_research {
class LocalSearchPhaseParameters;
} // namespace operations_research
ABSL_FLAG(bool, routing_shift_insertion_cost_by_penalty, true,
"Shift insertion costs by the penalty of the inserted node(s).");
ABSL_FLAG(int64_t, sweep_sectors, 1,
"The number of sectors the space is divided into before it is sweeped"
" by the ray.");
namespace operations_research {
// --- VehicleTypeCurator ---
void VehicleTypeCurator::Reset(const std::function<bool(int)>& store_vehicle) {
const std::vector<std::set<VehicleClassEntry>>& all_vehicle_classes_per_type =
vehicle_type_container_->sorted_vehicle_classes_per_type;
sorted_vehicle_classes_per_type_.resize(all_vehicle_classes_per_type.size());
const std::vector<std::deque<int>>& all_vehicles_per_class =
vehicle_type_container_->vehicles_per_vehicle_class;
vehicles_per_vehicle_class_.resize(all_vehicles_per_class.size());
for (int type = 0; type < all_vehicle_classes_per_type.size(); type++) {
std::set<VehicleClassEntry>& stored_class_entries =
sorted_vehicle_classes_per_type_[type];
stored_class_entries.clear();
for (VehicleClassEntry class_entry : all_vehicle_classes_per_type[type]) {
const int vehicle_class = class_entry.vehicle_class;
std::vector<int>& stored_vehicles =
vehicles_per_vehicle_class_[vehicle_class];
stored_vehicles.clear();
for (int vehicle : all_vehicles_per_class[vehicle_class]) {
if (store_vehicle(vehicle)) {
stored_vehicles.push_back(vehicle);
}
}
if (!stored_vehicles.empty()) {
stored_class_entries.insert(class_entry);
}
}
}
}
void VehicleTypeCurator::Update(
const std::function<bool(int)>& remove_vehicle) {
for (std::set<VehicleClassEntry>& class_entries :
sorted_vehicle_classes_per_type_) {
auto class_entry_it = class_entries.begin();
while (class_entry_it != class_entries.end()) {
const int vehicle_class = class_entry_it->vehicle_class;
std::vector<int>& vehicles = vehicles_per_vehicle_class_[vehicle_class];
vehicles.erase(std::remove_if(vehicles.begin(), vehicles.end(),
[&remove_vehicle](int vehicle) {
return remove_vehicle(vehicle);
}),
vehicles.end());
if (vehicles.empty()) {
class_entry_it = class_entries.erase(class_entry_it);
} else {
class_entry_it++;
}
}
}
}
bool VehicleTypeCurator::HasCompatibleVehicleOfType(
int type, const std::function<bool(int)>& vehicle_is_compatible) const {
for (const VehicleClassEntry& vehicle_class_entry :
sorted_vehicle_classes_per_type_[type]) {
for (int vehicle :
vehicles_per_vehicle_class_[vehicle_class_entry.vehicle_class]) {
if (vehicle_is_compatible(vehicle)) return true;
}
}
return false;
}
std::pair<int, int> VehicleTypeCurator::GetCompatibleVehicleOfType(
int type, std::function<bool(int)> vehicle_is_compatible,
std::function<bool(int)> stop_and_return_vehicle) {
std::set<VehicleTypeCurator::VehicleClassEntry>& sorted_classes =
sorted_vehicle_classes_per_type_[type];
auto vehicle_class_it = sorted_classes.begin();
while (vehicle_class_it != sorted_classes.end()) {
const int vehicle_class = vehicle_class_it->vehicle_class;
std::vector<int>& vehicles = vehicles_per_vehicle_class_[vehicle_class];
DCHECK(!vehicles.empty());
for (auto vehicle_it = vehicles.begin(); vehicle_it != vehicles.end();
vehicle_it++) {
const int vehicle = *vehicle_it;
if (vehicle_is_compatible(vehicle)) {
vehicles.erase(vehicle_it);
if (vehicles.empty()) {
sorted_classes.erase(vehicle_class_it);
}
return {vehicle, -1};
}
if (stop_and_return_vehicle(vehicle)) {
return {-1, vehicle};
}
}
// If no compatible vehicle was found in this class, move on to the next
// vehicle class.
vehicle_class_it++;
}
// No compatible vehicle of the given type was found and the stopping
// condition wasn't met.
return {-1, -1};
}
// - Models with pickup/deliveries or node precedences are best handled by
// PARALLEL_CHEAPEST_INSERTION.
// - As of January 2018, models with single nodes and at least one node with
// only one allowed vehicle are better solved by PATH_MOST_CONSTRAINED_ARC.
// - In all other cases, PATH_CHEAPEST_ARC is used.
// TODO(user): Make this smarter.
FirstSolutionStrategy::Value AutomaticFirstSolutionStrategy(
bool has_pickup_deliveries, bool has_node_precedences,
bool has_single_vehicle_node) {
if (has_pickup_deliveries || has_node_precedences) {
return FirstSolutionStrategy::PARALLEL_CHEAPEST_INSERTION;
}
if (has_single_vehicle_node) {
return FirstSolutionStrategy::PATH_MOST_CONSTRAINED_ARC;
}
return FirstSolutionStrategy::PATH_CHEAPEST_ARC;
}
// --- First solution decision builder ---
// IntVarFilteredDecisionBuilder
IntVarFilteredDecisionBuilder::IntVarFilteredDecisionBuilder(
std::unique_ptr<IntVarFilteredHeuristic> heuristic)
: heuristic_(std::move(heuristic)) {}
Decision* IntVarFilteredDecisionBuilder::Next(Solver* solver) {
Assignment* const assignment = heuristic_->BuildSolution();
if (assignment != nullptr) {
VLOG(2) << "Number of decisions: " << heuristic_->number_of_decisions();
VLOG(2) << "Number of rejected decisions: "
<< heuristic_->number_of_rejects();
assignment->Restore();
} else {
solver->Fail();
}
return nullptr;
}
int64_t IntVarFilteredDecisionBuilder::number_of_decisions() const {
return heuristic_->number_of_decisions();
}
int64_t IntVarFilteredDecisionBuilder::number_of_rejects() const {
return heuristic_->number_of_rejects();
}
std::string IntVarFilteredDecisionBuilder::DebugString() const {
return absl::StrCat("IntVarFilteredDecisionBuilder(",
heuristic_->DebugString(), ")");
}
// --- First solution heuristics ---
// IntVarFilteredHeuristic
IntVarFilteredHeuristic::IntVarFilteredHeuristic(
Solver* solver, const std::vector<IntVar*>& vars,
LocalSearchFilterManager* filter_manager)
: assignment_(solver->MakeAssignment()),
solver_(solver),
vars_(vars),
delta_(solver->MakeAssignment()),
is_in_delta_(vars_.size(), false),
empty_(solver->MakeAssignment()),
filter_manager_(filter_manager),
number_of_decisions_(0),
number_of_rejects_(0) {
assignment_->MutableIntVarContainer()->Resize(vars_.size());
delta_indices_.reserve(vars_.size());
}
void IntVarFilteredHeuristic::ResetSolution() {
number_of_decisions_ = 0;
number_of_rejects_ = 0;
// Wiping assignment when starting a new search.
assignment_->MutableIntVarContainer()->Clear();
assignment_->MutableIntVarContainer()->Resize(vars_.size());
delta_->MutableIntVarContainer()->Clear();
SynchronizeFilters();
}
Assignment* const IntVarFilteredHeuristic::BuildSolution() {
ResetSolution();
if (!InitializeSolution()) {
return nullptr;
}
SynchronizeFilters();
if (BuildSolutionInternal()) {
return assignment_;
}
return nullptr;
}
const Assignment* RoutingFilteredHeuristic::BuildSolutionFromRoutes(
const std::function<int64_t(int64_t)>& next_accessor) {
ResetSolution();
ResetVehicleIndices();
// NOTE: We don't need to clear or pre-set the two following vectors as the
// for loop below will set all elements.
start_chain_ends_.resize(model()->vehicles());
end_chain_starts_.resize(model()->vehicles());
for (int v = 0; v < model_->vehicles(); v++) {
int64_t node = model_->Start(v);
while (!model_->IsEnd(node)) {
const int64_t next = next_accessor(node);
DCHECK_NE(next, node);
SetValue(node, next);
SetVehicleIndex(node, v);
node = next;
}
// We relax all routes from start to end, so routes can now be extended
// by inserting nodes between the start and end.
start_chain_ends_[v] = model()->Start(v);
end_chain_starts_[v] = model()->End(v);
}
if (!Commit()) {
return nullptr;
}
SynchronizeFilters();
if (BuildSolutionInternal()) {
return assignment_;
}
return nullptr;
}
bool IntVarFilteredHeuristic::Commit() {
++number_of_decisions_;
const bool accept = FilterAccept();
if (accept) {
const Assignment::IntContainer& delta_container = delta_->IntVarContainer();
const int delta_size = delta_container.Size();
Assignment::IntContainer* const container =
assignment_->MutableIntVarContainer();
for (int i = 0; i < delta_size; ++i) {
const IntVarElement& delta_element = delta_container.Element(i);
IntVar* const var = delta_element.Var();
DCHECK_EQ(var, vars_[delta_indices_[i]]);
container->AddAtPosition(var, delta_indices_[i])
->SetValue(delta_element.Value());
}
SynchronizeFilters();
} else {
++number_of_rejects_;
}
// Reset is_in_delta to all false.
for (const int delta_index : delta_indices_) {
is_in_delta_[delta_index] = false;
}
delta_->Clear();
delta_indices_.clear();
return accept;
}
void IntVarFilteredHeuristic::SynchronizeFilters() {
if (filter_manager_) filter_manager_->Synchronize(assignment_, delta_);
}
bool IntVarFilteredHeuristic::FilterAccept() {
if (!filter_manager_) return true;
LocalSearchMonitor* const monitor = solver_->GetLocalSearchMonitor();
return filter_manager_->Accept(monitor, delta_, empty_,
std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max());
}
// RoutingFilteredHeuristic
RoutingFilteredHeuristic::RoutingFilteredHeuristic(
RoutingModel* model, LocalSearchFilterManager* filter_manager)
: IntVarFilteredHeuristic(model->solver(), model->Nexts(), filter_manager),
model_(model) {}
bool RoutingFilteredHeuristic::InitializeSolution() {
// Find the chains of nodes (when nodes have their "Next" value bound in the
// current solution, it forms a link in a chain). Eventually, starts[end]
// will contain the index of the first node of the chain ending at node 'end'
// and ends[start] will be the last node of the chain starting at node
// 'start'. Values of starts[node] and ends[node] for other nodes is used
// for intermediary computations and do not necessarily reflect actual chain
// starts and ends.
// Start by adding partial start chains to current assignment.
start_chain_ends_.clear();
start_chain_ends_.resize(model()->vehicles(), -1);
end_chain_starts_.clear();
end_chain_starts_.resize(model()->vehicles(), -1);
ResetVehicleIndices();
for (int vehicle = 0; vehicle < model()->vehicles(); ++vehicle) {
int64_t node = model()->Start(vehicle);
while (!model()->IsEnd(node) && Var(node)->Bound()) {
const int64_t next = Var(node)->Min();
SetValue(node, next);
SetVehicleIndex(node, vehicle);
node = next;
}
start_chain_ends_[vehicle] = node;
}
std::vector<int64_t> starts(Size() + model()->vehicles(), -1);
std::vector<int64_t> ends(Size() + model()->vehicles(), -1);
for (int node = 0; node < Size() + model()->vehicles(); ++node) {
// Each node starts as a singleton chain.
starts[node] = node;
ends[node] = node;
}
std::vector<bool> touched(Size(), false);
for (int node = 0; node < Size(); ++node) {
int current = node;
while (!model()->IsEnd(current) && !touched[current]) {
touched[current] = true;
IntVar* const next_var = Var(current);
if (next_var->Bound()) {
current = next_var->Value();
}
}
// Merge the sub-chain starting from 'node' and ending at 'current' with
// the existing sub-chain starting at 'current'.
starts[ends[current]] = starts[node];
ends[starts[node]] = ends[current];
}
// Set each route to be the concatenation of the chain at its starts and the
// chain at its end, without nodes in between.
for (int vehicle = 0; vehicle < model()->vehicles(); ++vehicle) {
end_chain_starts_[vehicle] = starts[model()->End(vehicle)];
int64_t node = start_chain_ends_[vehicle];
if (!model()->IsEnd(node)) {
int64_t next = starts[model()->End(vehicle)];
SetValue(node, next);
SetVehicleIndex(node, vehicle);
node = next;
while (!model()->IsEnd(node)) {
next = Var(node)->Min();
SetValue(node, next);
SetVehicleIndex(node, vehicle);
node = next;
}
}
}
if (!Commit()) {
ResetVehicleIndices();
return false;
}
return true;
}
void RoutingFilteredHeuristic::MakeDisjunctionNodesUnperformed(int64_t node) {
model()->ForEachNodeInDisjunctionWithMaxCardinalityFromIndex(
node, 1, [this, node](int alternate) {
if (node != alternate && !Contains(alternate)) {
SetValue(alternate, alternate);
}
});
}
void RoutingFilteredHeuristic::MakeUnassignedNodesUnperformed() {
for (int index = 0; index < Size(); ++index) {
if (!Contains(index)) {
SetValue(index, index);
}
}
}
void RoutingFilteredHeuristic::MakePartiallyPerformedPairsUnperformed() {
std::vector<bool> to_make_unperformed(Size(), false);
for (const auto& [pickups, deliveries] :
model()->GetPickupAndDeliveryPairs()) {
int64_t performed_pickup = -1;
for (int64_t pickup : pickups) {
if (Contains(pickup) && Value(pickup) != pickup) {
performed_pickup = pickup;
break;
}
}
int64_t performed_delivery = -1;
for (int64_t delivery : deliveries) {
if (Contains(delivery) && Value(delivery) != delivery) {
performed_delivery = delivery;
break;
}
}
if ((performed_pickup == -1) != (performed_delivery == -1)) {
if (performed_pickup != -1) {
to_make_unperformed[performed_pickup] = true;
}
if (performed_delivery != -1) {
to_make_unperformed[performed_delivery] = true;
}
}
}
for (int index = 0; index < Size(); ++index) {
if (to_make_unperformed[index] || !Contains(index)) continue;
int64_t next = Value(index);
while (next < Size() && to_make_unperformed[next]) {
const int64_t next_of_next = Value(next);
SetValue(index, next_of_next);
SetValue(next, next);
next = next_of_next;
}
}
}
// CheapestInsertionFilteredHeuristic
CheapestInsertionFilteredHeuristic::CheapestInsertionFilteredHeuristic(
RoutingModel* model,
std::function<int64_t(int64_t, int64_t, int64_t)> evaluator,
std::function<int64_t(int64_t)> penalty_evaluator,
LocalSearchFilterManager* filter_manager)
: RoutingFilteredHeuristic(model, filter_manager),
evaluator_(std::move(evaluator)),
penalty_evaluator_(std::move(penalty_evaluator)) {}
std::vector<std::vector<CheapestInsertionFilteredHeuristic::StartEndValue>>
CheapestInsertionFilteredHeuristic::ComputeStartEndDistanceForVehicles(
const std::vector<int>& vehicles) {
const absl::flat_hash_set<int> vehicle_set(vehicles.begin(), vehicles.end());
std::vector<std::vector<StartEndValue>> start_end_distances_per_node(
model()->Size());
for (int node = 0; node < model()->Size(); node++) {
if (Contains(node)) continue;
std::vector<StartEndValue>& start_end_distances =
start_end_distances_per_node[node];
const IntVar* const vehicle_var = model()->VehicleVar(node);
const int64_t num_allowed_vehicles = vehicle_var->Size();
const auto add_distance = [this, node, num_allowed_vehicles,
&start_end_distances](int vehicle) {
const int64_t start = model()->Start(vehicle);
const int64_t end = model()->End(vehicle);
// We compute the distance of node to the start/end nodes of the route.
const int64_t distance =
CapAdd(model()->GetArcCostForVehicle(start, node, vehicle),
model()->GetArcCostForVehicle(node, end, vehicle));
start_end_distances.push_back({num_allowed_vehicles, distance, vehicle});
};
// Iterating over an IntVar domain is faster than calling Contains.
// Therefore we iterate on 'vehicles' only if it's smaller than the domain
// size of the VehicleVar.
if (num_allowed_vehicles < vehicles.size()) {
std::unique_ptr<IntVarIterator> it(
vehicle_var->MakeDomainIterator(false));
for (const int64_t vehicle : InitAndGetValues(it.get())) {
if (vehicle < 0 || !vehicle_set.contains(vehicle)) continue;
add_distance(vehicle);
}
} else {
for (const int vehicle : vehicles) {
if (!vehicle_var->Contains(vehicle)) continue;
add_distance(vehicle);
}
}
// Sort the distances for the node to all start/ends of available vehicles
// in decreasing order.
std::sort(start_end_distances.begin(), start_end_distances.end(),
[](const StartEndValue& first, const StartEndValue& second) {
return second < first;
});
}
return start_end_distances_per_node;
}
template <class Queue>
void CheapestInsertionFilteredHeuristic::InitializePriorityQueue(
std::vector<std::vector<StartEndValue>>* start_end_distances_per_node,
Queue* priority_queue) {
const int num_nodes = model()->Size();
DCHECK_EQ(start_end_distances_per_node->size(), num_nodes);
for (int node = 0; node < num_nodes; node++) {
if (Contains(node)) continue;
std::vector<StartEndValue>& start_end_distances =
(*start_end_distances_per_node)[node];
if (start_end_distances.empty()) {
continue;
}
// Put the best StartEndValue for this node in the priority queue.
const StartEndValue& start_end_value = start_end_distances.back();
priority_queue->push(std::make_pair(start_end_value, node));
start_end_distances.pop_back();
}
}
void CheapestInsertionFilteredHeuristic::InsertBetween(int64_t node,
int64_t predecessor,
int64_t successor) {
SetValue(predecessor, node);
SetValue(node, successor);
MakeDisjunctionNodesUnperformed(node);
}
void CheapestInsertionFilteredHeuristic::AppendInsertionPositionsAfter(
int64_t node_to_insert, int64_t start, int64_t next_after_start,
int vehicle, std::vector<NodeInsertion>* node_insertions) {
DCHECK(node_insertions != nullptr);
int64_t insert_after = start;
while (!model()->IsEnd(insert_after)) {
const int64_t insert_before =
(insert_after == start) ? next_after_start : Value(insert_after);
node_insertions->push_back(
{insert_after, vehicle,
GetInsertionCostForNodeAtPosition(node_to_insert, insert_after,
insert_before, vehicle)});
insert_after = insert_before;
}
}
int64_t CheapestInsertionFilteredHeuristic::GetInsertionCostForNodeAtPosition(
int64_t node_to_insert, int64_t insert_after, int64_t insert_before,
int vehicle) const {
return CapSub(CapAdd(evaluator_(insert_after, node_to_insert, vehicle),
evaluator_(node_to_insert, insert_before, vehicle)),
evaluator_(insert_after, insert_before, vehicle));
}
int64_t CheapestInsertionFilteredHeuristic::GetUnperformedValue(
int64_t node_to_insert) const {
if (penalty_evaluator_ != nullptr) {
return penalty_evaluator_(node_to_insert);
}
return std::numeric_limits<int64_t>::max();
}
namespace {
template <class T>
void SortAndExtractPairSeconds(std::vector<std::pair<int64_t, T>>* pairs,
std::vector<T>* sorted_seconds) {
CHECK(pairs != nullptr);
CHECK(sorted_seconds != nullptr);
std::sort(pairs->begin(), pairs->end());
sorted_seconds->reserve(pairs->size());
for (const std::pair<int64_t, T>& p : *pairs) {
sorted_seconds->push_back(p.second);
}
}
} // namespace
// Priority queue entries used by global cheapest insertion heuristic.
// Entry in priority queue containing the insertion positions of a node pair.
class GlobalCheapestInsertionFilteredHeuristic::PairEntry {
public:
PairEntry(int pickup_to_insert, int pickup_insert_after,
int delivery_to_insert, int delivery_insert_after, int vehicle,
int64_t bucket)
: value_(std::numeric_limits<int64_t>::max()),
heap_index_(-1),
pickup_to_insert_(pickup_to_insert),
pickup_insert_after_(pickup_insert_after),
delivery_to_insert_(delivery_to_insert),
delivery_insert_after_(delivery_insert_after),
vehicle_(vehicle),
bucket_(bucket) {}
// Note: for compatibility reasons, comparator follows tie-breaking rules used
// in the first version of GlobalCheapestInsertion.
bool operator<(const PairEntry& other) const {
// We give higher priority to insertions from lower buckets.
if (bucket_ != other.bucket_) {
return bucket_ > other.bucket_;
}
// We then compare by value, then we favor insertions (vehicle != -1).
// The rest of the tie-breaking is done with std::tie.
if (value_ != other.value_) {
return value_ > other.value_;
}
if ((vehicle_ == -1) ^ (other.vehicle_ == -1)) {
return vehicle_ == -1;
}
return std::tie(pickup_insert_after_, pickup_to_insert_,
delivery_insert_after_, delivery_to_insert_, vehicle_) >
std::tie(other.pickup_insert_after_, other.pickup_to_insert_,
other.delivery_insert_after_, other.delivery_to_insert_,
other.vehicle_);
}
void SetHeapIndex(int h) { heap_index_ = h; }
int GetHeapIndex() const { return heap_index_; }
void set_value(int64_t value) { value_ = value; }
int pickup_to_insert() const { return pickup_to_insert_; }
int pickup_insert_after() const { return pickup_insert_after_; }
void set_pickup_insert_after(int pickup_insert_after) {
pickup_insert_after_ = pickup_insert_after;
}
int delivery_to_insert() const { return delivery_to_insert_; }
int delivery_insert_after() const { return delivery_insert_after_; }
int vehicle() const { return vehicle_; }
void set_vehicle(int vehicle) { vehicle_ = vehicle; }
private:
int64_t value_;
int heap_index_;
const int pickup_to_insert_;
int pickup_insert_after_;
const int delivery_to_insert_;
const int delivery_insert_after_;
int vehicle_;
const int64_t bucket_;
};
// Entry in priority queue containing the insertion position of a node.
class GlobalCheapestInsertionFilteredHeuristic::NodeEntry {
public:
NodeEntry(int node_to_insert, int insert_after, int vehicle, int64_t bucket)
: value_(std::numeric_limits<int64_t>::max()),
heap_index_(-1),
node_to_insert_(node_to_insert),
insert_after_(insert_after),
vehicle_(vehicle),
bucket_(bucket) {}
bool operator<(const NodeEntry& other) const {
// See PairEntry::operator<(), above. This one is similar.
if (bucket_ != other.bucket_) {
return bucket_ > other.bucket_;
}
if (value_ != other.value_) {
return value_ > other.value_;
}
if ((vehicle_ == -1) ^ (other.vehicle_ == -1)) {
return vehicle_ == -1;
}
return std::tie(insert_after_, node_to_insert_, vehicle_) >
std::tie(other.insert_after_, other.node_to_insert_, other.vehicle_);
}
void SetHeapIndex(int h) { heap_index_ = h; }
int GetHeapIndex() const { return heap_index_; }
void set_value(int64_t value) { value_ = value; }
int node_to_insert() const { return node_to_insert_; }
int insert_after() const { return insert_after_; }
void set_insert_after(int insert_after) { insert_after_ = insert_after; }
int vehicle() const { return vehicle_; }
void set_vehicle(int vehicle) { vehicle_ = vehicle; }
private:
int64_t value_;
int heap_index_;
const int node_to_insert_;
int insert_after_;
int vehicle_;
const int64_t bucket_;
};
// GlobalCheapestInsertionFilteredHeuristic
GlobalCheapestInsertionFilteredHeuristic::
GlobalCheapestInsertionFilteredHeuristic(
RoutingModel* model,
std::function<int64_t(int64_t, int64_t, int64_t)> evaluator,
std::function<int64_t(int64_t)> penalty_evaluator,
LocalSearchFilterManager* filter_manager,
GlobalCheapestInsertionParameters parameters)
: CheapestInsertionFilteredHeuristic(model, std::move(evaluator),
std::move(penalty_evaluator),
filter_manager),
gci_params_(parameters),
node_index_to_vehicle_(model->Size(), -1),
empty_vehicle_type_curator_(nullptr) {
CHECK_GT(gci_params_.neighbors_ratio, 0);
CHECK_LE(gci_params_.neighbors_ratio, 1);
CHECK_GE(gci_params_.min_neighbors, 1);
if (NumNeighbors() >= NumNonStartEndNodes() - 1) {
// All nodes are neighbors, so we set the neighbors_ratio to 1 to avoid
// unnecessary computations in the code.
gci_params_.neighbors_ratio = 1;
}
if (gci_params_.neighbors_ratio == 1) {
gci_params_.use_neighbors_ratio_for_initialization = false;
all_nodes_.resize(model->Size());
std::iota(all_nodes_.begin(), all_nodes_.end(), 0);
}
}
void GlobalCheapestInsertionFilteredHeuristic::ComputeNeighborhoods() {
if (gci_params_.neighbors_ratio == 1 ||
!node_index_to_neighbors_by_cost_class_.empty()) {
// Neighborhood computations not needed or already done.
return;
}
// TODO(user): Refactor the neighborhood computations in RoutingModel.
const int64_t num_neighbors = NumNeighbors();
// If num_neighbors was greater or equal num_non_start_end_nodes - 1,
// gci_params_.neighbors_ratio should have been set to 1.
DCHECK_LT(num_neighbors, NumNonStartEndNodes() - 1);
const RoutingModel& routing_model = *model();
const int64_t size = routing_model.Size();
node_index_to_neighbors_by_cost_class_.resize(size);
const int num_cost_classes = routing_model.GetCostClassesCount();
for (int64_t node_index = 0; node_index < size; node_index++) {
node_index_to_neighbors_by_cost_class_[node_index].resize(num_cost_classes);
for (int cc = 0; cc < num_cost_classes; cc++) {
node_index_to_neighbors_by_cost_class_[node_index][cc] =
absl::make_unique<SparseBitset<int64_t>>(size);
}
}
for (int64_t node_index = 0; node_index < size; ++node_index) {
DCHECK(!routing_model.IsEnd(node_index));
if (routing_model.IsStart(node_index)) {
// We don't compute neighbors for vehicle starts: all nodes are considered
// neighbors for a vehicle start.
continue;
}
// TODO(user): Use the model's IndexNeighborFinder when available.
for (int cost_class = 0; cost_class < num_cost_classes; cost_class++) {
if (!routing_model.HasVehicleWithCostClassIndex(
RoutingCostClassIndex(cost_class))) {
// No vehicle with this cost class, avoid unnecessary computations.
continue;
}
std::vector<std::pair</*cost*/ int64_t, /*node*/ int64_t>>
costed_after_nodes;
costed_after_nodes.reserve(size);
for (int after_node = 0; after_node < size; ++after_node) {
if (after_node != node_index && !routing_model.IsStart(after_node)) {
costed_after_nodes.push_back(
std::make_pair(routing_model.GetArcCostForClass(
node_index, after_node, cost_class),
after_node));
}
}
std::nth_element(costed_after_nodes.begin(),
costed_after_nodes.begin() + num_neighbors - 1,
costed_after_nodes.end());
costed_after_nodes.resize(num_neighbors);
for (auto [cost, neighbor] : costed_after_nodes) {
node_index_to_neighbors_by_cost_class_[node_index][cost_class]->Set(
neighbor);
// Add reverse neighborhood.
DCHECK(!routing_model.IsEnd(neighbor) &&
!routing_model.IsStart(neighbor));
node_index_to_neighbors_by_cost_class_[neighbor][cost_class]->Set(
node_index);
}
// Add all vehicle starts as neighbors to this node and vice-versa.
for (int vehicle = 0; vehicle < routing_model.vehicles(); vehicle++) {
const int64_t vehicle_start = routing_model.Start(vehicle);
node_index_to_neighbors_by_cost_class_[node_index][cost_class]->Set(
vehicle_start);
node_index_to_neighbors_by_cost_class_[vehicle_start][cost_class]->Set(
node_index);
}
}
}
}
bool GlobalCheapestInsertionFilteredHeuristic::IsNeighborForCostClass(
int cost_class, int64_t node_index, int64_t neighbor_index) const {
return gci_params_.neighbors_ratio == 1 ||
(*node_index_to_neighbors_by_cost_class_[node_index]
[cost_class])[neighbor_index];
}
bool GlobalCheapestInsertionFilteredHeuristic::CheckVehicleIndices() const {
std::vector<bool> node_is_visited(model()->Size(), -1);
for (int v = 0; v < model()->vehicles(); v++) {
for (int node = model()->Start(v); !model()->IsEnd(node);
node = Value(node)) {
if (node_index_to_vehicle_[node] != v) {
return false;
}
node_is_visited[node] = true;
}
}
for (int node = 0; node < model()->Size(); node++) {
if (!node_is_visited[node] && node_index_to_vehicle_[node] != -1) {
return false;
}
}
return true;
}
bool GlobalCheapestInsertionFilteredHeuristic::BuildSolutionInternal() {
ComputeNeighborhoods();
if (empty_vehicle_type_curator_ == nullptr) {
empty_vehicle_type_curator_ = absl::make_unique<VehicleTypeCurator>(
model()->GetVehicleTypeContainer());
}
// Store all empty vehicles in the empty_vehicle_type_curator_.
empty_vehicle_type_curator_->Reset(
[this](int vehicle) { return VehicleIsEmpty(vehicle); });
// Insert partially inserted pairs.
const RoutingModel::IndexPairs& pickup_delivery_pairs =
model()->GetPickupAndDeliveryPairs();
std::map<int64_t, std::vector<int>> pairs_to_insert_by_bucket;
absl::flat_hash_map<int, std::map<int64_t, std::vector<int>>>
vehicle_to_pair_nodes;
for (int index = 0; index < pickup_delivery_pairs.size(); index++) {
const RoutingModel::IndexPair& index_pair = pickup_delivery_pairs[index];
int pickup_vehicle = -1;
for (int64_t pickup : index_pair.first) {
if (Contains(pickup)) {
pickup_vehicle = node_index_to_vehicle_[pickup];
break;
}
}
int delivery_vehicle = -1;
for (int64_t delivery : index_pair.second) {
if (Contains(delivery)) {
delivery_vehicle = node_index_to_vehicle_[delivery];
break;
}
}
if (pickup_vehicle < 0 && delivery_vehicle < 0) {
pairs_to_insert_by_bucket[GetBucketOfPair(index_pair)].push_back(index);
}
if (pickup_vehicle >= 0 && delivery_vehicle < 0) {
std::vector<int>& pair_nodes = vehicle_to_pair_nodes[pickup_vehicle][1];
for (int64_t delivery : index_pair.second) {
pair_nodes.push_back(delivery);
}
}
if (pickup_vehicle < 0 && delivery_vehicle >= 0) {
std::vector<int>& pair_nodes = vehicle_to_pair_nodes[delivery_vehicle][1];
for (int64_t pickup : index_pair.first) {
pair_nodes.push_back(pickup);
}
}
}
for (const auto& [vehicle, nodes] : vehicle_to_pair_nodes) {
if (!InsertNodesOnRoutes(nodes, {vehicle})) return false;
}
if (!InsertPairsAndNodesByRequirementTopologicalOrder()) return false;
// TODO(user): Adapt the pair insertions to also support seed and
// sequential insertion.
if (!InsertPairs(pairs_to_insert_by_bucket)) return false;
std::map<int64_t, std::vector<int>> nodes_by_bucket;
for (int node = 0; node < model()->Size(); ++node) {
if (!Contains(node) && model()->GetPickupIndexPairs(node).empty() &&
model()->GetDeliveryIndexPairs(node).empty()) {
nodes_by_bucket[GetBucketOfNode(node)].push_back(node);
}
}
InsertFarthestNodesAsSeeds();
if (gci_params_.is_sequential) {
if (!SequentialInsertNodes(nodes_by_bucket)) return false;
} else if (!InsertNodesOnRoutes(nodes_by_bucket, {})) {
return false;
}
MakeUnassignedNodesUnperformed();
DCHECK(CheckVehicleIndices());
return Commit();
}
bool GlobalCheapestInsertionFilteredHeuristic::
InsertPairsAndNodesByRequirementTopologicalOrder() {
const RoutingModel::IndexPairs& pickup_delivery_pairs =
model()->GetPickupAndDeliveryPairs();
for (const std::vector<int>& types :
model()->GetTopologicallySortedVisitTypes()) {
for (int type : types) {
std::map<int64_t, std::vector<int>> pairs_to_insert_by_bucket;
for (int index : model()->GetPairIndicesOfType(type)) {
pairs_to_insert_by_bucket[GetBucketOfPair(pickup_delivery_pairs[index])]
.push_back(index);
}
if (!InsertPairs(pairs_to_insert_by_bucket)) return false;
std::map<int64_t, std::vector<int>> nodes_by_bucket;
for (int node : model()->GetSingleNodesOfType(type)) {
nodes_by_bucket[GetBucketOfNode(node)].push_back(node);
}
if (!InsertNodesOnRoutes(nodes_by_bucket, {})) return false;
}
}
return true;
}
bool GlobalCheapestInsertionFilteredHeuristic::InsertPairs(
const std::map<int64_t, std::vector<int>>& pair_indices_by_bucket) {
AdjustablePriorityQueue<PairEntry> priority_queue;
std::vector<PairEntries> pickup_to_entries;
std::vector<PairEntries> delivery_to_entries;
std::vector<int> pair_indices_to_insert;
for (const auto& [bucket, pair_indices] : pair_indices_by_bucket) {
pair_indices_to_insert.insert(pair_indices_to_insert.end(),
pair_indices.begin(), pair_indices.end());
if (!InitializePairPositions(pair_indices_to_insert, &priority_queue,
&pickup_to_entries, &delivery_to_entries)) {
return false;
}
while (!priority_queue.IsEmpty()) {
if (StopSearchAndCleanup(&priority_queue)) {
return false;
}
PairEntry* const entry = priority_queue.Top();
const int64_t pickup = entry->pickup_to_insert();
const int64_t delivery = entry->delivery_to_insert();
if (Contains(pickup) || Contains(delivery)) {
DeletePairEntry(entry, &priority_queue, &pickup_to_entries,
&delivery_to_entries);
continue;
}
const int entry_vehicle = entry->vehicle();
if (entry_vehicle == -1) {
// Pair is unperformed.
SetValue(pickup, pickup);
SetValue(delivery, delivery);
if (!Commit()) {
DeletePairEntry(entry, &priority_queue, &pickup_to_entries,
&delivery_to_entries);
}
continue;
}
// Pair is performed.
if (UseEmptyVehicleTypeCuratorForVehicle(entry_vehicle)) {
if (!InsertPairEntryUsingEmptyVehicleTypeCurator(
pair_indices_to_insert, entry, &priority_queue,
&pickup_to_entries, &delivery_to_entries)) {
return false;
}