forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing.cc
6638 lines (6128 loc) · 266 KB
/
routing.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.
#include "ortools/constraint_solver/routing.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <functional>
#include <map>
#include <memory>
#include <numeric>
#include <tuple>
#include <utility>
#include "absl/base/casts.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/time/time.h"
#include "google/protobuf/duration.pb.h"
#include "google/protobuf/text_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/hash.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/protoutil.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/thorough_hash.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/routing_enums.pb.h"
#include "ortools/constraint_solver/routing_lp_scheduling.h"
#include "ortools/constraint_solver/routing_neighborhoods.h"
#include "ortools/constraint_solver/routing_parameters.h"
#include "ortools/graph/connectivity.h"
#include "ortools/graph/linear_assignment.h"
#include "ortools/graph/min_cost_flow.h"
#include "ortools/lp_data/lp_data.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/util/optional_boolean.pb.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/stats.h"
namespace operations_research {
class LocalSearchPhaseParameters;
} // namespace operations_research
DEFINE_int64(sweep_sectors, 1,
"The number of sectors the space is divided before it is sweeped "
"by the ray.");
// Trace settings
// TODO(user): Move most of the following settings to a model parameter
// proto.
namespace operations_research {
namespace {
// A decision builder which tries to assign values to variables as close as
// possible to target values first.
// TODO(user): Move to CP solver.
class SetValuesFromTargets : public DecisionBuilder {
public:
SetValuesFromTargets(std::vector<IntVar*> variables,
std::vector<int64> targets)
: variables_(std::move(variables)),
targets_(std::move(targets)),
index_(0),
steps_(variables_.size(), 0) {}
Decision* Next(Solver* const solver) override {
int index = index_.Value();
while (index < variables_.size() && variables_[index]->Bound()) {
++index;
}
index_.SetValue(solver, index);
if (index >= variables_.size()) return nullptr;
const int64 variable_min = variables_[index]->Min();
const int64 variable_max = variables_[index]->Max();
// Target can be before, inside, or after the variable range.
// We do a trichotomy on this for clarity.
if (targets_[index] <= variable_min) {
return solver->MakeAssignVariableValue(variables_[index], variable_min);
} else if (targets_[index] >= variable_max) {
return solver->MakeAssignVariableValue(variables_[index], variable_max);
} else {
int64 step = steps_[index];
int64 value = CapAdd(targets_[index], step);
// If value is out of variable's range, we can remove the interval of
// values already explored (which can make the solver fail) and
// recall Next() to get back into the trichotomy above.
if (value < variable_min || variable_max < value) {
step = GetNextStep(step);
value = CapAdd(targets_[index], step);
if (step > 0) {
// Values in [variable_min, value) were already explored.
variables_[index]->SetMin(value);
} else {
// Values in (value, variable_max] were already explored.
variables_[index]->SetMax(value);
}
return Next(solver);
}
steps_.SetValue(solver, index, GetNextStep(step));
return solver->MakeAssignVariableValueOrDoNothing(variables_[index],
value);
}
}
private:
int64 GetNextStep(int64 step) const {
return (step > 0) ? -step : CapSub(1, step);
}
const std::vector<IntVar*> variables_;
const std::vector<int64> targets_;
Rev<int> index_;
RevArray<int64> steps_;
};
} // namespace
DecisionBuilder* MakeSetValuesFromTargets(Solver* solver,
std::vector<IntVar*> variables,
std::vector<int64> targets) {
return solver->RevAlloc(
new SetValuesFromTargets(std::move(variables), std::move(targets)));
}
namespace {
bool DimensionFixedTransitsEqualTransitEvaluatorForVehicle(
const RoutingDimension& dimension, int vehicle) {
const RoutingModel* const model = dimension.model();
int node = model->Start(vehicle);
while (!model->IsEnd(node)) {
if (!model->NextVar(node)->Bound()) {
return false;
}
const int next = model->NextVar(node)->Value();
if (dimension.transit_evaluator(vehicle)(node, next) !=
dimension.FixedTransitVar(node)->Value()) {
return false;
}
node = next;
}
return true;
}
bool DimensionFixedTransitsEqualTransitEvaluators(
const RoutingDimension& dimension) {
for (int vehicle = 0; vehicle < dimension.model()->vehicles(); vehicle++) {
if (!DimensionFixedTransitsEqualTransitEvaluatorForVehicle(dimension,
vehicle)) {
return false;
}
}
return true;
}
class SetCumulsFromLocalDimensionCosts : public DecisionBuilder {
public:
SetCumulsFromLocalDimensionCosts(
const std::vector<std::unique_ptr<LocalDimensionCumulOptimizer>>*
local_optimizers,
const std::vector<std::unique_ptr<LocalDimensionCumulOptimizer>>*
local_mp_optimizers,
SearchMonitor* monitor, bool optimize_and_pack = false)
: local_optimizers_(*local_optimizers),
local_mp_optimizers_(*local_mp_optimizers),
monitor_(monitor),
optimize_and_pack_(optimize_and_pack) {}
Decision* Next(Solver* const solver) override {
// The following boolean variable indicates if the solver should fail, in
// order to postpone the Fail() call until after the internal for loop, so
// there are no memory leaks related to the cumul_values vector.
bool should_fail = false;
for (int i = 0; i < local_optimizers_.size(); ++i) {
const auto& optimizer = local_optimizers_[i];
const RoutingDimension* const dimension = optimizer->dimension();
RoutingModel* const model = dimension->model();
const auto next = [model](int64 i) { return model->NextVar(i)->Value(); };
const auto compute_cumul_values =
[this, &next](LocalDimensionCumulOptimizer* optimizer, int vehicle,
std::vector<int64>* cumul_values) {
return optimize_and_pack_ ? optimizer->ComputePackedRouteCumuls(
vehicle, next, cumul_values)
: optimizer->ComputeRouteCumuls(
vehicle, next, cumul_values);
};
for (int vehicle = 0; vehicle < model->vehicles(); ++vehicle) {
// TODO(user): Investigate if we should skip unused vehicles.
DCHECK(DimensionFixedTransitsEqualTransitEvaluatorForVehicle(*dimension,
vehicle));
std::vector<int64> cumul_values;
const DimensionSchedulingStatus status =
compute_cumul_values(optimizer.get(), vehicle, &cumul_values);
if (status == DimensionSchedulingStatus::INFEASIBLE) {
should_fail = true;
break;
}
// If relaxation is not feasible, try the MILP optimizer.
if (status == DimensionSchedulingStatus::RELAXED_OPTIMAL_ONLY) {
cumul_values.clear();
DCHECK(local_mp_optimizers_[i] != nullptr);
if (compute_cumul_values(local_mp_optimizers_[i].get(), vehicle,
&cumul_values) ==
DimensionSchedulingStatus::INFEASIBLE) {
should_fail = true;
break;
}
} else {
DCHECK(status == DimensionSchedulingStatus::OPTIMAL);
}
std::vector<IntVar*> cumuls;
int current = model->Start(vehicle);
while (true) {
cumuls.push_back(dimension->CumulVar(current));
if (!model->IsEnd(current)) {
current = model->NextVar(current)->Value();
} else {
break;
}
}
// Setting the cumuls of path start/end first is more efficient than
// setting the cumuls in order of path appearance, because setting start
// and end cumuls gives an opportunity to fix all cumuls with two
// decisions instead of |path| decisions.
// To this effect, we put end cumul just after the start cumul.
std::swap(cumuls[1], cumuls[cumuls.size() - 1]);
std::swap(cumul_values[1], cumul_values[cumuls.size() - 1]);
// TODO(user): Use SetValuesFromTargets to return a Decision instead
// of the nested Solve.
if (!solver->SolveAndCommit(
MakeSetValuesFromTargets(solver, std::move(cumuls),
std::move(cumul_values)),
monitor_)) {
should_fail = true;
break;
}
}
if (should_fail) {
solver->Fail();
}
}
return nullptr;
}
private:
const std::vector<std::unique_ptr<LocalDimensionCumulOptimizer>>&
local_optimizers_;
const std::vector<std::unique_ptr<LocalDimensionCumulOptimizer>>&
local_mp_optimizers_;
SearchMonitor* const monitor_;
const bool optimize_and_pack_;
};
class SetCumulsFromGlobalDimensionCosts : public DecisionBuilder {
public:
SetCumulsFromGlobalDimensionCosts(
const std::vector<std::unique_ptr<GlobalDimensionCumulOptimizer>>*
global_optimizers,
SearchMonitor* monitor, bool optimize_and_pack = false)
: global_optimizers_(*global_optimizers),
monitor_(monitor),
optimize_and_pack_(optimize_and_pack) {}
Decision* Next(Solver* const solver) override {
// The following boolean variable indicates if the solver should fail, in
// order to postpone the Fail() call until after the for loop, so there are
// no memory leaks related to the cumul_values vector.
bool should_fail = false;
for (const auto& global_optimizer : global_optimizers_) {
const RoutingDimension* dimension = global_optimizer->dimension();
RoutingModel* const model = dimension->model();
const auto next = [model](int64 i) { return model->NextVar(i)->Value(); };
DCHECK(DimensionFixedTransitsEqualTransitEvaluators(*dimension));
std::vector<int64> cumul_values;
const bool cumuls_optimized =
optimize_and_pack_
? global_optimizer->ComputePackedCumuls(next, &cumul_values)
: global_optimizer->ComputeCumuls(next, &cumul_values);
// TODO(user): Use SetValuesFromTargets to return a Decision instead
// of the nested Solve.
if (!cumuls_optimized ||
!solver->SolveAndCommit(
MakeSetValuesFromTargets(solver, dimension->cumuls(),
std::move(cumul_values)),
monitor_)) {
should_fail = true;
break;
}
}
if (should_fail) {
solver->Fail();
}
return nullptr;
}
private:
const std::vector<std::unique_ptr<GlobalDimensionCumulOptimizer>>&
global_optimizers_;
SearchMonitor* const monitor_;
const bool optimize_and_pack_;
};
} // namespace
const Assignment* RoutingModel::PackCumulsOfOptimizerDimensionsFromAssignment(
const Assignment* original_assignment, absl::Duration duration_limit) {
CHECK(closed_);
const int64 time_limit_ms =
absl::time_internal::IsInfiniteDuration(duration_limit)
? kint64max
: absl::ToInt64Milliseconds(duration_limit);
if (time_limit_ms <= 0 || original_assignment == nullptr ||
(global_dimension_optimizers_.empty() &&
local_dimension_optimizers_.empty())) {
DCHECK(local_dimension_mp_optimizers_.empty());
return original_assignment;
}
RegularLimit* const limit = GetOrCreateLimit();
limit->UpdateLimits(time_limit_ms, kint64max, kint64max, kint64max);
// Initialize the packed_assignment with the Next values in the
// original_assignment.
Assignment* packed_assignment = solver_->MakeAssignment();
packed_assignment->Add(Nexts());
packed_assignment->CopyIntersection(original_assignment);
std::vector<DecisionBuilder*> decision_builders;
decision_builders.push_back(solver_->MakeRestoreAssignment(preassignment_));
decision_builders.push_back(
solver_->MakeRestoreAssignment(packed_assignment));
decision_builders.push_back(
solver_->RevAlloc(new SetCumulsFromLocalDimensionCosts(
&local_dimension_optimizers_, &local_dimension_mp_optimizers_,
GetOrCreateLargeNeighborhoodSearchLimit(),
/*optimize_and_pack=*/true)));
decision_builders.push_back(
solver_->RevAlloc(new SetCumulsFromGlobalDimensionCosts(
&global_dimension_optimizers_,
GetOrCreateLargeNeighborhoodSearchLimit(),
/*optimize_and_pack=*/true)));
decision_builders.push_back(
CreateFinalizerForMinimizedAndMaximizedVariables());
DecisionBuilder* restore_pack_and_finalize =
solver_->Compose(decision_builders);
solver_->Solve(restore_pack_and_finalize,
packed_dimensions_assignment_collector_, limit);
if (packed_dimensions_assignment_collector_->solution_count() != 1) {
LOG(ERROR) << "The given assignment is not valid for this model, or cannot "
"be packed.";
return nullptr;
}
packed_assignment->Copy(original_assignment);
packed_assignment->CopyIntersection(
packed_dimensions_assignment_collector_->solution(0));
return packed_assignment;
}
namespace {
// Constraint which ensures that var != values.
class DifferentFromValues : public Constraint {
public:
DifferentFromValues(Solver* solver, IntVar* var, std::vector<int64> values)
: Constraint(solver), var_(var), values_(std::move(values)) {}
void Post() override {}
void InitialPropagate() override { var_->RemoveValues(values_); }
std::string DebugString() const override { return "DifferentFromValues"; }
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(RoutingModelVisitor::kRemoveValues, this);
visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument,
{var_});
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument, values_);
visitor->EndVisitConstraint(RoutingModelVisitor::kRemoveValues, this);
}
private:
IntVar* const var_;
const std::vector<int64> values_;
};
// Set of "light" constraints, well-suited for use within Local Search.
// These constraints are "checking" constraints, only triggered on WhenBound
// events. The provide very little (or no) domain filtering.
// TODO(user): Move to core constraintsolver library.
// Light one-dimension function-based element constraint ensuring:
// var == values(index).
// Doesn't perform bound reduction of the resulting variable until the index
// variable is bound.
// If deep_serialize returns false, the model visitor will not extract all
// possible values from the values function.
template <typename F>
class LightFunctionElementConstraint : public Constraint {
public:
LightFunctionElementConstraint(Solver* const solver, IntVar* const var,
IntVar* const index, F values,
std::function<bool()> deep_serialize)
: Constraint(solver),
var_(var),
index_(index),
values_(std::move(values)),
deep_serialize_(std::move(deep_serialize)) {}
~LightFunctionElementConstraint() override {}
void Post() override {
Demon* demon = MakeConstraintDemon0(
solver(), this, &LightFunctionElementConstraint::IndexBound,
"IndexBound");
index_->WhenBound(demon);
}
void InitialPropagate() override {
if (index_->Bound()) {
IndexBound();
}
}
std::string DebugString() const override {
return "LightFunctionElementConstraint";
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(RoutingModelVisitor::kLightElement, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kTargetArgument,
var_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
index_);
// Warning: This will expand all values into a vector.
if (deep_serialize_()) {
visitor->VisitInt64ToInt64Extension(values_, index_->Min(),
index_->Max());
}
visitor->EndVisitConstraint(RoutingModelVisitor::kLightElement, this);
}
private:
void IndexBound() { var_->SetValue(values_(index_->Min())); }
IntVar* const var_;
IntVar* const index_;
F values_;
std::function<bool()> deep_serialize_;
};
template <typename F>
Constraint* MakeLightElement(Solver* const solver, IntVar* const var,
IntVar* const index, F values,
std::function<bool()> deep_serialize) {
return solver->RevAlloc(new LightFunctionElementConstraint<F>(
solver, var, index, std::move(values), std::move(deep_serialize)));
}
// Light two-dimension function-based element constraint ensuring:
// var == values(index1, index2).
// Doesn't perform bound reduction of the resulting variable until the index
// variables are bound.
// Ownership of the 'values' callback is taken by the constraint.
template <typename F>
class LightFunctionElement2Constraint : public Constraint {
public:
LightFunctionElement2Constraint(Solver* const solver, IntVar* const var,
IntVar* const index1, IntVar* const index2,
F values,
std::function<bool()> deep_serialize)
: Constraint(solver),
var_(var),
index1_(index1),
index2_(index2),
values_(std::move(values)),
deep_serialize_(std::move(deep_serialize)) {}
~LightFunctionElement2Constraint() override {}
void Post() override {
Demon* demon = MakeConstraintDemon0(
solver(), this, &LightFunctionElement2Constraint::IndexBound,
"IndexBound");
index1_->WhenBound(demon);
index2_->WhenBound(demon);
}
void InitialPropagate() override { IndexBound(); }
std::string DebugString() const override {
return "LightFunctionElement2Constraint";
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(RoutingModelVisitor::kLightElement2, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kTargetArgument,
var_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
index1_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndex2Argument,
index2_);
// Warning: This will expand all values into a vector.
const int64 index1_min = index1_->Min();
const int64 index1_max = index1_->Max();
visitor->VisitIntegerArgument(ModelVisitor::kMinArgument, index1_min);
visitor->VisitIntegerArgument(ModelVisitor::kMaxArgument, index1_max);
if (deep_serialize_()) {
for (int i = index1_min; i <= index1_max; ++i) {
visitor->VisitInt64ToInt64Extension(
[this, i](int64 j) { return values_(i, j); }, index2_->Min(),
index2_->Max());
}
}
visitor->EndVisitConstraint(RoutingModelVisitor::kLightElement2, this);
}
private:
void IndexBound() {
if (index1_->Bound() && index2_->Bound()) {
var_->SetValue(values_(index1_->Min(), index2_->Min()));
}
}
IntVar* const var_;
IntVar* const index1_;
IntVar* const index2_;
Solver::IndexEvaluator2 values_;
std::function<bool()> deep_serialize_;
};
template <typename F>
Constraint* MakeLightElement2(Solver* const solver, IntVar* const var,
IntVar* const index1, IntVar* const index2,
F values, std::function<bool()> deep_serialize) {
return solver->RevAlloc(new LightFunctionElement2Constraint<F>(
solver, var, index1, index2, std::move(values),
std::move(deep_serialize)));
}
// Shortcuts to spawn neighborhood operators from ./routing_neighborhoods.h.
// TODO(user): Consider removing all these trivial wrappers and just inlining
// the solver->RevAlloc(new ...Operator()) calls in the client code.
LocalSearchOperator* MakeRelocateNeighbors(
Solver* solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
RoutingModel::TransitCallback2 arc_evaluator) {
return solver->RevAlloc(new MakeRelocateNeighborsOperator(
vars, secondary_vars, std::move(start_empty_path_class),
std::move(arc_evaluator)));
}
LocalSearchOperator* MakePairActive(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new MakePairActiveOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* MakePairInactive(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new MakePairInactiveOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* MakePairRelocate(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new PairRelocateOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* MakeLightPairRelocate(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new LightPairRelocateOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* MakePairExchange(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new PairExchangeOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* MakePairExchangeRelocate(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new PairExchangeRelocateOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* SwapIndexPair(Solver* const solver,
const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(
new SwapIndexPairOperator(vars, secondary_vars, pairs));
}
LocalSearchOperator* IndexPairSwapActive(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new IndexPairSwapActiveOperator(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* PairNodeSwapActive(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->ConcatenateOperators(
{solver->RevAlloc(new PairNodeSwapActiveOperator<true>(
vars, secondary_vars, start_empty_path_class, pairs)),
solver->RevAlloc(new PairNodeSwapActiveOperator<false>(
vars, secondary_vars, std::move(start_empty_path_class), pairs))});
}
LocalSearchOperator* MakeRelocateSubtrip(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new RelocateSubtrip(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
LocalSearchOperator* MakeExchangeSubtrip(
Solver* const solver, const std::vector<IntVar*>& vars,
const std::vector<IntVar*>& secondary_vars,
std::function<int(int64)> start_empty_path_class,
const RoutingModel::IndexPairs& pairs) {
return solver->RevAlloc(new ExchangeSubtrip(
vars, secondary_vars, std::move(start_empty_path_class), pairs));
}
// Evaluators
template <class A, class B>
static int64 ReturnZero(A a, B b) {
return 0;
}
bool TransitCallbackPositive(const RoutingTransitCallback2& callback, int size1,
int size2) {
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (callback(i, j) < 0) {
return false;
}
}
}
return true;
}
} // namespace
// ----- Routing model -----
static const int kUnassigned = -1;
const int64 RoutingModel::kNoPenalty = -1;
const RoutingModel::DisjunctionIndex RoutingModel::kNoDisjunction(-1);
const RoutingModel::DimensionIndex RoutingModel::kNoDimension(-1);
RoutingModel::RoutingModel(const RoutingIndexManager& index_manager)
: RoutingModel(index_manager, DefaultRoutingModelParameters()) {}
RoutingModel::RoutingModel(const RoutingIndexManager& index_manager,
const RoutingModelParameters& parameters)
: nodes_(index_manager.num_nodes()),
vehicles_(index_manager.num_vehicles()),
fixed_cost_of_vehicle_(vehicles_, 0),
cost_class_index_of_vehicle_(vehicles_, CostClassIndex(-1)),
linear_cost_factor_of_vehicle_(vehicles_, 0),
quadratic_cost_factor_of_vehicle_(vehicles_, 0),
vehicle_amortized_cost_factors_set_(false),
consider_empty_route_costs_(vehicles_, false),
cost_classes_(),
costs_are_homogeneous_across_vehicles_(
parameters.reduce_vehicle_cost_model()),
cache_callbacks_(false),
vehicle_class_index_of_vehicle_(vehicles_, VehicleClassIndex(-1)),
vehicle_pickup_delivery_policy_(vehicles_, PICKUP_AND_DELIVERY_NO_ORDER),
has_hard_type_incompatibilities_(false),
has_temporal_type_incompatibilities_(false),
has_same_vehicle_type_requirements_(false),
has_temporal_type_requirements_(false),
num_visit_types_(0),
starts_(vehicles_),
ends_(vehicles_),
manager_(index_manager) {
// Initialize vehicle costs to the zero evaluator.
vehicle_to_transit_cost_.assign(
vehicles_, RegisterTransitCallback(ReturnZero<int64, int64>));
// Active caching after initializing vehicle_to_transit_cost_ to avoid
// uselessly caching ReturnZero.
cache_callbacks_ = (nodes_ <= parameters.max_callback_cache_size());
VLOG(1) << "Model parameters:\n" << parameters.DebugString();
ConstraintSolverParameters solver_parameters =
parameters.has_solver_parameters() ? parameters.solver_parameters()
: Solver::DefaultSolverParameters();
solver_ = absl::make_unique<Solver>("Routing", solver_parameters);
// TODO(user): Remove when removal of NodeIndex is complete.
start_end_count_ = index_manager.num_unique_depots();
Initialize();
const int64 size = Size();
index_to_pickup_index_pairs_.resize(size);
index_to_delivery_index_pairs_.resize(size);
index_to_visit_type_.resize(index_manager.num_indices(), kUnassigned);
index_to_type_policy_.resize(index_manager.num_indices());
index_to_vehicle_.resize(index_manager.num_indices(), kUnassigned);
for (int v = 0; v < index_manager.num_vehicles(); ++v) {
starts_[v] = index_manager.GetStartIndex(v);
index_to_vehicle_[starts_[v]] = v;
ends_[v] = index_manager.GetEndIndex(v);
index_to_vehicle_[ends_[v]] = v;
}
const std::vector<RoutingIndexManager::NodeIndex>& index_to_node =
index_manager.GetIndexToNodeMap();
index_to_equivalence_class_.resize(index_manager.num_indices());
for (int i = 0; i < index_to_node.size(); ++i) {
index_to_equivalence_class_[i] = index_to_node[i].value();
}
allowed_vehicles_.resize(Size() + vehicles_);
}
void RoutingModel::Initialize() {
const int size = Size();
// Next variables
solver_->MakeIntVarArray(size, 0, size + vehicles_ - 1, "Nexts", &nexts_);
solver_->AddConstraint(solver_->MakeAllDifferent(nexts_, false));
index_to_disjunctions_.resize(size + vehicles_);
// Vehicle variables. In case that node i is not active, vehicle_vars_[i] is
// bound to -1.
solver_->MakeIntVarArray(size + vehicles_, -1, vehicles_ - 1, "Vehicles",
&vehicle_vars_);
// Active variables
solver_->MakeBoolVarArray(size, "Active", &active_);
// Used vehicle variables
solver_->MakeBoolVarArray(vehicles_, "VehicleCostsConsidered",
&vehicle_costs_considered_);
// Is-bound-to-end variables.
solver_->MakeBoolVarArray(size + vehicles_, "IsBoundToEnd",
&is_bound_to_end_);
// Cost cache
cost_cache_.clear();
cost_cache_.resize(size + vehicles_, {kUnassigned, CostClassIndex(-1), 0});
preassignment_ = solver_->MakeAssignment();
}
RoutingModel::~RoutingModel() {
gtl::STLDeleteElements(&dimensions_);
// State dependent transit callbacks.
absl::flat_hash_set<RangeIntToIntFunction*> value_functions_delete;
absl::flat_hash_set<RangeMinMaxIndexFunction*> index_functions_delete;
for (const auto& cache_line : state_dependent_transit_evaluators_cache_) {
for (const auto& key_transit : *cache_line) {
value_functions_delete.insert(key_transit.second.transit);
index_functions_delete.insert(key_transit.second.transit_plus_identity);
}
}
gtl::STLDeleteElements(&value_functions_delete);
gtl::STLDeleteElements(&index_functions_delete);
}
int RoutingModel::RegisterUnaryTransitCallback(TransitCallback1 callback) {
const int index = unary_transit_evaluators_.size();
unary_transit_evaluators_.push_back(std::move(callback));
return RegisterTransitCallback([this, index](int i, int j) {
return unary_transit_evaluators_[index](i);
});
}
int RoutingModel::RegisterPositiveUnaryTransitCallback(
TransitCallback1 callback) {
is_transit_evaluator_positive_.push_back(true);
DCHECK(TransitCallbackPositive(
[&callback](int i, int) { return callback(i); }, Size() + vehicles(), 1));
return RegisterUnaryTransitCallback(std::move(callback));
}
int RoutingModel::RegisterTransitCallback(TransitCallback2 callback) {
if (cache_callbacks_) {
const int size = Size() + vehicles();
std::vector<int64> cache(size * size, 0);
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
cache[i * size + j] = callback(i, j);
}
}
transit_evaluators_.push_back(
[cache, size](int64 i, int64 j) { return cache[i * size + j]; });
} else {
transit_evaluators_.push_back(std::move(callback));
}
if (transit_evaluators_.size() != unary_transit_evaluators_.size()) {
DCHECK_EQ(transit_evaluators_.size(), unary_transit_evaluators_.size() + 1);
unary_transit_evaluators_.push_back(nullptr);
}
if (transit_evaluators_.size() != is_transit_evaluator_positive_.size()) {
DCHECK_EQ(transit_evaluators_.size(),
is_transit_evaluator_positive_.size() + 1);
is_transit_evaluator_positive_.push_back(false);
}
return transit_evaluators_.size() - 1;
}
int RoutingModel::RegisterPositiveTransitCallback(TransitCallback2 callback) {
is_transit_evaluator_positive_.push_back(true);
DCHECK(TransitCallbackPositive(callback, Size() + vehicles(),
Size() + vehicles()));
return RegisterTransitCallback(std::move(callback));
}
int RoutingModel::RegisterStateDependentTransitCallback(
VariableIndexEvaluator2 callback) {
state_dependent_transit_evaluators_cache_.push_back(
absl::make_unique<StateDependentTransitCallbackCache>());
StateDependentTransitCallbackCache* const cache =
state_dependent_transit_evaluators_cache_.back().get();
state_dependent_transit_evaluators_.push_back(
[cache, callback](int64 i, int64 j) {
StateDependentTransit value;
if (gtl::FindCopy(*cache, CacheKey(i, j), &value)) return value;
value = callback(i, j);
cache->insert({CacheKey(i, j), value});
return value;
});
return state_dependent_transit_evaluators_.size() - 1;
}
void RoutingModel::AddNoCycleConstraintInternal() {
if (no_cycle_constraint_ == nullptr) {
no_cycle_constraint_ = solver_->MakeNoCycle(nexts_, active_);
solver_->AddConstraint(no_cycle_constraint_);
}
}
bool RoutingModel::AddDimension(int evaluator_index, int64 slack_max,
int64 capacity, bool fix_start_cumul_to_zero,
const std::string& name) {
const std::vector<int> evaluator_indices(vehicles_, evaluator_index);
std::vector<int64> capacities(vehicles_, capacity);
return AddDimensionWithCapacityInternal(evaluator_indices, slack_max,
std::move(capacities),
fix_start_cumul_to_zero, name);
}
bool RoutingModel::AddDimensionWithVehicleTransits(
const std::vector<int>& evaluator_indices, int64 slack_max, int64 capacity,
bool fix_start_cumul_to_zero, const std::string& name) {
std::vector<int64> capacities(vehicles_, capacity);
return AddDimensionWithCapacityInternal(evaluator_indices, slack_max,
std::move(capacities),
fix_start_cumul_to_zero, name);
}
bool RoutingModel::AddDimensionWithVehicleCapacity(
int evaluator_index, int64 slack_max, std::vector<int64> vehicle_capacities,
bool fix_start_cumul_to_zero, const std::string& name) {
const std::vector<int> evaluator_indices(vehicles_, evaluator_index);
return AddDimensionWithCapacityInternal(evaluator_indices, slack_max,
std::move(vehicle_capacities),
fix_start_cumul_to_zero, name);
}
bool RoutingModel::AddDimensionWithVehicleTransitAndCapacity(
const std::vector<int>& evaluator_indices, int64 slack_max,
std::vector<int64> vehicle_capacities, bool fix_start_cumul_to_zero,
const std::string& name) {
return AddDimensionWithCapacityInternal(evaluator_indices, slack_max,
std::move(vehicle_capacities),
fix_start_cumul_to_zero, name);
}
bool RoutingModel::AddDimensionWithCapacityInternal(
const std::vector<int>& evaluator_indices, int64 slack_max,
std::vector<int64> vehicle_capacities, bool fix_start_cumul_to_zero,
const std::string& name) {
CHECK_EQ(vehicles_, vehicle_capacities.size());
return InitializeDimensionInternal(
evaluator_indices, std::vector<int>(), slack_max, fix_start_cumul_to_zero,
new RoutingDimension(this, std::move(vehicle_capacities), name, nullptr));
}
bool RoutingModel::InitializeDimensionInternal(
const std::vector<int>& evaluator_indices,
const std::vector<int>& state_dependent_evaluator_indices, int64 slack_max,
bool fix_start_cumul_to_zero, RoutingDimension* dimension) {
CHECK(dimension != nullptr);
CHECK_EQ(vehicles_, evaluator_indices.size());
CHECK((dimension->base_dimension_ == nullptr &&
state_dependent_evaluator_indices.empty()) ||
vehicles_ == state_dependent_evaluator_indices.size());
if (!HasDimension(dimension->name())) {
const DimensionIndex dimension_index(dimensions_.size());
dimension_name_to_index_[dimension->name()] = dimension_index;
dimensions_.push_back(dimension);
dimension->Initialize(evaluator_indices, state_dependent_evaluator_indices,
slack_max);
solver_->AddConstraint(solver_->MakeDelayedPathCumul(
nexts_, active_, dimension->cumuls(), dimension->transits()));
if (fix_start_cumul_to_zero) {
for (int i = 0; i < vehicles_; ++i) {
IntVar* const start_cumul = dimension->CumulVar(Start(i));
CHECK_EQ(0, start_cumul->Min());
start_cumul->SetValue(0);
}
}
return true;
}
delete dimension;
return false;
}
namespace {
int RegisterCallback(RoutingTransitCallback2 callback, bool is_positive,
RoutingModel* model) {
if (is_positive) {
return model->RegisterPositiveTransitCallback(std::move(callback));
}
return model->RegisterTransitCallback(std::move(callback));
}
int RegisterUnaryCallback(RoutingTransitCallback1 callback, bool is_positive,
RoutingModel* model) {
if (is_positive) {
return model->RegisterPositiveUnaryTransitCallback(std::move(callback));
}
return model->RegisterUnaryTransitCallback(std::move(callback));
}
} // namespace
bool RoutingModel::AddConstantDimensionWithSlack(
int64 value, int64 capacity, int64 slack_max, bool fix_start_cumul_to_zero,
const std::string& dimension_name) {
return AddDimension(RegisterUnaryCallback([value](int64) { return value; },
/*is_positive=*/value >= 0, this),
slack_max, capacity, fix_start_cumul_to_zero,
dimension_name);
}
bool RoutingModel::AddVectorDimension(std::vector<int64> values, int64 capacity,
bool fix_start_cumul_to_zero,
const std::string& dimension_name) {
return AddDimension(
RegisterUnaryCallback(
[this, values](int64 i) {
return values[manager_.IndexToNode(i).value()];
},
/*is_positive=*/
std::all_of(std::begin(values), std::end(values),
[](int64 transit) { return transit >= 0; }),
this),
0, capacity, fix_start_cumul_to_zero, dimension_name);
}
bool RoutingModel::AddMatrixDimension(std::vector<std::vector<int64>> values,
int64 capacity,
bool fix_start_cumul_to_zero,