forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouting_search.cc
5589 lines (5182 loc) · 216 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-2018 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 <cstdlib>
#include <map>
#include <numeric>
#include <set>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "ortools/base/map_util.h"
#include "ortools/base/small_map.h"
#include "ortools/base/small_ordered_set.h"
#include "ortools/base/stl_util.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_lp_scheduling.h"
#include "ortools/graph/christofides.h"
#include "ortools/util/bitset.h"
#include "ortools/util/saturated_arithmetic.h"
DEFINE_bool(routing_strong_debug_checks, false,
"Run stronger checks in debug; these stronger tests might change "
"the complexity of the code in particular.");
DEFINE_bool(routing_shift_insertion_cost_by_penalty, true,
"Shift insertion costs by the penalty of the inserted node(s).");
namespace operations_research {
namespace {
// Node disjunction filter class.
class NodeDisjunctionFilter : public IntVarLocalSearchFilter {
public:
NodeDisjunctionFilter(const RoutingModel& routing_model,
Solver::ObjectiveWatcher objective_callback)
: IntVarLocalSearchFilter(routing_model.Nexts(),
std::move(objective_callback)),
routing_model_(routing_model),
active_per_disjunction_(routing_model.GetNumberOfDisjunctions(), 0),
inactive_per_disjunction_(routing_model.GetNumberOfDisjunctions(), 0),
synchronized_objective_value_(kint64min),
accepted_objective_value_(kint64min) {}
bool Accept(Assignment* delta, Assignment* deltadelta) override {
const int64 kUnassigned = -1;
const Assignment::IntContainer& container = delta->IntVarContainer();
const int delta_size = container.Size();
gtl::small_map<std::map<RoutingModel::DisjunctionIndex, int>>
disjunction_active_deltas;
gtl::small_map<std::map<RoutingModel::DisjunctionIndex, int>>
disjunction_inactive_deltas;
bool lns_detected = false;
// Update active/inactive count per disjunction for each element of delta.
for (int i = 0; i < delta_size; ++i) {
const IntVarElement& new_element = container.Element(i);
IntVar* const var = new_element.Var();
int64 index = kUnassigned;
if (FindIndex(var, &index)) {
const bool is_inactive =
(new_element.Min() <= index && new_element.Max() >= index);
if (new_element.Min() != new_element.Max()) {
lns_detected = true;
}
for (const RoutingModel::DisjunctionIndex disjunction_index :
routing_model_.GetDisjunctionIndices(index)) {
const bool active_state_changed =
!IsVarSynced(index) || (Value(index) == index) != is_inactive;
if (active_state_changed) {
if (!is_inactive) {
++gtl::LookupOrInsert(&disjunction_active_deltas,
disjunction_index, 0);
if (IsVarSynced(index)) {
--gtl::LookupOrInsert(&disjunction_inactive_deltas,
disjunction_index, 0);
}
} else {
++gtl::LookupOrInsert(&disjunction_inactive_deltas,
disjunction_index, 0);
if (IsVarSynced(index)) {
--gtl::LookupOrInsert(&disjunction_active_deltas,
disjunction_index, 0);
}
}
}
}
}
}
// Check if any disjunction has too many active nodes.
for (const std::pair<RoutingModel::DisjunctionIndex, int>
disjunction_active_delta : disjunction_active_deltas) {
const int current_active_nodes =
active_per_disjunction_[disjunction_active_delta.first];
const int active_nodes =
current_active_nodes + disjunction_active_delta.second;
const int max_cardinality = routing_model_.GetDisjunctionMaxCardinality(
disjunction_active_delta.first);
// Too many active nodes.
if (active_nodes > max_cardinality) {
PropagateObjectiveValue(0);
return false;
}
}
// Update penalty costs for disjunctions.
accepted_objective_value_ = synchronized_objective_value_;
for (const std::pair<RoutingModel::DisjunctionIndex, int>
disjunction_inactive_delta : disjunction_inactive_deltas) {
const int64 penalty = routing_model_.GetDisjunctionPenalty(
disjunction_inactive_delta.first);
if (penalty != 0 && !lns_detected) {
const RoutingModel::DisjunctionIndex disjunction_index =
disjunction_inactive_delta.first;
const int current_inactive_nodes =
inactive_per_disjunction_[disjunction_index];
const int inactive_nodes =
current_inactive_nodes + disjunction_inactive_delta.second;
const int max_inactive_cardinality =
routing_model_.GetDisjunctionIndices(disjunction_index).size() -
routing_model_.GetDisjunctionMaxCardinality(disjunction_index);
// Too many inactive nodes.
if (inactive_nodes > max_inactive_cardinality) {
if (penalty < 0) {
// Nodes are mandatory, i.e. exactly max_cardinality nodes must be
// performed, so the move is not acceptable.
PropagateObjectiveValue(0);
return false;
} else if (current_inactive_nodes <= max_inactive_cardinality) {
// Add penalty if there were not too many inactive nodes before the
// move.
accepted_objective_value_ =
CapAdd(accepted_objective_value_, penalty);
}
} else if (current_inactive_nodes > max_inactive_cardinality) {
// Remove penalty if there were too many inactive nodes before the
// move and there are not too many after the move.
accepted_objective_value_ =
CapSub(accepted_objective_value_, penalty);
}
}
}
if (lns_detected) accepted_objective_value_ = 0;
const int64 new_objective_value =
CapAdd(accepted_objective_value_, injected_objective_value_);
PropagateObjectiveValue(new_objective_value);
if (lns_detected) {
return true;
} else {
IntVar* const cost_var = routing_model_.CostVar();
// Only compare to max as a cost lower bound is computed.
// TODO(user): Factor out the access to the objective upper bound.
int64 cost_max = cost_var->Max();
if (delta->Objective() == cost_var) {
cost_max = std::min(cost_max, delta->ObjectiveMax());
}
if (!delta->HasObjective()) {
delta->AddObjective(cost_var);
}
delta->SetObjectiveMin(new_objective_value);
return new_objective_value <= cost_max;
}
}
std::string DebugString() const override { return "NodeDisjunctionFilter"; }
int64 GetSynchronizedObjectiveValue() const override {
return synchronized_objective_value_;
}
int64 GetAcceptedObjectiveValue() const override {
return accepted_objective_value_;
}
private:
void OnSynchronize(const Assignment* delta) override {
synchronized_objective_value_ = 0;
for (RoutingModel::DisjunctionIndex i(0);
i < active_per_disjunction_.size(); ++i) {
active_per_disjunction_[i] = 0;
inactive_per_disjunction_[i] = 0;
const std::vector<int64>& disjunction_indices =
routing_model_.GetDisjunctionIndices(i);
for (const int64 index : disjunction_indices) {
const bool index_synced = IsVarSynced(index);
if (index_synced) {
if (Value(index) != index) {
++active_per_disjunction_[i];
} else {
++inactive_per_disjunction_[i];
}
}
}
const int64 penalty = routing_model_.GetDisjunctionPenalty(i);
const int max_cardinality =
routing_model_.GetDisjunctionMaxCardinality(i);
if (inactive_per_disjunction_[i] >
disjunction_indices.size() - max_cardinality &&
penalty > 0) {
synchronized_objective_value_ =
CapAdd(synchronized_objective_value_, penalty);
}
}
PropagateObjectiveValue(
CapAdd(injected_objective_value_, synchronized_objective_value_));
}
const RoutingModel& routing_model_;
gtl::ITIVector<RoutingModel::DisjunctionIndex, int> active_per_disjunction_;
gtl::ITIVector<RoutingModel::DisjunctionIndex, int> inactive_per_disjunction_;
int64 synchronized_objective_value_;
int64 accepted_objective_value_;
};
} // namespace
IntVarLocalSearchFilter* MakeNodeDisjunctionFilter(
const RoutingModel& routing_model,
Solver::ObjectiveWatcher objective_callback) {
return routing_model.solver()->RevAlloc(
new NodeDisjunctionFilter(routing_model, std::move(objective_callback)));
}
LocalSearchFilterManager::LocalSearchFilterManager(
Solver* const solver, const std::vector<LocalSearchFilter*>& filters,
IntVar* objective)
: solver_(solver),
filters_(filters),
objective_(objective),
is_incremental_(false),
synchronized_value_(kint64min),
accepted_value_(kint64min) {
for (LocalSearchFilter* filter : filters_) {
is_incremental_ |= filter->IsIncremental();
}
// TODO(user): static reordering should take place here.
}
// TODO(user): the behaviour of Accept relies on the initial order of
// filters having at most one filter with negative objective values,
// this could be fixed by having filters return their general bounds.
bool LocalSearchFilterManager::Accept(Assignment* delta,
Assignment* deltadelta) {
int64 objective_max = kint64max;
if (objective_ != nullptr) {
objective_max = objective_->Max();
if (delta->Objective() == objective_) {
objective_max = std::min(objective_max, delta->ObjectiveMax());
}
}
accepted_value_ = 0;
bool ok = true;
LocalSearchMonitor* const monitor =
(solver_ == nullptr) ? nullptr : solver_->GetLocalSearchMonitor();
for (LocalSearchFilter* filter : filters_) {
if (!ok && !filter->IsIncremental()) continue;
if (monitor != nullptr) monitor->BeginFiltering(filter);
const bool accept = filter->Accept(delta, deltadelta);
ok &= accept;
if (monitor != nullptr) monitor->EndFiltering(filter, !accept);
if (ok) {
accepted_value_ =
CapAdd(accepted_value_, filter->GetAcceptedObjectiveValue());
ok = accepted_value_ <= objective_max;
}
}
return ok;
}
void LocalSearchFilterManager::Synchronize(const Assignment* assignment,
const Assignment* delta) {
synchronized_value_ = 0;
for (LocalSearchFilter* filter : filters_) {
filter->Synchronize(assignment, delta);
synchronized_value_ =
CapAdd(synchronized_value_, filter->GetSynchronizedObjectiveValue());
}
}
const int64 BasePathFilter::kUnassigned = -1;
BasePathFilter::BasePathFilter(const std::vector<IntVar*>& nexts,
int next_domain_size,
Solver::ObjectiveWatcher objective_callback)
: IntVarLocalSearchFilter(nexts, std::move(objective_callback)),
node_path_starts_(next_domain_size, kUnassigned),
paths_(nexts.size(), -1),
new_synchronized_unperformed_nodes_(nexts.size()),
new_nexts_(nexts.size(), kUnassigned),
touched_paths_(nexts.size()),
touched_path_nodes_(next_domain_size),
ranks_(next_domain_size, -1),
status_(BasePathFilter::UNKNOWN) {}
bool BasePathFilter::Accept(Assignment* delta, Assignment* deltadelta) {
if (IsDisabled()) return true;
PropagateObjectiveValue(injected_objective_value_);
for (const int touched : delta_touched_) {
new_nexts_[touched] = kUnassigned;
}
delta_touched_.clear();
const Assignment::IntContainer& container = delta->IntVarContainer();
const int delta_size = container.Size();
delta_touched_.reserve(delta_size);
// Determining touched paths and touched nodes (a node is touched if it
// corresponds to an element of delta or that an element of delta points to
// it.
touched_paths_.SparseClearAll();
touched_path_nodes_.SparseClearAll();
for (int i = 0; i < delta_size; ++i) {
const IntVarElement& new_element = container.Element(i);
IntVar* const var = new_element.Var();
int64 index = kUnassigned;
if (FindIndex(var, &index)) {
if (!new_element.Bound()) {
// LNS detected
return true;
}
new_nexts_[index] = new_element.Value();
delta_touched_.push_back(index);
const int64 start = node_path_starts_[index];
touched_path_nodes_.Set(index);
touched_path_nodes_.Set(new_nexts_[index]);
if (start != kUnassigned) {
touched_paths_.Set(start);
}
}
}
// Checking feasibility of touched paths.
InitializeAcceptPath();
bool accept = true;
// Finding touched subchains from ranks of touched nodes in paths; the first
// and last node of a subchain will have remained on the same path and will
// correspond to the min and max ranks of touched nodes in the current
// assignment.
for (const int64 touched_start : touched_paths_.PositionsSetAtLeastOnce()) {
int min_rank = kint32max;
int64 start = kUnassigned;
int max_rank = kint32min;
int64 end = kUnassigned;
// Linear search on touched nodes is ok since there shouldn't be many of
// them.
// TODO(user): Remove the linear loop.
for (const int64 touched_path_node :
touched_path_nodes_.PositionsSetAtLeastOnce()) {
if (node_path_starts_[touched_path_node] == touched_start) {
const int rank = ranks_[touched_path_node];
if (rank < min_rank) {
min_rank = rank;
start = touched_path_node;
}
if (rank > max_rank) {
max_rank = rank;
end = touched_path_node;
}
}
}
if (!AcceptPath(touched_start, start, end)) {
accept = false;
break;
}
}
// Order is important: FinalizeAcceptPath() must always be called.
return FinalizeAcceptPath(delta) && accept;
}
void BasePathFilter::ComputePathStarts(std::vector<int64>* path_starts,
std::vector<int>* index_to_path) {
path_starts->clear();
const int nexts_size = Size();
index_to_path->assign(nexts_size, kUnassigned);
Bitset64<> has_prevs(nexts_size);
for (int i = 0; i < nexts_size; ++i) {
if (!IsVarSynced(i)) {
has_prevs.Set(i);
} else {
const int next = Value(i);
if (next < nexts_size) {
has_prevs.Set(next);
}
}
}
for (int i = 0; i < nexts_size; ++i) {
if (!has_prevs[i]) {
(*index_to_path)[i] = path_starts->size();
path_starts->push_back(i);
}
}
}
bool BasePathFilter::HavePathsChanged() {
std::vector<int64> path_starts;
std::vector<int> index_to_path(Size(), kUnassigned);
ComputePathStarts(&path_starts, &index_to_path);
if (path_starts.size() != starts_.size()) {
return true;
}
for (int i = 0; i < path_starts.size(); ++i) {
if (path_starts[i] != starts_[i]) {
return true;
}
}
for (int i = 0; i < Size(); ++i) {
if (index_to_path[i] != paths_[i]) {
return true;
}
}
return false;
}
void BasePathFilter::SynchronizeFullAssignment() {
// Subclasses of BasePathFilter might not propagate injected objective values
// so making sure it is done here (can be done again by the subclass if
// needed).
PropagateObjectiveValue(injected_objective_value_);
ComputePathStarts(&starts_, &paths_);
for (int64 index = 0; index < Size(); index++) {
if (IsVarSynced(index) && Value(index) == index &&
node_path_starts_[index] != kUnassigned) {
// index was performed before and is now unperformed.
new_synchronized_unperformed_nodes_.Set(index);
}
}
// Marking unactive nodes (which are not on a path).
node_path_starts_.assign(node_path_starts_.size(), kUnassigned);
// Marking nodes on a path and storing next values.
const int nexts_size = Size();
for (const int64 start : starts_) {
int node = start;
node_path_starts_[node] = start;
DCHECK(IsVarSynced(node));
int next = Value(node);
while (next < nexts_size) {
node = next;
node_path_starts_[node] = start;
DCHECK(IsVarSynced(node));
next = Value(node);
}
node_path_starts_[next] = start;
}
OnBeforeSynchronizePaths();
UpdateAllRanks();
OnAfterSynchronizePaths();
}
void BasePathFilter::OnSynchronize(const Assignment* delta) {
if (status_ == BasePathFilter::UNKNOWN) {
status_ =
DisableFiltering() ? BasePathFilter::DISABLED : BasePathFilter::ENABLED;
}
if (IsDisabled()) return;
new_synchronized_unperformed_nodes_.ClearAll();
if (delta == nullptr || delta->Empty() || starts_.empty()) {
SynchronizeFullAssignment();
return;
}
// Subclasses of BasePathFilter might not propagate injected objective values
// so making sure it is done here (can be done again by the subclass if
// needed).
PropagateObjectiveValue(injected_objective_value_);
// This code supposes that path starts didn't change.
DCHECK(!FLAGS_routing_strong_debug_checks || !HavePathsChanged());
const Assignment::IntContainer& container = delta->IntVarContainer();
touched_paths_.SparseClearAll();
for (int i = 0; i < container.Size(); ++i) {
const IntVarElement& new_element = container.Element(i);
int64 index = kUnassigned;
if (FindIndex(new_element.Var(), &index)) {
const int64 start = node_path_starts_[index];
if (start != kUnassigned) {
touched_paths_.Set(start);
if (Value(index) == index) {
// New unperformed node (its previous start isn't unassigned).
DCHECK_LT(index, new_nexts_.size());
new_synchronized_unperformed_nodes_.Set(index);
node_path_starts_[index] = kUnassigned;
}
}
}
}
OnBeforeSynchronizePaths();
for (const int64 touched_start : touched_paths_.PositionsSetAtLeastOnce()) {
int64 node = touched_start;
while (node < Size()) {
node_path_starts_[node] = touched_start;
node = Value(node);
}
node_path_starts_[node] = touched_start;
UpdatePathRanksFromStart(touched_start);
OnSynchronizePathFromStart(touched_start);
}
OnAfterSynchronizePaths();
}
void BasePathFilter::UpdateAllRanks() {
for (int i = 0; i < ranks_.size(); ++i) {
ranks_[i] = kUnassigned;
}
for (int r = 0; r < NumPaths(); ++r) {
UpdatePathRanksFromStart(Start(r));
OnSynchronizePathFromStart(Start(r));
}
}
void BasePathFilter::UpdatePathRanksFromStart(int start) {
int rank = 0;
int64 node = start;
while (node < Size()) {
ranks_[node] = rank;
rank++;
node = Value(node);
}
ranks_[node] = rank;
}
namespace {
class VehicleAmortizedCostFilter : public BasePathFilter {
public:
VehicleAmortizedCostFilter(const RoutingModel& routing_model,
Solver::ObjectiveWatcher objective_callback);
~VehicleAmortizedCostFilter() override {}
std::string DebugString() const override {
return "VehicleAmortizedCostFilter";
}
int64 GetSynchronizedObjectiveValue() const override {
return current_vehicle_cost_;
}
int64 GetAcceptedObjectiveValue() const override {
return delta_vehicle_cost_;
}
private:
void OnSynchronizePathFromStart(int64 start) override;
void OnAfterSynchronizePaths() override;
void InitializeAcceptPath() override;
bool AcceptPath(int64 path_start, int64 chain_start,
int64 chain_end) override;
bool FinalizeAcceptPath(Assignment* delta) override;
IntVar* const objective_;
int64 current_vehicle_cost_;
int64 delta_vehicle_cost_;
std::vector<int> current_route_lengths_;
std::vector<int64> start_to_end_;
std::vector<int> start_to_vehicle_;
std::vector<int64> vehicle_to_start_;
const std::vector<int64>& linear_cost_factor_of_vehicle_;
const std::vector<int64>& quadratic_cost_factor_of_vehicle_;
};
VehicleAmortizedCostFilter::VehicleAmortizedCostFilter(
const RoutingModel& routing_model,
Solver::ObjectiveWatcher objective_callback)
: BasePathFilter(routing_model.Nexts(),
routing_model.Size() + routing_model.vehicles(),
std::move(objective_callback)),
objective_(routing_model.CostVar()),
current_vehicle_cost_(0),
delta_vehicle_cost_(0),
current_route_lengths_(Size(), -1),
linear_cost_factor_of_vehicle_(
routing_model.GetAmortizedLinearCostFactorOfVehicles()),
quadratic_cost_factor_of_vehicle_(
routing_model.GetAmortizedQuadraticCostFactorOfVehicles()) {
start_to_end_.resize(Size(), -1);
start_to_vehicle_.resize(Size(), -1);
vehicle_to_start_.resize(routing_model.vehicles());
for (int v = 0; v < routing_model.vehicles(); v++) {
const int64 start = routing_model.Start(v);
start_to_vehicle_[start] = v;
start_to_end_[start] = routing_model.End(v);
vehicle_to_start_[v] = start;
}
}
void VehicleAmortizedCostFilter::OnSynchronizePathFromStart(int64 start) {
const int64 end = start_to_end_[start];
CHECK_GE(end, 0);
const int route_length = Rank(end) - 1;
CHECK_GE(route_length, 0);
current_route_lengths_[start] = route_length;
}
void VehicleAmortizedCostFilter::OnAfterSynchronizePaths() {
current_vehicle_cost_ = 0;
for (int vehicle = 0; vehicle < vehicle_to_start_.size(); vehicle++) {
const int64 start = vehicle_to_start_[vehicle];
DCHECK_EQ(vehicle, start_to_vehicle_[start]);
const int route_length = current_route_lengths_[start];
DCHECK_GE(route_length, 0);
if (route_length == 0) {
// The path is empty.
continue;
}
const int64 linear_cost_factor = linear_cost_factor_of_vehicle_[vehicle];
const int64 route_length_cost =
CapProd(quadratic_cost_factor_of_vehicle_[vehicle],
route_length * route_length);
current_vehicle_cost_ = CapAdd(
current_vehicle_cost_, CapSub(linear_cost_factor, route_length_cost));
}
PropagateObjectiveValue(
CapAdd(current_vehicle_cost_, injected_objective_value_));
}
void VehicleAmortizedCostFilter::InitializeAcceptPath() {
delta_vehicle_cost_ = current_vehicle_cost_;
}
bool VehicleAmortizedCostFilter::AcceptPath(int64 path_start, int64 chain_start,
int64 chain_end) {
// Number of nodes previously between chain_start and chain_end
const int previous_chain_nodes = Rank(chain_end) - 1 - Rank(chain_start);
CHECK_GE(previous_chain_nodes, 0);
int new_chain_nodes = 0;
int64 node = GetNext(chain_start);
while (node != chain_end) {
new_chain_nodes++;
node = GetNext(node);
}
const int previous_route_length = current_route_lengths_[path_start];
CHECK_GE(previous_route_length, 0);
const int new_route_length =
previous_route_length - previous_chain_nodes + new_chain_nodes;
const int vehicle = start_to_vehicle_[path_start];
CHECK_GE(vehicle, 0);
DCHECK_EQ(path_start, vehicle_to_start_[vehicle]);
// Update the cost related to used vehicles.
// TODO(user): Handle possible overflows.
if (previous_route_length == 0) {
// The route was empty before, it is no longer the case (changed path).
CHECK_GT(new_route_length, 0);
delta_vehicle_cost_ =
CapAdd(delta_vehicle_cost_, linear_cost_factor_of_vehicle_[vehicle]);
} else if (new_route_length == 0) {
// The route is now empty.
delta_vehicle_cost_ =
CapSub(delta_vehicle_cost_, linear_cost_factor_of_vehicle_[vehicle]);
}
// Update the cost related to the sum of the squares of the route lengths.
const int64 quadratic_cost_factor =
quadratic_cost_factor_of_vehicle_[vehicle];
delta_vehicle_cost_ =
CapAdd(delta_vehicle_cost_,
CapProd(quadratic_cost_factor,
previous_route_length * previous_route_length));
delta_vehicle_cost_ = CapSub(
delta_vehicle_cost_,
CapProd(quadratic_cost_factor, new_route_length * new_route_length));
return true;
}
bool VehicleAmortizedCostFilter::FinalizeAcceptPath(Assignment* delta) {
int64 objective_max = objective_->Max();
if (delta->Objective() == objective_) {
objective_max = std::min(objective_max, delta->ObjectiveMax());
}
const int64 new_objective_value =
CapAdd(injected_objective_value_, delta_vehicle_cost_);
if (!delta->HasObjective()) {
delta->AddObjective(objective_);
}
delta->SetObjectiveMin(new_objective_value);
PropagateObjectiveValue(new_objective_value);
return new_objective_value <= objective_max;
}
} // namespace
IntVarLocalSearchFilter* MakeVehicleAmortizedCostFilter(
const RoutingModel& routing_model,
Solver::ObjectiveWatcher objective_callback) {
return routing_model.solver()->RevAlloc(new VehicleAmortizedCostFilter(
routing_model, std::move(objective_callback)));
}
namespace {
class TypeRegulationsFilter : public BasePathFilter {
public:
explicit TypeRegulationsFilter(const RoutingModel& model);
~TypeRegulationsFilter() override {}
std::string DebugString() const override { return "TypeRegulationsFilter"; }
private:
void OnSynchronizePathFromStart(int64 start) override;
bool AcceptPath(int64 path_start, int64 chain_start,
int64 chain_end) override;
bool HardIncompatibilitiesRespected(int vehicle, int64 chain_start,
int64 chain_end);
const RoutingModel& routing_model_;
std::vector<int> start_to_vehicle_;
// The following vector is used to keep track of the type counts for hard
// incompatibilities.
std::vector<std::vector<int>> hard_incompatibility_type_counts_per_vehicle_;
// Used to verify the temporal incompatibilities.
TypeIncompatibilityChecker temporal_incompatibility_checker_;
TypeRequirementChecker requirement_checker_;
};
TypeRegulationsFilter::TypeRegulationsFilter(const RoutingModel& model)
: BasePathFilter(model.Nexts(), model.Size() + model.vehicles(), nullptr),
routing_model_(model),
start_to_vehicle_(model.Size(), -1),
temporal_incompatibility_checker_(model,
/*check_hard_incompatibilities*/ false),
requirement_checker_(model) {
const int num_vehicles = model.vehicles();
const bool has_hard_type_incompatibilities =
model.HasHardTypeIncompatibilities();
if (has_hard_type_incompatibilities) {
hard_incompatibility_type_counts_per_vehicle_.resize(num_vehicles);
}
const int num_visit_types = model.GetNumberOfVisitTypes();
for (int vehicle = 0; vehicle < num_vehicles; vehicle++) {
const int64 start = model.Start(vehicle);
start_to_vehicle_[start] = vehicle;
if (has_hard_type_incompatibilities) {
hard_incompatibility_type_counts_per_vehicle_[vehicle].resize(
num_visit_types, 0);
}
}
}
void TypeRegulationsFilter::OnSynchronizePathFromStart(int64 start) {
if (!routing_model_.HasHardTypeIncompatibilities()) return;
const int vehicle = start_to_vehicle_[start];
CHECK_GE(vehicle, 0);
std::vector<int>& type_counts =
hard_incompatibility_type_counts_per_vehicle_[vehicle];
std::fill(type_counts.begin(), type_counts.end(), 0);
const int num_types = type_counts.size();
int64 node = start;
while (node < Size()) {
DCHECK(IsVarSynced(node));
const int type = routing_model_.GetVisitType(node);
if (type >= 0) {
CHECK_LT(type, num_types);
type_counts[type]++;
}
node = Value(node);
}
}
bool TypeRegulationsFilter::HardIncompatibilitiesRespected(int vehicle,
int64 chain_start,
int64 chain_end) {
if (!routing_model_.HasHardTypeIncompatibilities()) return true;
std::vector<int> new_type_counts =
hard_incompatibility_type_counts_per_vehicle_[vehicle];
const int num_types = new_type_counts.size();
std::vector<int> types_to_check;
// Go through the new nodes on the path and increment their type counts.
int64 node = GetNext(chain_start);
while (node != chain_end) {
const int type = routing_model_.GetVisitType(node);
if (type >= 0) {
CHECK_LT(type, num_types);
const int previous_count = new_type_counts[type]++;
if (previous_count == 0) {
// New type on the route, mark to check its incompatibilities.
types_to_check.push_back(type);
}
}
node = GetNext(node);
}
// Update new_type_counts by decrementing the occurrence of the types of the
// nodes no longer on the route.
node = Value(chain_start);
while (node != chain_end) {
const int type = routing_model_.GetVisitType(node);
if (type >= 0) {
CHECK_LT(type, num_types);
int& type_count = new_type_counts[type];
CHECK_GE(type_count, 1);
type_count--;
}
node = Value(node);
}
// Check the incompatibilities for types in types_to_check.
for (int type : types_to_check) {
for (int incompatible_type :
routing_model_.GetHardTypeIncompatibilitiesOfType(type)) {
if (new_type_counts[incompatible_type] > 0) {
return false;
}
}
}
return true;
}
bool TypeRegulationsFilter::AcceptPath(int64 path_start, int64 chain_start,
int64 chain_end) {
const int vehicle = start_to_vehicle_[path_start];
CHECK_GE(vehicle, 0);
const auto next_accessor = [this](int64 node) { return GetNext(node); };
return HardIncompatibilitiesRespected(vehicle, chain_start, chain_end) &&
temporal_incompatibility_checker_.CheckVehicle(vehicle,
next_accessor) &&
requirement_checker_.CheckVehicle(vehicle, next_accessor);
}
} // namespace
IntVarLocalSearchFilter* MakeTypeRegulationsFilter(
const RoutingModel& routing_model) {
return routing_model.solver()->RevAlloc(
new TypeRegulationsFilter(routing_model));
}
namespace {
int64 GetNextValueFromForbiddenIntervals(
int64 value, const SortedDisjointIntervalList& forbidden_intervals) {
int64 next_value = value;
const auto first_interval_it =
forbidden_intervals.FirstIntervalGreaterOrEqual(next_value);
if (first_interval_it != forbidden_intervals.end() &&
next_value >= first_interval_it->start) {
next_value = CapAdd(first_interval_it->end, 1);
}
return next_value;
}
// ChainCumul filter. Version of dimension path filter which is O(delta) rather
// than O(length of touched paths). Currently only supports dimensions without
// costs (global and local span cost, soft bounds) and with unconstrained
// cumul variables except overall capacity and cumul variables of path ends.
class ChainCumulFilter : public BasePathFilter {
public:
ChainCumulFilter(const RoutingModel& routing_model,
const RoutingDimension& dimension,
Solver::ObjectiveWatcher objective_callback);
~ChainCumulFilter() override {}
std::string DebugString() const override {
return "ChainCumulFilter(" + name_ + ")";
}
private:
void OnSynchronizePathFromStart(int64 start) override;
bool AcceptPath(int64 path_start, int64 chain_start,
int64 chain_end) override;
const std::vector<IntVar*> cumuls_;
std::vector<int64> start_to_vehicle_;
std::vector<int64> start_to_end_;
std::vector<const RoutingModel::TransitCallback2*> evaluators_;
const std::vector<int64> vehicle_capacities_;
std::vector<int64> current_path_cumul_mins_;
std::vector<int64> current_max_of_path_end_cumul_mins_;
std::vector<int64> old_nexts_;
std::vector<int> old_vehicles_;
std::vector<int64> current_transits_;
const std::string name_;
};
ChainCumulFilter::ChainCumulFilter(const RoutingModel& routing_model,
const RoutingDimension& dimension,
Solver::ObjectiveWatcher objective_callback)
: BasePathFilter(routing_model.Nexts(), dimension.cumuls().size(),
std::move(objective_callback)),
cumuls_(dimension.cumuls()),
evaluators_(routing_model.vehicles(), nullptr),
vehicle_capacities_(dimension.vehicle_capacities()),
current_path_cumul_mins_(dimension.cumuls().size(), 0),
current_max_of_path_end_cumul_mins_(dimension.cumuls().size(), 0),
old_nexts_(routing_model.Size(), kUnassigned),
old_vehicles_(routing_model.Size(), kUnassigned),
current_transits_(routing_model.Size(), 0),
name_(dimension.name()) {
start_to_vehicle_.resize(Size(), -1);
start_to_end_.resize(Size(), -1);
for (int i = 0; i < routing_model.vehicles(); ++i) {
start_to_vehicle_[routing_model.Start(i)] = i;
start_to_end_[routing_model.Start(i)] = routing_model.End(i);
evaluators_[i] = &dimension.transit_evaluator(i);
}
}
// On synchronization, maintain "propagated" cumul mins and max level of cumul
// from each node to the end of the path; to be used by AcceptPath to
// incrementally check feasibility.
void ChainCumulFilter::OnSynchronizePathFromStart(int64 start) {
const int vehicle = start_to_vehicle_[start];
std::vector<int64> path_nodes;
int64 node = start;
int64 cumul = cumuls_[node]->Min();
while (node < Size()) {
path_nodes.push_back(node);
current_path_cumul_mins_[node] = cumul;
const int64 next = Value(node);
if (next != old_nexts_[node] || vehicle != old_vehicles_[node]) {
old_nexts_[node] = next;
old_vehicles_[node] = vehicle;
current_transits_[node] = (*evaluators_[vehicle])(node, next);
}
cumul = CapAdd(cumul, current_transits_[node]);
cumul = std::max(cumuls_[next]->Min(), cumul);
node = next;
}
path_nodes.push_back(node);
current_path_cumul_mins_[node] = cumul;
int64 max_cumuls = cumul;
for (int i = path_nodes.size() - 1; i >= 0; --i) {
const int64 node = path_nodes[i];
max_cumuls = std::max(max_cumuls, current_path_cumul_mins_[node]);
current_max_of_path_end_cumul_mins_[node] = max_cumuls;
}
}
// The complexity of the method is O(size of chain (chain_start...chain_end).
bool ChainCumulFilter::AcceptPath(int64 path_start, int64 chain_start,
int64 chain_end) {
const int vehicle = start_to_vehicle_[path_start];
const int64 capacity = vehicle_capacities_[vehicle];
int64 node = chain_start;
int64 cumul = current_path_cumul_mins_[node];
while (node != chain_end) {
const int64 next = GetNext(node);
if (IsVarSynced(node) && next == Value(node) &&
vehicle == old_vehicles_[node]) {
cumul = CapAdd(cumul, current_transits_[node]);
} else {
cumul = CapAdd(cumul, (*evaluators_[vehicle])(node, next));
}
cumul = std::max(cumuls_[next]->Min(), cumul);
if (cumul > capacity) return false;
node = next;
}
const int64 end = start_to_end_[path_start];
const int64 end_cumul_delta =
CapSub(current_path_cumul_mins_[end], current_path_cumul_mins_[node]);
const int64 after_chain_cumul_delta =
CapSub(current_max_of_path_end_cumul_mins_[node],
current_path_cumul_mins_[node]);
return CapAdd(cumul, after_chain_cumul_delta) <= capacity &&
CapAdd(cumul, end_cumul_delta) <= cumuls_[end]->Max();
}
// PathCumul filter.
class PathCumulFilter : public BasePathFilter {
public:
PathCumulFilter(const RoutingModel& routing_model,
const RoutingDimension& dimension,
Solver::ObjectiveWatcher objective_callback,
bool propagate_own_objective_value);
~PathCumulFilter() override {}
std::string DebugString() const override {
return "PathCumulFilter(" + name_ + ")";
}
int64 GetSynchronizedObjectiveValue() const override {
return propagate_own_objective_value_ ? synchronized_objective_value_ : 0;
}
int64 GetAcceptedObjectiveValue() const override {
return propagate_own_objective_value_ ? accepted_objective_value_ : 0;
}
private:
// This structure stores the "best" path cumul value for a solution, the path
// supporting this value, and the corresponding path cumul values for all
// paths.
struct SupportedPathCumul {
SupportedPathCumul() : cumul_value(0), cumul_value_support(0) {}
int64 cumul_value;
int cumul_value_support;
std::vector<int64> path_values;
};