forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing.cc
6933 lines (6413 loc) · 283 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-2024 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 <limits.h>
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <numeric>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/flags/flag.h"
#include "absl/functional/bind_front.h"
#include "absl/hash/hash.h"
#include "absl/log/check.h"
#include "absl/log/die_if_null.h"
#include "absl/memory/memory.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "ortools/base/dump_vars.h"
#include "ortools/base/int_type.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/strong_vector.h"
#include "ortools/base/types.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/constraint_solver/routing_constraints.h"
#include "ortools/constraint_solver/routing_decision_builders.h"
#include "ortools/constraint_solver/routing_enums.pb.h"
#include "ortools/constraint_solver/routing_filters.h"
#include "ortools/constraint_solver/routing_ils.h"
#include "ortools/constraint_solver/routing_ils.pb.h"
#include "ortools/constraint_solver/routing_index_manager.h"
#include "ortools/constraint_solver/routing_insertion_lns.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/constraint_solver/routing_parameters.pb.h"
#include "ortools/constraint_solver/routing_search.h"
#include "ortools/constraint_solver/routing_types.h"
#include "ortools/constraint_solver/routing_utils.h"
#include "ortools/constraint_solver/solver_parameters.pb.h"
#include "ortools/graph/connected_components.h"
#include "ortools/graph/ebert_graph.h"
#include "ortools/graph/linear_assignment.h"
#include "ortools/util/bitset.h"
#include "ortools/util/optional_boolean.pb.h"
#include "ortools/util/piecewise_linear_function.h"
#include "ortools/util/range_query_function.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/stats.h"
namespace operations_research {
class Cross;
class Exchange;
class ExtendedSwapActiveOperator;
class LocalSearchPhaseParameters;
class MakeActiveAndRelocate;
class MakeActiveOperator;
class MakeChainInactiveOperator;
class MakeInactiveOperator;
class Relocate;
class RelocateAndMakeActiveOperator;
class SwapActiveOperator;
class TwoOpt;
} // namespace operations_research
// Trace settings
namespace operations_research {
std::string RoutingModel::RouteDimensionTravelInfo::DebugString(
std::string line_prefix) const {
std::string s = absl::StrFormat("%stravel_cost_coefficient: %ld", line_prefix,
travel_cost_coefficient);
for (int i = 0; i < transition_info.size(); ++i) {
absl::StrAppendFormat(&s, "\ntransition[%d] {\n%s\n}\n", i,
transition_info[i].DebugString(line_prefix + "\t"));
}
return s;
}
std::string RoutingModel::RouteDimensionTravelInfo::TransitionInfo::DebugString(
std::string line_prefix) const {
return absl::StrFormat(
R"({
%spre: %ld
%spost: %ld
%slower_bound: %ld
%supper_bound: %ld
%stravel_value: %s
%scost: %s
})",
line_prefix, pre_travel_transit_value, line_prefix,
post_travel_transit_value, line_prefix,
compressed_travel_value_lower_bound, line_prefix,
travel_value_upper_bound, line_prefix,
travel_start_dependent_travel.DebugString(line_prefix + "\t"),
line_prefix, travel_compression_cost.DebugString(line_prefix + "\t"));
}
std::string RoutingModel::RouteDimensionTravelInfo::TransitionInfo::
PiecewiseLinearFormulation::DebugString(std::string line_prefix) const {
if (x_anchors.size() <= 10) {
return "{ " + DUMP_VARS(x_anchors, y_anchors).str() + "}";
}
return absl::StrFormat("{\n%s%s\n%s%s\n}", line_prefix,
DUMP_VARS(x_anchors).str(), line_prefix,
DUMP_VARS(y_anchors).str());
}
const Assignment* RoutingModel::PackCumulsOfOptimizerDimensionsFromAssignment(
const Assignment* original_assignment, absl::Duration duration_limit,
bool* time_limit_was_reached) {
CHECK(closed_);
if (original_assignment == nullptr) return nullptr;
if (duration_limit <= absl::ZeroDuration()) {
if (time_limit_was_reached) *time_limit_was_reached = true;
return original_assignment;
}
if (global_dimension_optimizers_.empty() &&
local_dimension_optimizers_.empty()) {
return original_assignment;
}
RegularLimit* const limit = GetOrCreateLimit();
limit->UpdateLimits(duration_limit, std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
RegularLimit* const cumulative_limit = GetOrCreateCumulativeLimit();
cumulative_limit->UpdateLimits(
duration_limit, std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max());
// Initialize the packed_assignment with the Next values in the
// original_assignment.
Assignment* packed_assignment = solver_->MakeAssignment();
packed_assignment->Add(Nexts());
// Also keep the Resource values to avoid unnecessary re-optimizations.
for (const RoutingDimension* const dimension : dimensions_) {
for (int rg_index : GetDimensionResourceGroupIndices(dimension)) {
DCHECK(HasLocalCumulOptimizer(*dimension));
packed_assignment->Add(resource_vars_[rg_index]);
}
}
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));
for (auto& [lp_optimizer, mp_optimizer] : local_dimension_optimizers_) {
if (HasGlobalCumulOptimizer(*lp_optimizer->dimension())) {
// Don't set cumuls of dimensions with a global optimizer.
continue;
}
decision_builders.push_back(MakeSetCumulsFromLocalDimensionCosts(
solver_.get(), lp_optimizer.get(), mp_optimizer.get(),
/*optimize_and_pack=*/true));
}
for (auto& [lp_optimizer, mp_optimizer] : global_dimension_optimizers_) {
decision_builders.push_back(MakeSetCumulsFromGlobalDimensionCosts(
solver_.get(), lp_optimizer.get(), mp_optimizer.get(), cumulative_limit,
/*optimize_and_pack=*/true));
}
decision_builders.push_back(finalizer_variables_->CreateFinalizer());
DecisionBuilder* restore_pack_and_finalize =
solver_->Compose(decision_builders);
solver_->Solve(restore_pack_and_finalize,
optimized_dimensions_assignment_collector_, limit);
const bool limit_was_reached = limit->Check();
if (time_limit_was_reached) *time_limit_was_reached = limit_was_reached;
if (optimized_dimensions_assignment_collector_->solution_count() != 1) {
if (limit_was_reached) {
VLOG(1) << "The packing reached the time limit.";
} else {
// TODO(user): Upgrade this to a LOG(DFATAL) when it no longer happens
// in the stress test.
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(
optimized_dimensions_assignment_collector_->solution(0));
return packed_assignment;
}
void RoutingModel::SetSweepArranger(SweepArranger* sweep_arranger) {
sweep_arranger_.reset(sweep_arranger);
}
SweepArranger* RoutingModel::sweep_arranger() const {
return sweep_arranger_.get();
}
void RoutingModel::NodeNeighborsByCostClass::ComputeNeighbors(
const RoutingModel& routing_model, int num_neighbors,
bool add_vehicle_starts_to_neighbors) {
// TODO(user): consider checking search limits.
const int size = routing_model.Size();
const int size_with_vehicle_nodes = size + routing_model.vehicles();
node_index_to_neighbors_by_cost_class_.clear();
if (num_neighbors >= size) {
all_nodes_.resize(size);
std::iota(all_nodes_.begin(), all_nodes_.end(), 0);
return;
}
node_index_to_neighbors_by_cost_class_.resize(size_with_vehicle_nodes);
const int num_cost_classes = routing_model.GetCostClassesCount();
for (int node_index = 0; node_index < size_with_vehicle_nodes; 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] =
std::make_unique<SparseBitset<int>>(size);
}
}
std::vector<std::pair</*cost*/ int64_t, /*node*/ int>> cost_nodes;
cost_nodes.reserve(size);
for (int node_index = 0; node_index < size_with_vehicle_nodes; ++node_index) {
if (routing_model.IsStart(node_index) || routing_model.IsEnd(node_index)) {
// For vehicle starts/ends, we consider all nodes (see below)
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;
}
cost_nodes.clear();
for (int after_node = 0; after_node < size; ++after_node) {
if (after_node != node_index && !routing_model.IsStart(after_node)) {
cost_nodes.push_back(
std::make_pair(routing_model.GetArcCostForClass(
node_index, after_node, cost_class),
after_node));
}
}
std::nth_element(cost_nodes.begin(),
cost_nodes.begin() + num_neighbors - 1,
cost_nodes.end());
cost_nodes.resize(num_neighbors);
// Make sure the order of the n first element is always the same.
std::sort(cost_nodes.begin(), cost_nodes.end());
auto& node_neighbors =
node_index_to_neighbors_by_cost_class_[node_index][cost_class];
for (const auto& costed_node : cost_nodes) {
const int neighbor = costed_node.second;
node_neighbors->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.
// TODO(user): Consider keeping vehicle start/ends out of neighbors, to
// prune arcs going from node to start for instance.
for (int vehicle = 0; vehicle < routing_model.vehicles(); vehicle++) {
const int vehicle_start = routing_model.Start(vehicle);
if (add_vehicle_starts_to_neighbors) node_neighbors->Set(vehicle_start);
node_index_to_neighbors_by_cost_class_[vehicle_start][cost_class]->Set(
node_index);
node_index_to_neighbors_by_cost_class_[routing_model.End(vehicle)]
[cost_class]
->Set(node_index);
}
}
}
}
const RoutingModel::NodeNeighborsByCostClass*
RoutingModel::GetOrCreateNodeNeighborsByCostClass(
double neighbors_ratio, int64_t min_neighbors, double& neighbors_ratio_used,
bool add_vehicle_starts_to_neighbors) {
const int64_t num_non_start_end_nodes = Size() - vehicles();
neighbors_ratio_used = neighbors_ratio;
int num_neighbors = std::max(
min_neighbors,
MathUtil::FastInt64Round(neighbors_ratio * num_non_start_end_nodes));
if (neighbors_ratio == 1 || num_neighbors >= num_non_start_end_nodes - 1) {
neighbors_ratio_used = 1;
num_neighbors = Size();
}
return GetOrCreateNodeNeighborsByCostClass(num_neighbors,
add_vehicle_starts_to_neighbors);
}
const RoutingModel::NodeNeighborsByCostClass*
RoutingModel::GetOrCreateNodeNeighborsByCostClass(
int num_neighbors, bool add_vehicle_starts_to_neighbors) {
const NodeNeighborsParameters params = {num_neighbors,
add_vehicle_starts_to_neighbors};
std::unique_ptr<NodeNeighborsByCostClass>* node_neighbors_by_cost_class_ptr =
gtl::FindOrNull(node_neighbors_by_cost_class_per_size_, params);
if (node_neighbors_by_cost_class_ptr != nullptr) {
return node_neighbors_by_cost_class_ptr->get();
}
std::unique_ptr<NodeNeighborsByCostClass>& node_neighbors_by_cost_class =
node_neighbors_by_cost_class_per_size_
.insert(std::make_pair(params,
std::make_unique<NodeNeighborsByCostClass>()))
.first->second;
node_neighbors_by_cost_class->ComputeNeighbors(
*this, num_neighbors, add_vehicle_starts_to_neighbors);
return node_neighbors_by_cost_class.get();
}
namespace {
// Evaluators
template <class A, class B>
static int64_t ReturnZero(A, B) {
return 0;
}
} // namespace
// ----- Routing model -----
static const int kUnassigned = -1;
const int64_t 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()) {}
namespace {
std::unique_ptr<Solver> CreateSolverFromParameters(
const RoutingModelParameters& parameters) {
VLOG(1) << "Model parameters:\n" << parameters;
ConstraintSolverParameters solver_parameters =
parameters.has_solver_parameters() ? parameters.solver_parameters()
: Solver::DefaultSolverParameters();
return std::make_unique<Solver>("Routing", solver_parameters);
}
} // namespace
RoutingModel::RoutingModel(const RoutingIndexManager& index_manager,
const RoutingModelParameters& parameters)
: solver_(CreateSolverFromParameters(parameters)),
nodes_(index_manager.num_nodes()),
vehicles_(index_manager.num_vehicles()),
max_active_vehicles_(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),
vehicle_used_when_empty_(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),
paths_metadata_(index_manager),
manager_(index_manager),
finalizer_variables_(std::make_unique<FinalizerVariables>(solver_.get())),
interrupt_cp_sat_(false),
interrupt_cp_(false) {
// Initialize vehicle costs to the zero evaluator.
vehicle_to_transit_cost_.assign(
vehicles_, RegisterTransitCallback(
ReturnZero<int64_t, int64_t>,
RoutingModel::kTransitEvaluatorSignPositiveOrZero));
// Active caching after initializing vehicle_to_transit_cost_ to avoid
// uselessly caching ReturnZero.
cache_callbacks_ = (nodes_ <= parameters.max_callback_cache_size());
// TODO(user): Remove when removal of NodeIndex is complete.
start_end_count_ = index_manager.num_unique_depots();
Initialize();
const int64_t size = Size();
index_to_pickup_positions_.resize(size);
index_to_delivery_positions_.resize(size);
index_to_visit_type_.resize(index_manager.num_indices(), kUnassigned);
index_to_type_policy_.resize(index_manager.num_indices());
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_);
// Active vehicle variables
solver_->MakeBoolVarArray(vehicles_, "ActiveVehicle", &vehicle_active_);
// Variables representing vehicles contributing to cost.
solver_->MakeBoolVarArray(vehicles_, "VehicleCostsConsidered",
&vehicle_route_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::RegisterUnaryTransitVector(std::vector<int64_t> values) {
TransitEvaluatorSign sign = kTransitEvaluatorSignUnknown;
if (std::all_of(std::cbegin(values), std::cend(values),
[](int64_t transit) { return transit >= 0; })) {
sign = kTransitEvaluatorSignPositiveOrZero;
} else if (std::all_of(std::cbegin(values), std::cend(values),
[](int64_t transit) { return transit <= 0; })) {
sign = kTransitEvaluatorSignNegativeOrZero;
}
return RegisterUnaryTransitCallback(
[this, values = std::move(values)](int64_t i) {
return values[manager_.IndexToNode(i).value()];
},
sign);
}
int RoutingModel::RegisterUnaryTransitCallback(TransitCallback1 callback,
TransitEvaluatorSign sign) {
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);
},
sign);
}
int RoutingModel::RegisterTransitMatrix(
std::vector<std::vector<int64_t> /*needed_for_swig*/> values) {
// TODO(user): when we move away from std::functions, use a (potentially
// vectorized) helper to compute the sign of a range.
bool all_transits_geq_zero = true;
bool all_transits_leq_zero = true;
for (const std::vector<int64_t>& transit_values : values) {
for (const int64_t value : transit_values) {
all_transits_leq_zero &= value <= 0;
all_transits_geq_zero &= value >= 0;
}
if (!all_transits_geq_zero && !all_transits_leq_zero) break;
}
const TransitEvaluatorSign sign =
all_transits_geq_zero
? kTransitEvaluatorSignPositiveOrZero
: (all_transits_leq_zero ? kTransitEvaluatorSignNegativeOrZero
: kTransitEvaluatorSignUnknown);
return RegisterTransitCallback(
[this, values = std::move(values)](int64_t i, int64_t j) {
return values[manager_.IndexToNode(i).value()]
[manager_.IndexToNode(j).value()];
},
sign);
}
int RoutingModel::RegisterTransitCallback(TransitCallback2 callback,
TransitEvaluatorSign sign) {
if (cache_callbacks_) {
TransitEvaluatorSign actual_sign = sign;
const int size = Size() + vehicles();
std::vector<int64_t> cache(size * size, 0);
bool all_transits_geq_zero = true;
bool all_transits_leq_zero = true;
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
const int64_t value = callback(i, j);
cache[i * size + j] = value;
all_transits_geq_zero &= value >= 0;
all_transits_leq_zero &= value <= 0;
}
}
actual_sign =
all_transits_geq_zero
? kTransitEvaluatorSignPositiveOrZero
: (all_transits_leq_zero ? kTransitEvaluatorSignNegativeOrZero
: kTransitEvaluatorSignUnknown);
transit_evaluators_.push_back(
[cache = std::move(cache), size](int64_t i, int64_t j) {
return cache[i * size + j];
});
DCHECK(sign == kTransitEvaluatorSignUnknown || actual_sign == sign);
} 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);
}
transit_evaluator_sign_.push_back(sign);
return transit_evaluators_.size() - 1;
}
int RoutingModel::RegisterStateDependentTransitCallback(
VariableIndexEvaluator2 callback) {
state_dependent_transit_evaluators_cache_.push_back(
std::make_unique<StateDependentTransitCallbackCache>());
StateDependentTransitCallbackCache* const cache =
state_dependent_transit_evaluators_cache_.back().get();
state_dependent_transit_evaluators_.push_back(
[cache, callback](int64_t i, int64_t 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_t slack_max,
int64_t capacity, bool fix_start_cumul_to_zero,
const std::string& name) {
const std::vector<int> evaluator_indices(vehicles_, evaluator_index);
std::vector<int64_t> 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_t slack_max,
int64_t capacity, bool fix_start_cumul_to_zero, const std::string& name) {
std::vector<int64_t> 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_t slack_max,
std::vector<int64_t> 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_t slack_max,
std::vector<int64_t> 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_t slack_max,
std::vector<int64_t> 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_t 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;
}
std::pair<int, bool> RoutingModel::AddConstantDimensionWithSlack(
int64_t value, int64_t capacity, int64_t slack_max,
bool fix_start_cumul_to_zero, const std::string& dimension_name) {
const TransitEvaluatorSign sign = value < 0
? kTransitEvaluatorSignNegativeOrZero
: kTransitEvaluatorSignPositiveOrZero;
const int evaluator_index =
RegisterUnaryTransitCallback([value](int64_t) { return value; }, sign);
return std::make_pair(evaluator_index,
AddDimension(evaluator_index, slack_max, capacity,
fix_start_cumul_to_zero, dimension_name));
}
std::pair<int, bool> RoutingModel::AddVectorDimension(
std::vector<int64_t> values, int64_t capacity, bool fix_start_cumul_to_zero,
const std::string& dimension_name) {
const int evaluator_index = RegisterUnaryTransitVector(std::move(values));
return std::make_pair(evaluator_index,
AddDimension(evaluator_index, 0, capacity,
fix_start_cumul_to_zero, dimension_name));
}
std::pair<int, bool> RoutingModel::AddMatrixDimension(
std::vector<std::vector<int64_t>> values, int64_t capacity,
bool fix_start_cumul_to_zero, const std::string& dimension_name) {
const int evaluator_index = RegisterTransitMatrix(std::move(values));
return std::make_pair(evaluator_index,
AddDimension(evaluator_index, 0, capacity,
fix_start_cumul_to_zero, dimension_name));
}
namespace {
// RangeMakeElementExpr is an IntExpr that corresponds to a
// RangeIntToIntFunction indexed by an IntVar.
// Do not create this class dicretly, but rather use MakeRangeMakeElementExpr.
class RangeMakeElementExpr : public BaseIntExpr {
public:
RangeMakeElementExpr(const RangeIntToIntFunction* callback, IntVar* index,
Solver* s)
: BaseIntExpr(s), callback_(ABSL_DIE_IF_NULL(callback)), index_(index) {
CHECK(callback_ != nullptr);
CHECK(index != nullptr);
}
int64_t Min() const override {
// Converting [index_->Min(), index_->Max()] to [idx_min, idx_max).
const int idx_min = index_->Min();
const int idx_max = index_->Max() + 1;
return (idx_min < idx_max) ? callback_->RangeMin(idx_min, idx_max)
: std::numeric_limits<int64_t>::max();
}
void SetMin(int64_t new_min) override {
const int64_t old_min = Min();
const int64_t old_max = Max();
if (old_min < new_min && new_min <= old_max) {
const int64_t old_idx_min = index_->Min();
const int64_t old_idx_max = index_->Max() + 1;
if (old_idx_min < old_idx_max) {
const int64_t new_idx_min = callback_->RangeFirstInsideInterval(
old_idx_min, old_idx_max, new_min, old_max + 1);
index_->SetMin(new_idx_min);
if (new_idx_min < old_idx_max) {
const int64_t new_idx_max = callback_->RangeLastInsideInterval(
new_idx_min, old_idx_max, new_min, old_max + 1);
index_->SetMax(new_idx_max);
}
}
}
}
int64_t Max() const override {
// Converting [index_->Min(), index_->Max()] to [idx_min, idx_max).
const int idx_min = index_->Min();
const int idx_max = index_->Max() + 1;
return (idx_min < idx_max) ? callback_->RangeMax(idx_min, idx_max)
: std::numeric_limits<int64_t>::min();
}
void SetMax(int64_t new_max) override {
const int64_t old_min = Min();
const int64_t old_max = Max();
if (old_min <= new_max && new_max < old_max) {
const int64_t old_idx_min = index_->Min();
const int64_t old_idx_max = index_->Max() + 1;
if (old_idx_min < old_idx_max) {
const int64_t new_idx_min = callback_->RangeFirstInsideInterval(
old_idx_min, old_idx_max, old_min, new_max + 1);
index_->SetMin(new_idx_min);
if (new_idx_min < old_idx_max) {
const int64_t new_idx_max = callback_->RangeLastInsideInterval(
new_idx_min, old_idx_max, old_min, new_max + 1);
index_->SetMax(new_idx_max);
}
}
}
}
void WhenRange(Demon* d) override { index_->WhenRange(d); }
private:
const RangeIntToIntFunction* const callback_;
IntVar* const index_;
};
IntExpr* MakeRangeMakeElementExpr(const RangeIntToIntFunction* callback,
IntVar* index, Solver* s) {
return s->RegisterIntExpr(
s->RevAlloc(new RangeMakeElementExpr(callback, index, s)));
}
} // namespace
bool RoutingModel::AddDimensionDependentDimensionWithVehicleCapacity(
const std::vector<int>& dependent_transits,
const RoutingDimension* base_dimension, int64_t slack_max,
std::vector<int64_t> vehicle_capacities, bool fix_start_cumul_to_zero,
const std::string& name) {
const std::vector<int> pure_transits(vehicles_, /*zero_evaluator*/ 0);
return AddDimensionDependentDimensionWithVehicleCapacity(
pure_transits, dependent_transits, base_dimension, slack_max,
std::move(vehicle_capacities), fix_start_cumul_to_zero, name);
}
bool RoutingModel::AddDimensionDependentDimensionWithVehicleCapacity(
int transit, const RoutingDimension* dimension, int64_t slack_max,
int64_t vehicle_capacity, bool fix_start_cumul_to_zero,
const std::string& name) {
return AddDimensionDependentDimensionWithVehicleCapacity(
/*zero_evaluator*/ 0, transit, dimension, slack_max, vehicle_capacity,
fix_start_cumul_to_zero, name);
}
bool RoutingModel::AddDimensionDependentDimensionWithVehicleCapacityInternal(
const std::vector<int>& pure_transits,
const std::vector<int>& dependent_transits,
const RoutingDimension* base_dimension, int64_t slack_max,
std::vector<int64_t> vehicle_capacities, bool fix_start_cumul_to_zero,
const std::string& name) {
CHECK_EQ(vehicles_, vehicle_capacities.size());
RoutingDimension* new_dimension = nullptr;
if (base_dimension == nullptr) {
new_dimension = new RoutingDimension(this, std::move(vehicle_capacities),
name, RoutingDimension::SelfBased());
} else {
new_dimension = new RoutingDimension(this, std::move(vehicle_capacities),
name, base_dimension);
}
return InitializeDimensionInternal(pure_transits, dependent_transits,
slack_max, fix_start_cumul_to_zero,
new_dimension);
}
bool RoutingModel::AddDimensionDependentDimensionWithVehicleCapacity(
int pure_transit, int dependent_transit,
const RoutingDimension* base_dimension, int64_t slack_max,
int64_t vehicle_capacity, bool fix_start_cumul_to_zero,
const std::string& name) {
std::vector<int> pure_transits(vehicles_, pure_transit);
std::vector<int> dependent_transits(vehicles_, dependent_transit);
std::vector<int64_t> vehicle_capacities(vehicles_, vehicle_capacity);
return AddDimensionDependentDimensionWithVehicleCapacityInternal(
pure_transits, dependent_transits, base_dimension, slack_max,
std::move(vehicle_capacities), fix_start_cumul_to_zero, name);
}
RoutingModel::StateDependentTransit RoutingModel::MakeStateDependentTransit(
const std::function<int64_t(int64_t)>& f, int64_t domain_start,
int64_t domain_end) {
const std::function<int64_t(int64_t)> g = [&f](int64_t x) {
return f(x) + x;
};
// The next line is safe, because MakeCachedIntToIntFunction does not count
// on keeping the closure of its first argument alive.
return {MakeCachedIntToIntFunction(f, domain_start, domain_end),
MakeCachedRangeMinMaxIndexFunction(g, domain_start, domain_end)};
}
std::vector<std::string> RoutingModel::GetAllDimensionNames() const {
std::vector<std::string> dimension_names;
for (const auto& dimension_name_index : dimension_name_to_index_) {
dimension_names.push_back(dimension_name_index.first);
}
std::sort(dimension_names.begin(), dimension_names.end());
return dimension_names;
}
GlobalDimensionCumulOptimizer* RoutingModel::GetMutableGlobalCumulLPOptimizer(
const RoutingDimension& dimension) const {
const int optimizer_index = GetGlobalCumulOptimizerIndex(dimension);
return optimizer_index < 0
? nullptr
: global_dimension_optimizers_[optimizer_index].lp_optimizer.get();
}
GlobalDimensionCumulOptimizer* RoutingModel::GetMutableGlobalCumulMPOptimizer(
const RoutingDimension& dimension) const {
const int optimizer_index = GetGlobalCumulOptimizerIndex(dimension);
return optimizer_index < 0
? nullptr
: global_dimension_optimizers_[optimizer_index].mp_optimizer.get();
}
int RoutingModel::GetGlobalCumulOptimizerIndex(
const RoutingDimension& dimension) const {
DCHECK(closed_);
const DimensionIndex dim_index = GetDimensionIndex(dimension.name());
if (dim_index < 0 || dim_index >= global_optimizer_index_.size() ||
global_optimizer_index_[dim_index] < 0) {
return -1;
}
const int optimizer_index = global_optimizer_index_[dim_index];
DCHECK_LT(optimizer_index, global_dimension_optimizers_.size());
return optimizer_index;
}
LocalDimensionCumulOptimizer* RoutingModel::GetMutableLocalCumulLPOptimizer(
const RoutingDimension& dimension) const {
const int optimizer_index = GetLocalCumulOptimizerIndex(dimension);
return optimizer_index < 0
? nullptr
: local_dimension_optimizers_[optimizer_index].lp_optimizer.get();
}
LocalDimensionCumulOptimizer* RoutingModel::GetMutableLocalCumulMPOptimizer(
const RoutingDimension& dimension) const {
const int optimizer_index = GetLocalCumulOptimizerIndex(dimension);
return optimizer_index < 0
? nullptr
: local_dimension_optimizers_[optimizer_index].mp_optimizer.get();
}
int RoutingModel::GetLocalCumulOptimizerIndex(
const RoutingDimension& dimension) const {
DCHECK(closed_);
const DimensionIndex dim_index = GetDimensionIndex(dimension.name());
if (dim_index < 0 || dim_index >= local_optimizer_index_.size() ||
local_optimizer_index_[dim_index] < 0) {
return -1;
}
const int optimizer_index = local_optimizer_index_[dim_index];
DCHECK_LT(optimizer_index, local_dimension_optimizers_.size());
return optimizer_index;
}
bool RoutingModel::HasDimension(absl::string_view dimension_name) const {
return dimension_name_to_index_.contains(dimension_name);
}
RoutingModel::DimensionIndex RoutingModel::GetDimensionIndex(
const std::string& dimension_name) const {
return gtl::FindWithDefault(dimension_name_to_index_, dimension_name,
kNoDimension);
}
const RoutingDimension& RoutingModel::GetDimensionOrDie(
const std::string& dimension_name) const {
return *dimensions_[gtl::FindOrDie(dimension_name_to_index_, dimension_name)];
}
RoutingDimension* RoutingModel::GetMutableDimension(
const std::string& dimension_name) const {
const DimensionIndex index = GetDimensionIndex(dimension_name);
if (index != kNoDimension) {
return dimensions_[index];
}
return nullptr;
}
// ResourceGroup
namespace {
using ResourceGroup = RoutingModel::ResourceGroup;
} // namespace
ResourceGroup::Attributes::Attributes()
: start_domain_(Domain::AllValues()), end_domain_(Domain::AllValues()) {
/// The default attributes have unconstrained start/end domains.
}
ResourceGroup::Attributes::Attributes(Domain start_domain, Domain end_domain)
: start_domain_(std::move(start_domain)),
end_domain_(std::move(end_domain)) {}
const ResourceGroup::Attributes&
ResourceGroup::Resource::GetDimensionAttributes(
const RoutingDimension* dimension) const {
DimensionIndex dimension_index = model_->GetDimensionIndex(dimension->name());
DCHECK_NE(dimension_index, kNoDimension);
return gtl::FindWithDefault(dimension_attributes_, dimension_index,
GetDefaultAttributes());
}
void ResourceGroup::Resource::SetDimensionAttributes(
Attributes attributes, const RoutingDimension* dimension) {
DCHECK(dimension_attributes_.empty())
<< "As of 2021/07, each resource can only constrain a single dimension.";
const DimensionIndex dimension_index =
model_->GetDimensionIndex(dimension->name());
DCHECK_NE(dimension_index, kNoDimension);
DCHECK(!dimension_attributes_.contains(dimension_index));
dimension_attributes_[dimension_index] = std::move(attributes);
}
const ResourceGroup::Attributes& ResourceGroup::Resource::GetDefaultAttributes()
const {
static const Attributes* const kAttributes = new Attributes();
return *kAttributes;
}
ResourceGroup* RoutingModel::AddResourceGroup() {
DCHECK_EQ(resource_groups_.size(), resource_vars_.size());
// Create and add the resource group.
// Using 'new' to access private constructor.
resource_groups_.push_back(absl::WrapUnique(new ResourceGroup(this)));
const int rg_index = resource_groups_.back()->Index();
DCHECK_EQ(rg_index, resource_groups_.size() - 1);
// Create and add the resource vars (the proper variable bounds and
// constraints are set up when closing the model).
resource_vars_.push_back({});
solver_->MakeIntVarArray(vehicles(), -1, std::numeric_limits<int64_t>::max(),
absl::StrCat("Resources[", rg_index, "]"),
&resource_vars_.back());
return resource_groups_[rg_index].get();